Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(engine): guard Duration overflow panics on untrusted numeric inputs (#4417)

Louis Beaumont8bee4fd868a9
diff --git a/crates/screenpipe-engine/src/retention.rs b/crates/screenpipe-engine/src/retention.rs
index fd91877ff..7c0f05e24 100644
--- a/crates/screenpipe-engine/src/retention.rs
+++ b/crates/screenpipe-engine/src/retention.rs
@@ -134,6 +134,21 @@ pub async fn retention_configure(
));
}
+ // Enforce a sane maximum. 100 years is absurdly generous for "keep the last
+ // N days" yet far below where `Utc::now() - Duration::days(..)` overflows
+ // chrono's date range and panics the retention loop. The loop also guards
+ // this defensively (see `retention_cutoff`), but reject it here with a clear
+ // error rather than silently accepting a value that can never take effect.
+ const MAX_RETENTION_DAYS: u32 = 36_500;
+ if retention_days > MAX_RETENTION_DAYS {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ JsonResponse(
+ json!({"error": format!("retention_days must be at most {MAX_RETENTION_DAYS}")}),
+ ),
+ ));
+ }
+
let mut guard = state.retention_state.inner.write().await;
let wants_enabled = request.enabled.unwrap_or(true);
@@ -313,7 +328,16 @@ fn spawn_retention_loop(
}
};
- let cutoff = Utc::now() - Duration::days(retention_days as i64);
+ let cutoff = match retention_cutoff(retention_days, Utc::now()) {
+ Some(c) => c,
+ None => {
+ warn!(
+ "retention: retention_days={} out of range, skipping cleanup cycle",
+ retention_days
+ );
+ continue;
+ }
+ };
info!(
"retention: cleaning up data before {} ({}d retention, mode={:?})",
@@ -346,6 +370,17 @@ fn spawn_retention_loop(
})
}
+/// Compute the deletion cutoff: data older than the returned instant is
+/// eligible for removal. Returns `None` when `retention_days` is so large the
+/// subtraction would underflow chrono's representable date range — in which
+/// case `Utc::now() - Duration::days(..)` would *panic*. `retention_days` is a
+/// `u32` with no hard upper bound at every entry point (a persisted config from
+/// an older client can bypass the endpoint's range check), so the loop must
+/// treat an out-of-range value as "skip", never delete-from-a-bogus-window.
+fn retention_cutoff(retention_days: u32, now: DateTime<Utc>) -> Option<DateTime<Utc>> {
+ Duration::try_days(retention_days as i64).and_then(|d| now.checked_sub_signed(d))
+}
+
async fn do_local_cleanup(
db: &Arc<DatabaseManager>,
cutoff: DateTime<Utc>,
@@ -543,3 +578,27 @@ async fn do_local_cleanup(
Ok(total)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn retention_cutoff_normal_values() {
+ let now = Utc::now();
+ // 14 days back is exactly 14 days before now.
+ let c = retention_cutoff(14, now).expect("14d is in range");
+ assert_eq!(now - c, Duration::days(14));
+ // The configure endpoint's max (100 years) must still compute.
+ assert!(retention_cutoff(36_500, now).is_some());
+ }
+
+ #[test]
+ fn retention_cutoff_out_of_range_is_none_not_panic() {
+ let now = Utc::now();
+ // u32::MAX days (~11.7M years) underflows chrono's date range. The old
+ // `now - Duration::days(..)` panicked here; the guard must yield None so
+ // the retention loop skips the cycle instead of crashing.
+ assert_eq!(retention_cutoff(u32::MAX, now), None);
+ }
+}
diff --git a/crates/screenpipe-engine/src/routes/time.rs b/crates/screenpipe-engine/src/routes/time.rs
index 8014b4190..b8a93490e 100644
--- a/crates/screenpipe-engine/src/routes/time.rs
+++ b/crates/screenpipe-engine/src/routes/time.rs
@@ -28,16 +28,22 @@ fn parse_relative_time(s: &str) -> Option<DateTime<Utc>> {
let value: f64 = trimmed[..num_end].parse().ok()?;
let unit = trimmed[num_end..].trim();
+ // `value as i64` saturates a huge/inf float to i64::MAX rather than
+ // wrapping, and the `Duration::*` / `DateTime - Duration` operators both
+ // *panic* on overflow. A user passing `start_time=99999999999999w` (or any
+ // absurd magnitude) would otherwise panic the request handler instead of
+ // getting a clean "invalid time" 400. Use the checked constructors and a
+ // checked subtraction so out-of-range input falls through to `None`.
let duration = match unit {
- "s" | "sec" | "second" | "seconds" => Duration::seconds(value as i64),
- "m" | "min" | "minute" | "minutes" => Duration::minutes(value as i64),
- "h" | "hr" | "hour" | "hours" => Duration::hours(value as i64),
- "d" | "day" | "days" => Duration::days(value as i64),
- "w" | "week" | "weeks" => Duration::weeks(value as i64),
+ "s" | "sec" | "second" | "seconds" => Duration::try_seconds(value as i64),
+ "m" | "min" | "minute" | "minutes" => Duration::try_minutes(value as i64),
+ "h" | "hr" | "hour" | "hours" => Duration::try_hours(value as i64),
+ "d" | "day" | "days" => Duration::try_days(value as i64),
+ "w" | "week" | "weeks" => Duration::try_weeks(value as i64),
_ => return None,
- };
+ }?;
- Some(Utc::now() - duration)
+ Utc::now().checked_sub_signed(duration)
}
/// Try to parse a string as either ISO 8601 or relative time.
@@ -147,4 +153,17 @@ mod tests {
assert!(parse_flexible_datetime("banana").is_err());
assert!(parse_flexible_datetime("").is_err());
}
+
+ #[test]
+ fn test_parse_overflow_does_not_panic() {
+ // Previously these panicked inside chrono's Duration constructors /
+ // the DateTime subtraction. They must return a clean Err instead so
+ // the request handler answers 400, not a connection reset.
+ assert!(parse_flexible_datetime("99999999999999w").is_err());
+ assert!(parse_flexible_datetime("99999999999999999999d ago").is_err());
+ assert!(parse_flexible_datetime("1e30h").is_err());
+ // Valid Duration magnitude but the resulting instant is before the
+ // representable DateTime range — checked_sub_signed yields None.
+ assert!(parse_flexible_datetime("20000000w").is_err());
+ }
}