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
//! Flatpages middleware
//!
//! Provides static page fallback functionality. When a request results in a 404,
//! the middleware attempts to serve content from a flatpages store.

use crate::xss::XssProtector;
use async_trait::async_trait;
use bytes::Bytes;
use hyper::StatusCode;
use reinhardt_http::{Handler, Middleware, Request, Response, Result};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// Authentication state stored in request extensions
///
/// This should be populated by authentication middleware and can be
/// checked by other middleware like Flatpages.
///
/// # Examples
///
/// ```
/// use reinhardt_middleware::flatpages::AuthenticationState;
///
/// // Authenticated user
/// let auth = AuthenticationState::authenticated("user123".to_string());
/// assert!(auth.is_authenticated());
///
/// // Anonymous user
/// let auth = AuthenticationState::anonymous();
/// assert!(!auth.is_authenticated());
/// ```
#[derive(Debug, Clone)]
pub struct AuthenticationState {
	authenticated: bool,
	user_id: Option<String>,
}

impl AuthenticationState {
	/// Create authentication state for an authenticated user
	pub fn authenticated(user_id: String) -> Self {
		Self {
			authenticated: true,
			user_id: Some(user_id),
		}
	}

	/// Create authentication state for an anonymous user
	pub fn anonymous() -> Self {
		Self {
			authenticated: false,
			user_id: None,
		}
	}

	/// Check if user is authenticated
	pub fn is_authenticated(&self) -> bool {
		self.authenticated
	}

	/// Get user ID if authenticated
	pub fn user_id(&self) -> Option<&str> {
		self.user_id.as_deref()
	}
}

/// Flatpage content
#[derive(Debug, Clone, PartialEq)]
pub struct Flatpage {
	/// URL path
	pub url: String,
	/// Page title
	pub title: String,
	/// Page content (HTML)
	pub content: String,
	/// Whether template rendering is enabled
	pub enable_comments: bool,
	/// Registration required to view
	pub registration_required: bool,
}

impl Flatpage {
	/// Create a new flatpage
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_middleware::Flatpage;
	///
	/// let page = Flatpage::new(
	///     "/about/".to_string(),
	///     "About Us".to_string(),
	///     "<h1>About Us</h1>".to_string(),
	/// );
	/// ```
	pub fn new(url: String, title: String, content: String) -> Self {
		Self {
			url,
			title,
			content,
			enable_comments: false,
			registration_required: false,
		}
	}

	/// Enable comments
	pub fn with_comments(mut self) -> Self {
		self.enable_comments = true;
		self
	}

	/// Require registration
	pub fn require_registration(mut self) -> Self {
		self.registration_required = true;
		self
	}
}

/// Flatpages storage
#[derive(Debug, Default)]
pub struct FlatpageStore {
	pages: RwLock<HashMap<String, Flatpage>>,
}

impl FlatpageStore {
	/// Create a new flatpage store
	pub fn new() -> Self {
		Self::default()
	}

	/// Register a flatpage
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_middleware::{Flatpage, FlatpageStore};
	///
	/// let store = FlatpageStore::new();
	/// let page = Flatpage::new(
	///     "/about/".to_string(),
	///     "About".to_string(),
	///     "<h1>About</h1>".to_string(),
	/// );
	/// store.register(page);
	/// ```
	pub fn register(&self, page: Flatpage) {
		let url = page.url.clone();
		self.pages
			.write()
			.unwrap_or_else(|e| e.into_inner())
			.insert(url, page);
	}

	/// Get flatpage by URL
	pub fn get(&self, url: &str) -> Option<Flatpage> {
		self.pages
			.read()
			.unwrap_or_else(|e| e.into_inner())
			.get(url)
			.cloned()
	}

	/// Remove flatpage
	pub fn remove(&self, url: &str) -> Option<Flatpage> {
		self.pages
			.write()
			.unwrap_or_else(|e| e.into_inner())
			.remove(url)
	}

	/// Get all flatpages
	pub fn all(&self) -> Vec<Flatpage> {
		self.pages
			.read()
			.unwrap_or_else(|e| e.into_inner())
			.values()
			.cloned()
			.collect()
	}

	/// Clear all flatpages
	pub fn clear(&self) {
		self.pages
			.write()
			.unwrap_or_else(|e| e.into_inner())
			.clear();
	}
}

/// Flatpages middleware configuration
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct FlatpagesConfig {
	/// Whether the middleware is enabled
	pub enabled: bool,
	/// Whether to append trailing slash when looking up flatpages
	pub append_slash: bool,
	/// Whether to try without trailing slash
	pub try_without_slash: bool,
}

impl FlatpagesConfig {
	/// Create a new configuration with defaults
	pub fn new() -> Self {
		Self {
			enabled: true,
			append_slash: true,
			try_without_slash: true,
		}
	}

	/// Disable the middleware
	pub fn disabled() -> Self {
		Self {
			enabled: false,
			append_slash: true,
			try_without_slash: true,
		}
	}
}

impl Default for FlatpagesConfig {
	fn default() -> Self {
		Self::new()
	}
}

/// Flatpages middleware
///
/// # Examples
///
/// ```
/// use reinhardt_middleware::{Flatpage, FlatpageStore, FlatpagesMiddleware, FlatpagesConfig};
/// use std::sync::Arc;
///
/// let config = FlatpagesConfig::new();
/// let middleware = Arc::new(FlatpagesMiddleware::new(config));
///
/// // Register a flatpage
/// let page = Flatpage::new(
///     "/about/".to_string(),
///     "About Us".to_string(),
///     "<h1>About Us</h1>".to_string(),
/// );
/// middleware.store().register(page);
/// ```
pub struct FlatpagesMiddleware {
	config: FlatpagesConfig,
	store: Arc<FlatpageStore>,
}

impl FlatpagesMiddleware {
	/// Create a new flatpages middleware
	pub fn new(config: FlatpagesConfig) -> Self {
		Self {
			config,
			store: Arc::new(FlatpageStore::new()),
		}
	}

	/// Create from an existing Arc-wrapped flatpage store
	///
	/// This is provided for cases where you already have an `Arc<FlatpageStore>`.
	/// In most cases, you should use `new()` instead, which creates the store internally.
	pub fn from_arc(config: FlatpagesConfig, store: Arc<FlatpageStore>) -> Self {
		Self { config, store }
	}

	/// Get a reference to the flatpage store
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_middleware::{FlatpagesMiddleware, FlatpagesConfig, Flatpage};
	///
	/// let middleware = FlatpagesMiddleware::new(FlatpagesConfig::new());
	///
	/// // Register a page using the store accessor
	/// let page = Flatpage::new(
	///     "/about/".to_string(),
	///     "About".to_string(),
	///     "<h1>About</h1>".to_string(),
	/// );
	/// middleware.store().register(page);
	/// ```
	pub fn store(&self) -> &FlatpageStore {
		&self.store
	}

	/// Get a cloned Arc of the store (for cases where you need ownership)
	///
	/// In most cases, you should use `store()` instead to get a reference.
	pub fn store_arc(&self) -> Arc<FlatpageStore> {
		Arc::clone(&self.store)
	}

	/// Try to get flatpage with various URL transformations
	fn try_get_page(&self, url: &str) -> Option<Flatpage> {
		// Try exact match first
		if let Some(page) = self.store.get(url) {
			return Some(page);
		}

		// Try with trailing slash
		if self.config.append_slash && !url.ends_with('/') {
			let with_slash = format!("{}/", url);
			if let Some(page) = self.store.get(&with_slash) {
				return Some(page);
			}
		}

		// Try without trailing slash
		if self.config.try_without_slash && url.ends_with('/') && url.len() > 1 {
			let without_slash = &url[..url.len() - 1];
			if let Some(page) = self.store.get(without_slash) {
				return Some(page);
			}
		}

		None
	}
}

#[async_trait]
impl Middleware for FlatpagesMiddleware {
	async fn process(&self, request: Request, handler: Arc<dyn Handler>) -> Result<Response> {
		// Skip if disabled
		if !self.config.enabled {
			return handler.handle(request).await;
		}

		// Get path and authentication state before moving request
		let path = request.uri.path().to_string();
		let is_authenticated = request
			.extensions
			.get::<AuthenticationState>()
			.map(|auth| auth.is_authenticated())
			.unwrap_or(false);

		// Convert errors to responses so post-processing always runs,
		// even when invoked outside MiddlewareChain. (#3244)
		let response = match handler.handle(request).await {
			Ok(resp) => resp,
			Err(e) => Response::from(e),
		};

		// Only intercept 404 responses
		if response.status != StatusCode::NOT_FOUND {
			return Ok(response);
		}

		// Try to find flatpage for this URL
		let path = path.as_str();
		if let Some(page) = self.try_get_page(path) {
			// Check authentication if registration_required
			if page.registration_required && !is_authenticated {
				// Return 401 Unauthorized with WWW-Authenticate header
				return Ok(Response::new(StatusCode::UNAUTHORIZED)
					.with_header("WWW-Authenticate", "Basic realm=\"Restricted\"")
					.with_body(Bytes::from("Authentication required to view this page")));
			}

			// Render flatpage content with HTML escaping to prevent stored XSS
			let escaped_title = XssProtector::escape_for_html_body(&page.title);
			let escaped_content = XssProtector::escape_for_html_body(&page.content);
			let html = format!(
				r#"<!DOCTYPE html>
<html>
<head>
    <title>{}</title>
</head>
<body>
    {}
</body>
</html>"#,
				escaped_title, escaped_content
			);

			return Ok(Response::new(StatusCode::OK).with_body(Bytes::from(html)));
		}

		// No flatpage found, return original 404
		Ok(response)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use bytes::Bytes;
	use hyper::{HeaderMap, Method, Version};
	use rstest::rstest;

	struct TestHandler {
		status: StatusCode,
	}

	impl TestHandler {
		fn ok() -> Self {
			Self {
				status: StatusCode::OK,
			}
		}

		fn not_found() -> Self {
			Self {
				status: StatusCode::NOT_FOUND,
			}
		}
	}

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

	#[tokio::test]
	async fn test_basic_flatpage() {
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

		// Register a flatpage
		let page = Flatpage::new(
			"/about/".to_string(),
			"About Us".to_string(),
			"<h1>About Us</h1>".to_string(),
		);
		middleware.store.register(page);

		let handler = Arc::new(TestHandler::not_found());
		let request = Request::builder()
			.method(Method::GET)
			.uri("/about/")
			.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);
		let body = String::from_utf8_lossy(&response.body);
		assert!(body.contains("About Us"));
		// Content is HTML-escaped to prevent XSS
		assert!(body.contains("&lt;h1&gt;About Us&lt;/h1&gt;"));
	}

	#[tokio::test]
	async fn test_flatpage_with_trailing_slash() {
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

		// Register flatpage with trailing slash
		let page = Flatpage::new(
			"/contact/".to_string(),
			"Contact".to_string(),
			"<p>Contact us</p>".to_string(),
		);
		middleware.store.register(page);

		let handler = Arc::new(TestHandler::not_found());

		// Request without trailing slash
		let request = Request::builder()
			.method(Method::GET)
			.uri("/contact")
			.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);
		let body = String::from_utf8_lossy(&response.body);
		assert!(body.contains("Contact"));
	}

	#[tokio::test]
	async fn test_flatpage_without_trailing_slash() {
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

		// Register flatpage without trailing slash
		let page = Flatpage::new(
			"/faq".to_string(),
			"FAQ".to_string(),
			"<p>Frequently Asked Questions</p>".to_string(),
		);
		middleware.store.register(page);

		let handler = Arc::new(TestHandler::not_found());

		// Request with trailing slash
		let request = Request::builder()
			.method(Method::GET)
			.uri("/faq/")
			.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);
		let body = String::from_utf8_lossy(&response.body);
		assert!(body.contains("FAQ"));
	}

	#[tokio::test]
	async fn test_no_flatpage_found() {
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

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

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

		// Should return original 404
		assert_eq!(response.status, StatusCode::NOT_FOUND);
		let body = String::from_utf8_lossy(&response.body);
		assert_eq!(body, "handler response");
	}

	#[tokio::test]
	async fn test_non_404_response_passthrough() {
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

		// Register a flatpage
		let page = Flatpage::new(
			"/about/".to_string(),
			"About".to_string(),
			"<h1>About</h1>".to_string(),
		);
		middleware.store.register(page);

		// Handler returns OK, not 404
		let handler = Arc::new(TestHandler::ok());
		let request = Request::builder()
			.method(Method::GET)
			.uri("/about/")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

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

		// Should return handler's OK response, not flatpage
		assert_eq!(response.status, StatusCode::OK);
		let body = String::from_utf8_lossy(&response.body);
		assert_eq!(body, "handler response");
	}

	#[tokio::test]
	async fn test_disabled_middleware() {
		let config = FlatpagesConfig::disabled();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

		// Register a flatpage
		let page = Flatpage::new(
			"/about/".to_string(),
			"About".to_string(),
			"<h1>About</h1>".to_string(),
		);
		middleware.store.register(page);

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

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

		// Should return 404 because middleware is disabled
		assert_eq!(response.status, StatusCode::NOT_FOUND);
	}

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

		// Test register and get
		let page1 = Flatpage::new(
			"/page1/".to_string(),
			"Page 1".to_string(),
			"<p>Content 1</p>".to_string(),
		);
		store.register(page1.clone());

		let retrieved = store.get("/page1/").unwrap();
		assert_eq!(retrieved, page1);

		// Test all
		let page2 = Flatpage::new(
			"/page2/".to_string(),
			"Page 2".to_string(),
			"<p>Content 2</p>".to_string(),
		);
		store.register(page2);

		let all = store.all();
		assert_eq!(all.len(), 2);

		// Test remove
		let removed = store.remove("/page1/").unwrap();
		assert_eq!(removed, page1);
		assert!(store.get("/page1/").is_none());

		// Test clear
		store.clear();
		assert_eq!(store.all().len(), 0);
	}

	#[tokio::test]
	async fn test_flatpage_with_comments() {
		let page = Flatpage::new(
			"/test/".to_string(),
			"Test".to_string(),
			"<p>Test</p>".to_string(),
		)
		.with_comments();

		assert!(page.enable_comments);
	}

	#[tokio::test]
	async fn test_flatpage_require_registration() {
		let page = Flatpage::new(
			"/test/".to_string(),
			"Test".to_string(),
			"<p>Test</p>".to_string(),
		)
		.require_registration();

		assert!(page.registration_required);
	}

	#[tokio::test]
	async fn test_exact_match_priority() {
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

		// Register both versions
		let page_with_slash = Flatpage::new(
			"/test/".to_string(),
			"With Slash".to_string(),
			"<p>With slash</p>".to_string(),
		);
		let page_without_slash = Flatpage::new(
			"/test".to_string(),
			"Without Slash".to_string(),
			"<p>Without slash</p>".to_string(),
		);
		middleware.store.register(page_with_slash);
		middleware.store.register(page_without_slash);

		let handler = Arc::new(TestHandler::not_found());

		// Request with slash should match with-slash version
		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.clone()).await.unwrap();
		let body = String::from_utf8_lossy(&response.body);
		assert!(body.contains("With Slash"));

		// Request without slash should match without-slash version
		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 body = String::from_utf8_lossy(&response.body);
		assert!(body.contains("Without Slash"));
	}

	#[tokio::test]
	async fn test_append_slash_disabled() {
		let mut config = FlatpagesConfig::new();
		config.append_slash = false;
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

		// Register with slash
		let page = Flatpage::new(
			"/test/".to_string(),
			"Test".to_string(),
			"<p>Test</p>".to_string(),
		);
		middleware.store.register(page);

		let handler = Arc::new(TestHandler::not_found());

		// Request without slash should NOT match
		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::NOT_FOUND);
	}

	#[tokio::test]
	async fn test_registration_required_authenticated_user() {
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

		// Register protected page
		let mut page = Flatpage::new(
			"/protected/".to_string(),
			"Protected Page".to_string(),
			"<p>Protected Content</p>".to_string(),
		);
		page.registration_required = true;
		middleware.store.register(page);

		let handler = Arc::new(TestHandler::not_found());

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

		// Add authentication state to request extensions
		request
			.extensions
			.insert(AuthenticationState::authenticated("user123".to_string()));

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

		// Should serve the protected page
		assert_eq!(response.status, StatusCode::OK);
		let body = String::from_utf8_lossy(&response.body);
		assert!(body.contains("Protected Content"));
	}

	#[tokio::test]
	async fn test_registration_required_anonymous_user() {
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

		// Register protected page
		let mut page = Flatpage::new(
			"/protected/".to_string(),
			"Protected Page".to_string(),
			"<p>Protected Content</p>".to_string(),
		);
		page.registration_required = true;
		middleware.store.register(page);

		let handler = Arc::new(TestHandler::not_found());

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

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

		// Should return 401 Unauthorized
		assert_eq!(response.status, StatusCode::UNAUTHORIZED);
		let body = String::from_utf8_lossy(&response.body);
		assert!(body.contains("Authentication required"));

		// Should include WWW-Authenticate header
		assert!(response.headers.contains_key("WWW-Authenticate"));
	}

	#[tokio::test]
	async fn test_no_registration_required_anonymous_user() {
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));

		// Register public page (registration_required defaults to false)
		let page = Flatpage::new(
			"/public/".to_string(),
			"Public Page".to_string(),
			"<p>Public Content</p>".to_string(),
		);
		middleware.store.register(page);

		let handler = Arc::new(TestHandler::not_found());

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

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

		// Should serve the public page
		assert_eq!(response.status, StatusCode::OK);
		let body = String::from_utf8_lossy(&response.body);
		assert!(body.contains("Public Content"));
	}

	#[rstest]
	#[case::script_tag_in_title("<script>alert('xss')</script>", "Safe content", "<script>", false)]
	#[case::script_tag_in_content("Safe Title", "<script>alert('xss')</script>", "<script>", false)]
	#[case::img_onerror_in_content(
		"Safe Title",
		r#"<img src=x onerror="alert('xss')">"#,
		"<img",
		false
	)]
	#[case::event_handler_in_title(
		r#"" onmouseover="alert('xss')"#,
		"Safe content",
		r#"onmouseover=""#,
		false
	)]
	#[case::ampersand_escaped("Tom & Jerry", "A & B", "&amp;", true)]
	#[tokio::test]
	async fn test_flatpage_xss_prevention(
		#[case] title: &str,
		#[case] content: &str,
		#[case] pattern: &str,
		#[case] should_contain: bool,
	) {
		// Arrange
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));
		let page = Flatpage::new(
			"/xss-test/".to_string(),
			title.to_string(),
			content.to_string(),
		);
		middleware.store.register(page);
		let handler = Arc::new(TestHandler::not_found());
		let request = Request::builder()
			.method(Method::GET)
			.uri("/xss-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 body = String::from_utf8_lossy(&response.body);
		assert_eq!(
			body.contains(pattern),
			should_contain,
			"Body should {} contain '{}'. Body: {}",
			if should_contain { "" } else { "NOT" },
			pattern,
			body
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_flatpage_xss_full_escape_verification() {
		// Arrange
		let config = FlatpagesConfig::new();
		let middleware = Arc::new(FlatpagesMiddleware::new(config));
		let page = Flatpage::new(
			"/escape-test/".to_string(),
			"<b>Title</b> & 'quotes' \"double\"".to_string(),
			"<script>alert(1)</script>".to_string(),
		);
		middleware.store.register(page);
		let handler = Arc::new(TestHandler::not_found());
		let request = Request::builder()
			.method(Method::GET)
			.uri("/escape-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 body = String::from_utf8_lossy(&response.body);
		// Verify title is escaped
		assert!(body.contains("&lt;b&gt;Title&lt;/b&gt;"));
		assert!(body.contains("&amp;"));
		assert!(body.contains("&#x27;quotes&#x27;"));
		assert!(body.contains("&quot;double&quot;"));
		// Verify content is escaped
		assert!(body.contains("&lt;script&gt;alert(1)&lt;/script&gt;"));
		// Verify no raw HTML tags in output
		assert!(!body.contains("<script>"));
		assert!(!body.contains("</script>"));
	}
}