Skip to main content

hyperlane_plugin_session/
impl.rs

1use super::*;
2
3/// Implements [`Hasher`] for [`SessionFxHasher`].
4impl Hasher for SessionFxHasher {
5    /// Returns the accumulated 64-bit hash digest.
6    ///
7    /// # Returns
8    ///
9    /// - `u64` - Finalized hash value.
10    #[inline(always)]
11    fn finish(&self) -> u64 {
12        let Self { hash } = self;
13        *hash
14    }
15
16    /// Absorbs `bytes` into the hash state using 8-byte word mixing.
17    ///
18    /// # Arguments
19    ///
20    /// - `&[u8]` - Input byte slice.
21    #[inline(always)]
22    fn write(&mut self, bytes: &[u8]) {
23        let Self { hash } = self;
24        let word: u64 = fx_hash_bytes(bytes);
25        *hash = (hash.rotate_left(5) ^ word).wrapping_mul(FX_HASH_K);
26    }
27
28    /// Absorbs a single `usize` word directly.
29    ///
30    /// # Arguments
31    ///
32    /// - `usize` - Input integer.
33    #[inline(always)]
34    fn write_usize(&mut self, i: usize) {
35        let Self { hash } = self;
36        *hash = (hash.rotate_left(5) ^ (i as u64)).wrapping_mul(FX_HASH_K);
37    }
38}
39
40/// Implements [`BuildHasher`] for [`SessionFxBuildHasher`].
41impl BuildHasher for SessionFxBuildHasher {
42    type Hasher = SessionFxHasher;
43
44    /// Constructs a fresh [`SessionFxHasher`] with zero state.
45    ///
46    /// # Returns
47    ///
48    /// - `Self::Hasher` - Zero-initialized hasher.
49    #[inline(always)]
50    fn build_hasher(&self) -> Self::Hasher {
51        SessionFxHasher { hash: 0 }
52    }
53}
54
55/// Default construction for [`SessionConfig`].
56impl Default for SessionConfig {
57    /// Constructs a secure default [`SessionConfig`] (`HttpOnly`, `SameSite=Lax`, 1 hour TTL).
58    fn default() -> Self {
59        Self {
60            cookie_name: DEFAULT_SESSION_COOKIE_NAME.to_owned(),
61            cookie_path: DEFAULT_SESSION_COOKIE_PATH.to_owned(),
62            cookie_domain: None,
63            same_site: DEFAULT_SESSION_SAME_SITE.to_owned(),
64            http_only: true,
65            secure: true,
66            ttl_secs: DEFAULT_SESSION_TTL_SECS,
67            max_sessions: DEFAULT_MAX_SESSIONS,
68            signing_secret: None,
69        }
70    }
71}
72
73/// Inherent fluent builders for [`SessionConfig`].
74impl SessionConfig {
75    /// Sets the session cookie name.
76    ///
77    /// # Arguments
78    ///
79    /// - `N` - Cookie name convertible into `String`.
80    ///
81    /// # Returns
82    ///
83    /// - `Self` - Updated configuration.
84    pub fn with_cookie_name<N>(mut self, name: N) -> Self
85    where
86        N: Into<String>,
87    {
88        self.set_cookie_name(name.into());
89        self
90    }
91
92    /// Sets the HMAC-SHA256 signing secret used to tamper-proof session cookies.
93    ///
94    /// # Arguments
95    ///
96    /// - `S` - Secret bytes convertible into `Vec<u8>`.
97    ///
98    /// # Returns
99    ///
100    /// - `Self` - Updated configuration.
101    pub fn with_signing_secret<S>(mut self, secret: S) -> Self
102    where
103        S: Into<Vec<u8>>,
104    {
105        self.set_signing_secret(Some(secret.into()));
106        self
107    }
108
109    /// Sets the session TTL in seconds.
110    ///
111    /// # Arguments
112    ///
113    /// - `u64` - Session TTL in seconds.
114    ///
115    /// # Returns
116    ///
117    /// - `Self` - Updated configuration.
118    pub fn with_ttl_secs(mut self, ttl_secs: u64) -> Self {
119        self.set_ttl_secs(ttl_secs);
120        self
121    }
122
123    /// Sets whether the `Secure` attribute is emitted on session cookies.
124    ///
125    /// # Arguments
126    ///
127    /// - `bool` - `true` for HTTPS-only cookies.
128    ///
129    /// # Returns
130    ///
131    /// - `Self` - Updated configuration.
132    pub fn with_secure(mut self, secure: bool) -> Self {
133        self.set_secure(secure);
134        self
135    }
136}
137
138/// Inherent implementation of [`SessionHandle`].
139impl SessionHandle {
140    /// Constructs a [`SessionHandle`] wrapping an existing or newly created session.
141    ///
142    /// # Arguments
143    ///
144    /// - `String` - Active session identifier.
145    /// - `Arc<HashMap<String, String>>` - Shared loaded session values.
146    /// - `bool` - Whether this session already existed in the store.
147    ///
148    /// # Returns
149    ///
150    /// - `Self` - Ready session handle.
151    pub(crate) fn new(id: String, values: Arc<HashMap<String, String>>, existed: bool) -> Self {
152        Self {
153            inner: Arc::new(SessionHandleInner {
154                dirty: AtomicBool::new(false),
155                state: Mutex::new(SessionState {
156                    id,
157                    previous_id: None,
158                    values,
159                    existed,
160                    dirty: false,
161                    destroyed: false,
162                }),
163            }),
164        }
165    }
166
167    /// Returns the current session identifier.
168    ///
169    /// # Returns
170    ///
171    /// - `String` - Session ID.
172    pub fn id(&self) -> String {
173        let Self { inner } = self;
174        inner
175            .state
176            .lock()
177            .map(|guard: MutexGuard<'_, SessionState>| guard.id.clone())
178            .unwrap_or_default()
179    }
180
181    /// Reads one attribute from the session without marking it dirty.
182    ///
183    /// # Arguments
184    ///
185    /// - `&str` - Attribute key.
186    ///
187    /// # Returns
188    ///
189    /// - `Option<String>` - Stored attribute value, if present.
190    pub fn get(&self, key: &str) -> Option<String> {
191        let Self { inner } = self;
192        inner
193            .state
194            .lock()
195            .ok()
196            .and_then(|guard: MutexGuard<'_, SessionState>| guard.values.get(key).cloned())
197    }
198
199    /// Inserts or updates a session attribute and marks the session dirty for persistence.
200    ///
201    /// # Arguments
202    ///
203    /// - `K` - Attribute key convertible into `String`.
204    /// - `V` - Attribute value convertible into `String`.
205    pub fn insert<K, V>(&self, key: K, value: V)
206    where
207        K: Into<String>,
208        V: Into<String>,
209    {
210        let Self { inner } = self;
211        if let Ok(mut guard) = inner.state.lock() {
212            Arc::make_mut(&mut guard.values).insert(key.into(), value.into());
213            guard.dirty = true;
214            guard.destroyed = false;
215            inner.dirty.store(true, Ordering::Release);
216        }
217    }
218
219    /// Removes a session attribute and marks the session dirty when present.
220    ///
221    /// # Arguments
222    ///
223    /// - `&str` - Attribute key to remove.
224    ///
225    /// # Returns
226    ///
227    /// - `Option<String>` - Removed value, if any.
228    pub fn remove(&self, key: &str) -> Option<String> {
229        let Self { inner } = self;
230        let mut guard: MutexGuard<'_, SessionState> = inner.state.lock().ok()?;
231        if !guard.values.contains_key(key) {
232            return None;
233        }
234        let removed: Option<String> = Arc::make_mut(&mut guard.values).remove(key);
235        if removed.is_some() {
236            guard.dirty = true;
237            inner.dirty.store(true, Ordering::Release);
238        }
239        removed
240    }
241
242    /// Mints a fresh unpredictable session ID (session-fixation defense) and marks the session dirty.
243    ///
244    /// # Returns
245    ///
246    /// - `String` - Newly generated session identifier.
247    pub fn regenerate_id(&self) -> String {
248        let Self { inner } = self;
249        let next_id: String = generate_session_id();
250        if let Ok(mut guard) = inner.state.lock() {
251            if guard.previous_id.is_none() && guard.existed {
252                guard.previous_id = Some(guard.id.clone());
253            }
254            guard.id = next_id.clone();
255            guard.dirty = true;
256            guard.destroyed = false;
257            inner.dirty.store(true, Ordering::Release);
258        }
259        next_id
260    }
261
262    /// Marks the session for deletion and clears its in-memory attributes.
263    pub fn destroy(&self) {
264        let Self { inner } = self;
265        if let Ok(mut guard) = inner.state.lock() {
266            guard.values = Arc::clone(empty_session_values());
267            guard.destroyed = true;
268            guard.dirty = true;
269            inner.dirty.store(true, Ordering::Release);
270        }
271    }
272
273    /// Reports whether this session has been modified during the current request.
274    ///
275    /// # Returns
276    ///
277    /// - `bool` - `true` when dirty.
278    #[inline]
279    pub fn is_dirty(&self) -> bool {
280        let Self { inner } = self;
281        inner.dirty.load(Ordering::Acquire)
282    }
283
284    /// Captures a snapshot of the internal [`SessionState`] only when dirty.
285    ///
286    /// # Returns
287    ///
288    /// - `Option<SessionState>` - Cloned state snapshot when dirty, or `None` for clean reads.
289    #[inline]
290    pub(crate) fn snapshot_if_dirty(&self) -> Option<SessionState> {
291        let Self { inner } = self;
292        if !inner.dirty.load(Ordering::Acquire) {
293            return None;
294        }
295        inner
296            .state
297            .lock()
298            .ok()
299            .and_then(|guard: MutexGuard<'_, SessionState>| {
300                if guard.dirty {
301                    Some(guard.clone())
302                } else {
303                    None
304                }
305            })
306    }
307}
308
309/// Default construction for [`InMemorySessionStore`].
310impl Default for InMemorySessionStore {
311    /// Constructs a default 64-shard [`InMemorySessionStore`].
312    fn default() -> Self {
313        Self::new(DEFAULT_MAX_SESSIONS)
314    }
315}
316
317/// Inherent implementation of [`InMemorySessionStore`].
318impl InMemorySessionStore {
319    /// Creates a 64-way cache-aligned sharded bounded [`InMemorySessionStore`] capped at `max_sessions`.
320    ///
321    /// # Arguments
322    ///
323    /// - `usize` - Maximum concurrent tracked sessions.
324    ///
325    /// # Returns
326    ///
327    /// - `Self` - Ready sharded session store.
328    pub fn new(max_sessions: usize) -> Self {
329        let shards: Box<[SessionShard; SESSION_SHARD_COUNT]> =
330            Box::new(from_fn(|_: usize| SessionShard {
331                map: RwLock::new(HashMap::with_hasher(SessionFxBuildHasher)),
332            }));
333        Self {
334            inner: Arc::new(InMemorySessionStoreInner {
335                max_sessions: max_sessions.max(1),
336                count: AtomicUsize::new(0),
337                shards,
338            }),
339        }
340    }
341
342    /// Returns the number of tracked sessions across all shards in `O(1)` time.
343    ///
344    /// # Returns
345    ///
346    /// - `usize` - Active tracked session count.
347    #[inline]
348    pub fn len(&self) -> usize {
349        let Self { inner } = self;
350        inner.count.load(Ordering::Relaxed)
351    }
352
353    /// Reports whether zero sessions are currently stored.
354    ///
355    /// # Returns
356    ///
357    /// - `bool` - `true` when empty.
358    #[inline]
359    pub fn is_empty(&self) -> bool {
360        self.len() == 0
361    }
362
363    /// Loads an unexpired shared session snapshot synchronously without cloning the underlying map.
364    ///
365    /// # Arguments
366    ///
367    /// - `&str` - Session identifier.
368    ///
369    /// # Returns
370    ///
371    /// - `Option<Arc<HashMap<String, String>>>` - Shared session attributes if live.
372    #[inline]
373    pub(crate) fn load_sync_shared(
374        &self,
375        session_id: &str,
376    ) -> Option<Arc<HashMap<String, String>>> {
377        let Self { inner } = self;
378        let idx: usize = session_shard_index(session_id);
379        let mut expired: bool = false;
380        if let Ok(map) = inner.shards[idx].map.read() {
381            let entry: &StoredSession = map.get(session_id)?;
382            let now: u64 = session_now_secs();
383            if now < entry.expires_at_secs {
384                return Some(Arc::clone(&entry.values));
385            }
386            expired = true;
387        }
388        if expired
389            && let Ok(mut map) = inner.shards[idx].map.write()
390            && map.remove(session_id).is_some()
391        {
392            inner.count.fetch_sub(1, Ordering::Relaxed);
393        }
394        None
395    }
396
397    /// Saves a shared session snapshot synchronously by borrowed ID, updating existing keys in place without cloning.
398    ///
399    /// # Arguments
400    ///
401    /// - `&str` - Session identifier.
402    /// - `Arc<HashMap<String, String>>` - Shared session attributes.
403    /// - `u64` - TTL in seconds.
404    #[inline]
405    pub(crate) fn save_sync_shared(
406        &self,
407        session_id: &str,
408        values: Arc<HashMap<String, String>>,
409        ttl_secs: u64,
410    ) {
411        let Self { inner } = self;
412        let now: u64 = session_now_secs();
413        if inner.count.load(Ordering::Relaxed) >= inner.max_sessions {
414            let _: usize = self.purge_expired();
415        }
416        let idx: usize = session_shard_index(session_id);
417        let expires_at_secs: u64 = now.saturating_add(ttl_secs.max(1));
418        if let Ok(mut map) = inner.shards[idx].map.write() {
419            if let Some(existing) = map.get_mut(session_id) {
420                existing.values = values;
421                existing.expires_at_secs = expires_at_secs;
422            } else if inner.count.load(Ordering::Relaxed) < inner.max_sessions {
423                map.insert(
424                    session_id.to_owned(),
425                    StoredSession {
426                        values,
427                        expires_at_secs,
428                    },
429                );
430                inner.count.fetch_add(1, Ordering::Relaxed);
431            }
432        }
433    }
434
435    /// Saves an owned session ID synchronously into its owning shard via a single entry lookup.
436    ///
437    /// # Arguments
438    ///
439    /// - `String` - Owned session identifier.
440    /// - `Arc<HashMap<String, String>>` - Shared session attributes.
441    /// - `u64` - TTL in seconds.
442    #[inline]
443    pub(crate) fn save_sync_owned(
444        &self,
445        session_id: String,
446        values: Arc<HashMap<String, String>>,
447        ttl_secs: u64,
448    ) {
449        let Self { inner } = self;
450        let now: u64 = session_now_secs();
451        if inner.count.load(Ordering::Relaxed) >= inner.max_sessions {
452            let _: usize = self.purge_expired();
453        }
454        let idx: usize = session_shard_index(&session_id);
455        let expires_at_secs: u64 = now.saturating_add(ttl_secs.max(1));
456        if let Ok(mut map) = inner.shards[idx].map.write() {
457            match map.entry(session_id) {
458                Entry::Occupied(mut occupied) => {
459                    occupied.insert(StoredSession {
460                        values,
461                        expires_at_secs,
462                    });
463                }
464                Entry::Vacant(vacant) => {
465                    if inner.count.load(Ordering::Relaxed) < inner.max_sessions {
466                        vacant.insert(StoredSession {
467                            values,
468                            expires_at_secs,
469                        });
470                        inner.count.fetch_add(1, Ordering::Relaxed);
471                    }
472                }
473            }
474        }
475    }
476
477    /// Deletes a session synchronously from its owning shard.
478    ///
479    /// # Arguments
480    ///
481    /// - `&str` - Session identifier.
482    ///
483    /// # Returns
484    ///
485    /// - `bool` - `true` when an entry existed and was deleted.
486    #[inline]
487    pub(crate) fn delete_sync(&self, session_id: &str) -> bool {
488        let Self { inner } = self;
489        let idx: usize = session_shard_index(session_id);
490        let removed: bool = inner.shards[idx]
491            .map
492            .write()
493            .ok()
494            .and_then(
495                |mut map: RwLockWriteGuard<'_, SessionFxHashMap<String, StoredSession>>| {
496                    map.remove(session_id)
497                },
498            )
499            .is_some();
500        if removed {
501            inner.count.fetch_sub(1, Ordering::Relaxed);
502        }
503        removed
504    }
505}
506
507/// Implements [`SessionStore`] for [`InMemorySessionStore`].
508impl SessionStore for InMemorySessionStore {
509    /// Loads an unexpired session from its single owning shard.
510    ///
511    /// # Arguments
512    ///
513    /// - `&'a self` - Shared reference to self.
514    /// - `&'a str` - Session identifier.
515    ///
516    /// # Returns
517    ///
518    /// - `SessionFuture<'a, Option<HashMap<String, String>>>` - Attributes when live.
519    fn load<'a>(
520        &'a self,
521        session_id: &'a str,
522    ) -> SessionFuture<'a, Option<HashMap<String, String>>> {
523        let outcome: Option<HashMap<String, String>> = self
524            .load_sync_shared(session_id)
525            .map(|values: Arc<HashMap<String, String>>| (*values).clone());
526        Box::pin(async move { outcome })
527    }
528
529    /// Saves a session into its owning shard while enforcing `max_sessions`.
530    ///
531    /// # Arguments
532    ///
533    /// - `String` - Session identifier.
534    /// - `HashMap<String, String>` - Session attributes.
535    /// - `u64` - TTL in seconds.
536    ///
537    /// # Returns
538    ///
539    /// - `SessionFuture<'_, ()>` - Completion future.
540    fn save(
541        &self,
542        session_id: String,
543        values: HashMap<String, String>,
544        ttl_secs: u64,
545    ) -> SessionFuture<'_, ()> {
546        self.save_sync_owned(session_id, Arc::new(values), ttl_secs);
547        Box::pin(async {})
548    }
549
550    /// Deletes a session from its owning shard.
551    ///
552    /// # Arguments
553    ///
554    /// - `&'a self` - Shared reference to self.
555    /// - `&'a str` - Session identifier.
556    ///
557    /// # Returns
558    ///
559    /// - `SessionFuture<'a, bool>` - `true` if deleted.
560    fn delete<'a>(&'a self, session_id: &'a str) -> SessionFuture<'a, bool> {
561        let removed: bool = self.delete_sync(session_id);
562        Box::pin(async move { removed })
563    }
564
565    /// Evicts expired sessions across all 64 shards.
566    ///
567    /// # Returns
568    ///
569    /// - `usize` - Number of expired sessions purged.
570    fn purge_expired(&self) -> usize {
571        let Self { inner } = self;
572        let now: u64 = session_now_secs();
573        let mut evicted: usize = 0;
574        for shard in inner.shards.iter() {
575            let non_empty: bool = shard
576                .map
577                .read()
578                .map(
579                    |map: RwLockReadGuard<'_, SessionFxHashMap<String, StoredSession>>| {
580                        !map.is_empty()
581                    },
582                )
583                .unwrap_or(false);
584            if !non_empty {
585                continue;
586            }
587            if let Ok(mut map) = shard.map.write() {
588                let before: usize = map.len();
589                map.retain(|_: &String, entry: &mut StoredSession| now < entry.expires_at_secs);
590                evicted += before.saturating_sub(map.len());
591            }
592        }
593        if evicted > 0 {
594            inner.count.fetch_sub(evicted, Ordering::Relaxed);
595        }
596        evicted
597    }
598}
599
600/// Inherent implementation of [`SessionCompiled`].
601impl SessionCompiled {
602    /// Precomputes HMAC key states and `Set-Cookie` templates once from `config`.
603    ///
604    /// # Arguments
605    ///
606    /// - `&SessionConfig` - Session configuration to compile.
607    ///
608    /// # Returns
609    ///
610    /// - `Self` - Precompiled cookie and signing templates.
611    pub(crate) fn from_config(config: &SessionConfig) -> Self {
612        let valid_cookie_name: bool = is_valid_cookie_name(config.get_cookie_name());
613        let hmac_key: Option<HmacSha256Key> = config
614            .get_signing_secret()
615            .map(|secret: Vec<u8>| precompute_hmac_sha256_key(&secret));
616        let mut live_builder: CookieBuilder =
617            CookieBuilder::new(config.get_cookie_name(), COOKIE_TEMPLATE_VALUE);
618        live_builder
619            .set_path(config.get_cookie_path())
620            .set_same_site(config.get_same_site());
621        if let Some(domain) = config.get_cookie_domain() {
622            live_builder.set_domain(domain);
623        }
624        if config.get_http_only() {
625            live_builder.http_only();
626        }
627        if config.get_secure() {
628            live_builder.secure();
629        }
630        live_builder.set_max_age(config.get_ttl_secs() as i64);
631        let live_sample: String = live_builder.build();
632        let mut clear_builder: CookieBuilder = CookieBuilder::new(config.get_cookie_name(), "");
633        clear_builder
634            .set_path(config.get_cookie_path())
635            .set_same_site(config.get_same_site());
636        if let Some(domain) = config.get_cookie_domain() {
637            clear_builder.set_domain(domain);
638        }
639        if config.get_http_only() {
640            clear_builder.http_only();
641        }
642        if config.get_secure() {
643            clear_builder.secure();
644        }
645        clear_builder.set_max_age(0i64);
646        let clear_cookie: String = clear_builder.build();
647        let prefix_len: usize = config.get_cookie_name().len() + 1;
648        let sentinel_end: usize = prefix_len + COOKIE_TEMPLATE_VALUE.len();
649        if live_sample.len() >= sentinel_end {
650            Self {
651                hmac_key,
652                cookie_prefix: live_sample[..prefix_len].to_owned(),
653                cookie_suffix: live_sample[sentinel_end..].to_owned(),
654                clear_cookie,
655                valid_cookie_config: true,
656                valid_cookie_name,
657            }
658        } else {
659            Self {
660                hmac_key,
661                cookie_prefix: String::new(),
662                cookie_suffix: String::new(),
663                clear_cookie,
664                valid_cookie_config: false,
665                valid_cookie_name,
666            }
667        }
668    }
669}
670
671/// Inherent implementation of [`SessionPlugin`].
672impl SessionPlugin {
673    /// Constructs a [`SessionPlugin`] with precompiled cookie templates and optional direct store fast path.
674    ///
675    /// # Arguments
676    ///
677    /// - `SessionConfig` - Session configuration.
678    /// - `Arc<dyn SessionStore>` - Backing session store.
679    /// - `Option<InMemorySessionStore>` - Optional built-in store handle for sync fast path.
680    ///
681    /// # Returns
682    ///
683    /// - `Self` - Constructed session plugin instance.
684    pub(crate) fn from_parts(
685        config: SessionConfig,
686        store: Arc<dyn SessionStore>,
687        fast_store: Option<InMemorySessionStore>,
688    ) -> Self {
689        let compiled: Arc<SessionCompiled> = Arc::new(SessionCompiled::from_config(&config));
690        Self {
691            config,
692            store,
693            compiled,
694            fast_store,
695        }
696    }
697
698    /// Initializes the global [`SessionPlugin`] once with `config` and the default [`InMemorySessionStore`].
699    ///
700    /// # Arguments
701    ///
702    /// - `SessionConfig` - Cookie and session policy.
703    ///
704    /// # Returns
705    ///
706    /// - `&'static Self` - Reference to the initialized global plugin.
707    pub fn init(config: SessionConfig) -> &'static Self {
708        let mem_store: InMemorySessionStore = InMemorySessionStore::new(config.get_max_sessions());
709        let store: Arc<dyn SessionStore> = Arc::new(mem_store.clone());
710        SESSION_PLUGIN.get_or_init(|| Self::from_parts(config, store, Some(mem_store)))
711    }
712
713    /// Initializes the global [`SessionPlugin`] once with `config` and a custom [`SessionStore`].
714    ///
715    /// # Arguments
716    ///
717    /// - `SessionConfig` - Cookie and session policy.
718    /// - `Arc<dyn SessionStore>` - Pluggable session store backend.
719    ///
720    /// # Returns
721    ///
722    /// - `&'static Self` - Reference to the initialized global plugin.
723    pub fn init_with_store(config: SessionConfig, store: Arc<dyn SessionStore>) -> &'static Self {
724        SESSION_PLUGIN.get_or_init(|| Self::from_parts(config, store, None))
725    }
726
727    /// Returns the initialized global [`SessionPlugin`], if initialized.
728    ///
729    /// # Returns
730    ///
731    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
732    pub fn get() -> Option<&'static Self> {
733        SESSION_PLUGIN.get()
734    }
735
736    /// Returns the active [`SessionConfig`].
737    ///
738    /// # Returns
739    ///
740    /// - `&SessionConfig` - Active session configuration.
741    pub fn get_config(&self) -> &SessionConfig {
742        &self.config
743    }
744
745    /// Returns the active [`Arc<dyn SessionStore>`].
746    ///
747    /// # Returns
748    ///
749    /// - `&Arc<dyn SessionStore>` - Active backing store.
750    pub fn get_store(&self) -> &Arc<dyn SessionStore> {
751        &self.store
752    }
753
754    /// Retrieves the active [`SessionHandle`] stored in `ctx`.
755    ///
756    /// # Arguments
757    ///
758    /// - `&Context` - Request context.
759    ///
760    /// # Returns
761    ///
762    /// - `Option<SessionHandle>` - Per-request session handle, if session middleware ran.
763    pub fn current(ctx: &Context) -> Option<SessionHandle> {
764        ctx.try_get_attribute(ATTR_SESSION_HANDLE)
765    }
766
767    /// Formats a `Set-Cookie` header value into a stack buffer when it fits, avoiding heap allocation.
768    ///
769    /// # Arguments
770    ///
771    /// - `&str` - Session identifier.
772    /// - `&'a mut [u8; SET_COOKIE_STACK_CAP]` - Stack destination buffer.
773    ///
774    /// # Returns
775    ///
776    /// - `Option<&'a str>` - Borrowed formatted cookie value when it fits on the stack.
777    #[inline]
778    fn format_live_set_cookie_stack<'a>(
779        &self,
780        session_id: &str,
781        buf: &'a mut [u8; SET_COOKIE_STACK_CAP],
782    ) -> Option<&'a str> {
783        let Self { compiled, .. } = self;
784        if !compiled.valid_cookie_config || !is_valid_set_cookie_value(session_id) {
785            return Some("");
786        }
787        let sig_extra: usize = if compiled.hmac_key.is_some() { 65 } else { 0 };
788        let total: usize = compiled.cookie_prefix.len()
789            + session_id.len()
790            + sig_extra
791            + compiled.cookie_suffix.len();
792        if total > SET_COOKIE_STACK_CAP {
793            return None;
794        }
795        let mut pos: usize = 0;
796        let prefix: &[u8] = compiled.cookie_prefix.as_bytes();
797        buf[pos..pos + prefix.len()].copy_from_slice(prefix);
798        pos += prefix.len();
799        let sid_bytes: &[u8] = session_id.as_bytes();
800        buf[pos..pos + sid_bytes.len()].copy_from_slice(sid_bytes);
801        pos += sid_bytes.len();
802        if let Some(key) = &compiled.hmac_key {
803            buf[pos] = BYTE_DOT;
804            pos += 1;
805            let mac: [u8; 32] = hmac_sha256_with_key(key, sid_bytes);
806            let hex: [u8; 64] = encode_hex_32_stack(&mac);
807            buf[pos..pos + hex.len()].copy_from_slice(&hex);
808            pos += hex.len();
809        }
810        let suffix: &[u8] = compiled.cookie_suffix.as_bytes();
811        buf[pos..pos + suffix.len()].copy_from_slice(suffix);
812        pos += suffix.len();
813        from_utf8(&buf[..pos]).ok()
814    }
815
816    /// Formats a `Set-Cookie` header value for `session_id` (or an expiration cookie when `clear` is `true`).
817    ///
818    /// # Arguments
819    ///
820    /// - `&str` - Session identifier.
821    /// - `bool` - When `true`, emits `Max-Age=0` with empty value to clear the client cookie.
822    ///
823    /// # Returns
824    ///
825    /// - `String` - Formatted `Set-Cookie` header value.
826    #[inline]
827    pub fn build_set_cookie(&self, session_id: &str, clear: bool) -> String {
828        let Self { compiled, .. } = self;
829        if !compiled.valid_cookie_config {
830            return String::new();
831        }
832        if clear {
833            return compiled.clear_cookie.clone();
834        }
835        if !is_valid_set_cookie_value(session_id) {
836            return String::new();
837        }
838        let sig_extra: usize = if compiled.hmac_key.is_some() { 65 } else { 0 };
839        let total: usize = compiled.cookie_prefix.len()
840            + session_id.len()
841            + sig_extra
842            + compiled.cookie_suffix.len();
843        let mut out: String = String::with_capacity(total);
844        out.push_str(&compiled.cookie_prefix);
845        out.push_str(session_id);
846        if let Some(key) = &compiled.hmac_key {
847            let mac: [u8; 32] = hmac_sha256_with_key(key, session_id.as_bytes());
848            let hex: [u8; 64] = encode_hex_32_stack(&mac);
849            out.push(COOKIE_SIG_DELIMITER);
850            if let Ok(sig) = from_utf8(&hex) {
851                out.push_str(sig);
852            }
853        }
854        out.push_str(&compiled.cookie_suffix);
855        out
856    }
857
858    /// Installs or resets the per-request [`SessionHandle`] in `ctx`, reusing unique attribute slots without heap allocation.
859    ///
860    /// # Arguments
861    ///
862    /// - `&mut Context` - Request context.
863    /// - `&str` - Session identifier slice.
864    /// - `Option<String>` - Optional already-owned session identifier for overflow fallback.
865    /// - `Arc<HashMap<String, String>>` - Loaded or shared empty session attributes.
866    /// - `bool` - Whether the session already existed in the store.
867    ///
868    /// # Returns
869    ///
870    /// - `SessionHandle` - Active handle installed on `ctx`.
871    #[inline]
872    fn install_handle(
873        ctx: &mut Context,
874        sid: &str,
875        owned_sid: Option<String>,
876        values: Arc<HashMap<String, String>>,
877        existed: bool,
878    ) -> SessionHandle {
879        if let Some(slot) = ctx
880            .get_mut_attributes()
881            .get_mut(ATTR_SESSION_HANDLE_MAP_KEY)
882        {
883            if let Some(any_mut) = Arc::get_mut(slot)
884                && let Some(existing) = any_mut.downcast_mut::<SessionHandle>()
885            {
886                if let Some(inner_mut) = Arc::get_mut(&mut existing.inner)
887                    && let Ok(state) = inner_mut.state.get_mut()
888                {
889                    if let Some(id_owned) = owned_sid {
890                        state.id = id_owned;
891                    } else {
892                        state.id.clear();
893                        state.id.push_str(sid);
894                    }
895                    state.previous_id = None;
896                    state.values = values;
897                    state.existed = existed;
898                    state.dirty = false;
899                    state.destroyed = false;
900                    *inner_mut.dirty.get_mut() = false;
901                    return existing.clone();
902                }
903                let id_string: String = owned_sid.unwrap_or_else(|| sid.to_owned());
904                let handle: SessionHandle = SessionHandle::new(id_string, values, existed);
905                *existing = handle.clone();
906                return handle;
907            }
908            let id_string: String = owned_sid.unwrap_or_else(|| sid.to_owned());
909            let handle: SessionHandle = SessionHandle::new(id_string, values, existed);
910            *slot = Arc::new(handle.clone());
911            return handle;
912        }
913        let id_string: String = owned_sid.unwrap_or_else(|| sid.to_owned());
914        let handle: SessionHandle = SessionHandle::new(id_string, values, existed);
915        ctx.get_mut_attributes().insert(
916            ATTR_SESSION_HANDLE_MAP_KEY.to_owned(),
917            Arc::new(handle.clone()),
918        );
919        handle
920    }
921
922    /// Loads or initializes the [`SessionHandle`] on `ctx` from the incoming `Cookie` header.
923    ///
924    /// # Arguments
925    ///
926    /// - `&mut Context` - Incoming request context.
927    ///
928    /// # Returns
929    ///
930    /// - `SessionHandle` - Active session handle attached to `ctx`.
931    pub async fn load_into_context(&self, ctx: &mut Context) -> SessionHandle {
932        let Self {
933            config,
934            store,
935            compiled,
936            fast_store,
937        } = self;
938        let mut sid_stack: [u8; SID_STACK_CAP] = [0u8; SID_STACK_CAP];
939        let mut sid_len: usize = 0;
940        let mut owned_sid: Option<String> = None;
941        let mut loaded_values: Option<Arc<HashMap<String, String>>> = None;
942        if let Some(raw_cookie) = ctx
943            .get_request()
944            .get_headers()
945            .get(COOKIE)
946            .and_then(|values: &VecDeque<String>| values.back())
947            .map(String::as_str)
948            && let Some(raw_val) = find_cookie_value_trusted(
949                raw_cookie,
950                config.get_cookie_name(),
951                compiled.valid_cookie_name,
952            )
953        {
954            let verified_sid: Option<&str> = match &compiled.hmac_key {
955                Some(key) => verify_session_cookie_with_key(raw_val, key),
956                None => {
957                    if raw_val.is_empty() {
958                        None
959                    } else {
960                        Some(raw_val)
961                    }
962                }
963            };
964            if let Some(sid) = verified_sid {
965                let maybe_values: Option<Arc<HashMap<String, String>>> =
966                    if let Some(mem_store) = fast_store {
967                        mem_store.load_sync_shared(sid)
968                    } else {
969                        store.load(sid).await.map(Arc::new)
970                    };
971                if let Some(values) = maybe_values {
972                    let sid_bytes: &[u8] = sid.as_bytes();
973                    if sid_bytes.len() <= SID_STACK_CAP {
974                        sid_stack[..sid_bytes.len()].copy_from_slice(sid_bytes);
975                        sid_len = sid_bytes.len();
976                    } else {
977                        owned_sid = Some(sid.to_owned());
978                    }
979                    loaded_values = Some(values);
980                }
981            }
982        }
983        if let Some(values) = loaded_values {
984            let sid_ref: &str = from_utf8(&sid_stack[..sid_len]).unwrap_or_default();
985            return Self::install_handle(ctx, sid_ref, owned_sid, values, true);
986        }
987        let fresh_id: [u8; 32] = generate_session_id_bytes();
988        let fresh_str: &str = from_utf8(&fresh_id).unwrap_or_default();
989        Self::install_handle(
990            ctx,
991            fresh_str,
992            None,
993            Arc::clone(empty_session_values()),
994            false,
995        )
996    }
997
998    /// Persists dirty, regenerated, or destroyed session state and emits `Set-Cookie` on `ctx`.
999    ///
1000    /// # Arguments
1001    ///
1002    /// - `&mut Context` - Outgoing request/response context.
1003    pub async fn persist_from_context(&self, ctx: &mut Context) {
1004        let Self {
1005            config,
1006            store,
1007            compiled,
1008            fast_store,
1009        } = self;
1010        if let Some(mem_store) = fast_store {
1011            let mut cookie_buf: [u8; SET_COOKIE_STACK_CAP] = [0u8; SET_COOKIE_STACK_CAP];
1012            let mut cookie_len: Option<usize> = None;
1013            let mut cookie_fallback: Option<String> = None;
1014            let mut emit_clear: bool = false;
1015            {
1016                let Some(handle) = ctx
1017                    .get_attributes()
1018                    .get(ATTR_SESSION_HANDLE_MAP_KEY)
1019                    .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<SessionHandle>())
1020                else {
1021                    return;
1022                };
1023                if !handle.inner.dirty.load(Ordering::Acquire) {
1024                    return;
1025                }
1026                let Ok(guard) = handle.inner.state.lock() else {
1027                    return;
1028                };
1029                if !guard.dirty {
1030                    return;
1031                }
1032                if let Some(old_id) = guard.previous_id.as_deref() {
1033                    let _: bool = mem_store.delete_sync(old_id);
1034                }
1035                if guard.destroyed {
1036                    let _: bool = mem_store.delete_sync(&guard.id);
1037                    emit_clear = compiled.valid_cookie_config;
1038                } else {
1039                    mem_store.save_sync_shared(
1040                        &guard.id,
1041                        Arc::clone(&guard.values),
1042                        config.get_ttl_secs(),
1043                    );
1044                    if let Some(cookie_str) =
1045                        self.format_live_set_cookie_stack(&guard.id, &mut cookie_buf)
1046                    {
1047                        cookie_len = Some(cookie_str.len());
1048                    } else {
1049                        cookie_fallback = Some(self.build_set_cookie(&guard.id, false));
1050                    }
1051                }
1052            }
1053            if emit_clear {
1054                ctx.get_mut_response()
1055                    .add_header(SET_COOKIE, &compiled.clear_cookie);
1056            } else if let Some(len) = cookie_len {
1057                if let Ok(cookie_str) = from_utf8(&cookie_buf[..len]) {
1058                    ctx.get_mut_response().add_header(SET_COOKIE, cookie_str);
1059                }
1060            } else if let Some(set_cookie) = cookie_fallback {
1061                ctx.get_mut_response().add_header(SET_COOKIE, set_cookie);
1062            }
1063            return;
1064        }
1065        let Some(state) = ctx
1066            .get_attributes()
1067            .get(ATTR_SESSION_HANDLE_MAP_KEY)
1068            .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::<SessionHandle>())
1069            .and_then(SessionHandle::snapshot_if_dirty)
1070        else {
1071            return;
1072        };
1073        if let Some(old_id) = state.previous_id {
1074            let _: bool = store.delete(&old_id).await;
1075        }
1076        if state.destroyed {
1077            let _: bool = store.delete(&state.id).await;
1078            if compiled.valid_cookie_config {
1079                ctx.get_mut_response()
1080                    .add_header(SET_COOKIE, &compiled.clear_cookie);
1081            }
1082            return;
1083        }
1084        let mut cookie_buf: [u8; SET_COOKIE_STACK_CAP] = [0u8; SET_COOKIE_STACK_CAP];
1085        let stack_len: Option<usize> = self
1086            .format_live_set_cookie_stack(&state.id, &mut cookie_buf)
1087            .map(str::len);
1088        let fallback: Option<String> = if stack_len.is_none() {
1089            Some(self.build_set_cookie(&state.id, false))
1090        } else {
1091            None
1092        };
1093        let owned_values: HashMap<String, String> = Arc::try_unwrap(state.values)
1094            .unwrap_or_else(|shared: Arc<HashMap<String, String>>| (*shared).clone());
1095        store
1096            .save(state.id, owned_values, config.get_ttl_secs())
1097            .await;
1098        if let Some(len) = stack_len {
1099            if let Ok(cookie_str) = from_utf8(&cookie_buf[..len]) {
1100                ctx.get_mut_response().add_header(SET_COOKIE, cookie_str);
1101            }
1102        } else if let Some(set_cookie) = fallback {
1103            ctx.get_mut_response().add_header(SET_COOKIE, set_cookie);
1104        }
1105    }
1106}
1107
1108/// Implements [`ServerHook`] for [`SessionRequestHook`].
1109impl ServerHook for SessionRequestHook {
1110    /// Constructs a per-request [`SessionRequestHook`].
1111    ///
1112    /// # Arguments
1113    ///
1114    /// - `&mut Stream` - Connection stream.
1115    /// - `&mut Context` - Request context.
1116    ///
1117    /// # Returns
1118    ///
1119    /// - `Self` - Hook instance.
1120    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1121        Self
1122    }
1123
1124    /// Loads or initializes the per-request [`SessionHandle`] into `ctx`.
1125    ///
1126    /// # Arguments
1127    ///
1128    /// - `Self` - Hook instance.
1129    /// - `&mut Stream` - Connection stream.
1130    /// - `&mut Context` - Request context.
1131    ///
1132    /// # Returns
1133    ///
1134    /// - `Status` - Always `Status::Continue`.
1135    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
1136        let Some(plugin) = SessionPlugin::get() else {
1137            return Status::Continue;
1138        };
1139        let _: SessionHandle = plugin.load_into_context(ctx).await;
1140        Status::Continue
1141    }
1142}
1143
1144/// Implements [`ServerHook`] for [`SessionResponseHook`].
1145impl ServerHook for SessionResponseHook {
1146    /// Constructs a per-response [`SessionResponseHook`].
1147    ///
1148    /// # Arguments
1149    ///
1150    /// - `&mut Stream` - Connection stream.
1151    /// - `&mut Context` - Request context.
1152    ///
1153    /// # Returns
1154    ///
1155    /// - `Self` - Hook instance.
1156    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1157        Self
1158    }
1159
1160    /// Persists modified session state and attaches `Set-Cookie` only when dirty.
1161    ///
1162    /// # Arguments
1163    ///
1164    /// - `Self` - Hook instance.
1165    /// - `&mut Stream` - Connection stream.
1166    /// - `&mut Context` - Request context.
1167    ///
1168    /// # Returns
1169    ///
1170    /// - `Status` - Always `Status::Continue`.
1171    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
1172        let Some(plugin) = SessionPlugin::get() else {
1173            return Status::Continue;
1174        };
1175        plugin.persist_from_context(ctx).await;
1176        Status::Continue
1177    }
1178}