nonce

Per-request CSP nonce middleware.

Generates a cryptographically random nonce for every request, stores it in the request extensions so downstream middleware (notably crate::web::security_headers) can read it, and replaces any occurrences of NONCE_PLACEHOLDER in the rendered HTML body with the real value.

Templates that contain inline <script> or <style> tags write the placeholder with {{ crate::web::nonce::nonce_placeholder() }}; this middleware rewrites the placeholder on the way out so the nonce in the Content-Security-Policy header matches the one on the tag. The placeholder is random in each process, so user text in the page cannot spell it.

static NONCE_PLACEHOLDER

source

static NONCE_PLACEHOLDER: LazyLock<String> = LazyLock::new(|| random_marker("__CSP_NONCE_"));

Placeholder that templates write in place of the real nonce: __CSP_NONCE_ and 32 random hex digits and __.

The middleware rewrites every occurrence in HTML response bodies with the per-request nonce. The random part is new in each process and never reaches a client, so user text in a title, a note or an edit form cannot spell the placeholder and receive the nonce.

fn nonce_placeholder

source

pub fn nonce_placeholder() -> &'static str

The placeholder that templates write in place of the real nonce; see NONCE_PLACEHOLDER.

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

fn random_marker

source

pub(crate) fn random_marker(prefix: &str) -> String

Build a rewrite placeholder: prefix, then 16 random bytes as hex, then __.

Parameter Type Description
prefix &str the readable start of the placeholder, such as __CSP_NONCE_
returns String The placeholder text.

const NONCE_BYTE_LEN

source

const NONCE_BYTE_LEN: usize = 16;

Length in bytes of the random nonce before base64 encoding.

16 bytes (128 bits) is the minimum recommended by the W3C CSP spec for nonce-based strict-CSP deployments.

struct CspNonce

source

pub struct CspNonce(String);

Per-request CSP nonce stored in the request extensions.

Wrapped in a newtype so it can be extracted from extensions by type and so the inner string is not accidentally confused with other request-scoped strings.

Implements Clone, Debug.

CspNonce::generate

source

pub fn generate() -> Self

Generate a fresh random nonce suitable for a single HTTP response.

Parameter Type Description
returns Self A nonce of 16 random bytes in unpadded URL-safe base64, 22 characters long.

CspNonce::as_str

source

pub fn as_str(&self) -> &str

The nonce value as rendered into the CSP header and HTML tags.

Parameter Type Description
returns &str The base64 text of the nonce.

fn attach_nonce

source

pub async fn attach_nonce(request: Request, next: Next) -> Response

Middleware that attaches a per-request nonce and rewrites the response body.

The nonce is generated before the inner handler runs so downstream middleware (e.g. security_headers) can read it from the request extensions. After the handler produces its response, the body is buffered and every occurrence of NONCE_PLACEHOLDER is replaced with the real nonce value. Only text/html responses are rewritten; all other content types pass through untouched so binary assets (images, JSON, etc.) are not corrupted.

Parameter Type Description
request Request the incoming request; the nonce is added to its extensions
next Next the rest of the middleware stack and the handler
returns Response The handler’s response, with the placeholder replaced in an HTML body.

fn rewrite_html_body

source

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

Buffer the response body and replace NONCE_PLACEHOLDER with nonce.

Non-HTML responses and non-UTF-8 HTML bodies pass through unchanged. Any error buffering the body is logged and surfaced as a plain 500 response so a malformed downstream body cannot leak past this layer.

Parameter Type Description
response Response the response from the inner handler
nonce &str the per-request nonce 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 UTF-8 HTML, or a 500 response when the body could not be read.

fn base64_encode

source

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

Base64-encode bytes without padding using the URL-safe alphabet.

Small standalone helper to avoid pulling in a full base64 crate for a single nonce-encoding use case. The output is safe to embed in both the CSP header and HTML attribute values.

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