quiet-awning 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- quiet_awning-0.1.0/LICENSE +21 -0
- quiet_awning-0.1.0/PKG-INFO +49 -0
- quiet_awning-0.1.0/README.md +39 -0
- quiet_awning-0.1.0/pyproject.toml +19 -0
- quiet_awning-0.1.0/setup.cfg +4 -0
- quiet_awning-0.1.0/src/quiet_awning/__init__.py +6 -0
- quiet_awning-0.1.0/src/quiet_awning/asgi.py +67 -0
- quiet_awning-0.1.0/src/quiet_awning/headers.py +144 -0
- quiet_awning-0.1.0/src/quiet_awning/py.typed +0 -0
- quiet_awning-0.1.0/src/quiet_awning.egg-info/PKG-INFO +49 -0
- quiet_awning-0.1.0/src/quiet_awning.egg-info/SOURCES.txt +12 -0
- quiet_awning-0.1.0/src/quiet_awning.egg-info/dependency_links.txt +1 -0
- quiet_awning-0.1.0/src/quiet_awning.egg-info/top_level.txt +1 -0
- quiet_awning-0.1.0/tests/test_headers.py +60 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 quiet-awning contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: quiet-awning
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Security headers and Content Security Policy for Python web applications
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# quiet-awning for Python
|
|
12
|
+
|
|
13
|
+
Create HTTP security headers and Content Security Policy (CSP) without runtime dependencies. Python 3.10 or later is required.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
python -m pip install quiet-awning
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## ASGI
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from quiet_awning import SecurityMiddleware
|
|
23
|
+
|
|
24
|
+
app = SecurityMiddleware(
|
|
25
|
+
app,
|
|
26
|
+
nonce=True,
|
|
27
|
+
reporting_endpoint=("csp", "/csp-reports"),
|
|
28
|
+
csp_options={
|
|
29
|
+
"report_only": True,
|
|
30
|
+
"strict_dynamic": True,
|
|
31
|
+
"sources": {"img": ["https://images.example.com"]},
|
|
32
|
+
"report_uri": "/csp-reports",
|
|
33
|
+
},
|
|
34
|
+
)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Wrap the ASGI application after it has been created. The middleware writes headers when an HTTP response starts and preserves duplicate application headers. Existing values win unless `override=True`. The current request ID and nonce are exposed in `scope["state"]` as `request_id` and `csp_nonce`. With nonce mode, render the same nonce into authorized HTML tags and send it with the matching CSP. Configure caching for those responses and check that an existing CSP does not mask the generated policy.
|
|
38
|
+
|
|
39
|
+
The default policy is report-only. Set `report_only=False` to enforce it after checking reports and testing the page. Applications provide the report receiver. Production mode enables HSTS. Set `production=False` for nonproduction use.
|
|
40
|
+
|
|
41
|
+
Use `security_headers()` for a static header map or `build_csp()` for a standalone CSP header. Available presets are `strict`, `standard`, and `off`.
|
|
42
|
+
|
|
43
|
+
## Development
|
|
44
|
+
|
|
45
|
+
Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package.
|
|
46
|
+
|
|
47
|
+
## License
|
|
48
|
+
|
|
49
|
+
MIT
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# quiet-awning for Python
|
|
2
|
+
|
|
3
|
+
Create HTTP security headers and Content Security Policy (CSP) without runtime dependencies. Python 3.10 or later is required.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
python -m pip install quiet-awning
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## ASGI
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from quiet_awning import SecurityMiddleware
|
|
13
|
+
|
|
14
|
+
app = SecurityMiddleware(
|
|
15
|
+
app,
|
|
16
|
+
nonce=True,
|
|
17
|
+
reporting_endpoint=("csp", "/csp-reports"),
|
|
18
|
+
csp_options={
|
|
19
|
+
"report_only": True,
|
|
20
|
+
"strict_dynamic": True,
|
|
21
|
+
"sources": {"img": ["https://images.example.com"]},
|
|
22
|
+
"report_uri": "/csp-reports",
|
|
23
|
+
},
|
|
24
|
+
)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Wrap the ASGI application after it has been created. The middleware writes headers when an HTTP response starts and preserves duplicate application headers. Existing values win unless `override=True`. The current request ID and nonce are exposed in `scope["state"]` as `request_id` and `csp_nonce`. With nonce mode, render the same nonce into authorized HTML tags and send it with the matching CSP. Configure caching for those responses and check that an existing CSP does not mask the generated policy.
|
|
28
|
+
|
|
29
|
+
The default policy is report-only. Set `report_only=False` to enforce it after checking reports and testing the page. Applications provide the report receiver. Production mode enables HSTS. Set `production=False` for nonproduction use.
|
|
30
|
+
|
|
31
|
+
Use `security_headers()` for a static header map or `build_csp()` for a standalone CSP header. Available presets are `strict`, `standard`, and `off`.
|
|
32
|
+
|
|
33
|
+
## Development
|
|
34
|
+
|
|
35
|
+
Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package.
|
|
36
|
+
|
|
37
|
+
## License
|
|
38
|
+
|
|
39
|
+
MIT
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "quiet-awning"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Security headers and Content Security Policy for Python web applications"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = []
|
|
14
|
+
|
|
15
|
+
[tool.setuptools.packages.find]
|
|
16
|
+
where = ["src"]
|
|
17
|
+
|
|
18
|
+
[tool.setuptools.package-data]
|
|
19
|
+
quiet_awning = ["py.typed"]
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""ASGI response middleware."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
from secrets import token_urlsafe
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
from .headers import build_csp, reporting_endpoints, security_headers
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SecurityMiddleware:
|
|
13
|
+
"""Apply security headers to each HTTP response."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self, app: Any, *, preset: str = "strict", production: bool = True,
|
|
17
|
+
override: bool = False, request_id: bool = True, nonce: bool = False,
|
|
18
|
+
csp_options: Mapping[str, Any] | None = None,
|
|
19
|
+
reporting_endpoint: tuple[str, str] | None = None,
|
|
20
|
+
) -> None:
|
|
21
|
+
self.app = app
|
|
22
|
+
self.override = override
|
|
23
|
+
self.request_id = request_id
|
|
24
|
+
self.nonce = nonce
|
|
25
|
+
self.headers = security_headers(preset=preset, production=production, csp=False)
|
|
26
|
+
self.csp_options = {"preset": preset, "production": production,
|
|
27
|
+
**deepcopy(dict(csp_options or {}))}
|
|
28
|
+
if "nonce" in self.csp_options:
|
|
29
|
+
raise ValueError("Use the middleware nonce option for a per-request nonce.")
|
|
30
|
+
if reporting_endpoint is not None:
|
|
31
|
+
name, url = reporting_endpoint
|
|
32
|
+
self.headers["reporting-endpoints"] = reporting_endpoints(name, url)
|
|
33
|
+
self.csp_options["report_to"] = name
|
|
34
|
+
csp = build_csp(**self.csp_options, nonce=token_urlsafe(16) if nonce else None)
|
|
35
|
+
if csp is not None and not nonce:
|
|
36
|
+
self.headers[csp[0]] = csp[1]
|
|
37
|
+
|
|
38
|
+
async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
|
|
39
|
+
if scope.get("type") != "http":
|
|
40
|
+
await self.app(scope, receive, send)
|
|
41
|
+
return
|
|
42
|
+
|
|
43
|
+
headers = self.headers.copy()
|
|
44
|
+
state = dict(scope.get("state", {}))
|
|
45
|
+
if self.request_id:
|
|
46
|
+
request_id = uuid4().hex
|
|
47
|
+
state["request_id"] = request_id
|
|
48
|
+
headers["x-request-id"] = request_id
|
|
49
|
+
if self.nonce:
|
|
50
|
+
nonce = token_urlsafe(16)
|
|
51
|
+
csp = build_csp(**self.csp_options, nonce=nonce)
|
|
52
|
+
if csp is not None:
|
|
53
|
+
headers[csp[0]] = csp[1]
|
|
54
|
+
state["csp_nonce"] = nonce
|
|
55
|
+
additions = {key.encode("ascii"): value.encode("ascii") for key, value in headers.items()}
|
|
56
|
+
|
|
57
|
+
async def send_response(message: dict[str, Any]) -> None:
|
|
58
|
+
if message["type"] == "http.response.start":
|
|
59
|
+
existing = list(message.get("headers", ()))
|
|
60
|
+
if self.override:
|
|
61
|
+
existing = [(key, value) for key, value in existing if key.lower() not in additions]
|
|
62
|
+
names = {key.lower() for key, _ in existing}
|
|
63
|
+
existing.extend((key, value) for key, value in additions.items() if key not in names)
|
|
64
|
+
message = {**message, "headers": existing}
|
|
65
|
+
await send(message)
|
|
66
|
+
|
|
67
|
+
await self.app({**scope, "state": state}, receive, send_response)
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Build response policies without a framework dependency."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping, Sequence
|
|
4
|
+
import re
|
|
5
|
+
from urllib.parse import urlsplit
|
|
6
|
+
|
|
7
|
+
_PRESETS = {"strict", "standard", "off"}
|
|
8
|
+
_GROUPS = {group: f"{group}-src" for group in
|
|
9
|
+
("script", "style", "img", "font", "connect", "media", "frame", "worker")}
|
|
10
|
+
_FEATURES = ("camera", "microphone", "geolocation", "payment", "usb",
|
|
11
|
+
"accelerometer", "gyroscope", "magnetometer")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _tokens(values: Sequence[str]) -> list[str]:
|
|
15
|
+
if isinstance(values, (str, bytes)):
|
|
16
|
+
raise ValueError("CSP values must be sequences of tokens.")
|
|
17
|
+
result = []
|
|
18
|
+
for value in values:
|
|
19
|
+
if not isinstance(value, str) or not re.fullmatch(r"[!-~]+", value) or any(
|
|
20
|
+
char in value for char in ';,"\\'
|
|
21
|
+
):
|
|
22
|
+
raise ValueError("Invalid CSP token.")
|
|
23
|
+
if value not in result:
|
|
24
|
+
result.append(value)
|
|
25
|
+
if len(result) > 1 and any(value.lower() == "'none'" for value in result):
|
|
26
|
+
raise ValueError("The CSP none source must stand alone.")
|
|
27
|
+
return result
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _report_url(value: str, *, https_only: bool = False) -> str:
|
|
31
|
+
_tokens([value])
|
|
32
|
+
if "#" in value:
|
|
33
|
+
raise ValueError("Invalid CSP reporting URL.")
|
|
34
|
+
if value.startswith("/") and not value.startswith("//"):
|
|
35
|
+
return value
|
|
36
|
+
address = urlsplit(value)
|
|
37
|
+
protocols = {"https"} if https_only else {"http", "https"}
|
|
38
|
+
if address.scheme not in protocols or not address.hostname or address.username is not None:
|
|
39
|
+
raise ValueError("Invalid CSP reporting URL.")
|
|
40
|
+
return value
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def reporting_endpoints(name: str, url: str) -> str:
|
|
44
|
+
"""Return a Reporting-Endpoints value for one named endpoint."""
|
|
45
|
+
if not re.fullmatch(r"[a-z][a-z0-9_*-]*", name):
|
|
46
|
+
raise ValueError("Invalid CSP reporting endpoint name.")
|
|
47
|
+
return f'{name}="{_report_url(url, https_only=True)}"'
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_csp(
|
|
51
|
+
*,
|
|
52
|
+
preset: str = "strict",
|
|
53
|
+
report_only: bool = True,
|
|
54
|
+
production: bool = True,
|
|
55
|
+
sources: Mapping[str, Sequence[str]] | None = None,
|
|
56
|
+
directives: Mapping[str, Sequence[str] | None] | None = None,
|
|
57
|
+
nonce: str | None = None,
|
|
58
|
+
strict_dynamic: bool = False,
|
|
59
|
+
report_uri: str | None = None,
|
|
60
|
+
report_to: str | None = None,
|
|
61
|
+
) -> tuple[str, str] | None:
|
|
62
|
+
"""Return a CSP header name and value."""
|
|
63
|
+
if preset not in _PRESETS:
|
|
64
|
+
raise ValueError("Invalid CSP preset.")
|
|
65
|
+
if nonce is not None and not re.fullmatch(r"[A-Za-z0-9+/_-]+={0,2}", nonce):
|
|
66
|
+
raise ValueError("Invalid CSP nonce.")
|
|
67
|
+
if strict_dynamic and nonce is None:
|
|
68
|
+
raise ValueError("strict_dynamic requires a nonce.")
|
|
69
|
+
if preset == "off":
|
|
70
|
+
if nonce is not None:
|
|
71
|
+
raise ValueError("A nonce requires an active CSP preset.")
|
|
72
|
+
return None
|
|
73
|
+
policy = {
|
|
74
|
+
"default-src": ["'self'"], "base-uri": ["'self'"], "object-src": ["'none'"],
|
|
75
|
+
"frame-ancestors": ["'none'"], "form-action": ["'self'"], "script-src": ["'self'"],
|
|
76
|
+
"style-src": ["'self'"], "img-src": ["'self'", "data:"], "font-src": ["'self'"],
|
|
77
|
+
"connect-src": ["'self'"],
|
|
78
|
+
}
|
|
79
|
+
if preset == "standard":
|
|
80
|
+
policy["style-src"].append("'unsafe-inline'")
|
|
81
|
+
policy["img-src"].append("https:")
|
|
82
|
+
for group, values in (sources or {}).items():
|
|
83
|
+
if group not in _GROUPS:
|
|
84
|
+
raise ValueError("Invalid CSP source group.")
|
|
85
|
+
name = _GROUPS[group]
|
|
86
|
+
policy[name] = _tokens([*policy.get(name, policy["default-src"]), *_tokens(values)])
|
|
87
|
+
if production and not report_only:
|
|
88
|
+
policy["upgrade-insecure-requests"] = []
|
|
89
|
+
for name, override in (directives or {}).items():
|
|
90
|
+
if not re.fullmatch(r"[a-z][a-z0-9-]*", name):
|
|
91
|
+
raise ValueError("Invalid CSP directive.")
|
|
92
|
+
if override is None:
|
|
93
|
+
policy.pop(name, None)
|
|
94
|
+
else:
|
|
95
|
+
policy[name] = _tokens(override)
|
|
96
|
+
if report_uri is not None:
|
|
97
|
+
policy["report-uri"] = [_report_url(report_uri)]
|
|
98
|
+
if report_to is not None:
|
|
99
|
+
if not re.fullmatch(r"[a-z][a-z0-9_*-]*", report_to):
|
|
100
|
+
raise ValueError("Invalid CSP reporting endpoint name.")
|
|
101
|
+
policy["report-to"] = [report_to]
|
|
102
|
+
if nonce is not None:
|
|
103
|
+
for name in ("script-src", "style-src", "script-src-elem", "style-src-elem"):
|
|
104
|
+
if name.endswith("-elem") and name not in policy:
|
|
105
|
+
continue
|
|
106
|
+
values = policy.get(name, policy.get("default-src", []))
|
|
107
|
+
policy[name] = [value for value in values
|
|
108
|
+
if value.lower() not in {"'none'", "'unsafe-inline'"}]
|
|
109
|
+
policy[name].append(f"'nonce-{nonce}'")
|
|
110
|
+
if strict_dynamic and name.startswith("script-"):
|
|
111
|
+
policy[name].append("'strict-dynamic'")
|
|
112
|
+
policy[name] = list(dict.fromkeys(policy[name]))
|
|
113
|
+
header = "content-security-policy-report-only" if report_only else "content-security-policy"
|
|
114
|
+
return header, "; ".join(" ".join((name, *values)) for name, values in policy.items())
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def security_headers(
|
|
118
|
+
*, preset: str = "strict", production: bool = True, csp: bool = True,
|
|
119
|
+
hsts_max_age: int | None = 31_536_000, frame_options: str | None = "DENY",
|
|
120
|
+
) -> dict[str, str]:
|
|
121
|
+
"""Return static security headers."""
|
|
122
|
+
if preset not in _PRESETS:
|
|
123
|
+
raise ValueError("Invalid security header preset.")
|
|
124
|
+
if hsts_max_age is not None and (type(hsts_max_age) is not int or hsts_max_age < 0):
|
|
125
|
+
raise ValueError("HSTS max age must be a nonnegative integer.")
|
|
126
|
+
if frame_options not in {None, "DENY", "SAMEORIGIN"}:
|
|
127
|
+
raise ValueError("Invalid frame options.")
|
|
128
|
+
if preset == "off":
|
|
129
|
+
return {}
|
|
130
|
+
headers = {
|
|
131
|
+
"x-content-type-options": "nosniff",
|
|
132
|
+
"x-xss-protection": "0",
|
|
133
|
+
"referrer-policy": "strict-origin-when-cross-origin",
|
|
134
|
+
"permissions-policy": ", ".join(f"{feature}=()" for feature in _FEATURES),
|
|
135
|
+
}
|
|
136
|
+
if frame_options is not None:
|
|
137
|
+
headers["x-frame-options"] = frame_options
|
|
138
|
+
if production and hsts_max_age is not None:
|
|
139
|
+
headers["strict-transport-security"] = f"max-age={hsts_max_age}"
|
|
140
|
+
if csp:
|
|
141
|
+
policy = build_csp(preset=preset, production=production)
|
|
142
|
+
if policy is not None:
|
|
143
|
+
headers[policy[0]] = policy[1]
|
|
144
|
+
return headers
|
|
File without changes
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: quiet-awning
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Security headers and Content Security Policy for Python web applications
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# quiet-awning for Python
|
|
12
|
+
|
|
13
|
+
Create HTTP security headers and Content Security Policy (CSP) without runtime dependencies. Python 3.10 or later is required.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
python -m pip install quiet-awning
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## ASGI
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from quiet_awning import SecurityMiddleware
|
|
23
|
+
|
|
24
|
+
app = SecurityMiddleware(
|
|
25
|
+
app,
|
|
26
|
+
nonce=True,
|
|
27
|
+
reporting_endpoint=("csp", "/csp-reports"),
|
|
28
|
+
csp_options={
|
|
29
|
+
"report_only": True,
|
|
30
|
+
"strict_dynamic": True,
|
|
31
|
+
"sources": {"img": ["https://images.example.com"]},
|
|
32
|
+
"report_uri": "/csp-reports",
|
|
33
|
+
},
|
|
34
|
+
)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Wrap the ASGI application after it has been created. The middleware writes headers when an HTTP response starts and preserves duplicate application headers. Existing values win unless `override=True`. The current request ID and nonce are exposed in `scope["state"]` as `request_id` and `csp_nonce`. With nonce mode, render the same nonce into authorized HTML tags and send it with the matching CSP. Configure caching for those responses and check that an existing CSP does not mask the generated policy.
|
|
38
|
+
|
|
39
|
+
The default policy is report-only. Set `report_only=False` to enforce it after checking reports and testing the page. Applications provide the report receiver. Production mode enables HSTS. Set `production=False` for nonproduction use.
|
|
40
|
+
|
|
41
|
+
Use `security_headers()` for a static header map or `build_csp()` for a standalone CSP header. Available presets are `strict`, `standard`, and `off`.
|
|
42
|
+
|
|
43
|
+
## Development
|
|
44
|
+
|
|
45
|
+
Build with `python -m build` and verify distributions with `python -m twine check dist/*`. Install the wheel into a clean environment and run `python -m unittest discover -s tests` against the installed package.
|
|
46
|
+
|
|
47
|
+
## License
|
|
48
|
+
|
|
49
|
+
MIT
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/quiet_awning/__init__.py
|
|
5
|
+
src/quiet_awning/asgi.py
|
|
6
|
+
src/quiet_awning/headers.py
|
|
7
|
+
src/quiet_awning/py.typed
|
|
8
|
+
src/quiet_awning.egg-info/PKG-INFO
|
|
9
|
+
src/quiet_awning.egg-info/SOURCES.txt
|
|
10
|
+
src/quiet_awning.egg-info/dependency_links.txt
|
|
11
|
+
src/quiet_awning.egg-info/top_level.txt
|
|
12
|
+
tests/test_headers.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
quiet_awning
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
from quiet_awning import SecurityMiddleware, build_csp, security_headers
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class SecurityTests(unittest.IsolatedAsyncioTestCase):
|
|
7
|
+
async def test_middleware_preserves_duplicates_and_generates_new_nonces(self):
|
|
8
|
+
async def app(scope, receive, send):
|
|
9
|
+
await send({"type": "http.response.start", "status": 200, "headers": [
|
|
10
|
+
(b"x-frame-options", b"SAMEORIGIN"),
|
|
11
|
+
(b"set-cookie", b"a=1"), (b"set-cookie", b"b=2"),
|
|
12
|
+
]})
|
|
13
|
+
await send({"type": "http.response.body", "body": scope["state"]["csp_nonce"].encode()})
|
|
14
|
+
|
|
15
|
+
async def receive():
|
|
16
|
+
return {"type": "http.request"}
|
|
17
|
+
|
|
18
|
+
middleware = SecurityMiddleware(app, nonce=True, csp_options={"strict_dynamic": True},
|
|
19
|
+
reporting_endpoint=("csp", "/reports"))
|
|
20
|
+
nonces = []
|
|
21
|
+
for _ in range(2):
|
|
22
|
+
output = []
|
|
23
|
+
|
|
24
|
+
async def send(message):
|
|
25
|
+
output.append(message)
|
|
26
|
+
|
|
27
|
+
await middleware({"type": "http"}, receive, send)
|
|
28
|
+
headers = output[0]["headers"]
|
|
29
|
+
nonce = output[1]["body"]
|
|
30
|
+
nonces.append(nonce)
|
|
31
|
+
self.assertEqual([v for k, v in headers if k == b"set-cookie"], [b"a=1", b"b=2"])
|
|
32
|
+
self.assertEqual(dict(headers)[b"x-frame-options"], b"SAMEORIGIN")
|
|
33
|
+
self.assertIn(b"'nonce-" + nonce + b"'", dict(headers)[b"content-security-policy-report-only"])
|
|
34
|
+
self.assertTrue(dict(headers)[b"x-request-id"])
|
|
35
|
+
self.assertEqual(dict(headers)[b"reporting-endpoints"], b'csp="/reports"')
|
|
36
|
+
self.assertIn(b"report-to csp", dict(headers)[b"content-security-policy-report-only"])
|
|
37
|
+
self.assertNotEqual(*nonces)
|
|
38
|
+
|
|
39
|
+
async def test_override_replaces_case_insensitive_conflicts(self):
|
|
40
|
+
async def app(scope, receive, send):
|
|
41
|
+
await send({"type": "http.response.start", "status": 200,
|
|
42
|
+
"headers": [(b"X-Frame-Options", b"SAMEORIGIN")]})
|
|
43
|
+
|
|
44
|
+
output = []
|
|
45
|
+
|
|
46
|
+
async def send(message):
|
|
47
|
+
output.append(message)
|
|
48
|
+
|
|
49
|
+
await SecurityMiddleware(app, override=True)({"type": "http"}, None, send)
|
|
50
|
+
self.assertEqual(dict(output[0]["headers"])[b"x-frame-options"], b"DENY")
|
|
51
|
+
self.assertNotIn(b"X-Frame-Options", dict(output[0]["headers"]))
|
|
52
|
+
|
|
53
|
+
def test_csp_modes_and_configuration(self):
|
|
54
|
+
self.assertNotIn("strict-transport-security", security_headers(production=False))
|
|
55
|
+
report = build_csp(report_uri="/reports")
|
|
56
|
+
self.assertIn("report-uri /reports", report[1])
|
|
57
|
+
self.assertNotIn("upgrade-insecure-requests", report[1])
|
|
58
|
+
self.assertIn("upgrade-insecure-requests", build_csp(report_only=False)[1])
|
|
59
|
+
with self.assertRaises(ValueError):
|
|
60
|
+
build_csp(sources={"script": ["bad;directive"]})
|