1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use std::{ops::Deref, sync::Arc};

use libcsrf::{AesGcmCsrfProtection, CsrfProtection, UnencryptedCsrfCookie};

use crate::{FromRequest, Request, RequestBody, Result};

/// A CSRF Token for the next request.
///
/// See also [`Csrf`](crate::middleware::Csrf)
#[cfg_attr(docsrs, doc(cfg(feature = "csrf")))]
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct CsrfToken(pub String);

impl Deref for CsrfToken {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[async_trait::async_trait]
impl<'a> FromRequest<'a> for &'a CsrfToken {
    async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self> {
        Ok(req
            .extensions()
            .get::<CsrfToken>()
            .expect("To use the `CsrfToken` extractor, the `Csrf` middleware is required."))
    }
}

/// A verifier for CSRF Token.
///
/// See also [`Csrf`](crate::middleware::Csrf)
#[cfg_attr(docsrs, doc(cfg(feature = "csrf")))]
pub struct CsrfVerifier {
    cookie: Option<UnencryptedCsrfCookie>,
    protect: Arc<AesGcmCsrfProtection>,
}

impl CsrfVerifier {
    pub(crate) fn new(
        cookie: Option<UnencryptedCsrfCookie>,
        protect: Arc<AesGcmCsrfProtection>,
    ) -> Self {
        Self { cookie, protect }
    }
}

#[async_trait::async_trait]
impl<'a> FromRequest<'a> for &'a CsrfVerifier {
    async fn from_request(req: &'a Request, _body: &mut RequestBody) -> Result<Self> {
        Ok(req
            .extensions()
            .get::<CsrfVerifier>()
            .expect("To use the `CsrfVerifier` extractor, the `Csrf` middleware is required."))
    }
}

impl CsrfVerifier {
    /// Return `true` if the token is valid.
    pub fn is_valid(&self, token: &str) -> bool {
        let cookie = match &self.cookie {
            Some(cookie) => cookie,
            None => return false,
        };

        let token_data = match base64::decode(token) {
            Ok(data) => data,
            Err(_) => return false,
        };

        let token = match self.protect.parse_token(&token_data) {
            Ok(token) => token,
            Err(_) => return false,
        };

        self.protect.verify_token_pair(&token, cookie)
    }
}