reinhardt-middleware 0.1.2

Middleware system for request/response processing pipeline
Documentation
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//! Session Middleware
//!
//! Provides enhanced session management functionality.
//! Supports various backends including Cookie, Redis, and database.
//!
//! This module is split into responsibility-focused submodules:
//!
//! - `id` — session-ID newtypes and the request-scoped active ID holder
//! - `data` — the `SessionData` payload, read/write/rotate helpers
//! - `store` — in-memory `SessionStore` with lazy eviction
//! - `backend` — pluggable `AsyncSessionBackend` trait
//! - `config` — `SessionConfig` cookie/TTL knobs
//! - `middleware` — `SessionMiddleware` that wires it all together
//! - `injectable` — DI integration (`Injectable` impls + `SessionStoreRef`)
//!
//! All public types are re-exported here so existing call sites that
//! used `crate::session::*` continue to work unchanged.

mod auth_ext;
mod backend;
mod config;
mod cookie;
mod data;
mod id;
mod injectable;
mod middleware;
mod store;
mod value;

// Test-only fixtures shared between in-crate unit tests and external
// integration tests. Hidden from the public API surface and only compiled
// when `cfg(test)` is active (for unit tests) or the `test-support`
// feature is enabled (for integration tests). See Issue #4462.
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
pub mod test_support;

pub use auth_ext::SessionAuthExt;
pub use backend::AsyncSessionBackend;
pub use config::SessionConfig;
pub use data::{SessionData, USER_ID_SESSION_KEY};
pub use id::{ActiveSessionId, SessionCookieName, SessionId};
pub use injectable::SessionStoreRef;
pub use middleware::SessionMiddleware;
pub use store::SessionStore;
pub use value::{
	OptionalSessionValue, OptionalSessionValueNamed, SessionKey, SessionValue, SessionValueNamed,
	UserIdKey,
};

#[cfg(test)]
mod tests {
	use super::*;
	use async_trait::async_trait;
	use bytes::Bytes;
	use hyper::{HeaderMap, Method, StatusCode, Version};
	#[allow(deprecated)]
	use reinhardt_conf::Settings;
	use reinhardt_http::{Handler, Middleware, Request, Response, Result};
	use std::sync::{Arc, RwLock};
	use std::thread;
	use std::time::{Duration, SystemTime};

	struct TestHandler;

	#[async_trait]
	impl Handler for TestHandler {
		async fn handle(&self, _request: Request) -> Result<Response> {
			Ok(Response::new(StatusCode::OK).with_body(Bytes::from("OK")))
		}
	}

	#[tokio::test]
	async fn test_session_creation() {
		let config = SessionConfig::new("sessionid".to_string(), Duration::from_secs(3600));
		let middleware = SessionMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		assert_eq!(response.status, StatusCode::OK);
		assert!(response.headers.contains_key("set-cookie"));

		let cookie = response
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();
		assert!(cookie.starts_with("sessionid="));
	}

	#[tokio::test]
	async fn test_session_persistence() {
		let config = SessionConfig::new("sessionid".to_string(), Duration::from_secs(3600));
		let middleware = Arc::new(SessionMiddleware::new(config));
		let handler = Arc::new(TestHandler);

		// First request
		let request1 = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response1 = middleware.process(request1, handler.clone()).await.unwrap();
		let cookie1 = response1
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();

		// Extract session ID
		let session_id = cookie1
			.split(';')
			.next()
			.unwrap()
			.split('=')
			.nth(1)
			.unwrap();

		// Second request (with same session ID)
		let mut headers = HeaderMap::new();
		headers.insert(
			hyper::header::COOKIE,
			hyper::header::HeaderValue::from_str(&format!("sessionid={}", session_id)).unwrap(),
		);
		let request2 = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.build()
			.unwrap();
		let response2 = middleware.process(request2, handler).await.unwrap();

		assert_eq!(response2.status, StatusCode::OK);

		// Same session ID should be returned
		let cookie2 = response2
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();
		assert!(cookie2.contains(session_id));
	}

	#[tokio::test]
	async fn test_session_expiration() {
		let config = SessionConfig::new("sessionid".to_string(), Duration::from_millis(100));
		let middleware = Arc::new(SessionMiddleware::new(config));
		let handler = Arc::new(TestHandler);

		// First request
		let request1 = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response1 = middleware.process(request1, handler.clone()).await.unwrap();
		let cookie1 = response1
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();
		let session_id1 = cookie1
			.split(';')
			.next()
			.unwrap()
			.split('=')
			.nth(1)
			.unwrap();

		// Wait until expiration
		thread::sleep(Duration::from_millis(150));

		// Request after expiration
		let mut headers = HeaderMap::new();
		headers.insert(
			hyper::header::COOKIE,
			hyper::header::HeaderValue::from_str(&format!("sessionid={}", session_id1)).unwrap(),
		);
		let request2 = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.build()
			.unwrap();
		let response2 = middleware.process(request2, handler).await.unwrap();

		// New session ID should be created
		let cookie2 = response2
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();
		let session_id2 = cookie2
			.split(';')
			.next()
			.unwrap()
			.split('=')
			.nth(1)
			.unwrap();

		assert_ne!(session_id1, session_id2);
	}

	#[tokio::test]
	async fn test_cookie_attributes() {
		let config = SessionConfig::new("sessionid".to_string(), Duration::from_secs(3600))
			.with_secure()
			.with_http_only(true)
			.with_same_site("Strict".to_string())
			.with_path("/app".to_string());
		let middleware = SessionMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		let cookie = response
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();
		assert!(cookie.contains("Secure"));
		assert!(cookie.contains("HttpOnly"));
		assert!(cookie.contains("SameSite=Strict"));
		assert!(cookie.contains("Path=/app"));
	}

	#[tokio::test]
	async fn test_session_data() {
		let mut session = SessionData::new(Duration::from_secs(3600));

		session.set("user_id".to_string(), 123).unwrap();
		session
			.set("username".to_string(), "alice".to_string())
			.unwrap();

		let user_id: i32 = session.get("user_id").unwrap();
		assert_eq!(user_id, 123);

		let username: String = session.get("username").unwrap();
		assert_eq!(username, "alice");

		assert!(session.contains_key("user_id"));
		assert!(!session.contains_key("email"));

		session.delete("username");
		assert!(!session.contains_key("username"));
	}

	#[tokio::test]
	async fn test_session_store() {
		let store = SessionStore::new();

		let session1 = SessionData::new(Duration::from_secs(3600));
		let id1 = session1.id.clone();
		store.save(session1);

		let session2 = SessionData::new(Duration::from_secs(3600));
		let id2 = session2.id.clone();
		store.save(session2);

		assert_eq!(store.len(), 2);
		assert!(!store.is_empty());

		let retrieved1 = store.get(&id1).unwrap();
		assert_eq!(retrieved1.id, id1);

		store.delete(&id1);
		assert_eq!(store.len(), 1);
		assert!(store.get(&id1).is_none());
		assert!(store.get(&id2).is_some());
	}

	#[tokio::test]
	async fn test_session_cleanup() {
		let store = SessionStore::new();

		let mut session1 = SessionData::new(Duration::from_millis(10));
		session1.expires_at = SystemTime::now() - Duration::from_millis(20);
		store.save(session1);

		let session2 = SessionData::new(Duration::from_secs(3600));
		let id2 = session2.id.clone();
		store.save(session2);

		store.cleanup();

		assert_eq!(store.len(), 1);
		assert!(store.get(&id2).is_some());
	}

	#[tokio::test]
	async fn test_with_defaults_constructor() {
		let middleware = SessionMiddleware::with_defaults();
		let handler = Arc::new(TestHandler);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/page")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		assert_eq!(response.status, StatusCode::OK);
		assert!(response.headers.contains_key("set-cookie"));

		let cookie = response
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();
		// Default cookie name should be "sessionid"
		assert!(cookie.starts_with("sessionid="));
		// Default path should be "/"
		assert!(cookie.contains("Path=/"));
	}

	#[tokio::test]
	async fn test_custom_cookie_name() {
		let config = SessionConfig::new("my_session".to_string(), Duration::from_secs(3600));
		let middleware = SessionMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = middleware.process(request, handler).await.unwrap();

		let cookie = response
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();
		// Custom cookie name should be used
		assert!(cookie.starts_with("my_session="));
		assert!(!cookie.starts_with("sessionid="));
	}

	#[rstest::rstest]
	#[tokio::test]
	async fn test_session_config_from_settings_secure_enabled() {
		// Arrange
		#[allow(deprecated)]
		let mut settings = Settings::new(std::path::PathBuf::from("/app"), "test-secret".to_string());
		settings.core.security.session_cookie_secure = true;

		// Act
		#[allow(deprecated)]
		let config = SessionConfig::from_settings(&settings);

		// Assert
		assert_eq!(config.secure, true);
	}

	#[rstest::rstest]
	#[tokio::test]
	async fn test_session_config_from_settings_defaults() {
		// Arrange
		#[allow(deprecated)]
		let settings = Settings::default();

		// Act
		#[allow(deprecated)]
		let config = SessionConfig::from_settings(&settings);

		// Assert
		assert_eq!(config.secure, false);
		assert_eq!(config.cookie_name, "sessionid");
		assert_eq!(config.ttl, Duration::from_secs(3600));
	}

	#[rstest::rstest]
	#[tokio::test]
	async fn test_session_middleware_from_settings() {
		// Arrange
		#[allow(deprecated)]
		let mut settings = Settings::new(std::path::PathBuf::from("/app"), "test-secret".to_string());
		settings.core.security.session_cookie_secure = true;
		#[allow(deprecated)]
		let middleware = SessionMiddleware::from_settings(&settings);
		let handler = Arc::new(TestHandler);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		// Act
		let response = middleware.process(request, handler).await.unwrap();

		// Assert
		assert_eq!(response.status, StatusCode::OK);
		let cookie = response
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();
		assert!(cookie.contains("Secure"));
	}

	#[rstest::rstest]
	fn test_rwlock_poison_recovery_session_store() {
		// Arrange
		let store = Arc::new(SessionStore::new());
		let session = SessionData::new(Duration::from_secs(3600));
		let session_id = session.id.clone();
		store.save(session);

		// Act - poison the RwLock by panicking while holding a write guard
		let store_clone = Arc::clone(&store);
		let _ = thread::spawn(move || {
			let _guard = store_clone.sessions.write().unwrap();
			panic!("intentional panic to poison lock");
		})
		.join();

		// Assert - operations still work after poison recovery
		assert!(store.get(&session_id).is_some());
		assert_eq!(store.len(), 1);
		assert!(!store.is_empty());
		store.delete(&session_id);
		assert_eq!(store.len(), 0);
	}

	/// Handler that captures the session ID from request extensions
	struct SessionIdCapturingHandler {
		captured: Arc<RwLock<Option<SessionId>>>,
	}

	#[async_trait]
	impl Handler for SessionIdCapturingHandler {
		async fn handle(&self, request: Request) -> Result<Response> {
			// Capture session ID from extensions
			let session_id = request.extensions.get::<SessionId>();
			let mut guard = self.captured.write().unwrap();
			*guard = session_id;
			Ok(Response::new(StatusCode::OK).with_body(Bytes::from("OK")))
		}
	}

	#[rstest::rstest]
	#[tokio::test]
	async fn test_session_id_injected_into_request_extensions() {
		// Arrange
		let config = SessionConfig::new("sessionid".to_string(), Duration::from_secs(3600));
		let middleware = SessionMiddleware::new(config);
		let captured = Arc::new(RwLock::new(None));
		let handler = Arc::new(SessionIdCapturingHandler {
			captured: Arc::clone(&captured),
		});

		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		// Act
		let _response = middleware.process(request, handler).await.unwrap();

		// Assert - handler received request with session ID in extensions
		let guard = captured.read().unwrap();
		let session_id = guard
			.as_ref()
			.expect("SessionId should be present in extensions");
		assert!(
			!session_id.as_str().is_empty(),
			"Session ID should not be empty"
		);
	}

	#[rstest::rstest]
	#[tokio::test]
	async fn test_session_id_in_extensions_matches_cookie() {
		// Arrange
		let config = SessionConfig::new("sessionid".to_string(), Duration::from_secs(3600));
		let middleware = SessionMiddleware::new(config);
		let captured = Arc::new(RwLock::new(None));
		let handler = Arc::new(SessionIdCapturingHandler {
			captured: Arc::clone(&captured),
		});

		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		// Act
		let response = middleware.process(request, handler).await.unwrap();

		// Assert - session ID in extensions matches the one in Set-Cookie header
		let guard = captured.read().unwrap();
		let session_id = guard.as_ref().expect("SessionId should be present");

		let cookie = response
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();
		let cookie_session_id = cookie.split(';').next().unwrap().split('=').nth(1).unwrap();

		assert_eq!(session_id.as_str(), cookie_session_id);
	}

	#[rstest::rstest]
	#[tokio::test]
	async fn test_session_id_in_extensions_preserved_for_existing_session() {
		// Arrange
		let config = SessionConfig::new("sessionid".to_string(), Duration::from_secs(3600));
		let middleware = Arc::new(SessionMiddleware::new(config));
		let captured = Arc::new(RwLock::new(None));

		// First request to create session
		let handler1 = Arc::new(TestHandler);
		let request1 = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response1 = middleware.process(request1, handler1).await.unwrap();
		let cookie = response1
			.headers
			.get("set-cookie")
			.unwrap()
			.to_str()
			.unwrap();
		let original_session_id = cookie
			.split(';')
			.next()
			.unwrap()
			.split('=')
			.nth(1)
			.unwrap()
			.to_string();

		// Second request with existing session cookie
		let handler2 = Arc::new(SessionIdCapturingHandler {
			captured: Arc::clone(&captured),
		});
		let mut headers = HeaderMap::new();
		headers.insert(
			hyper::header::COOKIE,
			hyper::header::HeaderValue::from_str(&format!("sessionid={}", original_session_id))
				.unwrap(),
		);
		let request2 = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.build()
			.unwrap();

		// Act
		let _response2 = middleware.process(request2, handler2).await.unwrap();

		// Assert - session ID in extensions matches the original session
		let guard = captured.read().unwrap();
		let session_id = guard.as_ref().expect("SessionId should be present");
		assert_eq!(session_id.as_str(), original_session_id);
	}

	/// Handler that rotates the session ID via `SessionData::regenerate_id`,
	/// emulating session-fixation prevention on login. Replays #3827.
	struct RotatingHandler {
		store: Arc<SessionStore>,
	}

	#[async_trait]
	impl Handler for RotatingHandler {
		async fn handle(&self, request: Request) -> Result<Response> {
			let active_id = request
				.extensions
				.get::<ActiveSessionId>()
				.expect("ActiveSessionId should be present");
			let original_id = active_id.get();

			let mut session = self
				.store
				.get(&original_id)
				.expect("session created by middleware should be present");
			session.id_holder = Some(active_id);

			let old_id = session.regenerate_id();
			session
				.set("user_id".to_string(), "user-42".to_string())
				.unwrap();
			self.store.delete(&old_id);
			self.store.save(session);

			Ok(Response::new(StatusCode::OK).with_body(Bytes::from("OK")))
		}
	}

	/// Regression test for #3827: a handler that rotates the session ID for
	/// session-fixation prevention must end up with the new ID in the
	/// response `Set-Cookie`, and that cookie must point at a stored session.
	#[tokio::test]
	async fn test_handler_id_rotation_propagates_to_cookie() {
		// Arrange
		let config = SessionConfig::new("sessionid".to_string(), Duration::from_secs(3600));
		let store = Arc::new(SessionStore::new());
		let middleware = SessionMiddleware::from_arc(config, Arc::clone(&store));
		let handler = Arc::new(RotatingHandler {
			store: Arc::clone(&store),
		});
		let request = Request::builder()
			.method(Method::POST)
			.uri("/login")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		// Act
		let response = middleware.process(request, handler).await.unwrap();

		// Assert: extract the session ID the client will receive…
		let cookie = response
			.headers
			.get("set-cookie")
			.expect("Set-Cookie should be set")
			.to_str()
			.unwrap();
		let cookie_session_id = cookie
			.split(';')
			.next()
			.unwrap()
			.split('=')
			.nth(1)
			.unwrap()
			.to_string();

		// …and verify the store contains exactly that session, with the user_id
		// the handler wrote during rotation.
		let stored = store
			.get(&cookie_session_id)
			.expect("Session referenced by Set-Cookie must exist in store");
		assert_eq!(stored.id, cookie_session_id);
		assert_eq!(
			stored.get::<String>("user_id").as_deref(),
			Some("user-42"),
			"Rotated session must carry the data written by the handler"
		);
	}

	/// Handler that captures the cookie name from request extensions
	struct CookieNameCapturingHandler {
		captured: Arc<RwLock<Option<SessionCookieName>>>,
	}

	#[async_trait]
	impl Handler for CookieNameCapturingHandler {
		async fn handle(&self, request: Request) -> Result<Response> {
			let cookie_name = request.extensions.get::<SessionCookieName>();
			let mut guard = self.captured.write().unwrap();
			*guard = cookie_name;
			Ok(Response::new(StatusCode::OK).with_body(Bytes::from("OK")))
		}
	}

	#[rstest::rstest]
	#[tokio::test]
	async fn test_session_cookie_name_injected_into_extensions() {
		// Arrange
		let config = SessionConfig::new("custom_session".to_string(), Duration::from_secs(3600));
		let middleware = SessionMiddleware::new(config);
		let captured = Arc::new(RwLock::new(None));
		let handler = Arc::new(CookieNameCapturingHandler {
			captured: Arc::clone(&captured),
		});

		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		// Act
		let _response = middleware.process(request, handler).await.unwrap();

		// Assert - handler received the configured cookie name in extensions
		let guard = captured.read().unwrap();
		let cookie_name = guard
			.as_ref()
			.expect("SessionCookieName should be present in extensions");
		assert_eq!(
			cookie_name.as_str(),
			"custom_session",
			"Cookie name should match configured value, not hardcoded 'sessionid'"
		);
	}

	/// Handler that returns a response with an existing Set-Cookie header
	struct HandlerWithSetCookie;

	#[async_trait]
	impl Handler for HandlerWithSetCookie {
		async fn handle(&self, _request: Request) -> Result<Response> {
			let mut response = Response::new(StatusCode::OK).with_body(Bytes::from("OK"));
			response.headers.insert(
				hyper::header::SET_COOKIE,
				hyper::header::HeaderValue::from_static("csrftoken=xyz789; Path=/"),
			);
			Ok(response)
		}
	}

	#[rstest::rstest]
	#[tokio::test]
	async fn test_session_set_cookie_appends_not_replaces() {
		// Arrange
		let config = SessionConfig::new("sessionid".to_string(), Duration::from_secs(3600));
		let middleware = SessionMiddleware::new(config);
		let handler = Arc::new(HandlerWithSetCookie);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		// Act
		let response = middleware.process(request, handler).await.unwrap();

		// Assert - both Set-Cookie headers should be present
		let set_cookies: Vec<&hyper::header::HeaderValue> = response
			.headers
			.get_all(hyper::header::SET_COOKIE)
			.iter()
			.collect();
		assert_eq!(
			set_cookies.len(),
			2,
			"Expected both the original CSRF cookie and session cookie"
		);

		let cookies_str: Vec<&str> = set_cookies.iter().map(|v| v.to_str().unwrap()).collect();
		assert!(
			cookies_str.iter().any(|c| c.contains("csrftoken=xyz789")),
			"Original Set-Cookie header should be preserved"
		);
		assert!(
			cookies_str.iter().any(|c| c.contains("sessionid=")),
			"Session Set-Cookie header should be appended"
		);
	}
}

#[cfg(test)]
mod async_backend_tests {
	use super::*;
	use async_trait::async_trait;
	use reinhardt_http::Result;
	use std::collections::HashMap;
	use std::sync::{Arc, RwLock};
	use std::time::Duration;

	/// In-memory MockBackend for testing `AsyncSessionBackend`.
	struct MockBackend {
		sessions: RwLock<HashMap<String, SessionData>>,
	}

	impl MockBackend {
		fn new() -> Self {
			Self {
				sessions: RwLock::new(HashMap::new()),
			}
		}
	}

	#[async_trait]
	impl AsyncSessionBackend for MockBackend {
		async fn load(&self, id: &str) -> Result<Option<SessionData>> {
			let sessions = self.sessions.read().unwrap_or_else(|e| e.into_inner());
			Ok(sessions.get(id).cloned())
		}

		async fn save(&self, session: &SessionData) -> Result<()> {
			let mut sessions = self.sessions.write().unwrap_or_else(|e| e.into_inner());
			sessions.insert(session.id.clone(), session.clone());
			Ok(())
		}

		async fn destroy(&self, id: &str) -> Result<()> {
			let mut sessions = self.sessions.write().unwrap_or_else(|e| e.into_inner());
			sessions.remove(id);
			Ok(())
		}

		async fn touch(&self, id: &str, ttl: Duration) -> Result<()> {
			let mut sessions = self.sessions.write().unwrap_or_else(|e| e.into_inner());
			if let Some(session) = sessions.get_mut(id) {
				session.touch(ttl);
			}
			Ok(())
		}
	}

	#[tokio::test]
	async fn test_mock_backend_load_nonexistent() {
		let backend = MockBackend::new();
		let result = backend.load("nonexistent-id").await.unwrap();
		assert!(result.is_none());
	}

	#[tokio::test]
	async fn test_mock_backend_save_and_load() {
		let backend = MockBackend::new();
		let session = SessionData::new(Duration::from_secs(3600));
		let id = session.id.clone();

		backend.save(&session).await.unwrap();

		let loaded = backend.load(&id).await.unwrap();
		assert!(loaded.is_some());
		assert_eq!(loaded.unwrap().id, id);
	}

	#[tokio::test]
	async fn test_mock_backend_save_overwrites() {
		let backend = MockBackend::new();
		let mut session = SessionData::new(Duration::from_secs(3600));
		let id = session.id.clone();

		backend.save(&session).await.unwrap();

		// Update a value and save again
		session.set("key".to_string(), "value").unwrap();
		backend.save(&session).await.unwrap();

		let loaded = backend.load(&id).await.unwrap().unwrap();
		let val: String = loaded.get("key").unwrap();
		assert_eq!(val, "value");
	}

	#[tokio::test]
	async fn test_mock_backend_destroy() {
		let backend = MockBackend::new();
		let session = SessionData::new(Duration::from_secs(3600));
		let id = session.id.clone();

		backend.save(&session).await.unwrap();
		assert!(backend.load(&id).await.unwrap().is_some());

		backend.destroy(&id).await.unwrap();
		assert!(backend.load(&id).await.unwrap().is_none());
	}

	#[tokio::test]
	async fn test_mock_backend_destroy_nonexistent_is_ok() {
		let backend = MockBackend::new();
		// Destroying a session that doesn't exist should not return an error
		let result = backend.destroy("ghost-id").await;
		assert!(result.is_ok());
	}

	#[tokio::test]
	async fn test_mock_backend_touch_updates_expiry() {
		let backend = MockBackend::new();
		let session = SessionData::new(Duration::from_secs(3600));
		let id = session.id.clone();
		let original_expires = session.expires_at;

		backend.save(&session).await.unwrap();

		// Touch with a longer TTL
		backend.touch(&id, Duration::from_secs(7200)).await.unwrap();

		let loaded = backend.load(&id).await.unwrap().unwrap();
		assert!(
			loaded.expires_at > original_expires,
			"expires_at should be extended after touch"
		);
	}

	#[tokio::test]
	async fn test_mock_backend_touch_nonexistent_is_ok() {
		let backend = MockBackend::new();
		// Touching a non-existent session is a no-op (not an error)
		let result = backend.touch("ghost-id", Duration::from_secs(3600)).await;
		assert!(result.is_ok());
	}

	#[tokio::test]
	async fn test_backend_dyn_dispatch() {
		// Verify the trait is object-safe and usable via Arc<dyn AsyncSessionBackend>
		let backend: Arc<dyn AsyncSessionBackend> = Arc::new(MockBackend::new());
		let session = SessionData::new(Duration::from_secs(3600));
		let id = session.id.clone();

		backend.save(&session).await.unwrap();
		let loaded = backend.load(&id).await.unwrap();
		assert!(loaded.is_some());

		backend.touch(&id, Duration::from_secs(1800)).await.unwrap();
		backend.destroy(&id).await.unwrap();
		assert!(backend.load(&id).await.unwrap().is_none());
	}
}