---------------------------------------------------------------------- This is the API documentation for the secure library. ---------------------------------------------------------------------- ## Classes Main classes provided by the package Secure(*, cache: 'CacheControl | None' = None, coep: 'CrossOriginEmbedderPolicy | None' = None, coop: 'CrossOriginOpenerPolicy | None' = None, corp: 'CrossOriginResourcePolicy | None' = None, csp: 'ContentSecurityPolicy | None' = None, custom: 'list[CustomHeader] | None' = None, hsts: 'StrictTransportSecurity | None' = None, permissions: 'PermissionsPolicy | None' = None, referrer: 'ReferrerPolicy | None' = None, xpcdp: 'XPermittedCrossDomainPolicies | None' = None, xdfc: 'XDnsPrefetchControl | None' = None, server: 'Server | None' = None, xcto: 'XContentTypeOptions | None' = None, xfo: 'XFrameOptions | None' = None) -> 'None' Configure and apply HTTP security headers for web applications. A :class:`Secure` instance is the library's public facade. It encapsulates a set of typed header builders and applies them to response objects from common Python web frameworks (FastAPI, Starlette, Flask, Django, etc.). Typical pipeline: >>> secure = ( ... Secure.with_default_headers().allowlist_headers().deduplicate_headers().validate_and_normalize_headers() ... ) Then, inside your framework integration: >>> secure.set_headers(response) >>> # or in async contexts: >>> await secure.set_headers_async(response) Attributes ---------- headers_list : Ordered list of header objects representing the configured headers. Methods like :meth:`allowlist_headers` and :meth:`deduplicate_headers` operate on this list in place and return ``self`` for chaining. ## Dataclasses Dataclass definitions CacheControl(_directives: 'dict[str, str | None]' = , _extras: 'list[str]' = , _raw_value: 'str | None' = None, _default_value: 'str' = 'no-store, max-age=0') -> None Fluent builder for the `Cache-Control` HTTP header. Default header value: `no-store, max-age=0` Notes: * Directive names are case-insensitive; lowercase is the recommended form. * Directives are comma-separated and resilient to repeated calls for the same helper. * Common directives follow a deterministic, canonical order to keep serialized output stable regardless of call order. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control - https://owasp.org/www-project-secure-headers/#cache-control ContentSecurityPolicy(_directives: 'dict[str, list[str] | None]' = , _raw_value: 'str | None' = None) -> None Fluent builder for the ``Content-Security-Policy`` HTTP response header. Default header value: `default-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; form-action 'self'` Notes: * The structured helpers intentionally avoid full CSP validation; use ``.value(...)`` when you need to emit an exact policy string. * Multiple policies can be sent by instantiating another ``ContentSecurityPolicy`` and adding it to ``Secure.headers_list``. * MDN describes fallback behavior between directives (e.g., ``default-src`` acts as a fallback for fetch directives). Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy - https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP - https://owasp.org/www-project-secure-headers/#content-security-policy CrossOriginEmbedderPolicy(_directive: 'str' = 'require-corp') -> None Builder for the ``Cross-Origin-Embedder-Policy`` (COEP) HTTP response header. COEP controls how the document embeds and loads cross-origin resources, with directives that range from no isolation (``unsafe-none``) to strict isolation (``require-corp``) or credentialless loading. Default header value: ``require-corp`` Notes: * Per MDN, omitting the header is equivalent to ``unsafe-none``. * Each helper closes over canonical MDN directives while ``value(...)`` acts as an escape hatch for custom strings. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cross-Origin-Embedder-Policy - https://owasp.org/www-project-secure-headers/#cross-origin-embedder-policy CrossOriginOpenerPolicy(_directive: 'str' = 'same-origin') -> None Builder for the ``Cross-Origin-Opener-Policy`` (COOP) HTTP response header. COOP lets a page opt into a dedicated browsing context group or share like with its opener, helping protect against XS-Leaks. Default header value: ``same-origin`` Notes: * If this header is absent, browsers behave as if ``unsafe-none`` were set. * Use the fluent helpers to pick MDN-defined directives; ``value(...)`` is provided as an escape hatch. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cross-Origin-Opener-Policy - https://owasp.org/www-project-secure-headers/#cross-origin-opener-policy CrossOriginResourcePolicy(_value: 'str' = ) -> None Builder for the ``Cross-Origin-Resource-Policy`` (CORP) HTTP response header. CORP expresses the resource owner's intent for which origins may load this resource, with MDN documenting ``same-site``, ``same-origin``, and ``cross-origin`` directives. Default header value: `same-origin` Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cross-Origin-Resource-Policy - https://resourcepolicy.fyi/ - https://owasp.org/www-project-secure-headers/#cross-origin-resource-policy CustomHeader(header: 'str', value: 'str') -> 'None' Wrapper for an arbitrary HTTP header. Default header value: provided by the caller at initialization. Notes: * Header names and values are normalized via ``normalize_header_value`` to prevent header injection. * This class keeps parity with other builders via ``value``, ``set``, and escape-hatch helpers so it plugs into the fluent API. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers PermissionsPolicy(_directives: 'dict[str, str]' = , _raw_value: 'str | None' = None) -> None Builder for the `Permissions-Policy` HTTP header. Default header value: `geolocation=(), microphone=(), camera=()` Notes: * Directive helpers cover MDN features; use ``value(...)`` when you already have a ready-made header string. * Allowlists follow MDN syntax: ``()``, ``*``, ``self``, ``src``, or double-quoted origins; ``()``/``none`` cannot be mixed with other tokens, and wildcard must stand alone. * Call helpers repeatedly without worrying about duplicates: each directive is unique and re-assigning it keeps the order of the most recent write. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Permissions-Policy - https://owasp.org/www-project-secure-headers/#permissions-policy - https://www.w3.org/TR/permissions-policy-1/ ReferrerPolicy(_policies: 'list[str]' = ) -> None Builder for the ``Referrer-Policy`` HTTP response header. Default header value: ``strict-origin-when-cross-origin`` Notes: * ``Referrer-Policy`` controls how much of the ``Referer`` header is sent. * The comma-separated fallback list should place the primary policy last. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Referrer-Policy - https://owasp.org/www-project-secure-headers/#referrer-policy Server(_value: 'str' = '') -> None Builder for the ``Server`` HTTP response header. Default header value: ``""`` Notes: * The default is intentionally empty to avoid leaking server details. * Callers can override this value for compatibility with legacy tooling. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server - https://owasp.org/www-project-secure-headers/ StrictTransportSecurity(_max_age: 'int | None' = None, _include_subdomains: 'bool' = False, _preload: 'bool' = False, _raw_value: 'str | None' = None) -> None Builder for the ``Strict-Transport-Security`` (HSTS) HTTP response header. Default header value: ``max-age=31536000`` Notes: * Only send this header over HTTPS; browsers ignore it otherwise. * ``preload`` requires ``includeSubDomains`` and at least one year ``max-age``. * ``max-age`` is required by the HSTS specification. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Strict-Transport-Security - https://hstspreload.org/ - https://owasp.org/www-project-secure-headers/ XContentTypeOptions(_value: 'str' = 'nosniff') -> None Builder for the `X-Content-Type-Options` HTTP header. Default header value: `nosniff` Notes: * The only standardized directive is `nosniff`; other values are allowed but discouraged. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options - https://owasp.org/www-project-secure-headers/#x-content-type-options XDnsPrefetchControl(_value: 'str' = ) -> None Builder for the non-standard `X-DNS-Prefetch-Control` HTTP header. Default header value: `off` Notes: * Browsers may ignore this header as it is non-standard, but it documents the desired behavior for DNS prefetching. * Normalization keeps ``on``/``off`` lowercase while permitting other values unchanged. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-DNS-Prefetch-Control - https://owasp.org/www-project-secure-headers/#x-dns-prefetch-control XFrameOptions(_value: 'str' = 'SAMEORIGIN') -> None Builder for the `X-Frame-Options` HTTP response header. Default header value: `SAMEORIGIN` Notes: * Consider CSP `frame-ancestors` for richer framing controls. * This header is only processed when sent as an HTTP response header. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Frame-Options - https://owasp.org/www-project-secure-headers/#x-frame-options XPermittedCrossDomainPolicies(_value: 'str' = ) -> None Builder for the `X-Permitted-Cross-Domain-Policies` HTTP response header. Default header value: `none` Notes: * This header governs which cross-domain policy files legacy clients (Flash, Silverlight, etc.) may load. * Use helper methods for MDN-defined directives; ``value`` is an escape hatch. Resources: - https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Permitted-Cross-Domain-Policies - https://owasp.org/www-project-secure-headers/#x-permitted-cross-domain-policies ## StrictTransportSecurity Methods Methods for the StrictTransportSecurity class StrictTransportSecurity.header_value Return the serialized ``Strict-Transport-Security`` header value. clear(self) -> 'StrictTransportSecurity' Clear configured directives and reset back to the library default. value(self, value: 'str') -> 'StrictTransportSecurity' Set a raw header value (escape hatch), replacing any configured directives. max_age(self, seconds: 'int') -> 'StrictTransportSecurity' Set ``max-age``: how long (in seconds) the browser should remember to use HTTPS only. include_subdomains(self) -> 'StrictTransportSecurity' Add ``includeSubDomains``: apply the HSTS policy to all subdomains as well. preload(self) -> 'StrictTransportSecurity' Add ``preload``: enable HSTS preload list requirements (requires includeSubDomains and 1y+ max-age). ## Secure Methods Methods for the Secure class with_default_headers() -> 'Secure' Create a :class:`Secure` instance with a sensible default set of headers. This configuration is suitable for many modern applications and can be customized with methods like :meth:`allowlist_headers` or by adding additional header builder objects. Returns ------- Secure Instance preconfigured with :data:`Preset.BALANCED`, the recommended default profile. from_preset(preset: 'Preset') -> 'Secure' Create a :class:`Secure` instance using a predefined security preset. Parameters ---------- preset : The security preset to use, for example :data:`Preset.BALANCED` for the recommended default profile, :data:`Preset.BASIC` for compatibility- oriented behavior, or :data:`Preset.STRICT` for a hardened configuration with stronger guarantees. Returns ------- Secure Instance configured with the selected preset. Raises ------ ValueError If an unknown preset is provided. __str__(self) -> 'str' Return a human-readable listing of headers and their effective values. __repr__(self) -> 'str' Return a detailed representation of the :class:`Secure` instance. validate_and_normalize_headers(self, *, on_invalid: 'OnInvalidPolicy' = 'drop', strict: 'bool' = False, allow_obs_text: 'bool' = False, logger: 'logging.Logger | None' = None) -> 'Secure' Validate and normalize the current header items and cache an immutable mapping. This operates on :meth:`header_items` (not ``headers_list`` directly) to preserve ordering, multi-valued behavior, and any prior deduplication. The resulting mapping is stored as a normalized snapshot that is returned by :attr:`headers` until the configured headers change. Parameters ---------- on_invalid : Policy for invalid headers: - ``"drop"``: silently drop invalid entries (default). - ``"warn"``: log a warning and drop invalid entries. - ``"raise"``: raise :class:`ValueError` on invalid entries. strict : If true, treat CR/LF and disallowed characters as hard errors. Other invalid cases (name/value) are governed by ``on_invalid``. allow_obs_text : If true, allow "obs-text" (bytes 0x80-0xFF) as per older RFCs. logger : Optional :class:`logging.Logger` used when ``on_invalid="warn"`` or when dropping headers with ``on_invalid="drop"`` but logging is desired. Returns ------- Secure The same instance, for call chaining. Raises ------ ValueError If a header name is invalid (when ``on_invalid="raise"``), if duplicates are found when building the single-valued mapping, or if ``strict=True`` and CR/LF or disallowed characters are present. deduplicate_headers(self, *, action: 'DeduplicateAction' = 'raise', comma_join_ok: 'frozenset[str]' = frozenset({'cache-control'}), multi_ok: 'frozenset[str]' = frozenset({'content-security-policy'}), logger: 'logging.Logger | None' = None) -> 'Secure' Deduplicate headers in :attr:`headers_list` according to the chosen policy. Parameters ---------- action : Policy when encountering disallowed duplicates: - ``"raise"``: raise :class:`ValueError` (default). - ``"first"``: keep the first instance and drop others. - ``"last"``: keep the last instance and drop others. - ``"concat"``: join values with commas when safe. comma_join_ok : Names (lowercased) for which RFC 7230-style comma joining is safe. multi_ok : Names (lowercased) that are allowed to appear multiple times (for example Content-Security-Policy). logger : Optional :class:`logging.Logger` used for warning messages when dropping duplicates in non-``"raise"`` modes. Returns ------- Secure The same instance, for call chaining. Raises ------ ValueError If duplicates are found for headers that are not in ``multi_ok`` and the action is ``"raise"`` or ``"concat"`` for unsafe headers. allowlist_headers(self, *, allowed: 'Iterable[str]' = frozenset({'x-xss-protection', 'cross-origin-resource-policy', 'content-security-policy-report-only', 'cross-origin-opener-policy', 'strict-transport-security', 'referrer-policy', 'cache-control', 'x-download-options', 'x-content-type-options', 'content-security-policy', 'cross-origin-embedder-policy', 'server', 'x-frame-options', 'permissions-policy', 'x-permitted-cross-domain-policies', 'x-dns-prefetch-control', 'origin-agent-cluster'}), allow_extra: 'Iterable[str] | None' = None, on_unexpected: 'OnUnexpectedPolicy' = 'raise', allow_x_prefixed: 'bool' = False, logger: 'logging.Logger | None' = None) -> 'Secure' Enforce a case-insensitive allowlist for header names in :attr:`headers_list`. Parameters ---------- allowed : Base allowlist of header names (case-insensitive). allow_extra : Additional names to allow, for example app-specific headers. on_unexpected : Policy for headers not in the allowlist: - ``"raise"``: error on any name not in the allowlist (default). - ``"drop"``: remove unexpected headers (logs if logger is set). - ``"warn"``: keep unexpected headers but log a warning. allow_x_prefixed : If true, allows any header starting with ``"x-"``. logger : Optional :class:`logging.Logger` used for warnings in ``"drop"`` and ``"warn"`` modes. Returns ------- Secure The same instance, for call chaining. Raises ------ ValueError If ``on_unexpected="raise"`` and any header is not in the allowlist. header_items(self) -> 'HeaderItems' Serialize the current headers into ``(name, value)`` pairs. It does not enforce uniqueness. Use :meth:`deduplicate_headers` or :meth:`validate_and_normalize_headers` when you need a single-valued mapping. Returns ------- tuple[tuple[str, str], ...] Immutable sequence of ``(name, value)`` pairs. set_headers(self, response: 'ResponseProtocol') -> 'None' Apply configured headers synchronously to ``response``. This method is strictly sync-only. It is suitable for synchronous frameworks or sync response objects in async frameworks. Supported patterns ------------------ * ``response.set_header(name, value)`` (synchronous). * ``response.headers.set(name, value)`` (Werkzeug-style headers container). * ``response.headers[name] = value`` (mapping interface). Parameters ---------- response : Response object implementing either :class:`SetHeaderProtocol` or :class:`HeadersProtocol`. Raises ------ RuntimeError If an async setter is detected (for example an async method is used in a sync context). AttributeError If the response lacks both ``.set_header`` and ``.headers``, or if ``.headers`` does not support setting values. HeaderSetError If setting an individual header fails. set_headers_async(self, response: 'ResponseProtocol') -> 'None' Apply configured headers asynchronously to ``response``. This method is designed for async frameworks such as FastAPI and Starlette. It transparently supports sync or async setters. Supported patterns ------------------ * ``await response.set_header(name, value)`` for async setters. * ``response.set_header(name, value)`` for sync setters returning ``None``. * ``await response.headers.set(name, value)`` for async headers containers. * ``response.headers.set(name, value)`` for sync headers containers. * ``await response.headers.__setitem__(name, value)`` for async mappings. * ``response.headers[name] = value`` for sync mappings. Parameters ---------- response : Response object implementing either :class:`SetHeaderProtocol` or :class:`HeadersProtocol`. Raises ------ AttributeError If the response lacks both ``.set_header`` and ``.headers``, or if ``.headers`` does not support setting values. HeaderSetError If setting an individual header fails. ## CacheControl Methods Methods for the CacheControl class value(self, value: 'str') -> 'CacheControl' Set an explicit header value, replacing all configured directives. This is an escape hatch: it bypasses directive helpers. Safety: - Rejects CR/LF to prevent header-splitting. - Strips leading/trailing whitespace and rejects empty results. set(self, value: 'str') -> 'CacheControl' Alias for :meth:`value`. clear(self) -> 'CacheControl' Clear all directives and explicit value, returning to the default state. custom(self, directive: 'str') -> 'CacheControl' Add a custom directive token (non-standard / extra). This is intended for directives not covered by helper methods. Examples: .custom("foo") .custom("foo=bar") Safety: - Rejects commas (would break tokenization). - Rejects CR/LF (header-splitting). - Validates the directive *name* as an RFC token. immutable(self) -> 'CacheControl' Indicate the response will not be updated while it is fresh. max_age(self, seconds: 'int') -> 'CacheControl' Set `max-age=N` (freshness lifetime in responses, acceptable age in requests). max_stale(self, seconds: 'int | None' = None) -> 'CacheControl' Allow reusing a stale response within `seconds`, or any stale age when omitted (request). min_fresh(self, seconds: 'int') -> 'CacheControl' Require a stored response to remain fresh for at least `seconds` (request). must_revalidate(self) -> 'CacheControl' Require revalidation with the origin server once a stored response becomes stale (response). must_understand(self) -> 'CacheControl' Store the response only if the cache understands the caching requirements for its status code. no_cache(self) -> 'CacheControl' Allow storing but require validation with the origin server before each reuse. no_store(self) -> 'CacheControl' Instruct caches (private or shared) not to store this response. no_transform(self) -> 'CacheControl' Instruct intermediaries not to transform the request or response content. only_if_cached(self) -> 'CacheControl' Request an already-cached response; if none is available, a 504 may be returned (request). private(self) -> 'CacheControl' Indicate the response may be stored only in a private cache (e.g., a browser cache). proxy_revalidate(self) -> 'CacheControl' Like `must-revalidate`, but for shared caches only (response). public(self) -> 'CacheControl' Indicate the response may be stored in a shared cache (response). s_maxage(self, seconds: 'int') -> 'CacheControl' Set `s-maxage=N` (freshness lifetime in shared caches only). s_max_age(self, seconds: 'int') -> 'CacheControl' Alias for :meth:`s_maxage`. stale_if_error(self, seconds: 'int') -> 'CacheControl' Allow reusing a stale response for `seconds` when a 500/502/503/504 error is encountered. stale_while_revalidate(self, seconds: 'int') -> 'CacheControl' Allow reusing a stale response for `seconds` while revalidation happens in the background. ## ContentSecurityPolicy Methods Methods for the ContentSecurityPolicy class value(self, value: 'str') -> 'ContentSecurityPolicy' Set an exact header value (escape hatch). set(self, value: 'str') -> 'ContentSecurityPolicy' Alias for :meth:`value`. clear(self) -> 'ContentSecurityPolicy' Clear all configured directives and any raw override. After calling this, the header value falls back to the library default. report_only(self) -> 'ContentSecurityPolicy' Use the report-only header name (`Content-Security-Policy-Report-Only`). enforce(self) -> 'ContentSecurityPolicy' Use the enforcing header name (`Content-Security-Policy`). custom(self, directive: 'str', *values: 'str') -> 'ContentSecurityPolicy' Alias for :meth:`custom_directive`. custom_directive(self, directive: 'str', *values: 'str') -> 'ContentSecurityPolicy' Add (or update) a directive. - Directives are de-duplicated: each directive name appears at most once. - Values are treated as tokens: duplicates are removed (preserving order). - Passing no values sets a valueless directive (overwriting prior values). Args: directive: Directive name (for example, ``default-src``). *values: Directive tokens (for example, ``'self'``, ``https:``, ``example.com``). Returns: The same instance, for method chaining. base_uri(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources for the document `` element. block_all_mixed_content(self) -> 'ContentSecurityPolicy' Prevent loading any assets using HTTP when the page is loaded using HTTPS. Deprecated in MDN's reference; prefer modern HTTPS-only deployments and consider `upgrade-insecure-requests` instead when appropriate. child_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources for web workers and nested browsing contexts. connect_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources for script interfaces (for example, XHR, Fetch, WebSocket). default_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set the fallback policy for all fetch directives. fenced_frame_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources for nested browsing contexts loaded into ``. font_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources for fonts. form_action(self, *sources: 'str') -> 'ContentSecurityPolicy' Restrict the URLs which can be used as the target of form submissions. frame_ancestors(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid parent sources that may embed the page in a frame. frame_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources for nested browsing contexts loaded into frames/iframes. img_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources for images and favicons. manifest_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources for application manifests. media_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources for media (audio, video, track). object_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources for plugin-like objects (for example, ``, ``). prefetch_src(self, *sources: 'str') -> 'ContentSecurityPolicy' Set valid sources to be prefetched or prerendered. Deprecated and non-standard in MDN's reference; use only if you have a specific compatibility need. report_to(self, *values: 'str') -> 'ContentSecurityPolicy' Configure reporting endpoints via `report-to` groups. report_uri(self, *uris: 'str') -> 'ContentSecurityPolicy' Configure the legacy reporting endpoint(s) via `report-uri`. Deprecated in MDN's reference. If you use `report-to`, note that browsers that support `report-to` ignore `report-uri`. require_trusted_types_for(self, *values: 'str') -> 'ContentSecurityPolicy' Enforce Trusted Types at specific DOM injection sinks. sandbox(self, *values: 'str') -> 'ContentSecurityPolicy' Enable a sandbox for the requested resource (similar to `