ntex-session 4.3.0

Session for ntex web framework.
Documentation
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! User sessions for the ntex web framework.
//!
//! The crate provides a backend-independent [`Session`] API. A session
//! middleware loads the session state for each request and writes changes
//! back to the response; handlers access the state through the [`Session`]
//! extractor or the [`UserSession`] trait.
//!
//! Session values are stored as JSON strings and are (de)serialized with
//! `serde_json`.
//!
//! Only a cookie based backend, [`CookieSession`], is provided (enabled by the
//! default `cookie-session` feature). Other backends can be built on top of
//! [`Session::set_session`] and [`Session::get_changes`].
//!
//! # Example
//!
//! ```rust
//! use ntex::web::{self, App};
//! use ntex_session::{CookieSession, Session};
//!
//! async fn index(session: Session) -> Result<&'static str, serde_json::Error> {
//!     let count = session.get::<u32>("counter")?.unwrap_or(0);
//!     session.set("counter", count + 1)?;
//!     Ok("Welcome!")
//! }
//!
//! let app = App::default()
//!     .middleware(
//!         // Use a secret, stable key in production; disable Secure only for local HTTP.
//!         CookieSession::signed(&[0; 32]).secure(false),
//!     )
//!     .service(web::resource("/").to(index));
//! ```
use std::{cell::RefCell, convert::Infallible, rc::Rc};

use ntex::http::{Payload, RequestHead};
use ntex::util::{Extensions, HashMap};
use ntex::web::{FromRequest, HttpRequest, WebRequest, WebResponse};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::error::Error as JsonError;

#[cfg(feature = "cookie-session")]
mod cookie;
#[cfg(feature = "cookie-session")]
pub use crate::cookie::{CookieSession, CookieSessionError, CookieSessionMiddleware};

/// The high-level interface you use to read and modify session data.
///
/// `Session` is an extractor, it can also be obtained with
/// [`UserSession::get_session`] from an [`HttpRequest`], [`WebRequest`] or
/// [`RequestHead`]. All handles for the same request share the same state.
/// Without session middleware, the state is not persisted between requests.
///
/// Once the session is [purged](Session::purge), further handler mutations
/// through [`set`](Self::set), [`remove`](Self::remove), [`clear`](Self::clear),
/// or [`renew`](Self::renew) are ignored.
///
/// ```rust
/// use ntex_session::Session;
/// use ntex::web::*;
/// use serde_json::error::Error as JsonError;
///
/// fn index(session: Session) -> Result<&'static str, JsonError> {
///     // access session data
///     if let Some(count) = session.get::<i32>("counter")? {
///         session.set("counter", count + 1)?;
///     } else {
///         session.set("counter", 1)?;
///     }
///
///     Ok("Welcome!")
/// }
/// # fn main() {}
/// ```
pub struct Session(Rc<RefCell<SessionInner>>);

/// Helper trait that allows to get the session of a request.
pub trait UserSession {
    /// Get the session of the request, creating an empty one if needed.
    fn get_session(&self) -> Session;
}

impl UserSession for HttpRequest {
    fn get_session(&self) -> Session {
        Session::get_session(&mut self.extensions_mut())
    }
}

impl<St> UserSession for WebRequest<St> {
    fn get_session(&self) -> Session {
        Session::get_session(&mut self.extensions_mut())
    }
}

impl UserSession for RequestHead {
    fn get_session(&self) -> Session {
        Session::get_session(&mut self.extensions_mut())
    }
}

/// Status of the session after the request is handled.
///
/// Returned by [`Session::get_changes`], backends use it to decide how to
/// update the client.
#[derive(PartialEq, Clone, Debug, Default)]
pub enum SessionStatus {
    /// A call to [`Session::set`], [`Session::remove`], or [`Session::clear`]
    /// marked the state changed, even if it did not alter any stored value.
    Changed,
    /// Session was purged, the backend should remove it.
    Purged,
    /// Session was renewed, the backend should re-issue it with the
    /// existing state.
    Renewed,
    /// Session was not modified.
    #[default]
    Unchanged,
}

#[derive(Default)]
struct SessionInner {
    state: HashMap<String, String>,
    pub status: SessionStatus,
}

impl Session {
    /// Get a value from the session.
    ///
    /// Returns `Ok(None)` if the key is not set.
    ///
    /// # Errors
    ///
    /// Returns an error if the stored JSON cannot be deserialized into `T`.
    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, JsonError> {
        if let Some(s) = self.0.borrow().state.get(key) {
            Ok(Some(serde_json::from_str(s)?))
        } else {
            Ok(None)
        }
    }

    /// Set a value in the session.
    ///
    /// Marks the session changed before serializing. Ignored if the session
    /// is purged, in which case the value is not serialized.
    ///
    /// # Errors
    ///
    /// Returns an error if the value cannot be serialized. The existing value
    /// is preserved, but the session remains marked changed.
    pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), JsonError> {
        let mut inner = self.0.borrow_mut();
        if inner.status != SessionStatus::Purged {
            inner.status = SessionStatus::Changed;
            inner
                .state
                .insert(key.to_owned(), serde_json::to_string(&value)?);
        }
        Ok(())
    }

    /// Remove a value from the session.
    ///
    /// Ignored if the session is purged.
    pub fn remove(&self, key: &str) {
        let mut inner = self.0.borrow_mut();
        if inner.status != SessionStatus::Purged {
            inner.status = SessionStatus::Changed;
            inner.state.remove(key);
        }
    }

    /// Remove all values from the session.
    ///
    /// Ignored if the session is purged.
    pub fn clear(&self) {
        let mut inner = self.0.borrow_mut();
        if inner.status != SessionStatus::Purged {
            inner.status = SessionStatus::Changed;
            inner.state.clear()
        }
    }

    /// Remove the session, both client and server side.
    ///
    /// All values are dropped, and later calls to [`set`](Self::set),
    /// [`remove`](Self::remove), [`clear`](Self::clear), and [`renew`](Self::renew)
    /// in the same request are ignored. The backend performs the removal.
    pub fn purge(&self) {
        let mut inner = self.0.borrow_mut();
        inner.status = SessionStatus::Purged;
        inner.state.clear();
    }

    /// Marks the session for reissue while preserving its existing state.
    ///
    /// The backend chooses the renewal mechanism; [`CookieSession`] rewrites
    /// the cookie without rotating its signing or encryption key. Ignored if
    /// the session is purged.
    pub fn renew(&self) {
        let mut inner = self.0.borrow_mut();
        if inner.status != SessionStatus::Purged {
            inner.status = SessionStatus::Renewed;
        }
    }

    /// Load session state into the request.
    ///
    /// Used by session backends before calling the inner service. Extends the
    /// current state, overwriting matching keys without changing the status.
    /// Values must be JSON encoded, as returned by [`Session::get_changes`];
    /// this method does not validate them.
    pub fn set_session<St>(data: impl Iterator<Item = (String, String)>, req: &WebRequest<St>) {
        let session = Session::get_session(&mut req.extensions_mut());
        let mut inner = session.0.borrow_mut();
        inner.state.extend(data);
    }

    /// Drains the state from the response's request and returns its current status.
    ///
    /// Used by session backends after the inner service returns. The state is
    /// moved out of all shared handles, but the status is not reset. Returns
    /// `None` for the state only if no session was created; otherwise returns
    /// `Some`, even for empty or unchanged state.
    pub fn get_changes(
        res: &mut WebResponse,
    ) -> (
        SessionStatus,
        Option<impl Iterator<Item = (String, String)> + use<>>,
    ) {
        if let Some(s_impl) = res
            .request()
            .extensions()
            .get::<Rc<RefCell<SessionInner>>>()
        {
            let state = std::mem::take(&mut s_impl.borrow_mut().state);
            (s_impl.borrow().status.clone(), Some(state.into_iter()))
        } else {
            (SessionStatus::Unchanged, None)
        }
    }

    fn get_session(extensions: &mut Extensions) -> Session {
        if let Some(s_impl) = extensions.get::<Rc<RefCell<SessionInner>>>() {
            return Session(Rc::clone(s_impl));
        }
        let inner = Rc::new(RefCell::new(SessionInner::default()));
        extensions.insert(inner.clone());
        Session(inner)
    }
}

/// Extractor implementation for Session type.
///
/// ```rust
/// use ntex_session::Session;
/// use serde_json::error::Error as JsonError;
///
/// fn index(session: Session) -> Result<&'static str, JsonError> {
///     // access session data
///     if let Some(count) = session.get::<i32>("counter")? {
///         session.set("counter", count + 1)?;
///     } else {
///         session.set("counter", 1)?;
///     }
///
///     Ok("Welcome!")
/// }
/// # fn main() {}
/// ```
impl<St> FromRequest<St> for Session {
    type Error = Infallible;

    #[inline]
    async fn from_request(
        _: &St,
        req: &HttpRequest,
        _: &mut Payload,
    ) -> Result<Session, Infallible> {
        Ok(Session::get_session(&mut req.extensions_mut()))
    }
}

#[cfg(test)]
mod tests {
    use ntex::web::{HttpResponse, test};

    use super::*;

    #[test]
    fn session() {
        let req = test::TestRequest::default().to_srv_request();

        Session::set_session(
            vec![("key".to_string(), "\"value\"".to_string())].into_iter(),
            &req,
        );
        let session = Session::get_session(&mut req.extensions_mut());
        let res = session.get::<String>("key").unwrap();
        assert_eq!(res, Some("value".to_string()));

        session.set("key2", "value2".to_string()).unwrap();
        session.remove("key");

        let mut res = req.into_response(HttpResponse::Ok().build());
        let (_status, state) = Session::get_changes(&mut res);
        let changes: Vec<_> = state.unwrap().collect();
        assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
    }

    #[test]
    fn get_session() {
        let req = test::TestRequest::default().to_srv_request();

        Session::set_session(
            vec![("key".to_string(), "\"value\"".to_string())].into_iter(),
            &req,
        );

        let session = req.get_session();
        let res = session.get::<String>("key").unwrap();
        assert_eq!(res, Some("value".to_string()));
    }

    #[test]
    fn get_session_from_request_head() {
        let mut req = test::TestRequest::default().to_srv_request();

        Session::set_session(
            vec![("key".to_string(), "\"value\"".to_string())].into_iter(),
            &req,
        );

        let session = req.head_mut().get_session();
        let res = session.get::<String>("key").unwrap();
        assert_eq!(res, Some("value".to_string()));
    }

    /// STATEMENT: `Session::purge` removes all data and cannot be undone by later mutations.
    ///
    /// HOW:
    /// - Store a value, purge the session, then attempt `set`, `remove`, `clear` and `renew`.
    /// - Assert the value is absent and `get_changes` returns `Purged` with empty state.
    #[test]
    fn purge_session() {
        let req = test::TestRequest::default().to_srv_request();
        let session = req.get_session();
        session.set("key", "value").unwrap();
        session.purge();
        session.set("key", "replacement").unwrap();
        session.remove("key");
        session.clear();
        session.renew();
        assert_eq!(session.get::<String>("key").unwrap(), None);

        let mut res = req.into_response(HttpResponse::Ok().build());
        let (status, state) = Session::get_changes(&mut res);
        assert_eq!(status, SessionStatus::Purged);
        assert_eq!(state.unwrap().count(), 0);
    }

    /// STATEMENT: `Session::renew` requests reissue without discarding loaded session data.
    ///
    /// HOW:
    /// - Load a JSON-encoded value and renew the session without changing that value.
    /// - Assert `get_changes` returns `Renewed` and the original key and encoded value.
    #[test]
    fn renew_session() {
        let req = test::TestRequest::default().to_srv_request();
        Session::set_session([("key".to_owned(), "42".to_owned())].into_iter(), &req);
        req.get_session().renew();

        let mut res = req.into_response(HttpResponse::Ok().build());
        let (status, state) = Session::get_changes(&mut res);
        assert_eq!(status, SessionStatus::Renewed);
        assert_eq!(
            state.unwrap().collect::<Vec<_>>(),
            [("key".to_owned(), "42".to_owned())]
        );
    }

    /// STATEMENT: Request session handles share mutations, and `get_changes` drains their state.
    ///
    /// HOW:
    /// - Assert an untouched response has no session changes, then obtain two handles from one `HttpRequest`.
    /// - Set values through both handles, clear them, and store a replacement value.
    /// - Assert both handles see the changes and the response drains the JSON-encoded replacement.
    #[test]
    fn shared_session_handles_clear_and_drain_state() {
        let mut untouched =
            test::TestRequest::default().to_srv_response(HttpResponse::Ok().build());
        let (status, state) = Session::get_changes(&mut untouched);
        assert_eq!(status, SessionStatus::Unchanged);
        assert!(state.is_none());

        let req = test::TestRequest::default().to_http_request();
        let first = req.get_session();
        let second = req.clone().get_session();
        first.set("first", 1).unwrap();
        second.set("second", 2).unwrap();
        assert_eq!(second.get::<u32>("first").unwrap(), Some(1));
        assert_eq!(first.get::<u32>("second").unwrap(), Some(2));
        second.clear();
        assert_eq!(first.get::<u32>("first").unwrap(), None);
        assert_eq!(first.get::<u32>("second").unwrap(), None);
        first.set("replacement", 3).unwrap();

        let mut res = WebRequest::from_request(req).into_response(HttpResponse::Ok().build());
        let (status, state) = Session::get_changes(&mut res);
        assert_eq!(status, SessionStatus::Changed);
        assert_eq!(
            state.unwrap().collect::<Vec<_>>(),
            [("replacement".to_owned(), "3".to_owned())]
        );
        assert_eq!(second.get::<u32>("replacement").unwrap(), None);
    }

    /// STATEMENT: Session JSON errors are returned without overwriting an existing value.
    ///
    /// HOW:
    /// - Load invalid JSON and a valid integer, then deserialize the invalid value and the integer as a string.
    /// - Attempt to replace the integer with a serializer that fails and assert all errors are returned.
    /// - Assert the original integer still appears in the session and its response changes.
    #[test]
    fn session_json_errors_preserve_existing_values() {
        struct Unserializable;

        impl Serialize for Unserializable {
            fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
                Err(serde::ser::Error::custom("cannot serialize session value"))
            }
        }

        let req = test::TestRequest::default().to_srv_request();
        Session::set_session(
            [
                ("bad".to_owned(), "not-json".to_owned()),
                ("good".to_owned(), "42".to_owned()),
            ]
            .into_iter(),
            &req,
        );
        let session = req.get_session();
        assert!(session.get::<u32>("bad").is_err());
        assert!(session.get::<String>("good").is_err());
        assert!(
            session
                .set("good", Unserializable)
                .unwrap_err()
                .to_string()
                .contains("cannot serialize")
        );
        assert_eq!(session.get::<u32>("good").unwrap(), Some(42));

        let mut res = req.into_response(HttpResponse::Ok().build());
        let (_, state) = Session::get_changes(&mut res);
        let state: HashMap<_, _> = state.unwrap().collect();
        assert_eq!(state.get("good").map(String::as_str), Some("42"));
    }
}