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    /// - `HashMap<String, String>` - 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: HashMap<String, String>, existed: bool) -> Self {
100        Self {
101            state: Arc::new(Mutex::new(SessionState {
102                id,
103                previous_id: None,
104                values,
105                existed,
106                dirty: false,
107                destroyed: false,
108            })),
109        }
110    }
111
112    /// Returns the current session identifier.
113    ///
114    /// # Returns
115    ///
116    /// - `String` - Session ID.
117    pub fn id(&self) -> String {
118        let Self { state } = self;
119        state
120            .lock()
121            .map(|guard: MutexGuard<'_, SessionState>| guard.id.clone())
122            .unwrap_or_default()
123    }
124
125    /// Reads one attribute from the session without marking it dirty.
126    ///
127    /// # Arguments
128    ///
129    /// - `&str` - Attribute key.
130    ///
131    /// # Returns
132    ///
133    /// - `Option<String>` - Stored attribute value, if present.
134    pub fn get(&self, key: &str) -> Option<String> {
135        let Self { state } = self;
136        state
137            .lock()
138            .ok()
139            .and_then(|guard: MutexGuard<'_, SessionState>| guard.values.get(key).cloned())
140    }
141
142    /// Inserts or updates a session attribute and marks the session dirty for persistence.
143    ///
144    /// # Arguments
145    ///
146    /// - `K` - Attribute key convertible into `String`.
147    /// - `V` - Attribute value convertible into `String`.
148    pub fn insert<K, V>(&self, key: K, value: V)
149    where
150        K: Into<String>,
151        V: Into<String>,
152    {
153        let Self { state } = self;
154        if let Ok(mut guard) = state.lock() {
155            guard.values.insert(key.into(), value.into());
156            guard.dirty = true;
157            guard.destroyed = false;
158        }
159    }
160
161    /// Removes a session attribute and marks the session dirty when present.
162    ///
163    /// # Arguments
164    ///
165    /// - `&str` - Attribute key to remove.
166    ///
167    /// # Returns
168    ///
169    /// - `Option<String>` - Removed value, if any.
170    pub fn remove(&self, key: &str) -> Option<String> {
171        let Self { state } = self;
172        let mut guard: MutexGuard<'_, SessionState> = state.lock().ok()?;
173        let removed: Option<String> = guard.values.remove(key);
174        if removed.is_some() {
175            guard.dirty = true;
176        }
177        removed
178    }
179
180    /// Mints a fresh unpredictable session ID (session-fixation defense) and marks the session dirty.
181    ///
182    /// # Returns
183    ///
184    /// - `String` - Newly generated session identifier.
185    pub fn regenerate_id(&self) -> String {
186        let Self { state } = self;
187        let next_id: String = generate_session_id();
188        if let Ok(mut guard) = state.lock() {
189            if guard.previous_id.is_none() && guard.existed {
190                guard.previous_id = Some(guard.id.clone());
191            }
192            guard.id = next_id.clone();
193            guard.dirty = true;
194            guard.destroyed = false;
195        }
196        next_id
197    }
198
199    /// Marks the session for deletion and clears its in-memory attributes.
200    pub fn destroy(&self) {
201        let Self { state } = self;
202        if let Ok(mut guard) = state.lock() {
203            guard.values.clear();
204            guard.destroyed = true;
205            guard.dirty = true;
206        }
207    }
208
209    /// Reports whether this session has been modified during the current request.
210    ///
211    /// # Returns
212    ///
213    /// - `bool` - `true` when dirty.
214    pub fn is_dirty(&self) -> bool {
215        let Self { state } = self;
216        state
217            .lock()
218            .map(|guard: MutexGuard<'_, SessionState>| guard.dirty)
219            .unwrap_or(false)
220    }
221
222    /// Captures a snapshot of the internal [`SessionState`] for persistence in [`SessionResponseHook`].
223    ///
224    /// # Returns
225    ///
226    /// - `Option<SessionState>` - Cloned state snapshot.
227    pub(crate) fn snapshot(&self) -> Option<SessionState> {
228        let Self { state } = self;
229        state
230            .lock()
231            .ok()
232            .map(|guard: MutexGuard<'_, SessionState>| guard.clone())
233    }
234}
235
236/// Default construction for [`InMemorySessionStore`].
237impl Default for InMemorySessionStore {
238    /// Constructs a default 64-shard [`InMemorySessionStore`].
239    fn default() -> Self {
240        Self::new(DEFAULT_MAX_SESSIONS)
241    }
242}
243
244/// Inherent implementation of [`InMemorySessionStore`].
245impl InMemorySessionStore {
246    /// Creates a 64-way sharded bounded [`InMemorySessionStore`] capped at `max_sessions`.
247    ///
248    /// # Arguments
249    ///
250    /// - `usize` - Maximum concurrent tracked sessions.
251    ///
252    /// # Returns
253    ///
254    /// - `Self` - Ready sharded session store.
255    pub fn new(max_sessions: usize) -> Self {
256        let shards: SessionShardArray =
257            Box::new(from_fn(|_: usize| RwLock::new(hash_map_xx_hash3_64())));
258        Self {
259            inner: Arc::new(InMemorySessionStoreInner {
260                max_sessions: max_sessions.max(1),
261                count: AtomicUsize::new(0),
262                shards,
263            }),
264        }
265    }
266
267    /// Returns the number of tracked sessions across all shards in `O(1)` time.
268    ///
269    /// # Returns
270    ///
271    /// - `usize` - Active tracked session count.
272    pub fn len(&self) -> usize {
273        let Self { inner } = self;
274        inner.count.load(Ordering::Relaxed)
275    }
276
277    /// Reports whether zero sessions are currently stored.
278    ///
279    /// # Returns
280    ///
281    /// - `bool` - `true` when empty.
282    pub fn is_empty(&self) -> bool {
283        self.len() == 0
284    }
285}
286
287/// Implements [`SessionStore`] for [`InMemorySessionStore`].
288impl SessionStore for InMemorySessionStore {
289    /// Loads an unexpired session from its single owning shard.
290    ///
291    /// # Arguments
292    ///
293    /// - `&'a self` - Shared reference to self.
294    /// - `&'a str` - Session identifier.
295    ///
296    /// # Returns
297    ///
298    /// - `SessionFuture<'a, Option<HashMap<String, String>>>` - Attributes when live.
299    fn load<'a>(
300        &'a self,
301        session_id: &'a str,
302    ) -> SessionFuture<'a, Option<HashMap<String, String>>> {
303        let Self { inner } = self;
304        let idx: usize = session_shard_index(session_id);
305        let now: u64 = session_now_secs();
306        let loaded: Option<StoredSession> = inner.shards[idx].read().ok().and_then(
307            |map: RwLockReadGuard<'_, HashMapXxHash3_64<String, StoredSession>>| {
308                map.get(session_id).cloned()
309            },
310        );
311        let outcome: Option<HashMap<String, String>> = match loaded {
312            Some(entry) if now < entry.expires_at_secs => Some(entry.values),
313            Some(_) => {
314                if let Ok(mut map) = inner.shards[idx].write()
315                    && map.remove(session_id).is_some()
316                {
317                    inner.count.fetch_sub(1, Ordering::Relaxed);
318                }
319                None
320            }
321            None => None,
322        };
323        Box::pin(async move { outcome })
324    }
325
326    /// Saves a session into its owning shard while enforcing `max_sessions`.
327    ///
328    /// # Arguments
329    ///
330    /// - `String` - Session identifier.
331    /// - `HashMap<String, String>` - Session attributes.
332    /// - `u64` - TTL in seconds.
333    ///
334    /// # Returns
335    ///
336    /// - `SessionFuture<'_, ()>` - Completion future.
337    fn save(
338        &self,
339        session_id: String,
340        values: HashMap<String, String>,
341        ttl_secs: u64,
342    ) -> SessionFuture<'_, ()> {
343        let Self { inner } = self;
344        let now: u64 = session_now_secs();
345        if inner.count.load(Ordering::Relaxed) >= inner.max_sessions {
346            let _: usize = self.purge_expired();
347        }
348        let idx: usize = session_shard_index(&session_id);
349        if let Ok(mut map) = inner.shards[idx].write() {
350            let existed: bool = map.contains_key(&session_id);
351            if existed || inner.count.load(Ordering::Relaxed) < inner.max_sessions {
352                map.insert(
353                    session_id,
354                    StoredSession {
355                        values,
356                        expires_at_secs: now.saturating_add(ttl_secs.max(1)),
357                    },
358                );
359                if !existed {
360                    inner.count.fetch_add(1, Ordering::Relaxed);
361                }
362            }
363        }
364        Box::pin(async {})
365    }
366
367    /// Deletes a session from its owning shard.
368    ///
369    /// # Arguments
370    ///
371    /// - `&'a self` - Shared reference to self.
372    /// - `&'a str` - Session identifier.
373    ///
374    /// # Returns
375    ///
376    /// - `SessionFuture<'a, bool>` - `true` if deleted.
377    fn delete<'a>(&'a self, session_id: &'a str) -> SessionFuture<'a, bool> {
378        let Self { inner } = self;
379        let idx: usize = session_shard_index(session_id);
380        let removed: bool = inner.shards[idx]
381            .write()
382            .ok()
383            .and_then(
384                |mut map: RwLockWriteGuard<'_, HashMapXxHash3_64<String, StoredSession>>| {
385                    map.remove(session_id)
386                },
387            )
388            .is_some();
389        if removed {
390            inner.count.fetch_sub(1, Ordering::Relaxed);
391        }
392        Box::pin(async move { removed })
393    }
394
395    /// Evicts expired sessions across all 64 shards.
396    ///
397    /// # Returns
398    ///
399    /// - `usize` - Number of expired sessions purged.
400    fn purge_expired(&self) -> usize {
401        let Self { inner } = self;
402        let now: u64 = session_now_secs();
403        let mut evicted: usize = 0;
404        for shard in inner.shards.iter() {
405            if let Ok(mut map) = shard.write() {
406                let before: usize = map.len();
407                map.retain(|_: &String, entry: &mut StoredSession| now < entry.expires_at_secs);
408                evicted += before.saturating_sub(map.len());
409            }
410        }
411        if evicted > 0 {
412            inner.count.fetch_sub(evicted, Ordering::Relaxed);
413        }
414        evicted
415    }
416}
417
418/// Inherent implementation of [`SessionPlugin`].
419impl SessionPlugin {
420    /// Initializes the global [`SessionPlugin`] once with `config` and the default [`InMemorySessionStore`].
421    ///
422    /// # Arguments
423    ///
424    /// - `SessionConfig` - Cookie and session policy.
425    ///
426    /// # Returns
427    ///
428    /// - `&'static Self` - Reference to the initialized global plugin.
429    pub fn init(config: SessionConfig) -> &'static Self {
430        let store: SharedSessionStore =
431            Arc::new(InMemorySessionStore::new(config.get_max_sessions()));
432        Self::init_with_store(config, store)
433    }
434
435    /// Initializes the global [`SessionPlugin`] once with `config` and a custom [`SessionStore`].
436    ///
437    /// # Arguments
438    ///
439    /// - `SessionConfig` - Cookie and session policy.
440    /// - `SharedSessionStore` - Pluggable session store backend.
441    ///
442    /// # Returns
443    ///
444    /// - `&'static Self` - Reference to the initialized global plugin.
445    pub fn init_with_store(config: SessionConfig, store: SharedSessionStore) -> &'static Self {
446        SESSION_PLUGIN.get_or_init(|| Self { config, store })
447    }
448
449    /// Returns the initialized global [`SessionPlugin`], if initialized.
450    ///
451    /// # Returns
452    ///
453    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
454    pub fn get() -> Option<&'static Self> {
455        SESSION_PLUGIN.get()
456    }
457
458    /// Returns the active [`SessionConfig`].
459    ///
460    /// # Returns
461    ///
462    /// - `&SessionConfig` - Active session configuration.
463    pub fn get_config(&self) -> &SessionConfig {
464        &self.config
465    }
466
467    /// Returns the active [`SharedSessionStore`].
468    ///
469    /// # Returns
470    ///
471    /// - `&SharedSessionStore` - Active backing store.
472    pub fn get_store(&self) -> &SharedSessionStore {
473        &self.store
474    }
475
476    /// Retrieves the active [`SessionHandle`] stored in `ctx`.
477    ///
478    /// # Arguments
479    ///
480    /// - `&Context` - Request context.
481    ///
482    /// # Returns
483    ///
484    /// - `Option<SessionHandle>` - Per-request session handle, if session middleware ran.
485    pub fn current(ctx: &Context) -> Option<SessionHandle> {
486        ctx.try_get_attribute(ATTR_SESSION_HANDLE)
487    }
488
489    /// Formats a `Set-Cookie` header value for `session_id` (or an expiration cookie when `clear` is `true`).
490    ///
491    /// # Arguments
492    ///
493    /// - `&str` - Session identifier.
494    /// - `bool` - When `true`, emits `Max-Age=0` with empty value to clear the client cookie.
495    ///
496    /// # Returns
497    ///
498    /// - `String` - Formatted `Set-Cookie` header value.
499    pub fn build_set_cookie(&self, session_id: &str, clear: bool) -> String {
500        let config: &SessionConfig = self.get_config();
501        let value: String = if clear {
502            String::new()
503        } else if let Some(secret) = config.get_signing_secret() {
504            sign_session_cookie(session_id, &secret)
505        } else {
506            session_id.to_owned()
507        };
508        let mut builder: CookieBuilder = CookieBuilder::new(config.get_cookie_name(), value);
509        builder
510            .set_path(config.get_cookie_path())
511            .set_same_site(config.get_same_site());
512        if let Some(domain) = config.get_cookie_domain() {
513            builder.set_domain(domain);
514        }
515        if config.get_http_only() {
516            builder.http_only();
517        }
518        if config.get_secure() {
519            builder.secure();
520        }
521        if clear {
522            builder.set_max_age(0i64);
523        } else {
524            builder.set_max_age(config.get_ttl_secs() as i64);
525        }
526        builder.build()
527    }
528
529    /// Loads or initializes the [`SessionHandle`] on `ctx` from the incoming `Cookie` header.
530    ///
531    /// # Arguments
532    ///
533    /// - `&mut Context` - Incoming request context.
534    ///
535    /// # Returns
536    ///
537    /// - `SessionHandle` - Active session handle attached to `ctx`.
538    pub async fn load_into_context(&self, ctx: &mut Context) -> SessionHandle {
539        let config: &SessionConfig = self.get_config();
540        let candidate_id: Option<String> = ctx
541            .get_request()
542            .try_get_header_back(COOKIE)
543            .and_then(|raw: String| {
544                let cookies: Cookies = Cookie::parse(raw);
545                cookies.get(config.get_cookie_name()).cloned()
546            })
547            .and_then(|raw_val: String| match config.get_signing_secret() {
548                Some(secret) => verify_session_cookie(&raw_val, &secret),
549                None => {
550                    if raw_val.is_empty() {
551                        None
552                    } else {
553                        Some(raw_val)
554                    }
555                }
556            });
557        let handle: SessionHandle = if let Some(sid) = candidate_id {
558            if let Some(values) = self.get_store().load(&sid).await {
559                SessionHandle::new(sid, values, true)
560            } else {
561                SessionHandle::new(generate_session_id(), HashMap::new(), false)
562            }
563        } else {
564            SessionHandle::new(generate_session_id(), HashMap::new(), false)
565        };
566        ctx.set_attribute(ATTR_SESSION_HANDLE, handle.clone());
567        handle
568    }
569
570    /// Persists dirty, regenerated, or destroyed session state and emits `Set-Cookie` on `ctx`.
571    ///
572    /// # Arguments
573    ///
574    /// - `&mut Context` - Outgoing request/response context.
575    pub async fn persist_from_context(&self, ctx: &mut Context) {
576        let Some(handle) = Self::current(ctx) else {
577            return;
578        };
579        let Some(state) = handle.snapshot() else {
580            return;
581        };
582        if !state.dirty {
583            return;
584        }
585        if let Some(old_id) = state.previous_id {
586            let _: bool = self.get_store().delete(&old_id).await;
587        }
588        if state.destroyed {
589            let _: bool = self.get_store().delete(&state.id).await;
590            let clear_cookie: String = self.build_set_cookie(&state.id, true);
591            ctx.get_mut_response().add_header(SET_COOKIE, clear_cookie);
592            return;
593        }
594        self.get_store()
595            .save(
596                state.id.clone(),
597                state.values,
598                self.get_config().get_ttl_secs(),
599            )
600            .await;
601        let set_cookie: String = self.build_set_cookie(&state.id, false);
602        ctx.get_mut_response().add_header(SET_COOKIE, set_cookie);
603    }
604}
605
606/// Implements [`ServerHook`] for [`SessionRequestHook`].
607impl ServerHook for SessionRequestHook {
608    /// Constructs a per-request [`SessionRequestHook`].
609    ///
610    /// # Arguments
611    ///
612    /// - `&mut Stream` - Connection stream.
613    /// - `&mut Context` - Request context.
614    ///
615    /// # Returns
616    ///
617    /// - `Self` - Hook instance.
618    async fn new(_: &mut Stream, _: &mut Context) -> Self {
619        Self
620    }
621
622    /// Loads or initializes the per-request [`SessionHandle`] into `ctx`.
623    ///
624    /// # Arguments
625    ///
626    /// - `Self` - Hook instance.
627    /// - `&mut Stream` - Connection stream.
628    /// - `&mut Context` - Request context.
629    ///
630    /// # Returns
631    ///
632    /// - `Status` - Always `Status::Continue`.
633    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
634        let Some(plugin) = SessionPlugin::get() else {
635            return Status::Continue;
636        };
637        let _: SessionHandle = plugin.load_into_context(ctx).await;
638        Status::Continue
639    }
640}
641
642/// Implements [`ServerHook`] for [`SessionResponseHook`].
643impl ServerHook for SessionResponseHook {
644    /// Constructs a per-response [`SessionResponseHook`].
645    ///
646    /// # Arguments
647    ///
648    /// - `&mut Stream` - Connection stream.
649    /// - `&mut Context` - Request context.
650    ///
651    /// # Returns
652    ///
653    /// - `Self` - Hook instance.
654    async fn new(_: &mut Stream, _: &mut Context) -> Self {
655        Self
656    }
657
658    /// Persists modified session state and attaches `Set-Cookie` only when dirty.
659    ///
660    /// # Arguments
661    ///
662    /// - `Self` - Hook instance.
663    /// - `&mut Stream` - Connection stream.
664    /// - `&mut Context` - Request context.
665    ///
666    /// # Returns
667    ///
668    /// - `Status` - Always `Status::Continue`.
669    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
670        let Some(plugin) = SessionPlugin::get() else {
671            return Status::Continue;
672        };
673        plugin.persist_from_context(ctx).await;
674        Status::Continue
675    }
676}