From 75369e2bedcb8e7c18768e062ebabb5393f1730e Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sun, 25 Oct 2026 08:25:25 -0700 Subject: [PATCH 1/4] Commit the CSP Browser Trial as a Repeatable Check The blog policy shipped after a headless Chromium pass that no committed tool could repeat. check-csp-browser.py loads every rendered page of a running mirror in the Playwright image checks/browser/Dockerfile pins, and fails on any securitypolicyviolation that csp-browser-allow.txt does not list. The Playwright package is installed at the image tag's version, so Dependabot moves one pin. Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 10 +- OPERATIONS.md | 17 +- checks/README.md | 2 + checks/browser/Dockerfile | 1 + checks/check-csp-browser.py | 279 +++++++++++++++++++++++++ checks/csp-browser-allow.txt | 2 + checks/pyproject.toml | 4 + checks/tests/test_check_csp_browser.py | 212 +++++++++++++++++++ deploy/README.md | 8 +- 9 files changed, 530 insertions(+), 5 deletions(-) create mode 100644 checks/browser/Dockerfile create mode 100755 checks/check-csp-browser.py create mode 100644 checks/csp-browser-allow.txt create mode 100644 checks/tests/test_check_csp_browser.py 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/OPERATIONS.md b/OPERATIONS.md index 1ab033f6..c6367e78 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 then reports each `securitypolicyviolation` event by directive and blocked origin, with the first page it 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. 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/checks/README.md b/checks/README.md index cb3d98ab..cc3daa74 100644 --- a/checks/README.md +++ b/checks/README.md @@ -6,6 +6,7 @@ This README covers the URL contract alone. The other checks in this directory ea | Check | Fails when | | --- | --- | +| [`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 the built site runs and the blog's `script-src` 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 | @@ -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..ca9b4aa4 --- /dev/null +++ b/checks/check-csp-browser.py @@ -0,0 +1,279 @@ +#!/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, which 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 not path.startswith("#") 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}" + if parts.scheme and not parts.netloc and ":" in blocked: + return f"{parts.scheme}:" + 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.""" + done = subprocess.run( + command, + input="\n".join(paths) + "\n", + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + 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 = """ +window.__csp = []; +document.addEventListener('securitypolicyviolation', (e) => window.__csp.push({ + 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() + 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") + for violation in page.evaluate("window.__csp"): + emit({"page": path, **violation}) + except Error as error: + emit({"page": path, "error": str(error).splitlines()[0]}) + 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}") + records, refusal = run_probe( + docker_command(image, version, args.base_url, cache), 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/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..764c9693 100644 --- a/checks/pyproject.toml +++ b/checks/pyproject.toml @@ -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..c46cc142 --- /dev/null +++ b/checks/tests/test_check_csp_browser.py @@ -0,0 +1,212 @@ +"""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# note\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_scheme_url_reduces_to_its_scheme(self) -> None: + self.assertEqual(gate.blocked_origin("blob:https://mirror.example/1"), "blob:") + + 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_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 "") + + +if __name__ == "__main__": + unittest.main() diff --git a/deploy/README.md b/deploy/README.md index 2bf12835..c8c3209a 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -14,7 +14,8 @@ How the site is built, released, and served. The release is a **self-contained b | `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 @@ -306,6 +307,8 @@ The HSTS value carries neither `includeSubDomains` nor `preload`. `includeSubDom **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, and 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. @@ -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 From 2d7e0742935aa000ae28f75bfdc8d6822d72b6f6 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sun, 25 Oct 2026 08:32:05 -0700 Subject: [PATCH 2/4] Answer the Local Review of the CSP Browser Trial Co-Authored-By: Claude Opus 5.5 --- OPERATIONS.md | 2 +- checks/check-csp-browser.py | 8 +++----- checks/pyproject.toml | 2 +- checks/tests/test_check_csp_browser.py | 5 +---- deploy/README.md | 2 +- 5 files changed, 7 insertions(+), 12 deletions(-) diff --git a/OPERATIONS.md b/OPERATIONS.md index c6367e78..5a455e25 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -104,7 +104,7 @@ 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. 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 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. diff --git a/checks/check-csp-browser.py b/checks/check-csp-browser.py index ca9b4aa4..1be8974d 100755 --- a/checks/check-csp-browser.py +++ b/checks/check-csp-browser.py @@ -14,8 +14,8 @@ 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. +what it excuses. A page that does not answer `200` fails the run, since a trial over error pages +proves nothing. """ import argparse @@ -52,7 +52,7 @@ def read_paths(texts): for text in texts: for line in text.splitlines(): path = line.strip() - if path and not path.startswith("#") and path not in paths: + if path and path not in paths: paths.append(path) if SEARCH_PATH not in paths: paths.append(SEARCH_PATH) @@ -79,8 +79,6 @@ def blocked_origin(blocked): parts = urlsplit(blocked) if parts.scheme in ("http", "https") and parts.netloc: return f"{parts.scheme}://{parts.netloc}" - if parts.scheme and not parts.netloc and ":" in blocked: - return f"{parts.scheme}:" return blocked diff --git a/checks/pyproject.toml b/checks/pyproject.toml index 764c9693..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" diff --git a/checks/tests/test_check_csp_browser.py b/checks/tests/test_check_csp_browser.py index c46cc142..d07c0461 100644 --- a/checks/tests/test_check_csp_browser.py +++ b/checks/tests/test_check_csp_browser.py @@ -56,7 +56,7 @@ def test_the_committed_allow_list_parses(self) -> None: class ListTest(unittest.TestCase): def test_paths_keep_order_drop_repeats_and_add_search(self) -> None: - paths = gate.read_paths(["/\n/a/\n\n# note\n", "/a/\n/b/\n"]) + 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: @@ -77,9 +77,6 @@ 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_scheme_url_reduces_to_its_scheme(self) -> None: - self.assertEqual(gate.blocked_origin("blob:https://mirror.example/1"), "blob:") - def test_a_keyword_passes_through(self) -> None: self.assertEqual(gate.blocked_origin("inline"), "inline") diff --git a/deploy/README.md b/deploy/README.md index c8c3209a..fae40d09 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -7,7 +7,7 @@ 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, 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 | From 9675c450417527e7aaf467e1927ba1f85bcd99ac Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sun, 25 Oct 2026 08:33:04 -0700 Subject: [PATCH 3/4] Name the Browser Trial Among python3's Uses Co-Authored-By: Claude Opus 5.5 --- deploy/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deploy/README.md b/deploy/README.md index fae40d09..7b29f481 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -7,7 +7,7 @@ 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`, `check-csp-browser.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 | From 02542859e9d58e31318f63789cc1fdd5554ca539 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sun, 25 Oct 2026 08:42:45 -0700 Subject: [PATCH 4/4] Report a Browser Probe That Never Finished as a Refusal Co-Authored-By: Claude Opus 5.5 --- checks/check-csp-browser.py | 27 +++++++++++++++----------- checks/tests/test_check_csp_browser.py | 21 ++++++++++++++++++++ deploy/README.md | 2 +- 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/checks/check-csp-browser.py b/checks/check-csp-browser.py index 1be8974d..1fa85196 100755 --- a/checks/check-csp-browser.py +++ b/checks/check-csp-browser.py @@ -159,14 +159,17 @@ def docker_command(image, version, base_url, cache): def run_probe(command, paths, timeout): """The probe's records, one JSON object per output line, or a refusal naming why none came.""" - done = subprocess.run( - command, - input="\n".join(paths) + "\n", - capture_output=True, - text=True, - timeout=timeout, - check=False, - ) + 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, @@ -251,9 +254,11 @@ def main(argv=None): ) cache.mkdir(parents=True, exist_ok=True) print(f"csp-browser: {len(paths)} pages against {args.base_url}, {image}") - records, refusal = run_probe( - docker_command(image, version, args.base_url, cache), paths, args.timeout - ) + 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}") diff --git a/checks/tests/test_check_csp_browser.py b/checks/tests/test_check_csp_browser.py index d07c0461..b6503864 100644 --- a/checks/tests/test_check_csp_browser.py +++ b/checks/tests/test_check_csp_browser.py @@ -164,6 +164,15 @@ def test_a_probe_that_did_not_run_is_a_refusal(self) -> None: 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()), @@ -204,6 +213,18 @@ def test_a_probe_that_exits_nonzero_is_a_refusal_naming_its_stderr(self) -> None 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/deploy/README.md b/deploy/README.md index 7b29f481..c4e8a30a 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -307,7 +307,7 @@ The HSTS value carries neither `includeSubDomains` nor `preload`. `includeSubDom **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, and 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 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.