Add MIN/MAX ttl

This commit is contained in:
Sosthene 2024-12-03 12:27:41 +01:00
parent b5a238c205
commit 792d1b788d

View File

@ -12,7 +12,9 @@ use tide::{Request, Response, StatusCode};
use base64; use base64;
const STORAGE_DIR: &str = "./storage"; 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 /// Scans storage and removes expired files
async fn cleanup_expired_files() { async fn cleanup_expired_files() {
@ -156,6 +158,25 @@ async fn handle_store(mut req: Request<()>) -> tide::Result<Response> {
.build()); .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 // Decode the value from Base64
let value_bytes = match base64::decode(&data.value) { let value_bytes = match base64::decode(&data.value) {
Ok(value) => value, Ok(value) => value,
@ -166,10 +187,6 @@ async fn handle_store(mut req: Request<()>) -> tide::Result<Response> {
} }
}; };
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 // Store the data
match store_data(&data.key, &value_bytes, expires_at).await { match store_data(&data.key, &value_bytes, expires_at).await {
Ok(()) => { Ok(()) => {