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
319    /// On first request, a new session cookie is returned in response, regardless
320    /// of whether any session state is set.  With subsequent requests, if the
321    /// session state changes, then set-cookie is returned in response.  As
322    /// a user logs out, call session.purge() to set SessionStatus accordingly
323    /// and this will trigger removal of the session cookie in the response.
324    async fn call(
325        &self,
326        req: WebRequest<In>,
327        ctx: Ctx<'_, Self, St>,
328    ) -> Result<Self::Res, Self::Error> {
329        let inner = self.inner.clone();
330        let (is_new, state) = self.inner.load(&req);
331        let prolong_expiration = self.inner.expires_in.is_some();
332        Session::set_session(state.into_iter(), &req);
333
334        ctx.call(&self.service, req).await.map(|mut res| {
335            match Session::get_changes(&mut res) {
336                (SessionStatus::Changed, Some(state)) | (SessionStatus::Renewed, Some(state)) => {
337                    if let Err(e) = inner.set_cookie(&mut res, state) {
338                        res.error_response(ctx.st(), &e)
339                    } else {
340                        res
341                    }
342                }
343                (SessionStatus::Unchanged, Some(state)) if prolong_expiration => {
344                    if let Err(e) = inner.set_cookie(&mut res, state) {
345                        res.error_response(ctx.st(), &e)
346                    } else {
347                        res
348                    }
349                }
350                (SessionStatus::Unchanged, _) =>
351                // set a new session cookie upon first request (new client)
352                {
353                    if is_new {
354                        let state: HashMap<String, String> = HashMap::new();
355
356                        if let Err(e) = inner.set_cookie(&mut res, state.into_iter()) {
357                            res.error_response(ctx.st(), &e)
358                        } else {
359                            res
360                        }
361                    } else {
362                        res
363                    }
364                }
365                (SessionStatus::Purged, _) => {
366                    let _ = inner.remove_cookie(&mut res);
367                    res
368                }
369                _ => res,
370            }
371        })
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use ntex::web::{self, App, test};
379    use ntex::{time, util::Bytes};
380
381    #[ntex::test]
382    async fn cookie_session() {
383        let app = test::init_service(
384            App::new()
385                .middleware(CookieSession::signed(&[0; 32]).secure(false))
386                .service(web::resource("/").to(|ses: Session| async move {
387                    let _ = ses.set("counter", 100);
388                    "test"
389                })),
390        )
391        .await;
392
393        let request = test::TestRequest::get().to_request();
394        let response = app.call(request).await.unwrap();
395        assert!(response.cookies().any(|c| c.name() == "ntex-session"));
396    }
397
398    #[ntex::test]
399    async fn private_cookie() {
400        let app = test::init_service(
401            App::new()
402                .middleware(CookieSession::private(&[0; 32]).secure(false))
403                .service(web::resource("/").to(|ses: Session| async move {
404                    let _ = ses.set("counter", 100);
405                    "test"
406                })),
407        )
408        .await;
409
410        let request = test::TestRequest::get().to_request();
411        let response = app.call(request).await.unwrap();
412        assert!(response.cookies().any(|c| c.name() == "ntex-session"));
413    }
414
415    #[ntex::test]
416    async fn cookie_session_extractor() {
417        let app = test::init_service(
418            App::new()
419                .middleware(CookieSession::signed(&[0; 32]).secure(false))
420                .service(web::resource("/").to(|ses: Session| async move {
421                    let _ = ses.set("counter", 100);
422                    "test"
423                })),
424        )
425        .await;
426
427        let request = test::TestRequest::get().to_request();
428        let response = app.call(request).await.unwrap();
429        assert!(response.cookies().any(|c| c.name() == "ntex-session"));
430    }
431
432    #[ntex::test]
433    async fn basics() {
434        let app = test::init_service(
435            App::new()
436                .middleware(
437                    CookieSession::signed(&[0; 32])
438                        .path("/test/")
439                        .name("ntex-test")
440                        .domain("localhost")
441                        .http_only(true)
442                        .same_site(SameSite::Lax)
443                        .max_age(100),
444                )
445                .service(web::resource("/").to(|ses: Session| async move {
446                    let _ = ses.set("counter", 100);
447                    "test"
448                }))
449                .service(web::resource("/test/").to(|ses: Session| async move {
450                    let val: usize = ses.get("counter").unwrap().unwrap();
451                    format!("counter: {}", val)
452                })),
453        )
454        .await;
455
456        let request = test::TestRequest::get().to_request();
457        let response = app.call(request).await.unwrap();
458        let cookie = response
459            .cookies()
460            .find(|c| c.name() == "ntex-test")
461            .unwrap()
462            .into_owned();
463        assert_eq!(cookie.path().unwrap(), "/test/");
464
465        let request = test::TestRequest::with_uri("/test/")
466            .cookie(cookie)
467            .to_request();
468        let body = test::read_response(&app, request).await;
469        assert_eq!(body, Bytes::from_static(b"counter: 100"));
470    }
471
472    #[ntex::test]
473    async fn prolong_expiration() {
474        let app = test::init_service(
475            App::new()
476                .middleware(CookieSession::signed(&[0; 32]).secure(false).expires_in(60))
477                .service(web::resource("/").to(|ses: Session| async move {
478                    let _ = ses.set("counter", 100);
479                    "test"
480                }))
481                .service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
482        )
483        .await;
484
485        let request = test::TestRequest::get().to_request();
486        let response = app.call(request).await.unwrap();
487        let expires_1 = response
488            .cookies()
489            .find(|c| c.name() == "ntex-session")
490            .expect("Cookie is set")
491            .expires()
492            .expect("Expiration is set");
493
494        time::sleep(time::Seconds::ONE).await;
495
496        let request = test::TestRequest::with_uri("/test/").to_request();
497        let response = app.call(request).await.unwrap();
498        let expires_2 = response
499            .cookies()
500            .find(|c| c.name() == "ntex-session")
501            .expect("Cookie is set")
502            .expires()
503            .expect("Expiration is set");
504
505        assert!(
506            expires_2.datetime().unwrap() - expires_1.datetime().unwrap() >= Duration::seconds(1)
507        );
508    }
509}