secure 2.0.0__tar.gz → 2.0.1__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.
- secure-2.0.1/PKG-INFO +215 -0
- secure-2.0.1/README.md +187 -0
- {secure-2.0.0 → secure-2.0.1}/pyproject.toml +6 -2
- secure-2.0.1/secure/_internal/__init__.py +1 -0
- secure-2.0.1/secure/_internal/configured_headers.py +122 -0
- secure-2.0.1/secure/_internal/constants.py +39 -0
- secure-2.0.1/secure/_internal/emit.py +138 -0
- secure-2.0.1/secure/_internal/normalize.py +164 -0
- secure-2.0.1/secure/_internal/policy.py +167 -0
- secure-2.0.1/secure/_internal/presets.py +112 -0
- secure-2.0.1/secure/_internal/types.py +21 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/server.py +3 -3
- {secure-2.0.0 → secure-2.0.1}/secure/middleware/asgi.py +1 -1
- {secure-2.0.0 → secure-2.0.1}/secure/middleware/wsgi.py +1 -1
- secure-2.0.1/secure/secure.py +503 -0
- secure-2.0.1/secure.egg-info/PKG-INFO +215 -0
- {secure-2.0.0 → secure-2.0.1}/secure.egg-info/SOURCES.txt +8 -0
- secure-2.0.0/PKG-INFO +0 -693
- secure-2.0.0/README.md +0 -666
- secure-2.0.0/secure/secure.py +0 -977
- secure-2.0.0/secure.egg-info/PKG-INFO +0 -693
- {secure-2.0.0 → secure-2.0.1}/LICENSE +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/__init__.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/__init__.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/_validation.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/base_header.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/cache_control.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/content_security_policy.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/cross_origin_embedder_policy.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/cross_origin_opener_policy.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/cross_origin_resource_policy.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/custom_header.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/permissions_policy.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/referrer_policy.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/strict_transport_security.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/x_content_type_options.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/x_dns_prefetch_control.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/x_frame_options.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/headers/x_permitted_cross_domain_policies.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/middleware/__init__.py +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure/py.typed +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure.egg-info/dependency_links.txt +0 -0
- {secure-2.0.0 → secure-2.0.1}/secure.egg-info/top_level.txt +0 -0
- {secure-2.0.0 → secure-2.0.1}/setup.cfg +0 -0
secure-2.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: secure
|
|
3
|
+
Version: 2.0.1
|
|
4
|
+
Summary: A lightweight package that adds security headers for Python web frameworks.
|
|
5
|
+
Author-email: Caleb Kinney <caleb@typeerror.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/TypeError/secure
|
|
8
|
+
Project-URL: Documentation, https://github.com/TypeError/secure/tree/main/docs
|
|
9
|
+
Project-URL: Repository, https://github.com/TypeError/secure
|
|
10
|
+
Project-URL: Issue Tracker, https://github.com/TypeError/secure/issues
|
|
11
|
+
Keywords: security,headers,web,framework,HTTP
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# secure
|
|
30
|
+
|
|
31
|
+
HTTP security headers for Python web applications, centered on one object: `Secure`.
|
|
32
|
+
|
|
33
|
+
[](https://pypi.org/project/secure/)
|
|
34
|
+
[](https://pypi.org/project/secure/)
|
|
35
|
+
[](https://github.com/TypeError/secure/blob/main/LICENSE)
|
|
36
|
+
[](https://github.com/TypeError/secure/stargazers)
|
|
37
|
+
|
|
38
|
+
`secure` exists to keep header policy out of ad hoc view code. Instead of copying header strings into routes, middleware, and framework-specific hooks, you configure one `Secure` instance and apply it consistently.
|
|
39
|
+
|
|
40
|
+
Hand-written header code tends to drift. Headers get missed, defaults vary between apps, and sync or async framework details leak into otherwise simple code. `secure` gives you a small public API, opinionated presets, and typed builders when you need to go beyond the defaults.
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
`secure` requires Python 3.10+ and has no external dependencies.
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
uv add secure
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install secure
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Quick start
|
|
55
|
+
|
|
56
|
+
Start with `Secure.with_default_headers()`. It uses `Preset.BALANCED`, the recommended default for most applications.
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from secure import Secure
|
|
60
|
+
|
|
61
|
+
class Response:
|
|
62
|
+
def __init__(self):
|
|
63
|
+
self.headers = {}
|
|
64
|
+
|
|
65
|
+
response = Response()
|
|
66
|
+
Secure.with_default_headers().set_headers(response)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`Secure` applies headers to response objects that expose either:
|
|
70
|
+
|
|
71
|
+
- `response.set_header(name, value)`
|
|
72
|
+
- `response.headers[name] = value`
|
|
73
|
+
|
|
74
|
+
The quick start uses the `response.headers[name] = value` form.
|
|
75
|
+
|
|
76
|
+
Use `set_headers()` for synchronous response objects. Use `set_headers_async()` in async code or when the response object may use async setters.
|
|
77
|
+
|
|
78
|
+
## Presets
|
|
79
|
+
|
|
80
|
+
Most applications should start with `BALANCED`.
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from secure import Preset, Secure
|
|
84
|
+
|
|
85
|
+
balanced = Secure.from_preset(Preset.BALANCED)
|
|
86
|
+
basic = Secure.from_preset(Preset.BASIC)
|
|
87
|
+
strict = Secure.from_preset(Preset.STRICT)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- `Preset.BALANCED`: recommended default. Modern baseline with CSP, HSTS, referrer policy, permissions policy, and common browser protections.
|
|
91
|
+
- `Preset.BASIC`: compatibility-oriented. Adds legacy and interoperability headers that some deployments still expect.
|
|
92
|
+
- `Preset.STRICT`: hardened profile. Tightens CSP, disables caching, and denies framing.
|
|
93
|
+
|
|
94
|
+
Choose `BALANCED` unless you have a specific reason to prefer `BASIC` or `STRICT`.
|
|
95
|
+
|
|
96
|
+
## Middleware
|
|
97
|
+
|
|
98
|
+
If your framework supports app-wide middleware, prefer that over setting headers one response at a time.
|
|
99
|
+
|
|
100
|
+
### WSGI
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from flask import Flask
|
|
104
|
+
from secure import Secure
|
|
105
|
+
from secure.middleware import SecureWSGIMiddleware
|
|
106
|
+
|
|
107
|
+
app = Flask(__name__)
|
|
108
|
+
secure_headers = Secure.with_default_headers()
|
|
109
|
+
|
|
110
|
+
app.wsgi_app = SecureWSGIMiddleware(app.wsgi_app, secure=secure_headers)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### ASGI
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from fastapi import FastAPI
|
|
117
|
+
from secure import Secure
|
|
118
|
+
from secure.middleware import SecureASGIMiddleware
|
|
119
|
+
|
|
120
|
+
app = FastAPI()
|
|
121
|
+
secure_headers = Secure.with_default_headers()
|
|
122
|
+
|
|
123
|
+
app.add_middleware(SecureASGIMiddleware, secure=secure_headers)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Use `SecureWSGIMiddleware` when you can wrap a WSGI app directly. Use `SecureASGIMiddleware` when you want app-wide coverage in an ASGI stack such as FastAPI, Starlette, or Shiny.
|
|
127
|
+
|
|
128
|
+
## Advanced usage
|
|
129
|
+
|
|
130
|
+
Most applications can stop at a preset. When you need to tune a specific header, keep `Secure` as the entry point and pass builder objects into it.
|
|
131
|
+
|
|
132
|
+
### Custom policy
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
from secure import ContentSecurityPolicy, Secure, StrictTransportSecurity
|
|
136
|
+
|
|
137
|
+
secure_headers = Secure(
|
|
138
|
+
csp=(
|
|
139
|
+
ContentSecurityPolicy()
|
|
140
|
+
.default_src("'self'")
|
|
141
|
+
.img_src("'self'", "https://images.example.com")
|
|
142
|
+
.script_src("'self'", "https://cdn.example.com")
|
|
143
|
+
),
|
|
144
|
+
hsts=StrictTransportSecurity().max_age(63072000).include_subdomains(),
|
|
145
|
+
)
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Optional validation
|
|
149
|
+
|
|
150
|
+
The validation pipeline is optional. Use it when headers are being composed dynamically and you want stricter checks before emission.
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
from secure import Secure
|
|
154
|
+
|
|
155
|
+
secure_headers = (
|
|
156
|
+
Secure.with_default_headers()
|
|
157
|
+
.allowlist_headers()
|
|
158
|
+
.deduplicate_headers()
|
|
159
|
+
.validate_and_normalize_headers()
|
|
160
|
+
)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
If you need manual emission for an unsupported response contract, iterate over `secure_headers.header_items()`.
|
|
164
|
+
|
|
165
|
+
## Framework examples
|
|
166
|
+
|
|
167
|
+
See [docs/frameworks.md](./docs/frameworks.md) for the full matrix. The most common patterns are:
|
|
168
|
+
|
|
169
|
+
### FastAPI
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from fastapi import FastAPI
|
|
173
|
+
from secure import Secure
|
|
174
|
+
from secure.middleware import SecureASGIMiddleware
|
|
175
|
+
|
|
176
|
+
app = FastAPI()
|
|
177
|
+
secure_headers = Secure.with_default_headers()
|
|
178
|
+
app.add_middleware(SecureASGIMiddleware, secure=secure_headers)
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### Flask
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
from flask import Flask
|
|
185
|
+
from secure import Secure
|
|
186
|
+
|
|
187
|
+
app = Flask(__name__)
|
|
188
|
+
secure_headers = Secure.with_default_headers()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@app.after_request
|
|
192
|
+
def add_security_headers(response):
|
|
193
|
+
secure_headers.set_headers(response)
|
|
194
|
+
return response
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### Starlette
|
|
198
|
+
|
|
199
|
+
```python
|
|
200
|
+
from secure import Secure
|
|
201
|
+
from secure.middleware import SecureASGIMiddleware
|
|
202
|
+
from starlette.applications import Starlette
|
|
203
|
+
|
|
204
|
+
app = Starlette()
|
|
205
|
+
secure_headers = Secure.with_default_headers()
|
|
206
|
+
app.add_middleware(SecureASGIMiddleware, secure=secure_headers)
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## Links
|
|
210
|
+
|
|
211
|
+
- [Documentation index](./docs/README.md)
|
|
212
|
+
- [Installation](./docs/installation.md)
|
|
213
|
+
- [Usage](./docs/usage.md)
|
|
214
|
+
- [Framework integration](./docs/frameworks.md)
|
|
215
|
+
- [Migration notes](./docs/migration.md)
|
secure-2.0.1/README.md
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# secure
|
|
2
|
+
|
|
3
|
+
HTTP security headers for Python web applications, centered on one object: `Secure`.
|
|
4
|
+
|
|
5
|
+
[](https://pypi.org/project/secure/)
|
|
6
|
+
[](https://pypi.org/project/secure/)
|
|
7
|
+
[](https://github.com/TypeError/secure/blob/main/LICENSE)
|
|
8
|
+
[](https://github.com/TypeError/secure/stargazers)
|
|
9
|
+
|
|
10
|
+
`secure` exists to keep header policy out of ad hoc view code. Instead of copying header strings into routes, middleware, and framework-specific hooks, you configure one `Secure` instance and apply it consistently.
|
|
11
|
+
|
|
12
|
+
Hand-written header code tends to drift. Headers get missed, defaults vary between apps, and sync or async framework details leak into otherwise simple code. `secure` gives you a small public API, opinionated presets, and typed builders when you need to go beyond the defaults.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
`secure` requires Python 3.10+ and has no external dependencies.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
uv add secure
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install secure
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
Start with `Secure.with_default_headers()`. It uses `Preset.BALANCED`, the recommended default for most applications.
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from secure import Secure
|
|
32
|
+
|
|
33
|
+
class Response:
|
|
34
|
+
def __init__(self):
|
|
35
|
+
self.headers = {}
|
|
36
|
+
|
|
37
|
+
response = Response()
|
|
38
|
+
Secure.with_default_headers().set_headers(response)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`Secure` applies headers to response objects that expose either:
|
|
42
|
+
|
|
43
|
+
- `response.set_header(name, value)`
|
|
44
|
+
- `response.headers[name] = value`
|
|
45
|
+
|
|
46
|
+
The quick start uses the `response.headers[name] = value` form.
|
|
47
|
+
|
|
48
|
+
Use `set_headers()` for synchronous response objects. Use `set_headers_async()` in async code or when the response object may use async setters.
|
|
49
|
+
|
|
50
|
+
## Presets
|
|
51
|
+
|
|
52
|
+
Most applications should start with `BALANCED`.
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from secure import Preset, Secure
|
|
56
|
+
|
|
57
|
+
balanced = Secure.from_preset(Preset.BALANCED)
|
|
58
|
+
basic = Secure.from_preset(Preset.BASIC)
|
|
59
|
+
strict = Secure.from_preset(Preset.STRICT)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
- `Preset.BALANCED`: recommended default. Modern baseline with CSP, HSTS, referrer policy, permissions policy, and common browser protections.
|
|
63
|
+
- `Preset.BASIC`: compatibility-oriented. Adds legacy and interoperability headers that some deployments still expect.
|
|
64
|
+
- `Preset.STRICT`: hardened profile. Tightens CSP, disables caching, and denies framing.
|
|
65
|
+
|
|
66
|
+
Choose `BALANCED` unless you have a specific reason to prefer `BASIC` or `STRICT`.
|
|
67
|
+
|
|
68
|
+
## Middleware
|
|
69
|
+
|
|
70
|
+
If your framework supports app-wide middleware, prefer that over setting headers one response at a time.
|
|
71
|
+
|
|
72
|
+
### WSGI
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from flask import Flask
|
|
76
|
+
from secure import Secure
|
|
77
|
+
from secure.middleware import SecureWSGIMiddleware
|
|
78
|
+
|
|
79
|
+
app = Flask(__name__)
|
|
80
|
+
secure_headers = Secure.with_default_headers()
|
|
81
|
+
|
|
82
|
+
app.wsgi_app = SecureWSGIMiddleware(app.wsgi_app, secure=secure_headers)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### ASGI
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from fastapi import FastAPI
|
|
89
|
+
from secure import Secure
|
|
90
|
+
from secure.middleware import SecureASGIMiddleware
|
|
91
|
+
|
|
92
|
+
app = FastAPI()
|
|
93
|
+
secure_headers = Secure.with_default_headers()
|
|
94
|
+
|
|
95
|
+
app.add_middleware(SecureASGIMiddleware, secure=secure_headers)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Use `SecureWSGIMiddleware` when you can wrap a WSGI app directly. Use `SecureASGIMiddleware` when you want app-wide coverage in an ASGI stack such as FastAPI, Starlette, or Shiny.
|
|
99
|
+
|
|
100
|
+
## Advanced usage
|
|
101
|
+
|
|
102
|
+
Most applications can stop at a preset. When you need to tune a specific header, keep `Secure` as the entry point and pass builder objects into it.
|
|
103
|
+
|
|
104
|
+
### Custom policy
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from secure import ContentSecurityPolicy, Secure, StrictTransportSecurity
|
|
108
|
+
|
|
109
|
+
secure_headers = Secure(
|
|
110
|
+
csp=(
|
|
111
|
+
ContentSecurityPolicy()
|
|
112
|
+
.default_src("'self'")
|
|
113
|
+
.img_src("'self'", "https://images.example.com")
|
|
114
|
+
.script_src("'self'", "https://cdn.example.com")
|
|
115
|
+
),
|
|
116
|
+
hsts=StrictTransportSecurity().max_age(63072000).include_subdomains(),
|
|
117
|
+
)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Optional validation
|
|
121
|
+
|
|
122
|
+
The validation pipeline is optional. Use it when headers are being composed dynamically and you want stricter checks before emission.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from secure import Secure
|
|
126
|
+
|
|
127
|
+
secure_headers = (
|
|
128
|
+
Secure.with_default_headers()
|
|
129
|
+
.allowlist_headers()
|
|
130
|
+
.deduplicate_headers()
|
|
131
|
+
.validate_and_normalize_headers()
|
|
132
|
+
)
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
If you need manual emission for an unsupported response contract, iterate over `secure_headers.header_items()`.
|
|
136
|
+
|
|
137
|
+
## Framework examples
|
|
138
|
+
|
|
139
|
+
See [docs/frameworks.md](./docs/frameworks.md) for the full matrix. The most common patterns are:
|
|
140
|
+
|
|
141
|
+
### FastAPI
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from fastapi import FastAPI
|
|
145
|
+
from secure import Secure
|
|
146
|
+
from secure.middleware import SecureASGIMiddleware
|
|
147
|
+
|
|
148
|
+
app = FastAPI()
|
|
149
|
+
secure_headers = Secure.with_default_headers()
|
|
150
|
+
app.add_middleware(SecureASGIMiddleware, secure=secure_headers)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Flask
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from flask import Flask
|
|
157
|
+
from secure import Secure
|
|
158
|
+
|
|
159
|
+
app = Flask(__name__)
|
|
160
|
+
secure_headers = Secure.with_default_headers()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@app.after_request
|
|
164
|
+
def add_security_headers(response):
|
|
165
|
+
secure_headers.set_headers(response)
|
|
166
|
+
return response
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### Starlette
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from secure import Secure
|
|
173
|
+
from secure.middleware import SecureASGIMiddleware
|
|
174
|
+
from starlette.applications import Starlette
|
|
175
|
+
|
|
176
|
+
app = Starlette()
|
|
177
|
+
secure_headers = Secure.with_default_headers()
|
|
178
|
+
app.add_middleware(SecureASGIMiddleware, secure=secure_headers)
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Links
|
|
182
|
+
|
|
183
|
+
- [Documentation index](./docs/README.md)
|
|
184
|
+
- [Installation](./docs/installation.md)
|
|
185
|
+
- [Usage](./docs/usage.md)
|
|
186
|
+
- [Framework integration](./docs/frameworks.md)
|
|
187
|
+
- [Migration notes](./docs/migration.md)
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "secure"
|
|
7
|
-
version = "2.0.
|
|
7
|
+
version = "2.0.1"
|
|
8
8
|
description = "A lightweight package that adds security headers for Python web frameworks."
|
|
9
9
|
readme = { file = "README.md", content-type = "text/markdown" }
|
|
10
10
|
license = "MIT"
|
|
@@ -22,7 +22,7 @@ classifiers = [
|
|
|
22
22
|
"Programming Language :: Python :: 3.11",
|
|
23
23
|
"Programming Language :: Python :: 3.12",
|
|
24
24
|
"Programming Language :: Python :: 3.13",
|
|
25
|
-
|
|
25
|
+
"Programming Language :: Python :: 3.14",
|
|
26
26
|
"Typing :: Typed",
|
|
27
27
|
"Topic :: Software Development :: Libraries",
|
|
28
28
|
]
|
|
@@ -42,6 +42,10 @@ exclude = ["tests*", "docs*"]
|
|
|
42
42
|
[tool.setuptools.package-data]
|
|
43
43
|
secure = ["py.typed"]
|
|
44
44
|
|
|
45
|
+
[tool.pytest.ini_options]
|
|
46
|
+
pythonpath = ["."]
|
|
47
|
+
testpaths = ["tests"]
|
|
48
|
+
|
|
45
49
|
# --- Ruff (formatter + linter) ---
|
|
46
50
|
[tool.ruff]
|
|
47
51
|
target-version = "py310"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Private implementation details for the secure package."""
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from types import MappingProxyType
|
|
4
|
+
from typing import TYPE_CHECKING, Any, TypeAlias, overload
|
|
5
|
+
|
|
6
|
+
from ..headers.base_header import BaseHeader
|
|
7
|
+
from ..headers.custom_header import CustomHeader
|
|
8
|
+
from .types import HeaderItems, HeaderPair
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from collections.abc import Callable, Iterable
|
|
12
|
+
|
|
13
|
+
HeaderInput: TypeAlias = BaseHeader | HeaderPair | list[str]
|
|
14
|
+
HEADER_PAIR_SIZE = 2
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ConfiguredHeaders(list[BaseHeader]):
|
|
18
|
+
"""Mutable header builder collection with centralized mutation bookkeeping."""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
headers: Iterable[HeaderInput] = (),
|
|
23
|
+
*,
|
|
24
|
+
on_change: Callable[[], None],
|
|
25
|
+
) -> None:
|
|
26
|
+
self._on_change = on_change
|
|
27
|
+
super().__init__(_coerce_header_object(header, operation="ConfiguredHeaders") for header in headers)
|
|
28
|
+
|
|
29
|
+
def replace_all(self, headers: Iterable[HeaderInput]) -> None:
|
|
30
|
+
replacement = [_coerce_header_object(header, operation="headers_list") for header in headers]
|
|
31
|
+
super().clear()
|
|
32
|
+
super().extend(replacement)
|
|
33
|
+
self._on_change()
|
|
34
|
+
|
|
35
|
+
def append(self, header: HeaderInput) -> None:
|
|
36
|
+
super().append(_coerce_header_object(header, operation="headers_list.append"))
|
|
37
|
+
self._on_change()
|
|
38
|
+
|
|
39
|
+
def extend(self, headers: Iterable[HeaderInput]) -> None:
|
|
40
|
+
super().extend(_coerce_header_object(header, operation="headers_list.extend") for header in headers)
|
|
41
|
+
self._on_change()
|
|
42
|
+
|
|
43
|
+
def insert(self, index: int, header: HeaderInput) -> None:
|
|
44
|
+
super().insert(index, _coerce_header_object(header, operation="headers_list.insert"))
|
|
45
|
+
self._on_change()
|
|
46
|
+
|
|
47
|
+
@overload
|
|
48
|
+
def __setitem__(self, index: int, header: HeaderInput) -> None: ...
|
|
49
|
+
|
|
50
|
+
@overload
|
|
51
|
+
def __setitem__(self, index: slice, header: Iterable[HeaderInput]) -> None: ...
|
|
52
|
+
|
|
53
|
+
def __setitem__(self, index: int | slice, header: HeaderInput | Iterable[HeaderInput]) -> None:
|
|
54
|
+
if isinstance(index, slice):
|
|
55
|
+
super().__setitem__(
|
|
56
|
+
index,
|
|
57
|
+
[_coerce_header_object(item, operation="headers_list assignment") for item in header],
|
|
58
|
+
)
|
|
59
|
+
else:
|
|
60
|
+
super().__setitem__(index, _coerce_header_object(header, operation="headers_list assignment"))
|
|
61
|
+
self._on_change()
|
|
62
|
+
|
|
63
|
+
def __delitem__(self, index: int | slice) -> None:
|
|
64
|
+
super().__delitem__(index)
|
|
65
|
+
self._on_change()
|
|
66
|
+
|
|
67
|
+
def clear(self) -> None:
|
|
68
|
+
super().clear()
|
|
69
|
+
self._on_change()
|
|
70
|
+
|
|
71
|
+
def pop(self, index: int = -1) -> BaseHeader:
|
|
72
|
+
header = super().pop(index)
|
|
73
|
+
self._on_change()
|
|
74
|
+
return header
|
|
75
|
+
|
|
76
|
+
def remove(self, header: BaseHeader) -> None:
|
|
77
|
+
super().remove(header)
|
|
78
|
+
self._on_change()
|
|
79
|
+
|
|
80
|
+
def reverse(self) -> None:
|
|
81
|
+
super().reverse()
|
|
82
|
+
self._on_change()
|
|
83
|
+
|
|
84
|
+
def sort(self, *, key: Callable[[BaseHeader], Any] | None = None, reverse: bool = False) -> None:
|
|
85
|
+
super().sort(key=key, reverse=reverse)
|
|
86
|
+
self._on_change()
|
|
87
|
+
|
|
88
|
+
def __iadd__(self, headers: Iterable[HeaderInput]) -> ConfiguredHeaders:
|
|
89
|
+
self.extend(headers)
|
|
90
|
+
return self
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def header_items_from_objects(headers: Iterable[BaseHeader]) -> HeaderItems:
|
|
94
|
+
return tuple((header.header_name, header.header_value) for header in headers)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def header_mapping_from_items(items: HeaderItems) -> MappingProxyType[str, str]:
|
|
98
|
+
headers: dict[str, str] = {}
|
|
99
|
+
seen_names: set[str] = set()
|
|
100
|
+
|
|
101
|
+
for name, value in items:
|
|
102
|
+
lowered_name = name.lower()
|
|
103
|
+
if lowered_name in seen_names:
|
|
104
|
+
raise ValueError(f"Multiple '{name}' headers present; use `header_items()` when emitting multiples.")
|
|
105
|
+
seen_names.add(lowered_name)
|
|
106
|
+
headers[name] = value
|
|
107
|
+
|
|
108
|
+
return MappingProxyType(headers)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _coerce_header_object(header: HeaderInput, *, operation: str) -> BaseHeader:
|
|
112
|
+
if isinstance(header, BaseHeader):
|
|
113
|
+
return header
|
|
114
|
+
|
|
115
|
+
if (isinstance(header, tuple) and len(header) == HEADER_PAIR_SIZE) or (
|
|
116
|
+
isinstance(header, list) and len(header) == HEADER_PAIR_SIZE
|
|
117
|
+
):
|
|
118
|
+
name, value = header
|
|
119
|
+
if isinstance(name, str) and isinstance(value, str):
|
|
120
|
+
return CustomHeader(header=name, value=value)
|
|
121
|
+
|
|
122
|
+
raise TypeError(f"{operation} expects BaseHeader objects or (name, value) pairs")
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
# Headers that may appear multiple times as separate fields.
|
|
6
|
+
MULTI_OK: frozenset[str] = frozenset(
|
|
7
|
+
{
|
|
8
|
+
"content-security-policy",
|
|
9
|
+
}
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
# Headers where RFC7230-style comma merging is safe/expected.
|
|
13
|
+
COMMA_JOIN_OK: frozenset[str] = frozenset({"cache-control"})
|
|
14
|
+
|
|
15
|
+
# A default allowlist of secure headers.
|
|
16
|
+
DEFAULT_ALLOWED_HEADERS: frozenset[str] = frozenset(
|
|
17
|
+
{
|
|
18
|
+
"cache-control",
|
|
19
|
+
"content-security-policy",
|
|
20
|
+
"content-security-policy-report-only",
|
|
21
|
+
"cross-origin-embedder-policy",
|
|
22
|
+
"cross-origin-opener-policy",
|
|
23
|
+
"cross-origin-resource-policy",
|
|
24
|
+
"origin-agent-cluster",
|
|
25
|
+
"permissions-policy",
|
|
26
|
+
"referrer-policy",
|
|
27
|
+
"server",
|
|
28
|
+
"strict-transport-security",
|
|
29
|
+
"x-content-type-options",
|
|
30
|
+
"x-dns-prefetch-control",
|
|
31
|
+
"x-download-options",
|
|
32
|
+
"x-frame-options",
|
|
33
|
+
"x-permitted-cross-domain-policies",
|
|
34
|
+
"x-xss-protection",
|
|
35
|
+
}
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
# RFC 7230 token (visible ASCII except separators).
|
|
39
|
+
HEADER_NAME_RE = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")
|