django-csp-plus


Namedjango-csp-plus JSON
Version 3.1.1 PyPI version JSON
download
home_pagehttps://github.com/yunojuno/django-csp-plus
SummaryCSP tracking and violation report endpoint.
upload_time2024-02-06 08:52:57
maintainerYunoJuno
docs_urlNone
authorYunoJuno
requires_python>=3.10,<4.0
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # Django CSP Plus

Django app for building CSP and tracking violations.

This project is based on the excellent `django-csp` project from MDN,
with a couple of alterations:

1. It includes a violation report tracker
2. It stores rules in a model, so they can be edited at runtime

The `nonce` pattern has been lifted directly.

## History

The original reason for forking this from the original was the desire to
have the violation reporting with the same Django project as the source
pages. I'm sure there is / was an excellent reason for not doing so in
the original, but it's not explained, and Django seems like a great fit
for an HTTP endpoint that can parse JSON requests and store the data
somewhere.

The second reason was the experience we had with Sqreen - a fantastic
security app that we used from their beta launch through to their
acquisition by Datadog. They have/had a great violation report tool that
allowed you to see how many violations had occurred, and to
automatically add the valid domains to the working CSP, making CSP
trivial to manage (and requiring no restarts).

It felt like this is something we could add to the Django admin
relatively easily ("convert this violation report into a rule").

The final push was the desire to manage the rules at runtime - running a
large commercial site you never quite know what the marketing team has
just added to the site, and having to redeploy to unblock their new tool
was a pain.

We ended with these requirements:

1. Design time base rules
2. Runtime configurable rules
3. Builtin violation reporting
4. Support for nonces
5. Ability to exclude specific requests / responses

## Implementation

We have split the middleware in two - `CspNonceMiddleware`, which adds
the `request.csp_nonce` attribute, and `CspHeaderMiddleware`, which adds
the header. Most sites will want both, but you can run one without the
other.

The baseline, static, configuration of rules is a dict in `settings.py`.
This can then be enriched with dynamic rules stored in the `CspRule`
model.

You can add two special placeholders in the rules: `{nonce}` and
`{report-uri}`; if present these will be replaced with the current
`request.csp_nonce` and the local violation report URL on each request.
The CSP is cached for all requests with the placeholder text in (so it's
the same for all users / requests).

### Directives

Some directives are deprecated, and others not-yet implemented. The
canonical example is the `style-src-elem` directive (and its `style-`
and `-attr`) siblings which are _not_ supported by Safari. In order to
highlight these the corresponding directive choice labels have been
amended. Treat with caution as setting these attributes may have
unintended consequences.

#### Downgrading directives

In some instances you may want to "downgrade" a directive - for instance
converting all `script-src-elem` directives to `script-src` (for
compatibility reasons). This can be done using the
`CSP_REPORT_DIRECTIVE_DOWNGRADE` setting.

## Settings

### `CSP_ENABLED`

`bool`, default = `False`

Kill switch for the middleware. Defaults to `False` (disabled).

### `CSP_REPORT_DIRECTIVE_DOWNGRADE`

`dict[str, str]`, default =
```python
{
    "script-src-elem": "script-src",
    "script-src-attr": "script-src",
    "style-src-elem": "style-src",
    "style-src-attr": "style-src",
}
```

This is used to transparently "downgrade" any directives to a different
directive, and is primarily used for managing compatibility.

### `CSP_REPORT_ONLY`

`bool`, default = `True`

Set to `True` to run in report-only mode. Defaults to `True`.

### `CSP_REPORT_SAMPLING`

`float`, default = `1.0`

Float (0.0-1.0) - used as a percentage of responses on which to include
the `report-uri` directive. This can be used to turn down the noise -
once you have a stable CSP there is no point having every single request
include the reporting directive - you need a trickle not a flood.

### `CSP_REPORT_THROTTLING`

`float`, default = `0.0`

Float (0.0-1.0) - used as a percentage of reporting violation requests
to throttle (throw away). This is used to control potentially malicious
violation reporting. The reporting endpoint is public, and accepts JSON
payloads, so is open to abuse (sending very large, or malformed JSON)
and is a potential DOS vulnerability. If you set this value to 1.0 then
all inbound reporting requests are thrown away without processing. Use
in extremis.

### `CSP_CACHE_TIMEOUT`

`int`, default = `600`

The cache timeout for the templated CSP. Defaults to 5 min (600s).

### `CSP_FILTER_REQUEST_FUNC`

`Callable[[HttpRequest], bool]` - defaults to returning `True` for all
requests

A callable that takes `HttpRequest` and returns a bool - if False, the
middleware will not add the response header. Defaults to return `True`
for all requests.

### `CSP_FILTER_RESPONSE_FUNC`

`Callable[[HttpResponse], bool]` - defaults to `True` for all
`text/html` responses.

Callable that takes `HttpResponse` and returns a bool - if `False` the
middleware will not add the response header. Defaults to a function that
filters only responses with `Content-Type: text/html` - which results in
static content / JSON responses _not_ getting the CSP header.

### `CSP_DEFAULTS`

`dict[str, list[str]]`

The default (baseline) CSP as a dict of `{directive: values}`. This is
extended by the runtime rules (i.e. not overwritten). Defaults to:

```python
{
    "default-src": ["'none'"],
    "base-uri": ["'self'"],
    "connect-src": ["'self'"],
    "form-action": ["'self'"],
    "font-src": ["'self'"],
    "img-src": ["'self'"],
    "script-src": ["'self'"],
    "style-src": ["'self'"],
    "report-uri": ["{report_uri}"],
}
```

Note the `{report-uri}` value in the default - this is cached as-is,
with the local report URL injected into it at runtime.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/yunojuno/django-csp-plus",
    "name": "django-csp-plus",
    "maintainer": "YunoJuno",
    "docs_url": null,
    "requires_python": ">=3.10,<4.0",
    "maintainer_email": "code@yunojuno.com",
    "keywords": "",
    "author": "YunoJuno",
    "author_email": "code@yunojuno.com",
    "download_url": "https://files.pythonhosted.org/packages/79/ba/4397ad5803c8ced89c4482f4944b6bafe65cfe4c32ac32e8c1bb862deb0a/django_csp_plus-3.1.1.tar.gz",
    "platform": null,
    "description": "# Django CSP Plus\n\nDjango app for building CSP and tracking violations.\n\nThis project is based on the excellent `django-csp` project from MDN,\nwith a couple of alterations:\n\n1. It includes a violation report tracker\n2. It stores rules in a model, so they can be edited at runtime\n\nThe `nonce` pattern has been lifted directly.\n\n## History\n\nThe original reason for forking this from the original was the desire to\nhave the violation reporting with the same Django project as the source\npages. I'm sure there is / was an excellent reason for not doing so in\nthe original, but it's not explained, and Django seems like a great fit\nfor an HTTP endpoint that can parse JSON requests and store the data\nsomewhere.\n\nThe second reason was the experience we had with Sqreen - a fantastic\nsecurity app that we used from their beta launch through to their\nacquisition by Datadog. They have/had a great violation report tool that\nallowed you to see how many violations had occurred, and to\nautomatically add the valid domains to the working CSP, making CSP\ntrivial to manage (and requiring no restarts).\n\nIt felt like this is something we could add to the Django admin\nrelatively easily (\"convert this violation report into a rule\").\n\nThe final push was the desire to manage the rules at runtime - running a\nlarge commercial site you never quite know what the marketing team has\njust added to the site, and having to redeploy to unblock their new tool\nwas a pain.\n\nWe ended with these requirements:\n\n1. Design time base rules\n2. Runtime configurable rules\n3. Builtin violation reporting\n4. Support for nonces\n5. Ability to exclude specific requests / responses\n\n## Implementation\n\nWe have split the middleware in two - `CspNonceMiddleware`, which adds\nthe `request.csp_nonce` attribute, and `CspHeaderMiddleware`, which adds\nthe header. Most sites will want both, but you can run one without the\nother.\n\nThe baseline, static, configuration of rules is a dict in `settings.py`.\nThis can then be enriched with dynamic rules stored in the `CspRule`\nmodel.\n\nYou can add two special placeholders in the rules: `{nonce}` and\n`{report-uri}`; if present these will be replaced with the current\n`request.csp_nonce` and the local violation report URL on each request.\nThe CSP is cached for all requests with the placeholder text in (so it's\nthe same for all users / requests).\n\n### Directives\n\nSome directives are deprecated, and others not-yet implemented. The\ncanonical example is the `style-src-elem` directive (and its `style-`\nand `-attr`) siblings which are _not_ supported by Safari. In order to\nhighlight these the corresponding directive choice labels have been\namended. Treat with caution as setting these attributes may have\nunintended consequences.\n\n#### Downgrading directives\n\nIn some instances you may want to \"downgrade\" a directive - for instance\nconverting all `script-src-elem` directives to `script-src` (for\ncompatibility reasons). This can be done using the\n`CSP_REPORT_DIRECTIVE_DOWNGRADE` setting.\n\n## Settings\n\n### `CSP_ENABLED`\n\n`bool`, default = `False`\n\nKill switch for the middleware. Defaults to `False` (disabled).\n\n### `CSP_REPORT_DIRECTIVE_DOWNGRADE`\n\n`dict[str, str]`, default =\n```python\n{\n    \"script-src-elem\": \"script-src\",\n    \"script-src-attr\": \"script-src\",\n    \"style-src-elem\": \"style-src\",\n    \"style-src-attr\": \"style-src\",\n}\n```\n\nThis is used to transparently \"downgrade\" any directives to a different\ndirective, and is primarily used for managing compatibility.\n\n### `CSP_REPORT_ONLY`\n\n`bool`, default = `True`\n\nSet to `True` to run in report-only mode. Defaults to `True`.\n\n### `CSP_REPORT_SAMPLING`\n\n`float`, default = `1.0`\n\nFloat (0.0-1.0) - used as a percentage of responses on which to include\nthe `report-uri` directive. This can be used to turn down the noise -\nonce you have a stable CSP there is no point having every single request\ninclude the reporting directive - you need a trickle not a flood.\n\n### `CSP_REPORT_THROTTLING`\n\n`float`, default = `0.0`\n\nFloat (0.0-1.0) - used as a percentage of reporting violation requests\nto throttle (throw away). This is used to control potentially malicious\nviolation reporting. The reporting endpoint is public, and accepts JSON\npayloads, so is open to abuse (sending very large, or malformed JSON)\nand is a potential DOS vulnerability. If you set this value to 1.0 then\nall inbound reporting requests are thrown away without processing. Use\nin extremis.\n\n### `CSP_CACHE_TIMEOUT`\n\n`int`, default = `600`\n\nThe cache timeout for the templated CSP. Defaults to 5 min (600s).\n\n### `CSP_FILTER_REQUEST_FUNC`\n\n`Callable[[HttpRequest], bool]` - defaults to returning `True` for all\nrequests\n\nA callable that takes `HttpRequest` and returns a bool - if False, the\nmiddleware will not add the response header. Defaults to return `True`\nfor all requests.\n\n### `CSP_FILTER_RESPONSE_FUNC`\n\n`Callable[[HttpResponse], bool]` - defaults to `True` for all\n`text/html` responses.\n\nCallable that takes `HttpResponse` and returns a bool - if `False` the\nmiddleware will not add the response header. Defaults to a function that\nfilters only responses with `Content-Type: text/html` - which results in\nstatic content / JSON responses _not_ getting the CSP header.\n\n### `CSP_DEFAULTS`\n\n`dict[str, list[str]]`\n\nThe default (baseline) CSP as a dict of `{directive: values}`. This is\nextended by the runtime rules (i.e. not overwritten). Defaults to:\n\n```python\n{\n    \"default-src\": [\"'none'\"],\n    \"base-uri\": [\"'self'\"],\n    \"connect-src\": [\"'self'\"],\n    \"form-action\": [\"'self'\"],\n    \"font-src\": [\"'self'\"],\n    \"img-src\": [\"'self'\"],\n    \"script-src\": [\"'self'\"],\n    \"style-src\": [\"'self'\"],\n    \"report-uri\": [\"{report_uri}\"],\n}\n```\n\nNote the `{report-uri}` value in the default - this is cached as-is,\nwith the local report URL injected into it at runtime.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "CSP tracking and violation report endpoint.",
    "version": "3.1.1",
    "project_urls": {
        "Documentation": "https://github.com/yunojuno/django-csp-plus",
        "Homepage": "https://github.com/yunojuno/django-csp-plus",
        "Repository": "https://github.com/yunojuno/django-csp-plus"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "53941d01df23bc9e54ad4396ed43448339fddb943e3d3883dc1f5a9a4016622f",
                "md5": "acbf9b3d82dcae92d7479bf90b89121d",
                "sha256": "1c7d955b842a916f259ceecc6d22a5081d1ca51aa52f0ba37754c7eb2be33b49"
            },
            "downloads": -1,
            "filename": "django_csp_plus-3.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "acbf9b3d82dcae92d7479bf90b89121d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10,<4.0",
            "size": 21919,
            "upload_time": "2024-02-06T08:52:55",
            "upload_time_iso_8601": "2024-02-06T08:52:55.922070Z",
            "url": "https://files.pythonhosted.org/packages/53/94/1d01df23bc9e54ad4396ed43448339fddb943e3d3883dc1f5a9a4016622f/django_csp_plus-3.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "79ba4397ad5803c8ced89c4482f4944b6bafe65cfe4c32ac32e8c1bb862deb0a",
                "md5": "72ac5a4c51ca3029f1df7bdd9145deec",
                "sha256": "12aeeed612626f098ac0b84a250bc74fd9197b13b442a5cfe217f42fd640b724"
            },
            "downloads": -1,
            "filename": "django_csp_plus-3.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "72ac5a4c51ca3029f1df7bdd9145deec",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10,<4.0",
            "size": 18435,
            "upload_time": "2024-02-06T08:52:57",
            "upload_time_iso_8601": "2024-02-06T08:52:57.360603Z",
            "url": "https://files.pythonhosted.org/packages/79/ba/4397ad5803c8ced89c4482f4944b6bafe65cfe4c32ac32e8c1bb862deb0a/django_csp_plus-3.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-06 08:52:57",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "yunojuno",
    "github_project": "django-csp-plus",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "tox": true,
    "lcname": "django-csp-plus"
}
        
Elapsed time: 0.19537s