Skip to main content

hyperlane_plugin_session/
impl.rs

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