From 2e865b1baabd3f5fabb024b4fb058149fe37585f Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 20:29:45 -0700 Subject: [PATCH 01/10] Trial a Blog Content-Security-Policy as Report-Only Behind a Hash Gate Co-Authored-By: Claude Opus 5.5 --- checks/check-csp-scripts.py | 139 ++++++++++++++++++++++++++++++++++++ checks/security-headers.txt | 1 + deploy/Caddyfile | 1 + deploy/make-release.sh | 1 + 4 files changed, 142 insertions(+) create mode 100755 checks/check-csp-scripts.py diff --git a/checks/check-csp-scripts.py b/checks/check-csp-scripts.py new file mode 100755 index 00000000..3171e589 --- /dev/null +++ b/checks/check-csp-scripts.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Verify that the blog's Content-Security-Policy allows every script the built site runs. + +The policy is read from `checks/security-headers.txt`, which a unit case holds equal to the +Caddyfile. Every inline script must carry a hash the policy lists, and every hash the policy +lists must match an inline script, so a Hugo or theme update that changes a script's bytes fails +here rather than in a reader's browser. A script loaded by URL must come from an origin the +policy names, and an inline event handler or a `javascript:` URL fails outright, since a hash +cannot allow either. +""" + +import argparse +import base64 +import collections +import hashlib +import pathlib +import sys +from html.parser import HTMLParser +from urllib.parse import urlsplit + +CHECKS = pathlib.Path(__file__).resolve().parent +HEADERS = CHECKS / "security-headers.txt" +CSP = "Content-Security-Policy" + +# A script element whose type is none of these is a data block, which the browser never runs. +SCRIPT_TYPES = {"", "module", "text/javascript", "application/javascript"} + + +def script_sources(headers_text): + """The script-src tokens of the blog's policy, or None where the blog sends no policy.""" + for line in headers_text.splitlines(): + site, _, header = line.partition("\t") + name, _, value = header.partition(": ") + if site != "blog" or name not in (CSP, CSP + "-Report-Only"): + continue + for directive in value.split(";"): + tokens = directive.split() + if tokens and tokens[0] == "script-src": + return tokens[1:] + return [] + return None + + +def digest(body): + return "'sha256-" + base64.b64encode(hashlib.sha256(body.encode()).digest()).decode() + "'" + + +class ScriptScan(HTMLParser): + def __init__(self): + super().__init__(convert_charrefs=False) + self.inline = [] + self.loaded = [] + self.findings = [] + self.body = None + + def handle_starttag(self, tag, attrs): + for name, value in attrs: + 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:"): + self.findings.append(f"<{tag} {name}> is a javascript: URL") + if tag != "script": + return + attr = dict(attrs) + if (attr.get("type") or "").strip().lower() not in SCRIPT_TYPES: + return + if attr.get("src") is not None: + self.loaded.append(attr["src"] or "") + else: + self.body = [] + + def handle_data(self, data): + if self.body is not None: + self.body.append(data) + + def handle_endtag(self, tag): + if tag == "script" and self.body is not None: + self.inline.append("".join(self.body)) + self.body = None + + +def allowed(src, sources): + parts = urlsplit(src if not src.startswith("//") else "https:" + src) + if not parts.netloc: + return "'self'" in sources + return f"{parts.scheme}://{parts.netloc}" in sources + + +def check(public, sources): + used = collections.defaultdict(list) + findings = [] + for path in sorted(public.rglob("*.html")): + rel = str(path.relative_to(public)).replace("\\", "/") + scan = ScriptScan() + scan.feed(path.read_text(encoding="utf-8", errors="replace")) + scan.close() + findings += [f"{rel}: {finding}" for finding in scan.findings] + findings += [ + f"{rel}: " + + +def policy(*sources): + return f"default-src 'self'; script-src {' '.join(sources)}; img-src 'self'" + + +class CheckTest(unittest.TestCase): + def run_gate(self, pages, sources): + with tempfile.TemporaryDirectory() as tmp: + public = pathlib.Path(tmp) + for rel, html in pages.items(): + path = public / rel + 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) + + def test_a_listed_hash_for_every_inline_script_passes(self) -> None: + sources = ["'self'", gate.digest(THEME)] + pages = {"index.html": PAGE, "a/index.html": PAGE} + self.assertEqual(self.run_gate(pages, sources), []) + + def test_an_unlisted_inline_script_fails_with_its_hash(self) -> None: + findings = self.run_gate({"index.html": PAGE}, ["'self'"]) + self.assertEqual(len(findings), 1) + self.assertIn(gate.digest(THEME), findings[0]) + self.assertIn("not in script-src", findings[0]) + + def test_a_hash_no_script_matches_fails(self) -> None: + stale = gate.digest("retired()") + sources = ["'self'", gate.digest(THEME), stale] + findings = self.run_gate({"index.html": PAGE}, sources) + self.assertEqual( + findings, [f"script-src lists {stale}, which no inline script matches"] + ) + + def test_a_changed_byte_is_a_different_script(self) -> None: + sources = ["'self'", gate.digest(THEME)] + changed = PAGE.replace(THEME, THEME + ";") + findings = self.run_gate({"index.html": changed}, sources) + self.assertEqual(len(findings), 2) + + def test_the_hash_covers_the_raw_text_without_decoding_references(self) -> None: + body = "if (a && b) {}" + html = f"" + findings = self.run_gate({"index.html": html}, ["'self'", gate.digest(body)]) + self.assertEqual(findings, []) + + def test_data_blocks_and_empty_scripts_are_not_checked(self) -> None: + html = ( + '' + "" + ) + self.assertEqual(self.run_gate({"index.html": html}, ["'self'"]), []) + + def test_a_module_script_is_checked(self) -> None: + html = f'' + self.assertEqual(len(self.run_gate({"index.html": html}, ["'self'"])), 1) + + def test_a_script_url_needs_its_origin_named(self) -> None: + own = '' + other = '' + relative = '' + self.assertEqual(self.run_gate({"index.html": own}, ["'self'"]), []) + for html in (other, relative): + with self.subTest(html): + findings = self.run_gate({"index.html": html}, ["'self'"]) + self.assertEqual(len(findings), 1) + self.assertIn("does not name", findings[0]) + named = ["'self'", "https://cdn.example.test"] + self.assertEqual(self.run_gate({"index.html": other}, named), []) + + def test_handlers_and_javascript_urls_fail(self) -> None: + for html, expected in ( + ('', "inline event handler"), + ('Go', "javascript: URL"), + ): + with self.subTest(html): + findings = self.run_gate({"index.html": html}, ["'self'"]) + self.assertEqual(len(findings), 1) + self.assertIn(expected, findings[0]) + + +class PolicyTest(unittest.TestCase): + def test_the_blog_script_sources_are_read(self) -> None: + blog = policy("'self'", "'sha256-AAAA'") + family = policy("'none'") + text = ( + "blog\tReferrer-Policy: no-referrer\n" + f"blog\tContent-Security-Policy: {blog}\n" + f"family\tContent-Security-Policy: {family}\n" + ) + self.assertEqual(gate.script_sources(text), ["'self'", "'sha256-AAAA'"]) + + def test_a_blog_without_a_policy_reads_as_none(self) -> None: + family = policy("'self'") + text = f"family\tContent-Security-Policy: {family}\n" + self.assertIsNone(gate.script_sources(text)) + + def test_the_carried_blog_policy_never_allows_every_inline_script(self) -> None: + sources = gate.script_sources(gate.HEADERS.read_text(encoding="utf-8")) + self.assertIsNotNone(sources) + assert sources is not None + self.assertIn("'self'", sources) + self.assertNotIn("'unsafe-inline'", sources) + + +if __name__ == "__main__": + unittest.main() diff --git a/deploy/Caddyfile b/deploy/Caddyfile index a23b8c87..a344c435 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -37,7 +37,7 @@ Strict-Transport-Security "max-age=31536000" X-Content-Type-Options "nosniff" Referrer-Policy "strict-origin-when-cross-origin" - Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self' 'sha256-5ilQRTfItUB+Etsk1onTDCqBA1OpUBIKfJhdMlZ61Co=' 'sha256-QOwTHff6BrH8cmnR7hf10tIuyQ09hKSkEevZzo+G8WE=' 'sha256-UBD9lfFHKxagKGHh9S8B2hytN1cmDsFK1Tl1uedsZ0Q=' 'sha256-eyUVosQAviXm2qeOTG819D1n0kSst2gY8VmfgVsZlag='; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'" + Content-Security-Policy "default-src 'self'; script-src 'self' 'sha256-5ilQRTfItUB+Etsk1onTDCqBA1OpUBIKfJhdMlZ61Co=' 'sha256-QOwTHff6BrH8cmnR7hf10tIuyQ09hKSkEevZzo+G8WE=' 'sha256-UBD9lfFHKxagKGHh9S8B2hytN1cmDsFK1Tl1uedsZ0Q=' 'sha256-eyUVosQAviXm2qeOTG819D1n0kSst2gY8VmfgVsZlag='; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'" } # One map serves four classes because their key spaces are disjoint. diff --git a/deploy/README.md b/deploy/README.md index 5beb4f3a..65170363 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -302,7 +302,9 @@ 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. -**Only the family site sends a `Content-Security-Policy`.** Its page loads few resources, so its policy names each kind: its own files, Google Fonts, inline styles, and `data:` images. Blog posts embed third-party content, so a blog policy waits on a survey of what the posts load. +**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, and images load only from the site itself. Its `script-src` lists a hash for each inline script the theme writes, rather than allowing every inline script. + +**A Hugo or theme update can change those scripts' bytes.** [`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. **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. @@ -445,6 +447,7 @@ 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-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 From 2bdb467cfb060434c2c3175535a9ac18532b2b74 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 20:52:48 -0700 Subject: [PATCH 03/10] Check the Shipped Caddyfile's Policy and Name the CSP Gate in Its Docs Co-Authored-By: Claude Opus 5.5 --- checks/check-csp-scripts.py | 40 ++++++++++++++++---------- checks/tests/test_check_csp_scripts.py | 26 +++++++++++------ deploy/README.md | 5 ++-- deploy/make-release.sh | 2 ++ themes/README.md | 2 +- 5 files changed, 49 insertions(+), 26 deletions(-) diff --git a/checks/check-csp-scripts.py b/checks/check-csp-scripts.py index fdac1e56..378cf7d5 100755 --- a/checks/check-csp-scripts.py +++ b/checks/check-csp-scripts.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 """Verify that the blog's Content-Security-Policy allows every script the built site runs. -The policy is read from `checks/security-headers.txt`, which a unit case holds equal to the -Caddyfile. Every inline script must carry a hash the policy lists. Every hash the policy lists +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 +check. Every inline script must carry a hash the policy lists. Every hash the policy lists must match an inline script. A Hugo or theme update that changes a script's bytes then fails here rather than in a reader's browser. A script loaded by URL must come from an origin the policy names. An inline event handler or a `javascript:` URL fails outright, since a hash cannot @@ -21,26 +22,31 @@ CHECKS = pathlib.Path(__file__).resolve().parent HEADERS = CHECKS / "security-headers.txt" +CADDYFILE = CHECKS.parent / "deploy" / "Caddyfile" CSP = "Content-Security-Policy" SCRIPT_TYPES = {"", "module", "text/javascript", "application/javascript"} -def script_sources(headers_text): - """The script-src tokens of the blog's policy, or None where the blog sends no policy.""" +def blog_policy(headers_text): + """The blog's policy as security-headers.txt holds it, or None where the blog sends none.""" for line in headers_text.splitlines(): site, _, header = line.partition("\t") name, _, value = header.partition(": ") - if site != "blog" or name != CSP: - continue - for directive in value.split(";"): - tokens = directive.split() - if tokens and tokens[0] == "script-src": - return tokens[1:] - return [] + if site == "blog" and name == CSP: + return value return None +def script_sources(policy): + directives = {} + for directive in policy.split(";"): + tokens = directive.split() + if tokens: + directives.setdefault(tokens[0], tokens[1:]) + return directives.get("script-src", directives.get("default-src", [])) + + def digest(body): return ( "'sha256-" @@ -96,7 +102,7 @@ def check(public, sources): used = collections.defaultdict(list) findings = [] for path in sorted(public.rglob("*.html")): - rel = str(path.relative_to(public)).replace("\\", "/") + rel = path.relative_to(public).as_posix() scan = ScriptScan() scan.feed(path.read_text(encoding="utf-8", errors="replace")) scan.close() @@ -133,11 +139,15 @@ def main(argv=None): args = parser.parse_args(argv) if not args.public.is_dir(): sys.exit(f"FAIL: {args.public} is not a directory - run hugo first") - sources = script_sources(HEADERS.read_text(encoding="utf-8")) - if sources is None: + policy = blog_policy(HEADERS.read_text(encoding="utf-8")) + if policy is None: sys.exit(f"FAIL: {HEADERS.name} holds no {CSP} for the blog") + if f'{CSP} "{policy}"' not in CADDYFILE.read_text(encoding="utf-8"): + sys.exit( + f"FAIL: {CADDYFILE.name} does not send the blog {CSP} {HEADERS.name} holds" + ) - findings = check(args.public, sources) + findings = check(args.public, script_sources(policy)) if not findings: print("PASS - the blog's script-src allows every script the site runs") return 0 diff --git a/checks/tests/test_check_csp_scripts.py b/checks/tests/test_check_csp_scripts.py index 178901d2..da8e8e2f 100644 --- a/checks/tests/test_check_csp_scripts.py +++ b/checks/tests/test_check_csp_scripts.py @@ -102,7 +102,7 @@ def test_handlers_and_javascript_urls_fail(self) -> None: class PolicyTest(unittest.TestCase): - def test_the_blog_script_sources_are_read(self) -> None: + def test_the_blog_policy_is_read(self) -> None: blog = policy("'self'", "'sha256-AAAA'") family = policy("'none'") text = ( @@ -110,17 +110,27 @@ def test_the_blog_script_sources_are_read(self) -> None: f"blog\tContent-Security-Policy: {blog}\n" f"family\tContent-Security-Policy: {family}\n" ) - self.assertEqual(gate.script_sources(text), ["'self'", "'sha256-AAAA'"]) + self.assertEqual(gate.blog_policy(text), blog) def test_a_blog_without_a_policy_reads_as_none(self) -> None: family = policy("'self'") text = f"family\tContent-Security-Policy: {family}\n" - self.assertIsNone(gate.script_sources(text)) - - def test_the_carried_blog_policy_never_allows_every_inline_script(self) -> None: - sources = gate.script_sources(gate.HEADERS.read_text(encoding="utf-8")) - self.assertIsNotNone(sources) - assert sources is not None + self.assertIsNone(gate.blog_policy(text)) + + def test_script_src_is_read_and_default_src_stands_in_for_it(self) -> None: + sources = gate.script_sources(policy("'self'", "'sha256-AAAA'")) + self.assertEqual(sources, ["'self'", "'sha256-AAAA'"]) + fallback = gate.script_sources("default-src 'self'; img-src 'self'") + self.assertEqual(fallback, ["'self'"]) + self.assertEqual(gate.script_sources("img-src 'self'"), []) + + def test_the_carried_policy_is_what_the_caddyfile_sends(self) -> None: + carried = gate.blog_policy(gate.HEADERS.read_text(encoding="utf-8")) + self.assertIsNotNone(carried) + assert carried is not None + sent = gate.CADDYFILE.read_text(encoding="utf-8") + self.assertIn(f'Content-Security-Policy "{carried}"', sent) + sources = gate.script_sources(carried) self.assertIn("'self'", sources) self.assertNotIn("'unsafe-inline'", sources) diff --git a/deploy/README.md b/deploy/README.md index 65170363..8d88619c 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`, `capture/build-redirects.py` | the build-time gate, regenerating maps | `apt install python3` | +| `python3` (3.10+) | `check-url-parity.py`, `check-csp-scripts.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 | @@ -302,7 +302,7 @@ 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, and images load only from the site itself. 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. 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 or theme update can change those scripts' bytes.** [`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. @@ -431,6 +431,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. - **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 diff --git a/deploy/make-release.sh b/deploy/make-release.sh index 60b2e1ec..5bf53b75 100755 --- a/deploy/make-release.sh +++ b/deploy/make-release.sh @@ -203,6 +203,8 @@ hugo --gc --minify --panicOnWarning echo "==> verifying the URL contract" checks/check-url-parity.py public + +echo "==> verifying the Content-Security-Policy" checks/check-csp-scripts.py public echo "==> precompressing" diff --git a/themes/README.md b/themes/README.md index bee84e99..680f5520 100644 --- a/themes/README.md +++ b/themes/README.md @@ -73,7 +73,7 @@ The content width is unchanged from the theme default, deliberately. 720px at th ## Updating -Nothing is carried, so an update is a replace. Delete `PaperMod/`, drop the new upstream tree in its place, and update the upstream table at the top of the PaperMod section. Then confirm the site still builds under `--panicOnWarning`, which is the gate the theme has failed before. Run the `diff -r` above afterwards, so the next reader inherits the same guarantee. +Nothing is carried, so an update is a replace. Delete `PaperMod/`, drop the new upstream tree in its place, and update the upstream table at the top of the PaperMod section. Then confirm the site still builds under `--panicOnWarning`, which is the gate the theme has failed before. The release build's `checks/check-csp-scripts.py` also fails where the theme's inline scripts changed, and `deploy/README.md` "Security headers" says how to update the policy's hashes. Run the `diff -r` above afterwards, so the next reader inherits the same guarantee. Re-check the customization table before the replace, while the upstream table still names the old commit. Each theme hook it names is a comment-only file upstream today. If upstream adds content to one, the local override hides it without any build failure. The exception is `blank.css`, which the head partial bundles beside `custom.css` rather than shadowing. Added rules there still ship, ahead of `custom.css`. A rule duplicating one in `custom.css` needs no change, since the `custom.css` copy keeps the rule if upstream drops it. A conflicting upstream rule wins wherever its selector is more specific or its declaration is `!important`. Restate the site's value in `custom.css` with a selector at least as specific, since `custom.css` comes later, marked `!important` only where the upstream declaration is. Once `blank.css` carries any rule, correct each place calling it comment-only or rule-free: this paragraph, the customization table, and the `custom.css` header comment. Use the clone from the `diff -r` check above, or make a fresh one. Diff each row's theme hook between the recorded commit and the new commit. A comment-only diff needs no action. For a partial, added content means porting it into the override, or deciding it is unwanted. From 2c51a36f218d9710dcf1358665505676e1982a5c Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 21:01:14 -0700 Subject: [PATCH 04/10] Test the CSP Gate's Refusals With Constructed Policy Files Co-Authored-By: Claude Opus 5.5 --- checks/check-csp-scripts.py | 21 +++++++++++----- checks/tests/test_check_csp_scripts.py | 33 +++++++++++++++++++------- themes/README.md | 2 +- 3 files changed, 40 insertions(+), 16 deletions(-) diff --git a/checks/check-csp-scripts.py b/checks/check-csp-scripts.py index 378cf7d5..01184c4f 100755 --- a/checks/check-csp-scripts.py +++ b/checks/check-csp-scripts.py @@ -131,6 +131,19 @@ def check(public, sources): return findings +def load_policy(headers, caddyfile): + """The blog's policy, or a refusal naming why it cannot be checked.""" + policy = blog_policy(headers.read_text(encoding="utf-8")) + if policy is None: + return None, f"{headers.name} holds no {CSP} for the blog" + if f'{CSP} "{policy}"' not in caddyfile.read_text(encoding="utf-8"): + return ( + None, + f"{caddyfile.name} does not send the blog {CSP} {headers.name} holds", + ) + return policy, None + + def main(argv=None): parser = argparse.ArgumentParser(description=(__doc__ or "").partition("\n")[0]) parser.add_argument( @@ -139,13 +152,9 @@ def main(argv=None): args = parser.parse_args(argv) if not args.public.is_dir(): sys.exit(f"FAIL: {args.public} is not a directory - run hugo first") - policy = blog_policy(HEADERS.read_text(encoding="utf-8")) + policy, refusal = load_policy(HEADERS, CADDYFILE) if policy is None: - sys.exit(f"FAIL: {HEADERS.name} holds no {CSP} for the blog") - if f'{CSP} "{policy}"' not in CADDYFILE.read_text(encoding="utf-8"): - sys.exit( - f"FAIL: {CADDYFILE.name} does not send the blog {CSP} {HEADERS.name} holds" - ) + sys.exit(f"FAIL: {refusal}") findings = check(args.public, script_sources(policy)) if not findings: diff --git a/checks/tests/test_check_csp_scripts.py b/checks/tests/test_check_csp_scripts.py index da8e8e2f..8c8e473e 100644 --- a/checks/tests/test_check_csp_scripts.py +++ b/checks/tests/test_check_csp_scripts.py @@ -124,15 +124,30 @@ def test_script_src_is_read_and_default_src_stands_in_for_it(self) -> None: self.assertEqual(fallback, ["'self'"]) self.assertEqual(gate.script_sources("img-src 'self'"), []) - def test_the_carried_policy_is_what_the_caddyfile_sends(self) -> None: - carried = gate.blog_policy(gate.HEADERS.read_text(encoding="utf-8")) - self.assertIsNotNone(carried) - assert carried is not None - sent = gate.CADDYFILE.read_text(encoding="utf-8") - self.assertIn(f'Content-Security-Policy "{carried}"', sent) - sources = gate.script_sources(carried) - self.assertIn("'self'", sources) - self.assertNotIn("'unsafe-inline'", sources) + def load(self, headers, caddyfile): + with tempfile.TemporaryDirectory() as tmp: + root = pathlib.Path(tmp) + (root / "security-headers.txt").write_text(headers, encoding="utf-8") + (root / "Caddyfile").write_text(caddyfile, encoding="utf-8") + return gate.load_policy(root / "security-headers.txt", root / "Caddyfile") + + def test_a_policy_the_caddyfile_sends_loads(self) -> None: + blog = policy("'self'") + sent = f'header {{\n\tContent-Security-Policy "{blog}"\n}}\n' + held = f"blog\tContent-Security-Policy: {blog}\n" + self.assertEqual(self.load(held, sent), (blog, None)) + + def test_a_caddyfile_sending_another_value_refuses(self) -> None: + sent = f'header {{\n\tContent-Security-Policy "{policy("'self'")}"\n}}\n' + held = f"blog\tContent-Security-Policy: {policy("'self'", "'sha256-AAAA'")}\n" + loaded, refusal = self.load(held, sent) + self.assertIsNone(loaded) + self.assertIn("Caddyfile does not send", refusal or "") + + def test_a_header_file_without_a_blog_policy_refuses(self) -> None: + loaded, refusal = self.load("blog\tReferrer-Policy: no-referrer\n", "") + self.assertIsNone(loaded) + self.assertIn("holds no Content-Security-Policy", refusal or "") if __name__ == "__main__": diff --git a/themes/README.md b/themes/README.md index 680f5520..c058fe66 100644 --- a/themes/README.md +++ b/themes/README.md @@ -73,7 +73,7 @@ The content width is unchanged from the theme default, deliberately. 720px at th ## Updating -Nothing is carried, so an update is a replace. Delete `PaperMod/`, drop the new upstream tree in its place, and update the upstream table at the top of the PaperMod section. Then confirm the site still builds under `--panicOnWarning`, which is the gate the theme has failed before. The release build's `checks/check-csp-scripts.py` also fails where the theme's inline scripts changed, and `deploy/README.md` "Security headers" says how to update the policy's hashes. Run the `diff -r` above afterwards, so the next reader inherits the same guarantee. +Nothing is carried, so an update is a replace. Delete `PaperMod/`, drop the new upstream tree in its place, and update the upstream table at the top of the PaperMod section. Then confirm the site still builds under `--panicOnWarning`, which is the gate the theme has failed before. The release build's `checks/check-csp-scripts.py` also fails where an update changes the theme's inline scripts, and `deploy/README.md` "Security headers" says how to update the policy's hashes. Run the `diff -r` above afterwards, so the next reader inherits the same guarantee. Re-check the customization table before the replace, while the upstream table still names the old commit. Each theme hook it names is a comment-only file upstream today. If upstream adds content to one, the local override hides it without any build failure. The exception is `blank.css`, which the head partial bundles beside `custom.css` rather than shadowing. Added rules there still ship, ahead of `custom.css`. A rule duplicating one in `custom.css` needs no change, since the `custom.css` copy keeps the rule if upstream drops it. A conflicting upstream rule wins wherever its selector is more specific or its declaration is `!important`. Restate the site's value in `custom.css` with a selector at least as specific, since `custom.css` comes later, marked `!important` only where the upstream declaration is. Once `blank.css` carries any rule, correct each place calling it comment-only or rule-free: this paragraph, the customization table, and the `custom.css` header comment. Use the clone from the `diff -r` check above, or make a fresh one. Diff each row's theme hook between the recorded commit and the new commit. A comment-only diff needs no action. For a partial, added content means porting it into the override, or deciding it is unwanted. From 813fbe5d4b03ce6f09234c3159c2afe10ce1385b Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 21:10:29 -0700 Subject: [PATCH 05/10] Drop the Unused Google Maps Shortcode the Blog Policy Blocks Co-Authored-By: Claude Opus 5.5 --- deploy/README.md | 2 +- layouts/shortcodes/googlemaps.html | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) delete mode 100644 layouts/shortcodes/googlemaps.html diff --git a/deploy/README.md b/deploy/README.md index 8d88619c..952ab330 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -302,7 +302,7 @@ 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. 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 added to the policy first, or the browser blocks it. 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 or theme update can change those scripts' bytes.** [`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. diff --git a/layouts/shortcodes/googlemaps.html b/layouts/shortcodes/googlemaps.html deleted file mode 100644 index c37c434a..00000000 --- a/layouts/shortcodes/googlemaps.html +++ /dev/null @@ -1,5 +0,0 @@ - From bca2a7ab7e45e9469b4c6b2090c5197c5b36b3ca Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 21:18:34 -0700 Subject: [PATCH 06/10] Check Import Maps and Speculation Rules Against the Blog Policy Co-Authored-By: Claude Opus 5.5 --- checks/check-csp-scripts.py | 16 ++++++++++++---- checks/tests/test_check_csp_scripts.py | 9 ++++++--- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/checks/check-csp-scripts.py b/checks/check-csp-scripts.py index 01184c4f..0bb59cb3 100755 --- a/checks/check-csp-scripts.py +++ b/checks/check-csp-scripts.py @@ -6,9 +6,10 @@ check. Every inline script must carry a hash the policy lists. Every hash the policy lists must match an inline script. A Hugo or theme update that changes a script's bytes then fails here rather than in a reader's browser. A script loaded by URL must come from an origin the -policy names. An inline event handler or a `javascript:` URL fails outright, since a hash cannot -allow either. A data block, whose type is not JavaScript, never runs, and the browser never -checks an empty script, so neither needs a hash. +policy names. An inline event handler or a `javascript:` URL fails outright, since a hash allows +neither without `'unsafe-hashes'`, which the blog policy does not carry. An import map and a +speculation rules block are checked like a script. Any other type is a data block that never +runs, and the browser never checks an empty script, so neither needs a hash. """ import argparse @@ -25,7 +26,14 @@ CADDYFILE = CHECKS.parent / "deploy" / "Caddyfile" CSP = "Content-Security-Policy" -SCRIPT_TYPES = {"", "module", "text/javascript", "application/javascript"} +SCRIPT_TYPES = { + "", + "module", + "text/javascript", + "application/javascript", + "importmap", + "speculationrules", +} def blog_policy(headers_text): diff --git a/checks/tests/test_check_csp_scripts.py b/checks/tests/test_check_csp_scripts.py index 8c8e473e..be71dd84 100644 --- a/checks/tests/test_check_csp_scripts.py +++ b/checks/tests/test_check_csp_scripts.py @@ -73,9 +73,12 @@ def test_data_blocks_and_empty_scripts_are_not_checked(self) -> None: ) self.assertEqual(self.run_gate({"index.html": html}, ["'self'"]), []) - def test_a_module_script_is_checked(self) -> None: - html = f'' - self.assertEqual(len(self.run_gate({"index.html": html}, ["'self'"])), 1) + def test_modules_import_maps_and_speculation_rules_are_checked(self) -> None: + for kind in ("module", "importmap", "speculationrules"): + with self.subTest(kind): + html = f'' + findings = self.run_gate({"index.html": html}, ["'self'"]) + self.assertEqual(len(findings), 1) def test_a_script_url_needs_its_origin_named(self) -> None: own = '' From b6371209299c30d2b19e937f6c01240e611f4c88 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 21:26:58 -0700 Subject: [PATCH 07/10] Read Built Pages Strictly and Name the Script Host Form the Gate Reads Co-Authored-By: Claude Opus 5.5 --- checks/check-csp-scripts.py | 2 +- checks/tests/test_check_csp_scripts.py | 6 ++++-- deploy/README.md | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/checks/check-csp-scripts.py b/checks/check-csp-scripts.py index 0bb59cb3..83e0d306 100755 --- a/checks/check-csp-scripts.py +++ b/checks/check-csp-scripts.py @@ -112,7 +112,7 @@ def check(public, sources): for path in sorted(public.rglob("*.html")): rel = path.relative_to(public).as_posix() scan = ScriptScan() - scan.feed(path.read_text(encoding="utf-8", errors="replace")) + scan.feed(path.read_text(encoding="utf-8")) scan.close() findings += [f"{rel}: {finding}" for finding in scan.findings] findings += [ diff --git a/checks/tests/test_check_csp_scripts.py b/checks/tests/test_check_csp_scripts.py index be71dd84..4e53eb0e 100644 --- a/checks/tests/test_check_csp_scripts.py +++ b/checks/tests/test_check_csp_scripts.py @@ -141,8 +141,10 @@ def test_a_policy_the_caddyfile_sends_loads(self) -> None: self.assertEqual(self.load(held, sent), (blog, None)) def test_a_caddyfile_sending_another_value_refuses(self) -> None: - sent = f'header {{\n\tContent-Security-Policy "{policy("'self'")}"\n}}\n' - held = f"blog\tContent-Security-Policy: {policy("'self'", "'sha256-AAAA'")}\n" + sent_policy = policy("'self'") + held_policy = policy("'self'", "'sha256-AAAA'") + sent = f'header {{\n\tContent-Security-Policy "{sent_policy}"\n}}\n' + held = f"blog\tContent-Security-Policy: {held_policy}\n" loaded, refusal = self.load(held, sent) self.assertIsNone(loaded) self.assertIn("Caddyfile does not send", refusal or "") diff --git a/deploy/README.md b/deploy/README.md index 952ab330..e15bcf37 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -302,7 +302,7 @@ 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 added to the policy first, or the browser blocks it. 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 the policy first, or the browser blocks it. Write a script's host as `https://`, the one form 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 or theme update can change those scripts' bytes.** [`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. From 7773e40565a4c60f37d1bc4f081a01f5f26050b3 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 21:33:57 -0700 Subject: [PATCH 08/10] Name Theme Settings Among What Changes the Blog's Inline Scripts 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 e15bcf37..ba5a83a6 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -304,7 +304,7 @@ The HSTS value carries neither `includeSubDomains` nor `preload`. `includeSubDom **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://`, the one form 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 or theme update can change those scripts' bytes.** [`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. +**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. **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. From a7e9ea25a882aff6e83451513d3a9891c4824a91 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 21:46:02 -0700 Subject: [PATCH 09/10] Check Every Script Type a Browser Runs and Name the Proxy's Injected Scripts Co-Authored-By: Claude Opus 5.5 --- checks/check-csp-scripts.py | 20 +++++++++++++++----- checks/tests/test_check_csp_scripts.py | 9 +++++++-- deploy/README.md | 2 ++ 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/checks/check-csp-scripts.py b/checks/check-csp-scripts.py index 83e0d306..a7614877 100755 --- a/checks/check-csp-scripts.py +++ b/checks/check-csp-scripts.py @@ -7,9 +7,10 @@ must match an inline script. A Hugo or theme update that changes a script's bytes then fails here rather than in a reader's browser. A script loaded by URL must come from an origin the policy names. An inline event handler or a `javascript:` URL fails outright, since a hash allows -neither without `'unsafe-hashes'`, which the blog policy does not carry. An import map and a -speculation rules block are checked like a script. Any other type is a data block that never -runs, and the browser never checks an empty script, so neither needs a hash. +neither without `'unsafe-hashes'`, which the blog policy does not carry. A script whose type the +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. """ import argparse @@ -29,10 +30,19 @@ SCRIPT_TYPES = { "", "module", - "text/javascript", - "application/javascript", "importmap", "speculationrules", + "application/ecmascript", + "application/javascript", + "application/x-ecmascript", + "application/x-javascript", + "text/ecmascript", + "text/javascript", + *(f"text/javascript1.{minor}" for minor in range(6)), + "text/jscript", + "text/livescript", + "text/x-ecmascript", + "text/x-javascript", } diff --git a/checks/tests/test_check_csp_scripts.py b/checks/tests/test_check_csp_scripts.py index 4e53eb0e..ebe6b802 100644 --- a/checks/tests/test_check_csp_scripts.py +++ b/checks/tests/test_check_csp_scripts.py @@ -73,8 +73,13 @@ def test_data_blocks_and_empty_scripts_are_not_checked(self) -> None: ) self.assertEqual(self.run_gate({"index.html": html}, ["'self'"]), []) - def test_modules_import_maps_and_speculation_rules_are_checked(self) -> None: - for kind in ("module", "importmap", "speculationrules"): + def test_every_type_the_browser_runs_is_checked(self) -> None: + for kind in ( + "module", + "importmap", + "speculationrules", + "Application/X-JavaScript", + ): with self.subTest(kind): html = f'' findings = self.run_gate({"index.html": html}, ["'self'"]) diff --git a/deploy/README.md b/deploy/README.md index ba5a83a6..1ef7e29d 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -306,6 +306,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 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. ## Trusting the proxy From 0df172fc6b9c6574c20ead11e89a629fbc75831e Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 21:56:16 -0700 Subject: [PATCH 10/10] Name the CSP Gate Beside the URL Parity Check Wherever It Is Run Co-Authored-By: Claude Opus 5.5 --- .vscode/tasks.json | 13 ++++++++++++- CONTENT.md | 2 ++ README.md | 3 ++- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 074b96da..4b3a34f5 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -63,6 +63,16 @@ "dependsOn": "Build: Site", "problemMatcher": [] }, + { + "label": "Check: CSP Scripts", + "type": "process", + "command": "checks/check-csp-scripts.py", + "args": [ + "public" + ], + "dependsOn": "Build: Site", + "problemMatcher": [] + }, { "label": "Clean Compile", "dependsOrder": "sequence", @@ -71,7 +81,8 @@ "Lint: Spelling", "Lint: Shell", "Lint: Shell Format", - "Check: URL Parity" + "Check: URL Parity", + "Check: CSP Scripts" ], "problemMatcher": [] } diff --git a/CONTENT.md b/CONTENT.md index 4ead3e5e..02c4d456 100644 --- a/CONTENT.md +++ b/CONTENT.md @@ -192,6 +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-live-urls.sh` | yes, against a running server | | markdownlint | no, `content/.markdownlint-cli2.jsonc` ignores the tree | | CSpell | no, `cspell.json` ignores the tree | @@ -210,6 +211,7 @@ A fact in a published post that proves wrong is corrected in the post. It is not [checks]: ./checks/ [codestyle]: ./CODESTYLE.md +[csp-scripts]: ./checks/check-csp-scripts.py [operations]: ./OPERATIONS.md [metadata]: ./checks/check-media-metadata.py [normalize]: ./scripts/normalize-media.py diff --git a/README.md b/README.md index d9d34a9b..4e017191 100644 --- a/README.md +++ b/README.md @@ -189,11 +189,12 @@ 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: +Build the site and verify it against the URL contract and the blog's script policy: ```sh hugo --gc --minify --panicOnWarning checks/check-url-parity.py public +checks/check-csp-scripts.py public ``` Build a release and verify it against a running server: