Skip to main content

ntex_session/
cookie.rs

1//! Cookie-backed sessions using [`CookieSession`].
2//!
3//! Signed cookies expose their contents but detect tampering; private cookies
4//! additionally encrypt the contents. The protected, percent-encoded
5//! `name=value` pair must fit within 4096 bytes, excluding cookie attributes.
6//! Changing the secret key invalidates existing session cookies.
7
8use std::{collections::HashMap, convert::Infallible, rc::Rc};
9
10use cookie::{Cookie, CookieJar, Key, SameSite};
11use derive_more::{Display, From};
12use ntex::http::{HttpMessage, header::HeaderValue, header::SET_COOKIE};
13use ntex::service::{BindCtx, Ctx, Middleware, Service};
14use ntex::web::{DefaultError, State, WebRequest, WebResponse, WebResponseError};
15use serde_json::error::Error as JsonError;
16use time::{Duration, OffsetDateTime};
17
18use crate::{Session, SessionStatus};
19
20/// Browsers drop cookies whose `name=value` pair is larger than this.
21const MAX_COOKIE_SIZE: usize = 4096;
22
23/// `Path` and `Domain` values are written to `Set-Cookie` verbatim, so they
24/// must be valid header bytes and must not start another attribute.
25fn is_valid_attr(value: &str) -> bool {
26    value
27        .bytes()
28        .all(|b| (0x20..0x7f).contains(&b) && b != b';')
29}
30
31/// Errors that can occur during handling cookie session.
32#[derive(Debug, From, Display, thiserror::Error)]
33pub enum CookieSessionError {
34    /// The protected, percent-encoded `name=value` pair exceeds 4096 bytes, excluding attributes.
35    #[display("Size of the encoded session cookie is greater than 4096 bytes.")]
36    Overflow,
37    /// Failed to serialize session state.
38    #[display("Fail to serialize session")]
39    Serialize(JsonError),
40}
41
42impl<St> WebResponseError<St, DefaultError> for CookieSessionError {}
43
44enum CookieSecurity {
45    Signed,
46    Private,
47}
48
49struct CookieSessionInner {
50    key: Key,
51    security: CookieSecurity,
52    name: String,
53    path: String,
54    domain: Option<String>,
55    secure: bool,
56    http_only: bool,
57    max_age: Option<Duration>,
58    expires_in: Option<Duration>,
59    same_site: Option<SameSite>,
60}
61
62impl CookieSessionInner {
63    fn new(key: &[u8], security: CookieSecurity) -> Self {
64        CookieSessionInner {
65            security,
66            key: Key::derive_from(key),
67            name: "ntex-session".to_owned(),
68            path: "/".to_owned(),
69            domain: None,
70            secure: true,
71            http_only: true,
72            max_age: None,
73            expires_in: None,
74            same_site: None,
75        }
76    }
77
78    fn set_cookie(
79        &self,
80        res: &mut WebResponse,
81        state: impl Iterator<Item = (String, String)>,
82    ) -> Result<(), CookieSessionError> {
83        let state: HashMap<String, String> = state.collect();
84        let value = serde_json::to_string(&state).map_err(CookieSessionError::Serialize)?;
85
86        let mut cookie = self.cookie(value);
87        if let Some(expires_in) = self.expires_in {
88            cookie.set_expires(OffsetDateTime::now_utc() + expires_in);
89        }
90
91        if let Some(max_age) = self.max_age {
92            cookie.set_max_age(max_age);
93        }
94
95        let mut jar = CookieJar::new();
96
97        match self.security {
98            CookieSecurity::Signed => jar.signed_mut(&self.key).add(cookie),
99            CookieSecurity::Private => jar.private_mut(&self.key).add(cookie),
100        }
101
102        for cookie in jar.delta() {
103            let val = cookie.encoded().to_string();
104            // percent-encoded name and value never contain `;`
105            if val.split(';').next().map_or(0, str::len) > MAX_COOKIE_SIZE {
106                return Err(CookieSessionError::Overflow);
107            }
108            res.headers_mut()
109                .append(SET_COOKIE, HeaderValue::from_str(&val).unwrap());
110        }
111
112        Ok(())
113    }
114
115    /// invalidates session cookie
116    fn remove_cookie(&self, res: &mut WebResponse) -> Result<(), Infallible> {
117        // removal must carry the same attributes, browsers reject `__Secure-`
118        // and `__Host-` cookies without `Secure`
119        let mut cookie = self.cookie(String::new());
120        cookie.set_max_age(Duration::ZERO);
121        cookie.set_expires(OffsetDateTime::now_utc() - Duration::days(365));
122
123        let val = HeaderValue::from_str(&cookie.encoded().to_string()).unwrap();
124        res.headers_mut().append(SET_COOKIE, val);
125
126        Ok(())
127    }
128
129    fn cookie(&self, value: String) -> Cookie<'static> {
130        let mut cookie = Cookie::new(self.name.clone(), value);
131        cookie.set_path(self.path.clone());
132        cookie.set_secure(self.secure);
133        cookie.set_http_only(self.http_only);
134
135        if let Some(ref domain) = self.domain {
136            cookie.set_domain(domain.clone());
137        }
138        if let Some(same_site) = self.same_site {
139            cookie.set_same_site(same_site);
140        }
141        cookie
142    }
143
144    fn load<St>(&self, req: &WebRequest<St>) -> (bool, HashMap<String, String>) {
145        if let Ok(cookies) = req.cookies() {
146            for cookie in cookies.iter() {
147                if cookie.name() == self.name {
148                    let mut jar = CookieJar::new();
149                    jar.add_original(cookie.clone());
150
151                    let cookie_opt = match self.security {
152                        CookieSecurity::Signed => jar.signed(&self.key).get(&self.name),
153                        CookieSecurity::Private => jar.private(&self.key).get(&self.name),
154                    };
155                    if let Some(cookie) = cookie_opt
156                        && let Ok(val) = serde_json::from_str(cookie.value())
157                    {
158                        return (false, val);
159                    }
160                }
161            }
162        }
163        (true, HashMap::new())
164    }
165}
166
167/// Use cookies for session storage.
168///
169/// `CookieSession` creates sessions which are limited in size (as the payload
170/// must fit into a single cookie). An Internal Server Error is generated if
171/// the signed or encrypted, percent-encoded `name=value` pair exceeds 4096
172/// bytes. Cookie attributes are not counted toward this limit.
173///
174/// A cookie may have a security policy of *signed* or *private*. Each has a
175/// respective `CookieSession` constructor.
176///
177/// A *signed* cookie is stored on the client as plaintext alongside
178/// a signature such that the cookie may be viewed but not modified by the
179/// client.
180///
181/// A *private* cookie is stored on the client as encrypted text
182/// such that it may neither be viewed nor modified by the client.
183///
184/// The constructors take a key as an argument.
185/// Keep this key secret and stable; changing it makes existing session cookies
186/// unreadable. The constructors require at least 32 bytes.
187///
188/// Missing, malformed, tampered, undecryptable, or invalid-JSON cookies load
189/// an empty session and are replaced. A new cookie is sent when no valid
190/// session cookie was loaded, when the session changes or is renewed, or
191/// (with [`expires_in`](Self::expires_in)) on each response returned by the
192/// inner service. [`Session::purge`] instead expires the cookie, preserving
193/// its configured scope and security attributes. Inner service errors
194/// propagate without writing a cookie.
195///
196/// The backend relies on `cookie` crate to create and read cookies.
197/// Cookie values are percent encoded.
198///
199/// Defaults: name `ntex-session`, path `/`, `Secure` and `HttpOnly` set, no
200/// domain, `SameSite`, `Max-Age` or `Expires`. Configuration methods replace
201/// their previous values and do not validate cookie attributes.
202///
203/// # Panics
204///
205/// Configuration methods panic while this backend is shared with a live
206/// middleware service. Writing a cookie panics if its configured attributes
207/// cannot form a valid `Set-Cookie` header, or if its expiration is outside
208/// the range supported by [`time::OffsetDateTime`].
209///
210/// # Example
211///
212/// ```rust
213/// use ntex_session::CookieSession;
214/// use ntex::web::{self, App, HttpResponse};
215///
216/// let app = App::default().middleware(
217///     CookieSession::signed(&[0; 32])
218///         .domain("www.rust-lang.org")
219///         .name("ntex-session")
220///         .path("/")
221///         .secure(true))
222///     .service(web::resource("/").to(|| async { HttpResponse::Ok() }));
223/// ```
224pub struct CookieSession(Rc<CookieSessionInner>);
225
226impl CookieSession {
227    /// Constructs a signed [`CookieSession`].
228    ///
229    /// The client can read but not modify the session state.
230    ///
231    /// # Panics
232    ///
233    /// Panics if `key` is shorter than 32 bytes.
234    pub fn signed(key: &[u8]) -> Self {
235        CookieSession(Rc::new(CookieSessionInner::new(
236            key,
237            CookieSecurity::Signed,
238        )))
239    }
240
241    /// Constructs an encrypted [`CookieSession`].
242    ///
243    /// The session state is encrypted, the client can neither read nor modify it.
244    ///
245    /// # Panics
246    ///
247    /// Panics if `key` is shorter than 32 bytes.
248    pub fn private(key: &[u8]) -> Self {
249        CookieSession(Rc::new(CookieSessionInner::new(
250            key,
251            CookieSecurity::Private,
252        )))
253    }
254
255    /// Sets the session cookie's `Path` attribute.
256    ///
257    /// Default is `/`.
258    ///
259    /// # Panics
260    ///
261    /// Panics if this backend is shared with a live middleware service, or if
262    /// `value` contains `;` or characters other than printable ASCII.
263    pub fn path<S: Into<String>>(mut self, value: S) -> Self {
264        let value = value.into();
265        assert!(
266            is_valid_attr(&value),
267            "invalid session cookie path: {value:?}"
268        );
269        Rc::get_mut(&mut self.0).unwrap().path = value;
270        self
271    }
272
273    /// Sets the session cookie's name.
274    ///
275    /// Default is `ntex-session`. Names with the `__Secure-` prefix require
276    /// [`secure`](Self::secure); `__Host-` also requires path `/` and no
277    /// [`domain`](Self::domain).
278    ///
279    /// # Panics
280    ///
281    /// Panics if this backend is shared with a live middleware service.
282    pub fn name<S: Into<String>>(mut self, value: S) -> Self {
283        Rc::get_mut(&mut self.0).unwrap().name = value.into();
284        self
285    }
286
287    /// Sets the session cookie's `Domain` attribute.
288    ///
289    /// Not set by default, the cookie is sent only to the origin host.
290    ///
291    /// # Panics
292    ///
293    /// Panics if this backend is shared with a live middleware service, or if
294    /// `value` contains `;` or characters other than printable ASCII.
295    pub fn domain<S: Into<String>>(mut self, value: S) -> Self {
296        let value = value.into();
297        assert!(
298            is_valid_attr(&value),
299            "invalid session cookie domain: {value:?}"
300        );
301        Rc::get_mut(&mut self.0).unwrap().domain = Some(value);
302        self
303    }
304
305    /// Sets the session cookie's `Secure` attribute.
306    ///
307    /// If the `secure` field is set, a cookie will only be transmitted when the
308    /// connection is secure - i.e. `https`. Default is `true`, set it to
309    /// `false` to use sessions over plain `http`.
310    ///
311    /// # Panics
312    ///
313    /// Panics if this backend is shared with a live middleware service.
314    pub fn secure(mut self, value: bool) -> Self {
315        Rc::get_mut(&mut self.0).unwrap().secure = value;
316        self
317    }
318
319    /// Sets the session cookie's `HttpOnly` attribute.
320    ///
321    /// If set, the cookie is not available to client side scripts. Default
322    /// is `true`.
323    ///
324    /// # Panics
325    ///
326    /// Panics if this backend is shared with a live middleware service.
327    pub fn http_only(mut self, value: bool) -> Self {
328        Rc::get_mut(&mut self.0).unwrap().http_only = value;
329        self
330    }
331
332    /// Sets the session cookie's [`SameSite`] attribute.
333    ///
334    /// Not set by default.
335    ///
336    /// # Panics
337    ///
338    /// Panics if this backend is shared with a live middleware service.
339    pub fn same_site(mut self, value: SameSite) -> Self {
340        Rc::get_mut(&mut self.0).unwrap().same_site = Some(value);
341        self
342    }
343
344    /// Sets the session cookie's `Max-Age` attribute, in seconds.
345    ///
346    /// Unset by default. If [`expires_in`](Self::expires_in) is also unset,
347    /// the cookie expires when the browser session ends.
348    ///
349    /// # Panics
350    ///
351    /// Panics if this backend is shared with a live middleware service.
352    pub fn max_age(self, seconds: i64) -> Self {
353        self.max_age_time(Duration::seconds(seconds))
354    }
355
356    /// Sets the session cookie's `Max-Age` attribute.
357    ///
358    /// Same as [`max_age`](Self::max_age), but takes a [`time::Duration`].
359    ///
360    /// # Panics
361    ///
362    /// Panics if this backend is shared with a live middleware service.
363    pub fn max_age_time(mut self, value: time::Duration) -> Self {
364        Rc::get_mut(&mut self.0).unwrap().max_age = Some(value);
365        self
366    }
367
368    /// Sets the session cookie's `Expires` to the given number of seconds from now.
369    ///
370    /// The cookie is re-sent on each response returned by the inner service,
371    /// unless the session is purged, so its expiration is extended on each
372    /// request. Unset by default. If `Max-Age` is also configured, browsers
373    /// give it precedence over `Expires`.
374    ///
375    /// # Panics
376    ///
377    /// Panics if this backend is shared with a live middleware service.
378    pub fn expires_in(self, seconds: i64) -> Self {
379        self.expires_in_time(Duration::seconds(seconds))
380    }
381
382    /// Sets the session cookie's `Expires` to the given duration from now.
383    ///
384    /// Same as [`expires_in`](Self::expires_in), but takes a [`time::Duration`].
385    ///
386    /// # Panics
387    ///
388    /// Panics if this backend is shared with a live middleware service.
389    pub fn expires_in_time(mut self, value: Duration) -> Self {
390        Rc::get_mut(&mut self.0).unwrap().expires_in = Some(value);
391        self
392    }
393}
394
395impl<S, St> Middleware<S, St> for CookieSession {
396    type Service = CookieSessionMiddleware<S>;
397
398    fn create(&self, _: &St, service: S) -> Self::Service {
399        CookieSessionMiddleware {
400            service,
401            inner: self.0.clone(),
402        }
403    }
404}
405
406/// Cookie session middleware service, created by [`CookieSession`].
407pub struct CookieSessionMiddleware<S> {
408    service: S,
409    inner: Rc<CookieSessionInner>,
410}
411
412impl<S, St: State, In> Service<St, WebRequest<In>> for CookieSessionMiddleware<S>
413where
414    S: Service<St, WebRequest<In>, Res = WebResponse>,
415    S::Error: 'static,
416    CookieSessionError: WebResponseError<St, St::Error>,
417{
418    type Res = WebResponse;
419    type Error = S::Error;
420
421    #[inline]
422    fn bind(&self, ctx: BindCtx<'_>) {
423        ctx.bind(&self.service);
424    }
425
426    #[inline]
427    async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
428        ctx.ready(&self.service).await
429    }
430
431    #[inline]
432    async fn shutdown(&self, ctx: Ctx<'_, Self, St>) {
433        ctx.shutdown(&self.service).await;
434    }
435
436    /// Loads session state, calls the inner service, and persists or removes
437    /// the session cookie according to [`SessionStatus`].
438    ///
439    /// # Errors
440    ///
441    /// Propagates inner service errors without writing cookies. Cookie size
442    /// and serialization errors are rendered as error responses instead.
443    ///
444    /// # Panics
445    ///
446    /// Panics if the configured expiration is outside the supported date range.
447    async fn call(
448        &self,
449        req: WebRequest<In>,
450        ctx: Ctx<'_, Self, St>,
451    ) -> Result<Self::Res, Self::Error> {
452        let inner = self.inner.clone();
453        let (is_new, state) = self.inner.load(&req);
454        let prolong_expiration = self.inner.expires_in.is_some();
455        Session::set_session(state.into_iter(), &req);
456
457        ctx.call(&self.service, req).await.map(|mut res| {
458            match Session::get_changes(&mut res) {
459                (SessionStatus::Changed, Some(state)) | (SessionStatus::Renewed, Some(state)) => {
460                    if let Err(e) = inner.set_cookie(&mut res, state) {
461                        res.error_response(ctx.st(), &e)
462                    } else {
463                        res
464                    }
465                }
466                (SessionStatus::Unchanged, Some(state)) if prolong_expiration => {
467                    if let Err(e) = inner.set_cookie(&mut res, state) {
468                        res.error_response(ctx.st(), &e)
469                    } else {
470                        res
471                    }
472                }
473                (SessionStatus::Unchanged, _) =>
474                // set a new session cookie upon first request (new client)
475                {
476                    if is_new {
477                        let state: HashMap<String, String> = HashMap::new();
478
479                        if let Err(e) = inner.set_cookie(&mut res, state.into_iter()) {
480                            res.error_response(ctx.st(), &e)
481                        } else {
482                            res
483                        }
484                    } else {
485                        res
486                    }
487                }
488                (SessionStatus::Purged, _) => {
489                    let _ = inner.remove_cookie(&mut res);
490                    res
491                }
492                _ => res,
493            }
494        })
495    }
496}
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501    use ntex::web::{self, App, test};
502    use ntex::{time, util::Bytes};
503
504    #[ntex::test]
505    async fn cookie_session() {
506        let app = test::init_service(
507            App::new()
508                .middleware(CookieSession::signed(&[0; 32]).secure(false))
509                .service(web::resource("/").to(|ses: Session| async move {
510                    let _ = ses.set("counter", 100);
511                    "test"
512                })),
513        )
514        .await;
515
516        let request = test::TestRequest::get().to_request();
517        let response = app.call(request).await.unwrap();
518        assert!(response.cookies().any(|c| c.name() == "ntex-session"));
519    }
520
521    #[ntex::test]
522    async fn private_cookie() {
523        let app = test::init_service(
524            App::new()
525                .middleware(CookieSession::private(&[0; 32]).secure(false))
526                .service(web::resource("/").to(|ses: Session| async move {
527                    let _ = ses.set("counter", 100);
528                    "test"
529                })),
530        )
531        .await;
532
533        let request = test::TestRequest::get().to_request();
534        let response = app.call(request).await.unwrap();
535        assert!(response.cookies().any(|c| c.name() == "ntex-session"));
536    }
537
538    #[ntex::test]
539    async fn cookie_session_extractor() {
540        let app = test::init_service(
541            App::new()
542                .middleware(CookieSession::signed(&[0; 32]).secure(false))
543                .service(web::resource("/").to(|ses: Session| async move {
544                    let _ = ses.set("counter", 100);
545                    "test"
546                })),
547        )
548        .await;
549
550        let request = test::TestRequest::get().to_request();
551        let response = app.call(request).await.unwrap();
552        assert!(response.cookies().any(|c| c.name() == "ntex-session"));
553    }
554
555    #[ntex::test]
556    async fn basics() {
557        let app = test::init_service(
558            App::new()
559                .middleware(
560                    CookieSession::signed(&[0; 32])
561                        .path("/test/")
562                        .name("ntex-test")
563                        .domain("localhost")
564                        .http_only(true)
565                        .same_site(SameSite::Lax)
566                        .max_age(100),
567                )
568                .service(web::resource("/").to(|ses: Session| async move {
569                    let _ = ses.set("counter", 100);
570                    "test"
571                }))
572                .service(web::resource("/test/").to(|ses: Session| async move {
573                    let val: usize = ses.get("counter").unwrap().unwrap();
574                    format!("counter: {}", val)
575                })),
576        )
577        .await;
578
579        let request = test::TestRequest::get().to_request();
580        let response = app.call(request).await.unwrap();
581        let cookie = response
582            .cookies()
583            .find(|c| c.name() == "ntex-test")
584            .unwrap()
585            .into_owned();
586        assert_eq!(cookie.path().unwrap(), "/test/");
587
588        let request = test::TestRequest::with_uri("/test/")
589            .cookie(cookie)
590            .to_request();
591        let body = test::read_response(&app, request).await;
592        assert_eq!(body, Bytes::from_static(b"counter: 100"));
593    }
594
595    #[ntex::test]
596    async fn prolong_expiration() {
597        let app = test::init_service(
598            App::new()
599                .middleware(CookieSession::signed(&[0; 32]).secure(false).expires_in(60))
600                .service(web::resource("/").to(|ses: Session| async move {
601                    let _ = ses.set("counter", 100);
602                    "test"
603                }))
604                .service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
605        )
606        .await;
607
608        let request = test::TestRequest::get().to_request();
609        let response = app.call(request).await.unwrap();
610        let expires_1 = response
611            .cookies()
612            .find(|c| c.name() == "ntex-session")
613            .expect("Cookie is set")
614            .expires()
615            .expect("Expiration is set");
616
617        time::sleep(time::Seconds::ONE).await;
618
619        let request = test::TestRequest::with_uri("/test/").to_request();
620        let response = app.call(request).await.unwrap();
621        let expires_2 = response
622            .cookies()
623            .find(|c| c.name() == "ntex-session")
624            .expect("Cookie is set")
625            .expires()
626            .expect("Expiration is set");
627
628        assert!(
629            expires_2.datetime().unwrap() - expires_1.datetime().unwrap() >= Duration::seconds(1)
630        );
631    }
632
633    /// STATEMENT: The size limit applies to the encoded cookie, so a session whose
634    /// JSON is small but grows past 4096 bytes after signing and encoding is
635    /// rejected instead of being silently dropped by the browser.
636    ///
637    /// HOW:
638    /// - Store 1000 `"` characters: about 2 KB of JSON, but every `"` becomes
639    ///   `%5C%22` (6 bytes) in the cookie.
640    /// - Check the response is `500` and carries no `Set-Cookie`.
641    /// - Store 1000 plain characters and check the cookie is still set.
642    #[ntex::test]
643    async fn size_limit_applies_to_encoded_cookie() {
644        let app = test::init_service(
645            App::new()
646                .middleware(CookieSession::signed(&[0; 32]).secure(false))
647                .service(web::resource("/quotes").to(|ses: Session| async move {
648                    let _ = ses.set("v", "\"".repeat(1000));
649                    "test"
650                }))
651                .service(web::resource("/plain").to(|ses: Session| async move {
652                    let _ = ses.set("v", "a".repeat(1000));
653                    "test"
654                })),
655        )
656        .await;
657
658        let request = test::TestRequest::with_uri("/quotes").to_request();
659        let response = app.call(request).await.unwrap();
660        assert_eq!(
661            response.status(),
662            ntex::http::StatusCode::INTERNAL_SERVER_ERROR
663        );
664        assert!(!response.headers().contains_key(SET_COOKIE));
665
666        let request = test::TestRequest::with_uri("/plain").to_request();
667        let response = app.call(request).await.unwrap();
668        assert!(response.status().is_success());
669        assert!(response.cookies().any(|c| c.name() == "ntex-session"));
670    }
671
672    /// STATEMENT: The purge cookie carries the same `Secure`, `HttpOnly` and
673    /// `SameSite` attributes as the session cookie, so browsers accept it for
674    /// `__Host-` prefixed names.
675    ///
676    /// HOW:
677    /// - Configure a `__Host-session` cookie with `SameSite::Strict` and call
678    ///   `purge()` in the handler.
679    /// - Parse the `Set-Cookie` header and check the name, empty value, zero
680    ///   `Max-Age`, `Secure`, `HttpOnly`, `SameSite=Strict` and path `/`.
681    #[ntex::test]
682    async fn purge_cookie_keeps_security_attributes() {
683        let app = test::init_service(
684            App::new()
685                .middleware(
686                    CookieSession::signed(&[0; 32])
687                        .name("__Host-session")
688                        .same_site(SameSite::Strict),
689                )
690                .service(web::resource("/").to(|ses: Session| async move {
691                    ses.purge();
692                    "test"
693                })),
694        )
695        .await;
696
697        let request = test::TestRequest::get().to_request();
698        let response = app.call(request).await.unwrap();
699        let cookie = response
700            .cookies()
701            .find(|c| c.name() == "__Host-session")
702            .unwrap();
703        assert_eq!(cookie.value(), "");
704        assert_eq!(cookie.max_age(), Some(Duration::ZERO));
705        assert_eq!(cookie.secure(), Some(true));
706        assert_eq!(cookie.http_only(), Some(true));
707        assert_eq!(cookie.same_site(), Some(SameSite::Strict));
708        assert_eq!(cookie.path(), Some("/"));
709    }
710
711    fn protected_session_cookie(private: bool, key: &[u8], value: String) -> Cookie<'static> {
712        let mut jar = CookieJar::new();
713        let cookie = Cookie::new("ntex-session", value);
714        let key = Key::derive_from(key);
715        if private {
716            jar.private_mut(&key).add(cookie);
717        } else {
718            jar.signed_mut(&key).add(cookie);
719        }
720        jar.get("ntex-session").unwrap().clone()
721    }
722
723    /// STATEMENT: Signed and private sessions preserve values through renewal and reject invalid cookies.
724    ///
725    /// HOW:
726    /// - For each security policy, store a counter with custom cookie attributes and replay the cookie.
727    /// - Assert unchanged requests read the counter without reissuing cookies, while renewal preserves it and the attributes.
728    /// - Replay tampered, wrong-key, authenticated invalid JSON and malformed cookie headers; assert empty sessions and replacement cookies.
729    /// - Purge a valid session and assert the deletion retains its scope and security attributes with an expired lifetime.
730    #[ntex::test]
731    async fn protected_sessions_roundtrip_renew_reject_and_purge() {
732        for private in [false, true] {
733            let policy = if private {
734                CookieSession::private(&[0; 32])
735            } else {
736                CookieSession::signed(&[0; 32])
737            };
738            let app = test::init_service(
739                App::new()
740                    .middleware(
741                        policy
742                            .path("/account")
743                            .domain("localhost")
744                            .http_only(false)
745                            .same_site(SameSite::Strict)
746                            .max_age(120),
747                    )
748                    .service(web::resource("/write").to(|ses: Session| async move {
749                        ses.set("counter", 42).unwrap();
750                        "stored"
751                    }))
752                    .service(web::resource("/read").to(|ses: Session| async move {
753                        web::types::Json(ses.get::<u32>("counter").unwrap())
754                    }))
755                    .service(web::resource("/renew").to(|ses: Session| async move {
756                        ses.renew();
757                        web::types::Json(ses.get::<u32>("counter").unwrap())
758                    }))
759                    .service(web::resource("/purge").to(|ses: Session| async move {
760                        ses.purge();
761                        "purged"
762                    })),
763            )
764            .await;
765
766            let response = app
767                .call(test::TestRequest::with_uri("/write").to_request())
768                .await
769                .unwrap();
770            let cookie = response.cookies().next().unwrap().into_owned();
771            let response = app
772                .call(
773                    test::TestRequest::with_uri("/read")
774                        .cookie(cookie.clone())
775                        .to_request(),
776                )
777                .await
778                .unwrap();
779            assert!(!response.headers().contains_key(SET_COOKIE));
780            assert_eq!(test::read_body(response).await.as_ref(), b"42");
781
782            let response = app
783                .call(
784                    test::TestRequest::with_uri("/renew")
785                        .cookie(cookie.clone())
786                        .to_request(),
787                )
788                .await
789                .unwrap();
790            let renewed = response.cookies().next().unwrap().into_owned();
791            assert_eq!(renewed.path(), Some("/account"));
792            assert_eq!(renewed.domain(), Some("localhost"));
793            assert_eq!(renewed.secure(), Some(true));
794            assert_ne!(renewed.http_only(), Some(true));
795            assert_eq!(renewed.same_site(), Some(SameSite::Strict));
796            assert_eq!(renewed.max_age(), Some(Duration::seconds(120)));
797            assert_eq!(test::read_body(response).await.as_ref(), b"42");
798            let response = app
799                .call(
800                    test::TestRequest::with_uri("/read")
801                        .cookie(renewed)
802                        .to_request(),
803                )
804                .await
805                .unwrap();
806            assert!(!response.headers().contains_key(SET_COOKIE));
807            assert_eq!(test::read_body(response).await.as_ref(), b"42");
808
809            let mut tampered = cookie.clone();
810            tampered.set_value(format!("{}tampered", tampered.value()));
811            let invalid = [
812                tampered,
813                protected_session_cookie(private, &[1; 32], r#"{"counter":"42"}"#.to_owned()),
814                protected_session_cookie(private, &[0; 32], "not-json".to_owned()),
815                protected_session_cookie(private, &[0; 32], r#"{"counter":42}"#.to_owned()),
816            ];
817            for invalid in invalid {
818                let response = app
819                    .call(
820                        test::TestRequest::with_uri("/read")
821                            .cookie(Cookie::new("unrelated", "value"))
822                            .cookie(invalid)
823                            .to_request(),
824                    )
825                    .await
826                    .unwrap();
827                assert!(response.status().is_success());
828                assert!(response.cookies().any(|c| c.name() == "ntex-session"));
829                assert_eq!(test::read_body(response).await.as_ref(), b"null");
830            }
831            let response = app
832                .call(
833                    test::TestRequest::with_uri("/read")
834                        .header(
835                            ntex::http::header::COOKIE,
836                            HeaderValue::from_bytes(b"\xff").unwrap(),
837                        )
838                        .to_request(),
839                )
840                .await
841                .unwrap();
842            assert!(response.status().is_success());
843            assert!(response.cookies().any(|c| c.name() == "ntex-session"));
844            assert_eq!(test::read_body(response).await.as_ref(), b"null");
845
846            let response = app
847                .call(
848                    test::TestRequest::with_uri("/purge")
849                        .cookie(cookie)
850                        .to_request(),
851                )
852                .await
853                .unwrap();
854            let deleted = response.cookies().next().unwrap();
855            assert_eq!(deleted.value(), "");
856            assert_eq!(deleted.path(), Some("/account"));
857            assert_eq!(deleted.domain(), Some("localhost"));
858            assert_eq!(deleted.secure(), Some(true));
859            assert_ne!(deleted.http_only(), Some(true));
860            assert_eq!(deleted.same_site(), Some(SameSite::Strict));
861            assert_eq!(deleted.max_age(), Some(Duration::ZERO));
862            assert!(deleted.expires().unwrap().datetime().unwrap() < OffsetDateTime::now_utc());
863        }
864    }
865
866    /// STATEMENT: Cookie size errors become server-error responses even without session mutations.
867    ///
868    /// HOW:
869    /// - Replay an authenticated oversized session to a policy with sliding expiration and no handler mutations.
870    /// - Request a new session with a cookie name exceeding the size limit.
871    /// - Assert both responses are `500` without `Set-Cookie` headers.
872    #[ntex::test]
873    async fn unchanged_sessions_report_cookie_size_errors() {
874        let app = test::init_service(
875            App::new()
876                .middleware(CookieSession::signed(&[0; 32]).expires_in(60))
877                .service(web::resource("/").to(|| async { "unchanged" })),
878        )
879        .await;
880        let state = HashMap::from([("large", serde_json::to_string(&"a".repeat(4096)).unwrap())]);
881        let cookie =
882            protected_session_cookie(false, &[0; 32], serde_json::to_string(&state).unwrap());
883        let response = app
884            .call(test::TestRequest::get().cookie(cookie).to_request())
885            .await
886            .unwrap();
887        assert_eq!(
888            response.status(),
889            ntex::http::StatusCode::INTERNAL_SERVER_ERROR
890        );
891        assert!(!response.headers().contains_key(SET_COOKIE));
892
893        let app = test::init_service(
894            App::new()
895                .middleware(CookieSession::signed(&[0; 32]).name("a".repeat(4096)))
896                .service(web::resource("/").to(|| async { "unchanged" })),
897        )
898        .await;
899        let response = app
900            .call(test::TestRequest::get().to_request())
901            .await
902            .unwrap();
903        assert_eq!(
904            response.status(),
905            ntex::http::StatusCode::INTERNAL_SERVER_ERROR
906        );
907        assert!(!response.headers().contains_key(SET_COOKIE));
908    }
909
910    /// STATEMENT: A `Path` that cannot be sent in `Set-Cookie` is rejected when configured.
911    ///
912    /// HOW:
913    /// - Configure a path containing a newline.
914    /// - Confirm `path` panics instead of a later request panicking.
915    #[test]
916    #[should_panic(expected = "invalid session cookie path")]
917    fn invalid_path_is_rejected_by_builder() {
918        let _ = CookieSession::signed(&[0; 32]).path("/\n");
919    }
920
921    /// STATEMENT: A `Domain` that would inject another cookie attribute is rejected when configured.
922    ///
923    /// HOW:
924    /// - Configure a domain containing `;`.
925    /// - Confirm `domain` panics instead of emitting an extra attribute.
926    #[test]
927    #[should_panic(expected = "invalid session cookie domain")]
928    fn domain_with_separator_is_rejected_by_builder() {
929        let _ = CookieSession::signed(&[0; 32]).domain("example.com; HttpOnly");
930    }
931}