csrf

CSRF protection middleware (signed-cookie double-submit pattern).

Implements the scheme described in ADR qktwrnmm:

  1. A random per-session token is issued in a SameSite=Strict cookie named CSRF_COOKIE. The cookie value is base64url(token) . base64url(issued_at_be) . base64url(HMAC-SHA256(key, token || issued_at_be)).
  2. Mutating requests (POST/PUT/PATCH/DELETE) must include a _csrf form field whose value matches the cookie’s raw token component; mismatch is rejected with 403 Forbidden.
  3. Safe methods (GET/HEAD/OPTIONS/TRACE) are exempt from verification and still get a fresh cookie stamped if one was missing or invalid.
  4. Templates embed the raw token into mutating forms, and into the page’s csrf-token meta tag for script-driven posts such as the Markdown preview, via the CSRF_TOKEN_PLACEHOLDER placeholder, which this middleware rewrites in text/html response bodies – the same technique the CSP nonce middleware uses.

The signing key is a 32-byte HMAC-SHA256 key sourced from the [serve] csrf_signing_key config value and loaded on server start by crate::web::serve. Key rotation invalidates every outstanding cookie on the next request, which the middleware reissues transparently.

static CSRF_TOKEN_PLACEHOLDER

source

static CSRF_TOKEN_PLACEHOLDER: LazyLock<String> = LazyLock::new(|| crate::web::nonce::random_marker("__CSRF_TOKEN_"));

Placeholder string templates use in place of the raw CSRF token.

This middleware rewrites every occurrence of the literal with the per-request token before the response is returned to the client, so every mutating form picks up a matching value without the handler plumbing a token through the template struct.

It is __CSRF_TOKEN_ and 32 random hex digits and __, new in each process, so user text cannot spell it and receive the token.

fn csrf_token_placeholder

source

pub fn csrf_token_placeholder() -> &'static str

The placeholder that templates write in place of the CSRF token; see CSRF_TOKEN_PLACEHOLDER.

Parameter Type Description
returns &'static str The placeholder text, the same for the life of the process.

const CSRF_MAX_AGE_SECS

source

const CSRF_MAX_AGE_SECS: u64 = CSRF_COOKIE_MAX_AGE_SECS;

Maximum age of a signed cookie accepted on verification.

const CSRF_TOKEN_BYTE_LEN

source

const CSRF_TOKEN_BYTE_LEN: usize = 32;

Length in bytes of the random CSRF token before base64 encoding.

type HmacSha256

source

type HmacSha256 = Hmac<Sha256>;

HMAC with SHA-256, the MAC that signs CSRF cookies.

struct CsrfKey

source

pub struct CsrfKey(Arc<[u8; 32]>);

Shared signing-key state for the CSRF middleware.

Wrapped in an Arc so the axum middleware closure can capture it by clone without allocating per-request copies of the 32-byte key.

Implements Clone, Debug.

CsrfKey::from_bytes

source

pub fn from_bytes(bytes: [u8; 32]) -> Self

Build a key from a 32-byte slice.

Parameter Type Description
bytes [u8; 32] the raw key
returns Self The key, shared behind an Arc so clones do not copy it.

CsrfKey::from_hex

source

pub fn from_hex(hex: &str) -> Result<Self, String>

Parse a hex-encoded 32-byte key.

Parameter Type Description
hex &str 64 hex digits, in any case
returns Result<Self, String> The key, or a message saying that the text is not hex or is not exactly 32 bytes.

CsrfKey::generate

source

pub fn generate() -> Self

Generate a fresh random 32-byte key suitable for HMAC-SHA256.

Parameter Type Description
returns Self The key, from the thread-local random number generator.

CsrfKey::to_hex

source

pub fn to_hex(&self) -> String

Encode the key bytes as lowercase hex (for persistence in config.toml).

Parameter Type Description
returns String 64 lowercase hex digits, which CsrfKey::from_hex reads back.

CsrfKey::as_bytes

source

fn as_bytes(&self) -> &[u8]

Borrow the raw key for HMAC.

Parameter Type Description
returns &[u8] The 32 key bytes.

fn csrf_layer

source

pub async fn csrf_layer(key: CsrfKey, request: Request, next: Next) -> Response

Middleware that enforces CSRF protection on mutating requests and rewrites the CSRF_TOKEN_PLACEHOLDER placeholder in HTML responses.

On every request the middleware reads the existing gest_csrf cookie and verifies its HMAC signature; a missing, malformed, or expired cookie is silently replaced with a fresh token. On mutating requests (POST/PUT/DELETE/PATCH) the middleware additionally reads the submitted _csrf form field and rejects the request with 403 Forbidden if it does not match the cookie’s raw token. Safe methods (GET/HEAD/OPTIONS/TRACE) skip verification but still get a refreshed cookie when needed.

A mutating request’s body is buffered to read the field and then passed on unchanged.

Parameter Type Description
key CsrfKey the key that signs and checks the cookie
request Request the incoming request
next Next the rest of the middleware stack and the handler
returns Response The handler’s response with the token placeholder replaced and, when a new token was issued, a Set-Cookie header; a 403 response when the token check fails; or a 500 response when the body could not be read.

fn base64url_decode

source

fn base64url_decode(input: &str) -> Option<Vec<u8>>

Base64-url decode (no padding) into raw bytes.

Leftover bits of a final partial character are dropped.

Parameter Type Description
input &str URL-safe base64 text with no = padding
returns Option<Vec<u8>> The decoded bytes, or None when the text holds a character outside the alphabet.

fn base64url_encode

source

fn base64url_encode(input: &[u8]) -> String

Base64-url encode (no padding) – the same alphabet as base64url_decode.

Parameter Type Description
input &[u8] the bytes to encode
returns String The encoded text, with no = padding.

fn ct_eq

source

fn ct_eq(a: &str, b: &str) -> bool

Constant-time string compare used for _csrf form-field verification.

Strings of different lengths return early, so only the length is not hidden.

Parameter Type Description
a &str the first string
b &str the second string
returns bool true when the two strings have the same bytes.

fn decode_hex

source

fn decode_hex(s: &str) -> Option<Vec<u8>>

Decode a lowercase or mixed-case hex string into a byte vector.

Parameter Type Description
s &str the hex text
returns Option<Vec<u8>> The bytes, or None when the length is odd or a character is not a hex digit.

fn encode_hex

source

fn encode_hex(bytes: &[u8]) -> String

Encode bytes as lowercase hex.

Parameter Type Description
bytes &[u8] the bytes to encode
returns String Two hex digits for each byte.

fn extract_csrf_field

source

fn extract_csrf_field(body: &[u8]) -> Option<String>

Read the _csrf field from a application/x-www-form-urlencoded body.

Parameter Type Description
body &[u8] the raw request body
returns Option<String> The value of the first _csrf field, or None when there is none.

fn generate_token

source

fn generate_token() -> String

Generate a URL-safe base64url (no padding) random token.

Parameter Type Description
returns String 32 random bytes as base64url text.

fn hex_nibble

source

fn hex_nibble(b: u8) -> Option<u8>

Parse a single hex digit into its nibble value.

Parameter Type Description
b u8 an ASCII character
returns Option<u8> The value 0 to 15, or None when b is not a hex digit.

fn is_mutating

source

fn is_mutating(method: &Method) -> bool

Return true for request methods that should go through CSRF verification.

Parameter Type Description
method &Method the request’s method
returns bool true for POST, PUT, PATCH and DELETE.

fn rewrite_html_body

source

async fn rewrite_html_body(response: Response, token: &str) -> Response

Replace every occurrence of CSRF_TOKEN_PLACEHOLDER in an HTML body.

Only text/html responses are rewritten; binary assets and non-UTF-8 HTML pass through untouched.

Parameter Type Description
response Response the response from the inner handler
token &str the token to write in place of the placeholder
returns Response The response with the placeholder replaced and Content-Length removed, the response unchanged when it is not HTML or holds no placeholder, or a 500 response when the body could not be read.

fn sign_token

source

fn sign_token(token: &str, issued_at: u64, key: &CsrfKey) -> String

HMAC-sign token || issued_at with key, returning the full signed cookie value as base64(token) . base64(issued_at) . base64(mac).

The MAC covers the decoded token bytes followed by issued_at as 8 big-endian bytes. It panics if token is not valid base64url, which generate_token never produces.

Parameter Type Description
token &str the token, as base64url text
issued_at u64 when the token was issued, in seconds since the Unix epoch
key &CsrfKey the signing key
returns String The cookie value, three base64url parts joined by ..

fn unix_secs

source

fn unix_secs() -> u64

Seconds since the Unix epoch, saturating to 0 on clocks set before 1970.

Parameter Type Description
returns u64 The current time in whole seconds.