logo
  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
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::{sync::Arc, time::Duration};

use libcsrf::{
    AesGcmCsrfProtection, CsrfCookie as RawCsrfCookie, CsrfProtection, CsrfToken as RawCsrfToken,
    UnencryptedCsrfCookie,
};

use crate::{
    middleware::{CookieJarManager, CookieJarManagerEndpoint},
    web::{
        cookie::{Cookie, SameSite},
        CsrfToken, CsrfVerifier,
    },
    Endpoint, Middleware, Request, Result,
};

/// Middleware for Cross-Site Request Forgery (CSRF) protection.
///
/// # Example
///
/// ```
/// use poem::{
///     get, handler,
///     http::{header, Method, StatusCode},
///     middleware::Csrf,
///     post,
///     web::{cookie::Cookie, CsrfToken, CsrfVerifier},
///     Endpoint, EndpointExt, Error, Request, Result, Route,
/// };
/// use serde::Deserialize;
///
/// #[handler]
/// async fn login_ui(token: &CsrfToken) -> String {
///     token.0.clone()
/// }
///
/// #[handler]
/// async fn login(verifier: &CsrfVerifier, req: &Request) -> Result<String> {
///     let csrf_token = req
///         .header("X-CSRF-Token")
///         .ok_or_else(|| Error::from_status(StatusCode::UNAUTHORIZED))?;
///
///     if !verifier.is_valid(&csrf_token) {
///         return Err(Error::from_status(StatusCode::UNAUTHORIZED));
///     }
///
///     Ok(format!("login success"))
/// }
///
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let app = Route::new()
///     .at("/", get(login_ui).post(login))
///     .with(Csrf::new());
///
/// let resp = app.call(Request::default()).await.unwrap();
/// assert_eq!(resp.status(), StatusCode::OK);
/// let cookie = resp.headers().get(header::SET_COOKIE).unwrap();
/// let cookie = Cookie::parse(cookie.to_str().unwrap()).unwrap();
/// let csrf_token = resp.into_body().into_string().await.unwrap();
///
/// let resp = app
///     .call(
///         Request::builder()
///             .method(Method::POST)
///             .header("X-CSRF-Token", csrf_token)
///             .header(
///                 header::COOKIE,
///                 format!("{}={}", cookie.name(), cookie.value_str()),
///             )
///             .finish(),
///     )
///     .await
///     .unwrap();
/// assert_eq!(resp.status(), StatusCode::OK);
/// assert_eq!(
///     resp.into_body().into_string().await.unwrap(),
///     "login success"
/// );
/// # });
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "csrf")))]
pub struct Csrf {
    cookie_name: String,
    key: [u8; 32],
    secure: bool,
    http_only: bool,
    same_site: Option<SameSite>,
    ttl: Duration,
}

impl Default for Csrf {
    fn default() -> Self {
        Self {
            cookie_name: "poem-csrf-token".to_string(),
            key: Default::default(),
            secure: true,
            http_only: true,
            same_site: Some(SameSite::Strict),
            ttl: Duration::from_secs(24 * 60 * 60),
        }
    }
}

impl Csrf {
    /// Create `Csrf` middleware.
    pub fn new() -> Self {
        Default::default()
    }

    /// Sets AES256 key to provide signed, encrypted CSRF tokens and cookies.
    #[must_use]
    pub fn key(self, key: [u8; 32]) -> Self {
        Self { key, ..self }
    }

    /// Sets the `Secure` to the csrf cookie. Default is `true`.
    #[must_use]
    pub fn secure(self, value: bool) -> Self {
        Self {
            secure: value,
            ..self
        }
    }

    /// Sets the `HttpOnly` to the csrf cookie. Default is `true`.
    #[must_use]
    pub fn http_only(self, value: bool) -> Self {
        Self {
            http_only: value,
            ..self
        }
    }

    /// Sets the `SameSite` to the csrf cookie. Default is
    /// [`SameSite::Strict`](libcookie::SameSite::Strict).
    #[must_use]
    pub fn same_site(self, value: impl Into<Option<SameSite>>) -> Self {
        Self {
            same_site: value.into(),
            ..self
        }
    }

    /// Sets the protection ttl. This will be used for both the cookie
    /// expiry and the time window over which CSRF tokens are considered
    /// valid.
    ///
    /// The default for this value is one day.
    #[must_use]
    pub fn ttl(self, ttl: Duration) -> Self {
        Self { ttl, ..self }
    }
}

impl<E: Endpoint> Middleware<E> for Csrf {
    type Output = CookieJarManagerEndpoint<CsrfEndpoint<E>>;

    fn transform(&self, ep: E) -> Self::Output {
        CookieJarManager::new().transform(CsrfEndpoint {
            inner: ep,
            protect: Arc::new(AesGcmCsrfProtection::from_key(self.key)),
            cookie_name: self.cookie_name.clone(),
            secure: self.secure,
            http_only: self.http_only,
            same_site: self.same_site,
            ttl: self.ttl,
        })
    }
}

/// Endpoint for Csrf middleware.
#[cfg_attr(docsrs, doc(cfg(feature = "csrf")))]
pub struct CsrfEndpoint<E> {
    inner: E,
    protect: Arc<AesGcmCsrfProtection>,
    cookie_name: String,
    secure: bool,
    http_only: bool,
    same_site: Option<SameSite>,
    ttl: Duration,
}

impl<E> CsrfEndpoint<E> {
    fn generate_token(
        &self,
        existing_cookie: Option<&UnencryptedCsrfCookie>,
    ) -> (RawCsrfToken, RawCsrfCookie) {
        let existing_cookie_bytes = existing_cookie.and_then(|c| {
            let c = c.value();
            if c.len() < 64 {
                None
            } else {
                let mut buf = [0; 64];
                buf.copy_from_slice(c);
                Some(buf)
            }
        });

        self.protect
            .generate_token_pair(existing_cookie_bytes.as_ref(), self.ttl.as_secs() as i64)
            .expect("couldn't generate token/cookie pair")
    }
}

#[async_trait::async_trait]
impl<E: Endpoint> Endpoint for CsrfEndpoint<E> {
    type Output = E::Output;

    async fn call(&self, mut req: Request) -> Result<Self::Output> {
        let existing_cookie = req
            .cookie()
            .get(&self.cookie_name)
            .and_then(|cookie| base64::decode(cookie.value_str()).ok())
            .and_then(|value| self.protect.parse_cookie(&value).ok());

        let (token, cookie) = self.generate_token(existing_cookie.as_ref());
        let csrf_cookie = {
            let mut cookie =
                Cookie::new_with_str(&self.cookie_name, base64::encode(cookie.value()));
            cookie.set_secure(self.secure);
            cookie.set_http_only(self.http_only);
            cookie.set_same_site(self.same_site);
            cookie.set_max_age(self.ttl);
            cookie
        };

        req.cookie().add(csrf_cookie);
        req.extensions_mut()
            .insert(CsrfToken(base64::encode(token.value())));
        req.extensions_mut()
            .insert(CsrfVerifier::new(existing_cookie, self.protect.clone()));

        self.inner.call(req).await
    }
}

#[cfg(test)]
mod tests {
    use http::{header, Method, StatusCode};

    use super::*;
    use crate::{get, handler, EndpointExt, Error, IntoResponse, Result};

    const CSRF_TOKEN_NAME: &'static str = "X-CSRF-Token";

    #[tokio::test]
    async fn test_csrf() {
        #[handler(internal)]
        fn login_ui(token: &CsrfToken) -> impl IntoResponse {
            token.0.to_string()
        }

        #[handler(internal)]
        fn login(verifier: &CsrfVerifier, req: &Request) -> Result<impl IntoResponse> {
            let token = req
                .header(CSRF_TOKEN_NAME)
                .ok_or_else(|| Error::from_string("missing token", StatusCode::BAD_REQUEST))?;
            match verifier.is_valid(token) {
                true => Ok("ok"),
                false => Err(Error::from_string("invalid token", StatusCode::BAD_REQUEST)),
            }
        }

        let app = get(login_ui).post(login).with(Csrf::new());

        for _ in 0..5 {
            let resp = app.call(Request::default()).await.unwrap();
            let cookie = resp
                .header(header::SET_COOKIE)
                .map(|cookie| cookie.to_string())
                .unwrap();
            let token = resp.into_body().into_string().await.unwrap();

            let resp = app
                .call(
                    Request::builder()
                        .method(Method::POST)
                        .header(CSRF_TOKEN_NAME, token)
                        .header(header::COOKIE, cookie)
                        .finish(),
                )
                .await
                .unwrap()
                .into_body()
                .into_string()
                .await
                .unwrap();
            assert_eq!(resp, "ok");
        }

        let resp = app.call(Request::default()).await.unwrap();
        let cookie = resp
            .header(header::SET_COOKIE)
            .map(|cookie| cookie.to_string())
            .unwrap();
        let token = resp.into_body().into_string().await.unwrap();

        let mut token = base64::decode(token).unwrap();
        token[0] = token[0].wrapping_add(1);

        assert_eq!(
            app.call(
                Request::builder()
                    .method(Method::POST)
                    .header(CSRF_TOKEN_NAME, base64::encode(token))
                    .header(header::COOKIE, cookie)
                    .finish(),
            )
            .await
            .unwrap_err()
            .to_string(),
            "invalid token"
        );
    }
}