actix_csrf/
token_rng.rs

1//! Token generators and related crypto functions.
2
3use base64::engine::general_purpose::URL_SAFE_NO_PAD;
4use base64::Engine;
5use rand::{CryptoRng, Error, Fill, RngCore};
6
7/// Used to generate CSRF tokens.
8///
9/// This trait is used to generate a token that can be used as a CSRF token. It
10/// is implemented for all CSRNG (Cryptographically Secure RNG) types. This
11/// should not be implemented directly; instead, implement [`CryptoRng`] and
12/// [`RngCore`] instead.
13///
14/// Implementors of this trait should generate a token that's difficult to
15/// guess and is safe to store as a cookie. For blanket implementations, this
16/// is 32 bytes of random data, encoded as base64 without padding.
17pub trait TokenRng: CryptoRng {
18    /// Generates a CSRF token.
19    ///
20    /// # Errors
21    ///
22    /// Returns an error if the underlying RNG fails to generate a token.
23    fn generate_token(&mut self) -> Result<String, Error>;
24}
25
26impl<Rng: CryptoRng + RngCore> TokenRng for Rng {
27    fn generate_token(&mut self) -> Result<String, Error> {
28        let mut buf = [0; 32];
29        buf.try_fill(self)?;
30        Ok(URL_SAFE_NO_PAD.encode(buf))
31    }
32}