diff --git a/CHANGELOG.md b/CHANGELOG.md index aee23ae..a3bc5bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,9 @@ ### Changed +- `chrono` заменён на `time` (новый модуль `timeutil`): RUSTSEC-2026-0543 помечает `chrono` как + неподдерживаемый, `cargo deny` падал. Формат на проводе тот же (RFC 3339, но UTC теперь с + суффиксом `Z`, а не `+00:00`). - `[profile.release]`: `lto = "thin"`, `codegen-units = 1`. Релизный бинарь с `protocol-http` уменьшился с 12.3 МБ до 9.7 МБ (−21%); `http_parser/evaluate` в criterion — 314 нс → 278 нс (−12%), остальные бенчмарки в пределах шума. diff --git a/Cargo.lock b/Cargo.lock index 8666d85..b564414 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,15 +17,6 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - [[package]] name = "anes" version = "0.1.6" @@ -360,20 +351,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - [[package]] name = "ciborium" version = "0.2.2" @@ -721,6 +698,9 @@ name = "deranged" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] [[package]] name = "derive_more" @@ -1210,30 +1190,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.3.0" @@ -2257,7 +2213,6 @@ version = "0.3.0-dev" dependencies = [ "anyhow", "axum", - "chrono", "clap", "criterion", "crossterm", @@ -2279,6 +2234,7 @@ dependencies = [ "socket2", "subtle", "thiserror 2.0.21", + "time", "tokio", "tokio-splice", "toml", @@ -3847,65 +3803,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - [[package]] name = "windows-sys" version = "0.52.0" diff --git a/Cargo.toml b/Cargo.toml index e177b55..300d86c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,7 @@ prometheus = { version = "0.14", features = ["process"] } toml = "1.1" rand = { version = "0.10", default-features = false, features = ["std", "std_rng", "thread_rng"] } clap = { version = "4", features = ["derive"] } -chrono = { version = "0.4", features = ["serde"] } +time = { version = "0.3", features = ["formatting", "parsing", "serde"] } # TUI (rampart-tui): лёгкие deps, без feature-gate ratatui = "0.30" diff --git a/src/app/runtime.rs b/src/app/runtime.rs index 914c410..48922cf 100644 --- a/src/app/runtime.rs +++ b/src/app/runtime.rs @@ -235,7 +235,7 @@ async fn push_attack_event(writer: &Option ApiResult { .get_multiplexed_async_connection() .await .map_err(redis_unavailable)?; - let now = chrono::Utc::now().timestamp(); + let now = crate::timeutil::unix_now(); let mut cursor = 0_u64; let mut filled = 0_usize; loop { diff --git a/src/manager/api/blacklist/common.rs b/src/manager/api/blacklist/common.rs index 8b7e176..8805e80 100644 --- a/src/manager/api/blacklist/common.rs +++ b/src/manager/api/blacklist/common.rs @@ -46,9 +46,7 @@ pub(super) fn legacy_metadata(now: i64) -> BlacklistMetadata { } pub(super) fn format_timestamp(timestamp: i64) -> String { - chrono::DateTime::from_timestamp(timestamp, 0) - .map(|value| value.to_rfc3339()) - .unwrap_or_else(|| chrono::Utc::now().to_rfc3339()) + crate::timeutil::format_rfc3339(timestamp).unwrap_or_else(crate::timeutil::now_rfc3339) } pub(super) fn event_payload( diff --git a/src/manager/api/blacklist/list.rs b/src/manager/api/blacklist/list.rs index 998401f..0acafda 100644 --- a/src/manager/api/blacklist/list.rs +++ b/src/manager/api/blacklist/list.rs @@ -52,7 +52,7 @@ pub async fn list_blacklist( .take(usize::try_from(limit).unwrap_or(usize::MAX)) .collect(); let metadata = load_metadata(&mut conn, &page).await?; - let now = chrono::Utc::now().timestamp(); + let now = crate::timeutil::unix_now(); let items = page .iter() .filter_map(|target| entry(target, metadata.get(target), now)) @@ -116,8 +116,8 @@ fn entry(target: &str, metadata: Option<&Option>, now: i64) - None => legacy_metadata(now), }; if record.expires_at_unix <= now - || chrono::DateTime::from_timestamp(record.created_at_unix, 0).is_none() - || chrono::DateTime::from_timestamp(record.expires_at_unix, 0).is_none() + || !crate::timeutil::is_valid_unix(record.created_at_unix) + || !crate::timeutil::is_valid_unix(record.expires_at_unix) { return None; } diff --git a/src/manager/api/blacklist/mutate.rs b/src/manager/api/blacklist/mutate.rs index 1038ee2..9acb83f 100644 --- a/src/manager/api/blacklist/mutate.rs +++ b/src/manager/api/blacklist/mutate.rs @@ -37,7 +37,7 @@ pub async fn add_blacklist( } let target = ip.to_string(); - let created_at_unix = chrono::Utc::now().timestamp(); + let created_at_unix = crate::timeutil::unix_now(); let metadata = super::common::BlacklistMetadata { created_at_unix, expires_at_unix: created_at_unix + duration_secs as i64, diff --git a/src/manager/auth.rs b/src/manager/auth.rs index f7ea6a7..42a6f20 100644 --- a/src/manager/auth.rs +++ b/src/manager/auth.rs @@ -17,7 +17,7 @@ pub struct Claims { } pub fn create_token(secret: &str, expiration: u64, audience: &str) -> Result { - let now = chrono::Utc::now().timestamp() as usize; + let now = crate::timeutil::unix_now() as usize; let claims = Claims { sub: "rampart-admin".to_string(), aud: audience.to_string(), diff --git a/src/manager/sync/heartbeat.rs b/src/manager/sync/heartbeat.rs index 5dc0ab7..5d0760f 100644 --- a/src/manager/sync/heartbeat.rs +++ b/src/manager/sync/heartbeat.rs @@ -37,7 +37,7 @@ async fn check_nodes(state: &AppState) -> anyhow::Result<()> { let mut conn = state.redis_client.get_multiplexed_async_connection().await?; let keys = collect_node_keys(&mut conn).await?; - let now = chrono::Utc::now().timestamp(); + let now = crate::timeutil::unix_now(); for key in &keys { let raw: Option = conn.get(key).await?; @@ -73,8 +73,7 @@ pub fn offline_update(raw: &str, now: i64) -> Option { let mut node = serde_json::from_str::(raw).ok()?; let hb = node["last_heartbeat"] .as_str() - .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()) - .map(|t| t.timestamp()) + .and_then(crate::timeutil::parse_rfc3339_unix) .unwrap_or(0); if now - hb <= NODE_TTL_SECS { return None; diff --git a/src/store/clickhouse.rs b/src/store/clickhouse.rs index 7c1a753..96d7f49 100644 --- a/src/store/clickhouse.rs +++ b/src/store/clickhouse.rs @@ -6,11 +6,11 @@ //! request timeout and every flush by a global timeout, so an unreachable or //! hung ClickHouse degrades into dropped events instead of a stalled daemon. -use chrono::{DateTime, Utc}; use prometheus::IntCounter; use serde::Serialize; use std::sync::{Arc, LazyLock}; use std::time::Duration; +use time::OffsetDateTime; use tokio::sync::Mutex; use tokio::sync::watch; @@ -39,7 +39,8 @@ pub static CLICKHOUSE_DROPPED: LazyLock = LazyLock::new(|| { /// One row of the `rampart_events` table. #[derive(Debug, Clone, Serialize)] pub struct ClickHouseEvent { - pub timestamp: DateTime, + #[serde(with = "time::serde::rfc3339")] + pub timestamp: OffsetDateTime, pub event_type: String, pub ip: String, pub data_float: f64, diff --git a/src/store/redis/sync/event.rs b/src/store/redis/sync/event.rs index 80f8dae..21c218b 100644 --- a/src/store/redis/sync/event.rs +++ b/src/store/redis/sync/event.rs @@ -58,10 +58,10 @@ pub(super) fn handle(msg: &Msg, blacklist: &Blacklist) -> anyhow::Result<()> { /// /// Returns `Ok(None)` when the expiry is already in the past. fn absolute_duration(expires_at: i64) -> anyhow::Result> { - if chrono::DateTime::from_timestamp(expires_at, 0).is_none() { + if !crate::timeutil::is_valid_unix(expires_at) { anyhow::bail!("invalid blacklist event expiry timestamp"); } - let remaining = expires_at.saturating_sub(chrono::Utc::now().timestamp()); + let remaining = expires_at.saturating_sub(crate::timeutil::unix_now()); if remaining <= 0 { return Ok(None); } diff --git a/src/store/redis/sync/publisher.rs b/src/store/redis/sync/publisher.rs index f88be07..a93c51a 100644 --- a/src/store/redis/sync/publisher.rs +++ b/src/store/redis/sync/publisher.rs @@ -112,7 +112,7 @@ async fn publish_ban( manager: &mut Option, event: &LocalBanEvent, ) -> anyhow::Result<()> { - let now = chrono::Utc::now().timestamp(); + let now = crate::timeutil::unix_now(); let remaining = event.expires_at_unix.saturating_sub(now); if remaining <= 0 { return Ok(()); diff --git a/src/store/redis/sync/snapshot.rs b/src/store/redis/sync/snapshot.rs index cfbe9b6..2b7956b 100644 --- a/src/store/redis/sync/snapshot.rs +++ b/src/store/redis/sync/snapshot.rs @@ -32,7 +32,7 @@ pub(super) async fn reconcile(manager: &ConnectionManager, blacklist: &Blacklist let mut conn = manager.clone(); let members: Vec = command(redis::cmd("SMEMBERS").arg(BLACKLIST_KEY).query_async(&mut conn)).await?; let metadata: HashMap = command(conn.hgetall(BLACKLIST_METADATA_KEY)).await?; - let now = chrono::Utc::now().timestamp(); + let now = crate::timeutil::unix_now(); let mut active = Vec::with_capacity(members.len()); for target in members { @@ -50,8 +50,8 @@ pub(super) async fn reconcile(manager: &ConnectionManager, blacklist: &Blacklist None => continue, }, }; - if chrono::DateTime::from_timestamp(record.created_at_unix, 0).is_none() - || chrono::DateTime::from_timestamp(record.expires_at_unix, 0).is_none() + if !crate::timeutil::is_valid_unix(record.created_at_unix) + || !crate::timeutil::is_valid_unix(record.expires_at_unix) { continue; } diff --git a/src/timeutil.rs b/src/timeutil.rs new file mode 100644 index 0000000..d3536a1 --- /dev/null +++ b/src/timeutil.rs @@ -0,0 +1,43 @@ +//! Wall-clock helpers on top of the `time` crate (unix seconds and RFC 3339). +//! +//! Every timestamp that crosses a process boundary (Redis records, manager API, +//! ClickHouse rows, JWT claims) is unix seconds or an RFC 3339 string; this module is +//! the single place that converts between them and rejects out-of-range values. + +use time::OffsetDateTime; +use time::format_description::well_known::Rfc3339; + +/// Current unix time in seconds. +#[must_use] +pub fn unix_now() -> i64 { + OffsetDateTime::now_utc().unix_timestamp() +} + +/// Whether `ts` (unix seconds) is a representable calendar date. Absurd values from +/// untrusted records (Redis, API) must be rejected instead of flowing into arithmetic. +#[must_use] +pub fn is_valid_unix(ts: i64) -> bool { + OffsetDateTime::from_unix_timestamp(ts).is_ok() +} + +/// Formats unix seconds as RFC 3339 (UTC, `Z` suffix); `None` when out of range. +#[must_use] +pub fn format_rfc3339(ts: i64) -> Option { + OffsetDateTime::from_unix_timestamp(ts).ok()?.format(&Rfc3339).ok() +} + +/// Current time as RFC 3339. +#[must_use] +pub fn now_rfc3339() -> String { + OffsetDateTime::now_utc() + .format(&Rfc3339) + .unwrap_or_else(|_| String::from("1970-01-01T00:00:00Z")) +} + +/// Parses an RFC 3339 string (any offset) into unix seconds. +#[must_use] +pub fn parse_rfc3339_unix(text: &str) -> Option { + OffsetDateTime::parse(text, &Rfc3339) + .ok() + .map(OffsetDateTime::unix_timestamp) +} diff --git a/tests/clickhouse_writer.rs b/tests/clickhouse_writer.rs index 0ce466b..fbe868f 100644 --- a/tests/clickhouse_writer.rs +++ b/tests/clickhouse_writer.rs @@ -7,7 +7,7 @@ use rampart::store::clickhouse::{ClickHouseEvent, ClickHouseWriter, MAX_BUFFER_E fn event(seq: usize) -> ClickHouseEvent { ClickHouseEvent { - timestamp: chrono::Utc::now(), + timestamp: time::OffsetDateTime::now_utc(), event_type: "test".to_string(), ip: format!("192.0.2.{}", seq % 250), data_float: 0.0, diff --git a/tests/manager_heartbeat.rs b/tests/manager_heartbeat.rs index 9e29847..2e51917 100644 --- a/tests/manager_heartbeat.rs +++ b/tests/manager_heartbeat.rs @@ -5,9 +5,7 @@ use rampart::manager::sync::heartbeat::{NODES_KEY_PATTERN, offline_update}; fn rfc3339(ts: i64) -> String { - chrono::DateTime::from_timestamp(ts, 0) - .expect("in-range timestamp") - .to_rfc3339() + rampart::timeutil::format_rfc3339(ts).expect("in-range timestamp") } #[test]