From df4fa8967af21bed98d3b80378ecf7f81efd7916 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 10:04:10 -0700 Subject: [PATCH 01/10] Assert the Security Headers on Every Response the Live Check Reads The live check read no security header, so a Caddyfile edit that dropped one passed every gate. Each response it already requests now carries the exact values in checks/security-headers.txt, which a unit case holds to the Caddyfile. One missing .png probes the handle_errors route, at the cost of a static request rather than a page. The preflight and the family pages also print whether the run reached the Cloudflare edge, which replaces the hand probe in OPERATIONS.md. Co-Authored-By: Claude Opus 5.5 --- OPERATIONS.md | 13 +- checks/README.md | 9 ++ checks/check-live-urls.sh | 88 +++++++++-- checks/security-headers.txt | 7 + checks/tests/test_check_live_urls_sample.py | 162 +++++++++++++++++++- deploy/README.md | 3 + 6 files changed, 255 insertions(+), 27 deletions(-) create mode 100644 checks/security-headers.txt diff --git a/OPERATIONS.md b/OPERATIONS.md index 64fb6b55..b83f55a9 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -90,7 +90,7 @@ Sourcing the environment file first puts the deploy root and the base URL in the It refuses to install a release that fails the build gate. `check-live-urls.sh` does take a base URL, which is where the sourced `$SITE_BASE_URL` goes. It follows every URL in the contract against the running mirror, checking each redirect's destination rather than trusting its status code. -Expect a `PASS` naming the number of URLs honored. That is the three lists' combined length, plus the family pages where `SITE_EXTRA_BASE_URL` is set. Anything less is a finding, and the output names each URL that failed and what it answered. +Expect a `PASS` naming the number of URLs honored. That is the three lists' combined length, plus the family pages where `SITE_EXTRA_BASE_URL` is set, plus the one missing file that must answer `404`. Every response must also carry the security headers in [`checks/security-headers.txt`](./checks/security-headers.txt) with their exact values. Anything less is a finding, and the output names each URL that failed and what it answered. 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. @@ -129,16 +129,9 @@ The deploy root and the base URL are the only host-specific values. A local run **A VPS release is named by its deploy run, never by a commit.** The hub's deploy task names each release `--` and verifies the site against that id itself. To check a VPS site by hand afterwards, pass that id as `EXPECT_RELEASE`. Read it from the **Deploy site job**'s log, where `make-release.sh` prints `==> installing release ` with the id ending in the run's own id and attempt. The Validate sources job prints the same line earlier in the run, for a scratch bundle stamped with a bare timestamp, so the first match of a log search is the wrong id. Never copy it from the site's `X-Blog-Release` header, since a stale config still serves the previous id and the check would then pass against it. A short SHA never matches, so the check waits out its timeout and fails. -**Production's deploy checks a sample of the contract, and every other run checks all of it.** The production edge bans a client that requests more than 40 distinct pages in a burst. It also bans one when more than 10 distinct pages answer `404`, `403` or `400`. A full run from the GitHub runner therefore gets it banned. The deploy hook sets `SAMPLE_CONTRACT=1` for `production` alone, and the check then requests one URL from each class. That covers each redirect class, each shape of page that must render, each media tree, and the family pages. It also covers `/all/`, `/feed.xml`, and `/sitemap.xml`, the fixed redirect destinations no list names. The script holds that to 30 distinct pages at most, and none is expected to answer an error. Staging and the local mirrors keep the whole contract, which is where it is proven. **A hand run against the VPS production site sets `SAMPLE_CONTRACT=1` too**, for the same reason the hook does. The local production mirror sits behind no such edge and keeps the whole contract. `checks/check-live-urls.sh --print-sample` lists what a sampled run requests without requesting anything. [`deploy/README.md`](./deploy/README.md#environment-variables) carries the budget. +**Production's deploy checks a sample of the contract, and every other run checks all of it.** The production edge bans a client that requests more than 40 distinct pages in a burst. It also bans one when more than 10 distinct pages answer `404`, `403` or `400`. A full run from the GitHub runner therefore gets it banned. The deploy hook sets `SAMPLE_CONTRACT=1` for `production` alone, and the check then requests one URL from each class. That covers each redirect class, each shape of page that must render, each media tree, and the family pages. It also covers `/all/`, `/feed.xml`, and `/sitemap.xml`, the fixed redirect destinations no list names. The script holds that to 30 distinct pages at most, and none is expected to answer an error. Its one `404` is a missing `.png`, which the edge counts as a static request rather than a page. Staging and the local mirrors keep the whole contract, which is where it is proven. **A hand run against the VPS production site sets `SAMPLE_CONTRACT=1` too**, for the same reason the hook does. The local production mirror sits behind no such edge and keeps the whole contract. `checks/check-live-urls.sh --print-sample` lists what a sampled run requests without requesting anything. [`deploy/README.md`](./deploy/README.md#environment-variables) carries the budget. -**A hand run counts as measured through Cloudflare only once the target answers `server: cloudflare` with a `cf-ray` header.** Right after a hostname flips to proxied, the resolver on the machine running the check can keep answering with the origin for minutes. Another resolver can already answer with Cloudflare by then. A run in that window measures the origin directly. Before the run, check every host it reaches from the same machine, the family host included, and go ahead only when each prints `proxied`: - -```sh -for host in ; do - h=$(curl -q -sSI "https://$host/") - if printf '%s\n' "$h" | grep -qi '^server: cloudflare' && printf '%s\n' "$h" | grep -qi '^cf-ray:'; then echo "$host proxied"; else echo "$host UNCONFIRMED"; fi -done -``` +**A hand run counts as measured through Cloudflare only once every host it reaches prints ` proxied`.** The check prints a verdict for the base host after its preflight and for the family host after its pages. It prints `proxied` only when the response carries `server: cloudflare` with a `cf-ray` header. Right after a hostname flips to proxied, the resolver on the machine running the check can keep answering with the origin for minutes. Another resolver can already answer with Cloudflare by then. A run in that window prints ` UNCONFIRMED` and measured the origin directly, so run it again once the resolver catches up. **Always set `SITE_BASE_URL` for anything that is not production.** The base URL is baked into the canonical tag, the feed links, and every absolute permalink, so a mirror built without it serves pages that all point back at the production address. Nothing downstream catches this, because the pages render at the right paths and the build gate passes. `make-release.sh` bridges it to Hugo's own `HUGO_BASEURL` internally, and the effective value is printed on every build for that reason. diff --git a/checks/README.md b/checks/README.md index 6db6d13f..82dd2f13 100644 --- a/checks/README.md +++ b/checks/README.md @@ -107,6 +107,14 @@ wc -l checks/golden-urls.txt checks/redirect-urls.txt checks/golden-media-legacy **The mode case is why this is not theoretical.** A hard-linked file carries its inode's mode, so a media file that acquires a bad one rides the chain into every later release, present and correctly named and unreadable to the server. A build-time `is_file()` on the runner cannot see it, and neither can a check that never requests an image. +## `security-headers.txt`, and why every response's headers are read + +`security-headers.txt` holds, per site, each security header `deploy/Caddyfile` sends and its exact value. `check-live-urls.sh` reads it and asserts those headers on every response it already requests: the preflight, each page, redirect, and media file, and each family page. A header that goes missing or loses strength fails the run, where a presence check would pass a shortened HSTS lifetime or a loosened policy. + +**One request is added, a missing `.png` under `/media/`.** The `404` answers from the Caddyfile's `handle_errors` block rather than from the route every other request takes, so it is checked on its own. Being a static file, it stays out of the sampled run's page budget. + +**The values live once here, and a unit case holds them to the Caddyfile.** `checks/tests/test_check_live_urls_sample.py` reads each site block's security headers and fails when they differ from this file in either direction. A header added to the Caddyfile is therefore added here too. See [`deploy/README.md`][deploy-readme-security-headers] for why each value is what it is. + ## Directionality The parity check fails on a **missing** URL and only notes an **extra** one. New posts, new tags, and deeper pagination legitimately add URLs, and nothing legitimately removes a URL the site has served. That asymmetry is what makes the lists append-only, which in turn is what makes the length-floor assertion in `check-live-urls.sh` sound: without it a truncated list would make every assertion below it pass vacuously. @@ -184,4 +192,5 @@ Three traps in that adjudication, each of which produced a wrong answer first an [check-text-pii]: ./check-text-pii.py [check-url-parity]: ./check-url-parity.py [deploy-readme-redirects]: ../deploy/README.md#how-the-redirects-are-expressed +[deploy-readme-security-headers]: ../deploy/README.md#security-headers [fuzz-media-parsers]: ./fuzz-media-parsers.py diff --git a/checks/check-live-urls.sh b/checks/check-live-urls.sh index a3e77dcf..261067a0 100755 --- a/checks/check-live-urls.sh +++ b/checks/check-live-urls.sh @@ -62,6 +62,22 @@ SAMPLE_MAX_PATHS=30 SAMPLE_MAX_STATICS=8 # Pages only a redirect reaches, so no list names them and a sampled redirect never requests them. SAMPLE_DESTINATIONS=(/all/ /feed.xml /sitemap.xml) +# The 404 answers from handle_errors rather than the route every other request takes. +# A missing file of a static type keeps the probe out of the page budget. +MISSING_PROBE=/media/live-check-missing.png + +# A unit case holds these equal to deploy/Caddyfile, so a weakened value fails as well as a missing one. +SECURITY_HEADERS=$(awk -F'\t' '$1 == "blog" { print $2 }' "$CHECKS/security-headers.txt") +FAMILY_SECURITY_HEADERS=$(awk -F'\t' '$1 == "family" { print $2 }' "$CHECKS/security-headers.txt") +if [ -z "$SECURITY_HEADERS" ] || [ -z "$FAMILY_SECURITY_HEADERS" ]; then + echo "FAIL security-headers.txt: no headers for one site at $CHECKS/security-headers.txt" >&2 + exit 1 +fi +# One curl -w line per header, in the list's order, so a compliant response reads back as the list itself. +HEADER_FORMAT='' +while IFS= read -r line; do + HEADER_FORMAT+="${line%%: *}: %header{${line%%: *}}\n" +done <<<"$SECURITY_HEADERS" # Each classifier sets CLASS rather than printing it, since a subshell per URL costs seconds across the redirect list. # The redirect classes are the rows of deploy/README.md's table, with the map shapes last, since a bare .html test would claim two Blogger rows. @@ -178,9 +194,10 @@ if [ -n "$SAMPLE" ]; then done # The budget counts distinct non-static paths per host, which is never less than the edge counts, with the preflight's / among them. + # The 404 probe is the first static request. # A sampled redirect is not followed, so each costs one path, and a legacy media URL costs two requests, since it takes a hop. declare -A sample_paths=(["blog /"]=1) - sample_statics=0 + sample_statics=1 for entry in "${SAMPLE_PLAN[@]}"; do IFS=$'\t' read -r kind class _ url <<<"$entry" case "$kind" in @@ -380,6 +397,20 @@ curl_retry() { return "$rc" } +# Invoked indirectly, the same way as curl_retry above. +# shellcheck disable=SC2329 +# Reads a response's "Name: value" lines, either a header dump or HEADER_FORMAT's output, which matches the list outright when nothing is wrong. +check_headers() { + local what="$1" response="$2" expected="$3" line name want got + [ "$response" = "$expected" ] && return + while IFS= read -r line; do + name="${line%%: *}" + want="${line#*: }" + got=$(printf '%s\n' "$response" | grep -i "^$name:" | tr -d '\r' | sed 's/^[^:]*: *//' | paste -sd ',' -) + [ "$got" = "$want" ] || echo "$what sends $name '${got:-}', expected '$want'" >>"$FAILED" + done <<<"$expected" +} + # Invoked indirectly, the same way as curl_retry above. # shellcheck disable=SC2329 transfer_failure() { @@ -394,15 +425,20 @@ transfer_failure() { # Invoked indirectly, the same way as curl_retry above. # shellcheck disable=SC2329 check_render() { - local url="$1" code why rc=0 auth=(-K "$CHECKRC") + local url="$1" out code why rc=0 auth=(-K "$CHECKRC") [ -n "$CURLRC" ] && auth+=(-K "$CURLRC") - code=$(curl_retry -q -s -o /dev/null -w '%{http_code}' --max-time 30 "${auth[@]}" "$BASE$url") || rc=$? + out=$(curl_retry -q -s -o /dev/null -w "%{http_code}\n$HEADER_FORMAT" --max-time 30 "${auth[@]}" "$BASE$url") || rc=$? + code="${out%%$'\n'*}" why=$(transfer_failure "$code" "$rc") if [ -n "$why" ]; then echo "render $url $why" >>"$FAILED" return fi - [ "$code" = "200" ] || echo "render $url expected 200, got $code" >>"$FAILED" + if [ "$code" != "200" ]; then + echo "render $url expected 200, got $code" >>"$FAILED" + return + fi + check_headers "render $url" "${out#*$'\n'}" "$SECURITY_HEADERS" } # A caching proxy may answer a media URL from its copy for the file's lifetime, so a file a release lost would still pass. @@ -421,7 +457,7 @@ check_media() { local url="$1" what="media $1" out code len target type why rc=0 auth=(-K "$CHECKRC") target_auth=(-K "$CHECKRC") [ -n "$CURLRC" ] && auth+=(-K "$CURLRC") # The redirect URL gets a line of its own, because an empty one would let read shift the type into its place. - local format='%{http_code} %{size_download}\n%{redirect_url}\n%{content_type}\n' + local format="%{http_code} %{size_download}\n%{redirect_url}\n%{content_type}\n$HEADER_FORMAT" # Command substitution rather than `read < <(...)`, because process substitution discards curl's exit status. out=$(curl_retry -q -s -o /dev/null -w "$format" --max-time 30 "${auth[@]}" "$BASE$url?$CACHE_BUST") || rc=$? { @@ -442,6 +478,7 @@ check_media() { echo "$what answered $code with no usable Location" >>"$FAILED" return fi + check_headers "$what" "${out#*$'\n'*$'\n'*$'\n'}" "$SECURITY_HEADERS" # Same origin boundary as check_redirect, and for the same reason: a rule that one day points off-site must not mail the token there. # A bare prefix would also accept a lookalike host registered as an attacker's subdomain. if [ -n "$CURLRC" ]; then @@ -478,6 +515,7 @@ check_media() { image/*) ;; *) echo "$what answered 200 as $type, expected an image" >>"$FAILED" ;; esac + check_headers "$what" "${out#*$'\n'*$'\n'*$'\n'}" "$SECURITY_HEADERS" } # Invoked indirectly, the same way as check_render above. @@ -486,7 +524,7 @@ check_redirect() { local url="$1" out code dest dcode why rc=0 auth=(-K "$CHECKRC") dest_auth=(-K "$CHECKRC") [ -n "$CURLRC" ] && auth+=(-K "$CURLRC") # One request reads both fields, so a second fetch failing in transit cannot pass an empty destination on as a broken target. - out=$(curl_retry -q -s -o /dev/null -w '%{http_code} %{redirect_url}\n' --max-time 30 "${auth[@]}" "$BASE$url") || rc=$? + out=$(curl_retry -q -s -o /dev/null -w "%{http_code} %{redirect_url}\n$HEADER_FORMAT" --max-time 30 "${auth[@]}" "$BASE$url") || rc=$? read -r code dest <<<"$out" why=$(transfer_failure "$code" "$rc") if [ -n "$why" ]; then @@ -504,6 +542,7 @@ check_redirect() { echo "redirect $url answered $code with no usable Location" >>"$FAILED" return fi + check_headers "redirect $url" "${out#*$'\n'}" "$SECURITY_HEADERS" # A sampled run proves the rule fired and leaves the destination to the full contract, since following would take it past its budget. [ -n "$SAMPLE" ] && return # A redirect to a 404 is a broken redirect, so the destination is followed rather than trusted. @@ -529,8 +568,8 @@ check_redirect() { esac } -export -f curl_retry transfer_failure check_render check_redirect check_media -export BASE FAILED CURLRC CHECKRC SAMPLE CACHE_BUST +export -f curl_retry transfer_failure check_headers check_render check_redirect check_media +export BASE FAILED CURLRC CHECKRC SAMPLE CACHE_BUST HEADER_FORMAT SECURITY_HEADERS echo "==> $BASE" @@ -626,6 +665,19 @@ elif [ -n "$got_release" ]; then echo "==> rules from release $got_release" fi +# A resolver can keep answering with the origin for minutes after a name flips, and only the edge sends both headers. +# Pattern matching rather than grep -q, which can stop reading before printf finishes and fail the pipeline. +proxy_verdict() { + local h="${2,,}" + if [[ $h == *$'\n'"server: cloudflare"* && $h == *$'\n'"cf-ray:"* ]]; then + echo "==> $1 proxied" + else + echo "==> $1 UNCONFIRMED, so this run reached the origin rather than the edge" + fi +} +proxy_verdict "${BASE#*://}" "$preflight_headers" +check_headers "preflight $BASE/" "$preflight_headers" "$SECURITY_HEADERS" + n_render=$(grep -c . "$RENDER_SRC") echo "==> checking $n_render URLs that must render" grep . "$RENDER_SRC" | xargs -P "$PARALLEL" -I{} bash -c 'check_render "$@"' _ {} @@ -638,6 +690,20 @@ n_media=$(grep -c . "$MEDIA_SRC") echo "==> checking $n_media media URLs that must be served as images" grep . "$MEDIA_SRC" | xargs -P "$PARALLEL" -I{} bash -c 'check_media "$@"' _ {} +n_missing=1 +echo "==> checking that a missing file answers 404 with the security headers" +rc=0 +out=$(curl_retry -q -s -o /dev/null -w "%{http_code}\n$HEADER_FORMAT" --max-time 30 "${AUTH[@]}" "$BASE$MISSING_PROBE?$CACHE_BUST") || rc=$? +code="${out%%$'\n'*}" +why=$(transfer_failure "$code" "$rc") +if [ -n "$why" ]; then + echo "missing $MISSING_PROBE $why" >>"$FAILED" +elif [ "$code" != "404" ]; then + echo "missing $MISSING_PROBE expected 404, got $code" >>"$FAILED" +else + check_headers "missing $MISSING_PROBE" "${out#*$'\n'}" "$SECURITY_HEADERS" +fi + # The title tells the family page from the blog, since one container answers both and an unknown host falls through to the blog with a 200. # X-Blog-Env still tells one environment from another, and the family host is a proxy rule of its own that can aim at the wrong container. # Sending no Accept-Language keeps / from redirecting to /af/. @@ -673,8 +739,10 @@ if [ -n "$FAMILY_BASE" ]; then if [ -n "${EXPECT_RELEASE:-}" ] && [ "$family_release" != "$EXPECT_RELEASE" ]; then echo "family $page_path is from release '${family_release:-}', expected '$EXPECT_RELEASE'" >>"$FAILED" fi + check_headers "family $page_path" "$(<"$FAMILY_HEAD")" "$FAMILY_SECURITY_HEADERS" fi done + [ -s "$FAMILY_HEAD" ] && proxy_verdict "${FAMILY_BASE#*://}" "$(<"$FAMILY_HEAD")" else echo "==> SITE_EXTRA_BASE_URL is unset, so the family site is not checked" fi @@ -683,12 +751,12 @@ fi # Swallowing only the exit status keeps the printed count usable. failures=$(grep -c . "$FAILED" 2>/dev/null || true) if [ "$failures" -eq 0 ]; then - echo "PASS - $((n_render + n_redirect + n_media + n_family)) ${SAMPLE:+sampled }URLs honored" + echo "PASS - $((n_render + n_redirect + n_media + n_family + n_missing)) ${SAMPLE:+sampled }URLs honored" exit 0 fi echo -echo "FAIL - $failures of $((n_render + n_redirect + n_media + n_family)) ${SAMPLE:+sampled }URLs" +echo "FAIL - $failures findings across $((n_render + n_redirect + n_media + n_family + n_missing)) ${SAMPLE:+sampled }URLs" sort "$FAILED" | head -40 [ "$failures" -gt 40 ] && echo "... and $((failures - 40)) more" exit 1 diff --git a/checks/security-headers.txt b/checks/security-headers.txt new file mode 100644 index 00000000..d6244440 --- /dev/null +++ b/checks/security-headers.txt @@ -0,0 +1,7 @@ +blog Strict-Transport-Security: max-age=31536000 +blog X-Content-Type-Options: nosniff +blog Referrer-Policy: strict-origin-when-cross-origin +family Strict-Transport-Security: max-age=31536000 +family X-Content-Type-Options: nosniff +family Referrer-Policy: strict-origin-when-cross-origin +family Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; connect-src 'self' https://fonts.googleapis.com https://fonts.gstatic.com; script-src 'self'; img-src 'self' data: diff --git a/checks/tests/test_check_live_urls_sample.py b/checks/tests/test_check_live_urls_sample.py index 6adfb07b..b2388f43 100644 --- a/checks/tests/test_check_live_urls_sample.py +++ b/checks/tests/test_check_live_urls_sample.py @@ -10,15 +10,17 @@ import tempfile import threading import unittest -from typing import ClassVar, Self +from typing import ClassVar, Self, cast CHECKS = pathlib.Path(__file__).resolve().parent.parent SCRIPT = CHECKS / "check-live-urls.sh" README = CHECKS.parent / "deploy" / "README.md" +CADDYFILE = CHECKS.parent / "deploy" / "Caddyfile" LISTS = ( "golden-urls.txt", "redirect-urls.txt", "golden-media-live.txt", + "security-headers.txt", ) # The edge's crawl scenario overflows past 40 distinct paths, and the sample keeps a margin under it. @@ -36,6 +38,20 @@ MEDIA_CLASSES = {"media", "external", "legacy upload"} FAMILY_PAGES = {"/", "/en/", "/af/"} DESTINATION = "/followed-destination/" +MISSING_PROBE = "/media/live-check-missing.png" + + +def expected_headers(site: str) -> list[tuple[str, str]]: + """The (name, value) pairs security-headers.txt holds for one site, in file order.""" + pairs = [] + for line in ( + (CHECKS / "security-headers.txt").read_text(encoding="utf-8").splitlines() + ): + row_site, header = line.split("\t", 1) + if row_site == site: + name, value = header.split(": ", 1) + pairs.append((name, value)) + return pairs def clean_env(**extra: str) -> dict[str, str]: @@ -185,10 +201,17 @@ class Handler(http.server.BaseHTTPRequestHandler): redirects: ClassVar[set[str]] = set() requested: ClassVar[list[str]] = [] page: ClassVar[bytes] = b"" + site_headers: ClassVar[list[tuple[str, str]]] = [] + + def headers_for(self, path: str) -> list[tuple[str, str]]: + """The headers this response carries, which a test narrows for one path.""" + return self.site_headers def do_GET(self) -> None: self.requested.append(self.path) - if self.path.startswith("/wp-content/uploads/"): + if self.path.split("?", 1)[0] == MISSING_PROBE: + self.answer(404, body=b"", content_type="text/html") + elif self.path.startswith("/wp-content/uploads/"): # Caddy's rule drops the query, as here. path = self.path.split("?", 1)[0] self.answer(301, location="/media/" + path.split("/uploads/", 1)[1]) @@ -203,6 +226,8 @@ def answer( self, code: int, location: str = "", body: bytes = b"", content_type: str = "" ) -> None: self.send_response(code) + for name, value in self.headers_for(self.path): + self.send_header(name, value) if location: self.send_header("Location", location) if content_type: @@ -225,15 +250,23 @@ def family_page() -> bytes: class MockSite: - def __init__(self, page: bytes = Handler.page) -> None: + def __init__( + self, + page: bytes = Handler.page, + site: str = "blog", + handler: type[Handler] = Handler, + ) -> None: self.page = page + self.headers = expected_headers(site) + self.base_handler = handler def __enter__(self) -> Self: redirects = (CHECKS / "redirect-urls.txt").read_text(encoding="utf-8").split() - class SiteHandler(Handler): - pass - + SiteHandler = cast( + "type[Handler]", type("SiteHandler", (self.base_handler,), {}) + ) + SiteHandler.site_headers = self.headers SiteHandler.redirects = set(redirects) SiteHandler.requested = [] SiteHandler.page = self.page @@ -265,7 +298,7 @@ def test_sampled_run_requests_exactly_the_planned_paths(self) -> None: planned = {"/"} | { url for kind, _, _, url in entries if kind in ("render", "redirect") } - with MockSite() as site, MockSite(family_page()) as family: + with MockSite() as site, MockSite(family_page(), "family") as family: result = run( SCRIPT, site.base, @@ -316,5 +349,120 @@ def test_media_requests_carry_a_query_no_earlier_run_sent(self) -> None: self.assertNotEqual(tokens[0], tokens[1]) +SECURITY_NAMES = { + "content-security-policy", + "content-security-policy-report-only", + "cross-origin-embedder-policy", + "cross-origin-opener-policy", + "cross-origin-resource-policy", + "permissions-policy", + "referrer-policy", + "strict-transport-security", + "x-content-type-options", + "x-frame-options", +} + + +def caddyfile_headers(block: str) -> list[tuple[str, str]]: + """The security headers a Caddyfile site block sets, in either the block or the one-line form.""" + pairs = [] + for line in block.splitlines(): + match = re.fullmatch(r'\s*(?:header\s+(?:@\S+\s+)?)?(\S+)\s+"([^"]*)"\s*', line) + if match and match[1].lower() in SECURITY_NAMES: + pairs.append((match[1], match[2])) + return pairs + + +def without(name: str, target: str) -> type[Handler]: + """A handler that leaves one header off the responses to one path, the query ignored.""" + + class Omitting(Handler): + def headers_for(self, path: str) -> list[tuple[str, str]]: + if path.split("?", 1)[0] != target: + return self.site_headers + return [(n, v) for n, v in self.site_headers if n != name] + + return Omitting + + +class SecurityHeaderTests(unittest.TestCase): + def test_expected_values_are_the_caddyfile_values(self) -> None: + text = CADDYFILE.read_text(encoding="utf-8") + blog, family = re.split(r"(?m)^http://viljoen\.family:8080", text, maxsplit=1) + self.assertEqual( + sorted(caddyfile_headers(blog)), sorted(expected_headers("blog")) + ) + self.assertEqual( + sorted(caddyfile_headers(family)), sorted(expected_headers("family")) + ) + + def sampled( + self, handler: type[Handler] = Handler, family: type[Handler] = Handler + ) -> subprocess.CompletedProcess[str]: + with ( + MockSite(handler=handler) as site, + MockSite(family_page(), "family", family) as fam, + ): + return run( + SCRIPT, site.base, SAMPLE_CONTRACT="1", SITE_EXTRA_BASE_URL=fam.base + ) + + def test_a_missing_header_fails_on_every_kind_of_response(self) -> None: + entries = plan() + first = {kind: url for kind, _, _, url in reversed(entries)} + hsts = "Strict-Transport-Security" + for what, path in ( + ("preflight", "/"), + ("render", first["render"]), + ("redirect", first["redirect"]), + ("media", first["media"]), + ("missing", MISSING_PROBE), + ): + with self.subTest(what): + result = self.sampled(handler=without(hsts, path)) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertRegex( + result.stdout, + rf"{what} \S*{re.escape(path)}\S* sends {hsts} ''", + ) + csp = "Content-Security-Policy" + result = self.sampled(family=without(csp, "/en/")) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertIn(f"family /en/ sends {csp} ''", result.stdout) + + def test_a_weakened_value_fails(self) -> None: + class Weakened(Handler): + def headers_for(self, path: str) -> list[tuple[str, str]]: + return [ + (n, "max-age=60" if n == "Strict-Transport-Security" else v) + for n, v in self.site_headers + ] + + result = self.sampled(handler=Weakened) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertIn( + "sends Strict-Transport-Security 'max-age=60', expected 'max-age=31536000'", + result.stdout, + ) + + def test_a_compliant_run_names_each_host_unconfirmed_off_the_edge(self) -> None: + result = self.sampled() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stdout.count(" UNCONFIRMED, so this run reached"), 2) + + def test_both_edge_headers_read_as_proxied(self) -> None: + class Edge(Handler): + def version_string(self) -> str: + return "cloudflare" + + def headers_for(self, path: str) -> list[tuple[str, str]]: + return [*self.site_headers, ("CF-RAY", "0-TEST")] + + result = self.sampled(handler=Edge, family=Edge) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stdout.count(" proxied\n"), 2) + self.assertNotIn("UNCONFIRMED", result.stdout) + + if __name__ == "__main__": unittest.main() diff --git a/deploy/README.md b/deploy/README.md index e4b1c13a..9e9c3ada 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -302,6 +302,8 @@ The HSTS value carries neither `includeSubDomains` nor `preload`. `includeSubDom **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. +**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 A proxy fronts Caddy in every environment, so the peer address is always the proxy and the real @@ -442,6 +444,7 @@ Each of these fails silently when it fails, which is why it is checked rather th [capture-build-redirects]: ../capture/build-redirects.py [capture-readme]: ../capture/README.md [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 From 81788e45a234a9db2b3d2dbd2248b44651ce7253 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 10:13:49 -0700 Subject: [PATCH 02/10] Read the Headers After the Reload and on Followed Destinations The preflight assertion read the dump taken before the release wait, so a release that changed a header value failed against the previous config. The wait now refreshes the whole dump. A same-origin redirect destination is header-checked too, one header_value reader replaces the copies, and the Caddyfile test reads a bare value as well as a quoted one. Co-Authored-By: Claude Opus 5.5 --- checks/check-live-urls.sh | 41 +++++++++++---------- checks/tests/test_check_live_urls_sample.py | 29 ++++++++++++++- 2 files changed, 48 insertions(+), 22 deletions(-) diff --git a/checks/check-live-urls.sh b/checks/check-live-urls.sh index 261067a0..76a6749d 100755 --- a/checks/check-live-urls.sh +++ b/checks/check-live-urls.sh @@ -397,6 +397,10 @@ curl_retry() { return "$rc" } +# Invoked indirectly, the same way as curl_retry above. +# shellcheck disable=SC2329 +header_value() { printf '%s\n' "$1" | grep -i "^$2:" | tr -d '\r' | sed 's/^[^:]*: *//'; } + # Invoked indirectly, the same way as curl_retry above. # shellcheck disable=SC2329 # Reads a response's "Name: value" lines, either a header dump or HEADER_FORMAT's output, which matches the list outright when nothing is wrong. @@ -406,7 +410,7 @@ check_headers() { while IFS= read -r line; do name="${line%%: *}" want="${line#*: }" - got=$(printf '%s\n' "$response" | grep -i "^$name:" | tr -d '\r' | sed 's/^[^:]*: *//' | paste -sd ',' -) + got=$(header_value "$response" "$name" | paste -sd ',' -) [ "$got" = "$want" ] || echo "$what sends $name '${got:-}', expected '$want'" >>"$FAILED" done <<<"$expected" } @@ -521,7 +525,7 @@ check_media() { # Invoked indirectly, the same way as check_render above. # shellcheck disable=SC2329 check_redirect() { - local url="$1" out code dest dcode why rc=0 auth=(-K "$CHECKRC") dest_auth=(-K "$CHECKRC") + local url="$1" out code dest dout dcode why rc=0 auth=(-K "$CHECKRC") dest_auth=(-K "$CHECKRC") [ -n "$CURLRC" ] && auth+=(-K "$CURLRC") # One request reads both fields, so a second fetch failing in transit cannot pass an empty destination on as a broken target. out=$(curl_retry -q -s -o /dev/null -w "%{http_code} %{redirect_url}\n$HEADER_FORMAT" --max-time 30 "${auth[@]}" "$BASE$url") || rc=$? @@ -555,7 +559,8 @@ check_redirect() { esac fi rc=0 - dcode=$(curl_retry -q -s -o /dev/null -w '%{http_code}' --max-time 30 "${dest_auth[@]}" "$dest") || rc=$? + dout=$(curl_retry -q -s -o /dev/null -w "%{http_code}\n$HEADER_FORMAT" --max-time 30 "${dest_auth[@]}" "$dest") || rc=$? + dcode="${dout%%$'\n'*}" why=$(transfer_failure "$dcode" "$rc") if [ -n "$why" ]; then echo "redirect $url -> $dest destination $why" >>"$FAILED" @@ -566,9 +571,13 @@ check_redirect() { 200 | 301 | 308) ;; *) echo "redirect $url -> $dest destination answered $dcode" >>"$FAILED" ;; esac + # An off-site destination is the family host, whose own pages are checked against its own list. + case "$dest" in + "$BASE" | "$BASE"/*) check_headers "redirect $url -> $dest destination" "${dout#*$'\n'}" "$SECURITY_HEADERS" ;; + esac } -export -f curl_retry transfer_failure check_headers check_render check_redirect check_media +export -f curl_retry transfer_failure header_value check_headers check_render check_redirect check_media export BASE FAILED CURLRC CHECKRC SAMPLE CACHE_BUST HEADER_FORMAT SECURITY_HEADERS echo "==> $BASE" @@ -582,7 +591,7 @@ if ! preflight_headers=$(curl -q -sS -o /dev/null -D- -w '%{http_code}' --max-ti exit 1 fi preflight="${preflight_headers##*$'\n'}" -header_of() { printf '%s' "$preflight_headers" | grep -i "^$1:" | tr -d '\r' | sed 's/^[^:]*: *//'; } +header_of() { header_value "$preflight_headers" "$1"; } if [ "$preflight" != "200" ]; then echo "FAIL preflight: $BASE/ answered $preflight, expected 200" >&2 @@ -606,7 +615,7 @@ fi # Nothing in a response body says which environment answered. # A proxy rule aimed at the wrong container returns a healthy 200 under the right hostname. if [ -n "${EXPECT_SITE_ENV:-}" ]; then - got_env=$(printf '%s' "$preflight_headers" | grep -i '^x-blog-env:' | tr -d '\r' | sed 's/^[^:]*: *//') + got_env=$(header_of x-blog-env) if [ "$got_env" != "$EXPECT_SITE_ENV" ]; then echo "FAIL preflight: $BASE/ is served by '${got_env:-}', expected '$EXPECT_SITE_ENV'" >&2 echo " the hostname resolved to the wrong environment's container, or SITE_ENV is" >&2 @@ -618,17 +627,7 @@ fi # Nothing else proves the rules answering are the ones just shipped, as no deploy restarts Caddy. # A stale config serves the previous release's rules while the new content is already live. -# Returns non-zero on a transport failure, and empty on a reply carrying no release header. -# Collapsing the two would report an unreachable host as a config that never reloaded. -read_release() { - local headers - headers=$(curl -q -sS -o /dev/null -D- --max-time 30 "${AUTH[@]}" "$BASE/" 2>"$CURLERR") || return 1 - printf '%s' "$headers" | grep -i '^x-blog-release:' | tr -d '\r' | sed 's/^[^:]*: *//' - # Explicit, because pipefail carries grep's no-match status out of the function, which would report a reachable host serving no release header as unreachable. - return 0 -} - -got_release=$(printf '%s' "$preflight_headers" | grep -i '^x-blog-release:' | tr -d '\r' | sed 's/^[^:]*: *//') +got_release=$(header_of x-blog-release) if [ -n "${EXPECT_RELEASE:-}" ]; then # The reload is asynchronous, so a check run straight after a deploy races it. # Content is live instantly, while rules change on the next poll. @@ -637,11 +636,13 @@ if [ -n "${EXPECT_RELEASE:-}" ]; then while [ "$got_release" != "$EXPECT_RELEASE" ] && [ "$waited" -lt "${RELOAD_TIMEOUT:-30}" ]; do sleep 1 waited=$((waited + 1)) - if ! got_release=$(read_release); then + # The whole dump is refreshed, since the security headers asserted below come from the converged config too. + if ! preflight_headers=$(curl -q -sS -o /dev/null -D- --max-time 30 "${AUTH[@]}" "$BASE/" 2>"$CURLERR"); then echo "FAIL: $BASE/ became unreachable after ${waited}s of waiting for the reload" >&2 sed 's/^/ /' "$CURLERR" >&2 exit 1 fi + got_release=$(header_of x-blog-release) done if [ "$got_release" != "$EXPECT_RELEASE" ]; then echo "FAIL preflight: after ${waited}s the rules are from release '${got_release:-}', expected '$EXPECT_RELEASE'" >&2 @@ -731,8 +732,8 @@ if [ -n "$FAMILY_BASE" ]; then elif ! grep -qF "$title" "$FAMILY_BODY"; then echo "family $page_path answered without the title '$title', so another site served it" >>"$FAILED" else - got_env=$(grep -i '^x-blog-env:' "$FAMILY_HEAD" | tr -d '\r' | sed 's/^[^:]*: *//') - family_release=$(grep -i '^x-blog-release:' "$FAMILY_HEAD" | tr -d '\r' | sed 's/^[^:]*: *//') + got_env=$(header_value "$(<"$FAMILY_HEAD")" x-blog-env) + family_release=$(header_value "$(<"$FAMILY_HEAD")" x-blog-release) if [ -n "${EXPECT_SITE_ENV:-}" ] && [ "$got_env" != "$EXPECT_SITE_ENV" ]; then echo "family $page_path is served by '${got_env:-}', expected '$EXPECT_SITE_ENV'" >>"$FAILED" fi diff --git a/checks/tests/test_check_live_urls_sample.py b/checks/tests/test_check_live_urls_sample.py index b2388f43..0537cb05 100644 --- a/checks/tests/test_check_live_urls_sample.py +++ b/checks/tests/test_check_live_urls_sample.py @@ -367,9 +367,11 @@ def caddyfile_headers(block: str) -> list[tuple[str, str]]: """The security headers a Caddyfile site block sets, in either the block or the one-line form.""" pairs = [] for line in block.splitlines(): - match = re.fullmatch(r'\s*(?:header\s+(?:@\S+\s+)?)?(\S+)\s+"([^"]*)"\s*', line) + match = re.fullmatch( + r'\s*(?:header\s+(?:@\S+\s+)?)?(\S+)\s+(?:"([^"]*)"|([^\s"{]+))\s*', line + ) if match and match[1].lower() in SECURITY_NAMES: - pairs.append((match[1], match[2])) + pairs.append((match[1], match[2] if match[2] is not None else match[3])) return pairs @@ -430,6 +432,29 @@ def test_a_missing_header_fails_on_every_kind_of_response(self) -> None: self.assertEqual(result.returncode, 1, result.stdout) self.assertIn(f"family /en/ sends {csp} ''", result.stdout) + def test_a_bare_caddyfile_value_is_read(self) -> None: + block = "\theader {\n\t\tX-Frame-Options DENY\n\t}\n" + self.assertEqual(caddyfile_headers(block), [("X-Frame-Options", "DENY")]) + + def test_headers_are_asserted_on_the_config_the_reload_converges_on(self) -> None: + class Reloading(Handler): + def headers_for(self, path: str) -> list[tuple[str, str]]: + if self.requested.count("/") < 2: + return [("X-Blog-Release", "old")] + return [*self.site_headers, ("X-Blog-Release", "new")] + + with MockSite(handler=Reloading) as site: + result = run(SCRIPT, site.base, SAMPLE_CONTRACT="1", EXPECT_RELEASE="new") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("rules from release new (after 1s)", result.stdout) + + def test_a_followed_destination_missing_a_header_fails(self) -> None: + hsts = "Strict-Transport-Security" + with MockSite(handler=without(hsts, DESTINATION)) as site: + result = run(SCRIPT, site.base) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertIn(f"{DESTINATION} destination sends {hsts} ''", result.stdout) + def test_a_weakened_value_fails(self) -> None: class Weakened(Handler): def headers_for(self, path: str) -> list[tuple[str, str]]: From c9b4ecc70700f1e32721cdef355f15c857d6d776 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 10:22:27 -0700 Subject: [PATCH 03/10] Keep the Header Assertions to This Site's Responses A media hop to another host is no longer held to this site's list, a repeated header reads as its first instance on both read paths, as curl's %header{} does, and a matcher-scoped security header in the Caddyfile fails the sync test rather than being demanded on every response. The curl row in deploy/README.md names the 7.84 floor %header{} needs. Co-Authored-By: Claude Opus 5.5 --- checks/check-live-urls.sh | 8 +++++--- checks/tests/test_check_live_urls_sample.py | 16 +++++++++++++--- deploy/README.md | 2 +- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/checks/check-live-urls.sh b/checks/check-live-urls.sh index 76a6749d..8e62178c 100755 --- a/checks/check-live-urls.sh +++ b/checks/check-live-urls.sh @@ -410,7 +410,7 @@ check_headers() { while IFS= read -r line; do name="${line%%: *}" want="${line#*: }" - got=$(header_value "$response" "$name" | paste -sd ',' -) + got=$(header_value "$response" "$name" | head -n 1) [ "$got" = "$want" ] || echo "$what sends $name '${got:-}', expected '$want'" >>"$FAILED" done <<<"$expected" } @@ -519,7 +519,9 @@ check_media() { image/*) ;; *) echo "$what answered 200 as $type, expected an image" >>"$FAILED" ;; esac - check_headers "$what" "${out#*$'\n'*$'\n'*$'\n'}" "$SECURITY_HEADERS" + case "$target" in + '' | "$BASE" | "$BASE"/*) check_headers "$what" "${out#*$'\n'*$'\n'*$'\n'}" "$SECURITY_HEADERS" ;; + esac } # Invoked indirectly, the same way as check_render above. @@ -571,7 +573,7 @@ check_redirect() { 200 | 301 | 308) ;; *) echo "redirect $url -> $dest destination answered $dcode" >>"$FAILED" ;; esac - # An off-site destination is the family host, whose own pages are checked against its own list. + # An off-site destination is another site's, whose headers this list does not govern. case "$dest" in "$BASE" | "$BASE"/*) check_headers "redirect $url -> $dest destination" "${dout#*$'\n'}" "$SECURITY_HEADERS" ;; esac diff --git a/checks/tests/test_check_live_urls_sample.py b/checks/tests/test_check_live_urls_sample.py index 0537cb05..97533bde 100644 --- a/checks/tests/test_check_live_urls_sample.py +++ b/checks/tests/test_check_live_urls_sample.py @@ -368,10 +368,16 @@ def caddyfile_headers(block: str) -> list[tuple[str, str]]: pairs = [] for line in block.splitlines(): match = re.fullmatch( - r'\s*(?:header\s+(?:@\S+\s+)?)?(\S+)\s+(?:"([^"]*)"|([^\s"{]+))\s*', line + r'\s*(?:header\s+(@\S+\s+)?)?(\S+)\s+(?:"([^"]*)"|([^\s"{]+))\s*', line ) - if match and match[1].lower() in SECURITY_NAMES: - pairs.append((match[1], match[2] if match[2] is not None else match[3])) + if not match or match[2].lower() not in SECURITY_NAMES: + continue + if match[1]: + raise AssertionError( + f"{match[2]} is scoped to {match[1].strip()}, and the live check asserts" + " security headers on every response" + ) + pairs.append((match[2], match[3] if match[3] is not None else match[4])) return pairs @@ -436,6 +442,10 @@ def test_a_bare_caddyfile_value_is_read(self) -> None: block = "\theader {\n\t\tX-Frame-Options DENY\n\t}\n" self.assertEqual(caddyfile_headers(block), [("X-Frame-Options", "DENY")]) + def test_a_matcher_scoped_security_header_is_refused(self) -> None: + with self.assertRaisesRegex(AssertionError, "scoped to @page"): + caddyfile_headers('\theader @page Content-Security-Policy "x"\n') + def test_headers_are_asserted_on_the_config_the_reload_converges_on(self) -> None: class Reloading(Handler): def headers_for(self, path: str) -> list[tuple[str, str]]: diff --git a/deploy/README.md b/deploy/README.md index 9e9c3ada..f1d6b81c 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -12,7 +12,7 @@ How the site is built, released, and served. The release is a **self-contained b | `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` | `check-live-urls.sh` | verifying a running server | `apt install curl` | +| `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 | From 1fa0b4efb6ffebf085c236b1702fd24e6d065dc1 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 10:36:38 -0700 Subject: [PATCH 04/10] Follow Block Nesting When Reading the Caddyfile's Headers The sync case read each line alone, so a path matcher was skipped and a header inside a matcher-scoped block read as site-wide, and it reached only an allowlist of names. It now tokenizes each line, tracks the block a header sits in, reads every header a site sets on all responses apart from its cache headers and markers, and refuses any other header scoped to fewer responses. Co-Authored-By: Claude Opus 5.5 --- checks/README.md | 2 +- checks/tests/test_check_live_urls_sample.py | 71 +++++++++++++-------- 2 files changed, 47 insertions(+), 26 deletions(-) diff --git a/checks/README.md b/checks/README.md index 82dd2f13..be930e70 100644 --- a/checks/README.md +++ b/checks/README.md @@ -113,7 +113,7 @@ wc -l checks/golden-urls.txt checks/redirect-urls.txt checks/golden-media-legacy **One request is added, a missing `.png` under `/media/`.** The `404` answers from the Caddyfile's `handle_errors` block rather than from the route every other request takes, so it is checked on its own. Being a static file, it stays out of the sampled run's page budget. -**The values live once here, and a unit case holds them to the Caddyfile.** `checks/tests/test_check_live_urls_sample.py` reads each site block's security headers and fails when they differ from this file in either direction. A header added to the Caddyfile is therefore added here too. See [`deploy/README.md`][deploy-readme-security-headers] for why each value is what it is. +**The values live once here, and a unit case holds them to the Caddyfile.** `checks/tests/test_check_live_urls_sample.py` reads every header a site block sets on all its responses, apart from its cache headers and the site's own markers. It fails when those differ from this file in either direction, and when a security header is scoped to fewer responses. See [`deploy/README.md`][deploy-readme-security-headers] for why each value is what it is. ## Directionality diff --git a/checks/tests/test_check_live_urls_sample.py b/checks/tests/test_check_live_urls_sample.py index 97533bde..0a0c5a61 100644 --- a/checks/tests/test_check_live_urls_sample.py +++ b/checks/tests/test_check_live_urls_sample.py @@ -5,6 +5,7 @@ import os import pathlib import re +import shlex import shutil import subprocess import tempfile @@ -349,35 +350,45 @@ def test_media_requests_carry_a_query_no_earlier_run_sent(self) -> None: self.assertNotEqual(tokens[0], tokens[1]) -SECURITY_NAMES = { - "content-security-policy", - "content-security-policy-report-only", - "cross-origin-embedder-policy", - "cross-origin-opener-policy", - "cross-origin-resource-policy", - "permissions-policy", - "referrer-policy", - "strict-transport-security", - "x-content-type-options", - "x-frame-options", -} +# The headers a site block sets that are not security headers, so the sync case leaves them to their own checks. +NOT_SECURITY = {"cache-control", "vary", "x-blog-env", "x-blog-release", "x-robots-tag"} def caddyfile_headers(block: str) -> list[tuple[str, str]]: - """The security headers a Caddyfile site block sets, in either the block or the one-line form.""" + """Every other header a Caddyfile site block sets on all its responses, refusing one scoped to fewer.""" pairs = [] + depth = 0 + header_block: tuple[int, bool] | None = None for line in block.splitlines(): - match = re.fullmatch( - r'\s*(?:header\s+(@\S+\s+)?)?(\S+)\s+(?:"([^"]*)"|([^\s"{]+))\s*', line - ) - if not match or match[2].lower() not in SECURITY_NAMES: + words = shlex.split(line, comments=True) + if not words: + continue + if words == ["}"]: + depth -= 1 + if header_block and depth < header_block[0]: + header_block = None continue - if match[1]: + if words[-1] == "{": + depth += 1 + if words[0] == "header": + header_block = (depth, len(words) > 2 or depth > 2) + continue + if words[0] == "header": + rest, scoped = words[1:], depth > 1 + if rest[0][0] in "@/*": + rest, scoped = rest[1:], True + elif header_block and depth == header_block[0]: + rest, scoped = words, header_block[1] + else: + continue + name = rest[0].lstrip("+?>") + if rest[0].startswith("-") or name.lower() in NOT_SECURITY: + continue + if scoped: raise AssertionError( - f"{match[2]} is scoped to {match[1].strip()}, and the live check asserts" - " security headers on every response" + f"{name} is scoped to fewer responses than the live check asserts it on" ) - pairs.append((match[2], match[3] if match[3] is not None else match[4])) + pairs.append((name, rest[1] if len(rest) > 1 else "")) return pairs @@ -439,12 +450,22 @@ def test_a_missing_header_fails_on_every_kind_of_response(self) -> None: self.assertIn(f"family /en/ sends {csp} ''", result.stdout) def test_a_bare_caddyfile_value_is_read(self) -> None: - block = "\theader {\n\t\tX-Frame-Options DENY\n\t}\n" + block = ":8080 {\n\theader {\n\t\tX-Frame-Options DENY\n\t}\n}\n" self.assertEqual(caddyfile_headers(block), [("X-Frame-Options", "DENY")]) - def test_a_matcher_scoped_security_header_is_refused(self) -> None: - with self.assertRaisesRegex(AssertionError, "scoped to @page"): - caddyfile_headers('\theader @page Content-Security-Policy "x"\n') + def test_a_scoped_security_header_is_refused(self) -> None: + for block in ( + '\theader @page Content-Security-Policy "x"\n', + "\theader /af/* X-Frame-Options DENY\n", + "\theader @image {\n\t\tX-Frame-Options DENY\n\t}\n", + "\thandle /x {\n\t\theader X-Frame-Options DENY\n\t}\n", + ): + with self.subTest(block), self.assertRaisesRegex(AssertionError, "scoped"): + caddyfile_headers(":8080 {\n" + block + "}\n") + + def test_any_header_outside_the_known_markers_is_read(self) -> None: + block = ':8080 {\n\theader {\n\t\tX-XSS-Protection "0"\n\t}\n}\n' + self.assertEqual(caddyfile_headers(block), [("X-XSS-Protection", "0")]) def test_headers_are_asserted_on_the_config_the_reload_converges_on(self) -> None: class Reloading(Handler): From f3f1c267421c1e9700d028d00963500cf9b9f1b7 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 11:17:03 -0700 Subject: [PATCH 05/10] Read the Caddyfile's Headers Through Caddy's Own Parser Each review round found another directive form the hand-written reader misread: path matchers, matcher-scoped blocks, status requirements, scoped deletions. The sync case now runs caddy adapt in a pinned image, offline, and walks the JSON, where a matcher, a require, an error route, or a delete is explicit. Dependabot tracks the image pin. Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 22 ++- checks/README.md | 5 +- checks/caddy/Dockerfile | 1 + checks/tests/test_check_live_urls_sample.py | 202 +++++++++++++------- 4 files changed, 161 insertions(+), 69 deletions(-) create mode 100644 checks/caddy/Dockerfile diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d5a2a978..82f93eab 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 and the Python tooling in scripts/requirements.txt are the ecosystems tracked here. +# 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. # 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 @@ -45,3 +45,23 @@ updates: pip-deps: patterns: - "*" + + - package-ecosystem: "docker" + target-branch: "main" + directory: "/checks/caddy" + schedule: + interval: "daily" + groups: + docker-deps: + patterns: + - "*" + + - package-ecosystem: "docker" + target-branch: "develop" + directory: "/checks/caddy" + schedule: + interval: "daily" + groups: + docker-deps: + patterns: + - "*" diff --git a/checks/README.md b/checks/README.md index be930e70..c0ae4fac 100644 --- a/checks/README.md +++ b/checks/README.md @@ -113,7 +113,9 @@ wc -l checks/golden-urls.txt checks/redirect-urls.txt checks/golden-media-legacy **One request is added, a missing `.png` under `/media/`.** The `404` answers from the Caddyfile's `handle_errors` block rather than from the route every other request takes, so it is checked on its own. Being a static file, it stays out of the sampled run's page budget. -**The values live once here, and a unit case holds them to the Caddyfile.** `checks/tests/test_check_live_urls_sample.py` reads every header a site block sets on all its responses, apart from its cache headers and the site's own markers. It fails when those differ from this file in either direction, and when a security header is scoped to fewer responses. See [`deploy/README.md`][deploy-readme-security-headers] for why each value is what it is. +**The values live once here, and a unit case holds them to the Caddyfile.** `checks/tests/test_check_live_urls_sample.py` reads the Caddyfile through `caddy adapt`, so Caddy's own parser decides what each directive covers. It compares every header a site sets on all its responses with this file, in both directions. The cache headers and the site's own markers are left out. It also fails on a security header that a matcher, a status requirement, an error route, or a deletion narrows to fewer responses. + +**That case needs Docker.** It builds the image [`caddy/Dockerfile`][caddy-dockerfile] pins and runs it with networking off. That works the same on a GitHub runner and on a workstation with no Caddy installed. Dependabot moves the pin. See [`deploy/README.md`][deploy-readme-security-headers] for why each value is what it is. ## Directionality @@ -183,6 +185,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-env-docs]: ./check-env-docs.py [check-github-env]: ./check-github-env.py diff --git a/checks/caddy/Dockerfile b/checks/caddy/Dockerfile new file mode 100644 index 00000000..2b3d91cd --- /dev/null +++ b/checks/caddy/Dockerfile @@ -0,0 +1 @@ +FROM caddy:2.11.7@sha256:504a44d7d74bd2bc28a66afc4774912fc21223ca8a67734af1c54ab2f999b489 diff --git a/checks/tests/test_check_live_urls_sample.py b/checks/tests/test_check_live_urls_sample.py index 0a0c5a61..705a011f 100644 --- a/checks/tests/test_check_live_urls_sample.py +++ b/checks/tests/test_check_live_urls_sample.py @@ -1,17 +1,19 @@ """Tests for the sampled mode of check-live-urls.sh, against a constructed local server.""" import collections +import functools import http.server +import json import os import pathlib import re -import shlex import shutil import subprocess import tempfile import threading import unittest -from typing import ClassVar, Self, cast +from collections.abc import Iterator +from typing import Any, ClassVar, Self, cast CHECKS = pathlib.Path(__file__).resolve().parent.parent SCRIPT = CHECKS / "check-live-urls.sh" @@ -350,46 +352,105 @@ def test_media_requests_carry_a_query_no_earlier_run_sent(self) -> None: self.assertNotEqual(tokens[0], tokens[1]) -# The headers a site block sets that are not security headers, so the sync case leaves them to their own checks. +# The headers a site sets that are not security headers, so the sync case leaves them to their own checks. NOT_SECURITY = {"cache-control", "vary", "x-blog-env", "x-blog-release", "x-robots-tag"} +Header = tuple[str, str, bool] -def caddyfile_headers(block: str) -> list[tuple[str, str]]: - """Every other header a Caddyfile site block sets on all its responses, refusing one scoped to fewer.""" - pairs = [] - depth = 0 - header_block: tuple[int, bool] | None = None - for line in block.splitlines(): - words = shlex.split(line, comments=True) - if not words: - continue - if words == ["}"]: - depth -= 1 - if header_block and depth < header_block[0]: - header_block = None - continue - if words[-1] == "{": - depth += 1 - if words[0] == "header": - header_block = (depth, len(words) > 2 or depth > 2) - continue - if words[0] == "header": - rest, scoped = words[1:], depth > 1 - if rest[0][0] in "@/*": - rest, scoped = rest[1:], True - elif header_block and depth == header_block[0]: - rest, scoped = words, header_block[1] - else: - continue - name = rest[0].lstrip("+?>") - if rest[0].startswith("-") or name.lower() in NOT_SECURITY: - continue - if scoped: - raise AssertionError( - f"{name} is scoped to fewer responses than the live check asserts it on" - ) - pairs.append((name, rest[1] if len(rest) > 1 else "")) - return pairs +@functools.cache +def caddy_image() -> str: + """The image checks/caddy/Dockerfile pins, built once per run.""" + built = subprocess.run( + ["docker", "build", "-q", str(CHECKS / "caddy")], + capture_output=True, + text=True, + timeout=600, + check=True, + ) + return built.stdout.strip() + + +def adapt(caddyfile: str) -> dict[str, Any]: + """Caddy's own JSON for a Caddyfile, adapted offline with the release's maps in place.""" + with tempfile.TemporaryDirectory() as tmp: + (pathlib.Path(tmp) / "Caddyfile").write_text(caddyfile, encoding="utf-8") + adapted = subprocess.run( + [ + "docker", + "run", + "--rm", + "--network", + "none", + "-v", + f"{tmp}:/etc/caddy:ro", + "-v", + f"{CADDYFILE.parent / 'maps'}:/srv/blog/current/maps:ro", + caddy_image(), + "caddy", + "adapt", + "--config", + "/etc/caddy/Caddyfile", + "--adapter", + "caddyfile", + ], + capture_output=True, + text=True, + timeout=120, + check=False, + ) + if adapted.returncode != 0: + raise AssertionError(f"caddy adapt failed: {adapted.stderr}") + config: dict[str, Any] = json.loads(adapted.stdout) + return config + + +def header_ops( + routes: list[dict[str, Any]], scoped: bool, top: bool +) -> Iterator[Header]: + """Each (name, value, scoped) a headers handler writes, scoped where a matcher or a status requirement narrows it.""" + for route in routes: + # A top-level host matcher picks the site rather than narrowing it. + keys = {k for m in route.get("match", []) for k in m} + narrowed = scoped or bool(keys - {"host"} if top else keys) + for handler in route.get("handle", []): + if handler["handler"] == "subroute": + yield from header_ops(handler.get("routes", []), narrowed, False) + if handler["handler"] != "headers": + continue + response = handler.get("response", {}) + required = narrowed or "require" in response + for op in ("set", "add"): + for name, values in response.get(op, {}).items(): + yield name.lower(), ", ".join(values), required + for name in [*response.get("delete", []), *response.get("replace", {})]: + yield name.lower(), "", True + + +def site_headers(caddyfile: str) -> dict[str, list[tuple[str, str]]]: + """Per site, the lowercased headers outside NOT_SECURITY it sets on every response, refusing any it narrows.""" + server = next(iter(adapt(caddyfile)["apps"]["http"]["servers"].values())) + sites: dict[str, list[tuple[str, str]]] = {} + narrowed = [] + for route in server.get("routes", []): + hosts = [h for m in route.get("match", []) for h in m.get("host", [])] + site = "family" if "viljoen.family" in hosts else "blog" + for name, value, scoped in header_ops([route], False, True): + if name in NOT_SECURITY: + continue + if scoped: + narrowed.append(f"{site} {name}") + else: + sites.setdefault(site, []).append((name, value)) + for name, _, _ in header_ops( + server.get("errors", {}).get("routes", []), True, True + ): + if name not in NOT_SECURITY: + narrowed.append(f"errors {name}") + if narrowed: + raise AssertionError( + f"{', '.join(narrowed)} reach fewer responses than the live check asserts them on" + ) + return sites def without(name: str, target: str) -> type[Handler]: @@ -405,16 +466,6 @@ def headers_for(self, path: str) -> list[tuple[str, str]]: class SecurityHeaderTests(unittest.TestCase): - def test_expected_values_are_the_caddyfile_values(self) -> None: - text = CADDYFILE.read_text(encoding="utf-8") - blog, family = re.split(r"(?m)^http://viljoen\.family:8080", text, maxsplit=1) - self.assertEqual( - sorted(caddyfile_headers(blog)), sorted(expected_headers("blog")) - ) - self.assertEqual( - sorted(caddyfile_headers(family)), sorted(expected_headers("family")) - ) - def sampled( self, handler: type[Handler] = Handler, family: type[Handler] = Handler ) -> subprocess.CompletedProcess[str]: @@ -449,24 +500,6 @@ def test_a_missing_header_fails_on_every_kind_of_response(self) -> None: self.assertEqual(result.returncode, 1, result.stdout) self.assertIn(f"family /en/ sends {csp} ''", result.stdout) - def test_a_bare_caddyfile_value_is_read(self) -> None: - block = ":8080 {\n\theader {\n\t\tX-Frame-Options DENY\n\t}\n}\n" - self.assertEqual(caddyfile_headers(block), [("X-Frame-Options", "DENY")]) - - def test_a_scoped_security_header_is_refused(self) -> None: - for block in ( - '\theader @page Content-Security-Policy "x"\n', - "\theader /af/* X-Frame-Options DENY\n", - "\theader @image {\n\t\tX-Frame-Options DENY\n\t}\n", - "\thandle /x {\n\t\theader X-Frame-Options DENY\n\t}\n", - ): - with self.subTest(block), self.assertRaisesRegex(AssertionError, "scoped"): - caddyfile_headers(":8080 {\n" + block + "}\n") - - def test_any_header_outside_the_known_markers_is_read(self) -> None: - block = ':8080 {\n\theader {\n\t\tX-XSS-Protection "0"\n\t}\n}\n' - self.assertEqual(caddyfile_headers(block), [("X-XSS-Protection", "0")]) - def test_headers_are_asserted_on_the_config_the_reload_converges_on(self) -> None: class Reloading(Handler): def headers_for(self, path: str) -> list[tuple[str, str]]: @@ -520,5 +553,40 @@ def headers_for(self, path: str) -> list[tuple[str, str]]: self.assertNotIn("UNCONFIRMED", result.stdout) +class CaddyfileSyncTests(unittest.TestCase): + """Caddy's own parser reads the Caddyfile, so no grammar is re-derived here.""" + + def test_expected_values_are_the_caddyfile_values(self) -> None: + sites = site_headers(CADDYFILE.read_text(encoding="utf-8")) + for site in ("blog", "family"): + with self.subTest(site): + expected = [(n.lower(), v) for n, v in expected_headers(site)] + self.assertEqual(sorted(sites[site]), sorted(expected)) + + def test_any_header_outside_the_known_markers_is_read(self) -> None: + for directive in ( + 'header X-XSS-Protection "0"', + 'route {\n\t\theader X-XSS-Protection "0"\n\t}', + ): + with self.subTest(directive): + sites = site_headers(f":8080 {{\n\t{directive}\n}}\n") + self.assertEqual(sites["blog"], [("x-xss-protection", "0")]) + + def test_a_security_header_reaching_fewer_responses_is_refused(self) -> None: + for directive in ( + "header @page {\n\t\tX-Frame-Options DENY\n\t}\n\t@page path /x", + "header /af/* X-Frame-Options DENY", + "handle /x {\n\t\theader X-Frame-Options DENY\n\t}", + "header {\n\t\tX-Frame-Options DENY\n\t\tmatch {\n\t\t\tstatus 2xx\n\t\t}\n\t}", + "header /assets/* -Referrer-Policy", + "handle_errors {\n\t\theader X-Frame-Options DENY\n\t}", + ): + with ( + self.subTest(directive), + self.assertRaisesRegex(AssertionError, "fewer responses"), + ): + site_headers(f":8080 {{\n\t{directive}\n}}\n") + + if __name__ == "__main__": unittest.main() From cd8ffed3b755f85fb25930fbec5b39a1cd964a5d Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 11:29:03 -0700 Subject: [PATCH 06/10] Treat Grouped Routes and Earlier Responders as Narrowing a Header A header in one of several mutually exclusive handle routes, or behind a handler that answers first, read as site-wide. Both now count as scoped. An error route repeating a value every response already carries is no longer refused. Co-Authored-By: Claude Opus 5.5 --- checks/README.md | 2 +- checks/tests/test_check_live_urls_sample.py | 82 ++++++++++++++------- 2 files changed, 56 insertions(+), 28 deletions(-) diff --git a/checks/README.md b/checks/README.md index c0ae4fac..e1cd3e97 100644 --- a/checks/README.md +++ b/checks/README.md @@ -113,7 +113,7 @@ wc -l checks/golden-urls.txt checks/redirect-urls.txt checks/golden-media-legacy **One request is added, a missing `.png` under `/media/`.** The `404` answers from the Caddyfile's `handle_errors` block rather than from the route every other request takes, so it is checked on its own. Being a static file, it stays out of the sampled run's page budget. -**The values live once here, and a unit case holds them to the Caddyfile.** `checks/tests/test_check_live_urls_sample.py` reads the Caddyfile through `caddy adapt`, so Caddy's own parser decides what each directive covers. It compares every header a site sets on all its responses with this file, in both directions. The cache headers and the site's own markers are left out. It also fails on a security header that a matcher, a status requirement, an error route, or a deletion narrows to fewer responses. +**The values live once here, and a unit case holds them to the Caddyfile.** `checks/tests/test_check_live_urls_sample.py` reads the Caddyfile through `caddy adapt`, so Caddy's own parser decides what each directive covers. It compares every header a site sets on all its responses with this file, in both directions. The cache headers and the site's own markers are left out. It also fails on a security header that reaches fewer responses than all of them. A matcher, a status requirement, an error route, a deletion, or a handler answering first each narrows one. **That case needs Docker.** It builds the image [`caddy/Dockerfile`][caddy-dockerfile] pins and runs it with networking off. That works the same on a GitHub runner and on a workstation with no Caddy installed. Dependabot moves the pin. See [`deploy/README.md`][deploy-readme-security-headers] for why each value is what it is. diff --git a/checks/tests/test_check_live_urls_sample.py b/checks/tests/test_check_live_urls_sample.py index 705a011f..54bba082 100644 --- a/checks/tests/test_check_live_urls_sample.py +++ b/checks/tests/test_check_live_urls_sample.py @@ -404,26 +404,51 @@ def adapt(caddyfile: str) -> dict[str, Any]: return config +# Handlers that never answer a request, so a header after one still reaches every response. +PASSIVE = {"headers", "map", "vars"} + + def header_ops( routes: list[dict[str, Any]], scoped: bool, top: bool ) -> Iterator[Header]: - """Each (name, value, scoped) a headers handler writes, scoped where a matcher or a status requirement narrows it.""" + """Each (name, value, scoped) a headers handler writes, scoped where any request can miss it.""" + shadowed = False for route in routes: # A top-level host matcher picks the site rather than narrowing it. keys = {k for m in route.get("match", []) for k in m} - narrowed = scoped or bool(keys - {"host"} if top else keys) + narrowed = ( + scoped + or shadowed + or "group" in route + or bool(keys - {"host"} if top else keys) + ) + answered = False for handler in route.get("handle", []): if handler["handler"] == "subroute": - yield from header_ops(handler.get("routes", []), narrowed, False) - if handler["handler"] != "headers": - continue - response = handler.get("response", {}) - required = narrowed or "require" in response - for op in ("set", "add"): - for name, values in response.get(op, {}).items(): - yield name.lower(), ", ".join(values), required - for name in [*response.get("delete", []), *response.get("replace", {})]: - yield name.lower(), "", True + yield from header_ops( + handler.get("routes", []), narrowed or answered, False + ) + elif handler["handler"] == "headers": + response = handler.get("response", {}) + required = narrowed or answered or "require" in response + for op in ("set", "add"): + for name, values in response.get(op, {}).items(): + yield name.lower(), ", ".join(values), required + for name in [*response.get("delete", []), *response.get("replace", {})]: + yield name.lower(), "", True + answered = answered or handler["handler"] not in PASSIVE + shadowed = shadowed or answered or bool(route.get("terminal")) + + +def by_site(routes: list[dict[str, Any]]) -> dict[str, list[Header]]: + """Each site's header writes, its top-level routes walked in order apart from the other site's.""" + grouped: dict[str, list[dict[str, Any]]] = {} + for route in routes: + hosts = [h for m in route.get("match", []) for h in m.get("host", [])] + grouped.setdefault( + "family" if "viljoen.family" in hosts else "blog", [] + ).append(route) + return {site: list(header_ops(rs, False, True)) for site, rs in grouped.items()} def site_headers(caddyfile: str) -> dict[str, list[tuple[str, str]]]: @@ -431,21 +456,17 @@ def site_headers(caddyfile: str) -> dict[str, list[tuple[str, str]]]: server = next(iter(adapt(caddyfile)["apps"]["http"]["servers"].values())) sites: dict[str, list[tuple[str, str]]] = {} narrowed = [] - for route in server.get("routes", []): - hosts = [h for m in route.get("match", []) for h in m.get("host", [])] - site = "family" if "viljoen.family" in hosts else "blog" - for name, value, scoped in header_ops([route], False, True): - if name in NOT_SECURITY: - continue - if scoped: - narrowed.append(f"{site} {name}") - else: - sites.setdefault(site, []).append((name, value)) - for name, _, _ in header_ops( - server.get("errors", {}).get("routes", []), True, True - ): - if name not in NOT_SECURITY: - narrowed.append(f"errors {name}") + for site, ops in by_site(server.get("routes", [])).items(): + sites[site] = [(n, v) for n, v, s in ops if not s and n not in NOT_SECURITY] + narrowed += [f"{site} {n}" for n, _, s in ops if s and n not in NOT_SECURITY] + # An error route repeating a value every response already carries narrows nothing. + for site, ops in by_site(server.get("errors", {}).get("routes", [])).items(): + wide = sites.get(site, []) + narrowed += [ + f"{site} errors {n}" + for n, v, s in ops + if n not in NOT_SECURITY and (s or (n, v) not in wide) + ] if narrowed: raise AssertionError( f"{', '.join(narrowed)} reach fewer responses than the live check asserts them on" @@ -572,6 +593,11 @@ def test_any_header_outside_the_known_markers_is_read(self) -> None: sites = site_headers(f":8080 {{\n\t{directive}\n}}\n") self.assertEqual(sites["blog"], [("x-xss-protection", "0")]) + def test_an_error_route_repeating_a_site_wide_value_is_read(self) -> None: + directive = "header X-Frame-Options DENY\n\thandle_errors {\n\t\theader X-Frame-Options DENY\n\t}" + sites = site_headers(f":8080 {{\n\t{directive}\n}}\n") + self.assertEqual(sites["blog"], [("x-frame-options", "DENY")]) + def test_a_security_header_reaching_fewer_responses_is_refused(self) -> None: for directive in ( "header @page {\n\t\tX-Frame-Options DENY\n\t}\n\t@page path /x", @@ -580,6 +606,8 @@ def test_a_security_header_reaching_fewer_responses_is_refused(self) -> None: "header {\n\t\tX-Frame-Options DENY\n\t\tmatch {\n\t\t\tstatus 2xx\n\t\t}\n\t}", "header /assets/* -Referrer-Policy", "handle_errors {\n\t\theader X-Frame-Options DENY\n\t}", + "handle /x {\n\t\trespond 200\n\t}\n\thandle {\n\t\theader X-Frame-Options DENY\n\t}", + "route {\n\t\tredir /y /z 301\n\t\theader X-Frame-Options DENY\n\t}", ): with ( self.subTest(directive), From 193880f10a26ad7f94d4b40a0b16d55793593757 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 11:48:17 -0700 Subject: [PATCH 07/10] Read Deferred Writes, Pass-Through Handlers, and Matched Error Routes A deferred header write misses error responses, so it now counts as scoped. A header after encode, rewrite, or templates still reaches every response, and an error route with its own matcher that repeats a site-wide value narrows nothing, so neither is refused any longer. Co-Authored-By: Claude Opus 5.5 --- checks/tests/test_check_live_urls_sample.py | 28 +++++++++++++++------ 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/checks/tests/test_check_live_urls_sample.py b/checks/tests/test_check_live_urls_sample.py index 54bba082..b0256fb2 100644 --- a/checks/tests/test_check_live_urls_sample.py +++ b/checks/tests/test_check_live_urls_sample.py @@ -405,7 +405,7 @@ def adapt(caddyfile: str) -> dict[str, Any]: # Handlers that never answer a request, so a header after one still reaches every response. -PASSIVE = {"headers", "map", "vars"} +PASSIVE = {"encode", "headers", "map", "rewrite", "templates", "vars"} def header_ops( @@ -430,7 +430,13 @@ def header_ops( ) elif handler["handler"] == "headers": response = handler.get("response", {}) - required = narrowed or answered or "require" in response + # A deferred write lands only when a handler writes, so an error response misses it. + required = ( + narrowed + or answered + or "require" in response + or bool(response.get("deferred")) + ) for op in ("set", "add"): for name, values in response.get(op, {}).items(): yield name.lower(), ", ".join(values), required @@ -465,7 +471,7 @@ def site_headers(caddyfile: str) -> dict[str, list[tuple[str, str]]]: narrowed += [ f"{site} errors {n}" for n, v, s in ops - if n not in NOT_SECURITY and (s or (n, v) not in wide) + if n not in NOT_SECURITY and (n, v) not in wide ] if narrowed: raise AssertionError( @@ -593,10 +599,16 @@ def test_any_header_outside_the_known_markers_is_read(self) -> None: sites = site_headers(f":8080 {{\n\t{directive}\n}}\n") self.assertEqual(sites["blog"], [("x-xss-protection", "0")]) - def test_an_error_route_repeating_a_site_wide_value_is_read(self) -> None: - directive = "header X-Frame-Options DENY\n\thandle_errors {\n\t\theader X-Frame-Options DENY\n\t}" - sites = site_headers(f":8080 {{\n\t{directive}\n}}\n") - self.assertEqual(sites["blog"], [("x-frame-options", "DENY")]) + def test_a_header_every_response_still_carries_is_read(self) -> None: + for directive in ( + "header X-Frame-Options DENY\n\thandle_errors {\n\t\theader X-Frame-Options DENY\n\t}", + "header X-Frame-Options DENY\n\thandle_errors 404 {\n\t\theader X-Frame-Options DENY\n\t}", + "route {\n\t\tencode gzip\n\t\theader X-Frame-Options DENY\n\t}", + "route {\n\t\trewrite * /x\n\t\theader X-Frame-Options DENY\n\t}", + ): + with self.subTest(directive): + sites = site_headers(f":8080 {{\n\t{directive}\n}}\n") + self.assertEqual(sites["blog"], [("x-frame-options", "DENY")]) def test_a_security_header_reaching_fewer_responses_is_refused(self) -> None: for directive in ( @@ -608,6 +620,8 @@ def test_a_security_header_reaching_fewer_responses_is_refused(self) -> None: "handle_errors {\n\t\theader X-Frame-Options DENY\n\t}", "handle /x {\n\t\trespond 200\n\t}\n\thandle {\n\t\theader X-Frame-Options DENY\n\t}", "route {\n\t\tredir /y /z 301\n\t\theader X-Frame-Options DENY\n\t}", + "header >X-Frame-Options DENY", + "header {\n\t\tdefer\n\t\tX-Frame-Options DENY\n\t}", ): with ( self.subTest(directive), From bb320f5f1ae488deb58e546976707fd6a30c92c8 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 12:02:00 -0700 Subject: [PATCH 08/10] Count a Header Deletion Only Where It Removes an Asserted Header Removing a header the site never sets on every response, such as Server, narrows nothing the live check asserts, so the sync case no longer refuses it. Deleting a site-wide security header on some responses is still refused, in the main routes and in an error route. Co-Authored-By: Claude Opus 5.5 --- checks/tests/test_check_live_urls_sample.py | 33 ++++++++++++++++----- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/checks/tests/test_check_live_urls_sample.py b/checks/tests/test_check_live_urls_sample.py index b0256fb2..cf7ae1e0 100644 --- a/checks/tests/test_check_live_urls_sample.py +++ b/checks/tests/test_check_live_urls_sample.py @@ -354,7 +354,7 @@ def test_media_requests_carry_a_query_no_earlier_run_sent(self) -> None: # The headers a site sets that are not security headers, so the sync case leaves them to their own checks. NOT_SECURITY = {"cache-control", "vary", "x-blog-env", "x-blog-release", "x-robots-tag"} -Header = tuple[str, str, bool] +Header = tuple[str, str | None, bool] @functools.cache @@ -441,7 +441,7 @@ def header_ops( for name, values in response.get(op, {}).items(): yield name.lower(), ", ".join(values), required for name in [*response.get("delete", []), *response.get("replace", {})]: - yield name.lower(), "", True + yield name.lower(), None, True answered = answered or handler["handler"] not in PASSIVE shadowed = shadowed or answered or bool(route.get("terminal")) @@ -462,16 +462,30 @@ def site_headers(caddyfile: str) -> dict[str, list[tuple[str, str]]]: server = next(iter(adapt(caddyfile)["apps"]["http"]["servers"].values())) sites: dict[str, list[tuple[str, str]]] = {} narrowed = [] - for site, ops in by_site(server.get("routes", [])).items(): - sites[site] = [(n, v) for n, v, s in ops if not s and n not in NOT_SECURITY] - narrowed += [f"{site} {n}" for n, _, s in ops if s and n not in NOT_SECURITY] + main = by_site(server.get("routes", [])) + for site, ops in main.items(): + sites[site] = [ + (n, v) + for n, v, s in ops + if v is not None and not s and n not in NOT_SECURITY + ] + # A deletion matters only where it removes a header the site sets on every response. + for site, ops in main.items(): + wide = {n for n, _ in sites[site]} + narrowed += [ + f"{site} {n}" + for n, v, s in ops + if s and n not in NOT_SECURITY and (v is not None or n in wide) + ] # An error route repeating a value every response already carries narrows nothing. for site, ops in by_site(server.get("errors", {}).get("routes", [])).items(): - wide = sites.get(site, []) + pairs = sites.get(site, []) narrowed += [ f"{site} errors {n}" for n, v, s in ops - if n not in NOT_SECURITY and (n, v) not in wide + if n not in NOT_SECURITY + and (n, v) not in pairs + and (v is not None or n in {m for m, _ in pairs}) ] if narrowed: raise AssertionError( @@ -605,6 +619,8 @@ def test_a_header_every_response_still_carries_is_read(self) -> None: "header X-Frame-Options DENY\n\thandle_errors 404 {\n\t\theader X-Frame-Options DENY\n\t}", "route {\n\t\tencode gzip\n\t\theader X-Frame-Options DENY\n\t}", "route {\n\t\trewrite * /x\n\t\theader X-Frame-Options DENY\n\t}", + "header X-Frame-Options DENY\n\theader -Server", + "header X-Frame-Options DENY\n\thandle_errors {\n\t\theader -Server\n\t}", ): with self.subTest(directive): sites = site_headers(f":8080 {{\n\t{directive}\n}}\n") @@ -616,7 +632,8 @@ def test_a_security_header_reaching_fewer_responses_is_refused(self) -> None: "header /af/* X-Frame-Options DENY", "handle /x {\n\t\theader X-Frame-Options DENY\n\t}", "header {\n\t\tX-Frame-Options DENY\n\t\tmatch {\n\t\t\tstatus 2xx\n\t\t}\n\t}", - "header /assets/* -Referrer-Policy", + "header Referrer-Policy no-referrer\n\theader /assets/* -Referrer-Policy", + "header Referrer-Policy no-referrer\n\thandle_errors {\n\t\theader -Referrer-Policy\n\t}", "handle_errors {\n\t\theader X-Frame-Options DENY\n\t}", "handle /x {\n\t\trespond 200\n\t}\n\thandle {\n\t\theader X-Frame-Options DENY\n\t}", "route {\n\t\tredir /y /z 301\n\t\theader X-Frame-Options DENY\n\t}", From 21e898bbeae18fd8875c5ccbca349f34aaed771b Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 12:17:25 -0700 Subject: [PATCH 09/10] List the 404 Probe in the Sample Plan and Keep the Build's Error --print-sample counted the probe in its static budget without listing it, so the listing and the budget could not be reconciled. It is now a plan row like any other request. A failed build of the Caddy image reports Docker's own output rather than a bare exit status. Co-Authored-By: Claude Opus 5.5 --- checks/check-live-urls.sh | 11 +++++++---- checks/tests/test_check_live_urls_sample.py | 7 ++++++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/checks/check-live-urls.sh b/checks/check-live-urls.sh index 8e62178c..d5dd8920 100755 --- a/checks/check-live-urls.sh +++ b/checks/check-live-urls.sh @@ -192,16 +192,16 @@ if [ -n "$SAMPLE" ]; then for page in "${FAMILY_PAGES[@]}"; do SAMPLE_PLAN+=("family"$'\t'"family page"$'\t'"${#FAMILY_PAGES[@]}"$'\t'"${page%%|*}") done + SAMPLE_PLAN+=("missing"$'\t'"missing file"$'\t'"1"$'\t'"$MISSING_PROBE") # The budget counts distinct non-static paths per host, which is never less than the edge counts, with the preflight's / among them. - # The 404 probe is the first static request. # A sampled redirect is not followed, so each costs one path, and a legacy media URL costs two requests, since it takes a hop. declare -A sample_paths=(["blog /"]=1) - sample_statics=1 + sample_statics=0 for entry in "${SAMPLE_PLAN[@]}"; do IFS=$'\t' read -r kind class _ url <<<"$entry" case "$kind" in - media) + media | missing) sample_statics=$((sample_statics + 1)) if [ "$class" = 'legacy upload' ]; then sample_statics=$((sample_statics + 1)) @@ -245,7 +245,10 @@ if [ -n "$SAMPLE" ]; then RENDER_SRC="$SAMPLE_DIR/render" REDIRECT_SRC="$SAMPLE_DIR/redirect" MEDIA_SRC="$SAMPLE_DIR/media" for entry in "${SAMPLE_PLAN[@]}"; do IFS=$'\t' read -r kind _ _ url <<<"$entry" - [ "$kind" = family ] || printf '%s\n' "$url" >>"$SAMPLE_DIR/$kind" + case "$kind" in + family | missing) ;; + *) printf '%s\n' "$url" >>"$SAMPLE_DIR/$kind" ;; + esac done echo "==> sampling the contract by class, ${#sample_paths[@]} distinct non-static paths" fi diff --git a/checks/tests/test_check_live_urls_sample.py b/checks/tests/test_check_live_urls_sample.py index cf7ae1e0..0520b613 100644 --- a/checks/tests/test_check_live_urls_sample.py +++ b/checks/tests/test_check_live_urls_sample.py @@ -120,6 +120,9 @@ def test_render_media_and_family_are_each_sampled(self) -> None: self.assertLessEqual(RENDER_CLASSES, by_kind["render"]) self.assertLessEqual(MEDIA_CLASSES, by_kind["media"]) self.assertEqual(by_kind["family pages"], FAMILY_PAGES) + self.assertEqual( + [url for kind, _, _, url in entries if kind == "missing"], [MISSING_PROBE] + ) def test_every_sampled_url_comes_from_its_list(self) -> None: source = { @@ -365,8 +368,10 @@ def caddy_image() -> str: capture_output=True, text=True, timeout=600, - check=True, + check=False, ) + if built.returncode != 0: + raise AssertionError(f"docker build of the Caddy image failed: {built.stderr}") return built.stdout.strip() From 554bf9340d7442ff063c663f277f1d3e4996f3ba Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Sat, 24 Oct 2026 12:31:40 -0700 Subject: [PATCH 10/10] Share One Status and Header Check Between Pages and the 404 Probe The 404 probe repeated check_render step for step. Both now call check_status with a label, the expected status, and the URL. Co-Authored-By: Claude Opus 5.5 --- checks/check-live-urls.sh | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/checks/check-live-urls.sh b/checks/check-live-urls.sh index d5dd8920..0ef03869 100755 --- a/checks/check-live-urls.sh +++ b/checks/check-live-urls.sh @@ -431,23 +431,27 @@ transfer_failure() { # Invoked indirectly, the same way as curl_retry above. # shellcheck disable=SC2329 -check_render() { - local url="$1" out code why rc=0 auth=(-K "$CHECKRC") +check_status() { + local what="$1" want="$2" target="$3" out code why rc=0 auth=(-K "$CHECKRC") [ -n "$CURLRC" ] && auth+=(-K "$CURLRC") - out=$(curl_retry -q -s -o /dev/null -w "%{http_code}\n$HEADER_FORMAT" --max-time 30 "${auth[@]}" "$BASE$url") || rc=$? + out=$(curl_retry -q -s -o /dev/null -w "%{http_code}\n$HEADER_FORMAT" --max-time 30 "${auth[@]}" "$target") || rc=$? code="${out%%$'\n'*}" why=$(transfer_failure "$code" "$rc") if [ -n "$why" ]; then - echo "render $url $why" >>"$FAILED" + echo "$what $why" >>"$FAILED" return fi - if [ "$code" != "200" ]; then - echo "render $url expected 200, got $code" >>"$FAILED" + if [ "$code" != "$want" ]; then + echo "$what expected $want, got $code" >>"$FAILED" return fi - check_headers "render $url" "${out#*$'\n'}" "$SECURITY_HEADERS" + check_headers "$what" "${out#*$'\n'}" "$SECURITY_HEADERS" } +# Invoked indirectly, the same way as curl_retry above. +# shellcheck disable=SC2329 +check_render() { check_status "render $1" 200 "$BASE$1"; } + # A caching proxy may answer a media URL from its copy for the file's lifetime, so a file a release lost would still pass. # The edge's cache key includes the query string and the file server ignores it, so a query no earlier run sent reaches the origin. CACHE_BUST="live-check=$(date +%s)-$$" @@ -582,7 +586,7 @@ check_redirect() { esac } -export -f curl_retry transfer_failure header_value check_headers check_render check_redirect check_media +export -f curl_retry transfer_failure header_value check_headers check_status check_render check_redirect check_media export BASE FAILED CURLRC CHECKRC SAMPLE CACHE_BUST HEADER_FORMAT SECURITY_HEADERS echo "==> $BASE" @@ -698,17 +702,7 @@ grep . "$MEDIA_SRC" | xargs -P "$PARALLEL" -I{} bash -c 'check_media "$@"' _ {} n_missing=1 echo "==> checking that a missing file answers 404 with the security headers" -rc=0 -out=$(curl_retry -q -s -o /dev/null -w "%{http_code}\n$HEADER_FORMAT" --max-time 30 "${AUTH[@]}" "$BASE$MISSING_PROBE?$CACHE_BUST") || rc=$? -code="${out%%$'\n'*}" -why=$(transfer_failure "$code" "$rc") -if [ -n "$why" ]; then - echo "missing $MISSING_PROBE $why" >>"$FAILED" -elif [ "$code" != "404" ]; then - echo "missing $MISSING_PROBE expected 404, got $code" >>"$FAILED" -else - check_headers "missing $MISSING_PROBE" "${out#*$'\n'}" "$SECURITY_HEADERS" -fi +check_status "missing $MISSING_PROBE" 404 "$BASE$MISSING_PROBE?$CACHE_BUST" # The title tells the family page from the blog, since one container answers both and an unknown host falls through to the blog with a 200. # X-Blog-Env still tells one environment from another, and the family host is a proxy rule of its own that can aim at the wrong container.