fix(iam): read EventBridge's rule and target condition keys from the vendored user guide (#9673)

Under enforcement a PutRule scoped by events:source was refused for every event pattern, and a PutTargets scoped by events:TargetArn for every target, as #8320 reports: the request condition key table never filled either key, so a Null or ForAllValues condition on them never saw a value. The table's reader is generic, but which member carries a key comes from SERVICES in regen_request_condition_keys.py, and EventBridge was not there. Neither botocore nor the Service Reference says where a request carries these keys: botocore models EventPattern as a string ("The event pattern").

EventBridge's user guide says it, in its table of condition keys: events:source is "the literal string for the source field of the event", with events:detail-type, events:detail.service, events:detail.eventTypeCode and events:detail.userIdentity.principalId the same for their fields, which a rule's event pattern gives ("EventPattern is a mandatory argument to PutRule"), and events:TargetArn is "the ARN of the target for the rule". A vendored source, tools/aws/sources/eventbridge-condition-keys.json, written by tools/aws/fetch_eventbridge_conditions.py from that page, gives each key its member, and the generator reads it for events (CONDITION_SOURCES), each key in the one operation the page names: PutEvents, CreateEventSource and UpdateEventSource take events:source too, which the page does not describe, so they are not read there. --verify checks the file against the page.

The table writes a field of a JSON document a string member holds after #: EventPattern#source.* is each literal string of the pattern's source, read by one generic step of the JSON reader. A pattern leaving a field out names nothing, so ForAllValues allows it and a Null check refuses it, as the page's examples show. The fields are read at the pattern's top level, where every example on the page gives them, so a $or branch's names nothing, and a matcher such as {"prefix": "aws."} is no literal string and names nothing. events:TargetArn reads each target's own Arn, not its dead-letter queue's.

Closes #8320.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-28 15:50:13 -04:00
1 parent 0609698473
commit b4cc436ad0
11 files changed
+583 -11

No files matched your search

+3
View File
@@ -94,6 +94,9 @@ on:
- 'src/main/resources/aws/request-condition-keys.json'
- 'tools/aws/regen_request_condition_keys.py'
- 'tools/aws/test_regen_request_condition_keys.py'
- 'tools/aws/sources/eventbridge-condition-keys.json'
- 'tools/aws/fetch_eventbridge_conditions.py'
- 'tools/aws/test_fetch_eventbridge_conditions.py'
- 'src/main/resources/aws/rest-routes.json'
- 'tools/aws/regen_rest_routes.py'
- 'tools/aws/test_regen_rest_routes.py'
+4 -2
View File
@@ -644,7 +644,9 @@ S3CONTROL_TAG_CONDITION_KEYS_PATHS := src/main/resources/aws/s3control-tag-condi
tools/aws/regen_iam_tag_on_create.py $(IAM_PASSED_ROLES_GENERATOR)
REQUEST_CONDITION_KEYS_PATHS := src/main/resources/aws/request-condition-keys.json \
tools/aws/regen_request_condition_keys.py tools/aws/test_regen_request_condition_keys.py \
tools/aws/regen_dynamodb_condition_keys.py tools/aws/regen_iam_tag_on_create.py $(IAM_PASSED_ROLES_GENERATOR)
tools/aws/regen_dynamodb_condition_keys.py tools/aws/regen_iam_tag_on_create.py $(IAM_PASSED_ROLES_GENERATOR) \
tools/aws/sources/eventbridge-condition-keys.json tools/aws/fetch_eventbridge_conditions.py \
tools/aws/test_fetch_eventbridge_conditions.py
DOCUMENTED_ROUTES_PATHS := src/main/resources/aws/rest-routes.json tools/aws/regen_rest_routes.py \
tools/aws/test_regen_rest_routes.py tools/aws/regen_partitions.py tools/aws/regen_query_services.py
IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json \
@@ -986,7 +988,7 @@ s3control-tag-condition-keys-verify: ## Check the S3 Control tag condition actio
$(PYTHON) tools/aws/regen_s3control_tag_condition_keys.py --verify
.PHONY: request-condition-keys-sync request-condition-keys-check request-condition-keys-verify
request-condition-keys-sync: ## Regenerate the Lambda Web, Redshift, Route 53 and STS request condition keys from AWS and botocore
request-condition-keys-sync: ## Regenerate the EventBridge, Lambda Web, Redshift, Route 53 and STS request condition keys from AWS and botocore
$(PYTHON) tools/aws/regen_request_condition_keys.py
request-condition-keys-check: ## Check the request condition key members against pinned botocore
$(PYTHON) tools/aws/regen_request_condition_keys.py --check
+16
View File
@@ -4173,6 +4173,22 @@ floci populates:
`ForAllValues:StringEquals` with `Null` set to `false` to require every change to match. The actions, the
request members, their botocore shapes and the request protocol come from the same
`request-condition-keys.json`, and Route 53 spells the names as its `DNSName` shape.
- `events:source`, `events:detail-type`, `events:detail.service`, `events:detail.eventTypeCode` and
`events:detail.userIdentity.principalId`: each literal string a `PutRule` request's event pattern gives the
event's field of that name, and `events:TargetArn`: the `Arn` of each target a `PutTargets` request adds, not its
dead-letter queue's. A pattern leaving a field out names nothing, so `ForAllValues` allows it and a `Null` check
on the key refuses it, as the
[EventBridge condition keys](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-conditions.html)
page shows. The fields are read at the pattern's top level, where every example on the page gives them, so a
`$or` branch's names nothing; a matcher in the pattern (`{"prefix": "aws."}`) is no literal string and names
nothing. Neither
botocore nor the Service Reference says which member carries these keys, so a vendored source,
`tools/aws/sources/eventbridge-condition-keys.json`, written by `tools/aws/fetch_eventbridge_conditions.py` from
that page, gives each: a key whose row is "the literal string for the source field of the event" reads that field
of `PutRule`'s `EventPattern` ("EventPattern is a mandatory argument to PutRule"), and `events:TargetArn`, "the
ARN of the target for the rule", reads `Targets[].Arn`. `PutEvents`, `CreateEventSource` and `UpdateEventSource`
take `events:source` too, which the page does not describe, so they are not read there. The actions and members
come from the same `request-condition-keys.json`.
- `eks:authenticationMode`, `eks:bootstrapClusterCreatorAdminPermissions`, `eks:endpointPrivateAccess` and
`eks:endpointPublicAccess`: the `accessConfig` and `resourcesVpcConfig` members a `CreateCluster` request
names, and the three an `UpdateClusterConfig` takes, read from the JSON body as given; a member left out or
@@ -1,5 +1,6 @@
package io.floci.aws.core.common;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
@@ -70,6 +71,8 @@ public class IamConditionContextResolver {
private static final Logger LOG = Logger.getLogger(IamConditionContextResolver.class);
/** Reads a resource EC2 holds as its fields, java.time ones included. */
private static final ObjectMapper RESOURCE_MAPPER = new ObjectMapper().findAndRegisterModules();
/** Reads the JSON document a request member holds as a string (an EventBridge rule's event pattern). */
private static final ObjectMapper DOCUMENT_MAPPER = new ObjectMapper();
/** Set by {@code ResourceArnBuilder.readJsonBody}, which runs earlier in the same filter pass. */
static final String BUFFERED_JSON_BODY = "floci.bufferedJsonBody";
@@ -483,13 +486,35 @@ public class IamConditionContextResolver {
if (body == null) {
return null;
}
values = member -> jsonValues(body, member.split("\\."), 0, new ArrayList<>());
values = member -> memberValues(body, member);
} else {
return null;
}
return requestConditions(action, values, requestConditionSpelling(namespace));
}
/**
* The scalar values of the member at {@code member} in a JSON body, a path as the table writes it: the values at
* the path ({@link #jsonValues}), or, for a string member holding a JSON document, the path after {@code #} read
* in each document it holds (an EventBridge rule's {@code EventPattern#source.*}, the literal strings of its
* {@code source}). A document that is not JSON, which the handler refuses, names nothing.
*/
private static List<String> memberValues(JsonNode body, String member) {
int document = member.indexOf('#');
if (document < 0) {
return jsonValues(body, member.split("\\."), 0, new ArrayList<>());
}
List<String> found = new ArrayList<>();
for (String text : jsonValues(body, member.substring(0, document).split("\\."), 0, new ArrayList<>())) {
try {
jsonValues(DOCUMENT_MAPPER.readTree(text), member.substring(document + 1).split("\\."), 0, found);
} catch (JsonProcessingException ignored) {
// A document that is not JSON names nothing; the handler refuses the request.
}
}
return found;
}
/**
* The scalar values at {@code path} in a JSON body, a member path as the table writes it, {@code *} stepping into
* every element of a list or map; a JSON null, a structure or a list where the path ends names nothing.
@@ -2,7 +2,7 @@
"_source": {
"generator": "tools/aws/regen_request_condition_keys.py",
"reference": "https://servicereference.us-east-1.amazonaws.com/",
"botocore": "botocore 1.43.118 (installed package)",
"botocore": "botocore 1.44.9 (installed package)",
"note": "make request-condition-keys-check re-derives members, their shapes and the protocols from botocore; make request-condition-keys-verify checks actions against AWS."
},
"actions": {
@@ -22,6 +22,26 @@
"eks:endpointPrivateAccess",
"eks:endpointPublicAccess"
],
"events:CreateEventSource": [
"events:source"
],
"events:PutEvents": [
"events:detail-type",
"events:source"
],
"events:PutRule": [
"events:detail-type",
"events:detail.eventTypeCode",
"events:detail.service",
"events:detail.userIdentity.principalId",
"events:source"
],
"events:PutTargets": [
"events:TargetArn"
],
"events:UpdateEventSource": [
"events:source"
],
"lambda:CreateWebFunction": [
"lambda:Request/WebFunctionAuthType"
],
@@ -100,6 +120,28 @@
"resourcesVpcConfig.endpointPublicAccess"
]
},
"events:PutRule": {
"events:detail-type": [
"EventPattern#detail-type.*"
],
"events:detail.eventTypeCode": [
"EventPattern#detail.eventTypeCode.*"
],
"events:detail.service": [
"EventPattern#detail.service.*"
],
"events:detail.userIdentity.principalId": [
"EventPattern#detail.userIdentity.principalId.*"
],
"events:source": [
"EventPattern#source.*"
]
},
"events:PutTargets": {
"events:TargetArn": [
"Targets.*.Arn"
]
},
"lambda:CreateWebFunction": {
"lambda:Request/WebFunctionAuthType": [
"endpointConfig.authType"
@@ -157,6 +199,16 @@
"resourcesVpcConfig.endpointPrivateAccess": "BoxedBoolean",
"resourcesVpcConfig.endpointPublicAccess": "BoxedBoolean"
},
"events:PutRule": {
"EventPattern#detail-type.*": "EventPattern",
"EventPattern#detail.eventTypeCode.*": "EventPattern",
"EventPattern#detail.service.*": "EventPattern",
"EventPattern#detail.userIdentity.principalId.*": "EventPattern",
"EventPattern#source.*": "EventPattern"
},
"events:PutTargets": {
"Targets.*.Arn": "TargetArn"
},
"lambda:CreateWebFunction": {
"endpointConfig.authType": "AuthType"
},
@@ -184,6 +236,7 @@
},
"protocols": {
"eks": "rest-json",
"events": "json",
"lambda": "rest-json",
"redshift": "query",
"route53": "rest-xml",
@@ -4000,6 +4000,66 @@ class IamRequestResourceEnforcementIntegrationTest {
return arn;
}
/**
* A rule is checked with the literal strings its event pattern gives the event's fields, as {@code events:source}
* and {@code events:detail-type}, and a rule's targets with their ARNs, as {@code events:TargetArn}, as the
* EventBridge user guide gives them: a pattern leaving the source out names none, so a {@code Null} check
* refuses it, and every source and every target ARN must be allowed.
*/
@Test
void anEventBridgeRuleIsCheckedWithItsPatternsSourcesAndItsTargetsArns() {
User user = user("events-conditions");
String rule = "conditions-" + suffix();
cleanup.register(() -> admin("events").header("X-Amz-Target", "AWSEvents.DeleteRule")
.contentType("application/x-amz-json-1.1").body("{\"Name\":\"" + rule + "\",\"Force\":true}")
.post("/"));
String sources = "{\"Effect\":\"Allow\",\"Action\":\"events:PutRule\",\"Resource\":\"*\",\"Condition\":{"
+ "\"Null\":{\"events:source\":\"false\"},\"ForAllValues:StringEquals\":{\"events:source\":"
+ "[\"aws.ec2\",\"aws.health\"]}}}";
user.policy(sources);
patternRule(user, rule, "{\"source\":[\"aws.ec2\"]}").statusCode(200);
patternRule(user, rule, "{\"source\":[\"aws.ec2\",\"aws.health\"]}").statusCode(200);
refusedJson(patternRule(user, rule, "{\"source\":[\"aws.ec2\",\"aws.s3\"]}"), "events:PutRule");
refusedJson(patternRule(user, rule, "{\"detail-type\":[\"EC2 Instance State-change Notification\"]}"),
"events:PutRule");
// An explicit deny on one source holds against an allow of every rule.
user.policy(allowOn("events:PutRule", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"events:PutRule\","
+ "\"Resource\":\"*\",\"Condition\":{\"ForAnyValue:StringEquals\":{\"events:source\":\"aws.s3\"}}}");
patternRule(user, rule, "{\"source\":[\"aws.ec2\"]}").statusCode(200);
refusedJson(patternRule(user, rule, "{\"source\":[\"aws.ec2\",\"aws.s3\"]}"), "events:PutRule");
user.policy("{\"Effect\":\"Allow\",\"Action\":\"events:PutRule\",\"Resource\":\"*\",\"Condition\":{"
+ "\"ForAllValues:StringEquals\":{\"events:detail-type\":"
+ "\"EC2 Instance State-change Notification\"}}}");
patternRule(user, rule, "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change "
+ "Notification\"]}").statusCode(200);
refusedJson(patternRule(user, rule, "{\"detail-type\":[\"AWS API Call via CloudTrail\"]}"), "events:PutRule");
String queue = "arn:aws:sqs:us-east-1:" + ACCOUNT + ":";
user.policy("{\"Effect\":\"Allow\",\"Action\":\"events:PutTargets\",\"Resource\":\"*\",\"Condition\":{"
+ "\"ForAllValues:ArnLike\":{\"events:TargetArn\":\"" + queue + "allowed-*\"}}}");
targets(user, rule, queue + "allowed-a", queue + "allowed-b").statusCode(200);
refusedJson(targets(user, rule, queue + "allowed-a", queue + "other"), "events:PutTargets");
}
/** {@code PutRule} of a rule of the name on the default bus with the event pattern, as {@code user}. */
private static ValidatableResponse patternRule(User user, String name, String pattern) {
return user.json("events", "AWSEvents.PutRule", "1.1").body("{\"Name\":\"" + name + "\",\"EventPattern\":\""
+ pattern.replace("\"", "\\\"") + "\"}").post("/").then();
}
/** {@code PutTargets} of one target for each ARN on the rule, as {@code user}. */
private static ValidatableResponse targets(User user, String rule, String... arns) {
StringBuilder targets = new StringBuilder();
for (int i = 0; i < arns.length; i++) {
targets.append(i == 0 ? "" : ",").append("{\"Id\":\"t").append(i).append("\",\"Arn\":\"").append(arns[i])
.append("\"}");
}
return user.json("events", "AWSEvents.PutTargets", "1.1").body("{\"Rule\":\"" + rule + "\",\"Targets\":["
+ targets + "]}").post("/").then();
}
/** Puts a rule of the name on the bus {@code bus} names, a JSON member or none, and gives its ARN. */
private String putRule(String name, String bus) {
String arn = admin("events").header("X-Amz-Target", "AWSEvents.PutRule").contentType("application/x-amz-json-1.1")
+158
View File
@@ -0,0 +1,158 @@
#!/usr/bin/env python3
"""Vendor which request member carries each EventBridge condition key a rule's request takes into
tools/aws/sources/eventbridge-condition-keys.json, a source of the request condition key table.
AWS's Service Reference gives PutRule the keys `events:source`, `events:detail-type` and the `events:detail.*` keys,
and PutTargets `events:TargetArn`, without saying where a request carries them, and botocore does not say it either:
it models PutRule's EventPattern as a string ("The event pattern") and PutTargets' Targets as the targets it adds.
EventBridge's user guide says, in its table of condition keys, what each one holds:
events:source Use source for the literal string for the source field of the event such as "aws.ec2"
events:TargetArn For target-arn, use the ARN of the target for the rule
and that the event's fields are those of the event pattern of the rule PutRule creates, and the target the one a
rule is given:
Policy B allows PutRule only if the event pattern of the rule being created matches Amazon EC2 events.
EventPattern is a mandatory argument to PutRule.
... you must also add a target to a rule.
To grant access to a specific resource, use the events:TargetArn condition key.
https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-conditions.html
This script copies each key's row of that table as it stands, with the sentence saying where its value is, and gives
each key whose row names a field of the event that field, read from PutRule's EventPattern, and the key whose row names
the ARN of the target, read from each of PutTargets' Targets. A row naming neither is not read. Nothing in the output
is written by hand; regen_request_condition_keys.py reads it to give the table those members.
Run from anywhere in the repo:
python3 tools/aws/fetch_eventbridge_conditions.py # rewrite the vendored file from the page
python3 tools/aws/fetch_eventbridge_conditions.py --verify # online: the file still says what the page does
"""
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
PAGE = "https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-conditions.html"
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "tools/aws/sources/eventbridge-condition-keys.json"
# The members the page says carry the keys, each with what a key's row says of its value and the sentences of the page
# that say where the request carries it: a field of the event, read from the event pattern of the rule PutRule
# creates, and the ARN of a target, read from each target PutTargets adds to a rule.
MEMBERS = (
{"operation": "PutRule", "member": "EventPattern",
"row": re.compile(r"\bthe literal string for the (?P<field>[A-Za-z][\w.-]*) field of the event\b"),
"says": (re.compile(r"\bPutRule only if the event pattern of the rule being created\b[^.]*\."),
re.compile(r"\bEventPattern is a mandatory argument to PutRule\s*\.")),
"document": True},
{"operation": "PutTargets", "member": "Targets.*.Arn",
"row": re.compile(r"\buse the ARN of the target for the rule\b"),
"says": (re.compile(r"\bpermissions for the events:PutTargets action because[^.]*add a target to a rule\."),
re.compile(r"\bTo grant access to a specific resource, use the events:TargetArn condition key\.")),
"document": False},
)
KEY_RE = re.compile(r"^events:[\w./-]+$")
def text(fragment: str) -> str:
"""A fragment of a page as text, spaces collapsed and none left before a full stop."""
return re.sub(r"\s+([.,])", r"\1", re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment)))).strip()
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 key_rows(page: str) -> list[tuple[str, str]]:
"""Each EventBridge key of the page's table of condition keys, with its row's key and value pair as text."""
for table in re.findall(r"<table[^>]*>(.*?)</table>", body(page), re.S):
rows = []
for row in re.findall(r"<tr>(.*?)</tr>", table, re.S):
cells = [text(cell) for cell in re.findall(r"<t[dh][^>]*>(.*?)</t[dh]>", row, re.S)]
key = cells[0].replace(" ", "") if cells else ""
if len(cells) > 1 and KEY_RE.match(key):
rows.append((key, cells[1]))
if rows:
return rows
raise ValueError(f"{PAGE} has no table of EventBridge condition keys: its layout changed")
def build(fetch) -> dict:
page = fetch(PAGE)
content = text(body(page))
keys = []
for member in MEMBERS:
said = [found.group(0) for found in (pattern.search(content) for pattern in member["says"]) if found]
if len(said) != len(member["says"]):
raise ValueError(f"{PAGE} no longer says where {member['operation']}'s {member['member']} carries its "
f"keys: its layout changed")
for key, row in key_rows(page):
found = member["row"].search(row)
if found is None:
continue
entry = {"key": key, "operation": member["operation"], "member": member["member"]}
if member["document"]:
entry["field"] = found.group("field")
keys.append({**entry, "row": row, "says": said})
if not keys:
raise ValueError(f"{PAGE} names no key's member: its layout changed")
return {
"_source": {
"page": PAGE,
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
"note": "Each EventBridge key whose row of the page's table of condition keys names a field of the event, "
"read from PutRule's EventPattern (field), or the ARN of the target, read from PutTargets' "
"Targets[].Arn, with the row and the page's sentences saying so, copied as they stand.",
},
"keys": sorted(keys, key=lambda entry: (entry["operation"], entry["key"])),
}
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, page: str) -> bool:
"""Whether the page now gives something other than the vendored file, its date aside."""
return vendored.get("keys") != build(lambda url: page)["keys"]
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 page")
args = parser.parse_args(argv)
try:
page = fetch(PAGE)
except OSError as e:
print(f"error: could not read the EventBridge user guide ({e})", file=sys.stderr)
return 2
if args.verify:
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
if stale(vendored, page):
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the EventBridge user guide does: run "
f"tools/aws/fetch_eventbridge_conditions.py and then make request-condition-keys-sync",
file=sys.stderr)
return 1
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the EventBridge user guide")
return 0
built = build(lambda url: page)
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['keys'])} keys)")
return 0
if __name__ == "__main__":
sys.exit(main())
+74 -6
View File
@@ -22,6 +22,13 @@ it. `SERVICES` names, for each namespace, the keys read and where:
name as `route53:ChangeResourceRecordSetsActions`, `...RecordTypes` and `...NormalizedRecordNames`. The names
are read as `DNSName` members, which Route 53 spells as AWS normalizes them for the key, through the spelling
the service registers for that shape.
- `events`: a PutRule request is checked with the literal strings its event pattern gives the event's `source`,
`detail-type`, `detail.service`, `detail.eventTypeCode` and `detail.userIdentity.principalId` fields as
`events:source`, `events:detail-type` and the `events:detail.*` keys, and a PutTargets request with the ARN of
each target it adds as `events:TargetArn`, as the EventBridge user guide gives them (`CONDITION_SOURCES`); a
pattern leaving a field out names nothing. PutEvents, CreateEventSource and UpdateEventSource take `events:source`
too, and PutEvents `events:detail-type`, from what they put or name, which the guide's table does not describe, so
they are not read there.
- `sts`: an AssumeRole request is checked with the session name and external ID it passes as
`sts:RoleSessionName` and `sts:ExternalId`, so the caller's identity-based policy can require them as a
trust policy can; an AssumeRole without `ExternalId` names none. AssumeRoleWithWebIdentity carries
@@ -42,7 +49,9 @@ The table comes from two sources:
`actions` holds every action that takes a key a namespace reads, with the ones it takes. `members` holds, for
every action and key read from the request, the paths of the request members named as `SERVICES` gives, as the
request carries them: dotted for a nested one, `*` for each element of a list or map in a JSON body, and in an XML
body the elements botocore names, a list's own by the name of its member (`ChangeBatch.Changes.Change.Action`).
body the elements botocore names, a list's own by the name of its member (`ChangeBatch.Changes.Change.Action`). A
string member holding a JSON document is followed by `#` and the path inside the document
(`EventPattern#source.*`, each literal string of the pattern's `source`).
A Query request is read as a flat form, so its member must be top-level; an XML request is read from its body, so
its member must not be in the URI or a header, nor reached through a map or a flattened list. A key read from the
stored resource has no member, and an action whose request does not carry the key is in `not_in_request`, with
@@ -68,12 +77,14 @@ import sys
import urllib.request
from pathlib import Path
import fetch_eventbridge_conditions
from regen_dynamodb_condition_keys import member_paths
from regen_iam_tag_on_create import _condition_keys, _resource_keys
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/request-condition-keys.json"
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "src/main/resources/aws/request-condition-keys.json"
REFERENCE = "https://servicereference.us-east-1.amazonaws.com/"
FLAT_PROTOCOLS = ("query", "ec2")
@@ -136,6 +147,35 @@ SERVICES = {
}
# CONDITION_SOURCES: the namespaces whose documentation says which request member carries a key, where neither
# botocore nor the Service Reference says it, with their botocore model and the vendored page that says so. Granted
# for EventBridge: its user guide's table of condition keys gives `events:source`, `events:detail-type` and the
# `events:detail.*` keys as "the literal string for the <field> field of the event", which a rule's "event pattern"
# gives ("EventPattern is a mandatory argument to PutRule"), and `events:TargetArn` as "the ARN of the target for the
# rule"; tools/aws/fetch_eventbridge_conditions.py vendors that page and `vendored_service` reads it. Each file is
# written by its own script from the page, unchanged, and nothing about an operation is stated here.
CONDITION_SOURCES: dict[str, dict] = {
"events": {"model": "events", "source": REPO_ROOT / "tools/aws/sources/eventbridge-condition-keys.json",
"fetcher": fetch_eventbridge_conditions},
}
def vendored_service(namespace: str) -> dict:
"""The `SERVICES` entry of a namespace a vendored page gives (`CONDITION_SOURCES`): each key read from the member
the page says carries it, a field of a JSON document after `#`, in the one operation the page names for it."""
granted = CONDITION_SOURCES[namespace]
document = json.loads(granted["source"].read_text(encoding="utf-8"))
request, operations = {}, {}
for entry in document["keys"]:
request[entry["key"]] = entry["member"] + (f"#{entry['field']}.*" if "field" in entry else "")
operations[entry["key"]] = entry["operation"]
return {"model": granted["model"], "request": request, "stored": (), "not_in_request": {},
"operations": operations}
SERVICES.update({namespace: vendored_service(namespace) for namespace in CONDITION_SOURCES})
def url(namespace: str) -> str:
return f"{REFERENCE}v1/{namespace}/{namespace}.json"
@@ -183,22 +223,31 @@ def _located(namespace: str, model: dict | None, actions: dict[str, list[str]]):
for key in keys:
if key not in service["request"] or (action, key) in service["not_in_request"]:
continue
name = service["request"][key]
# A vendored page names the one operation it reads a key from; another taking the key is not read.
if service.get("operations", {}).get(key, action.split(":", 1)[1]) != action.split(":", 1)[1]:
continue
name, _, document = service["request"][key].partition("#")
if model is None: # not modelled by botocore: the member is the name SERVICES gives
yield action, key, name, None
continue
operation = model["operations"].get(action.split(":", 1)[1])
if operation is None or "input" not in operation:
raise ValueError(f"{action} takes {key} but botocore has no request for it")
paths = member_paths(model, operation["input"]["shape"], {name})
# A vendored page gives a member by its path; `SERVICES` by its name, wherever it is.
paths = [name] if "." in name else member_paths(model, operation["input"]["shape"], {name})
if not paths:
raise ValueError(f"{action} takes {key} but its request has no {name} member")
nested = [path for path in paths if protocol in FLAT_PROTOCOLS and "." in path]
if nested:
raise ValueError(f"{action} takes {key} from {', '.join(nested)}, which a flat form does not carry")
for path in paths:
carried, shape = carried_member(model, operation["input"]["shape"], path, protocol == "rest-xml")
yield action, key, carried, shape
try:
carried, shape = carried_member(model, operation["input"]["shape"], path, protocol == "rest-xml")
except KeyError as e:
raise ValueError(f"{action} takes {key} from {path}, which its request does not have") from e
if document and model["shapes"][shape].get("type") != "string":
raise ValueError(f"{action} takes {key} from a document in {path}, which is not a string")
yield action, key, carried + (f"#{document}" if document else ""), shape
def carried_member(model: dict, shape: str, path: str, xml: bool) -> tuple[str, str]:
@@ -286,6 +335,23 @@ def _members(actions: dict[str, list[str]], botocore_data: Path | None) -> tuple
"protocols": dict(sorted(protocols.items()))}, provenance
def verify_condition_sources() -> list[str]:
"""Where a vendored page (`CONDITION_SOURCES`) no longer says what its file does: online."""
problems = []
for granted in CONDITION_SOURCES.values():
fetcher = granted["fetcher"]
try:
page = fetcher.fetch_url(fetcher.PAGE)
except OSError as e:
problems.append(f"could not read {fetcher.PAGE} ({e})")
continue
if fetcher.stale(json.loads(granted["source"].read_text(encoding="utf-8")), page):
problems.append(f"{granted['source'].relative_to(REPO_ROOT)} no longer says what {fetcher.PAGE} does: "
f"run {granted['source'].relative_to(REPO_ROOT).parent.parent}/"
f"{fetcher.__name__}.py and then make request-condition-keys-sync")
return problems
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--check", action="store_true", help="offline: members must match the pinned botocore")
@@ -304,6 +370,8 @@ def main(argv: list[str] | None = None) -> int:
problems.append(f"{section} differ from {provenance}")
if args.verify and document.get("actions") != _actions(args.source_dir):
problems.append("actions differ from the AWS Service Reference")
if args.verify:
problems += verify_condition_sources()
for problem in problems:
print(f"{OUTPUT.name}: {problem}", file=sys.stderr)
return 1 if problems else 0
@@ -0,0 +1,75 @@
{
"_source": {
"page": "https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-conditions.html",
"fetcher": "tools/aws/fetch_eventbridge_conditions.py",
"retrieved": "2026-11-28",
"note": "Each EventBridge key whose row of the page's table of condition keys names a field of the event, read from PutRule's EventPattern (field), or the ARN of the target, read from PutTargets' Targets[].Arn, with the row and the page's sentences saying so, copied as they stand."
},
"keys": [
{
"key": "events:detail-type",
"operation": "PutRule",
"member": "EventPattern",
"field": "detail-type",
"row": "\"events:detail-type\":\" detail-type \" Where detail-type is the literal string for the detail-type field of the event such as \"AWS API Call via CloudTrail\" and \"EC2 Instance State-change Notification\".",
"says": [
"PutRule only if the event pattern of the rule being created matches Amazon EC2 events.",
"EventPattern is a mandatory argument to PutRule."
]
},
{
"key": "events:detail.eventTypeCode",
"operation": "PutRule",
"member": "EventPattern",
"field": "detail.eventTypeCode",
"row": "\"events:detail.eventTypeCode\":\" eventTypeCode \" For eventTypeCode, use the literal string for the detail.eventTypeCode field of the event, such as \"AWS_ABUSE_DOS_REPORT\".",
"says": [
"PutRule only if the event pattern of the rule being created matches Amazon EC2 events.",
"EventPattern is a mandatory argument to PutRule."
]
},
{
"key": "events:detail.service",
"operation": "PutRule",
"member": "EventPattern",
"field": "detail.service",
"row": "\"events:detail.service\":\" service \" For service, use the literal string for the detail.service field of the event, such as \"ABUSE\".",
"says": [
"PutRule only if the event pattern of the rule being created matches Amazon EC2 events.",
"EventPattern is a mandatory argument to PutRule."
]
},
{
"key": "events:detail.userIdentity.principalId",
"operation": "PutRule",
"member": "EventPattern",
"field": "detail.userIdentity.principalId",
"row": "\"events:detail.userIdentity.principalId\":\" principal-id \" For principal-id, use the literal string for the detail.userIdentity.principalId field of the event with detail-type \"AWS API Call via CloudTrail\" such as \"AROAIDPPEZS35WEXAMPLE:AssumedRoleSessionName.\".",
"says": [
"PutRule only if the event pattern of the rule being created matches Amazon EC2 events.",
"EventPattern is a mandatory argument to PutRule."
]
},
{
"key": "events:source",
"operation": "PutRule",
"member": "EventPattern",
"field": "source",
"row": "\"events:source\":\" source \" Use source for the literal string for the source field of the event such as \"aws.ec2\" or \"aws.s3\". For more possible values for source, see the example events in Events from AWS services.",
"says": [
"PutRule only if the event pattern of the rule being created matches Amazon EC2 events.",
"EventPattern is a mandatory argument to PutRule."
]
},
{
"key": "events:TargetArn",
"operation": "PutTargets",
"member": "Targets.*.Arn",
"row": "\"events:TargetArn\":\" target-arn \" For target-arn, use the ARN of the target for the rule, for example \"arn:aws:lambda:*:*:function:*\".",
"says": [
"permissions for the events:PutTargets action because, if you want the rule to do more than publish a CloudWatch metric, you must also add a target to a rule.",
"To grant access to a specific resource, use the events:TargetArn condition key."
]
}
]
}
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Tests for fetch_eventbridge_conditions.py, on a page in the EventBridge user guide's markup."""
from __future__ import annotations
import pytest
import fetch_eventbridge_conditions as f
def row(key: str, value: str) -> str:
return f"<tr><td><p><code>{key}</code></p></td><td><p>{value}</p></td><td><p>ArrayOfString, Null</p></td></tr>"
ROWS = (row("events:creatorAccount", "For creatorAccount, use the account ID for the account that created the rule.")
+ row("events:source", 'Use source for the literal string for the <b>source</b> field of the event such as '
'"aws.ec2".')
+ row("events: detail.service", "For service, use the literal string for the <b>detail.service</b> field of "
"the event, such as \"ABUSE\".")
+ row("events:TargetArn", 'For target-arn, use the ARN of the target for the rule, for example "arn:aws:lambda:'
'*:*:function:*".'))
SAYS = ("<p>the user must also have permissions for the <code>events:PutTargets</code> action because, if you want the "
"rule to do more than publish a CloudWatch metric, you must also add a target to a rule.</p>"
"<p>To grant access to a specific resource, use the <code>events:TargetArn</code> condition key.</p>"
"<p>Policy B allows <code>PutRule</code> only if the event pattern of the rule being created matches Amazon "
"EC2 events.</p><p><code>EventPattern</code> is a mandatory argument to <code>PutRule</code>.</p>")
def page(rows: str = ROWS, says: str = SAYS) -> str:
return (f'<div id="main-col-body">{says}<table><tr><th>Condition key</th><th>Key value pair</th></tr>{rows}'
f'</table></div><div class="prev-next"></div>')
def test_each_key_is_read_from_the_member_its_row_names():
keys = {entry["key"]: entry for entry in f.build(lambda url: page())["keys"]}
# A field of the event is read from the rule's event pattern, a target's ARN from each target; a key naming
# neither is not read.
assert (keys["events:source"]["operation"], keys["events:source"]["member"], keys["events:source"]["field"]) \
== ("PutRule", "EventPattern", "source")
assert keys["events:detail.service"]["field"] == "detail.service"
assert (keys["events:TargetArn"]["operation"], keys["events:TargetArn"]["member"]) == ("PutTargets",
"Targets.*.Arn")
assert "field" not in keys["events:TargetArn"]
assert "events:creatorAccount" not in keys
assert keys["events:source"]["says"][1] == "EventPattern is a mandatory argument to PutRule."
def test_a_page_whose_layout_changed_is_refused():
for changed, message in ((page(rows=""), "no table"), (page(says=SAYS.replace("mandatory", "required")),
"no longer says where PutRule")):
with pytest.raises(ValueError, match=message):
f.build(lambda url: changed)
def test_the_file_is_stale_when_the_page_says_something_else():
vendored = f.build(lambda url: page())
assert not f.stale(vendored, page())
assert f.stale(vendored, page(rows=ROWS.replace("<b>source</b> field", "<b>origin</b> field")))
+56 -1
View File
@@ -132,7 +132,7 @@ def test_the_vendored_table_covers_its_namespaces():
"route53:ChangeResourceRecordSets"]
assert document["memberShapes"]["route53:ChangeResourceRecordSets"][
"ChangeBatch.Changes.Change.ResourceRecordSet.Name"] == "DNSName"
assert document["protocols"] == {"eks": "rest-json", "lambda": "rest-json",
assert document["protocols"] == {"eks": "rest-json", "events": "json", "lambda": "rest-json",
"redshift": "query", "route53": "rest-xml", "sts": "query"}
@@ -142,6 +142,9 @@ def test_the_vendored_table_covers_its_namespaces():
"tools/aws/test_regen_request_condition_keys.py",
"tools/aws/regen_dynamodb_condition_keys.py",
"tools/aws/regen_iam_tag_on_create.py",
"tools/aws/sources/eventbridge-condition-keys.json",
"tools/aws/fetch_eventbridge_conditions.py",
"tools/aws/test_fetch_eventbridge_conditions.py",
"tools/aws/regen_iam_passed_roles.py",
"tools/aws/regen_partitions.py",
"tools/aws/regen_query_services.py",
@@ -207,3 +210,55 @@ def test_assume_role_reads_its_session_name_and_external_id():
assert document["actions"]["sts:AssumeRoleWithSAML"] == ["sts:RoleSessionName"]
assert "sts:AssumeRoleWithSAML" not in document["members"]
assert "sts:GetCallerIdentity" not in document["actions"]
EVENTS = {"metadata": {"protocol": "json"}, "operations": {
"PutRule": {"input": {"shape": "PutRuleRequest"}}, "PutTargets": {"input": {"shape": "PutTargetsRequest"}},
"PutEvents": {"input": {"shape": "PutEventsRequest"}}}, "shapes": {
"PutRuleRequest": {"type": "structure", "members": {"Name": {"shape": "RuleName"},
"EventPattern": {"shape": "EventPattern"}}},
"PutTargetsRequest": {"type": "structure", "members": {"Rule": {"shape": "RuleName"},
"Targets": {"shape": "TargetList"}}},
"TargetList": {"type": "list", "member": {"shape": "Target"}},
"Target": {"type": "structure", "members": {"Arn": {"shape": "TargetArn"},
"DeadLetterConfig": {"shape": "DeadLetterConfig"}}},
"DeadLetterConfig": {"type": "structure", "members": {"Arn": {"shape": "ResourceArn"}}},
"PutEventsRequest": {"type": "structure", "members": {"Entries": {"shape": "Entries"}}},
"Entries": {"type": "list", "member": {"shape": "Entry"}},
"Entry": {"type": "structure", "members": {"Source": {"shape": "String"}}},
"RuleName": {"type": "string"}, "EventPattern": {"type": "string"}, "TargetArn": {"type": "string"},
"ResourceArn": {"type": "string"}, "String": {"type": "string"}}}
def test_a_vendored_key_is_read_from_its_member_in_the_one_operation_its_page_names():
# EventBridge's user guide reads events:source from the field of PutRule's event pattern, a JSON document the
# string member holds, and events:TargetArn from each target's own ARN, not its dead-letter queue's; PutEvents
# takes events:source too, which the page does not describe, so it is not read there.
actions = {"events:PutRule": ["events:source"], "events:PutTargets": ["events:TargetArn"],
"events:PutEvents": ["events:source"]}
assert request_members("events", EVENTS, actions) == {
"events:PutRule": {"events:source": ["EventPattern#source.*"]},
"events:PutTargets": {"events:TargetArn": ["Targets.*.Arn"]}}
assert member_shapes("events", EVENTS, actions)["events:PutRule"] == {"EventPattern#source.*": "EventPattern"}
def test_a_vendored_member_its_request_does_not_have_or_a_document_that_is_no_string_fails(monkeypatch):
import regen_request_condition_keys as r
entry = r.SERVICES["events"]
monkeypatch.setitem(r.SERVICES, "events", {**entry, "request": {**entry["request"], "events:TargetArn":
"Targets.*.Missing"}})
with pytest.raises(ValueError, match="Targets.*.Missing, which its request does not have"):
request_members("events", EVENTS, {"events:PutTargets": ["events:TargetArn"]})
monkeypatch.setitem(r.SERVICES, "events", {**entry, "request": {**entry["request"], "events:source":
"Targets#source.*"}})
with pytest.raises(ValueError, match="not a string"):
request_members("events", {**EVENTS, "operations": {"PutRule": {"input": {"shape": "PutTargetsRequest"}}}},
{"events:PutRule": ["events:source"]})
def test_the_vendored_table_reads_eventbridge_rules_and_targets():
document = json.loads(OUTPUT.read_text())
assert document["members"]["events:PutRule"]["events:source"] == ["EventPattern#source.*"]
assert document["members"]["events:PutRule"]["events:detail.service"] == ["EventPattern#detail.service.*"]
assert document["members"]["events:PutTargets"] == {"events:TargetArn": ["Targets.*.Arn"]}
assert "events:PutEvents" not in document["members"]