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.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-29 08:40:07 -04:00
1 parent 35fc6732c9
commit 8440821793
12 files changed
+576 -12

No files matched your search

+3
View File
@@ -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'
+2
View File
@@ -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 \
+17
View File
@@ -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`.
@@ -371,7 +371,8 @@ public class IamConditionContextResolver {
Map<String, String> members = IamConditionKeys.members(action);
Map<String, String> targets = IamConditionKeys.targets(action);
Map<String, IamConditionKeys.RequestTags> requestTags = IamConditionKeys.requestTags(action);
if (members.isEmpty() && targets.isEmpty() && requestTags.isEmpty()) {
Map<String, IamConditionKeys.MapKeyPart> mapKeyParts = IamConditionKeys.mapKeyParts(action);
if (members.isEmpty() && targets.isEmpty() && requestTags.isEmpty() && mapKeyParts.isEmpty()) {
return null;
}
Map<String, String> 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<String, List<String>> conditions, Map<String, String> form,
Map<String, IamConditionKeys.MapKeyPart> mapKeyParts) {
MultivaluedMap<String, String> parameters = queryParameters(form);
mapKeyParts.forEach((key, part) -> {
List<String> 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<String, String> queryParameters(Map<String, String> form) {
MultivaluedMap<String, String> parameters = new MultivaluedHashMap<>();
form.forEach(parameters::putSingle);
return parameters;
}
private static void addIamRequestTags(Map<String, List<String>> conditions, Map<String, String> form,
Map<String, IamConditionKeys.RequestTags> requestTags) {
MultivaluedMap<String, String> parameters = new MultivaluedHashMap<>();
form.forEach(parameters::putSingle);
MultivaluedMap<String, String> parameters = queryParameters(form);
requestTags.forEach((key, fields) -> {
List<String> keys = new ArrayList<>();
for (AwsQueryLists.IndexedMember member : AwsQueryLists.members(parameters, fields.member(), null)) {
@@ -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<String, Map<String, String>> members, Map<String, Map<String, String>> targets,
Map<String, Map<String, Resource>> resources,
Map<String, Map<String, MapKeyPart>> mapKeyParts,
Map<String, Map<String, RequestTags>> requestTags,
Map<String, Set<String>> 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<String> 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<String, MapKeyPart> mapKeyParts(String action) {
return TABLE.mapKeyParts().getOrDefault(action, Map.of());
}
static Map<String, RequestTags> requestTags(String action) {
return TABLE.requestTags().getOrDefault(action, Map.of());
}
@@ -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"]},
@@ -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("<Code>AccessDenied</Code>"))
.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);
}
}
@@ -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(?P<key>iam:[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<first>[A-Za-z]+) or "
r"(?P<second>[A-Za-z]+), use this condition key to restrict which property namespaces a principal "
r"can access\.")
OPERATION_RE = re.compile(r'<h1 class="topictitle" id="API_(?P<operation>[A-Za-z]+)">(?P=operation)</h1>')
REQUEST_PARAMETERS_RE = re.compile(r'<h2 id="API_[A-Za-z]+_RequestParameters">(?P<section>.*?)(?:<h2|$)', re.S)
# A parameter of the section: its name in bold in the first term, its other terms naming its wire form, then its
# description.
PARAMETER_RE = re.compile(r'<dt><span class="term">\s*<b>(?P<member>[A-Za-z0-9]+)</b>\s*</span></dt>'
r'(?:\s*<dt>(?:(?!<dd>).)*?</dt>)*\s*<dd>(?P<description>.*?)</dd>', re.S)
FORMAT_RE = re.compile(r"\bEach key uses the format (?P<format>(?P<namespace>[A-Za-z]+)(?P<separator>\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'<div id="main-col-body">(?P<body>.*?)(?:<div class="prev-next"|$)', page, re.S)
return match.group("body") if match else page
def _found(match: re.Match | None, page: str, what: str) -> 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())
+72 -7
View File
@@ -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
@@ -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 /."
}
]
}
@@ -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 = ('<dt><b><span class="term"><div id="ck_AccountPropertyNamespaces"></div>iam:AccountPropertyNamespaces</span>'
'</b></dt><dd><p>Works with <a href="#">string operators</a>.</p><p>Specifies the account property namespaces '
'being read or modified in the\n request. Account properties are organized into namespaces (for example,\n '
'<code class="code">RoleManager</code>). When you call <code class="code">PutAccountProperties</code> or\n '
'<code class="code">GetAccountProperties</code>, use this condition key to restrict which\n property namespaces '
'a principal can access.</p></dd>')
OTHER_KEY = ('<dt><b><span class="term">iam:AssociatedResourceArn</span></b></dt><dd><p>Works with ARN operators.</p>'
'</dd>')
PROPERTIES = ('<dt><span class="term">\n <b>Properties</b>\n </span></dt>\n'
'<dt><span class="term">Properties.entry.N.key (key)</span></dt>\n'
'<dd><p>A map of property key-value pairs to set. All keys must belong to the same\n namespace.</p>'
'<p>Each key uses the format <code class="code">Namespace/PropertyName</code>. The key must contain\n'
' exactly one <code class="code">/</code> separating the namespace from the property name, and cannot\n'
' start or end with <code class="code">/</code>.</p><p>Type: String to string map</p></dd>')
NAME = '<dt><span class="term">\n <b>RoleName</b>\n </span></dt>\n<dd><p>The name of the role.</p></dd>'
def keys_page(*entries: str) -> str:
listed = "".join(entries) if entries else OTHER_KEY + KEY
return f'<div id="main-col-body"><h1>IAM condition keys</h1><dl>{listed}</dl></div><div class="prev-next"></div>'
def operation_page(*parameters: str, operation: str = "PutAccountProperties") -> str:
listed = "".join(parameters) if parameters else NAME + PROPERTIES
return (f'<div id="main-col-body"><h1 class="topictitle" id="API_{operation}">{operation}</h1>'
f'<h2 id="API_{operation}_RequestParameters">Request Parameters</h2><dl>{listed}</dl>'
f'<h2 id="API_{operation}_Errors">Errors</h2></div><div class="prev-next"></div>')
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('<code class="code">/</code> separating',
'<code class="code">:</code> separating'))))
+55 -1
View File
@@ -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)