← Study Notes Security


Security

Content Security Policy

An HTTP header telling the browser exactly which sources of scripts, styles and other resources a page may load — an allow-list that turns most XSS from code execution into a blocked request and a console error. It is defence in depth, not a substitute for output encoding. Strict policies (nonces, no unsafe-inline) are the ones that actually help.


Purpose

CSP exists because output encoding fails sometimes — one forgotten template, one risky third-party script — and the browser is the last place the damage can be stopped. The Content-Security-Policy header declares what the page is allowed to load and run (script-src, style-src, img-src, …); anything outside the list is refused. An injected <script> that would have owned the session becomes a blocked request.

When to Use It

Blunting stored and reflected XSS on any site that renders user content; stopping exfiltration by restricting where data can be sent (connect-src); preventing clickjacking (frame-ancestors, the modern replacement for X-Frame-Options); and taming third-party script sprawl — the policy is an inventory of everyone allowed to run code on your page, which is clarifying all by itself.

Trade-offs

A strict CSP breaks things by design: inline scripts and styles, eval-based libraries, injected tag managers. The escape hatch — unsafe-inline — quietly guts the protection, which is how most deployed CSPs end up decorative. Third-party scripts churn their origins, so policies need maintenance, and report endpoints generate noise from browser extensions that was never your code.

Implementation

Deploy in Content-Security-Policy-Report-Only first and watch what would break. Move inline code into files or mark it with per-response nonces; aim for script-src 'self' 'nonce-…' with object-src 'none' and frame-ancestors 'none' unless framing is intended. A fully static site can run the strictest form — this portfolio ships script-src 'self' with no inline code at all — then enforce, and keep the report pipe open for regressions.