From 6bea3bf2ef31f978b98848a5f2a045dcab0cc2f0 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 26 Jan 2023 21:29:06 -0500 Subject: input length and range checking --- src/types/extract.rs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) (limited to 'src/types') diff --git a/src/types/extract.rs b/src/types/extract.rs index 6518ca1..bb50aa7 100644 --- a/src/types/extract.rs +++ b/src/types/extract.rs @@ -38,7 +38,7 @@ pub struct Json(pub T); #[async_trait] impl FromRequest for Json where - T: DeserializeOwned, + T: DeserializeOwned + Check, B: HttpBody + Send + 'static, B::Data: Send, B::Error: Into, @@ -56,10 +56,35 @@ impl FromRequest for Json where return Err(ResponseCode::BadRequest.msg("Invalid utf8 body")) }; - let Ok(value) = serde_json::from_str(&string) else { + let Ok(value) = serde_json::from_str::(&string) else { return Err(ResponseCode::BadRequest.msg("Invalid request body")) }; + if let Err(msg) = value.check() { + return Err(ResponseCode::BadRequest.msg(&msg)); + } + Ok(Json(value)) } -} \ No newline at end of file +} + +pub type CheckResult = std::result::Result<(), String>; + +pub trait Check { + + fn check(&self) -> CheckResult; + + fn assert_length(string: &str, min: usize, max: usize, message: &str) -> CheckResult { + if string.len() < min || string.len() > max { + return Err(message.to_string()) + } + Ok(()) + } + + fn assert_range(number: u64, min: u64, max: u64, message: &str) -> CheckResult { + if number < min || number > max { + return Err(message.to_string()) + } + Ok(()) + } +} \ No newline at end of file -- cgit v1.2.3-freya