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