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
//! Common middleware utilities
//!
//! Provides URL normalization and common request processing patterns.

use async_trait::async_trait;
use hyper::header::HOST;
use hyper::{Method, StatusCode};
use reinhardt_http::{Handler, Middleware, Request, Response, Result};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Common middleware configuration
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommonConfig {
	/// Append trailing slash to URLs that don't have one (except URLs with file extensions)
	pub append_slash: bool,
	/// Prepend 'www.' to the domain if not present
	pub prepend_www: bool,
}

impl CommonConfig {
	/// Create a new CommonConfig with default settings
	///
	/// Default configuration:
	/// - `append_slash`: true - Adds trailing slashes to URLs
	/// - `prepend_www`: false - Does not add www prefix
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_middleware::common::CommonConfig;
	///
	/// let config = CommonConfig::new();
	/// assert!(config.append_slash);
	/// assert!(!config.prepend_www);
	/// ```
	pub fn new() -> Self {
		Self {
			append_slash: true,
			prepend_www: false,
		}
	}
}

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

/// Common middleware for URL normalization
///
/// Handles common URL transformations:
/// - Appending trailing slashes to URLs
/// - Prepending 'www.' to domain names
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
/// use reinhardt_middleware::{CommonMiddleware, CommonConfig};
/// 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 = CommonConfig::new();
/// config.append_slash = true;
/// config.prepend_www = false;
///
/// let middleware = CommonMiddleware::with_config(config);
/// let handler = Arc::new(TestHandler);
///
/// let request = Request::builder()
///     .method(Method::GET)
///     .uri("/path/to/page")
///     .version(Version::HTTP_11)
///     .headers(HeaderMap::new())
///     .body(Bytes::new())
///     .build()
///     .unwrap();
///
/// let response = middleware.process(request, handler).await.unwrap();
/// // URL without trailing slash redirects to /path/to/page/
/// assert_eq!(response.status, StatusCode::MOVED_PERMANENTLY);
/// # });
/// ```
pub struct CommonMiddleware {
	config: CommonConfig,
}

impl CommonMiddleware {
	/// Create a new CommonMiddleware with default configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_middleware::CommonMiddleware;
	///
	/// let middleware = CommonMiddleware::new();
	/// ```
	pub fn new() -> Self {
		Self {
			config: CommonConfig::default(),
		}
	}

	/// Create a new CommonMiddleware with custom configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_middleware::{CommonMiddleware, CommonConfig};
	///
	/// let mut config = CommonConfig::new();
	/// config.append_slash = true;
	/// config.prepend_www = true;
	///
	/// let middleware = CommonMiddleware::with_config(config);
	/// ```
	pub fn with_config(config: CommonConfig) -> Self {
		Self { config }
	}

	/// Check if the URL path should have a trailing slash appended
	fn should_append_slash(&self, path: &str) -> bool {
		if !self.config.append_slash {
			return false;
		}

		// Already ends with slash
		if path.ends_with('/') {
			return false;
		}

		// Check if path looks like a file (has extension)
		if let Some(last_segment) = path.rsplit('/').next()
			&& last_segment.contains('.')
		{
			return false;
		}

		true
	}

	/// Check if the host should have www prepended
	fn should_prepend_www(&self, host: &str) -> bool {
		if !self.config.prepend_www {
			return false;
		}

		// Already has www
		if host.starts_with("www.") {
			return false;
		}

		// Localhost and IPs should not get www
		if host.starts_with("localhost") || host.starts_with("127.") || host.starts_with("192.168.")
		{
			return false;
		}

		true
	}

	/// Build the redirect URL
	fn build_redirect_url(&self, request: &Request) -> Option<String> {
		let path = request.uri.path();
		let query = request.uri.query();

		let host = request
			.headers
			.get(HOST)
			.and_then(|h| h.to_str().ok())
			.unwrap_or("localhost");

		let mut redirect_needed = false;
		let mut new_path = path.to_string();
		let mut new_host = host.to_string();

		// Check if we need to append slash
		if self.should_append_slash(path) {
			new_path.push('/');
			redirect_needed = true;
		}

		// Check if we need to prepend www
		if self.should_prepend_www(host) {
			new_host = format!("www.{}", host);
			redirect_needed = true;
		}

		if !redirect_needed {
			return None;
		}

		// Build the full URL using Request::scheme() which validates trusted proxies
		// before honoring X-Forwarded-Proto headers
		let scheme = request.scheme();

		let url = if let Some(q) = query {
			format!("{}://{}{}?{}", scheme, new_host, new_path, q)
		} else {
			format!("{}://{}{}", scheme, new_host, new_path)
		};

		Some(url)
	}
}

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

#[async_trait]
impl Middleware for CommonMiddleware {
	async fn process(&self, request: Request, handler: Arc<dyn Handler>) -> Result<Response> {
		// Check if we need to redirect
		if let Some(redirect_url) = self.build_redirect_url(&request) {
			// Use 307 Temporary Redirect for non-GET/HEAD methods to preserve
			// the request method and body. Use 301 Moved Permanently for GET/HEAD.
			let status = if matches!(request.method, Method::GET | Method::HEAD) {
				StatusCode::MOVED_PERMANENTLY
			} else {
				StatusCode::TEMPORARY_REDIRECT
			};
			let mut response = Response::new(status);
			response.headers.insert(
				hyper::header::LOCATION,
				redirect_url
					.parse()
					.unwrap_or_else(|_| hyper::header::HeaderValue::from_static("/")),
			);
			return Ok(response);
		}

		// No redirect needed, proceed with the handler
		handler.handle(request).await
	}
}

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

	#[tokio::test]
	async fn test_append_slash_redirects() {
		let config = CommonConfig {
			append_slash: true,
			prepend_www: false,
		};
		let middleware = CommonMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

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

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

		assert_eq!(response.status, StatusCode::MOVED_PERMANENTLY);
		let location = response.headers.get(hyper::header::LOCATION).unwrap();
		assert!(location.to_str().unwrap().contains("/path/to/page/"));
	}

	#[tokio::test]
	async fn test_no_redirect_with_trailing_slash() {
		let config = CommonConfig {
			append_slash: true,
			prepend_www: false,
		};
		let middleware = CommonMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

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

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

		assert_eq!(response.status, StatusCode::OK);
	}

	#[tokio::test]
	async fn test_no_redirect_for_file_extensions() {
		let config = CommonConfig {
			append_slash: true,
			prepend_www: false,
		};
		let middleware = CommonMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/static/file.css")
			.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);
	}

	#[tokio::test]
	async fn test_append_slash_with_query_params() {
		let config = CommonConfig {
			append_slash: true,
			prepend_www: false,
		};
		let middleware = CommonMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

		let request = Request::builder()
			.method(Method::GET)
			.uri("/search?q=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::MOVED_PERMANENTLY);
		let location = response.headers.get(hyper::header::LOCATION).unwrap();
		let loc_str = location.to_str().unwrap();
		assert!(loc_str.contains("/search/"));
		assert!(loc_str.contains("?q=test"));
	}

	#[tokio::test]
	async fn test_prepend_www() {
		let config = CommonConfig {
			append_slash: false,
			prepend_www: true,
		};
		let middleware = CommonMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

		let mut headers = HeaderMap::new();
		headers.insert(HOST, "example.com".parse().unwrap());

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

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

		assert_eq!(response.status, StatusCode::MOVED_PERMANENTLY);
		let location = response.headers.get(hyper::header::LOCATION).unwrap();
		assert!(location.to_str().unwrap().contains("www.example.com"));
	}

	#[tokio::test]
	async fn test_no_prepend_www_for_localhost() {
		let config = CommonConfig {
			append_slash: false,
			prepend_www: true,
		};
		let middleware = CommonMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

		let mut headers = HeaderMap::new();
		headers.insert(HOST, "localhost:8000".parse().unwrap());

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

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

		assert_eq!(response.status, StatusCode::OK);
	}

	#[tokio::test]
	async fn test_no_prepend_www_when_already_present() {
		let config = CommonConfig {
			append_slash: false,
			prepend_www: true,
		};
		let middleware = CommonMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

		let mut headers = HeaderMap::new();
		headers.insert(HOST, "www.example.com".parse().unwrap());

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

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

		assert_eq!(response.status, StatusCode::OK);
	}

	#[tokio::test]
	async fn test_both_transformations() {
		let config = CommonConfig {
			append_slash: true,
			prepend_www: true,
		};
		let middleware = CommonMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

		let mut headers = HeaderMap::new();
		headers.insert(HOST, "example.com".parse().unwrap());

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

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

		assert_eq!(response.status, StatusCode::MOVED_PERMANENTLY);
		let location = response.headers.get(hyper::header::LOCATION).unwrap();
		let loc_str = location.to_str().unwrap();
		assert!(loc_str.contains("www.example.com"));
		assert!(loc_str.contains("/page/"));
	}

	#[tokio::test]
	async fn test_both_disabled() {
		let config = CommonConfig {
			append_slash: false,
			prepend_www: false,
		};
		let middleware = CommonMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

		let mut headers = HeaderMap::new();
		headers.insert(HOST, "example.com".parse().unwrap());

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

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

		assert_eq!(response.status, StatusCode::OK);
	}

	#[rstest]
	#[case::get_returns_301(Method::GET, StatusCode::MOVED_PERMANENTLY)]
	#[case::head_returns_301(Method::HEAD, StatusCode::MOVED_PERMANENTLY)]
	#[case::post_returns_307(Method::POST, StatusCode::TEMPORARY_REDIRECT)]
	#[case::put_returns_307(Method::PUT, StatusCode::TEMPORARY_REDIRECT)]
	#[case::patch_returns_307(Method::PATCH, StatusCode::TEMPORARY_REDIRECT)]
	#[case::delete_returns_307(Method::DELETE, StatusCode::TEMPORARY_REDIRECT)]
	#[tokio::test]
	async fn test_redirect_status_by_method(
		#[case] method: Method,
		#[case] expected_status: StatusCode,
	) {
		// Arrange
		let config = CommonConfig {
			append_slash: true,
			prepend_www: false,
		};
		let middleware = CommonMiddleware::with_config(config);
		let handler = Arc::new(TestHandler);

		let request = Request::builder()
			.method(method)
			.uri("/path/to/page")
			.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, expected_status);
		assert!(response.headers.contains_key(hyper::header::LOCATION));
	}
}