diff --git a/src/main.rs b/src/main.rs index eedf733..1695bd4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,7 +12,9 @@ use tide::{Request, Response, StatusCode}; use base64; const STORAGE_DIR: &str = "./storage"; -const DEFAULT_TTL: u64 = 86400; +const MIN_TTL: u64 = 60; // 1 minute +const DEFAULT_TTL: u64 = 86400; // 1 day +const MAX_TTL: u64 = 31_536_000; // 1 year, to be discussed /// Scans storage and removes expired files async fn cleanup_expired_files() { @@ -156,6 +158,25 @@ async fn handle_store(mut req: Request<()>) -> tide::Result { .build()); } + // Validate the ttl + let live_for = if let Some(ttl) = data.ttl { + if ttl < MIN_TTL { + return Ok(Response::builder(StatusCode::BadRequest) + .body(format!("Invalid ttl: must be at least {} seconds.", MIN_TTL)) + .build()); + } else if ttl > MAX_TTL { + return Ok(Response::builder(StatusCode::BadRequest) + .body(format!("Invalid ttl: must be at most {} seconds.", MAX_TTL)) + .build()); + } + Duration::from_secs(ttl) + } else { + Duration::from_secs(DEFAULT_TTL) + }; + + let now = SystemTime::now(); + let expires_at = now.checked_add(live_for).ok_or(tide::Error::from_str(StatusCode::BadRequest, "Invalid ttl"))?; + // Decode the value from Base64 let value_bytes = match base64::decode(&data.value) { Ok(value) => value, @@ -166,10 +187,6 @@ async fn handle_store(mut req: Request<()>) -> tide::Result { } }; - let now = SystemTime::now(); - let live_for = if let Some(ttl) = data.ttl { Duration::from_secs(ttl) } else { Duration::from_secs(DEFAULT_TTL) }; - let expires_at = now.checked_add(live_for).ok_or(tide::Error::from_str(StatusCode::BadRequest, "Invalid ttl"))?; - // Store the data match store_data(&data.key, &value_bytes, expires_at).await { Ok(()) => {