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
//! Conditional GET Middleware
//!
//! Handles ETags and Last-Modified headers for conditional GET requests.

use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use hyper::header::{
	ETAG, IF_MATCH, IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_UNMODIFIED_SINCE, LAST_MODIFIED,
};
use hyper::{Method, StatusCode};
use reinhardt_http::{Handler, Middleware, Request, Response, Result};
use sha2::{Digest, Sha256};
use std::sync::Arc;

/// Conditional GET middleware
///
/// Implements HTTP conditional requests using ETags and Last-Modified headers.
/// - Supports If-None-Match (ETag-based)
/// - Supports If-Modified-Since (Last-Modified-based)
/// - Supports If-Match and If-Unmodified-Since for safe methods
pub struct ConditionalGetMiddleware {
	/// Whether to generate ETags automatically
	generate_etag: bool,
}

impl ConditionalGetMiddleware {
	/// Create a new ConditionalGetMiddleware
	///
	/// By default, automatic ETag generation is enabled for responses.
	///
	/// # Examples
	///
	/// ```
	/// use std::sync::Arc;
	/// use reinhardt_middleware::ConditionalGetMiddleware;
	/// 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("content")))
	///     }
	/// }
	///
	/// # tokio_test::block_on(async {
	/// let middleware = ConditionalGetMiddleware::new();
	/// let handler = Arc::new(TestHandler);
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/api/resource")
	///     .version(Version::HTTP_11)
	///     .headers(HeaderMap::new())
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let response = middleware.process(request, handler).await.unwrap();
	/// assert_eq!(response.status, StatusCode::OK);
	/// assert!(response.headers.contains_key(hyper::header::ETAG));
	/// # });
	/// ```
	pub fn new() -> Self {
		Self {
			generate_etag: true,
		}
	}
	/// Create middleware without automatic ETag generation
	///
	/// Use this when you want to handle ETags manually or rely only on Last-Modified headers.
	///
	/// # Examples
	///
	/// ```
	/// use std::sync::Arc;
	/// use reinhardt_middleware::ConditionalGetMiddleware;
	/// 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> {
	///         let mut response = Response::new(StatusCode::OK).with_body(Bytes::from("content"));
	///         response.headers.insert(
	///             hyper::header::LAST_MODIFIED,
	///             "Wed, 21 Oct 2015 07:28:00 GMT".parse().unwrap()
	///         );
	///         Ok(response)
	///     }
	/// }
	///
	/// # tokio_test::block_on(async {
	/// let middleware = ConditionalGetMiddleware::without_etag();
	/// let handler = Arc::new(TestHandler);
	///
	/// let request = Request::builder()
	///     .method(Method::GET)
	///     .uri("/api/resource")
	///     .version(Version::HTTP_11)
	///     .headers(HeaderMap::new())
	///     .body(Bytes::new())
	///     .build()
	///     .unwrap();
	///
	/// let response = middleware.process(request, handler).await.unwrap();
	/// assert_eq!(response.status, StatusCode::OK);
	/// assert!(!response.headers.contains_key(hyper::header::ETAG));
	/// assert!(response.headers.contains_key(hyper::header::LAST_MODIFIED));
	/// # });
	/// ```
	pub fn without_etag() -> Self {
		Self {
			generate_etag: false,
		}
	}

	/// Generate an ETag from response body
	fn generate_etag_from_body(&self, body: &[u8]) -> String {
		let mut hasher = Sha256::new();
		hasher.update(body);
		let result = hasher.finalize();
		format!("\"{}\"", hex::encode(&result[..16]))
	}

	/// Parse If-None-Match header
	fn parse_if_none_match(&self, value: &str) -> Vec<String> {
		value.split(',').map(|s| s.trim().to_string()).collect()
	}

	/// Check if ETag matches
	fn etag_matches(&self, etag: &str, if_none_match: &[String]) -> bool {
		if_none_match
			.iter()
			.any(|inm| inm == "*" || inm == etag || inm.trim_matches('"') == etag.trim_matches('"'))
	}

	/// Parse HTTP date
	fn parse_http_date(&self, value: &str) -> Option<DateTime<Utc>> {
		httpdate::parse_http_date(value).ok().map(DateTime::from)
	}
}

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

#[async_trait]
impl Middleware for ConditionalGetMiddleware {
	async fn process(&self, request: Request, handler: Arc<dyn Handler>) -> Result<Response> {
		// Store request headers for later use
		let if_none_match = request.headers.get(IF_NONE_MATCH).cloned();
		let if_modified_since = request.headers.get(IF_MODIFIED_SINCE).cloned();
		let if_match = request.headers.get(IF_MATCH).cloned();
		let if_unmodified_since = request.headers.get(IF_UNMODIFIED_SINCE).cloned();
		let method = request.method.clone();

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

		// Only process GET and HEAD requests
		if method != Method::GET && method != Method::HEAD {
			return Ok(response);
		}

		// Only process successful responses
		if !response.status.is_success() {
			return Ok(response);
		}

		// Generate ETag if not present and configured to do so
		let etag = if self.generate_etag && !response.headers.contains_key(ETAG) {
			let generated = self.generate_etag_from_body(&response.body);
			if let Ok(etag_value) = generated.parse() {
				response.headers.insert(ETAG, etag_value);
				Some(generated)
			} else {
				// ETag value could not be parsed as a valid header value;
				// treat as if no ETag was generated
				None
			}
		} else {
			response
				.headers
				.get(ETAG)
				.and_then(|v| v.to_str().ok())
				.map(|s| s.to_string())
		};

		// Get Last-Modified if present
		let last_modified = response
			.headers
			.get(LAST_MODIFIED)
			.and_then(|v| v.to_str().ok())
			.and_then(|s| self.parse_http_date(s));

		// Check If-None-Match (ETag)
		if let Some(if_none_match) = if_none_match
			&& let (Ok(inm_str), Some(etag_value)) = (if_none_match.to_str(), etag.as_ref())
		{
			let inm_list = self.parse_if_none_match(inm_str);
			if self.etag_matches(etag_value, &inm_list) {
				// Return 304 Not Modified
				let mut not_modified = Response::new(StatusCode::NOT_MODIFIED);

				// Copy relevant headers
				if let Some(etag_header) = response.headers.get(ETAG) {
					not_modified.headers.insert(ETAG, etag_header.clone());
				}
				if let Some(lm_header) = response.headers.get(LAST_MODIFIED) {
					not_modified
						.headers
						.insert(LAST_MODIFIED, lm_header.clone());
				}

				return Ok(not_modified);
			}
		}

		// Check If-Modified-Since (Last-Modified)
		if let Some(if_modified_since) = if_modified_since
			&& let (Ok(ims_str), Some(lm)) = (if_modified_since.to_str(), last_modified)
			&& let Some(ims) = self.parse_http_date(ims_str)
		{
			// If resource hasn't been modified since the given date
			if lm <= ims {
				// Return 304 Not Modified
				let mut not_modified = Response::new(StatusCode::NOT_MODIFIED);

				// Copy relevant headers
				if let Some(etag_header) = response.headers.get(ETAG) {
					not_modified.headers.insert(ETAG, etag_header.clone());
				}
				if let Some(lm_header) = response.headers.get(LAST_MODIFIED) {
					not_modified
						.headers
						.insert(LAST_MODIFIED, lm_header.clone());
				}

				return Ok(not_modified);
			}
		}

		// Check If-Match (for safe methods, should match)
		if let Some(if_match) = if_match
			&& let (Ok(im_str), Some(etag_value)) = (if_match.to_str(), etag.as_ref())
		{
			let im_list = self.parse_if_none_match(im_str);
			if !self.etag_matches(etag_value, &im_list) && !im_list.contains(&"*".to_string()) {
				// Return 412 Precondition Failed
				return Ok(Response::new(StatusCode::PRECONDITION_FAILED)
					.with_body(Bytes::from(&b"Precondition Failed"[..])));
			}
		}

		// Check If-Unmodified-Since
		if let Some(if_unmodified_since) = if_unmodified_since
			&& let (Ok(ius_str), Some(lm)) = (if_unmodified_since.to_str(), last_modified)
			&& let Some(ius) = self.parse_http_date(ius_str)
		{
			// If resource has been modified since the given date
			if lm > ius {
				// Return 412 Precondition Failed
				return Ok(Response::new(StatusCode::PRECONDITION_FAILED)
					.with_body(Bytes::from(&b"Precondition Failed"[..])));
			}
		}

		Ok(response)
	}
}

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

	struct TestHandler {
		body: &'static str,
		with_etag: Option<String>,
		with_last_modified: Option<DateTime<Utc>>,
	}

	#[async_trait]
	impl Handler for TestHandler {
		async fn handle(&self, _request: Request) -> Result<Response> {
			let mut response = Response::new(StatusCode::OK).with_body(self.body.as_bytes());

			if let Some(ref etag) = self.with_etag {
				response.headers.insert(ETAG, etag.parse().unwrap());
			}

			if let Some(lm) = self.with_last_modified {
				let lm_str = httpdate::fmt_http_date(lm.into());
				response
					.headers
					.insert(LAST_MODIFIED, lm_str.parse().unwrap());
			}

			Ok(response)
		}
	}

	#[tokio::test]
	async fn test_generates_etag() {
		let middleware = ConditionalGetMiddleware::new();
		let handler = Arc::new(TestHandler {
			body: "test response",
			with_etag: None,
			with_last_modified: None,
		});

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

	#[tokio::test]
	async fn test_if_none_match_returns_304() {
		let middleware = ConditionalGetMiddleware::new();
		let etag = "\"abc123\"";
		let handler = Arc::new(TestHandler {
			body: "test response",
			with_etag: Some(etag.to_string()),
			with_last_modified: None,
		});

		let mut headers = HeaderMap::new();
		headers.insert(IF_NONE_MATCH, etag.parse().unwrap());

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

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

		assert_eq!(response.status, StatusCode::NOT_MODIFIED);
		assert_eq!(response.body.len(), 0);
	}

	#[tokio::test]
	async fn test_if_modified_since_returns_304() {
		let middleware = ConditionalGetMiddleware::new();
		let last_modified = Utc::now() - chrono::Duration::days(1);
		let handler = Arc::new(TestHandler {
			body: "test response",
			with_etag: None,
			with_last_modified: Some(last_modified),
		});

		let mut headers = HeaderMap::new();
		let ims_str = httpdate::fmt_http_date((last_modified + chrono::Duration::hours(1)).into());
		headers.insert(IF_MODIFIED_SINCE, ims_str.parse().unwrap());

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

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

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

	#[tokio::test]
	async fn test_if_match_fails_returns_412() {
		let middleware = ConditionalGetMiddleware::new();
		let etag = "\"abc123\"";
		let handler = Arc::new(TestHandler {
			body: "test response",
			with_etag: Some(etag.to_string()),
			with_last_modified: None,
		});

		let mut headers = HeaderMap::new();
		headers.insert(IF_MATCH, "\"xyz789\"".parse().unwrap());

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

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

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

	#[tokio::test]
	async fn test_middleware_wont_overwrite_etag() {
		let middleware = ConditionalGetMiddleware::new();
		let custom_etag = "\"custom-etag\"";
		let handler = Arc::new(TestHandler {
			body: "test response",
			with_etag: Some(custom_etag.to_string()),
			with_last_modified: None,
		});

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

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

		assert_eq!(response.status, StatusCode::OK);
		assert_eq!(
			response.headers.get(ETAG).unwrap().to_str().unwrap(),
			custom_etag
		);
	}

	#[tokio::test]
	async fn test_if_none_match_and_different_etag() {
		let middleware = ConditionalGetMiddleware::new();
		let etag = "\"abc123\"";
		let handler = Arc::new(TestHandler {
			body: "test response",
			with_etag: Some(etag.to_string()),
			with_last_modified: None,
		});

		let mut headers = HeaderMap::new();
		headers.insert(IF_NONE_MATCH, "\"different-etag\"".parse().unwrap());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.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_if_modified_since_and_last_modified_in_the_future() {
		let middleware = ConditionalGetMiddleware::new();
		let last_modified = Utc::now();
		let handler = Arc::new(TestHandler {
			body: "test response",
			with_etag: None,
			with_last_modified: Some(last_modified),
		});

		let mut headers = HeaderMap::new();
		let ims_str = httpdate::fmt_http_date((last_modified - chrono::Duration::hours(1)).into());
		headers.insert(IF_MODIFIED_SINCE, ims_str.parse().unwrap());

		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.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_etag_on_post_request() {
		let middleware = ConditionalGetMiddleware::new();
		let handler = Arc::new(TestHandler {
			body: "test response",
			with_etag: None,
			with_last_modified: None,
		});

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

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

		// ETag should not be generated for POST requests
		assert!(!response.headers.contains_key(ETAG));
	}

	#[tokio::test]
	async fn test_without_etag_generation() {
		let middleware = ConditionalGetMiddleware::without_etag();
		let handler = Arc::new(TestHandler {
			body: "test response",
			with_etag: None,
			with_last_modified: None,
		});

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

		// ETag should not be generated when disabled
		assert!(!response.headers.contains_key(ETAG));
	}
}