Setting a Content Security Policy

A strict Content Security Policy (CSP) blocks whole classes of injection attacks at the browser boundary. Many teams skip strict policies because tuning them takes care, and a tight rule can break sloppy frontend code.

Permissive Policies

Too many sites ship a token CSP header with 'unsafe-inline' or broad wildcards like *.googleapis.com:

Content-Security-Policy: default-src 'self' 'unsafe-inline' https:;

That header adds little defense against Cross-Site Scripting (XSS). If an attacker finds an injection point, the browser runs the injected inline script or loads code from any HTTPS host.

A Tighter Baseline

On this portfolio, I restrict scripts, styles, and fonts to the site origin:

CONTENT_SECURITY_POLICY = {
    "DIRECTIVES": {
        "default-src": ["'self'"],
        "script-src": ["'self'"],
        "style-src": ["'self'"],
        "font-src": ["'self'"],
        "img-src": ["'self'", "data:"],
        "frame-ancestors": ["'none'"],
        "base-uri": ["'self'"],
        "form-action": ["'self'"],
    }
}

Self-hosting fonts and stylesheets and avoiding inline scripts lets you enforce this policy without exceptions. Consistent rules at the HTTP boundary catch mistakes before they reach a visitor's browser.

← Journal