Skip to main content

CSRF Protection Reference

This reference covers the technical contracts and schemas used by the CSRF protection layer in Framework M.

Protocols​

CSRFProtocol​

The core interface for CSRF validation.

class CSRFProtocol(Protocol):
async def validate_request(self, request_info: WebRequestInfo) -> bool:
"""
Validates an incoming request.
Returns True if safe, False if it should be rejected.
"""

Data Structures​

WebRequestInfo​

A library-agnostic Pydantic model that represents the security-relevant parts of an HTTP request.

FieldTypeDescription
methodstrThe HTTP method (e.g., "POST", "GET").
pathstrThe URL path component.
is_session_authboolTrue if the request is authenticated via a signed session cookie.
origin`strNone`
referer`strNone`

Default Implementation​

DefaultCSRFAdapter​

The standard adapter provided in framework-m-standard.

Validation Logic​

  1. Skip Safe Methods: Returns True for GET, HEAD, OPTIONS, TRACE.
  2. Skip Non-Session Auth: Returns True if is_session_auth is False. (Assumes header-based auth is immune).
  3. Validate Origin: If Origin is present, it must match one of the ALLOWED_ORIGINS.
  4. Validate Referer: If Origin is missing but Referer is present, its netloc must match ALLOWED_ORIGINS.
  5. Strict Mode: If both headers are missing for a state-changing session request, it returns False.

Entry Points​

The framework uses the framework_m.adapters.csrf entry point group to discover the active adapter.

  • Group: framework_m.adapters.csrf
  • Expected Return: A class implementing CSRFProtocol that accepts allowed_origins: Sequence[str] in its constructor.