reinhardt-core 0.1.1

Core components for Reinhardt framework
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
//! Custom validation hooks for parsers.
//!
//! This module provides traits and utilities for adding custom validation logic
//! before and after parsing operations.

use async_trait::async_trait;
use bytes::Bytes;

use super::parser::{ParseResult, ParsedData};

/// Trait for custom parser validation hooks.
///
/// Implement this trait to add custom validation logic that runs before or after
/// parsing operations. This allows you to enforce business rules, size limits,
/// or other constraints on parsed data.
///
/// # Examples
///
/// ```
/// use async_trait::async_trait;
/// use bytes::Bytes;
/// use reinhardt_core::parsers::validator::ParserValidator;
/// use reinhardt_core::parsers::parser::{ParseResult, ParsedData};
/// use reinhardt_core::exception::Error;
///
/// struct SizeLimitValidator {
///     max_size: usize,
/// }
///
/// #[async_trait]
/// impl ParserValidator for SizeLimitValidator {
///     async fn before_parse(&self, _content_type: Option<&str>, body: &Bytes) -> ParseResult<()> {
///         if body.len() > self.max_size {
///             return Err(Error::Validation(format!(
///                 "Body size {} exceeds maximum {}",
///                 body.len(),
///                 self.max_size
///             )));
///         }
///         Ok(())
///     }
///
///     async fn after_parse(&self, _data: &ParsedData) -> ParseResult<()> {
///         Ok(())
///     }
/// }
/// ```
#[async_trait]
pub trait ParserValidator: Send + Sync {
	/// Validate before parsing.
	///
	/// This hook is called before the parser processes the request body.
	/// Use it to validate content type, body size, or other pre-conditions.
	///
	/// # Arguments
	///
	/// * `content_type` - The Content-Type header value, if present
	/// * `body` - The raw request body bytes
	///
	/// # Returns
	///
	/// `Ok(())` if validation passes, `Err` otherwise
	async fn before_parse(&self, content_type: Option<&str>, body: &Bytes) -> ParseResult<()>;

	/// Validate after parsing.
	///
	/// This hook is called after the parser successfully processes the request body.
	/// Use it to validate the structure or content of the parsed data.
	///
	/// # Arguments
	///
	/// * `data` - The parsed data structure
	///
	/// # Returns
	///
	/// `Ok(())` if validation passes, `Err` otherwise
	async fn after_parse(&self, data: &ParsedData) -> ParseResult<()>;
}

/// Validator that enforces a maximum body size limit.
///
/// # Examples
///
/// ```
/// use reinhardt_core::parsers::validator::SizeLimitValidator;
///
/// // Limit requests to 1MB
/// let validator = SizeLimitValidator::new(1024 * 1024);
/// ```
#[derive(Debug, Clone)]
pub struct SizeLimitValidator {
	max_size: usize,
}

impl SizeLimitValidator {
	/// Create a new SizeLimitValidator with the specified maximum size in bytes.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::parsers::validator::SizeLimitValidator;
	///
	/// // Limit to 10KB
	/// let validator = SizeLimitValidator::new(10 * 1024);
	/// ```
	pub fn new(max_size: usize) -> Self {
		Self { max_size }
	}
}

#[async_trait]
impl ParserValidator for SizeLimitValidator {
	async fn before_parse(&self, _content_type: Option<&str>, body: &Bytes) -> ParseResult<()> {
		use crate::exception::Error;

		if body.len() > self.max_size {
			return Err(Error::Validation(format!(
				"Request body size {} exceeds maximum allowed size {}",
				body.len(),
				self.max_size
			)));
		}
		Ok(())
	}

	async fn after_parse(&self, _data: &ParsedData) -> ParseResult<()> {
		Ok(())
	}
}

/// Validator that checks for required content type.
///
/// # Examples
///
/// ```
/// use reinhardt_core::parsers::validator::ContentTypeValidator;
///
/// // Require application/json
/// let validator = ContentTypeValidator::new(vec!["application/json".to_string()]);
/// ```
#[derive(Debug, Clone)]
pub struct ContentTypeValidator {
	allowed_types: Vec<String>,
}

impl ContentTypeValidator {
	/// Create a new ContentTypeValidator with allowed content types.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::parsers::validator::ContentTypeValidator;
	///
	/// let validator = ContentTypeValidator::new(vec![
	///     "application/json".to_string(),
	///     "application/xml".to_string(),
	/// ]);
	/// ```
	pub fn new(allowed_types: Vec<String>) -> Self {
		Self { allowed_types }
	}
}

#[async_trait]
impl ParserValidator for ContentTypeValidator {
	async fn before_parse(&self, content_type: Option<&str>, _body: &Bytes) -> ParseResult<()> {
		use crate::exception::Error;

		if let Some(ct) = content_type {
			// Extract the media type (before any parameters like charset)
			// e.g., "application/json; charset=utf-8" -> "application/json"
			let media_type = ct.split(';').next().unwrap_or(ct).trim().to_lowercase();

			// Use exact matching on the media type portion instead of
			// substring matching to prevent bypass via crafted content types
			// (e.g., "application/not-json-at-all" should not match "json")
			for allowed in &self.allowed_types {
				if media_type == allowed.to_lowercase() {
					return Ok(());
				}
			}
			return Err(Error::Validation(format!(
				"Content-Type '{}' is not allowed. Allowed types: {:?}",
				ct, self.allowed_types
			)));
		}

		Err(Error::Validation(
			"Content-Type header is required".to_string(),
		))
	}

	async fn after_parse(&self, _data: &ParsedData) -> ParseResult<()> {
		Ok(())
	}
}

/// Composite validator that runs multiple validators in sequence.
///
/// # Examples
///
/// ```
/// use reinhardt_core::parsers::validator::{CompositeValidator, SizeLimitValidator, ContentTypeValidator};
///
/// let validator = CompositeValidator::new()
///     .add(SizeLimitValidator::new(1024 * 1024))
///     .add(ContentTypeValidator::new(vec!["application/json".to_string()]));
/// ```
#[derive(Default)]
pub struct CompositeValidator {
	validators: Vec<Box<dyn ParserValidator>>,
}

impl CompositeValidator {
	/// Create a new empty CompositeValidator.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::parsers::validator::CompositeValidator;
	///
	/// let validator = CompositeValidator::new();
	/// ```
	pub fn new() -> Self {
		Self::default()
	}

	/// Add a validator to the composite.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_core::parsers::validator::{CompositeValidator, SizeLimitValidator};
	///
	/// let validator = CompositeValidator::new()
	///     .add(SizeLimitValidator::new(1024));
	/// ```
	#[allow(clippy::should_implement_trait)]
	pub fn add<V: ParserValidator + 'static>(mut self, validator: V) -> Self {
		self.validators.push(Box::new(validator));
		self
	}
}

#[async_trait]
impl ParserValidator for CompositeValidator {
	async fn before_parse(&self, content_type: Option<&str>, body: &Bytes) -> ParseResult<()> {
		for validator in &self.validators {
			validator.before_parse(content_type, body).await?;
		}
		Ok(())
	}

	async fn after_parse(&self, data: &ParsedData) -> ParseResult<()> {
		for validator in &self.validators {
			validator.after_parse(data).await?;
		}
		Ok(())
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::rstest;
	use serde_json::json;

	#[rstest]
	#[tokio::test]
	async fn test_size_limit_validator_within_limit() {
		// Arrange
		let validator = SizeLimitValidator::new(100);
		let body = Bytes::from("small body");

		// Act
		let result = validator.before_parse(None, &body).await;

		// Assert
		assert!(result.is_ok());
	}

	#[rstest]
	#[tokio::test]
	async fn test_size_limit_validator_exceeds_limit() {
		// Arrange
		let validator = SizeLimitValidator::new(10);
		let body = Bytes::from("this is a very long body that exceeds the limit");

		// Act
		let result = validator.before_parse(None, &body).await;

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	#[tokio::test]
	async fn test_size_limit_validator_after_parse() {
		// Arrange
		let validator = SizeLimitValidator::new(100);
		let data = ParsedData::Json(json!({"key": "value"}));

		// Act
		let result = validator.after_parse(&data).await;

		// Assert
		assert!(result.is_ok());
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_allowed() {
		// Arrange
		let validator = ContentTypeValidator::new(vec!["application/json".to_string()]);
		let body = Bytes::new();

		// Act
		let result = validator
			.before_parse(Some("application/json"), &body)
			.await;

		// Assert
		assert!(result.is_ok());
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_not_allowed() {
		// Arrange
		let validator = ContentTypeValidator::new(vec!["application/json".to_string()]);
		let body = Bytes::new();

		// Act
		let result = validator.before_parse(Some("text/plain"), &body).await;

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_missing() {
		// Arrange
		let validator = ContentTypeValidator::new(vec!["application/json".to_string()]);
		let body = Bytes::new();

		// Act
		let result = validator.before_parse(None, &body).await;

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_with_charset() {
		// Arrange
		let validator = ContentTypeValidator::new(vec!["application/json".to_string()]);
		let body = Bytes::new();

		// Act
		let result = validator
			.before_parse(Some("application/json; charset=utf-8"), &body)
			.await;

		// Assert
		assert!(result.is_ok());
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_rejects_substring_match() {
		// Arrange - crafted content type that contains "json" as substring
		// but is not a valid JSON media type
		let validator = ContentTypeValidator::new(vec!["application/json".to_string()]);
		let body = Bytes::new();

		// Act - "not-json-at-all" contains "json" but should be rejected
		let result = validator
			.before_parse(Some("application/not-json-at-all"), &body)
			.await;

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_rejects_prefix_substring() {
		// Arrange - content type where allowed type is a prefix substring
		let validator = ContentTypeValidator::new(vec!["text/plain".to_string()]);
		let body = Bytes::new();

		// Act - "text/plaintext" starts with "text/plain" but should be rejected
		let result = validator.before_parse(Some("text/plaintext"), &body).await;

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_rejects_suffix_substring() {
		// Arrange - content type where allowed type is a suffix substring
		let validator = ContentTypeValidator::new(vec!["application/xml".to_string()]);
		let body = Bytes::new();

		// Act - "application/soap+xml" ends with "xml" but is a different type
		let result = validator
			.before_parse(Some("application/soap+xml"), &body)
			.await;

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_case_insensitive() {
		// Arrange
		let validator = ContentTypeValidator::new(vec!["application/json".to_string()]);
		let body = Bytes::new();

		// Act - uppercase variant should be accepted
		let result = validator
			.before_parse(Some("Application/JSON"), &body)
			.await;

		// Assert
		assert!(result.is_ok());
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_multiple_allowed_types() {
		// Arrange
		let validator = ContentTypeValidator::new(vec![
			"application/json".to_string(),
			"application/xml".to_string(),
			"text/plain".to_string(),
		]);
		let body = Bytes::new();

		// Act & Assert - all allowed types should pass
		assert!(
			validator
				.before_parse(Some("application/json"), &body)
				.await
				.is_ok()
		);
		assert!(
			validator
				.before_parse(Some("application/xml"), &body)
				.await
				.is_ok()
		);
		assert!(
			validator
				.before_parse(Some("text/plain"), &body)
				.await
				.is_ok()
		);

		// Act & Assert - non-allowed type should fail
		assert!(
			validator
				.before_parse(Some("text/html"), &body)
				.await
				.is_err()
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_with_multiple_parameters() {
		// Arrange
		let validator = ContentTypeValidator::new(vec!["application/json".to_string()]);
		let body = Bytes::new();

		// Act - content type with multiple parameters should still match
		let result = validator
			.before_parse(
				Some("application/json; charset=utf-8; boundary=something"),
				&body,
			)
			.await;

		// Assert
		assert!(result.is_ok());
	}

	#[rstest]
	#[tokio::test]
	async fn test_content_type_validator_whitespace_handling() {
		// Arrange
		let validator = ContentTypeValidator::new(vec!["application/json".to_string()]);
		let body = Bytes::new();

		// Act - media type with extra whitespace before semicolon
		let result = validator
			.before_parse(Some("  application/json  ; charset=utf-8"), &body)
			.await;

		// Assert
		assert!(result.is_ok());
	}

	#[rstest]
	#[tokio::test]
	async fn test_composite_validator_all_pass() {
		// Arrange
		let validator = CompositeValidator::new()
			.add(SizeLimitValidator::new(100))
			.add(ContentTypeValidator::new(vec![
				"application/json".to_string(),
			]));
		let body = Bytes::from("small");

		// Act
		let result = validator
			.before_parse(Some("application/json"), &body)
			.await;

		// Assert
		assert!(result.is_ok());
	}

	#[rstest]
	#[tokio::test]
	async fn test_composite_validator_first_fails() {
		// Arrange
		let validator = CompositeValidator::new()
			.add(SizeLimitValidator::new(3))
			.add(ContentTypeValidator::new(vec![
				"application/json".to_string(),
			]));
		let body = Bytes::from("this is too long");

		// Act
		let result = validator
			.before_parse(Some("application/json"), &body)
			.await;

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	#[tokio::test]
	async fn test_composite_validator_second_fails() {
		// Arrange
		let validator = CompositeValidator::new()
			.add(SizeLimitValidator::new(100))
			.add(ContentTypeValidator::new(vec![
				"application/json".to_string(),
			]));
		let body = Bytes::from("small");

		// Act
		let result = validator.before_parse(Some("text/plain"), &body).await;

		// Assert
		assert!(result.is_err());
	}

	#[rstest]
	#[tokio::test]
	async fn test_composite_validator_after_parse() {
		// Arrange
		let validator = CompositeValidator::new()
			.add(SizeLimitValidator::new(100))
			.add(ContentTypeValidator::new(vec![
				"application/json".to_string(),
			]));
		let data = ParsedData::Json(json!({"key": "value"}));

		// Act
		let result = validator.after_parse(&data).await;

		// Assert
		assert!(result.is_ok());
	}

	#[rstest]
	#[tokio::test]
	async fn test_composite_validator_empty() {
		// Arrange
		let validator = CompositeValidator::new();
		let body = Bytes::from("test");

		// Act & Assert - before_parse
		let result = validator.before_parse(None, &body).await;
		assert!(result.is_ok());

		// Act & Assert - after_parse
		let data = ParsedData::Json(json!({"key": "value"}));
		let result = validator.after_parse(&data).await;
		assert!(result.is_ok());
	}
}