pax_global_header 0000666 0000000 0000000 00000000064 13715033274 0014517 g ustar 00root root 0000000 0000000 52 comment=7fd8c50c0f4cfddfa47ef36ae77c92af9dae8281
django-csp-3.7/ 0000775 0000000 0000000 00000000000 13715033274 0013415 5 ustar 00root root 0000000 0000000 django-csp-3.7/.gitignore 0000664 0000000 0000000 00000000063 13715033274 0015404 0 ustar 00root root 0000000 0000000 *.py[co]
*.egg-info
*.db
*.sw[po]
.cache
.tox
dist
django-csp-3.7/.travis.yml 0000664 0000000 0000000 00000003672 13715033274 0015536 0 ustar 00root root 0000000 0000000 sudo: false
language: python
python:
- '2.7'
- '3.4'
- '3.5'
- '3.6'
- '3.7'
- 'pypy'
- 'pypy3'
env:
- DJANGO_VERSION=2.2.x
- DJANGO_VERSION=2.1.x
- DJANGO_VERSION=2.0.x
- DJANGO_VERSION=1.11.x
- DJANGO_VERSION=1.10.x
- DJANGO_VERSION=1.9.x
- DJANGO_VERSION=1.8.x
matrix:
include:
- python: '3.8'
env: DJANGO_VERSION=master
dist: xenial # meet SQLite >=3.8.3 requirement
- python: '3.7'
env: DJANGO_VERSION=master
dist: xenial # meet SQLite >=3.8.3 requirement
- python: '3.6'
env: DJANGO_VERSION=master
dist: xenial # meet SQLite >=3.8.3 requirement
- python: '3.8'
env: DJANGO_VERSION=3.0.x
dist: xenial # meet SQLite >=3.8.3 requirement
- python: '3.7'
env: DJANGO_VERSION=3.0.x
dist: xenial # meet SQLite >=3.8.3 requirement
- python: '3.6'
env: DJANGO_VERSION=3.0.x
dist: xenial # meet SQLite >=3.8.3 requirement
exclude:
- python: '2.7'
env: DJANGO_VERSION=2.2.x
- python: '3.4'
env: DJANGO_VERSION=2.2.x
- python: 'pypy'
env: DJANGO_VERSION=2.2.x
- python: '2.7'
env: DJANGO_VERSION=2.1.x
- python: '3.4'
env: DJANGO_VERSION=2.1.x
- python: 'pypy'
env: DJANGO_VERSION=2.1.x
- python: '2.7'
env: DJANGO_VERSION=2.0.x
- python: 'pypy'
env: DJANGO_VERSION=2.0.x
- python: '3.7'
env: DJANGO_VERSION=1.10.x
- python: '3.6'
env: DJANGO_VERSION=1.10.x
- python: '3.7'
env: DJANGO_VERSION=1.9.x
- python: '3.6'
env: DJANGO_VERSION=1.9.x
- python: '3.7'
env: DJANGO_VERSION=1.8.x
- python: '3.6'
env: DJANGO_VERSION=1.8.x
install:
- pip install tox coveralls
script:
- tox -e "$TRAVIS_PYTHON_VERSION-$DJANGO_VERSION"
after_success:
- coveralls
deploy:
provider: pypi
distributions: sdist bdist_wheel
user: "__token__"
on:
tags: true
repo: mozilla/django-csp
python: "3.7"
django-csp-3.7/CHANGES 0000664 0000000 0000000 00000004521 13715033274 0014412 0 ustar 00root root 0000000 0000000 =======
CHANGES
=======
3.7
===
- Add support for Trusted Types
- Use 128 bits base64 encoded for nonce
3.6
===
- Add support/testing for Django 2.2 and 3.0
- Add support/testing for Python 3.7 and 3.8
- Disable CSP for Django NotFound debug view
- Add new headers used in CSP level 3
- Add support for the report-to directive
3.5
===
- New RateLimitedCSPMiddleware middleware (#97)
- Add support for csp nonce and "script" template tag. (#78)
- Various smaller fixes along the way
3.4
===
- Remove support for Django 1.6 and 1.7 as they're out of life
- Adds pypy3, Django 2.0.x and current Django master to our CI tests
- Allow removing directives using @csp_replace
- Add CSP nonce support
3.3
===
- Add support for Django 1.11
- Add support for Python 3.6
3.2
===
- Add manifest-src fetch directive - https://w3c.github.io/webappsec-csp/#directive-manifest-src
- Add worker-src fetch directive - https://w3c.github.io/webappsec-csp/#directive-worker-src
- Add plugin-types document directive - https://w3c.github.io/webappsec-csp/#directive-plugin-types
- Add require-sri-for https://www.w3.org/TR/CSP/#directives-elsewhere - https://w3c.github.io/webappsec-subresource-integrity/#request-verification-algorithms
- Add upgrade-insecure-requests - https://w3c.github.io/webappsec-upgrade-insecure-requests/#delivery
- Add block-all-mixed-content - https://w3c.github.io/webappsec-mixed-content/
- Add deprecation warning for child-src (#80)
3.1
===
- Add support for Django 1.10 middlewares
- Allow lazy objects to be assigned to CSP_REPORT_URI
v3.0
====
- Add support for Python 3 and PyPy
- Move to pytest for testing
- Add wheel build support
- Drops support for Django < 1.6, adds support for Django 1.6, 1.7, 1.8 and 1.9
- Remove leftover references to the old report processing feature (#64)
- Fix accidental mutation of config (#52)
Please note that this is a big release that touches quite a few parts so please
make sure you're testing thoroughly and report any issues to
https://github.com/mozilla/django-csp/issues
v2.0.3
======
- Disable CSP on built-in error pages.
v2.0.1 & v2.0.2
===============
No changes. I just can't package Python files.
v2.0
====
- Dropped report processing feature and code.
- Complies with CSP v1.0 and v1.1 (excluding experimental features).
- Dropped support for X-Content-Security-Policy and X-WebKit-CSP
headers.
django-csp-3.7/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000001263 13715033274 0016216 0 ustar 00root root 0000000 0000000 # Community Participation Guidelines
This repository is governed by Mozilla's code of conduct and etiquette guidelines.
For more details, please read the
[Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/).
## How to Report
For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page.
django-csp-3.7/LICENSE 0000664 0000000 0000000 00000002766 13715033274 0014435 0 ustar 00root root 0000000 0000000 Copyright (c) 2013, Mozilla Foundation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of django-csp nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
django-csp-3.7/MANIFEST.in 0000664 0000000 0000000 00000000043 13715033274 0015150 0 ustar 00root root 0000000 0000000 include LICENSE
include README.rst
django-csp-3.7/README.rst 0000664 0000000 0000000 00000001455 13715033274 0015111 0 ustar 00root root 0000000 0000000
.. image:: https://badge.fury.io/py/django-csp.svg
:target: https://pypi.python.org/pypi/django_csp
.. image:: https://travis-ci.org/mozilla/django-csp.svg?branch=master
:target: https://travis-ci.org/mozilla/django-csp
.. image:: https://coveralls.io/repos/github/mozilla/django-csp/badge.svg?branch=master
:target: https://coveralls.io/github/mozilla/django-csp?branch=master
==========
Django-CSP
==========
Django-CSP adds Content-Security-Policy_ headers to Django.
The code lives on GitHub_, where you can report Issues_. The full
documentation is available on ReadTheDocs_.
.. _Content-Security-Policy: http://www.w3.org/TR/CSP/
.. _GitHub: https://github.com/mozilla/django-csp
.. _Issues: https://github.com/mozilla/django-csp/issues
.. _ReadTheDocs: http://django-csp.readthedocs.org/
django-csp-3.7/csp/ 0000775 0000000 0000000 00000000000 13715033274 0014202 5 ustar 00root root 0000000 0000000 django-csp-3.7/csp/__init__.py 0000664 0000000 0000000 00000000000 13715033274 0016301 0 ustar 00root root 0000000 0000000 django-csp-3.7/csp/context_processors.py 0000664 0000000 0000000 00000000212 13715033274 0020515 0 ustar 00root root 0000000 0000000 def nonce(request):
nonce = request.csp_nonce if hasattr(request, 'csp_nonce') else ''
return {
'CSP_NONCE': nonce
}
django-csp-3.7/csp/contrib/ 0000775 0000000 0000000 00000000000 13715033274 0015642 5 ustar 00root root 0000000 0000000 django-csp-3.7/csp/contrib/__init__.py 0000664 0000000 0000000 00000000000 13715033274 0017741 0 ustar 00root root 0000000 0000000 django-csp-3.7/csp/contrib/rate_limiting.py 0000664 0000000 0000000 00000001614 13715033274 0021045 0 ustar 00root root 0000000 0000000 import random
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):
config = getattr(response, '_csp_config', None)
update = getattr(response, '_csp_update', None)
replace = getattr(response, '_csp_replace', {})
nonce = getattr(request, '_csp_nonce', None)
report_percentage = getattr(settings, 'CSP_REPORT_PERCENTAGE')
include_report_uri = random.random() < report_percentage
if not include_report_uri:
replace['report-uri'] = None
return build_policy(config=config, update=update, replace=replace,
nonce=nonce)
django-csp-3.7/csp/decorators.py 0000664 0000000 0000000 00000002216 13715033274 0016722 0 ustar 00root root 0000000 0000000 from functools import wraps
def csp_exempt(f):
@wraps(f)
def _wrapped(*a, **kw):
r = f(*a, **kw)
r._csp_exempt = True
return r
return _wrapped
def csp_update(**kwargs):
update = dict((k.lower().replace('_', '-'), v) for k, v in kwargs.items())
def decorator(f):
@wraps(f)
def _wrapped(*a, **kw):
r = f(*a, **kw)
r._csp_update = update
return r
return _wrapped
return decorator
def csp_replace(**kwargs):
replace = dict((k.lower().replace('_', '-'), v) for k, v in kwargs.items())
def decorator(f):
@wraps(f)
def _wrapped(*a, **kw):
r = f(*a, **kw)
r._csp_replace = replace
return r
return _wrapped
return decorator
def csp(**kwargs):
config = dict(
(k.lower().replace('_', '-'), [v] if isinstance(v, str) else v)
for k, v
in kwargs.items()
)
def decorator(f):
@wraps(f)
def _wrapped(*a, **kw):
r = f(*a, **kw)
r._csp_config = config
return r
return _wrapped
return decorator
django-csp-3.7/csp/extensions/ 0000775 0000000 0000000 00000000000 13715033274 0016401 5 ustar 00root root 0000000 0000000 django-csp-3.7/csp/extensions/__init__.py 0000664 0000000 0000000 00000003357 13715033274 0020522 0 ustar 00root root 0000000 0000000 from __future__ import absolute_import
from jinja2 import nodes
from jinja2.ext import Extension
from csp.utils import SCRIPT_ATTRS, build_script_tag
class NoncedScript(Extension):
# a set of names that trigger the extension.
tags = set(['script'])
def parse(self, parser):
# the first token is the token that started the tag. In our case
# we only listen to ``'script'`` so this will be a name token with
# `script` as value. We get the line number so that we can give
# that line number to the nodes we create by hand.
lineno = next(parser.stream).lineno
# Get the current context and pass along
kwargs = [nodes.Keyword('ctx', nodes.ContextReference())]
# Parse until we are done with optional script tag attributes
while parser.stream.current.value in SCRIPT_ATTRS:
attr_name = parser.stream.current.value
parser.stream.skip(2)
kwargs.append(
nodes.Keyword(attr_name, parser.parse_expression()))
# now we parse the body of the script block up to `endscript` and
# drop the needle (which would always be `endscript` in that case)
body = parser.parse_statements(['name:endscript'], drop_needle=True)
# now return a `CallBlock` node that calls our _render_script
# helper method on this extension.
return nodes.CallBlock(
self.call_method('_render_script', kwargs=kwargs),
[], [], body).set_lineno(lineno)
def _render_script(self, caller, **kwargs):
ctx = kwargs.pop('ctx')
request = ctx.get('request')
kwargs['nonce'] = request.csp_nonce
kwargs['content'] = caller().strip()
return build_script_tag(**kwargs)
django-csp-3.7/csp/middleware.py 0000664 0000000 0000000 00000005244 13715033274 0016676 0 ustar 00root root 0000000 0000000 from __future__ import absolute_import
import os
import base64
from functools import partial
from django.conf import settings
from django.utils.functional import SimpleLazyObject
try:
from django.utils.six.moves import http_client
except ImportError:
# django 3.x removed six
import http.client as http_client
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
class MiddlewareMixin(object):
"""
If this middleware doesn't exist, this is an older version of django
and we don't need it.
"""
pass
from csp.utils import build_policy
class CSPMiddleware(MiddlewareMixin):
"""
Implements the Content-Security-Policy response header, which
conforming user-agents can use to restrict the permitted sources
of various content.
See http://www.w3.org/TR/CSP/
"""
def _make_nonce(self, request):
# Ensure that any subsequent calls to request.csp_nonce return the
# same value
if not getattr(request, '_csp_nonce', None):
request._csp_nonce = (
base64
.b64encode(os.urandom(16))
.decode("ascii")
)
return request._csp_nonce
def process_request(self, request):
nonce = partial(self._make_nonce, request)
request.csp_nonce = SimpleLazyObject(nonce)
def process_response(self, request, response):
if getattr(response, '_csp_exempt', False):
return response
# Check for ignored path prefix.
prefixes = getattr(settings, 'CSP_EXCLUDE_URL_PREFIXES', ())
if request.path_info.startswith(prefixes):
return response
# Check for debug view
status_code = response.status_code
exempted_debug_codes = (
http_client.INTERNAL_SERVER_ERROR,
http_client.NOT_FOUND,
)
if status_code in exempted_debug_codes and settings.DEBUG:
return response
header = 'Content-Security-Policy'
if getattr(settings, 'CSP_REPORT_ONLY', False):
header += '-Report-Only'
if header in response:
# Don't overwrite existing headers.
return response
response[header] = self.build_policy(request, response)
return response
def build_policy(self, request, response):
config = getattr(response, '_csp_config', None)
update = getattr(response, '_csp_update', None)
replace = getattr(response, '_csp_replace', None)
nonce = getattr(request, '_csp_nonce', None)
return build_policy(config=config, update=update, replace=replace,
nonce=nonce)
django-csp-3.7/csp/models.py 0000664 0000000 0000000 00000000046 13715033274 0016037 0 ustar 00root root 0000000 0000000 # This file intentionally left blank.
django-csp-3.7/csp/templatetags/ 0000775 0000000 0000000 00000000000 13715033274 0016674 5 ustar 00root root 0000000 0000000 django-csp-3.7/csp/templatetags/__init__.py 0000664 0000000 0000000 00000000000 13715033274 0020773 0 ustar 00root root 0000000 0000000 django-csp-3.7/csp/templatetags/csp.py 0000664 0000000 0000000 00000002443 13715033274 0020036 0 ustar 00root root 0000000 0000000 from __future__ import absolute_import
from django import template
from django.template.base import token_kwargs
from csp.utils import build_script_tag
register = template.Library()
def _unquote(s):
"""Helper func that strips single and double quotes from inside strings"""
return s.replace('"', '').replace("'", "")
@register.tag(name='script')
def script(parser, token):
# Parse out any keyword args
token_args = token.split_contents()
kwargs = token_kwargs(token_args[1:], parser)
nodelist = parser.parse(('endscript',))
parser.delete_first_token()
return NonceScriptNode(nodelist, **kwargs)
class NonceScriptNode(template.Node):
def __init__(self, nodelist, **kwargs):
self.nodelist = nodelist
self.script_attrs = {}
for k, v in kwargs.items():
self.script_attrs[k] = self._get_token_value(v)
def _get_token_value(self, t):
return _unquote(t.token) if getattr(t, 'token', None) else None
def render(self, context):
output = self.nodelist.render(context).strip()
request = context.get('request')
nonce = request.csp_nonce if hasattr(request, 'csp_nonce') else ''
self.script_attrs.update({'nonce': nonce, 'content': output})
return build_script_tag(**self.script_attrs)
django-csp-3.7/csp/tests/ 0000775 0000000 0000000 00000000000 13715033274 0015344 5 ustar 00root root 0000000 0000000 django-csp-3.7/csp/tests/__init__.py 0000664 0000000 0000000 00000000000 13715033274 0017443 0 ustar 00root root 0000000 0000000 django-csp-3.7/csp/tests/environment.py 0000664 0000000 0000000 00000000155 13715033274 0020263 0 ustar 00root root 0000000 0000000 from jinja2 import Environment
def environment(**options):
env = Environment(**options)
return env
django-csp-3.7/csp/tests/settings.py 0000664 0000000 0000000 00000001710 13715033274 0017555 0 ustar 00root root 0000000 0000000 import django
CSP_REPORT_ONLY = False
CSP_INCLUDE_NONCE_IN = ['default-src']
DATABASES = {
'default': {
'NAME': 'test.db',
'ENGINE': 'django.db.backends.sqlite3',
}
}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'csp',
)
SECRET_KEY = 'csp-test-key'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'environment': 'csp.tests.environment.environment',
'extensions': ['csp.extensions.NoncedScript']
},
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {},
},
]
# Django >1.6 requires `setup` call to initialise apps framework
if hasattr(django, 'setup'):
django.setup()
django-csp-3.7/csp/tests/test_context_processors.py 0000664 0000000 0000000 00000001145 13715033274 0022724 0 ustar 00root root 0000000 0000000 from django.http import HttpResponse
from django.test import RequestFactory
from csp.middleware import CSPMiddleware
from csp.context_processors import nonce
rf = RequestFactory()
mw = CSPMiddleware()
def test_nonce_context_processor():
request = rf.get('/')
mw.process_request(request)
context = nonce(request)
response = HttpResponse()
mw.process_response(request, response)
assert context['CSP_NONCE'] == request.csp_nonce
def test_nonce_context_processor_with_middleware_disabled():
request = rf.get('/')
context = nonce(request)
assert context['CSP_NONCE'] == ''
django-csp-3.7/csp/tests/test_contrib.py 0000664 0000000 0000000 00000001224 13715033274 0020414 0 ustar 00root root 0000000 0000000 from django.http import HttpResponse
from django.test import RequestFactory
from django.test.utils import override_settings
from csp.contrib.rate_limiting import RateLimitedCSPMiddleware
HEADER = 'Content-Security-Policy'
mw = RateLimitedCSPMiddleware()
rf = RequestFactory()
@override_settings(CSP_REPORT_PERCENTAGE=0.1, CSP_REPORT_URI='x')
def test_report_percentage():
times_seen = 0
for _ in range(5000):
request = rf.get('/')
response = HttpResponse()
mw.process_response(request, response)
if 'report-uri' in response[HEADER]:
times_seen += 1
# Roughly 10%
assert 400 <= times_seen <= 600
django-csp-3.7/csp/tests/test_decorators.py 0000664 0000000 0000000 00000010243 13715033274 0021122 0 ustar 00root root 0000000 0000000 from django.http import HttpResponse
from django.test import RequestFactory
from django.test.utils import override_settings
from csp.decorators import csp, csp_replace, csp_update, csp_exempt
from csp.middleware import CSPMiddleware
REQUEST = RequestFactory().get('/')
mw = CSPMiddleware()
def test_csp_exempt():
@csp_exempt
def view(request):
return HttpResponse()
response = view(REQUEST)
assert response._csp_exempt
@override_settings(CSP_IMG_SRC=['foo.com'])
def test_csp_update():
def view_without_decorator(request):
return HttpResponse()
response = view_without_decorator(REQUEST)
mw.process_response(REQUEST, response)
policy_list = sorted(response['Content-Security-Policy'].split("; "))
assert policy_list == ["default-src 'self'", "img-src foo.com"]
@csp_update(IMG_SRC='bar.com')
def view_with_decorator(request):
return HttpResponse()
response = view_with_decorator(REQUEST)
assert response._csp_update == {'img-src': 'bar.com'}
mw.process_response(REQUEST, response)
policy_list = sorted(response['Content-Security-Policy'].split("; "))
assert policy_list == ["default-src 'self'", "img-src foo.com bar.com"]
response = view_without_decorator(REQUEST)
mw.process_response(REQUEST, response)
policy_list = sorted(response['Content-Security-Policy'].split("; "))
assert policy_list == ["default-src 'self'", "img-src foo.com"]
@override_settings(CSP_IMG_SRC=['foo.com'])
def test_csp_replace():
def view_without_decorator(request):
return HttpResponse()
response = view_without_decorator(REQUEST)
mw.process_response(REQUEST, response)
policy_list = sorted(response['Content-Security-Policy'].split("; "))
assert policy_list == ["default-src 'self'", "img-src foo.com"]
@csp_replace(IMG_SRC='bar.com')
def view_with_decorator(request):
return HttpResponse()
response = view_with_decorator(REQUEST)
assert response._csp_replace == {'img-src': 'bar.com'}
mw.process_response(REQUEST, response)
policy_list = sorted(response['Content-Security-Policy'].split("; "))
assert policy_list == ["default-src 'self'", "img-src bar.com"]
response = view_without_decorator(REQUEST)
mw.process_response(REQUEST, response)
policy_list = sorted(response['Content-Security-Policy'].split("; "))
assert policy_list == ["default-src 'self'", "img-src foo.com"]
@csp_replace(IMG_SRC=None)
def view_removing_directive(request):
return HttpResponse()
response = view_removing_directive(REQUEST)
mw.process_response(REQUEST, response)
policy_list = sorted(response["Content-Security-Policy"].split("; "))
assert policy_list == ["default-src 'self'"]
def test_csp():
def view_without_decorator(request):
return HttpResponse()
response = view_without_decorator(REQUEST)
mw.process_response(REQUEST, response)
policy_list = sorted(response['Content-Security-Policy'].split("; "))
assert policy_list == ["default-src 'self'"]
@csp(IMG_SRC=['foo.com'], FONT_SRC=['bar.com'])
def view_with_decorator(request):
return HttpResponse()
response = view_with_decorator(REQUEST)
assert response._csp_config == \
{'img-src': ['foo.com'], 'font-src': ['bar.com']}
mw.process_response(REQUEST, response)
policy_list = sorted(response['Content-Security-Policy'].split("; "))
assert policy_list == ["font-src bar.com", "img-src foo.com"]
response = view_without_decorator(REQUEST)
mw.process_response(REQUEST, response)
policy_list = sorted(response['Content-Security-Policy'].split("; "))
assert policy_list == ["default-src 'self'"]
def test_csp_string_values():
# Test backwards compatibility where values were strings
@csp(IMG_SRC='foo.com', FONT_SRC='bar.com')
def view_with_decorator(request):
return HttpResponse()
response = view_with_decorator(REQUEST)
assert response._csp_config == \
{'img-src': ['foo.com'], 'font-src': ['bar.com']}
mw.process_response(REQUEST, response)
policy_list = sorted(response['Content-Security-Policy'].split("; "))
assert policy_list == ["font-src bar.com", "img-src foo.com"]
django-csp-3.7/csp/tests/test_jinja_extension.py 0000664 0000000 0000000 00000004761 13715033274 0022154 0 ustar 00root root 0000000 0000000 from csp.tests.utils import ScriptExtensionTestBase
class TestJinjaExtension(ScriptExtensionTestBase):
def test_script_tag_injects_nonce(self):
tpl = """
{% script %}
var hello='world';
{% endscript %}
"""
expected = ("""""")
self.assert_template_eq(*self.process_templates(tpl, expected))
def test_script_with_src_ignores_body(self):
tpl = """
{% script src="foo" %}
var hello='world';
{% endscript %}
"""
expected = """"""
self.assert_template_eq(*self.process_templates(tpl, expected))
def test_script_tag_sets_attrs_correctly(self):
tpl = """
{% script id='jeff' defer=True %}
var hello='world';
{% endscript %}
"""
expected = """
"""
self.assert_template_eq(*self.process_templates(tpl, expected))
def test_async_attribute_with_falsey(self):
tpl = """
{% script id="jeff" async=False %}
var hello='world';
{% endscript %}"""
expected = ('')
self.assert_template_eq(*self.process_templates(tpl, expected))
def test_async_attribute_with_truthy(self):
tpl = """
{% script id="jeff" async=True %}
var hello='world';
{% endscript %}"""
expected = ('')
self.assert_template_eq(*self.process_templates(tpl, expected))
def test_nested_script_tags_are_removed(self):
"""Let users wrap their code in script tags for the sake of their
development environment"""
tpl = """
{% script type="application/javascript" id="jeff" defer=True%}
{% endscript %}"""
expected = (
'')
self.assert_template_eq(*self.process_templates(tpl, expected))
django-csp-3.7/csp/tests/test_middleware.py 0000664 0000000 0000000 00000007503 13715033274 0021077 0 ustar 00root root 0000000 0000000 from django.http import (
HttpResponse,
HttpResponseServerError,
HttpResponseNotFound,
)
from django.test import RequestFactory
from django.test.utils import override_settings
from csp.middleware import CSPMiddleware
HEADER = 'Content-Security-Policy'
mw = CSPMiddleware()
rf = RequestFactory()
def test_add_header():
request = rf.get('/')
response = HttpResponse()
mw.process_response(request, response)
assert HEADER in response
def test_exempt():
request = rf.get('/')
response = HttpResponse()
response._csp_exempt = True
mw.process_response(request, response)
assert HEADER not in response
@override_settings(CSP_EXCLUDE_URL_PREFIXES=('/inlines-r-us'))
def text_exclude():
request = rf.get('/inlines-r-us/foo')
response = HttpResponse()
mw.process_response(request, response)
assert HEADER not in response
@override_settings(CSP_REPORT_ONLY=True)
def test_report_only():
request = rf.get('/')
response = HttpResponse()
mw.process_response(request, response)
assert HEADER not in response
assert HEADER + '-Report-Only' in response
def test_dont_replace():
request = rf.get('/')
response = HttpResponse()
response[HEADER] = 'default-src example.com'
mw.process_response(request, response)
assert response[HEADER] == 'default-src example.com'
def test_use_config():
request = rf.get('/')
response = HttpResponse()
response._csp_config = {'default-src': ['example.com']}
mw.process_response(request, response)
assert response[HEADER] == 'default-src example.com'
def test_use_update():
request = rf.get('/')
response = HttpResponse()
response._csp_update = {'default-src': ['example.com']}
mw.process_response(request, response)
assert response[HEADER] == "default-src 'self' example.com"
@override_settings(CSP_IMG_SRC=['foo.com'])
def test_use_replace():
request = rf.get('/')
response = HttpResponse()
response._csp_replace = {'img-src': ['bar.com']}
mw.process_response(request, response)
policy_list = sorted(response[HEADER].split('; '))
assert policy_list == ["default-src 'self'", "img-src bar.com"]
@override_settings(DEBUG=True)
def test_debug_errors_exempt():
request = rf.get('/')
response = HttpResponseServerError()
mw.process_response(request, response)
assert HEADER not in response
@override_settings(DEBUG=True)
def test_debug_notfound_exempt():
request = rf.get('/')
response = HttpResponseNotFound()
mw.process_response(request, response)
assert HEADER not in response
def test_nonce_created_when_accessed():
request = rf.get('/')
mw.process_request(request)
nonce = str(request.csp_nonce)
response = HttpResponse()
mw.process_response(request, response)
assert nonce in response[HEADER]
def test_no_nonce_when_not_accessed():
request = rf.get('/')
mw.process_request(request)
response = HttpResponse()
mw.process_response(request, response)
assert 'nonce-' not in response[HEADER]
def test_nonce_regenerated_on_new_request():
request1 = rf.get('/')
request2 = rf.get('/')
mw.process_request(request1)
mw.process_request(request2)
nonce1 = str(request1.csp_nonce)
nonce2 = str(request2.csp_nonce)
assert request1.csp_nonce != request2.csp_nonce
response1 = HttpResponse()
response2 = HttpResponse()
mw.process_response(request1, response1)
mw.process_response(request2, response2)
assert nonce1 not in response2[HEADER]
assert nonce2 not in response1[HEADER]
@override_settings(CSP_INCLUDE_NONCE_IN=[])
def test_no_nonce_when_disabled_by_settings():
request = rf.get('/')
mw.process_request(request)
nonce = str(request.csp_nonce)
response = HttpResponse()
mw.process_response(request, response)
assert nonce not in response[HEADER]
django-csp-3.7/csp/tests/test_templatetags.py 0000664 0000000 0000000 00000005051 13715033274 0021450 0 ustar 00root root 0000000 0000000 from csp.tests.utils import ScriptTagTestBase
class TestDjangoTemplateTag(ScriptTagTestBase):
def test_script_tag_injects_nonce(self):
tpl = """
{% load csp %}
{% script %}var hello='world';{% endscript %}"""
expected = """"""
self.assert_template_eq(*self.process_templates(tpl, expected))
def test_script_with_src_ignores_body(self):
tpl = ("""
{% load csp %}
{% script src="foo" %}
var hello='world';
{% endscript %}""")
expected = """"""
self.assert_template_eq(*self.process_templates(tpl, expected))
def test_script_tag_sets_attrs_correctly(self):
tpl = """
{% load csp %}
{% script type="application/javascript" id="jeff" defer=True%}
var hello='world';
{% endscript %}"""
expected = (
'')
self.assert_template_eq(*self.process_templates(tpl, expected))
def test_async_attribute_with_falsey(self):
tpl = """
{% load csp %}
{% script src="foo.com/bar.js" async=False %}
{% endscript %}"""
expected = ('')
self.assert_template_eq(*self.process_templates(tpl, expected))
def test_async_attribute_with_truthy(self):
tpl = """
{% load csp %}
{% script src="foo.com/bar.js" async=True %}
var hello='world';
{% endscript %}"""
expected = ''
self.assert_template_eq(*self.process_templates(tpl, expected))
def test_nested_script_tags_are_removed(self):
"""Lets end users wrap their code in script tags for the sake of their
development environment"""
tpl = """
{% load csp %}
{% script type="application/javascript" id="jeff" defer=True%}
{% endscript %}"""
expected = (
'')
self.assert_template_eq(*self.process_templates(tpl, expected))
django-csp-3.7/csp/tests/test_utils.py 0000664 0000000 0000000 00000021020 13715033274 0020110 0 ustar 00root root 0000000 0000000 from __future__ import absolute_import
import pytest
import six
from django.conf import settings
from django.test.utils import override_settings
from django.utils.functional import lazy
from csp.utils import build_policy
def policy_eq(a, b, msg='%r != %r'):
parts_a = sorted(a.split('; '))
parts_b = sorted(b.split('; '))
assert parts_a == parts_b, msg % (a, b)
def test_empty_policy():
policy = build_policy()
assert "default-src 'self'" == policy
def literal(s):
return s
lazy_literal = lazy(literal, six.text_type)
@override_settings(CSP_DEFAULT_SRC=['example.com', 'example2.com'])
def test_default_src():
policy = build_policy()
assert 'default-src example.com example2.com' == policy
@override_settings(CSP_SCRIPT_SRC=['example.com'])
def test_script_src():
policy = build_policy()
policy_eq("default-src 'self'; script-src example.com", policy)
@override_settings(CSP_SCRIPT_SRC_ATTR=['example.com'])
def test_script_src_attr():
policy = build_policy()
policy_eq("default-src 'self'; script-src-attr example.com", policy)
@override_settings(CSP_SCRIPT_SRC_ELEM=['example.com'])
def test_script_src_elem():
policy = build_policy()
policy_eq("default-src 'self'; script-src-elem example.com", policy)
@override_settings(CSP_OBJECT_SRC=['example.com'])
def test_object_src():
policy = build_policy()
policy_eq("default-src 'self'; object-src example.com", policy)
@override_settings(CSP_PREFETCH_SRC=['example.com'])
def test_prefetch_src():
policy = build_policy()
policy_eq("default-src 'self'; prefetch-src example.com", policy)
@override_settings(CSP_STYLE_SRC=['example.com'])
def test_style_src():
policy = build_policy()
policy_eq("default-src 'self'; style-src example.com", policy)
@override_settings(CSP_STYLE_SRC_ATTR=['example.com'])
def test_style_src_attr():
policy = build_policy()
policy_eq("default-src 'self'; style-src-attr example.com", policy)
@override_settings(CSP_STYLE_SRC_ELEM=['example.com'])
def test_style_src_elem():
policy = build_policy()
policy_eq("default-src 'self'; style-src-elem example.com", policy)
@override_settings(CSP_IMG_SRC=['example.com'])
def test_img_src():
policy = build_policy()
policy_eq("default-src 'self'; img-src example.com", policy)
@override_settings(CSP_MEDIA_SRC=['example.com'])
def test_media_src():
policy = build_policy()
policy_eq("default-src 'self'; media-src example.com", policy)
@override_settings(CSP_FRAME_SRC=['example.com'])
def test_frame_src():
policy = build_policy()
policy_eq("default-src 'self'; frame-src example.com", policy)
@override_settings(CSP_FONT_SRC=['example.com'])
def test_font_src():
policy = build_policy()
policy_eq("default-src 'self'; font-src example.com", policy)
@override_settings(CSP_CONNECT_SRC=['example.com'])
def test_connect_src():
policy = build_policy()
policy_eq("default-src 'self'; connect-src example.com", policy)
@override_settings(CSP_SANDBOX=['allow-scripts'])
def test_sandbox():
policy = build_policy()
policy_eq("default-src 'self'; sandbox allow-scripts", policy)
@override_settings(CSP_SANDBOX=[])
def test_sandbox_empty():
policy = build_policy()
policy_eq("default-src 'self'; sandbox", policy)
@override_settings(CSP_REPORT_URI='/foo')
def test_report_uri():
policy = build_policy()
policy_eq("default-src 'self'; report-uri /foo", policy)
@override_settings(CSP_REPORT_URI=lazy_literal('/foo'))
def test_report_uri_lazy():
policy = build_policy()
policy_eq("default-src 'self'; report-uri /foo", policy)
@override_settings(CSP_REPORT_TO='some_endpoint')
def test_report_to():
policy = build_policy()
policy_eq("default-src 'self'; report-to some_endpoint",
policy)
@override_settings(CSP_IMG_SRC=['example.com'])
def test_update_img():
policy = build_policy(update={'img-src': 'example2.com'})
policy_eq("default-src 'self'; img-src example.com example2.com",
policy)
def test_update_missing_setting():
"""update should work even if the setting is not defined."""
policy = build_policy(update={'img-src': 'example.com'})
policy_eq("default-src 'self'; img-src example.com", policy)
@override_settings(CSP_IMG_SRC=['example.com'])
def test_replace_img():
policy = build_policy(replace={'img-src': 'example2.com'})
policy_eq("default-src 'self'; img-src example2.com", policy)
def test_replace_missing_setting():
"""replace should work even if the setting is not defined."""
policy = build_policy(replace={'img-src': 'example.com'})
policy_eq("default-src 'self'; img-src example.com", policy)
def test_config():
policy = build_policy(
config={'default-src': ["'none'"], 'img-src': ["'self'"]})
policy_eq("default-src 'none'; img-src 'self'", policy)
@override_settings(CSP_IMG_SRC=('example.com',))
def test_update_string():
"""
GitHub issue #40 - given project settings as a tuple, and
an update/replace with a string, concatenate correctly.
"""
policy = build_policy(update={'img-src': 'example2.com'})
policy_eq("default-src 'self'; img-src example.com example2.com",
policy)
@override_settings(CSP_IMG_SRC=('example.com',))
def test_replace_string():
"""
Demonstrate that GitHub issue #40 doesn't affect replacements
"""
policy = build_policy(replace={'img-src': 'example2.com'})
policy_eq("default-src 'self'; img-src example2.com",
policy)
@override_settings(CSP_FORM_ACTION=['example.com'])
def test_form_action():
policy = build_policy()
policy_eq("default-src 'self'; form-action example.com", policy)
@override_settings(CSP_BASE_URI=['example.com'])
def test_base_uri():
policy = build_policy()
policy_eq("default-src 'self'; base-uri example.com", policy)
@override_settings(CSP_CHILD_SRC=['example.com'])
def test_child_src():
with pytest.warns(DeprecationWarning):
policy = build_policy()
policy_eq("default-src 'self'; child-src example.com", policy)
@override_settings(CSP_FRAME_ANCESTORS=['example.com'])
def test_frame_ancestors():
policy = build_policy()
policy_eq("default-src 'self'; frame-ancestors example.com", policy)
@override_settings(CSP_NAVIGATE_TO=['example.com'])
def test_navigate_to():
policy = build_policy()
policy_eq("default-src 'self'; navigate-to example.com", policy)
@override_settings(CSP_MANIFEST_SRC=['example.com'])
def test_manifest_src():
policy = build_policy()
policy_eq("default-src 'self'; manifest-src example.com", policy)
@override_settings(CSP_WORKER_SRC=['example.com'])
def test_worker_src():
policy = build_policy()
policy_eq("default-src 'self'; worker-src example.com", policy)
@override_settings(CSP_PLUGIN_TYPES=['application/pdf'])
def test_plugin_types():
policy = build_policy()
policy_eq("default-src 'self'; plugin-types application/pdf", policy)
@override_settings(CSP_REQUIRE_SRI_FOR=['script'])
def test_require_sri_for():
policy = build_policy()
policy_eq("default-src 'self'; require-sri-for script", policy)
@override_settings(CSP_REQUIRE_TRUSTED_TYPES_FOR=["'script'"])
def test_require_trusted_types_for():
policy = build_policy()
policy_eq("default-src 'self'; require-trusted-types-for 'script'", policy)
@override_settings(CSP_TRUSTED_TYPES=["strictPolicy", "laxPolicy",
"default", "'allow-duplicates'"])
def test_trusted_types():
policy = build_policy()
policy_eq("default-src 'self'; trusted-types strictPolicy laxPolicy "
+ "default 'allow-duplicates'", policy)
@override_settings(CSP_UPGRADE_INSECURE_REQUESTS=True)
def test_upgrade_insecure_requests():
policy = build_policy()
policy_eq("default-src 'self'; upgrade-insecure-requests", policy)
@override_settings(CSP_BLOCK_ALL_MIXED_CONTENT=True)
def test_block_all_mixed_content():
policy = build_policy()
policy_eq("default-src 'self'; block-all-mixed-content", policy)
def test_nonce():
policy = build_policy(nonce='abc123')
policy_eq("default-src 'self' 'nonce-abc123'", policy)
@override_settings(CSP_INCLUDE_NONCE_IN=['script-src', 'style-src'])
def test_nonce_include_in():
policy = build_policy(nonce='abc123')
policy_eq(("default-src 'self'; "
"script-src 'nonce-abc123'; "
"style-src 'nonce-abc123'"), policy)
@override_settings()
def test_nonce_include_in_absent():
del settings.CSP_INCLUDE_NONCE_IN
policy = build_policy(nonce='abc123')
policy_eq("default-src 'self' 'nonce-abc123'", policy)
django-csp-3.7/csp/tests/utils.py 0000664 0000000 0000000 00000002072 13715033274 0017057 0 ustar 00root root 0000000 0000000 from django.template import engines, Template, Context
from django.test import RequestFactory
from csp.middleware import CSPMiddleware
JINJA_ENV = engines['jinja2']
mw = CSPMiddleware()
rf = RequestFactory()
class ScriptTestBase(object):
def assert_template_eq(self, tpl1, tpl2):
aaa = tpl1.replace('\n', '').replace(' ', '')
bbb = tpl2.replace('\n', '').replace(' ', '')
assert aaa == bbb
def process_templates(self, tpl, expected):
request = rf.get('/')
mw.process_request(request)
ctx = self.make_context(request)
return (self.make_template(tpl).render(ctx).strip(),
expected.format(request.csp_nonce))
class ScriptTagTestBase(ScriptTestBase):
def make_context(self, request):
return Context({'request': request})
def make_template(self, tpl):
return Template(tpl)
class ScriptExtensionTestBase(ScriptTestBase):
def make_context(self, request):
return {'request': request}
def make_template(self, tpl):
return JINJA_ENV.from_string(tpl)
django-csp-3.7/csp/utils.py 0000664 0000000 0000000 00000015260 13715033274 0015720 0 ustar 00root root 0000000 0000000 import copy
import re
import warnings
from collections import OrderedDict
from itertools import chain
from django.conf import settings
from django.utils.encoding import force_str
CHILD_SRC_DEPRECATION_WARNING = \
'child-src is deprecated in CSP v3. Use frame-src and worker-src.'
def from_settings():
return {
# Fetch Directives
'child-src': getattr(settings, 'CSP_CHILD_SRC', None),
'connect-src': getattr(settings, 'CSP_CONNECT_SRC', None),
'default-src': getattr(settings, 'CSP_DEFAULT_SRC', ["'self'"]),
'script-src': getattr(settings, 'CSP_SCRIPT_SRC', None),
'script-src-attr': getattr(settings, 'CSP_SCRIPT_SRC_ATTR', None),
'script-src-elem': getattr(settings, 'CSP_SCRIPT_SRC_ELEM', None),
'object-src': getattr(settings, 'CSP_OBJECT_SRC', None),
'style-src': getattr(settings, 'CSP_STYLE_SRC', None),
'style-src-attr': getattr(settings, 'CSP_STYLE_SRC_ATTR', None),
'style-src-elem': getattr(settings, 'CSP_STYLE_SRC_ELEM', None),
'font-src': getattr(settings, 'CSP_FONT_SRC', None),
'frame-src': getattr(settings, 'CSP_FRAME_SRC', None),
'img-src': getattr(settings, 'CSP_IMG_SRC', None),
'manifest-src': getattr(settings, 'CSP_MANIFEST_SRC', None),
'media-src': getattr(settings, 'CSP_MEDIA_SRC', None),
'prefetch-src': getattr(settings, 'CSP_PREFETCH_SRC', None),
'worker-src': getattr(settings, 'CSP_WORKER_SRC', None),
# Document Directives
'base-uri': getattr(settings, 'CSP_BASE_URI', None),
'plugin-types': getattr(settings, 'CSP_PLUGIN_TYPES', None),
'sandbox': getattr(settings, 'CSP_SANDBOX', None),
# Navigation Directives
'form-action': getattr(settings, 'CSP_FORM_ACTION', None),
'frame-ancestors': getattr(settings, 'CSP_FRAME_ANCESTORS', None),
'navigate-to': getattr(settings, 'CSP_NAVIGATE_TO', None),
# Reporting Directives
'report-uri': getattr(settings, 'CSP_REPORT_URI', None),
'report-to': getattr(settings, 'CSP_REPORT_TO', None),
'require-sri-for': getattr(settings, 'CSP_REQUIRE_SRI_FOR', None),
#trusted Types Directives
'require-trusted-types-for': getattr(
settings,
'CSP_REQUIRE_TRUSTED_TYPES_FOR', None),
'trusted-types': getattr(settings, 'CSP_TRUSTED_TYPES', None),
# Other Directives
'upgrade-insecure-requests': getattr(
settings, 'CSP_UPGRADE_INSECURE_REQUESTS', False),
'block-all-mixed-content': getattr(
settings, 'CSP_BLOCK_ALL_MIXED_CONTENT', False),
}
def build_policy(config=None, update=None, replace=None, nonce=None):
"""Builds the policy as a string from the settings."""
if config is None:
config = from_settings()
# Be careful, don't mutate config as it could be from settings
update = update if update is not None else {}
replace = replace if replace is not None else {}
csp = {}
for k in set(chain(config, replace)):
if k in replace:
v = replace[k]
else:
v = config[k]
if v is not None:
v = copy.copy(v)
if not isinstance(v, (list, tuple)):
v = (v,)
csp[k] = v
for k, v in update.items():
if v is not None:
if not isinstance(v, (list, tuple)):
v = (v,)
if csp.get(k) is None:
csp[k] = v
else:
csp[k] += tuple(v)
report_uri = csp.pop('report-uri', None)
policy_parts = {}
for key, value in csp.items():
# flag directives with an empty directive value
if len(value) and value[0] is True:
policy_parts[key] = ''
elif len(value) and value[0] is False:
pass
else: # directives with many values like src lists
policy_parts[key] = ' '.join(value)
if key == 'child-src':
warnings.warn(CHILD_SRC_DEPRECATION_WARNING, DeprecationWarning)
if report_uri:
report_uri = map(force_str, report_uri)
policy_parts['report-uri'] = ' '.join(report_uri)
if nonce:
include_nonce_in = getattr(settings, 'CSP_INCLUDE_NONCE_IN',
['default-src'])
for section in include_nonce_in:
policy = policy_parts.get(section, '')
policy_parts[section] = ("%s %s" %
(policy, "'nonce-%s'" % nonce)).strip()
return '; '.join(['{} {}'.format(k, val).strip()
for k, val in policy_parts.items()])
def _default_attr_mapper(attr_name, val):
if val:
return ' {}="{}"'.format(attr_name, val)
else:
return ''
def _bool_attr_mapper(attr_name, val):
# Only return the bare word if the value is truthy
# ie - defer=False should actually return an empty string
if val:
return ' {}'.format(attr_name)
else:
return ''
def _async_attr_mapper(attr_name, val):
"""The `async` attribute works slightly different than the other bool
attributes. It can be set explicitly to `false` with no surrounding quotes
according to the spec."""
if val in [False, 'False']:
return ' {}=false'.format(attr_name)
elif val:
return ' {}'.format(attr_name)
else:
return ''
# Allow per-attribute customization of returned string template
SCRIPT_ATTRS = OrderedDict()
SCRIPT_ATTRS['nonce'] = _default_attr_mapper
SCRIPT_ATTRS['id'] = _default_attr_mapper
SCRIPT_ATTRS['src'] = _default_attr_mapper
SCRIPT_ATTRS['type'] = _default_attr_mapper
SCRIPT_ATTRS['async'] = _async_attr_mapper
SCRIPT_ATTRS['defer'] = _bool_attr_mapper
SCRIPT_ATTRS['integrity'] = _default_attr_mapper
SCRIPT_ATTRS['nomodule'] = _bool_attr_mapper
# Generates an interpolatable string of valid attrs eg - '{nonce}{id}...'
ATTR_FORMAT_STR = ''.join(['{{{}}}'.format(a) for a in SCRIPT_ATTRS])
def _unwrap_script(text):
"""Extract content defined between script tags"""
matches = re.search(r'', text)
if matches and len(matches.groups()):
return matches.group(1).strip()
return text
def build_script_tag(content=None, **kwargs):
data = {}
# Iterate all possible script attrs instead of kwargs to make
# interpolation as easy as possible below
for attr_name, mapper in SCRIPT_ATTRS.items():
data[attr_name] = mapper(attr_name, kwargs.get(attr_name))
# Don't render block contents if the script has a 'src' attribute
c = _unwrap_script(content) if content and not kwargs.get('src') else ''
attrs = ATTR_FORMAT_STR.format(**data).rstrip()
return (''.format(attrs, c).strip())
django-csp-3.7/docs/ 0000775 0000000 0000000 00000000000 13715033274 0014345 5 ustar 00root root 0000000 0000000 django-csp-3.7/docs/Makefile 0000664 0000000 0000000 00000012714 13715033274 0016012 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Django-CSP.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Django-CSP.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Django-CSP"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Django-CSP"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
django-csp-3.7/docs/conf.py 0000664 0000000 0000000 00000017277 13715033274 0015662 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# Django-CSP documentation build configuration file, created by
# sphinx-quickstart on Wed Oct 31 13:02:27 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
import pkg_resources
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Django-CSP'
copyright = u'2016 Mozilla Foundation'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = pkg_resources.get_distribution('django_csp').version
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Django-CSPdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Django-CSP.tex', u'Django-CSP Documentation',
u'James Socol, Mozilla', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'django-csp', u'Django-CSP Documentation',
[u'James Socol, Mozilla'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Django-CSP', u'Django-CSP Documentation',
u'James Socol, Mozilla', 'Django-CSP', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
django-csp-3.7/docs/configuration.rst 0000664 0000000 0000000 00000014023 13715033274 0017746 0 ustar 00root root 0000000 0000000 .. _configuration-chapter:
======================
Configuring django-csp
======================
Content-Security-Policy_ is a complicated header. There are many values
you may need to tweak here.
.. note::
Note when a setting requires a tuple or list. Since Python strings
are iterable, you may get very strange policies and errors.
It's worth reading the latest CSP spec and making sure you understand it
before configuring django-csp.
Policy Settings
===============
These settings affect the policy in the header. The defaults are in
*italics*.
.. note::
The "special" source values of ``'self'``, ``'unsafe-inline'``,
``'unsafe-eval'``, ``'none'`` and hash-source (``'sha256-...'``) must be quoted! e.g.:
``CSP_DEFAULT_SRC = ("'self'",)``. Without quotes they will not work
as intended.
``CSP_DEFAULT_SRC``
Set the ``default-src`` directive. A tuple or list of
values, e.g. ``("'self'", 'cdn.example.net')``. *'self'*
``CSP_SCRIPT_SRC``
Set the ``script-src`` directive. A tuple or list. *None*
``CSP_SCRIPT_SRC_ATTR``
Set the ``script-src-attr`` directive. A tuple or list. *None*
``CSP_SCRIPT_SRC_ELEM``
Set the ``script-src-elem`` directive. A tuple or list. *None*
``CSP_IMG_SRC``
Set the ``img-src`` directive. A tuple or list. *None*
``CSP_OBJECT_SRC``
Set the ``object-src`` directive. A tuple or list. *None*
``CSP_PREFETCH_SRC``
Set the ``prefetch-src`` directive. A tuple or list. *None*
``CSP_MEDIA_SRC``
Set the ``media-src`` directive. A tuple or list. *None*
``CSP_FRAME_SRC``
Set the ``frame-src`` directive. A tuple or list. *None*
``CSP_FONT_SRC``
Set the ``font-src`` directive. A tuple or list. *None*
``CSP_CONNECT_SRC``
Set the ``connect-src`` directive. A tuple or list. *None*
``CSP_STYLE_SRC``
Set the ``style-src`` directive. A tuple or list. *None*
``CSP_STYLE_SRC_ATTR``
Set the ``style-src-attr`` directive. A tuple or list. *None*
``CSP_STYLE_SRC_ELEM``
Set the ``style-src-elem`` directive. A tuple or list. *None*
``CSP_BASE_URI``
Set the ``base-uri`` directive. A tuple or list. *None*
Note: This doesn't use default-src as a fall-back.
``CSP_CHILD_SRC``
Set the ``child-src`` directive. A tuple or list. *None* Note: Deprecated in CSP v3. Use frame-src and worker-src instead.
``CSP_FRAME_ANCESTORS``
Set the ``frame-ancestors`` directive. A tuple or list. *None*
Note: This doesn't use default-src as a fall-back.
``CSP_NAVIGATE_TO``
Set the ``navigate-to`` directive. A tuple or list. *None*
Note: This doesn't use default-src as a fall-back.
``CSP_FORM_ACTION``
Set the ``FORM_ACTION`` directive. A tuple or list. *None*
Note: This doesn't use default-src as a fall-back.
``CSP_SANDBOX``
Set the ``sandbox`` directive. A tuple or list. *None*
Note: This doesn't use default-src as a fall-back.
``CSP_REPORT_URI``
Set the ``report-uri`` directive. A tuple or list. Each URI can be a
full or relative URI. *None*
Note: This doesn't use default-src as a fall-back.
``CSP_REPORT_TO``
Set the ``report-to`` directive. A string describing a reporting group. *None*
Note: This doesn't use default-src as a fall-back.
See Section 1.2: https://w3c.github.io/reporting/#group
``CSP_MANIFEST_SRC``
Set the ``manifest-src`` directive. A tuple or list. *None*
``CSP_WORKER_SRC``
Set the ``worker-src`` directive. A tuple or list. *None*
``CSP_PLUGIN_TYPES``
Set the ``plugin-types`` directive. A tuple or list. *None*
Note: This doesn't use default-src as a fall-back.
``CSP_REQUIRE_SRI_FOR``
Set the ``require-sri-for`` directive. A tuple or list. *None*
Valid values: ``script``, ``style``, or both. See: require-sri-for-known-tokens_
Note: This doesn't use default-src as a fall-back.
``CSP_UPGRADE_INSECURE_REQUESTS``
Include ``upgrade-insecure-requests`` directive. A boolean. *False*
See: upgrade-insecure-requests_
``CSP_REQUIRE_TRUSTED_TYPES_FOR``
Include ``reuire-trusted-types-for`` directive. A tuple or list. *None*
Valid values: ``'script'``
Note: This doesn't use default-src as a fall-back.
``CSP_TRUSTED_TYPES``
Include ``trusted-types`` directive. A tuple of list. *This header is empty by default*
Valid values: a list of allowed policy names that may include ``default`` and/or ``'allow-duplicates'``
Note: This doesn't use default-src as a fall-back.
``CSP_BLOCK_ALL_MIXED_CONTENT``
Include ``block-all-mixed-content`` directive. A boolean. *False*
See: block-all-mixed-content_
``CSP_INCLUDE_NONCE_IN``
Include dynamically generated nonce in all listed directives, e.g. ``CSP_INCLUDE_NONCE_IN=['script-src']`` will add ``'nonce-'`` to the ``script-src`` directive. A tuple or list. *None*
Changing the Policy
-------------------
The policy can be changed on a per-view (or even per-request) basis. See
the :ref:`decorator documentation ` for more details.
Other Settings
==============
These settings control the behavior of django-csp. Defaults are in
*italics*.
``CSP_REPORT_ONLY``
Send "report-only" headers instead of real headers. See the spec_
and the chapter on :ref:`reports ` for more info. A
boolean. *False*
``CSP_EXCLUDE_URL_PREFIXES``
A **tuple** of URL prefixes. URLs beginning with any of these will
not get the CSP headers. *()*
.. warning::
Excluding any path on your site will eliminate the benefits of CSP
everywhere on your site. The typical browser security model for
JavaScript considers all paths alike. A Cross-Site Scripting flaw
on, e.g., `excluded-page/` can therefore be leveraged to access everything
on the same origin.
.. _Content-Security-Policy: http://www.w3.org/TR/CSP/
.. _Content-Security-Policy-L3: https://w3c.github.io/webappsec-csp/
.. _spec: Content-Security-Policy_
.. _require-sri-for-known-tokens: https://w3c.github.io/webappsec-subresource-integrity/#opt-in-require-sri-for
.. _upgrade-insecure-requests: https://w3c.github.io/webappsec-upgrade-insecure-requests/#delivery
.. _block-all-mixed-content: https://w3c.github.io/webappsec-mixed-content/
django-csp-3.7/docs/contributing.rst 0000664 0000000 0000000 00000001607 13715033274 0017612 0 ustar 00root root 0000000 0000000 .. _contributing-chapter:
============
Contributing
============
Patches are more than welcome! You can find the issue tracker `on GitHub
`_ and we'd love pull
requests.
Style
=====
Patches should follow PEP8_ and should not introduce any new violations
as detected by the flake8_ tool.
Tests
=====
Patches fixing bugs should include regression tests (ideally tests that
fail without the rest of the patch). Patches adding new features should
test those features thoroughly.
To run the tests, install the requirements (probably into a virtualenv_)::
pip install -e .
pip install -e .[tests]
Then just `py.test`_ to run the tests::
py.test
.. _PEP8: http://www.python.org/dev/peps/pep-0008/
.. _flake8: https://pypi.python.org/pypi/flake8
.. _virtualenv: http://www.virtualenv.org/
.. _py.test: https://pytest.org/latest/usage.html
django-csp-3.7/docs/decorators.rst 0000664 0000000 0000000 00000005124 13715033274 0017246 0 ustar 00root root 0000000 0000000 .. _decorator-chapter:
====================================
Modifying the Policy with Decorators
====================================
Content Security Policies should be restricted and paranoid by default.
You may, on some views, need to expand or change the policy. django-csp
includes four decorators to help.
``@csp_exempt``
===============
Using the ``@csp_exempt`` decorator disables the CSP header on a given
view.
::
from csp.decorators import csp_exempt
# Will not have a CSP header.
@csp_exempt
def myview(request):
return render(...)
You can manually set this on a per-response basis by setting the
``_csp_exempt`` attribute on the response to ``True``::
# Also will not have a CSP header.
def myview(request):
response = render(...)
response._csp_exempt = True
return response
``@csp_update``
===============
The ``@csp_update`` header allows you to **append** values to the source
lists specified in the settings. If there is no setting, the value
passed to the decorator will be used verbatim.
.. note::
To quote the CSP spec: "There's no inheritance; ... the default list
is not used for that resource type" if it is set. E.g., the following
will not allow images from 'self'::
default-src 'self'; img-src imgsrv.com
The arguments to the decorator the same as the :ref:`settings
` without the ``CSP_`` prefix, e.g. ``IMG_SRC``.
(They are also case-insensitive.) The values are either strings, lists
or tuples.
::
from csp.decorators import csp_update
# Will allow images from imgsrv.com.
@csp_update(IMG_SRC='imgsrv.com')
def myview(request):
return render(...)
``@csp_replace``
================
The ``@csp_replace`` decorator allows you to **replace** a source list
specified in settings. If there is no setting, the value passed to the
decorator will be used verbatim. (See the note under ``@csp_update``.)
The arguments and values are the same as ``@csp_update``::
from csp.decorators import csp_replace
# settings.CSP_IMG_SRC = ['imgsrv.com']
# Will allow images from imgsrv2.com, but not imgsrv.com.
@csp_replace(IMG_SRC='imgsrv2.com')
def myview(request):
return render(...)
``@csp``
========
If you need to set the entire policy on a view, ignoring all the
settings, you can use the ``@csp`` decorator. The arguments and values
are as above::
from csp.decorators import csp
@csp(DEFAULT_SRC=["'self'"], IMG_SRC=['imgsrv.com'],
SCRIPT_SRC=['scriptsrv.com', 'googleanalytics.com'])
def myview(request):
return render(...)
django-csp-3.7/docs/index.rst 0000664 0000000 0000000 00000001440 13715033274 0016205 0 ustar 00root root 0000000 0000000 .. Django-CSP documentation master file, created by
sphinx-quickstart on Wed Oct 31 13:02:27 2012.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
==========
django-csp
==========
django-csp adds Content-Security-Policy_ headers to Django applications.
:Version: |release|
:Code: https://github.com/mozilla/django-csp
:License: BSD; see LICENSE file
:Issues: https://github.com/mozilla/django-csp/issues
Contents:
.. toctree::
:maxdepth: 2
installation
configuration
decorators
nonce
trusted_types
reports
contributing
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. _Content-Security-Policy: http://www.w3.org/TR/CSP/
django-csp-3.7/docs/installation.rst 0000664 0000000 0000000 00000001116 13715033274 0017577 0 ustar 00root root 0000000 0000000 .. _installation-chapter:
=====================
Installing django-csp
=====================
First, install django-csp via pip or from source::
# pip
$ pip install django-csp
::
# source
$ git clone https://github.com/mozilla/django-csp.git
$ cd django-csp
$ python setup.py install
Now edit your project's ``settings`` module, to add the django-csp middleware
to ``MIDDLEWARE``, like so::
MIDDLEWARE = (
# ...
'csp.middleware.CSPMiddleware',
# ...
)
That should do it! Go on to :ref:`configuring CSP `.
django-csp-3.7/docs/nonce.rst 0000664 0000000 0000000 00000005324 13715033274 0016205 0 ustar 00root root 0000000 0000000 ==============================
Using the generated CSP nonce
==============================
When ``CSP_INCLUDE_NONCE_IN`` is configured, the nonce value is returned in the CSP header. To actually make the browser do anything with this value, you will need to include it in the attributes of the tags that you wish to mark as safe.
``Middleware``
==============
Installing the middleware creates a lazily evaluated property ``csp_nonce`` and attaches it to all incoming requests.
.. code-block:: python
MIDDLEWARE_CLASSES = (
#...
'csp.middleware.CSPMiddleware',
#...
)
This value can be accessed directly on the request object in any view or template and manually appended to any script element like so -
.. code-block:: html
Assuming the ``CSP_INCLUDE_NONCE_IN`` list contains the ``script-src`` directive, this will result in the above script being allowed.
``Context Processor``
=====================
This library contains an optional context processor, adding ``csp.context_processors.nonce`` to your configured context processors exposes a variable called ``CSP_NONCE`` into the global template context. This is simple shorthand for ``request.csp_nonce``, but can be useful if you have many occurrences of script tags.
.. code-block:: jinja
``Django Template Tag/Jinja Extension``
=======================================
.. note::
If you're making use of ``csp.extensions.NoncedScript`` you need to have ``jinja2>=2.9.6`` installed, so please make sure to either use ``django-csp[jinja2]`` in your requirements or define it yourself.
Since it can be easy to forget to include the ``nonce`` property in a script tag, there is also a ``script`` template tag available for both Django templates and Jinja environments.
This tag will output a properly nonced script every time. For the sake of syntax highlighting, you can wrap the content inside of the ``script`` tag in ``
{% endscript %}
Jinja:
(assumes ``csp.extensions.NoncedScript`` is added to the jinja extensions setting)
.. code-block:: jinja
{% script type="application/javascript" async=False %}
{% endscript %}
Will output -
.. code-block:: html
django-csp-3.7/docs/reports.rst 0000664 0000000 0000000 00000002206 13715033274 0016575 0 ustar 00root root 0000000 0000000 .. _reports-chapter:
=====================
CSP Violation Reports
=====================
When something on a page violates the Content-Security-Policy, and the
policy defines a ``report-uri`` directive, the user agent may POST a
report_. Reports are JSON blobs containing information about how the
policy was violated.
Note: django-csp no longer handles report processing itself, so you will
need to stand up your own app to receive them, or else make use of a
third-party report processing service.
Throttling the number of reports
--------------------------------
To throttle the number of requests made to your ``report-uri`` endpoint, you
can use ``csp.contrib.rate_limiting.RateLimitedCSPMiddleware`` instead of
``csp.middleware.CSPMiddleware`` and set the ``CSP_REPORT_PERCENTAGE`` option:
``CSP_REPORT_PERCENTAGE``
Percentage of requests that should see the ``report-uri`` directive.
Use this to throttle the number of CSP violation reports made to your
``CSP_REPORT_URI``. A **float** between 0 and 1 (0 = no reports at all).
Ignored if ``CSP_REPORT_URI`` isn't set.
.. _report: http://www.w3.org/TR/CSP/#sample-violation-report
django-csp-3.7/docs/trusted_types.rst 0000664 0000000 0000000 00000014514 13715033274 0020022 0 ustar 00root root 0000000 0000000 ===================================
Implementing Trusted Types with CSP
===================================
``DOM Cross-site Scripting``
============================
Cross-site scripting (XSS) is one of the most prevalent vulnerabilities
on the web. Nonce-based CSP is used to prevent server-side XSS. Trusted
Types are used to prevent client-side or DOM-XSS_. Trusted Types rely on
the browser to enforce the policy that is provided to it. Currently, Trusted
Types are supported on Chrome 83 and Android Webview. Many browsers are in the
process of adding support. Check back for updated compatibility_.
Follow the simple steps below to make your web application Trusted Types
compliant.
``Step 1: Enable Trusted Types and Report Only Mode``
=====================================================
Trusted Types require data to be processed before being sent to a risky "sink" where DOM XSS might occur, such as when assigning to Element.innerHTML or calling document.write. When enforced, Trusted Types will tell the
browser to block any data that is not properly processed. In order to avoid
this, you must fix offending parts of your code. To see where adjustments will
be required, turn on trusted types and report only mode.
Configure django-csp so that ``CSP_REQUIRE_TRUSTED_TYPES_FOR`` is set to *‘script’*.
Configure django-csp so that ``CSP_REPORT_ONLY`` is set to *True*.
Configure django-csp so that ``CSP_REPORT_URI`` is set to an app or CSP report processing service that you control.
Now trusted types violations will be reported to your ``CSP_REPORT_URI`` without blocking any of your application’s functionalities.
``Step 2: Fixing Trusted Types Violations``
===========================================
There are four ways to resolve trusted types violations. They are explained
here in order of preference.
Rewrite the Code
----------------
It may be possible for your code to be rewritten without using dangerous
functions. For example, instead of dynamically placing an image using the
dangerous ``innerHTML`` sink, the image could be created with
``document.createElement`` and placed using the ``appendChild`` function.
Rewriting may be possible for any of the dangerous sinks, which are listed here.
* Script manipulation:
* ``