Allow reading nonce if it was included in header#269
Merged
jwhitlock merged 3 commits intomozilla:mainfrom Feb 28, 2025
Merged
Conversation
If the nonce was generated before the CSP headers were set, then allow reading it with request.csp_nonce. If the CSP headers were set with no nonce, then continue raising CSPNonceError when reading it as a string. If read as a boolean, then return False. This will allow other middleware like django-debug-toolbar to alter the response after the CSP middleware runs.
robhudson
reviewed
Feb 27, 2025
jwhitlock
commented
Feb 27, 2025
Contributor
Author
jwhitlock
left a comment
There was a problem hiding this comment.
Thanks @robhudson, I'll add some docs. And maybe another middleware that always generates the nonce...
This variant middleware always generates the nonce. This is useful when a process that runs after the middleware needs the nonce. One example is the middleware used by django-debug-toolbar (DDT). It needs to be defined early in the MIDDLEWARE list that it can inject HTML, CSS, and JavaScript after the response has been generated. DDT users could use this middleware to ensure the CSP nonce is always available for its asset.
Contributor
Author
|
I added a commit:
I meant to do this over two commits, |
Collaborator
|
The I like these changes. |
robhudson
approved these changes
Feb 28, 2025
2 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
If the nonce was generated before the CSP headers were set, then allow reading it with
request.csp_nonce.If the CSP headers were set with no nonce, then continue raising
CSPNonceErrorwhen reading it as a string. If read as a boolean (if request.csp_nonce), then returnFalse.This will allow other middleware like django-debug-toolbar to alter the response after the CSP middleware runs, fixing #268.