in csp/middleware.py [0:0]
def process_response(self, request: HttpRequest, response: HttpResponseBase) -> HttpResponseBase:
# Check for debug view
exempted_debug_codes = (
http_client.INTERNAL_SERVER_ERROR,
http_client.NOT_FOUND,
)
if response.status_code in exempted_debug_codes and settings.DEBUG:
return response
policy_parts = self.get_policy_parts(request=request, response=response)
csp = build_policy(**asdict(policy_parts))
if csp:
# Only set header if not already set and not an excluded prefix and not exempted.
is_not_exempt = getattr(response, "_csp_exempt", False) is False
no_header = HEADER not in response
policy = getattr(settings, "CONTENT_SECURITY_POLICY", None) or {}
prefixes = policy.get("EXCLUDE_URL_PREFIXES", None) or ()
is_not_excluded = not request.path_info.startswith(tuple(prefixes))
if no_header and is_not_exempt and is_not_excluded:
response[HEADER] = csp
policy_parts_ro = self.get_policy_parts(request=request, response=response, report_only=True)
csp_ro = build_policy(**asdict(policy_parts_ro), report_only=True)
if csp_ro:
# Only set header if not already set and not an excluded prefix and not exempted.
is_not_exempt = getattr(response, "_csp_exempt_ro", False) is False
no_header = HEADER_REPORT_ONLY not in response
policy = getattr(settings, "CONTENT_SECURITY_POLICY_REPORT_ONLY", None) or {}
prefixes = policy.get("EXCLUDE_URL_PREFIXES", None) or ()
is_not_excluded = not request.path_info.startswith(tuple(prefixes))
if no_header and is_not_exempt and is_not_excluded:
response[HEADER_REPORT_ONLY] = csp_ro
# 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.
if getattr(request, "_csp_nonce", None) is None:
setattr(request, "csp_nonce", CheckableLazyObject(self._csp_nonce_post_response))
return response