diff --git a/Cargo.lock b/Cargo.lock index 5284839..f61695f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11,15 +11,6 @@ dependencies = [ "memchr", ] -[[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 = "asn1-rs" version = "0.7.2" @@ -224,17 +215,6 @@ dependencies = [ "rand_core", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "num-traits", - "windows-link", -] - [[package]] name = "const-oid" version = "0.10.2" @@ -627,30 +607,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.4.0" @@ -779,6 +735,41 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" +dependencies = [ + "jiff-core", + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "js-sys" version = "0.3.106" @@ -1024,6 +1015,21 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -2006,7 +2012,8 @@ version = "0.3.0" dependencies = [ "auth-rs", "axum", - "chrono", + "jiff", + "log", "serde", "serde_json", "sha2", @@ -2048,65 +2055,12 @@ dependencies = [ "rustls-pki-types", ] -[[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 60386f7..e986509 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,8 +15,10 @@ publish = false [dependencies] axum = "0.8" -# A file's modification time as RFC 3339, in the config API's listing -chrono = { version = "0.4", default-features = false, features = ["std", "clock"] } +# A file's modification time as RFC 3339, in the config API's listing. 0.2, +# the line croner uses, so a service carries a single jiff. Only UTC is ever +# formatted, so none of the time zone database features. +jiff = { version = "0.2", default-features = false, features = ["std"] } serde = { version = "1", features = ["derive"] } # Content hashes: a config file's ETag, and the directory's sha2 = "0.11" @@ -39,3 +41,6 @@ tempfile = "3" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } # A log subscriber, so the fields of an audit event are evaluated in tests tracing-subscriber = "0.3" +# A `log` logger for tests/log_fallback_test.rs: with no tracing subscriber, +# tracing hands its events to the log crate (axum turns that feature on) +log = { version = "0.4", features = ["std"] } diff --git a/src/config/api.rs b/src/config/api.rs index 45c0302..dd083da 100644 --- a/src/config/api.rs +++ b/src/config/api.rs @@ -236,8 +236,27 @@ fn known_file(name: &str) -> Result<(), ApiError> { } } -fn rfc3339(time: std::time::SystemTime) -> String { - chrono::DateTime::::from(time).to_rfc3339() +// The exact shape chrono's to_rfc3339 gave, which this listing used before: +// a `+00:00` offset rather than `Z`, and the fraction in groups of three +// digits (none, milliseconds, microseconds or nanoseconds), so a client that +// compares or parses these strings sees no change. None only for a time +// outside jiff's range (beyond year 9999), which no file system reports. +fn rfc3339(time: std::time::SystemTime) -> Option { + let at = jiff::tz::TimeZone::UTC.to_datetime(jiff::Timestamp::try_from(time).ok()?); + let nanos = at.subsec_nanosecond(); + let fraction = if nanos == 0 { + String::new() + } else if nanos % 1_000_000 == 0 { + format!(".{:03}", nanos / 1_000_000) + } else if nanos % 1_000 == 0 { + format!(".{:06}", nanos / 1_000) + } else { + format!(".{nanos:09}") + }; + Some(format!( + "{}{fraction}+00:00", + at.strftime("%Y-%m-%dT%H:%M:%S") + )) } fn file_info(stat: &ConfigFileStat) -> ConfigFileInfo { @@ -245,7 +264,7 @@ fn file_info(stat: &ConfigFileStat) -> ConfigFileInfo { name: stat.name.clone(), size: stat.size, sha256: stat.sha256.clone(), - modified: stat.modified.map(rfc3339), + modified: stat.modified.and_then(rfc3339), } } @@ -623,3 +642,36 @@ fn deleted_names( deleted.dedup(); Ok(deleted) } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, UNIX_EPOCH}; + + // The strings chrono's to_rfc3339 gave for the same instants: the listing + // keeps that exact shape. + #[test] + fn rfc3339_keeps_the_shape_chrono_gave() { + let at = |secs, nanos| rfc3339(UNIX_EPOCH + Duration::new(secs, nanos)).unwrap(); + assert_eq!(at(1_700_000_000, 0), "2023-11-14T22:13:20+00:00"); + assert_eq!( + at(1_700_000_000, 500_000_000), + "2023-11-14T22:13:20.500+00:00" + ); + assert_eq!( + at(1_700_000_000, 250_000), + "2023-11-14T22:13:20.000250+00:00" + ); + assert_eq!(at(1_700_000_000, 7), "2023-11-14T22:13:20.000000007+00:00"); + assert_eq!( + rfc3339(UNIX_EPOCH - Duration::from_nanos(1)).unwrap(), + "1969-12-31T23:59:59.999999999+00:00" + ); + } + + #[test] + fn a_time_past_year_9999_has_no_rfc3339() { + let far = UNIX_EPOCH + Duration::from_secs(400_000_000_000); + assert_eq!(rfc3339(far), None); + } +} diff --git a/src/login.rs b/src/login.rs index 03945b9..3485a0a 100644 --- a/src/login.rs +++ b/src/login.rs @@ -480,9 +480,15 @@ pub async fn login_submit>( ); let mut response = axum::response::Redirect::to(&next).into_response(); - if let Ok(value) = HeaderValue::from_str(&cookie) { - response.headers_mut().insert(header::SET_COOKIE, value); - } + // Nothing to set when the value is not a valid header (it always is: a + // cookie name, a session token and a number). Written as an extend rather + // than an if let, whose never-taken else rust 1.100 counts as a line no + // test can reach. + response.headers_mut().extend( + HeaderValue::from_str(&cookie) + .ok() + .map(|value| (header::SET_COOKIE, value)), + ); response } diff --git a/src/pages.rs b/src/pages.rs index 0518ed9..80af575 100644 --- a/src/pages.rs +++ b/src/pages.rs @@ -1150,6 +1150,14 @@ mod tests { let html = page(&ctx("/api/v1/sources/src-d42", &headers), &json!({})); assert!(html.contains("Allow:")); assert!(html.contains("DELETE")); + + // A path the spec does not document has no Allow line to show; the + // response headers worth showing are listed either way. + let mut headers = HeaderMap::new(); + headers.insert(header::CONTENT_TYPE, "application/json".parse().unwrap()); + let html = page(&ctx("/api/v1/nowhere", &headers), &json!({})); + assert!(!html.contains("Allow:")); + assert!(html.contains("application/json")); } // Pressing Sync now lands on a POST-only path; the theme links there must diff --git a/tests/log_fallback_test.rs b/tests/log_fallback_test.rs new file mode 100644 index 0000000..1ce15f2 --- /dev/null +++ b/tests/log_fallback_test.rs @@ -0,0 +1,56 @@ +// A service that logs through the `log` crate and never sets up a tracing +// subscriber still sees these events: tracing hands them to `log` (its "log" +// feature, which axum turns on). Its own test binary, because a `log` logger +// is set once per process and no tracing subscriber may ever be set here. +use std::sync::Mutex; + +use auth_rs::http::{AuthContext, AuthMethod}; +use axum::http::HeaderMap; +use web_rs::UiAssets; + +struct Captured(Mutex>); + +impl log::Log for Captured { + fn enabled(&self, _: &log::Metadata) -> bool { + true + } + fn log(&self, record: &log::Record) { + self.0.lock().unwrap().push(record.args().to_string()); + } + fn flush(&self) {} +} + +static LOGGER: Captured = Captured(Mutex::new(Vec::new())); + +#[derive(Clone)] +struct Perm; + +impl auth_rs::http::Permission for Perm { + fn admin() -> Self { + Perm + } +} + +#[test] +fn events_reach_a_log_logger_when_there_is_no_tracing_subscriber() { + log::set_logger(&LOGGER).unwrap(); + log::set_max_level(log::LevelFilter::Trace); + + let auth = AuthContext { + key_name: Some("AWX".to_string()), + key_id: None, + permissions: (), + method: AuthMethod::ApiKey, + }; + web_rs::audit::record(&auth, &HeaderMap::new(), "sync", "src-a", "ok"); + let empty = tempfile::tempdir().unwrap(); + let _ = UiAssets::::new(empty.path(), "test_session"); + // A built UI is not worth a line. + let built = tempfile::tempdir().unwrap(); + std::fs::write(built.path().join("index.html"), "app").unwrap(); + let _ = UiAssets::::new(built.path(), "test_session"); + + let lines = LOGGER.0.lock().unwrap().join("\n"); + assert!(lines.contains("audit") && lines.contains("AWX"), "{lines}"); + assert_eq!(lines.matches("no index.html").count(), 1, "{lines}"); +} diff --git a/tests/ui_assets_test.rs b/tests/ui_assets_test.rs index 7baa880..83410a8 100644 --- a/tests/ui_assets_test.rs +++ b/tests/ui_assets_test.rs @@ -188,3 +188,35 @@ async fn a_build_without_its_index_still_answers() { let resp = ask(&app, "GET", "/sources", &[PAGE]).await; assert_eq!(resp.status(), StatusCode::NOT_FOUND); } + +// Collects what the subscriber writes, so the startup warning can be read. +#[derive(Clone, Default)] +struct Captured(Arc>>); + +impl std::io::Write for Captured { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +// A wrong ui directory is said once, at startup, naming the directory. +#[test] +fn a_directory_without_index_html_is_warned_at_startup() { + let empty = tempfile::tempdir().unwrap(); + let captured = Captured::default(); + let writer = captured.clone(); + let subscriber = tracing_subscriber::fmt() + .with_writer(move || writer.clone()) + .with_ansi(false) + .finish(); + tracing::subscriber::with_default(subscriber, || { + let _ = UiAssets::::new(empty.path(), COOKIE); + }); + let log = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap(); + assert!(log.contains("no index.html"), "{log}"); + assert!(log.contains(&empty.path().display().to_string()), "{log}"); +}