mirror of
https://github.com/floci-io/floci.git
synced 2026-12-04 02:28:08 -05:00
CloudWatch's OTel enrichment reads resource tags through ObservabilityAdmin's resource tags for telemetry feature, which has to be running before StartOTelEnrichment enables tag enrichment. Add the ObservabilityAdmin service with StartTelemetryEnrichment, StopTelemetryEnrichment and GetTelemetryEnrichmentStatus, one feature per account and Region. Starting the feature has Resource Explorer create a LOCAL index when the Region has none and a managed view that includes tags, as the CloudWatch user guide describes. GetManagedView and ListManagedViews now answer the views Floci's services create. A status read before the first start is the modeled ResourceNotFoundException, and a stop of a stopped or never-started feature changes nothing. The passed-roles table now reads ObservabilityAdmin. A vendored source, written from the CloudWatch user guide and the Observability Admin API reference, gives a dataset integration's role to CloudWatch Logs, whose trust policy it names, and gives where a telemetry pipeline's YAML configuration names its roles: its source's and its Secrets Manager extension's, each going to the service its source type's role trusts, and to CloudWatch Logs as well with a lookup processor or a conditional route. Part of #7030.
350 lines
19 KiB
Python
350 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Vendor where a CloudWatch Observability Admin request names the roles it passes, and the service each role is for,
|
|
into tools/aws/sources/observabilityadmin-roles.json, a source of the passed-roles table.
|
|
|
|
AWS's Service Reference passes the roles of CreateDatasetIntegration and UpdateDatasetIntegration to
|
|
`logs.amazonaws.com` and `test.logs.amazonaws.com`, and those of CreateTelemetryPipeline and UpdateTelemetryPipeline
|
|
to `logs.amazonaws.com` and `telemetry-pipelines.observabilityadmin.amazonaws.com`, without saying which role goes
|
|
where. botocore does not say it as data either, and a telemetry pipeline's request names no role in a member of its
|
|
own: its roles are in the pipeline configuration it carries as text. The CloudWatch user guide and the Observability
|
|
Admin API reference say both.
|
|
|
|
- A dataset integration's `RoleArn` is its execution role, which the guide's page on confused deputy prevention says
|
|
CloudWatch Logs assumes, giving the trust policy the role needs:
|
|
|
|
Dataset integration reads your CloudWatch Logs data through a role that CloudWatch Logs assumes on your behalf.
|
|
https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/omni-cross-service-confused-deputy-prevention.html
|
|
|
|
- A telemetry pipeline's `Configuration` holds its configuration in its `Body` ("The configuration is specified in
|
|
YAML format"), and the guide's IAM page for pipelines says "The IAM principal that calls CreateTelemetryPipeline needs
|
|
iam:PassRole permission for any roles referenced in the pipeline configuration":
|
|
|
|
https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/pipeline-iam-reference.html
|
|
|
|
The guide's pages of a source and of the Secrets Manager extension each list the parameters they take, the role's
|
|
among them ("aws.sts_role_arn: The ARN of the IAM role to assume for CloudWatch Logs interception";
|
|
"aws.secrets.<secret-name>.sts_role_arn: The ARN of the IAM role to assume for accessing the AWS Secrets Manager
|
|
secret"), each under the section of the configuration its example opens. The IAM page's first table gives each use
|
|
case's source type in the pipeline configuration and the sections of the page it needs, among them the one of its
|
|
source role's policies, whose trust policy names the service the role is for, or which says its setup "is identical
|
|
to" another's. A note under its second table says "For third-party pipelines that use a lookup processor or
|
|
conditional routing, also allow logs.amazonaws.com in iam:PassedToService", the processors page naming the lookup
|
|
processor and the sinks page the expression on "each conditional route".
|
|
|
|
This script copies each of those as it stands, with what the page's markup gives of it. Nothing in the output is
|
|
written by hand; regen_iam_passed_roles.py reads it to choose the service of a dataset integration's role and to give
|
|
PassedRoles where a pipeline configuration names its roles and the services each goes to.
|
|
|
|
Run from anywhere in the repo:
|
|
python3 tools/aws/fetch_observabilityadmin_roles.py # rewrite the vendored file from the pages
|
|
python3 tools/aws/fetch_observabilityadmin_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.parse
|
|
import urllib.request
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
API_REFERENCE = "https://docs.aws.amazon.com/cloudwatch/latest/observabilityadmin/"
|
|
GUIDE = "https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/"
|
|
CONFUSED_DEPUTY = GUIDE + "omni-cross-service-confused-deputy-prevention.html"
|
|
PIPELINE_IAM = GUIDE + "pipeline-iam-reference.html"
|
|
PROCESSORS = GUIDE + "transformation-processors.html"
|
|
SINKS = GUIDE + "pipeline-sinks.html"
|
|
CONFIGURATION = API_REFERENCE + "API_TelemetryPipelineConfiguration.html"
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/observabilityadmin-roles.json"
|
|
|
|
# The members that name a role, each with the id of the section of the confused deputy page about its role.
|
|
MEMBERS = (
|
|
{"operation": "CreateDatasetIntegration", "member": "RoleArn",
|
|
"section": "omni-cross-service-confused-deputy-prevention-dataset-integration-execution-role"},
|
|
{"operation": "UpdateDatasetIntegration", "member": "RoleArn",
|
|
"section": "omni-cross-service-confused-deputy-prevention-dataset-integration-execution-role"},
|
|
)
|
|
# The operations whose request carries a pipeline configuration, in the member its API reference page describes.
|
|
PIPELINES = (
|
|
{"operation": "CreateTelemetryPipeline", "member": "Configuration"},
|
|
{"operation": "UpdateTelemetryPipeline", "member": "Configuration"},
|
|
)
|
|
# The member of the configuration's type holding the configuration itself.
|
|
CONFIGURATION_MEMBER = "Body"
|
|
# The pages listing the parameters of a section of a pipeline configuration, the role's among them: the CloudWatch
|
|
# Logs source's, the custom Amazon S3 source's and the Secrets Manager extension's.
|
|
PARAMETER_PAGES = (
|
|
GUIDE + "aws-service-logs-from-cwl.html",
|
|
GUIDE + "ingestion-custom-data-sources.html",
|
|
GUIDE + "pipeline-extensions.html",
|
|
)
|
|
# The section of the IAM page holding the policies of each source role, and the id of the processors page's section
|
|
# on the lookup processor and of the sinks page's on routing.
|
|
SOURCE_ROLE_SECTION = "source-role-policies"
|
|
LOOKUP_SECTION = "lookup-processor"
|
|
ROUTING_SECTION = "cloudwatch-logs-sink-routing"
|
|
|
|
# A parameter naming a role, by its description.
|
|
ROLE_PARAMETER_RE = re.compile(r"^The ARN of the IAM role to assume\b")
|
|
# The services a trust policy names.
|
|
TRUST_RE = re.compile(r'"Principal"\s*:\s*\{\s*"Service"\s*:\s*"(?P<service>[a-z0-9.-]+\.amazonaws\.com)"')
|
|
# The sentence of the configuration's type saying the format its body is in.
|
|
FORMAT_RE = re.compile(r"The configuration is specified in YAML format\b[^.]*\.")
|
|
# The sentence of the IAM page naming a service its roles also go to, and for which pipelines.
|
|
ALSO_RE = re.compile(r"For third-party pipelines that use a lookup processor or conditional routing, also allow "
|
|
r"(?P<service>[a-z0-9.-]+\.amazonaws\.com) in iam:PassedToService\s*\.")
|
|
# The lookup processor's key, as its configuration opens: `processor: - lookup:`.
|
|
PROCESSOR_RE = re.compile(r"^\s*processor:\s*-\s*(?P<processor>[a-z_]+):")
|
|
# The key a conditional route sets.
|
|
ROUTE_RE = re.compile(r"Define an? (?P<key>[a-z_]+) expression on each conditional route\b")
|
|
# The sentence of a source role's section saying its setup is another's.
|
|
IDENTICAL_RE = re.compile(r'The IAM setup is identical to <a href="#(?P<section>[^"]+)"')
|
|
|
|
|
|
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 api_page(operation: str) -> str:
|
|
"""The API reference page of an operation."""
|
|
return API_REFERENCE + "API_" + operation + ".html"
|
|
|
|
|
|
def entry(page: str, url: str, anchor: str) -> str:
|
|
"""The description of the API reference entry whose term has the id `anchor`, as text, without its type."""
|
|
match = re.search(r'id="' + re.escape(anchor) + r'"[^>]*>.*?</dt>\s*<dd[^>]*>(?P<body>.*?)</dd>', page, re.S)
|
|
if match is None:
|
|
raise ValueError(f"{url} has no entry {anchor}: its layout changed")
|
|
described = re.search(r"(?P<body>.*?)<p>\s*Type:", match.group("body") + "<p>Type:", re.S)
|
|
return text(described.group("body"))
|
|
|
|
|
|
def section(page: str, url: str, anchor: str) -> str:
|
|
"""The markup of the section whose heading has the id `anchor`, up to the next heading of its level or above."""
|
|
match = re.search(r'<h(?P<level>[1-6])[^>]*\bid="' + re.escape(anchor) + r'"[^>]*>', page)
|
|
if match is None:
|
|
raise ValueError(f"{url} has no section {anchor}: its layout changed")
|
|
level = int(match.group("level"))
|
|
end = re.compile(r"<h[1-%d][\s>]" % level).search(page, match.end())
|
|
return page[match.end():end.start() if end else len(page)]
|
|
|
|
|
|
def heading(page: str, anchor: str) -> str:
|
|
match = re.search(r'<h[1-6][^>]*\bid="' + re.escape(anchor) + r'"[^>]*>(?P<title>.*?)</h[1-6]>', page, re.S)
|
|
return text(match.group("title")) if match else anchor
|
|
|
|
|
|
def subsections(page: str, url: str, anchor: str) -> list[str]:
|
|
"""The ids of the headings one level below the section whose heading has the id `anchor`."""
|
|
body = section(page, url, anchor)
|
|
level = int(re.search(r'<h(?P<level>[1-6])[^>]*\bid="' + re.escape(anchor) + r'"', page).group("level"))
|
|
return re.findall(r'<h%d[^>]*\bid="(?P<id>[^"]+)"' % (level + 1), body)
|
|
|
|
|
|
def trusted_by(page: str, url: str, anchor: str, seen: tuple[str, ...] = ()) -> tuple[list[str], str | None]:
|
|
"""The services the trust policies of a section name, or those of the section it says its setup is identical to,
|
|
with that section's id."""
|
|
body = section(page, url, anchor)
|
|
services = sorted({match.group("service") for code in re.findall(r"<pre[^>]*>(.*?)</pre>", body, re.S)
|
|
if "sts:AssumeRole" in text(code) for match in TRUST_RE.finditer(text(code))})
|
|
if services:
|
|
return services, None
|
|
identical = IDENTICAL_RE.search(body)
|
|
if identical is None or identical.group("section") in seen:
|
|
raise ValueError(f"{url}'s section {anchor} names no trust policy's service and no section its setup is "
|
|
f"identical to: its layout changed")
|
|
return trusted_by(page, url, identical.group("section"), seen + (anchor,))[0], identical.group("section")
|
|
|
|
|
|
def read_member(member: dict, fetch) -> dict:
|
|
"""The member's description on its API reference page, and what the confused deputy page's section of its role
|
|
says: its text, and the service the role's trust policy names."""
|
|
url = api_page(member["operation"])
|
|
description = entry(fetch(url), url, f"cwoa-{member['operation']}-request-{member['member']}")
|
|
page = fetch(CONFUSED_DEPUTY)
|
|
body = section(page, CONFUSED_DEPUTY, member["section"])
|
|
services, _ = trusted_by(page, CONFUSED_DEPUTY, member["section"])
|
|
paragraphs = [text(paragraph) for paragraph in re.findall(r"<p>(.*?)</p>", body, re.S)]
|
|
return {"operation": member["operation"], "member": member["member"], "description": description,
|
|
"rolePage": CONFUSED_DEPUTY, "section": heading(page, member["section"]),
|
|
"roleText": " ".join(paragraphs), "trustedBy": services}
|
|
|
|
|
|
def read_pipeline(pipeline: dict, fetch) -> dict:
|
|
"""The description of the member of the operation's request carrying its pipeline configuration."""
|
|
url = api_page(pipeline["operation"])
|
|
return {**pipeline, "page": url,
|
|
"description": entry(fetch(url), url, f"cwoa-{pipeline['operation']}-request-{pipeline['member']}")}
|
|
|
|
|
|
def read_configuration(fetch) -> dict:
|
|
"""What the configuration's type says of the member holding the configuration, and the format it is in."""
|
|
page = fetch(CONFIGURATION)
|
|
formatted = FORMAT_RE.search(text(page))
|
|
if formatted is None:
|
|
raise ValueError(f"{CONFIGURATION} no longer says the format of a pipeline configuration: its layout changed")
|
|
return {"type": "TelemetryPipelineConfiguration", "member": CONFIGURATION_MEMBER, "page": CONFIGURATION,
|
|
"description": entry(page, CONFIGURATION, f"cwoa-Type-TelemetryPipelineConfiguration-{CONFIGURATION_MEMBER}"),
|
|
"format": formatted.group(0)}
|
|
|
|
|
|
def read_role_parameters(url: str, page: str) -> list[dict]:
|
|
"""The parameters a page lists whose description says they name a role, each under the section of the pipeline
|
|
configuration the page's first example opens."""
|
|
example = re.search(r"<pre[^>]*>(?P<code>.*?)</pre>", page, re.S)
|
|
opening = re.match(r"\s*(?P<section>[a-z_]+):", text(example.group("code"))) if example else None
|
|
if opening is None:
|
|
raise ValueError(f"{url} has no example opening a section of a pipeline configuration: its layout changed")
|
|
found = []
|
|
for term, description in re.findall(r"<dt>(.*?)</dt>\s*<dd>(.*?)</dd>", page, re.S):
|
|
name = re.search(r'<code class="code">(?P<name>[^<]+)</code>', term)
|
|
if name and ROLE_PARAMETER_RE.match(text(description)):
|
|
found.append({"page": url, "under": opening.group("section"), "parameter": html.unescape(name.group("name")),
|
|
"description": text(description)})
|
|
if not found:
|
|
raise ValueError(f"{url} lists no parameter naming a role: its layout changed")
|
|
return found
|
|
|
|
|
|
def read_sources(fetch) -> list[dict]:
|
|
"""Each use case of the IAM page's first table: its source types, whether it stands for others it does not name
|
|
("and so on"), and, by the section of its source role's policies, the services that role is for."""
|
|
page = fetch(PIPELINE_IAM)
|
|
table = re.search(r"<table[^>]*>(?P<rows>.*?)</table>", page, re.S)
|
|
if table is None or "Source type in pipeline configuration" not in text(table.group("rows")):
|
|
raise ValueError(f"{PIPELINE_IAM} has no table of source types: its layout changed")
|
|
role_sections = set(subsections(page, PIPELINE_IAM, SOURCE_ROLE_SECTION))
|
|
sources = []
|
|
for row in re.findall(r"<tr>(.*?)</tr>", table.group("rows"), re.S):
|
|
cells = re.findall(r"<td[^>]*>(.*?)</td>", row, re.S)
|
|
if not cells:
|
|
continue
|
|
if len(cells) != 4:
|
|
raise ValueError(f"{PIPELINE_IAM}'s table of source types has a row of {len(cells)} cells: its layout "
|
|
f"changed")
|
|
types = [html.unescape(code) for code in re.findall(r'<code class="code">([^<]+)</code>', cells[2])]
|
|
found = {"useCase": text(cells[0]), "sourceTypes": types}
|
|
if text(cells[2]).endswith("and so on."):
|
|
found["andSoOn"] = True
|
|
linked = [anchor for anchor in re.findall(r'<a href="#([^"]+)"', cells[3]) if anchor in role_sections]
|
|
if len(linked) > 1:
|
|
raise ValueError(f"{PIPELINE_IAM} gives {found['useCase']} {len(linked)} source role sections: its "
|
|
f"layout changed")
|
|
if linked:
|
|
services, identical = trusted_by(page, PIPELINE_IAM, linked[0])
|
|
found["section"] = heading(page, linked[0])
|
|
if identical is not None:
|
|
found["identicalTo"] = heading(page, identical)
|
|
found["trustedBy"] = services
|
|
sources.append(found)
|
|
return sources
|
|
|
|
|
|
def read_also(fetch) -> dict:
|
|
"""The service the IAM page says a third-party pipeline's roles also go to with a lookup processor or conditional
|
|
routing, the key of the lookup processor and the key a conditional route sets."""
|
|
also = ALSO_RE.search(text(fetch(PIPELINE_IAM)))
|
|
if also is None:
|
|
raise ValueError(f"{PIPELINE_IAM} no longer says what else a third-party pipeline's roles go to: its layout "
|
|
f"changed")
|
|
lookup = section(fetch(PROCESSORS), PROCESSORS, LOOKUP_SECTION)
|
|
example = re.search(r"<pre[^>]*>(?P<code>.*?)</pre>", lookup, re.S)
|
|
processor = PROCESSOR_RE.match(text(example.group("code"))) if example else None
|
|
route = ROUTE_RE.search(text(section(fetch(SINKS), SINKS, ROUTING_SECTION)))
|
|
if processor is None or route is None:
|
|
raise ValueError(f"{PROCESSORS} or {SINKS} no longer names the lookup processor or a conditional route's "
|
|
f"expression: its layout changed")
|
|
return {"page": PIPELINE_IAM, "text": also.group(0), "passedToService": [also.group("service")],
|
|
"processor": processor.group("processor"), "processorPage": PROCESSORS,
|
|
"routeKey": route.group("key"), "routePage": SINKS, "routeText": route.group(0)}
|
|
|
|
|
|
def build(fetch) -> dict:
|
|
parameters = []
|
|
for url in PARAMETER_PAGES:
|
|
parameters += read_role_parameters(url, fetch(url))
|
|
members = [read_member(member, fetch) for member in MEMBERS]
|
|
pipelines = [read_pipeline(pipeline, fetch) for pipeline in PIPELINES]
|
|
pages = [api_page(member["operation"]) for member in MEMBERS] + [CONFUSED_DEPUTY]
|
|
pages += [pipeline["page"] for pipeline in pipelines] + [CONFIGURATION, *PARAMETER_PAGES, PIPELINE_IAM,
|
|
PROCESSORS, SINKS]
|
|
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, with the section of "
|
|
"the confused deputy page on its role and the service that role's trust policy names; the "
|
|
"members carrying a pipeline configuration, the format it is in, the parameters of its sections "
|
|
"that name a role, the source types of the IAM page's use cases with the services their source "
|
|
"roles' trust policies name, and the service a lookup processor or conditional routing also "
|
|
"passes those roles to.",
|
|
},
|
|
"members": members,
|
|
"pipelines": pipelines,
|
|
"configuration": read_configuration(fetch),
|
|
"roleParameters": parameters,
|
|
"sources": read_sources(fetch),
|
|
"also": read_also(fetch),
|
|
}
|
|
|
|
|
|
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 any(vendored.get(key) != built[key] for key in built 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,) = fetch_all(fetch)
|
|
except OSError as e:
|
|
print(f"error: could not read the CloudWatch 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 CloudWatch user guide and the "
|
|
f"Observability Admin API reference do: run tools/aws/fetch_observabilityadmin_roles.py and then "
|
|
f"make iam-passed-roles-sync", file=sys.stderr)
|
|
return 1
|
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the CloudWatch user guide and the Observability Admin API "
|
|
f"reference")
|
|
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, "
|
|
f"{len(built['pipelines'])} pipeline configurations)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|