Skip to content

Commit

Permalink
Refactor CSPMiddleware for extensibility (mozillaGH-36)
Browse files Browse the repository at this point in the history
  • Loading branch information
DylanYoung committed May 26, 2022
1 parent a6685c3 commit a218956
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 16 deletions.
18 changes: 5 additions & 13 deletions csp/contrib/rate_limiting.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,20 @@
from django.conf import settings

from csp.middleware import CSPMiddleware
from csp.utils import build_policy


class RateLimitedCSPMiddleware(CSPMiddleware):
"""A CSP middleware that rate-limits the number of violation reports sent
to report-uri by excluding it from some requests."""

def build_policy(self, request, response):
build_kwargs = {
key: getattr(response, '_csp_%s' % key, None)
for key in ('config', 'update', 'select')
}
replace = getattr(response, '_csp_replace', {})
nonce = getattr(request, '_csp_nonce', None)
def get_build_kwargs(self, request, response):
build_kwargs = super().get_build_kwargs(request, response)
replace = build_kwargs['replace'] or {}

report_percentage = getattr(settings, 'CSP_REPORT_PERCENTAGE')
include_report_uri = random.random() < report_percentage
if not include_report_uri:
replace['report-uri'] = None
build_kwargs['replace'] = replace

return build_policy(
replace=replace,
nonce=nonce,
**build_kwargs,
)
return build_kwargs
9 changes: 6 additions & 3 deletions csp/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,15 @@ def process_response(self, request, response):
response[header] = ', '.join(policies)
return response

def build_policy(self, request, response):
def get_build_kwargs(self, request, response):
build_kwargs = {
key: getattr(response, '_csp_%s' % key, None)
for key in ('config', 'update', 'replace', 'select')
}
build_kwargs["nonce"] = getattr(request, '_csp_nonce', None)
return build_kwargs

def build_policy(self, request, response):
return build_policy(
nonce=getattr(request, '_csp_nonce', None),
**build_kwargs,
**self.get_build_kwargs(request, response),
)

0 comments on commit a218956

Please sign in to comment.