reinhardt-middleware 0.1.0

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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
//! Content Security Policy (CSP) Middleware
//!
//! Provides CSP header management with:
//! - Customizable CSP directives
//! - Nonce generation for inline scripts/styles
//! - Report-Only mode for testing
//! - Per-request CSP overrides

use async_trait::async_trait;
use reinhardt_http::{Handler, Middleware, Request, Response, Result};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tracing::{debug, warn};

/// Type wrapper for CSP nonce stored in Request extensions
#[derive(Debug, Clone)]
pub struct CspNonce(pub String);

/// Validate that a nonce contains only base64 characters [A-Za-z0-9+/=].
///
/// Returns `true` if the nonce is non-empty and contains only valid base64
/// characters. This prevents header injection via malicious nonce values
/// containing characters like newlines, semicolons, or other special chars.
fn is_valid_nonce(nonce: &str) -> bool {
	!nonce.is_empty()
		&& nonce
			.bytes()
			.all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/' || b == b'=')
}

/// CSP directive configuration
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct CspConfig {
	/// CSP directives (e.g., "default-src", "script-src")
	pub directives: HashMap<String, Vec<String>>,
	/// Enable Report-Only mode (for testing without blocking)
	pub report_only: bool,
	/// Generate nonce for inline scripts/styles
	pub include_nonce: bool,
	/// Paths exempt from CSP header insertion.
	///
	/// When a request path matches an exempt prefix (with path-segment boundary
	/// checking), the middleware skips CSP header insertion entirely, allowing
	/// the handler's own CSP to take effect without interference.
	///
	/// This is useful when certain routes (e.g., admin panel) set their own
	/// CSP headers that differ from the application-wide policy.
	pub exempt_paths: HashSet<String>,
}

impl Default for CspConfig {
	fn default() -> Self {
		let mut directives = HashMap::new();
		directives.insert("default-src".to_string(), vec!["'self'".to_string()]);

		Self {
			directives,
			report_only: false,
			include_nonce: false,
			exempt_paths: HashSet::new(),
		}
	}
}

impl CspConfig {
	/// Create a strict CSP configuration
	///
	/// Returns a configuration with restrictive directives suitable for high-security applications.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_middleware::CspConfig;
	///
	/// let config = CspConfig::strict();
	/// assert!(config.directives.contains_key("default-src"));
	/// assert!(config.directives.contains_key("script-src"));
	/// assert!(!config.report_only);
	/// ```
	pub fn strict() -> Self {
		let mut directives = HashMap::new();
		directives.insert("default-src".to_string(), vec!["'self'".to_string()]);
		directives.insert("script-src".to_string(), vec!["'self'".to_string()]);
		directives.insert("style-src".to_string(), vec!["'self'".to_string()]);
		directives.insert(
			"img-src".to_string(),
			vec!["'self'".to_string(), "data:".to_string()],
		);
		directives.insert("font-src".to_string(), vec!["'self'".to_string()]);
		directives.insert("connect-src".to_string(), vec!["'self'".to_string()]);
		directives.insert("frame-ancestors".to_string(), vec!["'none'".to_string()]);
		directives.insert("base-uri".to_string(), vec!["'self'".to_string()]);
		directives.insert("form-action".to_string(), vec!["'self'".to_string()]);

		Self {
			directives,
			report_only: false,
			include_nonce: false,
			exempt_paths: HashSet::new(),
		}
	}

	/// Add a path prefix exempt from CSP header insertion.
	///
	/// Requests whose path matches this prefix (with path-segment boundary
	/// checking) will not have CSP headers set by this middleware, allowing
	/// handler-set CSP to take effect without interference.
	///
	/// Uses the same boundary matching as `CsrfMiddlewareConfig::add_exempt_path`:
	/// exempting `"/admin"` matches `"/admin"` and `"/admin/dashboard"` but
	/// NOT `"/administrator"`.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_middleware::CspConfig;
	///
	/// let config = CspConfig::strict()
	///     .add_exempt_path("/admin".to_string())
	///     .add_exempt_path("/static/admin".to_string());
	///
	/// assert!(config.exempt_paths.contains("/admin"));
	/// assert!(config.exempt_paths.contains("/static/admin"));
	/// ```
	pub fn add_exempt_path(mut self, path: String) -> Self {
		self.exempt_paths.insert(path);
		self
	}
}

/// Content Security Policy middleware
pub struct CspMiddleware {
	config: CspConfig,
}

impl CspMiddleware {
	/// Create a new CspMiddleware with default configuration
	///
	/// Default configuration includes `default-src 'self'` directive.
	///
	/// # Examples
	///
	/// ```
	/// use std::sync::Arc;
	/// use reinhardt_middleware::CspMiddleware;
	/// use reinhardt_http::{Handler, Middleware, Request, Response};
	/// use hyper::{StatusCode, Method, Version, HeaderMap};
	/// use bytes::Bytes;
	///
	/// struct TestHandler;
	///
	/// #[async_trait::async_trait]
	/// impl Handler for TestHandler {
	///     async fn handle(&self, _request: Request) -> reinhardt_core::exception::Result<Response> {
	///         Ok(Response::new(StatusCode::OK))
	///     }
	/// }
	///
	/// # tokio_test::block_on(async {
	/// let middleware = CspMiddleware::new();
	/// 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();
	/// let csp = response.headers.get("Content-Security-Policy").unwrap();
	/// assert!(csp.to_str().unwrap().contains("default-src 'self'"));
	/// # });
	/// ```
	pub fn new() -> Self {
		Self {
			config: CspConfig::default(),
		}
	}
	/// Create a new CspMiddleware with custom configuration
	///
	/// # Arguments
	///
	/// * `config` - Custom CSP configuration
	///
	/// # Examples
	///
	/// ```
	/// use std::sync::Arc;
	/// use reinhardt_middleware::{CspMiddleware, CspConfig};
	/// use reinhardt_http::{Handler, Middleware, Request, Response};
	/// use hyper::{StatusCode, Method, Version, HeaderMap};
	/// use bytes::Bytes;
	/// use std::collections::HashMap;
	///
	/// struct TestHandler;
	///
	/// #[async_trait::async_trait]
	/// impl Handler for TestHandler {
	///     async fn handle(&self, _request: Request) -> reinhardt_core::exception::Result<Response> {
	///         Ok(Response::new(StatusCode::OK))
	///     }
	/// }
	///
	/// # tokio_test::block_on(async {
	/// let mut directives = HashMap::new();
	/// directives.insert("default-src".to_string(), vec!["'self'".to_string()]);
	/// directives.insert("script-src".to_string(), vec!["'self'".to_string(), "https://cdn.example.com".to_string()]);
	///
	/// let mut config = CspConfig::default();
	/// config.directives = directives;
	/// config.report_only = false;
	/// config.include_nonce = false;
	///
	/// let middleware = CspMiddleware::with_config(config);
	/// let handler = Arc::new(TestHandler);
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/app")
	///     .version(Version::HTTP_11)
	///     .headers(HeaderMap::new())
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let response = middleware.process(request, handler).await.unwrap();
	/// let csp = response.headers.get("Content-Security-Policy").unwrap().to_str().unwrap();
	/// assert!(csp.contains("script-src 'self' https://cdn.example.com"));
	/// # });
	/// ```
	pub fn with_config(config: CspConfig) -> Self {
		Self { config }
	}
	/// Create a strict CSP middleware
	///
	/// Uses a restrictive configuration with strong security defaults.
	///
	/// # Examples
	///
	/// ```
	/// use std::sync::Arc;
	/// use reinhardt_middleware::CspMiddleware;
	/// use reinhardt_http::{Handler, Middleware, Request, Response};
	/// use hyper::{StatusCode, Method, Version, HeaderMap};
	/// use bytes::Bytes;
	///
	/// struct TestHandler;
	///
	/// #[async_trait::async_trait]
	/// impl Handler for TestHandler {
	///     async fn handle(&self, _request: Request) -> reinhardt_core::exception::Result<Response> {
	///         Ok(Response::new(StatusCode::OK))
	///     }
	/// }
	///
	/// # tokio_test::block_on(async {
	/// let middleware = CspMiddleware::strict();
	/// let handler = Arc::new(TestHandler);
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/secure-app")
	///     .version(Version::HTTP_11)
	///     .headers(HeaderMap::new())
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let response = middleware.process(request, handler).await.unwrap();
	/// let csp = response.headers.get("Content-Security-Policy").unwrap().to_str().unwrap();
	/// assert!(csp.contains("default-src 'self'"));
	/// assert!(csp.contains("script-src 'self'"));
	/// assert!(csp.contains("frame-ancestors 'none'"));
	/// assert!(csp.contains("base-uri 'self'"));
	/// # });
	/// ```
	pub fn strict() -> Self {
		Self {
			config: CspConfig::strict(),
		}
	}

	/// Generate a random nonce for CSP
	fn generate_nonce(&self) -> String {
		use base64::Engine;
		use rand::RngCore;

		let mut bytes = [0u8; 16];
		rand::rng().fill_bytes(&mut bytes);
		base64::engine::general_purpose::STANDARD.encode(bytes)
	}

	/// Build CSP header value with optional nonce
	///
	/// Nonce values are validated to contain only base64 characters before
	/// embedding in the header to prevent header injection attacks.
	fn build_csp_header(&self, nonce: Option<&str>) -> String {
		let mut parts = Vec::new();

		// Only use the nonce if it passes validation
		let validated_nonce = nonce.filter(|n| is_valid_nonce(n));

		for (directive, values) in &self.config.directives {
			let mut directive_values = values.clone();

			// Add nonce to script-src and style-src if enabled
			if self.config.include_nonce
				&& (directive == "script-src" || directive == "style-src")
				&& let Some(n) = validated_nonce
			{
				directive_values.push(format!("'nonce-{}'", n));
			}

			parts.push(format!("{} {}", directive, directive_values.join(" ")));
		}

		parts.join("; ")
	}

	/// Get the appropriate CSP header name
	fn get_header_name(&self) -> &'static str {
		if self.config.report_only {
			"Content-Security-Policy-Report-Only"
		} else {
			"Content-Security-Policy"
		}
	}
}

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

#[async_trait]
impl Middleware for CspMiddleware {
	async fn process(&self, request: Request, handler: Arc<dyn Handler>) -> Result<Response> {
		// Check if path is exempt from CSP insertion.
		// Uses path-segment boundary matching: exempt "/admin" matches "/admin"
		// and "/admin/dashboard" but NOT "/administrator".
		let path = request.uri.path();
		if self
			.config
			.exempt_paths
			.iter()
			.any(|exempt| path == exempt.as_str() || path.starts_with(&format!("{}/", exempt)))
		{
			debug!(
				path = path,
				"Path is CSP-exempt, skipping CSP header insertion"
			);
			return match handler.handle(request).await {
				Ok(resp) => Ok(resp),
				Err(e) => Ok(Response::from(e)),
			};
		}

		// Generate nonce if enabled
		let nonce = if self.config.include_nonce {
			let generated_nonce = self.generate_nonce();
			// Store nonce in request extensions for template access
			request.extensions.insert(CspNonce(generated_nonce.clone()));
			Some(generated_nonce)
		} else {
			None
		};

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

		// Add CSP header only if handler has not already set one
		let header_name = self.get_header_name();
		if response.headers.contains_key(header_name) {
			debug!(
				header = header_name,
				"CSP header already present in response, skipping middleware insertion"
			);
		} else {
			let csp_value = self.build_csp_header(nonce.as_deref());
			match csp_value.parse() {
				Ok(value) => {
					response.headers.insert(header_name, value);
				}
				Err(e) => {
					warn!(
						error = %e,
						"Failed to parse CSP header value, skipping header insertion"
					);
				}
			}
		}

		Ok(response)
	}
}

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

	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("content")))
		}
	}

	#[tokio::test]
	async fn test_default_csp_header() {
		let middleware = CspMiddleware::new();
		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);
		let csp_header = response.headers.get("Content-Security-Policy").unwrap();
		assert!(csp_header.to_str().unwrap().contains("default-src 'self'"));
	}

	#[tokio::test]
	async fn test_custom_csp_directives() {
		let mut directives = HashMap::new();
		directives.insert("default-src".to_string(), vec!["'self'".to_string()]);
		directives.insert(
			"script-src".to_string(),
			vec!["'self'".to_string(), "https://cdn.example.com".to_string()],
		);

		let config = CspConfig {
			directives,
			report_only: false,
			include_nonce: false,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(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 csp_header = response
			.headers
			.get("Content-Security-Policy")
			.unwrap()
			.to_str()
			.unwrap();
		assert!(csp_header.contains("default-src 'self'"));
		assert!(csp_header.contains("script-src 'self' https://cdn.example.com"));
	}

	#[tokio::test]
	async fn test_report_only_mode() {
		let config = CspConfig {
			directives: {
				let mut d = HashMap::new();
				d.insert("default-src".to_string(), vec!["'self'".to_string()]);
				d
			},
			report_only: true,
			include_nonce: false,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(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!(
			response
				.headers
				.contains_key("Content-Security-Policy-Report-Only")
		);
		assert!(!response.headers.contains_key("Content-Security-Policy"));
	}

	#[tokio::test]
	async fn test_nonce_generation() {
		let config = CspConfig {
			directives: {
				let mut d = HashMap::new();
				d.insert("script-src".to_string(), vec!["'self'".to_string()]);
				d
			},
			report_only: false,
			include_nonce: true,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(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 csp_header = response
			.headers
			.get("Content-Security-Policy")
			.unwrap()
			.to_str()
			.unwrap();
		assert!(csp_header.contains("'nonce-"));
	}

	#[tokio::test]
	async fn test_strict_csp() {
		let middleware = CspMiddleware::strict();
		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 csp_header = response
			.headers
			.get("Content-Security-Policy")
			.unwrap()
			.to_str()
			.unwrap();
		assert!(csp_header.contains("default-src 'self'"));
		assert!(csp_header.contains("script-src 'self'"));
		assert!(csp_header.contains("style-src 'self'"));
		assert!(csp_header.contains("frame-ancestors 'none'"));
		assert!(csp_header.contains("base-uri 'self'"));
	}

	#[tokio::test]
	async fn test_multiple_directive_values() {
		let mut directives = HashMap::new();
		directives.insert(
			"img-src".to_string(),
			vec![
				"'self'".to_string(),
				"data:".to_string(),
				"https:".to_string(),
			],
		);

		let config = CspConfig {
			directives,
			report_only: false,
			include_nonce: false,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(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 csp_header = response
			.headers
			.get("Content-Security-Policy")
			.unwrap()
			.to_str()
			.unwrap();
		assert!(csp_header.contains("img-src 'self' data: https:"));
	}

	#[tokio::test]
	async fn test_nonce_only_added_to_script_and_style() {
		let mut directives = HashMap::new();
		directives.insert("script-src".to_string(), vec!["'self'".to_string()]);
		directives.insert("style-src".to_string(), vec!["'self'".to_string()]);
		directives.insert("img-src".to_string(), vec!["'self'".to_string()]);

		let config = CspConfig {
			directives,
			report_only: false,
			include_nonce: true,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(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 csp_header = response
			.headers
			.get("Content-Security-Policy")
			.unwrap()
			.to_str()
			.unwrap();

		// Count nonce occurrences - should appear in script-src and style-src
		let nonce_count = csp_header.matches("'nonce-").count();
		assert_eq!(nonce_count, 2);
	}

	#[tokio::test]
	async fn test_empty_directives() {
		let config = CspConfig {
			directives: HashMap::new(),
			report_only: false,
			include_nonce: false,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(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();

		// Should still have the header, just empty
		assert!(response.headers.contains_key("Content-Security-Policy"));
	}

	#[tokio::test]
	async fn test_frame_ancestors_directive() {
		let mut directives = HashMap::new();
		directives.insert(
			"frame-ancestors".to_string(),
			vec!["'self'".to_string(), "https://trusted.com".to_string()],
		);

		let config = CspConfig {
			directives,
			report_only: false,
			include_nonce: false,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(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 csp_header = response
			.headers
			.get("Content-Security-Policy")
			.unwrap()
			.to_str()
			.unwrap();
		assert!(csp_header.contains("frame-ancestors 'self' https://trusted.com"));
	}

	#[tokio::test]
	async fn test_nonce_uniqueness_across_requests() {
		let config = CspConfig {
			directives: {
				let mut d = HashMap::new();
				d.insert("script-src".to_string(), vec!["'self'".to_string()]);
				d
			},
			report_only: false,
			include_nonce: true,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

		// First request
		let request1 = Request::builder()
			.method(Method::GET)
			.uri("/page1")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response1 = middleware.process(request1, handler.clone()).await.unwrap();
		let csp1 = response1
			.headers
			.get("Content-Security-Policy")
			.unwrap()
			.to_str()
			.unwrap()
			.to_string();

		// Second request
		let request2 = Request::builder()
			.method(Method::GET)
			.uri("/page2")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response2 = middleware.process(request2, handler).await.unwrap();
		let csp2 = response2
			.headers
			.get("Content-Security-Policy")
			.unwrap()
			.to_str()
			.unwrap()
			.to_string();

		// Extract nonces
		let extract_nonce = |csp: &str| -> Option<String> {
			csp.split("'nonce-")
				.nth(1)
				.and_then(|s| s.split('\'').next())
				.map(|s| s.to_string())
		};

		let nonce1 = extract_nonce(&csp1);
		let nonce2 = extract_nonce(&csp2);

		assert!(nonce1.is_some(), "First CSP should contain nonce");
		assert!(nonce2.is_some(), "Second CSP should contain nonce");

		// Nonces should be different (uniqueness check)
		assert_ne!(nonce1, nonce2, "Nonces should be unique across requests");
	}

	#[tokio::test]
	async fn test_response_body_preserved() {
		struct TestHandlerWithBody;

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

		let middleware = CspMiddleware::new();
		let handler = Arc::new(TestHandlerWithBody);

		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();

		// CSP header should be present
		assert!(response.headers.contains_key("Content-Security-Policy"));

		// Response body should be preserved exactly
		assert_eq!(response.body, Bytes::from("custom response content"));
	}

	#[rstest]
	fn test_nonce_is_valid_base64() {
		// Arrange
		use base64::Engine;
		let middleware = CspMiddleware::new();

		// Act
		let nonce = middleware.generate_nonce();

		// Assert
		let decoded = base64::engine::general_purpose::STANDARD.decode(&nonce);
		assert!(
			decoded.is_ok(),
			"Nonce should be valid base64, got: {}",
			nonce
		);
	}

	#[rstest]
	fn test_nonce_length() {
		// Arrange
		use base64::Engine;
		let middleware = CspMiddleware::new();

		// Act
		let nonce = middleware.generate_nonce();
		let decoded = base64::engine::general_purpose::STANDARD
			.decode(&nonce)
			.unwrap();

		// Assert
		assert_eq!(
			decoded.len(),
			16,
			"Nonce should be exactly 16 bytes (128 bits)"
		);
	}

	#[rstest]
	fn test_is_valid_nonce_accepts_base64() {
		// Arrange & Act & Assert
		assert!(is_valid_nonce("YWJjZGVmZw=="));
		assert!(is_valid_nonce("abc123+/="));
		assert!(is_valid_nonce("ABCDEFGHIJKLMNOP"));
	}

	#[rstest]
	fn test_is_valid_nonce_rejects_invalid_chars() {
		// Arrange & Act & Assert
		assert!(!is_valid_nonce(""));
		assert!(!is_valid_nonce("abc\ndef"));
		assert!(!is_valid_nonce("abc;def"));
		assert!(!is_valid_nonce("abc def"));
		assert!(!is_valid_nonce("abc'def"));
		assert!(!is_valid_nonce("abc\rdef"));
	}

	#[rstest]
	fn test_build_csp_header_rejects_invalid_nonce() {
		// Arrange
		let mut directives = HashMap::new();
		directives.insert("script-src".to_string(), vec!["'self'".to_string()]);
		let config = CspConfig {
			directives,
			report_only: false,
			include_nonce: true,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(config);

		// Act - nonce with header injection attempt (newline + semicolon)
		let csp = middleware.build_csp_header(Some("abc\r\ndef;injected"));

		// Assert - invalid nonce should be silently dropped
		assert!(
			!csp.contains("nonce-"),
			"Invalid nonce should not be embedded in header"
		);
		assert!(csp.contains("script-src 'self'"));
	}

	#[rstest]
	fn test_nonce_entropy() {
		// Arrange
		let middleware = CspMiddleware::new();
		let mut nonces = std::collections::HashSet::new();

		// Act
		for _ in 0..100 {
			nonces.insert(middleware.generate_nonce());
		}

		// Assert
		assert_eq!(
			nonces.len(),
			100,
			"All 100 nonces should be unique (statistical randomness)"
		);
	}

	#[tokio::test]
	async fn test_does_not_override_existing_csp_header() {
		// Arrange
		struct HandlerWithCsp;

		#[async_trait]
		impl Handler for HandlerWithCsp {
			async fn handle(&self, _request: Request) -> Result<Response> {
				Ok(Response::new(StatusCode::OK).with_header(
					"Content-Security-Policy",
					"default-src 'self'; style-src 'self' 'unsafe-inline'",
				))
			}
		}

		let middleware = CspMiddleware::strict();
		let handler = Arc::new(HandlerWithCsp);

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

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

		// Assert - handler's CSP should be preserved, not overwritten by middleware
		let csp = response
			.headers
			.get("Content-Security-Policy")
			.unwrap()
			.to_str()
			.unwrap();
		assert!(
			csp.contains("'unsafe-inline'"),
			"Handler-set CSP should be preserved, got: {}",
			csp
		);
	}

	#[tokio::test]
	async fn test_does_not_override_existing_csp_report_only_header() {
		// Arrange
		struct HandlerWithReportOnlyCsp;

		#[async_trait]
		impl Handler for HandlerWithReportOnlyCsp {
			async fn handle(&self, _request: Request) -> Result<Response> {
				Ok(Response::new(StatusCode::OK)
					.with_header("Content-Security-Policy-Report-Only", "default-src 'none'"))
			}
		}

		let config = CspConfig {
			directives: {
				let mut d = HashMap::new();
				d.insert("default-src".to_string(), vec!["'self'".to_string()]);
				d
			},
			report_only: true,
			include_nonce: false,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(config);
		let handler = Arc::new(HandlerWithReportOnlyCsp);

		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's report-only CSP should be preserved
		let csp = response
			.headers
			.get("Content-Security-Policy-Report-Only")
			.unwrap()
			.to_str()
			.unwrap();
		assert_eq!(
			csp, "default-src 'none'",
			"Handler-set report-only CSP should be preserved"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_exempt_path_skips_csp() {
		// Arrange
		let config = CspConfig::strict().add_exempt_path("/admin".to_string());
		let middleware = CspMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

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

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

		// Assert - CSP should not be set for exempt path
		assert!(
			!response.headers.contains_key("Content-Security-Policy"),
			"CSP should not be set for exempt path"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_exempt_path_exact_match() {
		// Arrange
		let config = CspConfig::strict().add_exempt_path("/admin".to_string());
		let middleware = CspMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

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

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

		// Assert - exact match should also be exempt
		assert!(
			!response.headers.contains_key("Content-Security-Policy"),
			"CSP should not be set for exact exempt path match"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_non_exempt_path_gets_csp() {
		// Arrange
		let config = CspConfig::strict().add_exempt_path("/admin".to_string());
		let middleware = CspMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

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

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

		// Assert - non-exempt path should still get CSP
		assert!(
			response.headers.contains_key("Content-Security-Policy"),
			"CSP should be set for non-exempt path"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_exempt_path_boundary_prevents_false_match() {
		// Arrange - exempt "/admin" should NOT exempt "/administrator"
		let config = CspConfig::strict().add_exempt_path("/admin".to_string());
		let middleware = CspMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

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

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

		// Assert - /administrator should NOT be exempt
		assert!(
			response.headers.contains_key("Content-Security-Policy"),
			"/administrator should NOT be exempt when only /admin is in exempt_paths"
		);
	}

	#[rstest]
	fn test_csp_config_add_exempt_path() {
		// Arrange & Act
		let config = CspConfig::default()
			.add_exempt_path("/admin".to_string())
			.add_exempt_path("/static/admin".to_string());

		// Assert
		assert!(config.exempt_paths.contains("/admin"));
		assert!(config.exempt_paths.contains("/static/admin"));
		assert_eq!(config.exempt_paths.len(), 2);
	}

	/// Handler that always returns an error to simulate inner handler failure.
	struct ErrorHandler;

	#[async_trait]
	impl Handler for ErrorHandler {
		async fn handle(&self, _request: Request) -> Result<Response> {
			Err(reinhardt_http::Error::Http("handler error".to_string()))
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_csp_header_applied_on_handler_error() {
		// Arrange
		let config = CspConfig {
			directives: {
				let mut d = HashMap::new();
				d.insert("default-src".to_string(), vec!["'none'".to_string()]);
				d
			},
			report_only: false,
			include_nonce: false,
			exempt_paths: HashSet::new(),
		};
		let middleware = CspMiddleware::with_config(config);
		let handler: Arc<dyn Handler> = Arc::new(ErrorHandler);

		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 — error is converted to response with CSP header applied
		assert!(response.status.is_client_error() || response.status.is_server_error());
		assert!(
			response.headers.contains_key("Content-Security-Policy"),
			"CSP header should be applied even when handler returns an error"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_csp_exempt_path_error_converted_to_response() {
		// Arrange
		let config = CspConfig::strict().add_exempt_path("/exempt".to_string());
		let middleware = CspMiddleware::with_config(config);
		let handler: Arc<dyn Handler> = Arc::new(ErrorHandler);

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

		// Act — should return Ok even though handler errors, because errors are
		// converted to responses
		let result = middleware.process(request, handler).await;

		// Assert
		assert!(
			result.is_ok(),
			"Handler error should be converted to response for exempt path"
		);
		let response = result.unwrap();
		assert!(response.status.is_client_error() || response.status.is_server_error());
	}

	#[rstest]
	#[tokio::test]
	async fn test_multiple_exempt_paths() {
		// Arrange
		let config = CspConfig::strict()
			.add_exempt_path("/admin".to_string())
			.add_exempt_path("/static/admin".to_string());
		let middleware = CspMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

		// Act & Assert - both paths should be exempt
		for uri in ["/admin/dashboard", "/static/admin/style.css"] {
			let request = Request::builder()
				.method(Method::GET)
				.uri(uri)
				.version(Version::HTTP_11)
				.headers(HeaderMap::new())
				.body(Bytes::new())
				.build()
				.unwrap();

			let response = middleware.process(request, handler.clone()).await.unwrap();
			assert!(
				!response.headers.contains_key("Content-Security-Policy"),
				"Path {} should be exempt from CSP",
				uri
			);
		}
	}
}