Skip to main content

ntex_session/
cookie.rs

1//! Cookie session.
2//!
3//! [**CookieSession**](struct.CookieSession.html)
4//! uses cookies as session storage. `CookieSession` creates sessions
5//! which are limited to storing fewer than 4000 bytes of data, as the payload
6//! must fit into a single cookie. An internal server error is generated if a
7//! session contains more than 4000 bytes.
8//!
9//! A cookie may have a security policy of *signed* or *private*. Each has
10//! a respective `CookieSession` constructor.
11//!
12//! A *signed* cookie may be viewed but not modified by the client. A *private*
13//! cookie may neither be viewed nor modified by the client.
14//!
15//! The constructors take a key as an argument. This is the private key
16//! for cookie session - when this value is changed, all session data is lost.
17
18use std::{collections::HashMap, convert::Infallible, rc::Rc};
19
20use cookie::{Cookie, CookieJar, Key, SameSite};
21use derive_more::{Display, From};
22use ntex::http::{HttpMessage, header::HeaderValue, header::SET_COOKIE};
23use ntex::service::{Ctx, Middleware, Service};
24use ntex::web::{DefaultError, State, WebRequest, WebResponse, WebResponseError};
25use serde_json::error::Error as JsonError;
26use time::{Duration, OffsetDateTime};
27
28use crate::{Session, SessionStatus};
29
30/// Errors that can occur during handling cookie session
31#[derive(Debug, From, Display, thiserror::Error)]
32pub enum CookieSessionError {
33    /// Size of the serialized session is greater than 4000 bytes.
34    #[display("Size of the serialized session is greater than 4000 bytes.")]
35    Overflow,
36    /// Fail to serialize session.
37    #[display("Fail to serialize session")]
38    Serialize(JsonError),
39}
40
41impl<St> WebResponseError<St, DefaultError> for CookieSessionError {}
42
43enum CookieSecurity {
44    Signed,
45    Private,
46}
47
48struct CookieSessionInner {
49    key: Key,
50    security: CookieSecurity,
51    name: String,
52    path: String,
53    domain: Option<String>,
54    secure: bool,
55    http_only: bool,
56    max_age: Option<Duration>,
57    expires_in: Option<Duration>,
58    same_site: Option<SameSite>,
59}
60
61impl CookieSessionInner {
62    fn new(key: &[u8], security: CookieSecurity) -> Self {
63        CookieSessionInner {
64            security,
65            key: Key::derive_from(key),
66            name: "ntex-session".to_owned(),
67            path: "/".to_owned(),
68            domain: None,
69            secure: true,
70            http_only: true,
71            max_age: None,
72            expires_in: None,
73            same_site: None,
74        }
75    }
76
77    fn set_cookie(
78        &self,
79        res: &mut WebResponse,
80        state: impl Iterator<Item = (String, String)>,
81    ) -> Result<(), CookieSessionError> {
82        let state: HashMap<String, String> = state.collect();
83        let value = serde_json::to_string(&state).map_err(CookieSessionError::Serialize)?;
84        if value.len() > 4064 {
85            return Err(CookieSessionError::Overflow);
86        }
87
88        let mut cookie = Cookie::new(self.name.clone(), value);
89        cookie.set_path(self.path.clone());
90        cookie.set_secure(self.secure);
91        cookie.set_http_only(self.http_only);
92
93        if let Some(ref domain) = self.domain {
94            cookie.set_domain(domain.clone());
95        }
96
97        if let Some(expires_in) = self.expires_in {
98            cookie.set_expires(OffsetDateTime::now_utc() + expires_in);
99        }
100
101        if let Some(max_age) = self.max_age {
102            cookie.set_max_age(max_age);
103        }
104
105        if let Some(same_site) = self.same_site {
106            cookie.set_same_site(same_site);
107        }
108
109        let mut jar = CookieJar::new();
110
111        match self.security {
112            CookieSecurity::Signed => jar.signed_mut(&self.key).add(cookie),
113            CookieSecurity::Private => jar.private_mut(&self.key).add(cookie),
114        }
115
116        for cookie in jar.delta() {
117            let val = HeaderValue::from_str(&cookie.encoded().to_string()).unwrap();
118            res.headers_mut().append(SET_COOKIE, val);
119        }
120
121        Ok(())
122    }
123
124    /// invalidates session cookie
125    fn remove_cookie(&self, res: &mut WebResponse) -> Result<(), Infallible> {
126        let mut cookie = Cookie::from(self.name.clone());
127        cookie.set_value("");
128        cookie.set_max_age(Duration::ZERO);
129        cookie.set_expires(OffsetDateTime::now_utc() - Duration::days(365));
130        cookie.set_path(&self.path);
131
132        if let Some(ref domain) = self.domain {
133            cookie.set_domain(domain);
134        }
135
136        let val = HeaderValue::from_str(&cookie.to_string()).unwrap();
137        res.headers_mut().append(SET_COOKIE, val);
138
139        Ok(())
140    }
141
142    fn load<St>(&self, req: &WebRequest<St>) -> (bool, HashMap<String, String>) {
143        if let Ok(cookies) = req.cookies() {
144            for cookie in cookies.iter() {
145                if cookie.name() == self.name {
146                    let mut jar = CookieJar::new();
147                    jar.add_original(cookie.clone());
148
149                    let cookie_opt = match self.security {
150                        CookieSecurity::Signed => jar.signed(&self.key).get(&self.name),
151                        CookieSecurity::Private => jar.private(&self.key).get(&self.name),
152                    };
153                    if let Some(cookie) = cookie_opt
154                        && let Ok(val) = serde_json::from_str(cookie.value())
155                    {
156                        return (false, val);
157                    }
158                }
159            }
160        }
161        (true, HashMap::new())
162    }
163}
164
165/// Use cookies for session storage.
166///
167/// `CookieSession` creates sessions which are limited to storing
168/// fewer than 4000 bytes of data (as the payload must fit into a single
169/// cookie). An Internal Server Error is generated if the session contains more
170/// than 4000 bytes.
171///
172/// A cookie may have a security policy of *signed* or *private*. Each has a
173/// respective `CookieSessionBackend` constructor.
174///
175/// A *signed* cookie is stored on the client as plaintext alongside
176/// a signature such that the cookie may be viewed but not modified by the
177/// client.
178///
179/// A *private* cookie is stored on the client as encrypted text
180/// such that it may neither be viewed nor modified by the client.
181///
182/// The constructors take a key as an argument.
183/// This is the private key for cookie session - when this value is changed,
184/// all session data is lost. The constructors will panic if the key is less
185/// than 32 bytes in length.
186///
187/// The backend relies on `cookie` crate to create and read cookies.
188/// By default all cookies are percent encoded, but certain symbols may
189/// cause troubles when reading cookie, if they are not properly percent encoded.
190///
191/// # Example
192///
193/// ```rust
194/// use ntex_session::CookieSession;
195/// use ntex::web::{self, App, HttpResponse, HttpServer};
196///
197/// let app = App::default().middleware(
198///     CookieSession::signed(&[0; 32])
199///         .domain("www.rust-lang.org")
200///         .name("ntex-session")
201///         .path("/")
202///         .secure(true))
203///     .service(web::resource("/").to(|| async { HttpResponse::Ok() }));
204/// ```
205pub struct CookieSession(Rc<CookieSessionInner>);
206
207impl CookieSession {
208    /// Construct new *signed* `CookieSessionBackend` instance.
209    ///
210    /// Panics if key length is less than 32 bytes.
211    pub fn signed(key: &[u8]) -> Self {
212        CookieSession(Rc::new(CookieSessionInner::new(
213            key,
214            CookieSecurity::Signed,
215        )))
216    }
217
218    /// Construct new *private* `CookieSessionBackend` instance.
219    ///
220    /// Panics if key length is less than 32 bytes.
221    pub fn private(key: &[u8]) -> Self {
222        CookieSession(Rc::new(CookieSessionInner::new(
223            key,
224            CookieSecurity::Private,
225        )))
226    }
227
228    /// Sets the `path` field in the session cookie being built.
229    pub fn path<S: Into<String>>(mut self, value: S) -> Self {
230        Rc::get_mut(&mut self.0).unwrap().path = value.into();
231        self
232    }
233
234    /// Sets the `name` field in the session cookie being built.
235    pub fn name<S: Into<String>>(mut self, value: S) -> Self {
236        Rc::get_mut(&mut self.0).unwrap().name = value.into();
237        self
238    }
239
240    /// Sets the `domain` field in the session cookie being built.
241    pub fn domain<S: Into<String>>(mut self, value: S) -> Self {
242        Rc::get_mut(&mut self.0).unwrap().domain = Some(value.into());
243        self
244    }
245
246    /// Sets the `secure` field in the session cookie being built.
247    ///
248    /// If the `secure` field is set, a cookie will only be transmitted when the
249    /// connection is secure - i.e. `https`
250    pub fn secure(mut self, value: bool) -> Self {
251        Rc::get_mut(&mut self.0).unwrap().secure = value;
252        self
253    }
254
255    /// Sets the `http_only` field in the session cookie being built.
256    pub fn http_only(mut self, value: bool) -> Self {
257        Rc::get_mut(&mut self.0).unwrap().http_only = value;
258        self
259    }
260
261    /// Sets the `same_site` field in the session cookie being built.
262    pub fn same_site(mut self, value: SameSite) -> Self {
263        Rc::get_mut(&mut self.0).unwrap().same_site = Some(value);
264        self
265    }
266
267    /// Sets the `max-age` field in the session cookie being built.
268    pub fn max_age(self, seconds: i64) -> Self {
269        self.max_age_time(Duration::seconds(seconds))
270    }
271
272    /// Sets the `max-age` field in the session cookie being built.
273    pub fn max_age_time(mut self, value: time::Duration) -> Self {
274        Rc::get_mut(&mut self.0).unwrap().max_age = Some(value);
275        self
276    }
277
278    /// Sets the `expires` field in the session cookie being built.
279    pub fn expires_in(self, seconds: i64) -> Self {
280        self.expires_in_time(Duration::seconds(seconds))
281    }
282
283    /// Sets the `expires` field in the session cookie being built.
284    pub fn expires_in_time(mut self, value: Duration) -> Self {
285        Rc::get_mut(&mut self.0).unwrap().expires_in = Some(value);
286        self
287    }
288}
289
290impl<S, St> Middleware<S, St> for CookieSession {
291    type Service = CookieSessionMiddleware<S>;
292
293    fn create(&self, _: &St, service: S) -> Self::Service {
294        CookieSessionMiddleware {
295            service,
296            inner: self.0.clone(),
297        }
298    }
299}
300
301/// Cookie session middleware
302pub struct CookieSessionMiddleware<S> {
303    service: S,
304    inner: Rc<CookieSessionInner>,
305}
306
307impl<S, St: State, In> Service<St, WebRequest<In>> for CookieSessionMiddleware<S>
308where
309    S: Service<St, WebRequest<In>, Res = WebResponse>,
310    S::Error: 'static,
311    CookieSessionError: WebResponseError<St, St::Error>,
312{
313    type Res = WebResponse;
314    type Error = S::Error;
315
316    ntex::forward_ready!(St, service);
317    ntex::forward_shutdown!(St, service);
318    ntex::forward_bind!(St, service);
319
320    /// On first request, a new session cookie is returned in response, regardless
321    /// of whether any session state is set.  With subsequent requests, if the
322    /// session state changes, then set-cookie is returned in response.  As
323    /// a user logs out, call session.purge() to set SessionStatus accordingly
324    /// and this will trigger removal of the session cookie in the response.
325    async fn call(
326        &self,
327        req: WebRequest<In>,
328        ctx: Ctx<'_, Self, St>,
329    ) -> Result<Self::Res, Self::Error> {
330        let inner = self.inner.clone();
331        let (is_new, state) = self.inner.load(&req);
332        let prolong_expiration = self.inner.expires_in.is_some();
333        Session::set_session(state.into_iter(), &req);
334
335        ctx.call(&self.service, req).await.map(|mut res| {
336            match Session::get_changes(&mut res) {
337                (SessionStatus::Changed, Some(state)) | (SessionStatus::Renewed, Some(state)) => {
338                    if let Err(e) = inner.set_cookie(&mut res, state) {
339                        res.error_response(ctx.st(), &e)
340                    } else {
341                        res
342                    }
343                }
344                (SessionStatus::Unchanged, Some(state)) if prolong_expiration => {
345                    if let Err(e) = inner.set_cookie(&mut res, state) {
346                        res.error_response(ctx.st(), &e)
347                    } else {
348                        res
349                    }
350                }
351                (SessionStatus::Unchanged, _) =>
352                // set a new session cookie upon first request (new client)
353                {
354                    if is_new {
355                        let state: HashMap<String, String> = HashMap::new();
356
357                        if let Err(e) = inner.set_cookie(&mut res, state.into_iter()) {
358                            res.error_response(ctx.st(), &e)
359                        } else {
360                            res
361                        }
362                    } else {
363                        res
364                    }
365                }
366                (SessionStatus::Purged, _) => {
367                    let _ = inner.remove_cookie(&mut res);
368                    res
369                }
370                _ => res,
371            }
372        })
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379    use ntex::web::{self, App, test};
380    use ntex::{time, util::Bytes};
381
382    #[ntex::test]
383    async fn cookie_session() {
384        let app = test::init_service(
385            App::new()
386                .middleware(CookieSession::signed(&[0; 32]).secure(false))
387                .service(web::resource("/").to(|ses: Session| async move {
388                    let _ = ses.set("counter", 100);
389                    "test"
390                })),
391        )
392        .await;
393
394        let request = test::TestRequest::get().to_request();
395        let response = app.call(request).await.unwrap();
396        assert!(response.cookies().any(|c| c.name() == "ntex-session"));
397    }
398
399    #[ntex::test]
400    async fn private_cookie() {
401        let app = test::init_service(
402            App::new()
403                .middleware(CookieSession::private(&[0; 32]).secure(false))
404                .service(web::resource("/").to(|ses: Session| async move {
405                    let _ = ses.set("counter", 100);
406                    "test"
407                })),
408        )
409        .await;
410
411        let request = test::TestRequest::get().to_request();
412        let response = app.call(request).await.unwrap();
413        assert!(response.cookies().any(|c| c.name() == "ntex-session"));
414    }
415
416    #[ntex::test]
417    async fn cookie_session_extractor() {
418        let app = test::init_service(
419            App::new()
420                .middleware(CookieSession::signed(&[0; 32]).secure(false))
421                .service(web::resource("/").to(|ses: Session| async move {
422                    let _ = ses.set("counter", 100);
423                    "test"
424                })),
425        )
426        .await;
427
428        let request = test::TestRequest::get().to_request();
429        let response = app.call(request).await.unwrap();
430        assert!(response.cookies().any(|c| c.name() == "ntex-session"));
431    }
432
433    #[ntex::test]
434    async fn basics() {
435        let app = test::init_service(
436            App::new()
437                .middleware(
438                    CookieSession::signed(&[0; 32])
439                        .path("/test/")
440                        .name("ntex-test")
441                        .domain("localhost")
442                        .http_only(true)
443                        .same_site(SameSite::Lax)
444                        .max_age(100),
445                )
446                .service(web::resource("/").to(|ses: Session| async move {
447                    let _ = ses.set("counter", 100);
448                    "test"
449                }))
450                .service(web::resource("/test/").to(|ses: Session| async move {
451                    let val: usize = ses.get("counter").unwrap().unwrap();
452                    format!("counter: {}", val)
453                })),
454        )
455        .await;
456
457        let request = test::TestRequest::get().to_request();
458        let response = app.call(request).await.unwrap();
459        let cookie = response
460            .cookies()
461            .find(|c| c.name() == "ntex-test")
462            .unwrap()
463            .into_owned();
464        assert_eq!(cookie.path().unwrap(), "/test/");
465
466        let request = test::TestRequest::with_uri("/test/")
467            .cookie(cookie)
468            .to_request();
469        let body = test::read_response(&app, request).await;
470        assert_eq!(body, Bytes::from_static(b"counter: 100"));
471    }
472
473    #[ntex::test]
474    async fn prolong_expiration() {
475        let app = test::init_service(
476            App::new()
477                .middleware(CookieSession::signed(&[0; 32]).secure(false).expires_in(60))
478                .service(web::resource("/").to(|ses: Session| async move {
479                    let _ = ses.set("counter", 100);
480                    "test"
481                }))
482                .service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
483        )
484        .await;
485
486        let request = test::TestRequest::get().to_request();
487        let response = app.call(request).await.unwrap();
488        let expires_1 = response
489            .cookies()
490            .find(|c| c.name() == "ntex-session")
491            .expect("Cookie is set")
492            .expires()
493            .expect("Expiration is set");
494
495        time::sleep(time::Seconds::ONE).await;
496
497        let request = test::TestRequest::with_uri("/test/").to_request();
498        let response = app.call(request).await.unwrap();
499        let expires_2 = response
500            .cookies()
501            .find(|c| c.name() == "ntex-session")
502            .expect("Cookie is set")
503            .expires()
504            .expect("Expiration is set");
505
506        assert!(
507            expires_2.datetime().unwrap() - expires_1.datetime().unwrap() >= Duration::seconds(1)
508        );
509    }
510}