diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 82f93eab..750c2ef3 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,6 +1,6 @@ # https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file # -# Workflow actions, the Python tooling in scripts/requirements.txt, and the Caddy image the unit suite adapts the Caddyfile with are the ecosystems tracked here. +# Workflow actions, the Python tooling in scripts/requirements.txt, and the container images under checks/ are the ecosystems tracked here. # The theme is vendored rather than pulled by a manager. # Both branches are targeted so each stays current independently of the release cadence. version: 2 @@ -48,7 +48,9 @@ updates: - package-ecosystem: "docker" target-branch: "main" - directory: "/checks/caddy" + directories: + - "/checks/caddy" + - "/checks/browser" schedule: interval: "daily" groups: @@ -58,7 +60,9 @@ updates: - package-ecosystem: "docker" target-branch: "develop" - directory: "/checks/caddy" + directories: + - "/checks/caddy" + - "/checks/browser" schedule: interval: "daily" groups: diff --git a/CONTENT.md b/CONTENT.md index 02c4d456..1db8eb19 100644 --- a/CONTENT.md +++ b/CONTENT.md @@ -192,7 +192,7 @@ This is the reason this file exists, so it is worth stating plainly. | --- | --- | | `hugo --gc --minify --panicOnWarning` | yes, it must build | | [`checks/check-url-parity.py`][parity] | yes, for URLs, asset references, and the orphan count | -| [`checks/check-csp-scripts.py`][csp-scripts] | yes, for a script, inline handler, or `javascript:` URL a post's raw HTML adds | +| [`checks/check-csp-scripts.py`][csp-scripts] | yes, for a script, inline handler, `javascript:` URL, frame, media file, or object a post's raw HTML adds | | `checks/check-live-urls.sh` | yes, against a running server | | markdownlint | no, `content/.markdownlint-cli2.jsonc` ignores the tree | | CSpell | no, `cspell.json` ignores the tree | diff --git a/OPERATIONS.md b/OPERATIONS.md index 1ab033f6..d225c6b5 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -94,7 +94,22 @@ Expect a `PASS` naming the number of URLs honored. That is the three lists' comb A documentation-only or workflow-only change does not need this. A change to the four paths above does, because for those CI's green is not evidence. -**The Python gates run per directory, the way CI runs them.** The validator gates [`checks/`](./checks/) and [`scripts/`](./scripts/), the two directories the workflows declare in its `python-directories` input, with ruff, mypy, and a test suite under coverage. `checks/` is standard library only, so its tools run through `uvx` and its suite runs under `unittest`. `scripts/` installs Pillow, pytest, and pytest-cov from its `requirements.txt`, which holds the one Pillow pin, and runs its suite under pytest. [`capture/`](./capture/) is not declared, because it is one-shot WordPress migration tooling that has already run and owes no test suite, so the validator's warning about its files is expected. +**A change to a `Content-Security-Policy` in `security-headers.txt` is also tried in a browser**, on the local staging mirror, before its pull request opens. So is a theme or `layouts/` change that adds a style, a font, a fetch, or a script. [`checks/check-csp-browser.py`](./checks/check-csp-browser.py) loads every page of `golden-urls.txt` plus `/search/` in headless Chromium. It scrolls each page to its end, clicks its code-copy buttons, and types a search query. It reads each `securitypolicyviolation` event from the page and from each frame in it. It reports them by directive and blocked origin, with the first page each occurred on. The event fires for an enforcing policy and a `Content-Security-Policy-Report-Only` one alike, so a trial can run Report-Only first: + +```sh +set -e +set -a; . ~/.secrets/blog.local.staging.env; set +a +checks/check-csp-browser.py "$SITE_BASE_URL" +``` + +- **It needs Docker and `uv` on the host, and no browser.** Chromium runs in the Playwright image [`checks/browser/Dockerfile`](./checks/browser/Dockerfile) pins, where Dependabot moves it. `uv` installs the Playwright package inside it at the image tag's own version, so the two cannot drift. Its cache is `UV_CACHE_DIR` where that is set, or a directory under the system temporary root. +- **The container shares the host network**, so it reaches a local mirror by the name the host resolves. +- **A violation fails the run unless [`checks/csp-browser-allow.txt`](./checks/csp-browser-allow.txt) lists it.** Each line is a directive, a blocked origin, and the reason, tab separated. A blocked scheme is written as the browser reports it, such as `data` with no colon. An entry that nothing matched fails a run over the default list, so an entry goes when its cause does. `--urls` takes another list, and such a partial run leaves unused entries alone. +- **A page that does not answer `200` fails the run**, since a trial over error pages proves nothing. +- **It runs only against the local mirrors.** VPS staging sits behind the auth gate, which the check does not present. A full run is hundreds of pages. Production takes only a handful of probes per pass, since a burst there can get the reviewing network banned. +- **It runs by hand rather than in the release.** It needs Docker, a browser image, and a running server, and neither the release build nor the unit suite has all three. + +**The Python gates run per directory, the way CI runs them.** The validator gates [`checks/`](./checks/) and [`scripts/`](./scripts/), the two directories the workflows declare in its `python-directories` input, with ruff, mypy, and a test suite under coverage. `checks/` is standard library only, so its tools run through `uvx` and its suite runs under `unittest`. The browser trial's container half is the one exception. `scripts/` installs Pillow, pytest, and pytest-cov from its `requirements.txt`, which holds the one Pillow pin, and runs its suite under pytest. [`capture/`](./capture/) is not declared, because it is one-shot WordPress migration tooling that has already run and owes no test suite. The validator's warning about its files is therefore expected. ```sh set -e diff --git a/README.md b/README.md index 4e017191..682ca5e9 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,7 @@ For a defect in the site or the tooling, such as a broken link, a missing redire The required tools and their install commands are listed in [deploy/README.md][deploy-readme]. Hugo must be the extended build. -Build the site and verify it against the URL contract and the blog's script policy: +Build the site and verify it against the URL contract and the blog's Content-Security-Policy: ```sh hugo --gc --minify --panicOnWarning diff --git a/checks/README.md b/checks/README.md index cb3d98ab..0dcd0663 100644 --- a/checks/README.md +++ b/checks/README.md @@ -6,7 +6,8 @@ This README covers the URL contract alone. The other checks in this directory ea | Check | Fails when | | --- | --- | -| [`check-csp-scripts.py`][check-csp-scripts] | the scripts the built site runs and the blog's `script-src` disagree | +| [`check-csp-browser.py`][check-csp-browser] | a page on a running mirror makes the browser block something that `csp-browser-allow.txt` does not list | +| [`check-csp-scripts.py`][check-csp-scripts] | the scripts, frames, media, or objects the built site loads and the blog's policy disagree | | [`check-env-docs.py`][check-env-docs] | a configuration value is declared without a description in `ENVIRONMENT.md`, or described there and declared nowhere | | [`check-github-env.py`][check-github-env] | the variables and secrets GitHub holds differ from the ones `ENVIRONMENT.md` lists | | [`check-media-metadata.py`][check-media-metadata] | carried media is not in a form the gate can vouch for | @@ -188,6 +189,7 @@ Three traps in that adjudication, each of which produced a wrong answer first an [capture-build-redirects]: ../capture/build-redirects.py [caddy-dockerfile]: ./caddy/Dockerfile [capture-readme]: ../capture/README.md +[check-csp-browser]: ./check-csp-browser.py [check-csp-scripts]: ./check-csp-scripts.py [check-env-docs]: ./check-env-docs.py [check-github-env]: ./check-github-env.py diff --git a/checks/browser/Dockerfile b/checks/browser/Dockerfile new file mode 100644 index 00000000..8bd10d2a --- /dev/null +++ b/checks/browser/Dockerfile @@ -0,0 +1 @@ +FROM mcr.microsoft.com/playwright/python:v1.55.0-noble@sha256:640d578aae63cfb632461d1b0aecb01414e4e020864ac3dd45a868dc0eff3078 diff --git a/checks/check-csp-browser.py b/checks/check-csp-browser.py new file mode 100755 index 00000000..cc3fb038 --- /dev/null +++ b/checks/check-csp-browser.py @@ -0,0 +1,287 @@ +#!/usr/bin/env python3 +"""Load a running site in headless Chromium and report what its Content-Security-Policy blocks. + +`check-csp-scripts.py` proves the built scripts match the policy's hashes. It cannot see what a +browser blocks at run time: a style, a font, a fetch, an image, or a script a proxy injects. This +check loads each page in a URL list against a mirror. It records every `securitypolicyviolation` +event in the page and in each frame it holds, as it fires. The event fires for an enforcing policy +and a Report-Only one alike. Each page is scrolled to its end so lazy images load, and its +code-copy buttons are clicked. The search page also gets a typed query, so the index fetch and the +results run. + +The browser runs in the Playwright image `browser/Dockerfile` pins, where Dependabot moves it. The +Playwright package is installed at the image tag's own version, so the two never disagree. The +host needs Docker and `uv`, and nothing else. + +A violation fails the run unless `csp-browser-allow.txt` lists its directive and blocked origin. +On a run over the default list, an entry nothing matched fails it too, so the list cannot outlive +what it excuses. A page that does not answer `200` fails the run, since a trial over error pages +proves nothing. +""" + +import argparse +import json +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile +from urllib.parse import urljoin, urlsplit + +CHECKS = pathlib.Path(__file__).resolve().parent +DOCKERFILE = CHECKS / "browser" / "Dockerfile" +ALLOW = CHECKS / "csp-browser-allow.txt" +URLS = CHECKS / "golden-urls.txt" +SEARCH_PATH = "/search/" +SEARCH_QUERY = "raid" +IMAGE = re.compile(r"^FROM\s+(\S+:v(\d+\.\d+\.\d+)-\S+)\s*$", re.MULTILINE) + + +def pinned_image(dockerfile_text): + """The image reference the Dockerfile pins and the Playwright version its tag names.""" + found = IMAGE.search(dockerfile_text) + if found is None: + raise ValueError("no FROM line naming a vX.Y.Z Playwright tag") + return found.group(1), found.group(2) + + +def read_paths(texts): + """The site paths the lists name, in order, once each, the search page always among them.""" + paths = [] + for text in texts: + for line in text.splitlines(): + path = line.strip() + if path and path not in paths: + paths.append(path) + if SEARCH_PATH not in paths: + paths.append(SEARCH_PATH) + return paths + + +def read_allow(text): + """The allow list as (directive, origin) pairs, each line also carrying its reason.""" + entries = [] + for number, line in enumerate(text.splitlines(), 1): + if not line.strip(): + continue + fields = line.split("\t") + if len(fields) != 3 or not all(field.strip() for field in fields): + raise ValueError( + f"line {number}: want directive, origin, and reason, tab separated" + ) + entries.append((fields[0].strip(), fields[1].strip())) + return entries + + +def blocked_origin(blocked): + """A blocked URL reduced to its origin, or the keyword the browser reports in its place.""" + parts = urlsplit(blocked) + if parts.scheme in ("http", "https") and parts.netloc: + return f"{parts.scheme}://{parts.netloc}" + return blocked + + +def summarize(records, allow, complete): + """Fold the probe's records into findings, allowed counts, and pages loaded. + + An allow entry nothing matched is a finding only where the run covered the whole default list. + """ + violations = {} + failures = [] + loaded = 0 + for record in records: + if "status" in record: + loaded += 1 + if record["status"] != 200: + failures.append(f"{record['page']} answered {record['status']}") + continue + if "error" in record: + failures.append(f"{record['page']}: {record['error']}") + continue + key = (record["directive"], blocked_origin(record["blocked"])) + entry = violations.setdefault( + key, {"count": 0, "page": record["page"], "disposition": set()} + ) + entry["count"] += 1 + entry["disposition"].add(record["disposition"]) + allowed = {key: violations.pop(key)["count"] for key in allow if key in violations} + findings = failures + [ + f"{directive} blocked {origin} {entry['count']} time(s)" + f" ({'/'.join(sorted(entry['disposition']))}), first on {entry['page']}" + for (directive, origin), entry in sorted(violations.items()) + ] + findings += [ + f"the allow list names {directive} {origin}, which nothing blocked" + for directive, origin in allow + if complete and (directive, origin) not in allowed + ] + return findings, allowed, loaded + + +def docker_command(image, version, base_url, cache): + uv = shutil.which("uv") + if uv is None: + raise FileNotFoundError("uv is not on PATH") + return [ + "docker", + "run", + "--rm", + "-i", + "--network", + "host", + "-u", + f"{os.getuid()}:{os.getgid()}", + "-e", + "HOME=/tmp", + "-e", + "UV_CACHE_DIR=/uv-cache", + "-v", + f"{uv}:/usr/local/bin/uv:ro", + "-v", + f"{cache}:/uv-cache", + "-v", + f"{CHECKS}:/checks:ro", + image, + "uv", + "run", + "--no-project", + "--python", + "/usr/bin/python3", + "--with", + f"playwright=={version}", + "python", + "/checks/check-csp-browser.py", + "--probe", + base_url, + ] + + +def run_probe(command, paths, timeout): + """The probe's records, one JSON object per output line, or a refusal naming why none came.""" + try: + done = subprocess.run( + command, + input="\n".join(paths) + "\n", + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + except (OSError, subprocess.TimeoutExpired) as error: + return None, f"the browser probe did not finish: {error}" + if done.returncode != 0: + return ( + None, + f"the browser probe exited {done.returncode}: {done.stderr[-2000:]}", + ) + return [json.loads(line) for line in done.stdout.splitlines() if line], None + + +LISTENER = """ +document.addEventListener('securitypolicyviolation', (e) => window.__cspReport({ + directive: e.effectiveDirective, blocked: e.blockedURI, disposition: e.disposition})); +""" + + +def probe(base_url, paths): + """Run inside the container, writing one JSON record per page and per violation.""" + from playwright.sync_api import Error, sync_playwright + + def emit(record): + print(json.dumps(record), flush=True) + + with sync_playwright() as driver: + browser = driver.chromium.launch() + context = browser.new_context() + violations = [] + context.expose_binding( + "__cspReport", lambda _, record: violations.append(record) + ) + context.add_init_script(LISTENER) + page = context.new_page() + for path in paths: + try: + response = page.goto(urljoin(base_url, path), wait_until="load") + emit({"page": path, "status": response.status if response else 0}) + page.evaluate( + "async () => { for (let y = 0; y < document.body.scrollHeight;" + " y += innerHeight) { scrollTo(0, y);" + " await new Promise(r => setTimeout(r, 50)); } }" + ) + for button in page.locator(".copy-code").all(): + button.dispatch_event("click") + if path == SEARCH_PATH: + page.locator("#searchInput:enabled").press_sequentially( + SEARCH_QUERY + ) + page.locator("#searchResults li").first.wait_for() + page.wait_for_load_state("networkidle") + except Error as error: + emit({"page": path, "error": str(error).splitlines()[0]}) + for violation in violations: + emit({"page": path, **violation}) + violations.clear() + browser.close() + + +def main(argv=None): + parser = argparse.ArgumentParser(description=(__doc__ or "").partition("\n")[0]) + parser.add_argument("base_url", help="the running mirror, such as $SITE_BASE_URL") + parser.add_argument( + "--urls", + type=pathlib.Path, + action="append", + help=f"a list of site paths, repeatable (default {URLS.name})", + ) + parser.add_argument( + "--probe", + action="store_true", + help="run the browser half, reading paths on stdin (inside the container)", + ) + parser.add_argument( + "--timeout", type=int, default=3600, help="seconds the whole run may take" + ) + args = parser.parse_args(argv) + if not urlsplit(args.base_url).netloc: + parser.error(f"{args.base_url} is not an absolute URL") + if args.probe: + probe(args.base_url, [line.strip() for line in sys.stdin if line.strip()]) + return 0 + + image, version = pinned_image(DOCKERFILE.read_text(encoding="utf-8")) + allow = read_allow(ALLOW.read_text(encoding="utf-8")) + paths = read_paths(p.read_text(encoding="utf-8") for p in (args.urls or [URLS])) + cache = pathlib.Path( + os.environ.get("UV_CACHE_DIR") + or pathlib.Path(tempfile.gettempdir()) / "blog-csp-browser-uv" + ) + cache.mkdir(parents=True, exist_ok=True) + print(f"csp-browser: {len(paths)} pages against {args.base_url}, {image}") + try: + command = docker_command(image, version, args.base_url, cache) + except FileNotFoundError as error: + sys.exit(f"FAIL: {error}") + records, refusal = run_probe(command, paths, args.timeout) + if records is None: + sys.exit(f"FAIL: {refusal}") + + findings, allowed, loaded = summarize(records, allow, args.urls is None) + for (directive, origin), count in sorted(allowed.items()): + print(f" allowed: {directive} blocked {origin} {count} time(s)") + if loaded != len(paths): + findings.insert(0, f"{loaded} of {len(paths)} pages reported a load") + if not findings: + print(f"PASS - {loaded} pages loaded with no violation the allow list lacks") + return 0 + print( + f"FAIL csp-browser: {len(findings)} problem{'' if len(findings) == 1 else 's'}" + ) + for item in findings: + print(f" {item}") + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/checks/check-csp-scripts.py b/checks/check-csp-scripts.py index 2ecf177d..f83261db 100755 --- a/checks/check-csp-scripts.py +++ b/checks/check-csp-scripts.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Verify that the blog's Content-Security-Policy allows every script the built site runs. +"""Verify that the blog's Content-Security-Policy allows every script and embed the built site loads. The policy is read from `checks/security-headers.txt`, and `deploy/Caddyfile`, which ships, must send the same value. Without `script-src` the browser applies `default-src`, and so does this @@ -11,6 +11,11 @@ browser runs is checked, an import map and a speculation rules block included. Any other type is a data block that never runs, and the browser never checks an empty script, so neither needs a hash. + +A frame, a media file, or an object loads under its own directive. A post may carry raw HTML, +so it can add one from a host the policy does not name. Each such load must come from a host or a +scheme its directive names. The browser's fallbacks apply: `child-src` then `default-src` for a +frame, and `default-src` for the others. An `about:` URL fetches nothing, so no directive applies. """ import argparse @@ -56,13 +61,40 @@ def blog_policy(headers_text): return None -def script_sources(policy): +FALLBACKS = { + "script-src": ("script-src", "default-src"), + "frame-src": ("frame-src", "child-src", "default-src"), + "media-src": ("media-src", "default-src"), + "object-src": ("object-src", "default-src"), +} + +EMBEDS = { + ("iframe", "src"): "frame-src", + ("frame", "src"): "frame-src", + ("audio", "src"): "media-src", + ("video", "src"): "media-src", + ("source", "src"): "media-src", + ("track", "src"): "media-src", + ("embed", "src"): "object-src", + ("object", "data"): "object-src", +} + + +def directive_sources(policy, directive): + """The sources the browser applies to a directive, its fallbacks included.""" directives = {} - for directive in policy.split(";"): - tokens = directive.split() + for part in policy.split(";"): + tokens = part.split() if tokens: directives.setdefault(tokens[0], tokens[1:]) - return directives.get("script-src", directives.get("default-src", [])) + for name in FALLBACKS[directive]: + if name in directives: + return directives[name] + return [] + + +def script_sources(policy): + return directive_sources(policy, "script-src") def digest(body): @@ -78,17 +110,21 @@ def __init__(self): super().__init__(convert_charrefs=False) self.inline = [] self.loaded = [] + self.embeds = [] self.findings = [] self.body = None def handle_starttag(self, tag, attrs): for name, value in attrs: + url = (value or "").strip() if name.startswith("on"): self.findings.append(f"<{tag} {name}> is an inline event handler") - elif name in ("href", "src", "action") and ( - value or "" - ).strip().lower().startswith("javascript:"): + elif name in ("href", "src", "action") and url.lower().startswith( + "javascript:" + ): self.findings.append(f"<{tag} {name}> is a javascript: URL") + elif (tag, name) in EMBEDS and url and not url.lower().startswith("about:"): + self.embeds.append((tag, name, url, EMBEDS[tag, name])) if tag != "script": return attr = dict(attrs) @@ -120,7 +156,11 @@ def allowed(src, sources): return "'self'" in sources -def check(public, sources): +def check(public, policy): + sources = script_sources(policy) + embed_sources = { + name: directive_sources(policy, name) for name in set(EMBEDS.values()) + } used = collections.defaultdict(list) findings = [] for path in sorted(public.rglob("*.html")): @@ -134,6 +174,11 @@ def check(public, sources): for src in scan.loaded if not allowed(src, sources) ] + findings += [ + f"{rel}: <{tag} {name}={src}> is from a host or scheme that {directive} does not name" + for tag, name, src, directive in scan.embeds + if not allowed(src, embed_sources[directive]) + ] for body in scan.inline: if body: used[digest(body)].append(rel) @@ -178,9 +223,9 @@ def main(argv=None): if policy is None: sys.exit(f"FAIL: {refusal}") - findings = check(args.public, script_sources(policy)) + findings = check(args.public, policy) if not findings: - print("PASS - the blog's script-src allows every script the site runs") + print("PASS - the blog's policy allows every script and embed the site loads") return 0 print(f"FAIL csp: {len(findings)} problem{'' if len(findings) == 1 else 's'}") for item in findings[:20]: diff --git a/checks/csp-browser-allow.txt b/checks/csp-browser-allow.txt new file mode 100644 index 00000000..c2a9ad66 --- /dev/null +++ b/checks/csp-browser-allow.txt @@ -0,0 +1,2 @@ +img-src https://docs.google.com dead hotlinked images on archived posts, kept until each post settles what replaces them +img-src https://www.elcolighting.com dead hotlinked image on an archived post, kept until the post settles what replaces it diff --git a/checks/pyproject.toml b/checks/pyproject.toml index 77bdefe0..9e4c72ca 100644 --- a/checks/pyproject.toml +++ b/checks/pyproject.toml @@ -1,4 +1,4 @@ -# Tool configuration only, since these gates are standard library alone and ship nothing. +# Tool configuration only, since these gates ship nothing. [tool.ruff] target-version = "py312" @@ -19,3 +19,7 @@ typeCheckingMode = "standard" [tool.coverage.run] source = ["."] omit = ["tests/*"] + +[[tool.mypy.overrides]] +module = ["playwright.*"] +ignore_missing_imports = true diff --git a/checks/tests/test_check_csp_browser.py b/checks/tests/test_check_csp_browser.py new file mode 100644 index 00000000..b6503864 --- /dev/null +++ b/checks/tests/test_check_csp_browser.py @@ -0,0 +1,230 @@ +"""Tests for check-csp-browser.py's host half, every record in them constructed rather than observed.""" + +import contextlib +import importlib.util +import io +import os +import pathlib +import sys +import tempfile +import unittest +from unittest import mock + +CHECKS = pathlib.Path(__file__).resolve().parent.parent +SPEC = importlib.util.spec_from_file_location( + "check_csp_browser", CHECKS / "check-csp-browser.py" +) +if SPEC is None or SPEC.loader is None: + raise ImportError("cannot load check-csp-browser.py") +gate = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(gate) + +BASE = "https://mirror.example/" +ALLOWED = ("img-src", "https://images.example") + + +def loaded(page, status=200): + return {"page": page, "status": status} + + +def blocked(page, directive, url, disposition="enforce"): + return { + "page": page, + "directive": directive, + "blocked": url, + "disposition": disposition, + } + + +class PinTest(unittest.TestCase): + def test_the_committed_dockerfile_pins_a_versioned_digest(self) -> None: + image, version = gate.pinned_image(gate.DOCKERFILE.read_text(encoding="utf-8")) + self.assertIn(f":v{version}-", image) + self.assertIn("@sha256:", image) + + def test_a_tag_without_a_version_is_refused(self) -> None: + with self.assertRaises(ValueError): + gate.pinned_image("FROM mcr.microsoft.com/playwright/python:latest\n") + + def test_the_committed_allow_list_parses(self) -> None: + for directive, origin in gate.read_allow( + gate.ALLOW.read_text(encoding="utf-8") + ): + self.assertTrue(directive.endswith("-src"), directive) + self.assertEqual(gate.blocked_origin(origin), origin) + + +class ListTest(unittest.TestCase): + def test_paths_keep_order_drop_repeats_and_add_search(self) -> None: + paths = gate.read_paths(["/\n/a/\n\n", "/a/\n/b/\n"]) + self.assertEqual(paths, ["/", "/a/", "/b/", gate.SEARCH_PATH]) + + def test_a_listed_search_page_is_not_added_twice(self) -> None: + paths = gate.read_paths([f"{gate.SEARCH_PATH}\n/\n"]) + self.assertEqual(paths, [gate.SEARCH_PATH, "/"]) + + def test_an_allow_line_without_a_reason_is_refused(self) -> None: + with self.assertRaises(ValueError): + gate.read_allow("img-src\thttps://images.example\n") + + def test_an_allow_list_reads_directive_and_origin(self) -> None: + allow = gate.read_allow("img-src\thttps://images.example\tgone\n\n") + self.assertEqual(allow, [ALLOWED]) + + +class OriginTest(unittest.TestCase): + def test_a_url_reduces_to_its_origin(self) -> None: + origin = gate.blocked_origin("https://images.example/a/b.png?x=1") + self.assertEqual(origin, "https://images.example") + + def test_a_keyword_passes_through(self) -> None: + self.assertEqual(gate.blocked_origin("inline"), "inline") + + +class SummarizeTest(unittest.TestCase): + def test_a_clean_run_has_no_findings(self) -> None: + findings, allowed, count = gate.summarize( + [loaded("/"), loaded("/a/")], [], True + ) + self.assertEqual((findings, allowed, count), ([], {}, 2)) + + def test_a_violation_is_counted_once_per_directive_and_origin(self) -> None: + records = [ + loaded("/"), + blocked("/", "style-src-elem", "inline"), + loaded("/a/"), + blocked("/a/", "style-src-elem", "inline", "report"), + ] + findings, _, _ = gate.summarize(records, [], True) + self.assertEqual( + findings, + ["style-src-elem blocked inline 2 time(s) (enforce/report), first on /"], + ) + + def test_an_allowed_violation_is_counted_not_reported(self) -> None: + records = [loaded("/"), blocked("/", "img-src", "https://images.example/1.png")] + findings, allowed, _ = gate.summarize(records, [ALLOWED], True) + self.assertEqual((findings, allowed), ([], {ALLOWED: 1})) + + def test_a_stale_allow_entry_fails_a_complete_run(self) -> None: + findings, _, _ = gate.summarize([loaded("/")], [ALLOWED], True) + self.assertEqual(len(findings), 1) + self.assertIn("which nothing blocked", findings[0]) + + def test_a_stale_allow_entry_passes_a_partial_run(self) -> None: + findings, _, _ = gate.summarize([loaded("/")], [ALLOWED], False) + self.assertEqual(findings, []) + + def test_a_page_that_is_not_200_fails(self) -> None: + findings, _, _ = gate.summarize([loaded("/gone/", 404)], [], True) + self.assertEqual(findings, ["/gone/ answered 404"]) + + def test_a_probe_error_fails(self) -> None: + records = [loaded("/"), {"page": "/", "error": "Timeout 30000ms exceeded."}] + findings, _, _ = gate.summarize(records, [], True) + self.assertEqual(findings, ["/: Timeout 30000ms exceeded."]) + + +class MainTest(unittest.TestCase): + def setUp(self) -> None: + cache = tempfile.TemporaryDirectory() + self.addCleanup(cache.cleanup) + env = mock.patch.dict(os.environ, {"UV_CACHE_DIR": cache.name}) + env.start() + self.addCleanup(env.stop) + + def run_main(self, records, argv=()): + with ( + mock.patch.object(gate, "run_probe", return_value=(records, None)), + mock.patch.object(gate, "docker_command", return_value=["true"]), + mock.patch.object(gate, "read_allow", return_value=[]), + contextlib.redirect_stdout(io.StringIO()) as out, + ): + code = gate.main([BASE, *argv]) + return code, out.getvalue() + + def test_every_page_loaded_clean_passes(self) -> None: + paths = gate.read_paths([gate.URLS.read_text(encoding="utf-8")]) + code, out = self.run_main([loaded(path) for path in paths]) + self.assertEqual(code, 0, out) + self.assertIn("PASS", out) + + def test_a_page_that_never_reported_fails(self) -> None: + code, out = self.run_main([loaded("/")]) + self.assertEqual(code, 1) + self.assertIn(" pages reported a load", out) + + def test_a_probe_that_did_not_run_is_a_refusal(self) -> None: + with ( + mock.patch.object(gate, "run_probe", return_value=(None, "exited 125")), + mock.patch.object(gate, "docker_command", return_value=["true"]), + contextlib.redirect_stdout(io.StringIO()), + self.assertRaises(SystemExit) as raised, + ): + gate.main([BASE]) + self.assertIn("exited 125", str(raised.exception.code)) + + def test_a_host_without_uv_fails_with_the_reason(self) -> None: + with ( + mock.patch.object(gate.shutil, "which", return_value=None), + contextlib.redirect_stdout(io.StringIO()), + self.assertRaises(SystemExit) as raised, + ): + gate.main([BASE]) + self.assertEqual(raised.exception.code, "FAIL: uv is not on PATH") + + def test_a_relative_base_url_is_a_usage_error(self) -> None: + with ( + contextlib.redirect_stderr(io.StringIO()), + self.assertRaises(SystemExit) as raised, + ): + gate.main(["mirror.example"]) + self.assertEqual(raised.exception.code, 2) + + +class CommandTest(unittest.TestCase): + def test_the_container_installs_the_tag_version_and_reaches_the_host(self) -> None: + with mock.patch.object(gate.shutil, "which", return_value="/bin/uv"): + command = gate.docker_command("img:v1.2.3-noble", "1.2.3", BASE, "/c") + self.assertIn("playwright==1.2.3", command) + self.assertEqual(command[command.index("--network") + 1], "host") + self.assertEqual(command[-2:], ["--probe", BASE]) + + def test_a_host_without_uv_is_refused(self) -> None: + with ( + mock.patch.object(gate.shutil, "which", return_value=None), + self.assertRaises(FileNotFoundError), + ): + gate.docker_command("img:v1.2.3-noble", "1.2.3", BASE, "/c") + + +class ProbeRunTest(unittest.TestCase): + def test_records_are_read_one_per_line_from_the_paths_on_stdin(self) -> None: + echo = "import json, sys\nfor line in sys.stdin: print(json.dumps({'page': line.strip(), 'status': 200}))" + records, refusal = gate.run_probe( + [sys.executable, "-c", echo], ["/", "/a/"], 60 + ) + self.assertIsNone(refusal) + self.assertEqual(records, [loaded("/"), loaded("/a/")]) + + def test_a_probe_that_exits_nonzero_is_a_refusal_naming_its_stderr(self) -> None: + fail = "import sys; sys.exit('no browser')" + records, refusal = gate.run_probe([sys.executable, "-c", fail], ["/"], 60) + self.assertIsNone(records) + self.assertIn("no browser", refusal or "") + + def test_a_probe_past_its_timeout_is_a_refusal(self) -> None: + stall = "import time; time.sleep(30)" + records, refusal = gate.run_probe([sys.executable, "-c", stall], ["/"], 1) + self.assertIsNone(records) + self.assertIn("timed out", refusal or "") + + def test_a_probe_that_cannot_start_is_a_refusal(self) -> None: + missing = [str(CHECKS / "no-such-command")] + records, refusal = gate.run_probe(missing, ["/"], 60) + self.assertIsNone(records) + self.assertIn("did not finish", refusal or "") + + +if __name__ == "__main__": + unittest.main() diff --git a/checks/tests/test_check_csp_scripts.py b/checks/tests/test_check_csp_scripts.py index ef4e3d08..ce6994c7 100644 --- a/checks/tests/test_check_csp_scripts.py +++ b/checks/tests/test_check_csp_scripts.py @@ -25,7 +25,7 @@ def policy(*sources): class CheckTest(unittest.TestCase): - def run_gate(self, pages, sources): + def run_gate(self, pages, sources, csp=None): with tempfile.TemporaryDirectory() as tmp: public = pathlib.Path(tmp) for rel, html in pages.items(): @@ -33,7 +33,7 @@ def run_gate(self, pages, sources): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(html, encoding="utf-8") with contextlib.redirect_stdout(io.StringIO()): - return gate.check(public, sources) + return gate.check(public, csp or policy(*sources)) def test_a_listed_hash_for_every_inline_script_passes(self) -> None: sources = ["'self'", gate.digest(THEME)] @@ -123,6 +123,66 @@ def test_handlers_and_javascript_urls_fail(self) -> None: self.assertEqual(len(findings), 1) self.assertIn(expected, findings[0]) + def test_an_embed_from_another_host_fails_under_its_directive(self) -> None: + for html, directive in ( + ('', "frame-src"), + ('', "frame-src"), + ('', "media-src"), + ('', "media-src"), + ( + '', + "media-src", + ), + ( + '', + "media-src", + ), + ('', "object-src"), + ('', "object-src"), + ): + with self.subTest(html): + findings = self.run_gate({"index.html": html}, ["'self'"]) + self.assertEqual(len(findings), 1) + self.assertIn(f"{directive} does not name", findings[0]) + + def test_an_embed_from_the_site_itself_passes_under_default_src(self) -> None: + html = '' + self.assertEqual(self.run_gate({"index.html": html}, ["'self'"]), []) + + def test_a_named_host_passes_and_the_fallback_order_holds(self) -> None: + html = '' + host = "https://maps.example.test" + for csp, findings in ( + (f"default-src 'self'; frame-src {host}", 0), + (f"default-src 'self'; child-src {host}", 0), + (f"default-src {host}", 0), + (f"default-src {host}; frame-src 'self'", 1), + (f"default-src {host}; child-src 'self'", 1), + ): + with self.subTest(csp): + found = self.run_gate({"index.html": html}, [], csp) + self.assertEqual(len(found), findings, found) + + def test_object_src_none_refuses_even_the_site_itself(self) -> None: + html = '' + csp = "default-src 'self'; object-src 'none'" + findings = self.run_gate({"index.html": html}, [], csp) + self.assertEqual(len(findings), 1) + self.assertIn("object-src does not name", findings[0]) + + def test_an_embed_without_a_value_or_with_about_blank_is_not_checked(self) -> None: + html = ( + '' + '' + ) + self.assertEqual(self.run_gate({"index.html": html}, ["'self'"]), []) + + def test_a_javascript_embed_is_reported_once(self) -> None: + html = '' + findings = self.run_gate({"index.html": html}, ["'self'"]) + self.assertEqual(len(findings), 1) + self.assertIn("javascript: URL", findings[0]) + class PolicyTest(unittest.TestCase): def test_the_blog_policy_is_read(self) -> None: diff --git a/deploy/README.md b/deploy/README.md index 2bf12835..11cc424d 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -7,14 +7,15 @@ How the site is built, released, and served. The release is a **self-contained b | Tool | Used by | Needed for | Install | | --- | --- | --- | --- | | `hugo` (extended) | `make-release.sh` | building the site | see below | -| `python3` (3.10+) | `check-url-parity.py`, `check-csp-scripts.py`, `capture/build-redirects.py` | the build-time gates, regenerating maps | `apt install python3` | +| `python3` (3.10+) | `check-url-parity.py`, `check-csp-scripts.py`, `check-csp-browser.py`, `capture/build-redirects.py` | the build-time gates, the browser trial, regenerating maps | `apt install python3` | | PyYAML | `capture/clean-content.py` | reading front matter during a conversion | `apt install python3-yaml` | | `rsync` | `make-release.sh` | installing a release, hard-linking unchanged files | `apt install rsync` | | `gzip` | `make-release.sh` | precompression | coreutils, already present | | `brotli` | `make-release.sh` | precompression | `apt install brotli` | | `curl` 7.84+ | `check-live-urls.sh` | verifying a running server, reading a header with `%header{}` | `apt install curl` | | `bash` 4.4+ | all scripts | arrays, `mapfile` | already present | -| `docker` | serving | running Caddy | orchestrated elsewhere | +| `docker` | serving, `check-csp-browser.py` | running Caddy, the headless browser | orchestrated elsewhere | +| `uv` | `check-csp-browser.py` | installing Playwright in the browser container | the upstream installer | **These scripts run on Linux, which is a dependency ceiling rather than an omission.** They use `mv -Tf`, `find -printf`, `mapfile`, and `sed -i` without an argument, all of which are GNU or @@ -302,10 +303,12 @@ The sites send the same security headers on every response, redirects and the `4 The HSTS value carries neither `includeSubDomains` nor `preload`. `includeSubDomains` would extend the policy to every subdomain of the site's hostname, and this bundle serves none of them. `preload` asks for the whole domain to be built into browsers, where a removal takes months to reach readers. HSTS at the edge is the host side's setting, and it stays off because Cloudflare applies it to every name in the zone. -**Each site sends its own `Content-Security-Policy`.** The family page loads few resources, so its policy names each kind: its own files, Google Fonts, inline styles, and `data:` images. The blog policy allows its own files, Google Fonts, and inline styles, which the theme and some archived posts carry. No post loads a script, frame, or object from another host. An embed from another host, such as a video or a map, needs that host in the policy first, or the browser blocks it. Write a script's host as `https://` and a scheme as `data:`, the forms the gate reads. Images load only from the site itself. That blocks the hotlinked images a few archived posts still reference, and each of those is already gone. Its `script-src` lists a hash for each inline script the theme writes, rather than allowing every inline script. +**Each site sends its own `Content-Security-Policy`.** The family page loads few resources, so its policy names each kind: its own files, Google Fonts, inline styles, and `data:` images. The blog policy allows its own files, Google Fonts, and inline styles, which the theme and some archived posts carry. No post loads a script, frame, or object from another host. An embed from another host, such as a video or a map, needs that host in its directive first. Without it the browser blocks the embed, and the release build fails on it. Write a host as `https://` and a scheme as `data:`, the forms the gate reads. Images load only from the site itself. That blocks the hotlinked images a few archived posts still reference, and each of those is already gone. Its `script-src` lists a hash for each inline script the theme writes, rather than allowing every inline script. **A Hugo update, a theme update, or a theme setting in `hugo.yaml` can change those scripts.** [`checks/check-csp-scripts.py`][checks-csp-scripts] runs in the release build and fails when the hashes and the built scripts differ. The fix is to copy each hash it reports into both the Caddyfile and `security-headers.txt`, and to drop each hash it reports as unused. +**The gate reads only what Hugo builds, so a policy change is also tried in a browser.** [`checks/check-csp-browser.py`][checks-csp-browser] loads every page of a running mirror in headless Chromium. It fails on anything the policy blocks that [`checks/csp-browser-allow.txt`][checks-csp-browser-allow] does not list. A run over the whole default list also fails on an entry there that nothing matched. The dead hotlinked images are its entries today. [OPERATIONS.md "Local Verification"][operations-local-verification] says when it runs and how. + **The policy also blocks a script the proxy injects into a page.** Cloudflare's Rocket Loader, Email Address Obfuscation, and Web Analytics each inject one, so each stays off. They are the host side's to set, and the gate cannot see them, since it reads only what Hugo builds. **A change to any of these values changes [`checks/security-headers.txt`][checks-security-headers] with it.** The live check asserts each value exactly, and a unit case fails while the two differ. @@ -433,7 +436,7 @@ Two orderings are load-bearing. `@post_child_feed` precedes `@post_child` becaus Each of these fails silently when it fails, which is why it is checked rather than assumed: - **The URL contract**, via `check-url-parity.py`, before anything is installed. -- **The blog's script hashes**, via `check-csp-scripts.py`, before anything is installed. +- **The blog's script hashes and embed sources**, via `check-csp-scripts.py`, before anything is installed. - **World-readability of the finished release.** `--chmod` and `--no-g` apply only to files rsync newly transfers. A file supplied by `--link-dest` is a hard link to the previous release's inode and keeps that inode's mode and ownership, so a badly moded file rides the @@ -450,12 +453,15 @@ Each of these fails silently when it fails, which is why it is checked rather th [caddyfile]: ./Caddyfile [capture-build-redirects]: ../capture/build-redirects.py [capture-readme]: ../capture/README.md +[checks-csp-browser]: ../checks/check-csp-browser.py +[checks-csp-browser-allow]: ../checks/csp-browser-allow.txt [checks-csp-scripts]: ../checks/check-csp-scripts.py [checks-redirect-urls]: ../checks/redirect-urls.txt [checks-security-headers]: ../checks/security-headers.txt [example-env]: ../.secrets/example.env [how-the-redirects-are-expressed]: #how-the-redirects-are-expressed [identifying-the-environment]: #identifying-the-environment +[operations-local-verification]: ../OPERATIONS.md#local-verification [operations-log-tiers]: ../OPERATIONS.md#the-log-is-three-tiers-and-each-is-blind-to-something [reloading-without-a-restart]: #reloading-without-a-restart [serving-the-family-site-on-a-local-name]: #serving-the-family-site-on-a-local-name