-
Notifications
You must be signed in to change notification settings - Fork 30
secure v2.0.0rc1: presets redesign, ASGI/WSGI middleware, and header updates #40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Use SPDX license metadata, move license-files to [project], remove deprecated fields, and bump version to 2.0.0.
Fixes issue #38. Return a read-only Mapping for `headers` by wrapping the built dict in `types.MappingProxyType` and updating the signature to `Mapping[str, str]`.
Fixes issue #37. - set_headers: if response.set_header is async and no event loop is running, run to completion via asyncio.run(); if a loop is running, raise a clear, prescriptive RuntimeError instructing to use `await set_headers_async(response)` - set_headers: handle “sync-looking but returns awaitable” setters the same way - set_headers: use headers.update(...) fast-path when available - set_headers_async: defensively await results from sync-looking setters; support mapping-style headers with callable update() and async __setitem__ fallback
Fixes issue #36 - Iterate header_items() in sync/async setters to keep CSP & Set-Cookie. - Avoid bulk dict.update() and lossy mappings. - headers() remains strict/immutable to prevent duplicate loss.
Fixes issue #34 - Wrap per-item header operations in try/except; re-raise as HeaderSetError (TypeError, ValueError, AttributeError) - Support async setters safely (await/asyncio.run); guide callers to async API when an event loop is running - Move try/except out of loops to satisfy Ruff PERF203; add Awaitable annotation to address ANN001
Fixes issue #33 - Call self._validate_and_normalize_header(...) before every header write - Reject CR/LF and disallowed control chars; enforce RFC7230 token names - Works in both set_header(...) and mapping (__setitem__) branches - Respects optional _strict/_allow_obs_text/_on_invalid if present - No breaking changes to public API; fix ships in v2.0
Updates issue #33, still resolved
Update issue #36 (Lack of Duplicate Header Detection in Secure Clas) - Move duplicate handling into chainable deduplicate_headers - Respect MULTI_OK and COMMA_JOIN_OK; preserve stable order - header_items now only serializes (name, value) pairs - Drop in-function dedupe and error logic - Invalidate cached headers mapping after mutation
New allowlist_headers(on_unexpected=raise|drop|warn, allow_extra, allow_x_prefixed) enforces a case-insensitive header allowlist (fixes #35).
…uest directive helpers
…improved security
…ptions for clarity
…ctive normalization
…ation for clarity
…directives and improved documentation
…ences and clarifying examples
…s to documentation
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR prepares the v2.0.0rc1 release of
secure, delivering a redesigned preset model, first-class ASGI/WSGI middleware, updated header directives, and a safer, more explicit header application pipeline.Summary
Preset.BALANCEDas the new recommended default.Secure.with_default_headers()to map toPreset.BALANCED.Breaking changes
Preset.BALANCED(new default).Preset.BASICtargets Helmet.js parity.Preset.STRICTno longer enables HSTS preload by default.Secure.headersis now strict about duplicate header names (case-insensitive).header_items()for multi-valued output or resolve duplicates via the pipeline helpers.Added
SecureASGIMiddlewareandSecureWSGIMiddleware(re-exported viasecure.middleware).allowlist_headers(...)deduplicate_headers(...)validate_and_normalize_headers(...)header_items().MULTI_OK,COMMA_JOIN_OK,DEFAULT_ALLOWED_HEADERS, and related policy enums.Documentation
BALANCED,BASIC,STRICT).Testing & tooling
pyproject.tomland Ruff configuration.Fixes
@cached_propertyUsage #38 – Potential thread-safety concern with@cached_propertyusageset_headers#37 – Potential asynchronous context confusion inset_headersSecureClass #36 – Lack of duplicate header detection inSecureclassSecureClass #35 – Lack of allowlisting for header names inSecureclassset_headersandset_headers_async#34 – Missing error handling inset_headersandset_headers_asyncAttributeError: 'Secure' object has no attribute 'hsts'PermissionsPolicymissing some permissionsThis is a release candidate. Feedback on preset defaults, middleware ergonomics, and the validation pipeline is especially welcome before the final v2.0.0 release.