From 8440821793c7e92059ddd4cb89df2a4c2f73e09c Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:40:07 -0400 Subject: [PATCH] fix(iam): read iam:AccountPropertyNamespaces from the keys PutAccountProperties sets (#9736) The generated IAM condition key table had iam:AccountPropertyNamespaces in notRead on both actions the Service Reference lists it on, so a policy keyed on it matched nothing: the IAM user guide's DenyRoleManagerEnablement statement, ForAnyValue:StringEquals on RoleManager, let a caller enable role manager, and an Allow requiring the namespace refused every call. Neither botocore nor the Service Reference says where the value is; AWS's pages do. The IAM user guide's condition key table: iam:AccountPropertyNamespaces "Specifies the account property namespaces being read or modified in the request ... When you call PutAccountProperties or GetAccountProperties". The API reference on PutAccountProperties' Properties: "Each key uses the format Namespace/PropertyName. The key must contain exactly one / separating the namespace from the property name". tools/aws/fetch_iam_account_property_namespaces.py copies both sentences into tools/aws/sources/iam-account-property-namespaces.json with what they name: the key, the operation, the parameter, the format, its separator and the part that is the namespace. regen_iam_condition_keys.py takes that entry as it stands, refusing it unless the Service Reference lists the pair and botocore models the parameter as a map of strings, and writes it to a new fromMapKeys section, which the IAM context resolver reads from the request's map as the operation's handler does. GetAccountProperties names no properties, so it stays in notRead. --- .github/workflows/iam-data-drift.yml | 3 + Makefile | 2 + docs/services/iam.md | 17 ++ .../common/IamConditionContextResolver.java | 40 ++++- .../aws/core/common/IamConditionKeys.java | 35 ++++ .../resources/aws/iam-condition-keys.json | 4 +- ...esConditionEnforcementIntegrationTest.java | 93 +++++++++++ .../fetch_iam_account_property_namespaces.py | 153 ++++++++++++++++++ tools/aws/regen_iam_condition_keys.py | 79 ++++++++- .../iam-account-property-namespaces.json | 30 ++++ ...t_fetch_iam_account_property_namespaces.py | 76 +++++++++ tools/aws/test_regen_iam_condition_keys.py | 56 ++++++- 12 files changed, 576 insertions(+), 12 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/iam/IamAccountPropertyNamespacesConditionEnforcementIntegrationTest.java create mode 100644 tools/aws/fetch_iam_account_property_namespaces.py create mode 100644 tools/aws/sources/iam-account-property-namespaces.json create mode 100644 tools/aws/test_fetch_iam_account_property_namespaces.py diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index 0e83942904..a723d39da2 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -88,6 +88,9 @@ on: - '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/fetch_iam_account_property_namespaces.py' + - 'tools/aws/sources/iam-account-property-namespaces.json' + - 'tools/aws/test_fetch_iam_account_property_namespaces.py' - 'src/main/resources/aws/s3control-tag-condition-keys.json' - 'tools/aws/regen_s3control_tag_condition_keys.py' - 'tools/aws/test_regen_s3control_tag_condition_keys.py' diff --git a/Makefile b/Makefile index 849d3f4c28..3b52546d88 100644 --- a/Makefile +++ b/Makefile @@ -641,6 +641,8 @@ DYNAMODB_CONDITION_KEYS_PATHS := src/main/resources/aws/dynamodb-condition-keys. 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/fetch_iam_account_property_namespaces.py tools/aws/sources/iam-account-property-namespaces.json \ + tools/aws/test_fetch_iam_account_property_namespaces.py \ tools/aws/regen_partitions.py tools/aws/regen_query_services.py S3CONTROL_TAG_CONDITION_KEYS_PATHS := src/main/resources/aws/s3control-tag-condition-keys.json \ tools/aws/regen_s3control_tag_condition_keys.py tools/aws/test_regen_s3control_tag_condition_keys.py \ diff --git a/docs/services/iam.md b/docs/services/iam.md index 094766e969..5a6a07ab15 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3921,6 +3921,23 @@ floci populates: 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. + The `fromMapKeys` entries read a key from a part of each key a request's map carries, where + AWS's pages say so. `tools/aws/fetch_iam_account_property_namespaces.py` copies two sentences + into `tools/aws/sources/iam-account-property-namespaces.json`: the + [user guide's](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html) + `iam:AccountPropertyNamespaces` "Specifies the account property namespaces being read or + modified in the request", for `PutAccountProperties` and `GetAccountProperties`, and the + [API reference's](https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutAccountProperties.html) + `Properties`: "Each key uses the format Namespace/PropertyName. The key must contain exactly + one / separating the namespace from the property name". The file names the key, the + operation, the parameter and the part, and the generator takes them as they stand, checking + that the Service Reference lists the pair and botocore models the parameter as a map of + strings. So the + [role manager guide's](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_role-manager_enable-use.html) + `DenyRoleManagerEnablement` statement, `ForAnyValue:StringEquals` on `RoleManager`, refuses a + call setting `RoleManager/Enabled`. `GetAccountProperties` names no properties, so it carries + no value for the key and stays in `notRead`. + 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`. diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index e786b5bbc1..40b27614e6 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -371,7 +371,8 @@ public class IamConditionContextResolver { Map members = IamConditionKeys.members(action); Map targets = IamConditionKeys.targets(action); Map requestTags = IamConditionKeys.requestTags(action); - if (members.isEmpty() && targets.isEmpty() && requestTags.isEmpty()) { + Map mapKeyParts = IamConditionKeys.mapKeyParts(action); + if (members.isEmpty() && targets.isEmpty() && requestTags.isEmpty() && mapKeyParts.isEmpty()) { return null; } Map form = formParameters(ctx); @@ -406,13 +407,46 @@ public class IamConditionContextResolver { if (!requestTags.isEmpty()) { addIamRequestTags(conditions, form, requestTags); } + if (!mapKeyParts.isEmpty()) { + addIamMapKeyParts(conditions, form, mapKeyParts); + } return conditions.isEmpty() ? null : conditions; } + /** + * The keys a request takes from a part of each key of a map it carries, as the table gives them from the format the + * API reference gives the map's keys: {@code iam:AccountPropertyNamespaces} is the {@code Namespace} of each + * {@code PutAccountProperties} {@code Properties} key, "each key uses the format Namespace/PropertyName". A key not + * in the format names nothing, and a part two keys share is named once. + */ + private static void addIamMapKeyParts(Map> conditions, Map form, + Map mapKeyParts) { + MultivaluedMap parameters = queryParameters(form); + mapKeyParts.forEach((key, part) -> { + List values = new ArrayList<>(); + for (AwsQueryLists.IndexedMember entry : AwsQueryLists.members(parameters, part.member(), "entry")) { + String mapKey = form.get(entry.prefix() + "." + part.keyMember()); + String value = mapKey == null ? null : part.of(mapKey); + if (value != null && !values.contains(value)) { + values.add(value); + } + } + if (!values.isEmpty()) { + conditions.put(key, values); + } + }); + } + + /** A Query request's flat form as the parameters the Query list readers take. */ + private static MultivaluedMap queryParameters(Map form) { + MultivaluedMap parameters = new MultivaluedHashMap<>(); + form.forEach(parameters::putSingle); + return parameters; + } + private static void addIamRequestTags(Map> conditions, Map form, Map requestTags) { - MultivaluedMap parameters = new MultivaluedHashMap<>(); - form.forEach(parameters::putSingle); + MultivaluedMap parameters = queryParameters(form); requestTags.forEach((key, fields) -> { List keys = new ArrayList<>(); for (AwsQueryLists.IndexedMember member : AwsQueryLists.members(parameters, fields.member(), null)) { diff --git a/src/main/java/io/floci/aws/core/common/IamConditionKeys.java b/src/main/java/io/floci/aws/core/common/IamConditionKeys.java index af6738e56c..30d4774874 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionKeys.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionKeys.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashSet; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; @@ -25,8 +26,23 @@ final class IamConditionKeys { */ record Resource(String type, String member, Pattern arn) {} + /** + * A key read from a part of each key a request's map carries: the map member, the name its keys have on the wire, + * the separator between the parts of the format the API reference gives them, how many parts it has and which one + * the value is ({@code Namespace} of {@code Namespace/PropertyName}). + */ + record MapKeyPart(String member, String keyMember, String separator, int parts, int part) { + + /** The part of {@code key} this reads, or null when the key is not in the format. */ + String of(String key) { + String[] found = key.split(Pattern.quote(separator), -1); + return found.length == parts ? found[part] : null; + } + } + private record Table(Map> members, Map> targets, Map> resources, + Map> mapKeyParts, Map> requestTags, Map> unreadTagPrefixes) {} @@ -40,6 +56,7 @@ final class IamConditionKeys { section(document.path("fromResource"), entry -> new Resource(text(entry, "type"), text(entry, "member"), RequestResourceMembers.pattern(text(entry, "arn")))), + section(document.path("fromMapKeys"), IamConditionKeys::mapKeyPart), section(document.path("requestTags"), entry -> new RequestTags(text(entry, "member"), entry.has("keyMember") ? text(entry, "keyMember") : null, entry.has("keyMember") ? text(entry, "valueMember") : null)), @@ -61,6 +78,16 @@ final class IamConditionKeys { return Map.copyOf(byAction); } + private static MapKeyPart mapKeyPart(JsonNode entry) { + String separator = text(entry, "separator"); + List parts = List.of(text(entry, "format").split(Pattern.quote(separator), -1)); + int part = parts.indexOf(text(entry, "part")); + if (part < 0) { + throw new IllegalStateException("Malformed IAM condition key entry: " + entry); + } + return new MapKeyPart(text(entry, "member"), text(entry, "keyMember"), separator, parts.size(), part); + } + /** * For each action, the prefixes of the tag keys the table does not read for it ({@code aws:ResourceTag/} for a * {@code notRead} entry on {@code aws:ResourceTag/${TagKey}}). @@ -108,6 +135,14 @@ final class IamConditionKeys { return TABLE.resources().getOrDefault(action, Map.of()); } + /** + * Each condition key a request for {@code action} takes from a part of each key of a map it carries, to the map and + * the part; empty when none. + */ + static Map mapKeyParts(String action) { + return TABLE.mapKeyParts().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 b70dd66556..8cc0fd0eff 100644 --- a/src/main/resources/aws/iam-condition-keys.json +++ b/src/main/resources/aws/iam-condition-keys.json @@ -172,6 +172,9 @@ {"action": "iam:RejectDelegationRequest", "key": "iam:DelegationRequestOwner", "type": "delegation-request", "member": "OwnerId", "arn": "arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}"}, {"action": "iam:SendDelegationToken", "key": "iam:DelegationRequestOwner", "type": "delegation-request", "member": "OwnerId", "arn": "arn:${Partition}:iam::${Account}:delegation-request/${DelegationRequestId}"} ], + "fromMapKeys": [ + {"action": "iam:PutAccountProperties", "key": "iam:AccountPropertyNamespaces", "member": "Properties", "keyMember": "key", "format": "Namespace/PropertyName", "separator": "/", "part": "Namespace"} + ], "notRead": [ {"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"]}, @@ -245,7 +248,6 @@ {"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:RemoveClientIDFromOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, diff --git a/src/test/java/io/floci/aws/services/iam/IamAccountPropertyNamespacesConditionEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamAccountPropertyNamespacesConditionEnforcementIntegrationTest.java new file mode 100644 index 0000000000..dc73f8f1d8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamAccountPropertyNamespacesConditionEnforcementIntegrationTest.java @@ -0,0 +1,93 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.EnforcementFixtures.UserCredentials; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import 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.floci.aws.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; + +/** + * {@code iam:AccountPropertyNamespaces} on {@code iam:PutAccountProperties} is the namespace of each property the + * request sets, the part before the {@code /} of each {@code Properties} key, as the API reference gives the keys: + * "Each key uses the format Namespace/PropertyName". The IAM user guide's policy keeping member accounts from enabling + * role manager denies the call with {@code ForAnyValue:StringEquals} on {@code RoleManager}, and an Allow requiring + * the namespace lets the call through. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class IamAccountPropertyNamespacesConditionEnforcementIntegrationTest { + + private static final String ADMIN = "test"; + private static final String ALLOW_PUT = """ + {"Effect":"Allow","Action":"iam:PutAccountProperties","Resource":"*"}"""; + // The IAM user guide's "DenyRoleManagerEnablement" statement, as it stands. + private static final String DENY_ROLE_MANAGER = """ + {"Sid":"DenyRoleManagerEnablement","Effect":"Deny","Action":"iam:PutAccountProperties","Resource":"*", + "Condition":{"ForAnyValue:StringEquals":{"iam:AccountPropertyNamespaces":"RoleManager"}}}"""; + private static final String ALLOW_ONLY_ROLE_MANAGER = """ + {"Effect":"Allow","Action":"iam:PutAccountProperties","Resource":"*", + "Condition":{"ForAllValues:StringEquals":{"iam:AccountPropertyNamespaces":"RoleManager"}, + "Null":{"iam:AccountPropertyNamespaces":"false"}}}"""; + + @TestHTTPResource("/") + static URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void theGuidesDenyKeepsACallerFromSettingRoleManagerProperties() { + UserCredentials user = user(ALLOW_PUT + "," + DENY_ROLE_MANAGER); + + put(user, "RoleManager/Enabled" + suffix()).statusCode(403) + .body(containsString("AccessDenied")) + .body(containsString("iam:PutAccountProperties")); + } + + @Test + void anAllowRequiringTheNamespaceLetsTheCallThrough() { + UserCredentials user = user(ALLOW_ONLY_ROLE_MANAGER); + + put(user, "RoleManager/Enabled" + suffix()).statusCode(200); + } + + private UserCredentials user(String statements) { + String userName = "account-properties-" + 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, "account-properties", + "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}"); + return user; + } + + /** A property name unique to the call, the half of the key nothing checks. */ + private static String suffix() { + return Long.toString(System.nanoTime(), 36).replace("-", ""); + } + + private static ValidatableResponse put(UserCredentials user, String key) { + return iam(user.accessKeyId(), "PutAccountProperties") + .formParam("Properties.entry.1.key", key) + .formParam("Properties.entry.1.value", "true") + .post("/").then(); + } + + 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/fetch_iam_account_property_namespaces.py b/tools/aws/fetch_iam_account_property_namespaces.py new file mode 100644 index 0000000000..b81f610d53 --- /dev/null +++ b/tools/aws/fetch_iam_account_property_namespaces.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Vendor what the IAM user guide and the IAM API reference say about iam:AccountPropertyNamespaces into +tools/aws/sources/iam-account-property-namespaces.json, a source of the IAM condition key table. + +AWS's Service Reference gives PutAccountProperties and GetAccountProperties the key `iam:AccountPropertyNamespaces`, +typed `ArrayOfString`, without saying where its values are, and botocore models PutAccountProperties' `Properties` as +a map of strings without naming the key. The IAM user guide's table of IAM condition keys says what the key is: + + iam:AccountPropertyNamespaces. Specifies the account property namespaces being read or modified in the request. + ... When you call PutAccountProperties or GetAccountProperties, use this condition key to restrict which property + namespaces a principal can access. + + https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html + +and the API reference's page on PutAccountProperties says where in the request each namespace is: + + Each key uses the format Namespace/PropertyName. The key must contain exactly one / separating the namespace from + the property name, and cannot start or end with /. + + https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutAccountProperties.html + +This script copies those sentences as they stand, with what each names: the key, the operations the guide names for +it, the request parameter whose keys carry the namespaces, the format of those keys, the separator between its parts +and the part that is the namespace. The operation page's operation must be one the guide names for the key. Nothing +in the output is written by hand; regen_iam_condition_keys.py reads it. + +Run from anywhere in the repo: + python3 tools/aws/fetch_iam_account_property_namespaces.py # rewrite the vendored file from the pages + python3 tools/aws/fetch_iam_account_property_namespaces.py --verify # online: the file still says what they do +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +KEYS_PAGE = "https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html" +OPERATION_PAGE = "https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutAccountProperties.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/iam-account-property-namespaces.json" + +KEY_RE = re.compile(r"\b(?Piam:[A-Za-z]+) Works with string operators\. Specifies the account property " + r"namespaces being read or modified in the request\. Account properties are organized into " + r"namespaces \(for example, [A-Za-z]+\)\. When you call (?P[A-Za-z]+) or " + r"(?P[A-Za-z]+), use this condition key to restrict which property namespaces a principal " + r"can access\.") +OPERATION_RE = re.compile(r'

(?P=operation)

') +REQUEST_PARAMETERS_RE = re.compile(r'

(?P
.*?)(?:\s*(?P[A-Za-z0-9]+)\s*' + r'(?:\s*
(?:(?!
).)*?)*\s*
(?P.*?)
', re.S) +FORMAT_RE = re.compile(r"\bEach key uses the format (?P(?P[A-Za-z]+)(?P\S)[A-Za-z]+)\. " + r"The key must contain exactly one (?P=separator) separating the namespace from the property " + r"name\b[^.]*\.") + + +def text(fragment: str) -> str: + """A fragment of a page as text, spaces collapsed, and none left before a mark an inline tag ends ahead of.""" + collapsed = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() + return re.sub(r" (?=[.,;)])", "", re.sub(r"\( ", "(", collapsed)) + + +def body(page: str) -> str: + """The page's own content, its navigation left out.""" + match = re.search(r'
(?P.*?)(?:
re.Match: + if match is None: + raise ValueError(f"{page} no longer says {what}: its layout or its wording changed") + return match + + +def build(fetch) -> dict: + named = _found(KEY_RE.search(text(body(fetch(KEYS_PAGE)))), KEYS_PAGE, + "what iam:AccountPropertyNamespaces is and which operations it is for") + content = body(fetch(OPERATION_PAGE)) + operation = _found(OPERATION_RE.search(content), OPERATION_PAGE, "which operation it is for").group("operation") + if operation not in (named.group("first"), named.group("second")): + raise ValueError(f"{KEYS_PAGE} gives {named.group('key')} to {named.group('first')} and " + f"{named.group('second')}, not to {operation}") + section = _found(REQUEST_PARAMETERS_RE.search(content), OPERATION_PAGE, "its request parameters") + keys = [] + for parameter in PARAMETER_RE.finditer(section.group("section")): + described = FORMAT_RE.search(text(parameter.group("description"))) + if described is not None: + keys.append({"operation": operation, "member": parameter.group("member"), "key": named.group("key"), + "format": described.group("format"), "separator": described.group("separator"), + "part": described.group("namespace"), "row": described.group(0)}) + if len(keys) != 1: + raise ValueError(f"{OPERATION_PAGE} gives {len(keys)} request parameters keys holding a namespace, not one: " + f"its layout or its wording changed") + return { + "_source": { + "pages": [KEYS_PAGE, OPERATION_PAGE], + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "The guide's sentence on iam:AccountPropertyNamespaces and the API reference's on the keys of " + "PutAccountProperties' properties, copied as they stand, with what each names: the key and its " + "operations, the parameter, its keys' format, the separator and the part that is the namespace.", + }, + "key": {"key": named.group("key"), "operations": sorted([named.group("first"), named.group("second")]), + "sentence": named.group(0)}, + "keys": keys, + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def stale(vendored: dict, fetch) -> bool: + """Whether the pages now give something other than the vendored file, its date aside.""" + built = build(fetch) + return {key: value for key, value in vendored.items() if key != "_source"} != { + key: value for key, value in built.items() if key != "_source"} + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages") + args = parser.parse_args(argv) + try: + pages = {url: fetch(url) for url in (KEYS_PAGE, OPERATION_PAGE)} + except OSError as e: + print(f"error: could not read the IAM user guide or API reference ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, pages.__getitem__): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the IAM user guide and API reference " + f"do: run tools/aws/fetch_iam_account_property_namespaces.py and then make iam-condition-keys-sync", + file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the IAM user guide and API reference") + return 0 + built = build(pages.__getitem__) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['keys'])} operations)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_iam_condition_keys.py b/tools/aws/regen_iam_condition_keys.py index 55a5996b4b..00ce70cdc0 100644 --- a/tools/aws/regen_iam_condition_keys.py +++ b/tools/aws/regen_iam_condition_keys.py @@ -22,6 +22,15 @@ value, and MEASURED names the member of that type's record it is read from, whic the reference says; its pairs go in fromResource with the type, that member and the type's ARN format, and the reader asks the type's service for what the record holds there. +A key the IAM user guide and the IAM API reference place in a part of each key of a request's map is read from that +part: tools/aws/fetch_iam_account_property_namespaces.py copies the guide's sentence on iam:AccountPropertyNamespaces +("Specifies the account property namespaces being read or modified in the request") and the API reference's on +PutAccountProperties' Properties ("Each key uses the format Namespace/PropertyName. The key must contain exactly one / +separating the namespace from the property name") into tools/aws/sources/iam-account-property-namespaces.json, which +names the key, the operation, the parameter, the format, its separator and the part that is the namespace. Its pairs +go in fromMapKeys with those and the name botocore gives the map's keys on the wire, as the file gives them: the +reference must list the pair, and botocore must model the member as a map of string keys. + 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 @@ -37,10 +46,14 @@ import urllib.error import urllib.request from pathlib import Path +import fetch_iam_account_property_namespaces 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" +# What the IAM user guide and API reference say iam:AccountPropertyNamespaces is read from, as +# tools/aws/fetch_iam_account_property_namespaces.py copies it. +ACCOUNT_PROPERTY_NAMESPACES = fetch_iam_account_property_namespaces.OUTPUT URL = "https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json" READ_TYPES = {"String", "ARN"} # Pairs whose value is a request member under another name: the member path, dotted for a nested one. @@ -240,6 +253,43 @@ def classify(pairs, types, model, resource_types=None, measured=None): require_measured_admitted(model, measured) return read, from_target, from_resource, not_read +def load_map_keys(): + return json.loads(ACCOUNT_PROPERTY_NAMESPACES.read_text(encoding="utf-8")) + + +def map_key_parts(pairs, types, model, vendored): + """The fromMapKeys entries: each pair the vendored pages place in a part of each key of a request's map + (`ACCOUNT_PROPERTY_NAMESPACES`), as they give it. The reference must list the pair, the key must be a string or a + list of strings, and botocore must model the member as a map of string keys.""" + listed = set(pairs) + entries = [] + for entry in vendored["keys"]: + action, key = "iam:" + entry["operation"], entry["key"] + if (action, key) not in listed: + raise ValueError(f"the vendored pages give {key} to {action}, which the reference does not list") + key_types = types.get(key) or [] + if not key_types or not {t.removeprefix("ArrayOf") for t in key_types} <= {"String"}: + raise ValueError(f"{action}: {key} is {key_types or 'untyped'}, which a part of a map key does not fit") + operation = model["operations"].get(entry["operation"]) + members = model["shapes"][operation["input"]["shape"]].get("members", {}) \ + if operation and "input" in operation else {} + if entry["member"] not in members: + raise ValueError(f"{action}: the API reference's {entry['member']} is not in botocore") + shape = model["shapes"][members[entry["member"]]["shape"]] + if shape["type"] != "map" or model["shapes"][shape["key"]["shape"]]["type"] != "string": + raise ValueError(f"{action}: {entry['member']} is not a map of string keys in botocore") + entries.append({"action": action, "key": key, "member": entry["member"], + "keyMember": shape["key"].get("locationName", "key"), "format": entry["format"], + "separator": entry["separator"], "part": entry["part"]}) + return sorted(entries, key=lambda entry: (entry["action"], entry["key"])) + + +def unclaimed(pairs, map_keys): + """The pairs no fromMapKeys entry reads, which classify sorts.""" + claimed = {(entry["action"], entry["key"]) for entry in map_keys} + return [pair for pair in pairs if pair not in claimed] + + def require_by_hand_listed(pairs): stale = sorted(set(BY_HAND) - set(pairs)) if stale: @@ -287,15 +337,15 @@ def validate_request_tags(entries, model): def pairs_of(document): return sorted((e["action"], e["key"]) for e in document["read"] + document["fromTarget"] + document["fromResource"] - + document["notRead"]) + + document["fromMapKeys"] + 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", ","), ("fromResource", ","), ("notRead", ","), - ("requestTags", "")): + for section, tail in (("read", ","), ("fromTarget", ","), ("fromResource", ","), ("fromMapKeys", ","), + ("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)] @@ -320,7 +370,10 @@ def main(argv=None): resource_types = {(e["action"], e["key"]): e["resources"] for e in document["fromTarget"] + document["notRead"] if e["key"] in RESOURCE_TAG_KEYS} measured = {(e["action"], e["key"]): (e["type"], e["arn"]) for e in document["fromResource"]} - if classify(pairs, document["types"], model, resource_types, measured) != ( + map_keys = map_key_parts(pairs, document["types"], model, load_map_keys()) + if map_keys != document["fromMapKeys"]: + raise ValueError("IAM map key condition keys differ from pinned botocore and the vendored pages") + if classify(unclaimed(pairs, map_keys), document["types"], model, resource_types, measured) != ( document["read"], document["fromTarget"], document["fromResource"], document["notRead"]): raise ValueError("IAM condition key members differ from pinned botocore") validate_request_tags(document["requestTags"], model) @@ -345,7 +398,18 @@ def main(argv=None): 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), measured_resources(reference)) != ( + vendored_keys = load_map_keys() + # The pages the vendored copy was taken from must still say what it does; a saved reference reads nothing + # online. + if args.source is None and fetch_iam_account_property_namespaces.stale( + vendored_keys, fetch_iam_account_property_namespaces.fetch_url): + raise ValueError(f"{ACCOUNT_PROPERTY_NAMESPACES} no longer says what the IAM user guide and API reference " + f"do (run tools/aws/fetch_iam_account_property_namespaces.py)") + map_keys = map_key_parts(pairs, types, model, vendored_keys) + if map_keys != document["fromMapKeys"]: + raise ValueError("IAM map key condition keys differ from AWS Service Reference") + if classify(unclaimed(pairs, map_keys), types, model, resource_tag_types(reference), + measured_resources(reference)) != ( document["read"], document["fromTarget"], document["fromResource"], document["notRead"]): raise ValueError("IAM condition key targets differ from AWS Service Reference") if request_tag_context(reference, model) != document["requestTags"]: @@ -354,12 +418,13 @@ def main(argv=None): require_by_hand_listed(pairs) data, provenance = resolve_botocore_data(args.botocore_data) model = load_model(latest_model_dir(data, "iam")) + map_keys = map_key_parts(pairs, types, model, load_map_keys()) read, from_target, from_resource, not_read = classify( - pairs, types, model, resource_tag_types(reference), measured_resources(reference)) + unclaimed(pairs, map_keys), types, model, resource_tag_types(reference), measured_resources(reference)) request_tags = request_tag_context(reference, model) OUTPUT.write_text(render({"source": URL, "botocore": provenance, "types": types, "read": read, "fromTarget": from_target, "fromResource": from_resource, - "notRead": not_read, "requestTags": request_tags})) + "fromMapKeys": map_keys, "notRead": not_read, "requestTags": request_tags})) return 0 diff --git a/tools/aws/sources/iam-account-property-namespaces.json b/tools/aws/sources/iam-account-property-namespaces.json new file mode 100644 index 0000000000..6d0bf70026 --- /dev/null +++ b/tools/aws/sources/iam-account-property-namespaces.json @@ -0,0 +1,30 @@ +{ + "_source": { + "pages": [ + "https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html", + "https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutAccountProperties.html" + ], + "fetcher": "tools/aws/fetch_iam_account_property_namespaces.py", + "retrieved": "2026-11-29", + "note": "The guide's sentence on iam:AccountPropertyNamespaces and the API reference's on the keys of PutAccountProperties' properties, copied as they stand, with what each names: the key and its operations, the parameter, its keys' format, the separator and the part that is the namespace." + }, + "key": { + "key": "iam:AccountPropertyNamespaces", + "operations": [ + "GetAccountProperties", + "PutAccountProperties" + ], + "sentence": "iam:AccountPropertyNamespaces Works with string operators. Specifies the account property namespaces being read or modified in the request. Account properties are organized into namespaces (for example, RoleManager). When you call PutAccountProperties or GetAccountProperties, use this condition key to restrict which property namespaces a principal can access." + }, + "keys": [ + { + "operation": "PutAccountProperties", + "member": "Properties", + "key": "iam:AccountPropertyNamespaces", + "format": "Namespace/PropertyName", + "separator": "/", + "part": "Namespace", + "row": "Each key uses the format Namespace/PropertyName. The key must contain exactly one / separating the namespace from the property name, and cannot start or end with /." + } + ] +} diff --git a/tools/aws/test_fetch_iam_account_property_namespaces.py b/tools/aws/test_fetch_iam_account_property_namespaces.py new file mode 100644 index 0000000000..0c6daa84f4 --- /dev/null +++ b/tools/aws/test_fetch_iam_account_property_namespaces.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Tests for fetch_iam_account_property_namespaces.py, on pages in the IAM user guide's and API reference's markup.""" +from __future__ import annotations + +import pytest + +import fetch_iam_account_property_namespaces as f + +KEY = ('
iam:AccountPropertyNamespaces
' + '

Works with string operators.

Specifies the account property namespaces ' + 'being read or modified in the\n request. Account properties are organized into namespaces (for example,\n ' + 'RoleManager). When you call PutAccountProperties or\n ' + 'GetAccountProperties, use this condition key to restrict which\n property namespaces ' + 'a principal can access.

') +OTHER_KEY = ('
iam:AssociatedResourceArn

Works with ARN operators.

' + '
') +PROPERTIES = ('
\n Properties\n
\n' + '
Properties.entry.N.key (key)
\n' + '

A map of property key-value pairs to set. All keys must belong to the same\n namespace.

' + '

Each key uses the format Namespace/PropertyName. The key must contain\n' + ' exactly one / separating the namespace from the property name, and cannot\n' + ' start or end with /.

Type: String to string map

') +NAME = '
\n RoleName\n
\n

The name of the role.

' + + +def keys_page(*entries: str) -> str: + listed = "".join(entries) if entries else OTHER_KEY + KEY + return f'

IAM condition keys

{listed}
' + + +def operation_page(*parameters: str, operation: str = "PutAccountProperties") -> str: + listed = "".join(parameters) if parameters else NAME + PROPERTIES + return (f'

{operation}

' + f'

Request Parameters

{listed}
' + f'

Errors

') + + +def pages(keys: str | None = None, operation: str | None = None): + return lambda url: (keys or keys_page()) if url == f.KEYS_PAGE else (operation or operation_page()) + + +def test_the_key_is_read_from_the_part_of_each_key_the_operations_parameter_names_the_namespace(): + built = f.build(pages()) + assert built["key"]["key"] == "iam:AccountPropertyNamespaces" + assert built["key"]["operations"] == ["GetAccountProperties", "PutAccountProperties"] + # A parameter whose keys hold no namespace, as RoleName, is not read. + assert built["keys"] == [{ + "operation": "PutAccountProperties", "member": "Properties", "key": "iam:AccountPropertyNamespaces", + "format": "Namespace/PropertyName", "separator": "/", "part": "Namespace", + "row": "Each key uses the format Namespace/PropertyName. The key must contain exactly one / separating the " + "namespace from the property name, and cannot start or end with /."}] + + +def test_a_page_whose_layout_or_wording_changed_is_refused(): + with pytest.raises(ValueError, match="what iam:AccountPropertyNamespaces is"): + f.build(pages(keys=keys_page(KEY.replace("being read or modified", "being changed")))) + with pytest.raises(ValueError, match="gives 0 request parameters"): + f.build(pages(operation=operation_page(NAME))) + with pytest.raises(ValueError, match="gives 0 request parameters"): + f.build(pages(operation=operation_page(PROPERTIES.replace("the namespace from", "the scope from")))) + with pytest.raises(ValueError, match="which operation it is for"): + f.build(pages(operation=operation_page().replace('class="topictitle"', 'class="title"'))) + + +def test_an_operation_page_the_guide_does_not_name_for_the_key_is_refused(): + with pytest.raises(ValueError, match="not to PutRolePolicy"): + f.build(pages(operation=operation_page(operation="PutRolePolicy"))) + + +def test_the_file_is_stale_when_a_page_says_something_else(): + vendored = f.build(pages()) + assert not f.stale(vendored, pages()) + assert f.stale(vendored, pages(operation=operation_page(PROPERTIES.replace("Namespace/PropertyName", + "Namespace:PropertyName") + .replace('/ separating', + ': separating')))) diff --git a/tools/aws/test_regen_iam_condition_keys.py b/tools/aws/test_regen_iam_condition_keys.py index d447117944..8c2e8eae94 100644 --- a/tools/aws/test_regen_iam_condition_keys.py +++ b/tools/aws/test_regen_iam_condition_keys.py @@ -165,7 +165,7 @@ def reference_from_document(document): action = actions.setdefault(name, {"Name": name, "ActionConditionKeys": [], "Resources": []}) action["Resources"].append({"Name": entry["type"], "ConditionKeys": [entry["key"]]}) formats[entry["type"]] = entry["arn"] - for entry in document["read"] + document["fromTarget"] + document["notRead"]: + for entry in document["read"] + document["fromTarget"] + document["fromMapKeys"] + document["notRead"]: name = entry["action"].removeprefix("iam:") action = actions.setdefault(name, {"Name": name, "ActionConditionKeys": [], "Resources": []}) if entry.get("resources"): @@ -211,6 +211,9 @@ def test_verify_fails_when_resource_type_changes_but_condition_keys_do_not(tmp_p "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/fetch_iam_account_property_namespaces.py", + "tools/aws/sources/iam-account-property-namespaces.json", + "tools/aws/test_fetch_iam_account_property_namespaces.py", "tools/aws/regen_partitions.py", "tools/aws/regen_query_services.py", "", @@ -380,3 +383,54 @@ def test_a_measured_entry_is_refused_without_a_link_or_a_member_botocore_holds(m ("Permissions", "https://docs.aws.amazon.com/IAM/latest/UserGuide/")) with pytest.raises(ValueError, match="not a string member"): regen_iam_condition_keys.require_measured_admitted(MODEL, measured) + + +ACCOUNT_PROPERTIES = {"operations": { + "PutAccountProperties": {"input": {"shape": "PutPropertiesInput"}}, + "GetAccountProperties": {"input": {"shape": "GetPropertiesInput"}}, +}, "shapes": { + "PutPropertiesInput": {"type": "structure", "members": {"Properties": {"shape": "PropertiesMap"}}}, + "GetPropertiesInput": {"type": "structure", "members": {}}, + "PropertiesMap": {"type": "map", "key": {"shape": "Key"}, "value": {"shape": "Key"}}, + "Key": {"type": "string"}, +}} +VENDORED = {"keys": [{"operation": "PutAccountProperties", "member": "Properties", "key": "iam:AccountPropertyNamespaces", + "format": "Namespace/PropertyName", "separator": "/", "part": "Namespace", + "row": "Each key uses the format Namespace/PropertyName."}]} +NAMESPACES = {"iam:AccountPropertyNamespaces": ["ArrayOfString"]} +PAIRS = [("iam:GetAccountProperties", "iam:AccountPropertyNamespaces"), + ("iam:PutAccountProperties", "iam:AccountPropertyNamespaces")] + + +def test_a_key_the_vendored_pages_place_in_a_map_keys_part_is_read_from_that_part(): + map_keys = regen_iam_condition_keys.map_key_parts(PAIRS, NAMESPACES, ACCOUNT_PROPERTIES, VENDORED) + assert map_keys == [{"action": "iam:PutAccountProperties", "key": "iam:AccountPropertyNamespaces", + "member": "Properties", "keyMember": "key", "format": "Namespace/PropertyName", + "separator": "/", "part": "Namespace"}] + # The operation whose request names no properties keeps the key unread. + rest = regen_iam_condition_keys.unclaimed(PAIRS, map_keys) + assert rest == [("iam:GetAccountProperties", "iam:AccountPropertyNamespaces")] + assert classify(rest, NAMESPACES, ACCOUNT_PROPERTIES)[3][0]["action"] == "iam:GetAccountProperties" + + +def test_a_pair_the_reference_does_not_list_is_refused(): + with pytest.raises(ValueError, match="which the reference does not list"): + regen_iam_condition_keys.map_key_parts(PAIRS[:1], NAMESPACES, ACCOUNT_PROPERTIES, VENDORED) + + +@pytest.mark.parametrize("shape, types, message", [ + ({"type": "list", "member": {"shape": "Key"}}, NAMESPACES, "not a map of string keys"), + ({"type": "map", "key": {"shape": "Key"}, "value": {"shape": "Key"}}, + {"iam:AccountPropertyNamespaces": ["ArrayOfARN"]}, "does not fit"), +]) +def test_a_member_or_key_a_map_key_part_does_not_fit_is_refused(shape, types, message): + model = json.loads(json.dumps(ACCOUNT_PROPERTIES)) + model["shapes"]["PropertiesMap"] = shape + with pytest.raises(ValueError, match=message): + regen_iam_condition_keys.map_key_parts(PAIRS, types, model, VENDORED) + + +def test_a_member_botocore_does_not_model_is_refused(): + vendored = {"keys": [{**VENDORED["keys"][0], "member": "Settings"}]} + with pytest.raises(ValueError, match="Settings is not in botocore"): + regen_iam_condition_keys.map_key_parts(PAIRS, NAMESPACES, ACCOUNT_PROPERTIES, vendored)