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/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..e1cd3e97 100644 --- a/checks/README.md +++ b/checks/README.md @@ -107,6 +107,16 @@ 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 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. + ## 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. @@ -175,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 @@ -184,4 +195,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/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/check-live-urls.sh b/checks/check-live-urls.sh index a3e77dcf..0ef03869 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. @@ -176,6 +192,7 @@ 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. # A sampled redirect is not followed, so each costs one path, and a legacy media URL costs two requests, since it takes a hop. @@ -184,7 +201,7 @@ if [ -n "$SAMPLE" ]; then 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)) @@ -228,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 @@ -380,6 +400,24 @@ 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. +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=$(header_value "$response" "$name" | head -n 1) + [ "$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() { @@ -393,18 +431,27 @@ 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") +check_status() { + local what="$1" want="$2" target="$3" 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[@]}" "$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" != "$want" ]; then + echo "$what expected $want, got $code" >>"$FAILED" return fi - [ "$code" = "200" ] || echo "render $url expected 200, got $code" >>"$FAILED" + 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)-$$" @@ -421,7 +468,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 +489,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,15 +526,18 @@ check_media() { image/*) ;; *) echo "$what answered 200 as $type, expected an image" >>"$FAILED" ;; esac + case "$target" in + '' | "$BASE" | "$BASE"/*) check_headers "$what" "${out#*$'\n'*$'\n'*$'\n'}" "$SECURITY_HEADERS" ;; + esac } # 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' --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 +555,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. @@ -516,7 +568,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" @@ -527,10 +580,14 @@ check_redirect() { 200 | 301 | 308) ;; *) echo "redirect $url -> $dest destination answered $dcode" >>"$FAILED" ;; esac + # 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 } -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 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" @@ -543,7 +600,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 @@ -567,7 +624,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 @@ -579,17 +636,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. @@ -598,11 +645,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 @@ -626,6 +675,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 +700,10 @@ 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" +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. # Sending no Accept-Language keeps / from redirecting to /af/. @@ -665,16 +731,18 @@ 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 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..0520b613 100644 --- a/checks/tests/test_check_live_urls_sample.py +++ b/checks/tests/test_check_live_urls_sample.py @@ -1,7 +1,9 @@ """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 @@ -10,15 +12,18 @@ import tempfile import threading import unittest -from typing import ClassVar, Self +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" 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 +41,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]: @@ -101,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 = { @@ -185,10 +207,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 +232,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 +256,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 +304,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 +355,302 @@ def test_media_requests_carry_a_query_no_earlier_run_sent(self) -> None: self.assertNotEqual(tokens[0], tokens[1]) +# 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 | None, bool] + + +@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=False, + ) + if built.returncode != 0: + raise AssertionError(f"docker build of the Caddy image failed: {built.stderr}") + 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 + + +# Handlers that never answer a request, so a header after one still reaches every response. +PASSIVE = {"encode", "headers", "map", "rewrite", "templates", "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 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 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 or answered, False + ) + elif handler["handler"] == "headers": + response = handler.get("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 + for name in [*response.get("delete", []), *response.get("replace", {})]: + yield name.lower(), None, 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]]]: + """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 = [] + 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(): + 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 pairs + and (v is not None or n in {m for m, _ in pairs}) + ] + 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]: + """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 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_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]]: + 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) + + +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_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}", + "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") + 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", + "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 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}", + "header >X-Frame-Options DENY", + "header {\n\t\tdefer\n\t\tX-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() diff --git a/deploy/README.md b/deploy/README.md index e4b1c13a..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 | @@ -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