secure 1.0.1__tar.gz → 2.0.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.
- secure-2.0.0/PKG-INFO +693 -0
- secure-2.0.0/README.md +666 -0
- secure-2.0.0/pyproject.toml +95 -0
- {secure-1.0.1 → secure-2.0.0}/secure/__init__.py +16 -1
- {secure-1.0.1 → secure-2.0.0}/secure/headers/__init__.py +6 -0
- secure-2.0.0/secure/headers/_validation.py +20 -0
- {secure-1.0.1 → secure-2.0.0}/secure/headers/base_header.py +26 -2
- secure-2.0.0/secure/headers/cache_control.py +308 -0
- secure-2.0.0/secure/headers/content_security_policy.py +332 -0
- secure-2.0.0/secure/headers/cross_origin_embedder_policy.py +108 -0
- secure-2.0.0/secure/headers/cross_origin_opener_policy.py +157 -0
- secure-2.0.0/secure/headers/cross_origin_resource_policy.py +114 -0
- secure-2.0.0/secure/headers/custom_header.py +70 -0
- secure-2.0.0/secure/headers/permissions_policy.py +416 -0
- secure-2.0.0/secure/headers/referrer_policy.py +170 -0
- {secure-1.0.1 → secure-2.0.0}/secure/headers/server.py +19 -8
- secure-2.0.0/secure/headers/strict_transport_security.py +155 -0
- {secure-1.0.1 → secure-2.0.0}/secure/headers/x_content_type_options.py +14 -5
- secure-2.0.0/secure/headers/x_dns_prefetch_control.py +103 -0
- secure-2.0.0/secure/headers/x_frame_options.py +113 -0
- secure-2.0.0/secure/headers/x_permitted_cross_domain_policies.py +129 -0
- secure-2.0.0/secure/middleware/__init__.py +9 -0
- secure-2.0.0/secure/middleware/asgi.py +158 -0
- secure-2.0.0/secure/middleware/wsgi.py +143 -0
- secure-2.0.0/secure/secure.py +977 -0
- secure-2.0.0/secure.egg-info/PKG-INFO +693 -0
- {secure-1.0.1 → secure-2.0.0}/secure.egg-info/SOURCES.txt +8 -2
- {secure-1.0.1 → secure-2.0.0}/secure.egg-info/top_level.txt +0 -1
- secure-1.0.1/MANIFEST.in +0 -2
- secure-1.0.1/PKG-INFO +0 -348
- secure-1.0.1/README.md +0 -324
- secure-1.0.1/pyproject.toml +0 -37
- secure-1.0.1/secure/headers/cache_control.py +0 -257
- secure-1.0.1/secure/headers/content_security_policy.py +0 -305
- secure-1.0.1/secure/headers/cross_origin_embedder_policy.py +0 -100
- secure-1.0.1/secure/headers/cross_origin_opener_policy.py +0 -111
- secure-1.0.1/secure/headers/custom_header.py +0 -56
- secure-1.0.1/secure/headers/permissions_policy.py +0 -412
- secure-1.0.1/secure/headers/referrer_policy.py +0 -168
- secure-1.0.1/secure/headers/strict_transport_security.py +0 -118
- secure-1.0.1/secure/headers/x_frame_options.py +0 -89
- secure-1.0.1/secure/secure.py +0 -286
- secure-1.0.1/secure.egg-info/PKG-INFO +0 -348
- {secure-1.0.1 → secure-2.0.0}/LICENSE +0 -0
- {secure-1.0.1 → secure-2.0.0}/secure/py.typed +0 -0
- {secure-1.0.1 → secure-2.0.0}/secure.egg-info/dependency_links.txt +0 -0
- {secure-1.0.1 → secure-2.0.0}/setup.cfg +0 -0
secure-2.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,693 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: secure
|
|
3
|
+
Version: 2.0.0
|
|
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: Typing :: Typed
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# secure
|
|
29
|
+
|
|
30
|
+
A small, focused library for adding modern security headers to Python web applications.
|
|
31
|
+
|
|
32
|
+
[](https://pypi.org/project/secure/)
|
|
33
|
+
[](https://pypi.org/project/secure/)
|
|
34
|
+
[](https://github.com/TypeError/secure/blob/main/LICENSE)
|
|
35
|
+
[](https://github.com/TypeError/secure/stargazers)
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Introduction
|
|
40
|
+
|
|
41
|
+
Security headers are one of the simplest ways to raise the security bar for a web application, but they are often applied inconsistently across frameworks and deployments.
|
|
42
|
+
|
|
43
|
+
`secure` gives you a single, modern, well typed API for configuring and applying HTTP security headers in Python. It focuses on:
|
|
44
|
+
|
|
45
|
+
- Good defaults that are safe to adopt.
|
|
46
|
+
- A small, explicit API instead of a large framework.
|
|
47
|
+
- Support for both synchronous and asynchronous response objects.
|
|
48
|
+
- Framework agnostic integration so you can use the same configuration everywhere.
|
|
49
|
+
|
|
50
|
+
The package is published on PyPI as `secure` and imported with:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import secure
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## Why use `secure`
|
|
59
|
+
|
|
60
|
+
- Apply essential security headers with a few lines of code.
|
|
61
|
+
- Share one configuration across multiple frameworks and applications.
|
|
62
|
+
- Start from secure presets, then customize as your needs grow.
|
|
63
|
+
- Keep header logic out of your views and handlers.
|
|
64
|
+
- Use one library for FastAPI, Starlette, Flask, Django, and more.
|
|
65
|
+
- Rely on modern Python 3.10+ features and full type hints for better editor support.
|
|
66
|
+
|
|
67
|
+
If you want your app to ship with a strong security baseline without pulling in a heavyweight dependency, `secure` is designed for you.
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## Supported frameworks
|
|
72
|
+
|
|
73
|
+
`secure` integrates with a range of popular Python web frameworks. The core API is framework independent, and each framework uses the same `Secure` object and methods.
|
|
74
|
+
|
|
75
|
+
| Framework | Documentation |
|
|
76
|
+
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
|
|
77
|
+
| [aiohttp](https://docs.aiohttp.org) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#aiohttp) |
|
|
78
|
+
| [Bottle](https://bottlepy.org) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#bottle) |
|
|
79
|
+
| [CherryPy](https://cherrypy.dev/) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#cherrypy) |
|
|
80
|
+
| [Django](https://www.djangoproject.com) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#django) |
|
|
81
|
+
| [Falcon](https://falconframework.org) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#falcon) |
|
|
82
|
+
| [FastAPI](https://fastapi.tiangolo.com) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#fastapi) |
|
|
83
|
+
| [Flask](http://flask.pocoo.org) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#flask) |
|
|
84
|
+
| [Masonite](https://docs.masoniteproject.com/) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#masonite) |
|
|
85
|
+
| [Morepath](https://morepath.readthedocs.io) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#morepath) |
|
|
86
|
+
| [Pyramid](https://trypyramid.com) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#pyramid) |
|
|
87
|
+
| [Quart](https://quart.palletsprojects.com/en/latest/) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#quart) |
|
|
88
|
+
| [Responder](https://responder.kennethreitz.org/) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#responder) |
|
|
89
|
+
| [Sanic](https://sanicframework.org) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#sanic) |
|
|
90
|
+
| [Starlette](https://www.starlette.io/) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#starlette) |
|
|
91
|
+
| [Tornado](https://www.tornadoweb.org/) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#tornado) |
|
|
92
|
+
| [TurboGears](https://turbogears.org/) | [Integration Guide](https://github.com/TypeError/secure/blob/main/docs/frameworks.md#turbogears) |
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## Features
|
|
97
|
+
|
|
98
|
+
- **Secure headers**
|
|
99
|
+
Apply headers like `Strict-Transport-Security`, `Content-Security-Policy`, `X-Content-Type-Options`, `X-Frame-Options`, and more.
|
|
100
|
+
|
|
101
|
+
- **Presets with secure defaults**
|
|
102
|
+
Start from opinionated presets like `Preset.BASIC` and `Preset.STRICT`, then customize as needed.
|
|
103
|
+
|
|
104
|
+
- **Policy builders**
|
|
105
|
+
Compose complex policies such as CSP and Permissions Policy through a fluent API.
|
|
106
|
+
|
|
107
|
+
- **Framework agnostic**
|
|
108
|
+
Works with sync and async response objects and does not depend on any single framework.
|
|
109
|
+
|
|
110
|
+
- **Zero external dependencies**
|
|
111
|
+
Easy to audit and suitable for security sensitive environments.
|
|
112
|
+
|
|
113
|
+
- **Modern Python design**
|
|
114
|
+
Uses Python 3.10+ features and full type hints so your editor and type checker can help you.
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## Requirements
|
|
119
|
+
|
|
120
|
+
- **Python 3.10 or higher**
|
|
121
|
+
|
|
122
|
+
`secure` targets modern Python and is currently tested on Python 3.10 through 3.13.
|
|
123
|
+
|
|
124
|
+
It uses features introduced in Python 3.10, including:
|
|
125
|
+
|
|
126
|
+
- Union type operator (`|`) for cleaner type annotations.
|
|
127
|
+
- Structural pattern matching (`match`).
|
|
128
|
+
- Improved typing and annotations.
|
|
129
|
+
- `functools.cached_property` for efficient lazy computation.
|
|
130
|
+
|
|
131
|
+
If you need support for Python 3.6 through 3.9, use version `0.3.0` of the library.
|
|
132
|
+
|
|
133
|
+
- **Dependencies**
|
|
134
|
+
|
|
135
|
+
This library has no external dependencies outside of the Python standard library.
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## Installation
|
|
140
|
+
|
|
141
|
+
You can install `secure` with your preferred Python package manager.
|
|
142
|
+
|
|
143
|
+
### Using `uv`
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
uv add secure
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### Using `pip`
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
pip install secure
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## Quick start
|
|
158
|
+
|
|
159
|
+
The core entry point is the `Secure` class. A typical simple setup looks like this:
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
import secure
|
|
163
|
+
|
|
164
|
+
secure_headers = secure.Secure.with_default_headers()
|
|
165
|
+
|
|
166
|
+
# For a synchronous framework
|
|
167
|
+
secure_headers.set_headers(response)
|
|
168
|
+
|
|
169
|
+
# For an asynchronous framework
|
|
170
|
+
await secure_headers.set_headers_async(response)
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`Secure.with_default_headers()` is equivalent to `Secure.from_preset(Preset.BALANCED)`, the recommended default profile.
|
|
174
|
+
|
|
175
|
+
`set_headers` and `set_headers_async` both operate on a response object that either:
|
|
176
|
+
|
|
177
|
+
- Exposes a `set_header(name, value)` method, or
|
|
178
|
+
- Exposes a mutable `headers` mapping that supports item assignment.
|
|
179
|
+
|
|
180
|
+
If your framework uses a different contract, see the framework specific guides or use `header_items()` to apply headers manually.
|
|
181
|
+
|
|
182
|
+
## Middleware
|
|
183
|
+
|
|
184
|
+
`secure.middleware` re-exports `SecureWSGIMiddleware` and `SecureASGIMiddleware`. Each middleware accepts a `Secure` instance (defaulting to `Secure.with_default_headers()`), overwrites headers by default, and only appends duplicates when a normalized name is included in `multi_ok` (the default `secure.secure.MULTI_OK` includes `Content-Security-Policy`).
|
|
185
|
+
|
|
186
|
+
### WSGI (Flask + Django)
|
|
187
|
+
|
|
188
|
+
Wrap any WSGI stack with `SecureWSGIMiddleware`, and pass a configured `Secure` instance if you need a custom CSP or additional headers.
|
|
189
|
+
|
|
190
|
+
```python
|
|
191
|
+
from flask import Flask
|
|
192
|
+
from secure import Secure
|
|
193
|
+
from secure.middleware import SecureWSGIMiddleware
|
|
194
|
+
|
|
195
|
+
secure_headers = Secure.with_default_headers()
|
|
196
|
+
app = Flask(__name__)
|
|
197
|
+
app.wsgi_app = SecureWSGIMiddleware(app.wsgi_app, secure=secure_headers)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
For Django, apply the headers through a middleware class since Django’s middleware pipeline wraps requests and responses rather than the raw WSGI callable:
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
from secure import Secure
|
|
204
|
+
|
|
205
|
+
class SecureHeadersMiddleware:
|
|
206
|
+
def __init__(self, get_response):
|
|
207
|
+
self.get_response = get_response
|
|
208
|
+
self.secure = Secure.with_default_headers()
|
|
209
|
+
|
|
210
|
+
def __call__(self, request):
|
|
211
|
+
response = self.get_response(request)
|
|
212
|
+
self.secure.set_headers(response)
|
|
213
|
+
return response
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Register the class in your `MIDDLEWARE` setting to enforce security headers on every response.
|
|
217
|
+
|
|
218
|
+
### ASGI (FastAPI + Shiny for Python)
|
|
219
|
+
|
|
220
|
+
`SecureASGIMiddleware` modifies only HTTP scopes (WebSocket messages pass through untouched). Mount it manually or via FastAPI’s `add_middleware`, and pass any `Secure` instance if you need to adjust the defaults.
|
|
221
|
+
|
|
222
|
+
```python
|
|
223
|
+
from fastapi import FastAPI
|
|
224
|
+
from secure import Secure
|
|
225
|
+
from secure.middleware import SecureASGIMiddleware
|
|
226
|
+
|
|
227
|
+
secure_headers = Secure.with_default_headers()
|
|
228
|
+
app = FastAPI()
|
|
229
|
+
app.add_middleware(SecureASGIMiddleware, secure=secure_headers)
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
If you need to tailor the CSP, build a custom `Secure` instance before wiring the middleware:
|
|
233
|
+
|
|
234
|
+
```python
|
|
235
|
+
from secure import ContentSecurityPolicy
|
|
236
|
+
|
|
237
|
+
secure_headers = Secure(
|
|
238
|
+
csp=ContentSecurityPolicy().default_src("'self'").script_src("https://trusted.cdn")
|
|
239
|
+
)
|
|
240
|
+
app = SecureASGIMiddleware(app, secure=secure_headers)
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Shiny for Python apps can be wrapped in the same way:
|
|
244
|
+
|
|
245
|
+
```python
|
|
246
|
+
from shiny import App
|
|
247
|
+
from secure import Secure
|
|
248
|
+
from secure.middleware import SecureASGIMiddleware
|
|
249
|
+
|
|
250
|
+
secure_headers = Secure.with_default_headers()
|
|
251
|
+
app = SecureASGIMiddleware(App(), secure=secure_headers)
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
### Customizing `multi_ok`
|
|
255
|
+
|
|
256
|
+
Pass the `multi_ok` argument to either middleware to append additional occurrences of headers that must appear multiple times (for example, when downstream code already emits a `Content-Security-Policy` line).
|
|
257
|
+
|
|
258
|
+
---
|
|
259
|
+
|
|
260
|
+
## Default secure headers
|
|
261
|
+
|
|
262
|
+
When you call `Secure.with_default_headers()` (or `Secure.from_preset(Preset.BALANCED)`), `secure` configures the recommended defaults that balance security and usability:
|
|
263
|
+
|
|
264
|
+
```http
|
|
265
|
+
Cross-Origin-Opener-Policy: same-origin
|
|
266
|
+
Cross-Origin-Resource-Policy: same-origin
|
|
267
|
+
Content-Security-Policy: default-src 'self'; base-uri 'self'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src 'self'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests
|
|
268
|
+
Strict-Transport-Security: max-age=31536000; includeSubDomains
|
|
269
|
+
Permissions-Policy: geolocation=(), microphone=(), camera=()
|
|
270
|
+
Referrer-Policy: strict-origin-when-cross-origin
|
|
271
|
+
Server:
|
|
272
|
+
X-Content-Type-Options: nosniff
|
|
273
|
+
X-Frame-Options: SAMEORIGIN
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
These defaults limit cross origin data leaks, mitigate clickjacking and MIME sniffing, and enforce a conservative Content Security Policy you can extend later. Balanced omits `Cache-Control` as well as the legacy/compatibility headers (`X-Permitted-Cross-Domain-Policies`, `X-DNS-Prefetch-Control`, `Origin-Agent-Cluster`, `X-Download-Options`, `X-XSS-Protection`), so add them manually if your deployment still depends on them.
|
|
277
|
+
|
|
278
|
+
---
|
|
279
|
+
|
|
280
|
+
## Presets
|
|
281
|
+
|
|
282
|
+
If you prefer to think in terms of profiles instead of individual headers, `secure` provides presets via the `Preset` enum and `Secure.from_preset`.
|
|
283
|
+
|
|
284
|
+
```python
|
|
285
|
+
from secure import Preset, Secure
|
|
286
|
+
|
|
287
|
+
# Recommended defaults for most applications
|
|
288
|
+
balanced_headers = Secure.from_preset(Preset.BALANCED)
|
|
289
|
+
|
|
290
|
+
# Helmet-parity defaults for compatibility-focused setups
|
|
291
|
+
basic_headers = Secure.from_preset(Preset.BASIC)
|
|
292
|
+
|
|
293
|
+
# Hardened defaults for security-focused deployments
|
|
294
|
+
strict_headers = Secure.from_preset(Preset.STRICT)
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
### BALANCED preset
|
|
298
|
+
|
|
299
|
+
The `BALANCED` preset is the new recommended default and matches `Secure.with_default_headers()`. It balances security with compatibility while keeping response headers relatively tight:
|
|
300
|
+
|
|
301
|
+
```http
|
|
302
|
+
Cross-Origin-Opener-Policy: same-origin
|
|
303
|
+
Cross-Origin-Resource-Policy: same-origin
|
|
304
|
+
Content-Security-Policy: default-src 'self'; base-uri 'self'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src 'self'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests
|
|
305
|
+
Strict-Transport-Security: max-age=31536000; includeSubDomains
|
|
306
|
+
Permissions-Policy: geolocation=(), microphone=(), camera=()
|
|
307
|
+
Referrer-Policy: strict-origin-when-cross-origin
|
|
308
|
+
Server:
|
|
309
|
+
X-Content-Type-Options: nosniff
|
|
310
|
+
X-Frame-Options: SAMEORIGIN
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
Balanced omits `Cache-Control` and the legacy/resource headers included by `Preset.BASIC`, but you can still add them manually if your deployment relies on them.
|
|
314
|
+
|
|
315
|
+
### BASIC preset
|
|
316
|
+
|
|
317
|
+
The `BASIC` preset matches Helmet.js defaults and ships with a broader compatibility-focused header set. It is useful when you require the same collection of headers Helmet enables out of the box:
|
|
318
|
+
|
|
319
|
+
```http
|
|
320
|
+
Cross-Origin-Opener-Policy: same-origin
|
|
321
|
+
Cross-Origin-Resource-Policy: same-origin
|
|
322
|
+
Content-Security-Policy: default-src 'self'; base-uri 'self'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src 'self'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests
|
|
323
|
+
Strict-Transport-Security: max-age=31536000; includeSubDomains
|
|
324
|
+
Referrer-Policy: no-referrer
|
|
325
|
+
X-Content-Type-Options: nosniff
|
|
326
|
+
X-Frame-Options: SAMEORIGIN
|
|
327
|
+
X-Permitted-Cross-Domain-Policies: none
|
|
328
|
+
X-DNS-Prefetch-Control: off
|
|
329
|
+
Origin-Agent-Cluster: ?1
|
|
330
|
+
X-Download-Options: noopen
|
|
331
|
+
X-XSS-Protection: 0
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
This preset still avoids `Cache-Control` and `Server` but includes the extra headers that Helmet adds for historical/compatibility reasons.
|
|
335
|
+
|
|
336
|
+
### STRICT preset
|
|
337
|
+
|
|
338
|
+
The `STRICT` preset enables stronger protections and is a better fit for security focused deployments that can tolerate tighter restrictions. It is conceptually similar to:
|
|
339
|
+
|
|
340
|
+
```http
|
|
341
|
+
Cache-Control: no-store, max-age=0
|
|
342
|
+
Cross-Origin-Embedder-Policy: require-corp
|
|
343
|
+
Cross-Origin-Opener-Policy: same-origin
|
|
344
|
+
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
|
|
345
|
+
Strict-Transport-Security: max-age=63072000; includeSubDomains
|
|
346
|
+
Permissions-Policy: geolocation=(), microphone=(), camera=()
|
|
347
|
+
Referrer-Policy: no-referrer
|
|
348
|
+
Server:
|
|
349
|
+
X-Content-Type-Options: nosniff
|
|
350
|
+
X-Frame-Options: DENY
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
Start with `BALANCED` and move to `STRICT` once you have validated that your application works correctly with the stricter Content Security Policy, caching, and frame restrictions. `STRICT` no longer sets HSTS preload by default, so you can opt-in separately when you are ready.
|
|
354
|
+
|
|
355
|
+
---
|
|
356
|
+
|
|
357
|
+
## Policy builders
|
|
358
|
+
|
|
359
|
+
`secure` lets you build rich header values through small, focused builder classes. Two common examples are `ContentSecurityPolicy` and `PermissionsPolicy`.
|
|
360
|
+
|
|
361
|
+
### Content Security Policy
|
|
362
|
+
|
|
363
|
+
```python
|
|
364
|
+
import secure
|
|
365
|
+
|
|
366
|
+
csp = (
|
|
367
|
+
secure.ContentSecurityPolicy()
|
|
368
|
+
.default_src("'self'")
|
|
369
|
+
.script_src("'self'", "cdn.typeerror.com")
|
|
370
|
+
.style_src("'unsafe-inline'")
|
|
371
|
+
.img_src("'self'", "images.typeerror.com")
|
|
372
|
+
.connect_src("'self'", "api.typeerror.com")
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
secure_headers = secure.Secure(csp=csp)
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
Resulting header:
|
|
379
|
+
|
|
380
|
+
```http
|
|
381
|
+
Content-Security-Policy: default-src 'self'; script-src 'self' cdn.typeerror.com; style-src 'unsafe-inline'; img-src 'self' images.typeerror.com; connect-src 'self' api.typeerror.com
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
You can treat the CSP builder as a safe string builder for CSP directives and keep all CSP logic in one place.
|
|
385
|
+
|
|
386
|
+
### Permissions Policy
|
|
387
|
+
|
|
388
|
+
```python
|
|
389
|
+
import secure
|
|
390
|
+
|
|
391
|
+
permissions = (
|
|
392
|
+
secure.PermissionsPolicy()
|
|
393
|
+
.geolocation("'self'")
|
|
394
|
+
.camera("'none'")
|
|
395
|
+
.microphone("'none'")
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
secure_headers = secure.Secure(permissions=permissions)
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
Resulting header:
|
|
402
|
+
|
|
403
|
+
```http
|
|
404
|
+
Permissions-Policy: geolocation=('self'), camera=('none'), microphone=('none')
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
Other headers, such as `StrictTransportSecurity`, `CrossOriginOpenerPolicy`, `CrossOriginEmbedderPolicy`, `ReferrerPolicy`, `Server`, and `XFrameOptions`, also have small builder classes that mirror their directive structure.
|
|
408
|
+
|
|
409
|
+
---
|
|
410
|
+
|
|
411
|
+
## Advanced usage: header pipeline and validation
|
|
412
|
+
|
|
413
|
+
For most applications, it is enough to construct a `Secure` instance and call `set_headers` or `set_headers_async`. If you want stronger guarantees and clearer failure modes, you can run headers through an explicit pipeline.
|
|
414
|
+
|
|
415
|
+
```python
|
|
416
|
+
import logging
|
|
417
|
+
import secure
|
|
418
|
+
|
|
419
|
+
logger = logging.getLogger("secure")
|
|
420
|
+
|
|
421
|
+
secure_headers = (
|
|
422
|
+
secure.Secure.with_default_headers()
|
|
423
|
+
.allowlist_headers(
|
|
424
|
+
allowed=secure.DEFAULT_ALLOWED_HEADERS,
|
|
425
|
+
allow_extra=["X-My-App-Header"],
|
|
426
|
+
on_unexpected="warn", # "raise" (default), "drop", or "warn"
|
|
427
|
+
allow_x_prefixed=False,
|
|
428
|
+
logger=logger,
|
|
429
|
+
)
|
|
430
|
+
.deduplicate_headers(
|
|
431
|
+
action="raise", # "raise" (default), "first", "last", or "concat"
|
|
432
|
+
comma_join_ok=secure.COMMA_JOIN_OK,
|
|
433
|
+
multi_ok=secure.MULTI_OK,
|
|
434
|
+
logger=logger,
|
|
435
|
+
)
|
|
436
|
+
.validate_and_normalize_headers(
|
|
437
|
+
on_invalid="drop", # "drop" (default), "warn", or "raise"
|
|
438
|
+
strict=False,
|
|
439
|
+
allow_obs_text=False,
|
|
440
|
+
logger=logger,
|
|
441
|
+
)
|
|
442
|
+
)
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
Key ideas:
|
|
446
|
+
|
|
447
|
+
- `allowlist_headers` enforces a case insensitive allowlist of header names and decides what to do with unexpected headers.
|
|
448
|
+
- `deduplicate_headers` resolves repeated header names so that you end up with clean `name, value` pairs.
|
|
449
|
+
- `validate_and_normalize_headers` validates header names and values, then freezes them into a single valued, immutable mapping exposed via the `.headers` property.
|
|
450
|
+
- After the pipeline runs through `validate_and_normalize_headers()`, `Secure` uses the normalized `.headers` mapping when `set_headers` or `set_headers_async` apply the headers, ensuring dropped entries never reach the wire and sanitized values replace unsafe input.
|
|
451
|
+
|
|
452
|
+
If you need to emit multi valued headers, such as multiple `Set-Cookie` fields, you can bypass the single valued mapping and work with `header_items()` directly:
|
|
453
|
+
|
|
454
|
+
```python
|
|
455
|
+
for name, value in secure_headers.header_items():
|
|
456
|
+
response.headers.add(name, value)
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
This pipeline gives you a repeatable, testable flow for going from high level policy objects to concrete headers on the wire.
|
|
460
|
+
|
|
461
|
+
---
|
|
462
|
+
|
|
463
|
+
## Framework examples
|
|
464
|
+
|
|
465
|
+
Below are simple examples for a synchronous and an asynchronous framework. See the framework specific guides for more detailed patterns.
|
|
466
|
+
|
|
467
|
+
### Shiny for Python
|
|
468
|
+
|
|
469
|
+
#### Recommended: ASGI middleware wrapper
|
|
470
|
+
|
|
471
|
+
Wraps the Shiny ASGI application and injects headers by intercepting the ASGI `http.response.start` message.
|
|
472
|
+
|
|
473
|
+
```python
|
|
474
|
+
from secure import Secure
|
|
475
|
+
from secure.middleware import SecureASGIMiddleware
|
|
476
|
+
from shiny import App, ui
|
|
477
|
+
|
|
478
|
+
secure_headers = Secure.with_default_headers()
|
|
479
|
+
|
|
480
|
+
app_ui = ui.page_fluid("Hello Shiny!")
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def server(input, output, session):
|
|
484
|
+
pass
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
app = App(app_ui, server)
|
|
488
|
+
|
|
489
|
+
app = SecureASGIMiddleware(app, secure=secure_headers)
|
|
490
|
+
```
|
|
491
|
+
|
|
492
|
+
### FastAPI
|
|
493
|
+
|
|
494
|
+
#### Recommended: `add_middleware` (ASGI)
|
|
495
|
+
|
|
496
|
+
Injects headers by intercepting the ASGI `http.response.start` message.
|
|
497
|
+
|
|
498
|
+
```python
|
|
499
|
+
from fastapi import FastAPI
|
|
500
|
+
from secure import Secure
|
|
501
|
+
from secure.middleware import SecureASGIMiddleware
|
|
502
|
+
|
|
503
|
+
app = FastAPI()
|
|
504
|
+
secure_headers = Secure.with_default_headers()
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
@app.get("/")
|
|
508
|
+
def read_root():
|
|
509
|
+
return {"Hello": "World"}
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
app.add_middleware(SecureASGIMiddleware, secure=secure_headers)
|
|
513
|
+
```
|
|
514
|
+
|
|
515
|
+
#### Alternative: route-level hook (@app.middleware("http"))
|
|
516
|
+
|
|
517
|
+
Applies headers directly to the response object returned by `call_next`.
|
|
518
|
+
|
|
519
|
+
```python
|
|
520
|
+
from fastapi import FastAPI
|
|
521
|
+
from secure import Secure
|
|
522
|
+
|
|
523
|
+
app = FastAPI()
|
|
524
|
+
secure_headers = Secure.with_default_headers()
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
@app.middleware("http")
|
|
528
|
+
async def add_security_headers(request, call_next):
|
|
529
|
+
response = await call_next(request)
|
|
530
|
+
await secure_headers.set_headers_async(response)
|
|
531
|
+
return response
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
@app.get("/")
|
|
535
|
+
def read_root():
|
|
536
|
+
return {"Hello": "World"}
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
### Starlette
|
|
540
|
+
|
|
541
|
+
#### Recommended: `add_middleware` (ASGI)
|
|
542
|
+
|
|
543
|
+
```python
|
|
544
|
+
from starlette.applications import Starlette
|
|
545
|
+
from secure import Secure
|
|
546
|
+
from secure.middleware import SecureASGIMiddleware
|
|
547
|
+
|
|
548
|
+
secure_headers = Secure.with_default_headers()
|
|
549
|
+
app = Starlette()
|
|
550
|
+
app.add_middleware(SecureASGIMiddleware, secure=secure_headers)
|
|
551
|
+
|
|
552
|
+
@app.route("/")
|
|
553
|
+
async def read_root(request):
|
|
554
|
+
return {"hello": "world"}
|
|
555
|
+
```
|
|
556
|
+
|
|
557
|
+
### Flask
|
|
558
|
+
|
|
559
|
+
#### Recommended: `after_request` hook
|
|
560
|
+
|
|
561
|
+
Applies headers directly to the Flask `Response` object.
|
|
562
|
+
|
|
563
|
+
```python
|
|
564
|
+
from flask import Flask, Response
|
|
565
|
+
from secure import Secure
|
|
566
|
+
|
|
567
|
+
app = Flask(__name__)
|
|
568
|
+
secure_headers = Secure.with_default_headers()
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
@app.after_request
|
|
572
|
+
def add_security_headers(response: Response):
|
|
573
|
+
secure_headers.set_headers(response)
|
|
574
|
+
return response
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
@app.route("/")
|
|
578
|
+
def home():
|
|
579
|
+
return "Hello, world"
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
if __name__ == "__main__":
|
|
583
|
+
app.run()
|
|
584
|
+
```
|
|
585
|
+
|
|
586
|
+
#### Alternative: WSGI middleware (`app.wsgi_app`)
|
|
587
|
+
|
|
588
|
+
Wraps the WSGI application and injects headers by wrapping `start_response`.
|
|
589
|
+
Useful for deployment-level / framework-agnostic WSGI setups.
|
|
590
|
+
|
|
591
|
+
```python
|
|
592
|
+
from flask import Flask
|
|
593
|
+
from secure import Secure
|
|
594
|
+
from secure.middleware.wsgi import SecureWSGIMiddleware
|
|
595
|
+
|
|
596
|
+
app = Flask(__name__)
|
|
597
|
+
secure_headers = Secure.with_default_headers()
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
@app.get("/")
|
|
601
|
+
def home():
|
|
602
|
+
return {"Hello": "World"}
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
app.wsgi_app = SecureWSGIMiddleware(app.wsgi_app, secure=secure_headers)
|
|
606
|
+
|
|
607
|
+
if __name__ == "__main__":
|
|
608
|
+
app.run()
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
---
|
|
612
|
+
|
|
613
|
+
## Error handling and logging
|
|
614
|
+
|
|
615
|
+
`secure` is designed to fail fast and clearly when something is misconfigured, with hooks for logging and diagnostics.
|
|
616
|
+
|
|
617
|
+
### Applying headers
|
|
618
|
+
|
|
619
|
+
`set_headers` and `set_headers_async` may raise:
|
|
620
|
+
|
|
621
|
+
- `HeaderSetError` when the underlying response object refuses a header or an unexpected error occurs while setting one.
|
|
622
|
+
- `AttributeError` when the response object implements neither `set_header(name, value)` nor a mutable `headers` mapping.
|
|
623
|
+
- `RuntimeError` from `set_headers` if it detects that the only available setter is asynchronous. In that case, use `set_headers_async` instead.
|
|
624
|
+
|
|
625
|
+
### Validation helpers
|
|
626
|
+
|
|
627
|
+
The pipeline methods may raise `ValueError` when configured to do so:
|
|
628
|
+
|
|
629
|
+
- `allowlist_headers` with `on_unexpected="raise"` when encountering an unexpected header name.
|
|
630
|
+
- `deduplicate_headers` with `action="raise"` when it cannot safely resolve duplicates.
|
|
631
|
+
- `validate_and_normalize_headers` with `on_invalid="raise"` or when it detects invalid or duplicate entries during normalization.
|
|
632
|
+
|
|
633
|
+
Passing a `logger` into these methods is recommended in production so you can see which headers were rejected and why, even when you choose `"drop"` or `"warn"` modes instead of raising.
|
|
634
|
+
|
|
635
|
+
---
|
|
636
|
+
|
|
637
|
+
## Documentation
|
|
638
|
+
|
|
639
|
+
For additional examples, framework specific helpers, and more detailed guidance, see the documentation in the `docs` directory:
|
|
640
|
+
|
|
641
|
+
- Configuration details.
|
|
642
|
+
- Framework integration notes.
|
|
643
|
+
- Reference for header builder classes.
|
|
644
|
+
- Migration notes for the v2.0.0 release and preset/default changes: <https://github.com/TypeError/secure/tree/main/docs/migration.md>
|
|
645
|
+
|
|
646
|
+
Documentation: <https://github.com/TypeError/secure/tree/main/docs>
|
|
647
|
+
|
|
648
|
+
---
|
|
649
|
+
|
|
650
|
+
## Attribution
|
|
651
|
+
|
|
652
|
+
`secure` implements recommendations from widely used security resources:
|
|
653
|
+
|
|
654
|
+
- [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) (licensed under [CC-BY-SA 2.5](https://creativecommons.org/licenses/by-sa/2.5/))
|
|
655
|
+
- [OWASP Secure Headers Project](https://owasp.org/www-project-secure-headers/) (licensed under [CC-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/))
|
|
656
|
+
|
|
657
|
+
Attribution comments are included in the source code where appropriate.
|
|
658
|
+
|
|
659
|
+
---
|
|
660
|
+
|
|
661
|
+
## Resources
|
|
662
|
+
|
|
663
|
+
- [OWASP Secure Headers Project](https://owasp.org/www-project-secure-headers/)
|
|
664
|
+
- [Mozilla Web Security Guidelines](https://infosec.mozilla.org/guidelines/web_security)
|
|
665
|
+
- [MDN Web Docs: HTTP Headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)
|
|
666
|
+
- [web.dev security guidance](https://web.dev)
|
|
667
|
+
- [W3C](https://www.w3.org)
|
|
668
|
+
|
|
669
|
+
---
|
|
670
|
+
|
|
671
|
+
## License
|
|
672
|
+
|
|
673
|
+
This project is licensed under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
|
674
|
+
|
|
675
|
+
---
|
|
676
|
+
|
|
677
|
+
## Contributing
|
|
678
|
+
|
|
679
|
+
Issues and pull requests are welcome. If you would like to discuss an idea, open an issue on GitHub so we can talk about the design before implementation.
|
|
680
|
+
|
|
681
|
+
Repository: <https://github.com/TypeError/secure>
|
|
682
|
+
|
|
683
|
+
---
|
|
684
|
+
|
|
685
|
+
## Changelog
|
|
686
|
+
|
|
687
|
+
See the [CHANGELOG](https://github.com/TypeError/secure/blob/main/CHANGELOG.md) for a detailed list of changes by release.
|
|
688
|
+
|
|
689
|
+
---
|
|
690
|
+
|
|
691
|
+
## Acknowledgements
|
|
692
|
+
|
|
693
|
+
Thank you to everyone who contributes ideas, issues, pull requests, and feedback, as well as the maintainers of MDN and OWASP resources that this project builds on.
|