Skip to content

Lesson 2 of 9 · 24m

Building a Practical CSP: Nonces, Hashes, and strict-dynamic

A production-shaped policy for server-rendered apps and SPAs, with the compatibility tradeoffs explained instead of hand-waved.

The first CSP most teams write is an inventory of every CDN they have ever used. It breaks on Tuesday because marketing added a tag manager. A durable CSP starts from trust relationships, not hostnames: who is allowed to execute code, and how did they earn that trust?

A strong baseline

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-r4nd0m' 'strict-dynamic';
  style-src 'self' 'unsafe-inline';
  img-src 'self' data: https:;
  font-src 'self' data:;
  connect-src 'self' https://api.internal.example;
  object-src 'none';
  base-uri 'none';
  form-action 'self';
  frame-ancestors 'none';
  upgrade-insecure-requests

object-src 'none' kills plugin content. base-uri 'none' stops injected <base> tags from rewriting relative URLs. form-action keeps attacker markup from posting credentials or tokens somewhere else. frame-ancestors replaces most legacy clickjacking uses of X-Frame-Options.

Why strict-dynamic changes the game

A host allowlist such as script-src https://cdn.jsdelivr.net trusts every library and every version hosted there, including JSONP endpoints and attacker-chosen modules. With strict-dynamic, modern browsers trust scripts because a trusted script loaded them:

<script nonce="r4nd0m" src="/static/app.js"></script>

If /static/app.js inserts a module dependency dynamically, that child inherits trust. Host allowlist entries are ignored by browsers that implement CSP3 strict-dynamic, so backwards-compatible entries are included only for older browsers.

Important boundary: parser-inserted scripts injected after load are not automatically trusted. element.innerHTML = '<script src=...>' was always bad practice; under strict-dynamic it is also unreliable.

Hashes for unavoidable static inline snippets

import base64, hashlib
body = b"window.__BOOTSTRAP__ = true;"
digest = base64.b64encode(hashlib.sha256(body).digest()).decode()
print("sha256-" + digest)

Any whitespace change alters the hash. Hash whack-a-mole is tolerable for one bootstrap snippet and miserable for twenty analytics snippets — prefer external files or nonces.

Field notes

  • Do not put secrets in bootstrap JavaScript because "CSP protects it." CSP reduces execution risk; it does not make public data private.
  • unsafe-eval exists for legacy template engines. Treat it as technical debt with a removal date.
  • style-src 'unsafe-inline' is common because CSS is harder to nonce. It is lower risk than script execution, but not zero risk for UI redress and data-dependent selectors.
  • Generate the nonce outside templating and pass it down. If templates can print attacker-controlled nonce values, the design failed.

Was this lesson helpful?

Sign in to rate