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

Reawaken development #204

Merged
merged 12 commits into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
72 changes: 0 additions & 72 deletions .circleci/config.yml

This file was deleted.

57 changes: 57 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
name: "CI" # Note that this name appears in the README's badge
on:
push:
branches:
- main
workflow_dispatch:
pull_request:
release:
types: [published]
jobs:
run-tests:
runs-on: ubuntu-latest
strategy:
matrix:
python-version:
- '3.8'
- '3.9'
- '3.10'
- '3.11'
- '3.12'
- 'pypy-3.8'
- 'pypy-3.9'
- 'pypy-3.10'

steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install tox tox-gh-actions
- name: Test with tox
run: tox

release:
name: Release django-csp
if: github.event_name == 'release' && github.event.action == 'published'
needs:
- run-tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: 3.12
- name: Install dependencies for package building only
run: pip install build
- name: Build package for upload to PyPI
run: python -m build .
- name: Upload the distribution to PyPI
uses: pypa/gh-action-pypi-publish@v1.4.2
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
27 changes: 27 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

# Global excludes, override per repo below if different excludes required.
# exclude: >
# (?x)^(
# DIRNAME_OR_FILENAME_HERE
# | DIRNAME_OR_FILENAME_HERE
# | DIRNAME_OR_FILENAME_HERE
# )
repos:
# Note: hooks that add content must run before ones which check formatting, lint, etc
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0 # Use the ref you want to point at
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.1.14
hooks:
# Run the linter
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
# Run the formatter
- id: ruff-format
29 changes: 19 additions & 10 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,19 @@ Next
====

- Remove deprecation warning for child-src
- Add project urls to setup.py
- Drop support for EOL Python <3.6 and Django <2.2 versions
- Rename default branch to main
- Fix capturing brackets in script template tags
- Move to Hatch for packaging
- Move project to pyproject.toml
- Add project urls
- Set up coverage badge

Unreleased
==========

- Drop support for EOL Python <3.8 and Django <2.2 versions
- Switch to ruff instead of pep8 and flake8
- Move from CircleCI to Github Actions for CI
- Add support for using pre-commit with the project

3.7
===
Expand Down Expand Up @@ -50,12 +59,12 @@ Next
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 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
Expand All @@ -76,7 +85,7 @@ v3.0

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
<https://github.com/mozilla/django-csp/issues>

v2.0.3
======
Expand Down
4 changes: 2 additions & 2 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Community Participation Guidelines

This repository is governed by Mozilla's code of conduct and etiquette 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/).
[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.
Expand Down
1 change: 0 additions & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,3 @@ 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.

9 changes: 2 additions & 7 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
.. image:: https://badge.fury.io/py/django-csp.svg
:target: https://pypi.python.org/pypi/django_csp

.. image:: https://circleci.com/gh/mozilla/django-csp/tree/main.svg?style=shield
:target: https://circleci.com/gh/mozilla/django-csp/?branch=main

.. image:: https://coveralls.io/repos/github/mozilla/django-csp/badge.svg?branch=main
:target: https://coveralls.io/github/mozilla/django-csp?branch=main
.. image:: https://github.com/mozilla/django-csp/actions/workflows/run-tests.yaml/badge.svg
:target: https://github.com/mozilla/django-csp/actions/workflows/run-tests.yaml

==========
Django-CSP
Expand All @@ -16,8 +13,6 @@ 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
Expand Down
6 changes: 2 additions & 4 deletions csp/context_processors.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
def nonce(request):
nonce = request.csp_nonce if hasattr(request, 'csp_nonce') else ''
nonce = request.csp_nonce if hasattr(request, "csp_nonce") else ""

return {
'CSP_NONCE': nonce
}
return {"CSP_NONCE": nonce}
15 changes: 7 additions & 8 deletions csp/contrib/rate_limiting.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@ class RateLimitedCSPMiddleware(CSPMiddleware):
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)
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')
report_percentage = getattr(settings, "CSP_REPORT_PERCENTAGE")
include_report_uri = random.random() < report_percentage
if not include_report_uri:
replace['report-uri'] = None
replace["report-uri"] = None

return build_policy(config=config, update=update, replace=replace,
nonce=nonce)
return build_policy(config=config, update=update, replace=replace, nonce=nonce)
17 changes: 10 additions & 7 deletions csp/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,50 @@ 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())
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())
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()
)
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
21 changes: 9 additions & 12 deletions csp/extensions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

class NoncedScript(Extension):
# a set of names that trigger the extension.
tags = set(['script'])
tags = set(["script"])

def parse(self, parser):
# the first token is the token that started the tag. In our case
Expand All @@ -18,29 +18,26 @@ def parse(self, parser):
lineno = next(parser.stream).lineno

# Get the current context and pass along
kwargs = [nodes.Keyword('ctx', nodes.ContextReference())]
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()))
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)
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)
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()
ctx = kwargs.pop("ctx")
request = ctx.get("request")
kwargs["nonce"] = request.csp_nonce
kwargs["content"] = caller().strip()

return build_script_tag(**kwargs)
Loading