1use super::*;
2
3impl Default for SessionConfig {
5 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
21impl SessionConfig {
23 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 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 pub fn with_ttl_secs(mut self, ttl_secs: u64) -> Self {
67 self.set_ttl_secs(ttl_secs);
68 self
69 }
70
71 pub fn with_secure(mut self, secure: bool) -> Self {
81 self.set_secure(secure);
82 self
83 }
84}
85
86impl SessionHandle {
88 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 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 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 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 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 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 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 #[inline]
227 pub fn is_dirty(&self) -> bool {
228 let Self { inner } = self;
229 inner.dirty.load(Ordering::Acquire)
230 }
231
232 #[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
257impl Default for InMemorySessionStore {
259 fn default() -> Self {
261 Self::new(DEFAULT_MAX_SESSIONS)
262 }
263}
264
265impl InMemorySessionStore {
267 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 #[inline]
294 pub fn len(&self) -> usize {
295 let Self { inner } = self;
296 inner.count.load(Ordering::Relaxed)
297 }
298
299 #[inline]
305 pub fn is_empty(&self) -> bool {
306 self.len() == 0
307 }
308
309 #[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 #[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 #[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
411impl SessionStore for InMemorySessionStore {
413 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 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 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 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
503impl SessionCompiled {
505 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
571impl SessionPlugin {
573 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 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 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 pub fn get() -> Option<&'static Self> {
633 SESSION_PLUGIN.get()
634 }
635
636 pub fn get_config(&self) -> &SessionConfig {
642 &self.config
643 }
644
645 pub fn get_store(&self) -> &SharedSessionStore {
651 &self.store
652 }
653
654 pub fn current(ctx: &Context) -> Option<SessionHandle> {
664 ctx.try_get_attribute(ATTR_SESSION_HANDLE)
665 }
666
667 #[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 #[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 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 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
882impl ServerHook for SessionRequestHook {
884 async fn new(_: &mut Stream, _: &mut Context) -> Self {
895 Self
896 }
897
898 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
918impl ServerHook for SessionResponseHook {
920 async fn new(_: &mut Stream, _: &mut Context) -> Self {
931 Self
932 }
933
934 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}