Repository navigation
Add CSP nonces to the browsable API's script tags for Django 6's built-in CSP #10108
Unanswered
jnovinger
asked this question in
Ideas & Suggestions
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Django 6.0 added built-in Content Security Policy support (
SECURE_CSP,ContentSecurityPolicyMiddleware, and thedjango.template.context_processors.cspcontext processor, which exposes the per-request nonce ascsp_nonce). The browsable API's templates don't use it: the seven<script src>tags inrest_framework/base.htmlandrest_framework/admin.htmlcarry no nonce.Since the inline JavaScript moved to static files (#6069), those scripts load fine under a policy that allows
'self'. Under'strict-dynamic', though, browsers ignore'self'and host allowlists, so all seven are blocked and the browsable API's JavaScript (the AJAX forms, CSRF handling) never runs. Django's own admin hit the same thing in ticket #36825, and Django 6.1 fixed it by adding{% csp_nonce_attr %}to the admin's tags.The change I'd propose is the same fix in DRF's two templates.
{% csp_nonce_attr %}isn't available on every Django version DRF supports, so each tag would get the equivalent:Without the CSP middleware and context processor,
csp_nonceisn't in the context and the tag renders exactly as it does today, so nothing changes for existing users. drf-spectacular has the same gap in its Swagger UI and Redoc templates (tfranzel/drf-spectacular#1559).For context, NetBox serves DRF's browsable API and is adding CSP support built on Django's for v4.8 (netbox-community/netbox#23502). For now that means overriding the
scriptblock just to add the nonce. I see this as tracking Django's new CSP support rather than a new feature, and I can open a PR if you agree.All reactions