Module

middleware.security_headers

Security headers middleware — X-Frame-Options, X-Content-Type-Options, Referrer-Policy.

Adds common security headers to HTML responses per HTML Living Standard recommendations (clickjacking, MIME sniffing, referrer leakage).

Headers are applied only to text/html responses. Skipped for JSON, SSE, static files, and other non-HTML content types.

Classes

SecurityHeadersConfig 5
Configuration for security headers. All values are applied as-is. Use standard header values.

Configuration for security headers.

All values are applied as-is. Use standard header values.

Attributes

Name Type Description
x_frame_options str
x_content_type_options str
referrer_policy str
content_security_policy str | None
strict_transport_security str | None
SecurityHeadersMiddleware 2
Add security headers to HTML responses. Per HTML spec recommendations: - X-Frame-Options — prevent…

Add security headers to HTML responses.

Per HTML spec recommendations:

  • X-Frame-Options — prevents clickjacking
  • X-Content-Type-Options — prevents MIME sniffing
  • Referrer-Policy — controls referrer leakage

Usage::

from chirp.middleware import SecurityHeadersMiddleware

app.add_middleware(SecurityHeadersMiddleware())

Or with custom config::

from chirp.middleware.security_headers import (
    SecurityHeadersConfig,
    SecurityHeadersMiddleware,
)

app.add_middleware(SecurityHeadersMiddleware(SecurityHeadersConfig(
    x_frame_options="SAMEORIGIN",
)))

Methods

Internal Methods 2
__init__ 1
def __init__(self, config: SecurityHeadersConfig | None = None) -> None
Parameters
Name Type Description
config Default:None
__call__ 2 AnyResponse
async
async def __call__(self, request: Request, next: Next) -> AnyResponse
Parameters
Name Type Description
request
next
Returns
AnyResponse

Functions

_is_html_response 1 bool
True if response is HTML and should receive security headers.
def _is_html_response(response: AnyResponse) -> bool
Parameters
Name Type Description
response AnyResponse
Returns
bool
_add_headers 2 AnyResponse
Add security headers to a Response or StreamingResponse.
def _add_headers(response: Response | StreamingResponse, config: SecurityHeadersConfig) -> AnyResponse
Parameters
Name Type Description
response Response | StreamingResponse
config SecurityHeadersConfig
Returns
AnyResponse