mirror of
https://github.com/floci-io/floci.git
synced 2026-12-04 18:48:00 -05:00
Under enforcement a REST route no vendored model names runs unchecked, and Bedrock AgentCore was among them: any caller
could create, read, update or delete its runtimes, runtime endpoints, gateways, gateway targets and rules, memories,
harnesses, browsers, code interpreters, workload identities and credential providers, put a resource policy, write and
read memory events and invoke a runtime, with no permission at all. AgentCore's two models are vendored now
(regen_rest_routes.MODELS: bedrock-agentcore and bedrock-agentcore-control, both signed bedrock-agentcore), so each
request is checked as its operation's action, and bedrock-agentcore joins the generated tables of request resources,
passed roles and tags on create: a resource by the id its path gives, the role each create or update passes, and the
tags a create carries.
The Service Reference passes CreateCapacityProvider's roles to bedrock-agentcore and ec2 without saying which member's
goes where. fetch_bedrock_agentcore_roles.py vendors what AWS says of each into
tools/aws/sources/bedrock-agentcore-roles.json, a ROLE_SOURCES entry as Batch's is: the operator role is "the IAM role
that AgentCore assumes to manage the capacity provider" (Control API reference), which AgentCore's capacity provider
sample says must trust bedrock-agentcore.amazonaws.com, and launchParameters.instanceProfileArn is "the IAM instance
profile to associate with launched instances", whose role the IAM User Guide's trust policy for an EC2 instance's role
gives to ec2.amazonaws.com. That member names an instance profile, which the rule does not read by its name, so the
source lists it in roleMembers, and the check that every vendored role is read now counts such members as the table
does.
BedrockAgentCoreStoredResourceArns answers the tags AgentCore holds on the resource an ARN reaches, in its account and
Region, which an aws:ResourceTag condition reads: a runtime, a runtime endpoint, a gateway, a memory or a harness as
the tag routes read the same ARN (a qualified runtime ARN answers the runtime's), and a custom browser, a custom code
interpreter or a browser profile from the tool. The table asks for a consent portal, a code interpreter by its name or
a configuration bundle to be found, which Floci does not serve, and for the memory an event is in, which the path of
GetEvent and DeleteEvent already names. A runtime endpoint's routes are checked on its runtime and a credential
provider's on *, as the generated table reads them: their ARNs end in a ${Name} beside another variable, which no
reading fills.
The tag routes no longer take the agent/<uuid> and agentEndpoint/<uuid> forms Floci wrote before #8088. They name no
AWS resource, so IAM could only check them as named, past a deny on the runtime or endpoint they reached; they now get
a ValidationException, and a legacy agent/ ARN names no runtime on invoke. A CloudFormation stack that holds an
agentEndpoint/<uuid> physical id still updates and deletes that endpoint.
A namespace the table reads is served on its tag routes only at the ARN its path encodes, as Connect's, MSK's and
MWAA's are, so AgentCore's and CloudFormation's AgentCore tests send the ARN encoded, as the SDKs do, and
docs/services/bedrock-agentcore.md says so.
IamRestRouteEnforcementIntegrationTest checks that with no grant a gateway's read is refused, that a grant on one
gateway reads it and refuses another, and that an aws:ResourceTag condition reads its tags; that a gateway create needs
iam:PassRole on its role and bedrock-agentcore:TagResource for the tags it carries; that a data plane event write is
checked on the memory its path names; that an aws:ResourceTag grant reads a browser's tags; and that a deny on a
runtime's tags holds for its ARN and its qualified ARN while the legacy endpoint form is refused.
245 lines
12 KiB
Python
245 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Vendor which role a Bedrock AgentCore request member names, and the service that role is for, into
|
|
tools/aws/sources/bedrock-agentcore-roles.json, a source of the passed-roles table.
|
|
|
|
AWS's Service Reference passes CreateCapacityProvider's roles to `bedrock-agentcore.amazonaws.com` and
|
|
`ec2.amazonaws.com` without saying which member's role goes where, and botocore does not say it as data either. The
|
|
request names two. The AgentCore Control API reference describes the first, PermissionsConfiguration's
|
|
capacityProviderOperatorRoleArn, as
|
|
|
|
The Amazon Resource Name (ARN) of the IAM role that AgentCore assumes to manage the capacity provider, ...
|
|
|
|
https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_PermissionsConfiguration.html
|
|
|
|
and AWS's AgentCore samples give the principal that role trusts, in the capacity provider sample's section on its two
|
|
roles, whose table says the operator role is the one "Passed to `create_capacity_provider(permissionsConfiguration=…)`":
|
|
|
|
Both must trust `bedrock-agentcore.amazonaws.com`.
|
|
|
|
https://github.com/awslabs/agentcore-samples/blob/main/01-features/02-host-your-agent/01-runtime/01-hosting-agents/
|
|
08-http-ec2-capacity-provider/README.md
|
|
|
|
The second, LaunchParameters' instanceProfileArn, is "The Amazon Resource Name (ARN) of the IAM instance profile to
|
|
associate with launched instances", and the IAM user guide's page on roles for applications on EC2 instances gives the
|
|
trust policy of an instance profile's role, which names `ec2.amazonaws.com`. This script copies each member's
|
|
description on its API reference page as it stands, the sample's lines on the operator role, and the service
|
|
principals each role's page says it trusts; a member naming an instance profile is marked so (`instanceProfile`),
|
|
since the roles passed are the profile's, and is named for the passed-roles rule (`roleMembers`), which reads a member
|
|
as a role by its name. Nothing in the output is written by hand; regen_iam_passed_roles.py reads it to choose, among
|
|
the services the Service Reference passes an operation's roles to, the one each member's role is for.
|
|
|
|
Run from anywhere in the repo:
|
|
python3 tools/aws/fetch_bedrock_agentcore_roles.py # rewrite the vendored file from the pages
|
|
python3 tools/aws/fetch_bedrock_agentcore_roles.py --verify # online: the file still says what the pages 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
|
|
|
|
API_REFERENCE = "https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/"
|
|
SAMPLE = ("https://raw.githubusercontent.com/awslabs/agentcore-samples/main/01-features/02-host-your-agent/01-runtime/"
|
|
"01-hosting-agents/08-http-ec2-capacity-provider/README.md")
|
|
EC2_ROLES = "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html"
|
|
MODEL = "bedrock-agentcore-control"
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/bedrock-agentcore-roles.json"
|
|
|
|
# The members that name a role, each a member of a type a request holds, with the page of its role: the sample's
|
|
# section on the operator role, or the IAM user guide's page on the role of an EC2 instance profile.
|
|
MEMBERS = (
|
|
{"type": "PermissionsConfiguration", "member": "capacityProviderOperatorRoleArn", "rolePage": SAMPLE,
|
|
"operation": "CreateCapacityProvider"},
|
|
{"type": "LaunchParameters", "member": "instanceProfileArn", "rolePage": EC2_ROLES},
|
|
)
|
|
# A description of a member naming an instance profile rather than a role.
|
|
INSTANCE_PROFILE_RE = re.compile(r"\bARN\) of the IAM instance profile\b")
|
|
# The sample's section on the roles a capacity provider takes, up to its next section.
|
|
ROLES_SECTION_RE = re.compile(r"^## The two roles\n(?P<section>.*?)(?=^## |\Z)", re.M | re.S)
|
|
# The sample's sentence on the principal its roles trust.
|
|
BOTH_TRUST_RE = re.compile(r"Both must trust `(?P<service>[a-z0-9.-]+\.amazonaws\.com)`\.")
|
|
# A trust policy in a code block, written out or as a CLI argument.
|
|
TRUST_RE = re.compile(r'"Principal"\s*:\s*\{\s*"Service"')
|
|
SERVICE_PRINCIPAL_RE = re.compile(r'"Principal"\s*:\s*\{\s*"Service"\s*:\s*"(?P<service>[a-z0-9.-]+\.amazonaws\.com)"')
|
|
|
|
|
|
def text(fragment: str) -> str:
|
|
"""A fragment of a page as text, spaces collapsed."""
|
|
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip()
|
|
|
|
|
|
def code(fragment: str) -> str:
|
|
"""A code block as the text it shows, the page's copy button left out."""
|
|
fragment = re.sub(r'<div class="code-btn-container">.*?</div></div>', "", fragment, flags=re.S)
|
|
return html.unescape(re.sub(r"<[^>]+>", "", re.sub(r"<!--.*?-->", "", fragment, flags=re.S))).strip()
|
|
|
|
|
|
def api_page(member: dict) -> str:
|
|
"""The API reference page describing the member's type."""
|
|
return API_REFERENCE + "API_" + member["type"] + ".html"
|
|
|
|
|
|
def anchor(member: dict) -> str:
|
|
"""The id of the member's entry on its API reference page."""
|
|
return f"bedrockagentcorecontrol-Type-{member['type']}-{member['member']}"
|
|
|
|
|
|
def read_description(page: str, member: dict) -> str:
|
|
"""The member's description on its API reference page, as text."""
|
|
match = re.search(r'id="' + re.escape(anchor(member)) + r'"[^>]*>(?P<entry>.*?)</dd>', page, re.S)
|
|
if match is None:
|
|
raise ValueError(f"{api_page(member)} has no entry {anchor(member)}: its layout changed")
|
|
entry = match.group("entry")
|
|
described = re.search(r"<dd[^>]*>(?P<body>.*?)<p>\s*Type:", entry + "<p>Type:", re.S)
|
|
return text(described.group("body") if described else entry)
|
|
|
|
|
|
def snake(name: str) -> str:
|
|
"""An operation's name as a boto3 client method, CreateCapacityProvider as create_capacity_provider."""
|
|
return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
|
|
|
|
|
|
def table_cell(section: str, row: str, column: str) -> str:
|
|
"""The cell of a Markdown table in the section at the row and column whose headings are given; empty when the
|
|
table has no such cell."""
|
|
rows = [[cell.strip() for cell in line.strip().strip("|").split("|")]
|
|
for line in section.splitlines() if line.lstrip().startswith("|")]
|
|
if not rows or column not in rows[0]:
|
|
return ""
|
|
index = rows[0].index(column)
|
|
for cells in rows[1:]:
|
|
if cells and cells[0] == row and index < len(cells):
|
|
return cells[index]
|
|
return ""
|
|
|
|
|
|
def read_operator_role(page: str, member: dict) -> dict:
|
|
"""What the sample's section on a capacity provider's roles says of the operator role: the call its table says it
|
|
is passed to, which must name the member's type, and the principal its sentence and trust policy say it trusts."""
|
|
match = ROLES_SECTION_RE.search(page)
|
|
if match is None:
|
|
raise ValueError(f"{SAMPLE} has no section \"The two roles\": its layout changed")
|
|
section = match.group("section")
|
|
passed_in = table_cell(section, "Passed to", "Operator role")
|
|
container = member["type"][0].lower() + member["type"][1:]
|
|
if f"`{snake(member['operation'])}({container}=" not in passed_in:
|
|
raise ValueError(f"{SAMPLE} no longer says the operator role is passed in {member['operation']}'s "
|
|
f"{container}: {passed_in!r}")
|
|
sentence = BOTH_TRUST_RE.search(section)
|
|
principals = {found.group("service") for found in SERVICE_PRINCIPAL_RE.finditer(section)}
|
|
if sentence is None or principals != {sentence.group("service")}:
|
|
raise ValueError(f"{SAMPLE} gives neither what the operator role trusts nor a trust policy naming it alone")
|
|
return {"rolePage": SAMPLE, "section": "The two roles", "passedIn": passed_in,
|
|
"roleText": sentence.group(0), "trustedBy": sorted(principals)}
|
|
|
|
|
|
def read_trusted_role(page: str, url: str) -> dict:
|
|
"""The title of a role's page and the service principals its trust policies name."""
|
|
title = re.search(r"<title>(?P<title>.*?)</title>", page, re.S)
|
|
services: set[str] = set()
|
|
for block in re.findall(r"<pre[^>]*>(.*?)</pre>", page, re.S):
|
|
shown = code(block)
|
|
if not TRUST_RE.search(shown):
|
|
continue
|
|
policy = shown[shown.index("{"):shown.rindex("}") + 1]
|
|
for statement in json.loads(policy)["Statement"]:
|
|
service = statement["Principal"]["Service"]
|
|
services.update([service] if isinstance(service, str) else service)
|
|
if title is None or not services:
|
|
raise ValueError(f"{url} gives no trust policy naming a service: its layout changed")
|
|
return {"rolePage": url, "title": text(title.group("title")), "trustedBy": sorted(services)}
|
|
|
|
|
|
def build(fetch) -> dict:
|
|
members = []
|
|
role_members = []
|
|
pages = []
|
|
for member in MEMBERS:
|
|
description = read_description(fetch(api_page(member)), member)
|
|
entry = {"type": member["type"], "member": member["member"], "description": description}
|
|
if member["rolePage"] == SAMPLE:
|
|
entry.update(read_operator_role(fetch(SAMPLE), member))
|
|
else:
|
|
entry.update(read_trusted_role(fetch(member["rolePage"]), member["rolePage"]))
|
|
if INSTANCE_PROFILE_RE.search(description):
|
|
entry["instanceProfile"] = True
|
|
role_members.append({"model": MODEL, "type": member["type"], "member": member["member"],
|
|
"page": api_page(member), "description": description})
|
|
members.append(entry)
|
|
pages += [api_page(member), member["rolePage"]]
|
|
return {
|
|
"_source": {
|
|
"pages": list(dict.fromkeys(pages)),
|
|
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
|
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
"note": "Each member's description on its API reference page, copied as it stands; for the operator role, "
|
|
"the AgentCore capacity provider sample's table cell naming the call it is passed in and its "
|
|
"sentence naming the principal the role trusts, with the trust policy it shows; for an instance "
|
|
"profile, the title of the IAM user guide's page on roles for EC2 instances and the service "
|
|
"principals its trust policies name. A member naming an instance profile is also listed in "
|
|
"roleMembers, since the passed-roles rule reads a member as a role by its name.",
|
|
},
|
|
"members": members,
|
|
"roleMembers": role_members,
|
|
}
|
|
|
|
|
|
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 fetch_all(fetch=fetch_url) -> tuple:
|
|
"""The pages, each fetched once, as a reader of them."""
|
|
cache: dict[str, str] = {}
|
|
|
|
def cached(url: str) -> str:
|
|
if url not in cache:
|
|
cache[url] = fetch(url)
|
|
return cache[url]
|
|
|
|
build(cached)
|
|
return (cache,)
|
|
|
|
|
|
def stale(vendored: dict, pages: dict[str, str]) -> bool:
|
|
"""Whether the pages now give something other than the vendored file, its date aside."""
|
|
built = build(lambda url: pages[url])
|
|
return vendored.get("members") != built["members"] or vendored.get("roleMembers") != built["roleMembers"]
|
|
|
|
|
|
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,) = fetch_all(fetch)
|
|
except OSError as e:
|
|
print(f"error: could not read the Bedrock AgentCore documentation ({e})", file=sys.stderr)
|
|
return 2
|
|
if args.verify:
|
|
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
|
|
if stale(vendored, pages):
|
|
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the AgentCore API reference, its "
|
|
f"capacity provider sample and the IAM user guide do: run "
|
|
f"tools/aws/fetch_bedrock_agentcore_roles.py and then make iam-passed-roles-sync", file=sys.stderr)
|
|
return 1
|
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the AgentCore API reference, its capacity provider sample "
|
|
f"and the IAM user guide")
|
|
return 0
|
|
built = build(lambda url: pages[url])
|
|
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
|
|
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['members'])} members' roles)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|