/// Cross-site request forgery tokens, bound to a session and fresh on /// every response (toboggan's `Auth/Csrf`). A session's key is derived /// from its secret, so no store holds it. A token is /// `base64url(nonce) "." base64url(HMAC-SHA256(key, nonce))`, with 16 /// fresh random bytes as the nonce. Every token minted for a session is /// valid until the session ends: tokens are stateless, not single-use. /// /// The app sends a token with each response (a header, a hidden form /// field) and checks the one that comes back on every request that /// changes something. import signed import std/base64 import std/bytes import std/crypto import std/random.{type random} import std/string /// The CSRF key of the session whose secret is `secret`: an HMAC under a /// fixed label, equal for equal secrets only, with no way back to the /// secret. Whoever holds the secret holds the session already; nobody else /// can compute the key. pub fn key :: secret: Bytes -> Bytes { crypto.hmac_sha256 secret (bytes.from_string "web/csrf-key/v1") } /// A fresh token under `key`. pub fn token :: key: Bytes -> String / { minted key (random.bytes 16) } /// Whether `token` was minted under `key`, compared in constant time. /// A token under another key, altered or malformed is not. pub fn valid :: key: Bytes token: String -> Bool { match string.split token "." { [nonce, _] -> match decoded nonce { Ok(raw) if bytes.length raw > 0 -> signed.same_bytes (bytes.from_string token) (bytes.from_string (minted key raw)) , _ -> False } , _ -> False } } fn minted :: key: Bytes nonce: Bytes -> String { "{encoded nonce}.{encoded (crypto.hmac_sha256 key nonce)}" } /// base64url without padding (RFC 4648 ยง5). fn encoded :: data: Bytes -> String { base64.encode data |> replaced _ "+" "-" |> replaced _ "/" "_" |> replaced _ "=" "" } fn decoded :: text: String -> Result { let padding = string.repeat "=" ((4 - string.length text % 4) % 4) base64.decode (replaced (replaced text "-" "+") "_" "/" <> padding) } fn replaced :: text: String from: String to: String -> String { string.join (string.split text from) to }