Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 52 additions & 98 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 7 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"] }
58 changes: 55 additions & 3 deletions src/config/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,16 +236,35 @@ fn known_file(name: &str) -> Result<(), ApiError> {
}
}

fn rfc3339(time: std::time::SystemTime) -> String {
chrono::DateTime::<chrono::Utc>::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<String> {
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 {
ConfigFileInfo {
name: stat.name.clone(),
size: stat.size,
sha256: stat.sha256.clone(),
modified: stat.modified.map(rfc3339),
modified: stat.modified.and_then(rfc3339),
}
}

Expand Down Expand Up @@ -623,3 +642,36 @@ fn deleted_names<C>(
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);
}
}
12 changes: 9 additions & 3 deletions src/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,9 +480,15 @@ pub async fn login_submit<P: Permission, S: SignIn<P>>(
);

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
}

Expand Down
8 changes: 8 additions & 0 deletions src/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
56 changes: 56 additions & 0 deletions tests/log_fallback_test.rs
Original file line number Diff line number Diff line change
@@ -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<Vec<String>>);

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::<Perm>::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::<Perm>::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}");
}
Loading
Loading