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
use async_trait::async_trait;
use reinhardt_http::{Handler, Middleware, Request, Response, Result};
use std::sync::Arc;

/// CORS middleware configuration
#[non_exhaustive]
pub struct CorsConfig {
	/// Origins allowed to make cross-origin requests (e.g., `"*"` or specific domains).
	pub allow_origins: Vec<String>,
	/// HTTP methods allowed for cross-origin requests.
	pub allow_methods: Vec<String>,
	/// HTTP headers allowed in cross-origin requests.
	pub allow_headers: Vec<String>,
	/// Whether to include credentials (cookies, authorization headers) in CORS requests.
	pub allow_credentials: bool,
	/// Maximum time (in seconds) the browser should cache preflight responses.
	pub max_age: Option<u64>,
}

impl Default for CorsConfig {
	fn default() -> Self {
		Self {
			allow_origins: vec!["*".to_string()],
			allow_methods: vec![
				"GET".to_string(),
				"POST".to_string(),
				"PUT".to_string(),
				"PATCH".to_string(),
				"DELETE".to_string(),
				"OPTIONS".to_string(),
			],
			allow_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
			allow_credentials: false,
			max_age: Some(3600),
		}
	}
}

/// CORS middleware
pub struct CorsMiddleware {
	config: CorsConfig,
}

impl CorsMiddleware {
	/// Create a new CORS middleware with custom configuration
	///
	/// # Arguments
	///
	/// * `config` - CORS configuration specifying allowed origins, methods, headers, etc.
	///
	/// # Examples
	///
	/// ```
	/// use std::sync::Arc;
	/// use reinhardt_middleware::{CorsMiddleware, cors::CorsConfig};
	/// 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).with_body(Bytes::from("OK")))
	///     }
	/// }
	///
	/// # tokio_test::block_on(async {
	/// let mut config = CorsConfig::default();
	/// config.allow_origins = vec!["https://example.com".to_string()];
	/// config.allow_methods = vec!["GET".to_string(), "POST".to_string()];
	/// config.allow_headers = vec!["Content-Type".to_string()];
	/// config.allow_credentials = true;
	/// config.max_age = Some(3600);
	///
	/// let middleware = CorsMiddleware::new(config);
	/// let handler = Arc::new(TestHandler);
	///
	/// let mut headers = HeaderMap::new();
	/// headers.insert("origin", "https://example.com".parse().unwrap());
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/api/data")
	///     .version(Version::HTTP_11)
	///     .headers(headers)
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let response = middleware.process(request, handler).await.unwrap();
	/// assert_eq!(response.headers.get("Access-Control-Allow-Origin").unwrap(), "https://example.com");
	/// assert_eq!(response.headers.get("Access-Control-Allow-Credentials").unwrap(), "true");
	/// # });
	/// ```
	pub fn new(config: CorsConfig) -> Self {
		Self { config }
	}
	/// Create a permissive CORS middleware that allows all origins
	///
	/// This is useful for development but should be used with caution in production.
	///
	/// # Examples
	///
	/// ```
	/// use std::sync::Arc;
	/// use reinhardt_middleware::CorsMiddleware;
	/// 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 = CorsMiddleware::permissive();
	/// let handler = Arc::new(TestHandler);
	///
	/// // Preflight request
	/// let request = Request::builder()
	///     .method(Method::OPTIONS)
	///     .uri("/api/users")
	///     .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::NO_CONTENT);
	/// assert!(response.headers.contains_key("Access-Control-Allow-Origin"));
	/// assert!(response.headers.contains_key("Access-Control-Allow-Methods"));
	/// # });
	/// ```
	pub fn permissive() -> Self {
		Self::new(CorsConfig::default())
	}
}

#[async_trait]
impl Middleware for CorsMiddleware {
	async fn process(&self, request: Request, next: Arc<dyn Handler>) -> Result<Response> {
		// Extract request Origin header for validation
		let request_origin = request
			.headers
			.get(hyper::header::ORIGIN)
			.and_then(|v| v.to_str().ok())
			.map(|s| s.to_string());

		// Determine the allowed origin value for this request
		let allowed_origin = self.resolve_origin(request_origin.as_deref());

		// Handle preflight OPTIONS request
		if request.method.as_str() == "OPTIONS" {
			let mut response = Response::no_content();

			if let Some(origin) = &allowed_origin {
				response.headers.insert(
					hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN,
					hyper::header::HeaderValue::from_str(origin)
						.unwrap_or_else(|_| hyper::header::HeaderValue::from_static("*")),
				);
			}

			response.headers.insert(
				hyper::header::ACCESS_CONTROL_ALLOW_METHODS,
				hyper::header::HeaderValue::from_str(&self.config.allow_methods.join(", "))
					.unwrap_or_else(|_| hyper::header::HeaderValue::from_static("*")),
			);

			response.headers.insert(
				hyper::header::ACCESS_CONTROL_ALLOW_HEADERS,
				hyper::header::HeaderValue::from_str(&self.config.allow_headers.join(", "))
					.unwrap_or_else(|_| hyper::header::HeaderValue::from_static("*")),
			);

			if let Some(max_age) = self.config.max_age {
				response.headers.insert(
					hyper::header::ACCESS_CONTROL_MAX_AGE,
					hyper::header::HeaderValue::from_str(&max_age.to_string())
						.unwrap_or_else(|_| hyper::header::HeaderValue::from_static("3600")),
				);
			}

			if self.config.allow_credentials {
				response.headers.insert(
					hyper::header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
					hyper::header::HeaderValue::from_static("true"),
				);
			}

			// Add Vary: Origin when origin depends on request
			if self.config.allow_origins.len() > 1
				|| !self.config.allow_origins.contains(&"*".to_string())
				|| self.config.allow_credentials
			{
				response.headers.append(
					hyper::header::VARY,
					hyper::header::HeaderValue::from_static("Origin"),
				);
			}

			return Ok(response);
		}

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

		if let Some(origin) = &allowed_origin {
			response.headers.insert(
				hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN,
				hyper::header::HeaderValue::from_str(origin)
					.unwrap_or_else(|_| hyper::header::HeaderValue::from_static("*")),
			);
		}

		if self.config.allow_credentials {
			response.headers.insert(
				hyper::header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
				hyper::header::HeaderValue::from_static("true"),
			);
		}

		// Add Vary: Origin when origin depends on request
		if self.config.allow_origins.len() > 1
			|| !self.config.allow_origins.contains(&"*".to_string())
			|| self.config.allow_credentials
		{
			response.headers.append(
				hyper::header::VARY,
				hyper::header::HeaderValue::from_static("Origin"),
			);
		}

		Ok(response)
	}
}

impl CorsMiddleware {
	/// Resolve the origin to include in the response based on the request origin.
	///
	/// Per the CORS specification (Fetch Standard), `Access-Control-Allow-Origin`
	/// must be either `*`, a single origin, or `null`. Multiple origins in a
	/// single header value are not valid.
	fn resolve_origin(&self, request_origin: Option<&str>) -> Option<String> {
		// Wildcard: allow all origins
		if self.config.allow_origins.contains(&"*".to_string()) {
			// When credentials are enabled, wildcard is not allowed per spec;
			// reflect the request origin instead
			if self.config.allow_credentials {
				return request_origin.map(|o| o.to_string());
			}
			return Some("*".to_string());
		}

		// Check if the request origin matches any allowed origin
		if let Some(origin) = request_origin
			&& self.config.allow_origins.iter().any(|o| o == origin)
		{
			return Some(origin.to_string());
		}

		// No match: omit the CORS origin header
		None
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use bytes::Bytes;
	use hyper::{HeaderMap, Method, StatusCode, Version};
	use reinhardt_http::Error;
	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("test response")))
		}
	}

	/// Helper to create a request with an Origin header
	fn create_request_with_origin(method: Method, uri: &str, origin: &str) -> Request {
		let mut headers = HeaderMap::new();
		headers.insert(
			hyper::header::ORIGIN,
			hyper::header::HeaderValue::from_str(origin).unwrap(),
		);

		Request::builder()
			.method(method)
			.uri(uri)
			.version(Version::HTTP_11)
			.headers(headers)
			.body(Bytes::new())
			.build()
			.unwrap()
	}

	#[tokio::test]
	async fn test_preflight_request_with_matching_origin() {
		// Arrange
		let config = CorsConfig {
			allow_origins: vec!["https://example.com".to_string()],
			allow_methods: vec!["GET".to_string(), "POST".to_string()],
			allow_headers: vec!["Content-Type".to_string()],
			allow_credentials: true,
			max_age: Some(7200),
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request =
			create_request_with_origin(Method::OPTIONS, "/api/test", "https://example.com");

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

		// Assert
		assert_eq!(response.status, StatusCode::NO_CONTENT);

		// Origin header should reflect the matching origin (not multiple)
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.unwrap(),
			"https://example.com"
		);

		assert!(
			response
				.headers
				.contains_key(hyper::header::ACCESS_CONTROL_ALLOW_METHODS)
		);
		assert!(
			response
				.headers
				.contains_key(hyper::header::ACCESS_CONTROL_ALLOW_HEADERS)
		);
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_MAX_AGE)
				.unwrap(),
			"7200"
		);
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
				.unwrap(),
			"true"
		);
		// Vary: Origin should be present when origin list is not wildcard
		assert_eq!(response.headers.get(hyper::header::VARY).unwrap(), "Origin");
	}

	#[tokio::test]
	async fn test_regular_request_with_matching_origin() {
		// Arrange
		let config = CorsConfig {
			allow_origins: vec!["https://app.example.com".to_string()],
			allow_methods: vec!["GET".to_string()],
			allow_headers: vec!["Authorization".to_string()],
			allow_credentials: false,
			max_age: None,
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request =
			create_request_with_origin(Method::GET, "/api/data", "https://app.example.com");

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

		// Assert
		assert_eq!(response.status, StatusCode::OK);
		assert_eq!(response.body, Bytes::from("test response"));

		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.unwrap(),
			"https://app.example.com"
		);

		assert!(
			!response
				.headers
				.contains_key(hyper::header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
		);

		// Vary: Origin should be present
		assert_eq!(response.headers.get(hyper::header::VARY).unwrap(), "Origin");
	}

	#[tokio::test]
	async fn test_request_with_non_matching_origin_omits_cors_headers() {
		// Arrange
		let config = CorsConfig {
			allow_origins: vec!["https://allowed.example.com".to_string()],
			allow_methods: vec!["GET".to_string()],
			allow_headers: vec!["Content-Type".to_string()],
			allow_credentials: false,
			max_age: None,
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request =
			create_request_with_origin(Method::GET, "/api/data", "https://evil.example.com");

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

		// Assert: request is still processed, but no CORS origin header
		assert_eq!(response.status, StatusCode::OK);
		assert!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.is_none()
		);
	}

	#[tokio::test]
	async fn test_permissive_mode_wildcard() {
		// Arrange
		let middleware = CorsMiddleware::permissive();
		let handler = Arc::new(TestHandler);

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

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

		// Assert
		assert_eq!(response.status, StatusCode::NO_CONTENT);

		// Wildcard origin
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.unwrap(),
			"*"
		);

		// Methods should be listed
		let methods_header = response
			.headers
			.get(hyper::header::ACCESS_CONTROL_ALLOW_METHODS)
			.unwrap()
			.to_str()
			.unwrap();
		assert!(methods_header.contains("GET"));
		assert!(methods_header.contains("POST"));
		assert!(methods_header.contains("PUT"));
		assert!(methods_header.contains("DELETE"));
	}

	#[tokio::test]
	async fn test_multiple_allowed_origins_reflects_matching_one() {
		// Arrange
		let config = CorsConfig {
			allow_origins: vec![
				"https://app1.example.com".to_string(),
				"https://app2.example.com".to_string(),
			],
			allow_methods: vec!["GET".to_string()],
			allow_headers: vec!["Content-Type".to_string()],
			allow_credentials: true,
			max_age: Some(3600),
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request =
			create_request_with_origin(Method::GET, "/api/resource", "https://app2.example.com");

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

		// Assert: only the matching origin is reflected (not both joined)
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.unwrap(),
			"https://app2.example.com"
		);

		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
				.unwrap(),
			"true"
		);

		// Vary: Origin must be present
		assert_eq!(response.headers.get(hyper::header::VARY).unwrap(), "Origin");
	}

	#[tokio::test]
	async fn test_multiple_origins_no_match_omits_origin_header() {
		// Arrange
		let config = CorsConfig {
			allow_origins: vec![
				"https://app1.example.com".to_string(),
				"https://app2.example.com".to_string(),
			],
			allow_methods: vec!["GET".to_string()],
			allow_headers: vec!["Content-Type".to_string()],
			allow_credentials: false,
			max_age: None,
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request = create_request_with_origin(
			Method::GET,
			"/api/resource",
			"https://attacker.example.com",
		);

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

		// Assert: no origin header for non-matching origin
		assert!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.is_none()
		);
	}

	#[tokio::test]
	async fn test_wildcard_with_credentials_reflects_origin() {
		// Arrange: wildcard + credentials requires reflecting origin per spec
		let config = CorsConfig {
			allow_origins: vec!["*".to_string()],
			allow_methods: vec!["GET".to_string()],
			allow_headers: vec!["Content-Type".to_string()],
			allow_credentials: true,
			max_age: None,
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request =
			create_request_with_origin(Method::GET, "/api/data", "https://any-origin.example.com");

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

		// Assert: should reflect the origin, not "*" (credentials mode)
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.unwrap(),
			"https://any-origin.example.com"
		);

		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
				.unwrap(),
			"true"
		);
	}

	#[tokio::test]
	async fn test_request_without_origin_header() {
		// Arrange
		let config = CorsConfig {
			allow_origins: vec!["https://example.com".to_string()],
			allow_methods: vec!["GET".to_string()],
			allow_headers: vec!["Content-Type".to_string()],
			allow_credentials: false,
			max_age: None,
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		// No Origin header (same-origin request)
		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: no origin header when no Origin in request
		assert_eq!(response.status, StatusCode::OK);
		assert!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.is_none()
		);
	}

	#[tokio::test]
	async fn test_wildcard_with_credentials_adds_vary_header_preflight() {
		// Arrange: wildcard origins + credentials enabled (cache poisoning scenario)
		let config = CorsConfig {
			allow_origins: vec!["*".to_string()],
			allow_methods: vec!["GET".to_string(), "POST".to_string()],
			allow_headers: vec!["Content-Type".to_string()],
			allow_credentials: true,
			max_age: None,
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request = create_request_with_origin(
			Method::OPTIONS,
			"/api/data",
			"https://attacker.example.com",
		);

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

		// Assert: preflight response must include Vary: Origin to prevent cache poisoning
		assert_eq!(response.status, StatusCode::NO_CONTENT);
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.unwrap(),
			"https://attacker.example.com"
		);
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
				.unwrap(),
			"true"
		);
		// Vary: Origin MUST be present when credentials + wildcard causes origin reflection
		assert_eq!(response.headers.get(hyper::header::VARY).unwrap(), "Origin");
	}

	#[tokio::test]
	async fn test_wildcard_with_credentials_adds_vary_header_regular_request() {
		// Arrange: wildcard origins + credentials enabled (cache poisoning scenario)
		let config = CorsConfig {
			allow_origins: vec!["*".to_string()],
			allow_methods: vec!["GET".to_string()],
			allow_headers: vec!["Content-Type".to_string()],
			allow_credentials: true,
			max_age: None,
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request =
			create_request_with_origin(Method::GET, "/api/data", "https://victim.example.com");

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

		// Assert: regular response must include Vary: Origin to prevent cache poisoning
		assert_eq!(response.status, StatusCode::OK);
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.unwrap(),
			"https://victim.example.com"
		);
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_CREDENTIALS)
				.unwrap(),
			"true"
		);
		// Vary: Origin MUST be present when credentials + wildcard causes origin reflection
		assert_eq!(response.headers.get(hyper::header::VARY).unwrap(), "Origin");
	}

	/// Handler that returns a response with an existing Vary header
	struct VaryHandler;

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

	#[rstest::rstest]
	#[tokio::test]
	async fn test_cors_preserves_existing_vary_header() {
		// Arrange
		let config = CorsConfig {
			allow_origins: vec!["https://example.com".to_string()],
			allow_methods: vec!["GET".to_string()],
			allow_headers: vec![],
			allow_credentials: false,
			max_age: None,
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(VaryHandler);

		let request = create_request_with_origin(Method::GET, "/api/test", "https://example.com");

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

		// Assert - both the existing Vary: Accept-Encoding and the appended Vary: Origin
		let vary_values: Vec<&str> = response
			.headers
			.get_all(hyper::header::VARY)
			.iter()
			.map(|v| v.to_str().unwrap())
			.collect();
		assert!(
			vary_values.contains(&"Accept-Encoding"),
			"Existing Vary header should be preserved"
		);
		assert!(
			vary_values.contains(&"Origin"),
			"CORS Vary: Origin should be appended"
		);
	}

	#[rstest::rstest]
	#[tokio::test]
	async fn test_cors_preserves_existing_vary_header_preflight() {
		// Arrange
		let config = CorsConfig {
			allow_origins: vec!["https://example.com".to_string()],
			allow_methods: vec!["GET".to_string(), "POST".to_string()],
			allow_headers: vec!["Content-Type".to_string()],
			allow_credentials: true,
			max_age: None,
		};
		let middleware = CorsMiddleware::new(config);
		let handler = Arc::new(TestHandler);

		let request =
			create_request_with_origin(Method::OPTIONS, "/api/test", "https://example.com");

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

		// Assert - Vary: Origin should be present via append (not insert)
		let vary_values: Vec<&str> = response
			.headers
			.get_all(hyper::header::VARY)
			.iter()
			.map(|v| v.to_str().unwrap())
			.collect();
		assert!(
			vary_values.contains(&"Origin"),
			"CORS Vary: Origin should be present in preflight"
		);
	}

	/// 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(Error::Http("handler error".to_string()))
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_cors_headers_applied_on_handler_error() {
		// Arrange
		let middleware = CorsMiddleware::permissive();
		let handler: Arc<dyn Handler> = Arc::new(ErrorHandler);

		let request = create_request_with_origin(Method::GET, "/test", "http://example.com");

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

		// Assert — error is converted to response, CORS headers applied
		assert!(response.status.is_client_error() || response.status.is_server_error());
		assert_eq!(
			response
				.headers
				.get(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN)
				.unwrap(),
			"*"
		);
	}
}