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

Allow reading nonce if it was included in header #269

Merged
merged 3 commits into from
Feb 28, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions csp/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ class PolicyParts:
nonce: str | None = None


class FalseLazyObject(SimpleLazyObject):
def __bool__(self) -> bool:
return False


class CSPMiddleware(MiddlewareMixin):
"""
Implements the Content-Security-Policy response header, which
Expand Down Expand Up @@ -95,7 +100,8 @@ def process_response(self, request: HttpRequest, response: HttpResponseBase) ->
# Once we've written the header, accessing the `request.csp_nonce` will no longer trigger
# the nonce to be added to the header. Instead we throw an error here to catch this since
# this has security implications.
setattr(request, "csp_nonce", SimpleLazyObject(self._csp_nonce_post_response))
if getattr(request, "_csp_nonce", None) is None:
setattr(request, "csp_nonce", FalseLazyObject(self._csp_nonce_post_response))

return response

Expand All @@ -109,7 +115,12 @@ def build_policy_ro(self, request: HttpRequest, response: HttpResponseBase) -> s
policy_parts_ro = self.get_policy_parts(request=request, response=response, report_only=True)
return build_policy(**asdict(policy_parts_ro), report_only=True)

def get_policy_parts(self, request: HttpRequest, response: HttpResponseBase, report_only: bool = False) -> PolicyParts:
def get_policy_parts(
self,
request: HttpRequest,
response: HttpResponseBase,
report_only: bool = False,
) -> PolicyParts:
if report_only:
config = getattr(response, "_csp_config_ro", None)
update = getattr(response, "_csp_update_ro", None)
Expand Down
15 changes: 13 additions & 2 deletions csp/tests/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,21 @@ def test_nonce_regenerated_on_new_request() -> None:
assert nonce2 not in response1[HEADER]


def test_nonce_attribute_error() -> None:
# Test `CSPNonceError` is raised when accessing the nonce after the response has been processed.
def test_no_nonce_access_after_middleware_is_attribute_error() -> None:
# Test `CSPNonceError` is raised when accessing an unset nonce after the response has been processed.
request = rf.get("/")
mw.process_request(request)
mw.process_response(request, HttpResponse())
assert bool(getattr(request, "csp_nonce", True)) is False
with pytest.raises(CSPNonceError):
str(getattr(request, "csp_nonce"))


def test_set_nonce_access_after_middleware_is_ok() -> None:
# Test accessing a set nonce after the response has been processed is OK.
request = rf.get("/")
mw.process_request(request)
nonce = str(getattr(request, "csp_nonce"))
mw.process_response(request, HttpResponse())
assert bool(getattr(request, "csp_nonce", False)) is True
assert str(getattr(request, "csp_nonce")) == nonce