Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rely on django-csp's private attribute for nonce #2088

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

tim-schilling
Copy link
Member

Description

This refactors how the CSP nonce is fetched. It's now done as a toolbar property and wraps the private attribute request._csp_nonce

This avoids the toolbar from generating a nonce that gets injected into the CSP header when the view doesn't expect it to. It also supports using a nonce that is generated from any other point while processing the request, including other middleware.

Fixes #2082

Checklist:

  • I have added the relevant tests for this change.
  • I have added an item to the Pending section of docs/changes.rst.

This refactors how the CSP nonce is fetched. It's now done as
a toolbar property and wraps the private attribute request._csp_nonce

This avoids the toolbar from generating a nonce that gets injected
into the CSP header when the view doesn't expect it to. It also
supports using a nonce that is generated from any other point
while processing the request, including other middleware.
@@ -42,6 +42,11 @@ def regular_view(request, title):
return render(request, "basic.html", {"title": title})


def csp_view(request):
"""Use request.csp_nonce to inject it into the headers"""
return render(request, "basic.html", {"title": f"CSP {request.csp_nonce}"})
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The nonce needed to be rendered in the view. I chose to do it here.

Comment on lines +75 to +76
for middleware in [MIDDLEWARE_CSP_BEFORE, MIDDLEWARE_CSP_LAST]:
with self.settings(MIDDLEWARE=middleware):
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It become important to test with both configurations of middleware. Or at least it will be more important if we stop relying on request._csp_nonce

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Fix failing tests in CspRenderingTestCase
2 participants