All notes

Change an inline script under a hash-based CSP when the pages and the header deploy separately

Content Security PolicyDeploymentCaddyAstro

Add the new hashes to the policy before you remove the old ones. A policy with script-src 'self' 'sha256-…' lets an inline script run only when the hash of its exact text is in the list. Change one character of the script and the browser blocks it, with one line in the console and nothing on the page to show for it. If the pages and the header reach production in two steps, there’s a moment when one is new and the other is old, and a script is blocked in that moment whichever goes first.

Where it bit

Rubric is a static Astro site. Its pages ship in one deploy, and Caddy, the reverse proxy in front, sets the Content-Security-Policy header from a file that ships in another. A fix to the header’s sign-in link changed two inline scripts, and so two hashes.

With the pages deployed first, the new scripts would have been blocked until the Caddy file followed. With Caddy first and only the new hashes, the old pages’ scripts would have been blocked instead. The pages are also cached for five minutes, so some browsers hold an old page after any deploy.

The order that leaves no gap

  1. Build the site and collect the hashes of its inline scripts.
  2. Add the new hashes to the policy and keep the old ones. Here that meant two files, the site’s own nginx.conf and the Caddy file, which a deploy check requires to match.
  3. Deploy the pages and the header, in either order. Every combination of old and new is now allowed.
  4. When both are live, remove the old hashes and deploy once more.

The policy between steps 2 and 4, shortened:

script-src 'self'
  'sha256-Ur5KiNWZ…'  'sha256-YVehwR0W…'    # the two scripts as they were
  'sha256-zkwyRoAV…'  'sha256-S4k30bOa…'    # the same two after the change
  …

An old hash left in the policy allows only that exact old script, so step 2 costs a longer header and nothing else. Step 4 brings the list back to what the site ships.

Get the hashes from the build

A hash is the SHA-256 of the script’s text exactly as it sits between the tags, base64-encoded. I don’t compute them by hand. A script runs after every build, hashes each inline script in the output and fails the build when one is missing from the policy:

const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
for (const [, attrs, body] of html.matchAll(SCRIPT)) {
  if (/\bsrc\s*=/i.test(attrs)) continue;   // a file, covered by 'self'
  hashes.add(`'sha256-${createHash('sha256').update(body, 'utf8').digest('base64')}'`);
}

It skips scripts with a non-JavaScript type, such as JSON-LD, which the browser doesn’t execute. When a hash is missing it prints the whole script-src to paste. On the full build it checked 13,628 uses of inline scripts.

After step 4 I checked the live site too. On eight kinds of page, every inline script’s hash was in the header the server sent.