Content Security Policy and browser headers
How does Django 6’s built-in ContentSecurityPolicyMiddleware compile policy dictionaries and inject per-request nonces lazily?
Even when every template autoescapes variables, a single unsafe mark_safe call or third-party widget can smuggle an inline <script> into HTML. Content Security Policy (CSP) adds a second barrier enforced inside the browser itself: an HTTP response header telling the browser which origins — and which specific inline scripts carrying a per-request cryptographic nonce — are allowed to execute.
For more than a decade, Django teams wired this up with third-party packages like django-csp. Starting in Django 6.0 (and refined in 6.1.3), CSP lives directly inside core across two tiny, tightly engineered modules: ContentSecurityPolicyMiddleware (ContentSecurityPolicyMiddleware, 33 lines) and LazyNonce + build_policy (LazyNonce, 128 lines).
Policy dictionaries, the CSP enum.StrEnum, and deterministic compilation
Open django/. Rather than asking projects to concatenate raw header strings (where missing single quotes around 'self' or 'none' silently turns a keyword into a hostname!), Django defines CSP, an enum.StrEnum carrying both the two header names (CSP, CSP), the standard quoted keywords (CSP, CSP, CSP), and a special sentinel CSP.
In settings.py, you declare SECURE_CSP (enforced) and/or SECURE_CSP_REPORT_ONLY (audit mode) as ordinary Python dictionaries mapping directives to iterables:
SECURE_CSP = {
"default-src": [CSP.SELF],
"script-src": [CSP.SELF, CSP.NONCE],
}
When the response unwinds through ContentSecurityPolicyMiddleware, Django calls build_policy(config, nonce):
- Directives set to
NoneorFalseare skipped cleanly (making per-environment overrides trivial). - Directives set to
Trueemit valueless directives such as"upgrade-insecure-requests". - If a directive’s values are given as a Python
set, line 110 callssorted(values). Why bother sorting? Because Python’s per-process hash randomization would otherwise shuffle the order of directive sources between worker restarts, breaking ETag stability and proxy caching! - If
CSP.NONCEappears in the directive’s values, line 116 checksif (has_sentinel :. That= CSP .NONCE in values) and nonce: and noncetest is where the real elegance of Django6.1’s design lives.
How LazyNonce avoids CSPRNG work on pages that need no nonce
Generating a cryptographic nonce on every single request (static JSON APIs, redirects, images, HTML pages with no inline scripts) wastes entropy and breaks deterministic caching by injecting a unique random header into every response.
Look at ContentSecurityPolicyMiddleware:
def process_request(self, request):
request._csp_nonce = LazyNonce()
Now look at LazyNonce and generate_nonce (lines 93–94):
class LazyNonce(SimpleLazyObject):
def __init__(self):
super().__init__(generate_nonce)
def __bool__(self):
return self._wrapped is not empty
def generate_nonce():
return secrets.token_urlsafe(16)
Read those six lines twice — they are a textbook use of Python’s descriptor and truthiness protocol!
- Creating
LazyNonce()allocates only a lightweightSimpleLazyObjectwrapper with_wrapped = empty. It does not callsecrets..token_urlsafe(16) - Unlike ordinary
SimpleLazyObject(whose__bool__forces evaluation of the wrapped object),LazyNonceoverrides truthiness without evaluating the lazy object: it simply checks.__bool__ self!._wrapped is not empty - If the view or template never coerces
"csp_nonce"(exposed viadjango,.template .context_processors .csp csp, orget_nonce(request)) into a string,_wrappedstaysempty. Whenbuild_policylater testsand nonce,bool(nonce)returnsFalse, sobuild_policystripsCSP.NONCEright out of the header — emitting"default-src 'self'; script-src 'self'"with zero CSPRNG calls and a completely static header! - The instant a template renders
<script nonce="{{ csp_nonce }}">(or{% csp_nonce_attr %}vianonce_attr,nonce_attr), string conversion triggersSimpleLazyObject, which calls._setup() secrets— 16 random bytes = 128 bits of entropy = a 22-character URL-safe base64 token — and caches it in.token_urlsafe(16) _wrapped. Nowbool(nonce)isTrue, andbuild_policyreplacesCSP.NONCEwith"'nonce-<token>'"!
Verify both paths — plus per-view @csp_override — live on Django 6.1.3:
Django 6 ContentSecurityPolicyMiddleware and LazyNonce
view does NOT read csp_nonce -> bool_in_view=False Content-Security-Policy="default-src 'self'; script-src 'self'"
view READS csp_nonce -> before=False after=True len=22 nonce_in_header=True Content-Security-Policy="default-src 'self'; script-src 'self' 'nonce-<22-char-nonce>'"
@csp_override(default-src 'none') -> Content-Security-Policy="default-src 'none'"
And check the microsecond cost we measured in ch05-bench:
+ Security + XFrameOptions (GET) 91.2 + 19.4
+ Security + XFO + CSP (nonce unused) 97.2 + 25.4
+ Security + XFO + CSP (nonce read) 112.3 + 40.5
When a view leaves LazyNonce unread, ContentSecurityPolicyMiddleware adds just +6.0 us (91.2 -> 97.2 us). Reading the nonce costs +15.1 us (97.2 -> 112.3 us) for secrets and header interpolation.
Per-view overrides and StreamingHttpResponse timing
Look at ContentSecurityPolicyMiddleware:
- It uses a fresh
sentinel = object()to checkgetattr(response, "_csp_config", sentinel)— distinguishing “this view used@csp_override({})to suppress the header entirely” (remember Chapter 4’stechnical_500_response!) from “this view set no override, so fall back tosettings”..SECURE_CSP - It honors
header not in response, so a view that setsresponsedirectly is never overwritten..headers["Content-Security-Policy"] - Because
process_responseruns after the view returns (and for aTemplateResponse, after template rendering completes), any nonce read inside the template is already evaluated by the timebuild_policyruns.
Where CSP and LazyNonce leak
- Caching a page that rendered
"csp_nonce"breaks every subsequent visitor. Because a nonce must be fresh on every response, serving a cached HTML document carrying yesterday’s<script nonce="abc...">alongside a response header carrying today’s nonce (or no nonce at all) causes the browser to block all of your own scripts. Never cache responses that evaluateLazyNoncein a shared cache. - Reading
"csp_nonce"inside aStreamingHttpResponsegenerator happens too late.process_responseruns and writes the HTTP headers before WSGI/ASGI starts iterating the streaming body. If a streaming generator touches"csp_nonce"lazily while yielding chunks,bool(nonce)was stillFalsewhenbuild_policyran — so the response header has no nonce and the browser blocks the streamed<script>. Forcestr(get_nonce(request))before returning theStreamingHttpResponse. if csp_nonce:in Python or template code checks whether the nonce was already evaluated, not whether CSP middleware is installed. That behavior is intentional (LazyNoncelets third-party libraries emit.__bool__ nonce="..."only if the page already opted in), yet developers who writeif get_nonce(request):expecting a truthy check for “is CSP enabled?” getFalse! Checkget_nonce(request) is not Noneinstead.
CSP restricts what scripts a browser will run if HTML is injected; the next section examines how Django prevents framing attacks and stops raw HTML injection from entering your templates in the first place: Framing rules and safe strings.