diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-14 13:27:44 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-14 13:27:44 +0000 |
| commit | f64a7084694fc28fc2069e39778a83716c1b858e (patch) | |
| tree | f2f25b8eff4548a4610f4383cf3bafa45057adfb /src | |
| parent | 96c1979e5d4b662e8b4426dc7e9a27a5b7742c67 (diff) | |
| download | genenetwork4-f64a7084694fc28fc2069e39778a83716c1b858e.tar.gz | |
logs: one access line per request, naming the caller
The proxy logs the caller through x-gn4-user, but the process log -- the one an
operator tails while a job runs -- named nobody, so "who started this GEMMA
run" meant going to the nginx log or guessing. genenetwork4 now writes one
compact JSON line per request on stderr:
{"event":"request","method":"GET","path":"/groups/BXD","status":200,
"took_ms":10,"request_id":"…","user":"zachs"}
Decisions in it: `user` is absent, not "-", when no token was verified (a dash
is a value a reader can mistake for a user name); the path is logged without
its query string, because a query can carry a credential and has no business
in a log; the token value itself is never logged, only its subject; and the
line carries the `request_id`, so it sits beside the existing `event: error`
lines for 5xx and one grep joins a failure to the request that caused it.
`GN4_ACCESS_LOG=false` turns it off where the proxy's log is the record of
truth.
Verified on a probe instance: with the test token the line says
user "gn4-test-stub", with zachs's token user "zachs", and an unauthenticated
401 has no user field at all.
docs/www/operator-checklist.md claimed "genenetwork4 does not log the token's
sub" -- true until now, which is exactly the kind of sentence that rots; it is
replaced by the line above, what it contains and what it deliberately omits.
README's x-gn4-user paragraph gains the same, next to the identity it already
described.
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 9 | ||||
| -rw-r--r-- | src/lib.rs | 87 |
2 files changed, 94 insertions, 2 deletions
diff --git a/src/config.rs b/src/config.rs index 58cc219..ff0ab8c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -57,6 +57,12 @@ pub struct Config { /// absent: a 404, and not in /openapi.json either. See /// `parse_switch` and src/routes/dev.rs. pub test_token_enabled: bool, + /// One access-log line per request on stderr, naming the caller + /// (`GN4_ACCESS_LOG`, default on). The line is one compact JSON object: + /// method, path, status, took_ms, request_id and `user` when the token + /// identified one. Turn it off where the proxy's own access log is the + /// record of truth and this would only duplicate it. + pub access_log: bool, /// gn-auth OAuth2 client id/secret and dev user credentials used by /// POST /get-test-token's password-grant call. Default to gn-auth's own /// well-known development fixtures (`flask init-dev-clients`, @@ -231,6 +237,7 @@ impl Config { "http://127.0.0.1:8081/".to_string(), ); values.insert("GENENETWORK4_BIND".to_string(), "0.0.0.0".to_string()); + values.insert("GN4_ACCESS_LOG".to_string(), "true".to_string()); values.insert("GENENETWORK4_TEST_TOKEN".to_string(), "true".to_string()); values.insert( "GN_AUTH_DEV_CLIENT_ID".to_string(), @@ -420,6 +427,7 @@ impl Config { "GENENETWORK4_PORT", "AUTH_SERVER_URL", "GENENETWORK4_BIND", + "GN4_ACCESS_LOG", "GENENETWORK4_TEST_TOKEN", "GN_AUTH_DEV_CLIENT_ID", "GN_AUTH_DEV_CLIENT_SECRET", @@ -494,6 +502,7 @@ impl Config { auth_server_url: values["AUTH_SERVER_URL"].clone(), bind: values["GENENETWORK4_BIND"].clone(), test_token_enabled: parse_switch(&values["GENENETWORK4_TEST_TOKEN"]), + access_log: parse_switch(&values["GN4_ACCESS_LOG"]), dev_token_client_id: values["GN_AUTH_DEV_CLIENT_ID"].clone(), dev_token_client_secret: values["GN_AUTH_DEV_CLIENT_SECRET"].clone(), dev_token_username: values["GN_AUTH_DEV_USERNAME"].clone(), diff --git a/src/lib.rs b/src/lib.rs index e6aa328..e054c42 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -82,19 +82,74 @@ async fn tag_caller( ) -> axum::response::Response { let slot = crate::auth::CallerSlot::default(); request.extensions_mut().insert(slot.clone()); + let started = std::time::Instant::now(); + let method = request.method().clone(); + // The path only: a query string can carry a credential (`?token=`) and has + // no business in a log line. + let path = request.uri().path().to_string(); + let request_id = request + .headers() + .get("x-request-id") + .and_then(|value| value.to_str().ok()) + .map(str::to_string); let mut response = next.run(request).await; - if let Some(subject) = slot.get() { + let subject = slot.get(); + if let Some(subject) = &subject { // The subject is a gn-auth user id (an ASCII username); anything // else is dropped rather than turned into an invalid header. - if let Ok(value) = axum::http::HeaderValue::from_str(&subject) { + if let Ok(value) = axum::http::HeaderValue::from_str(subject) { response .headers_mut() .insert(crate::auth::USER_HEADER, value); } } + // One line per request, with the user: the proxy's access log names the + // caller through `x-gn4-user`, but the process log is what an operator + // tails while watching a job, and "which user ran this" belongs in it. + if config::Config::load().access_log { + eprintln!( + "{}", + request_log_line( + method.as_str(), + &path, + response.status().as_u16(), + started.elapsed().as_millis(), + request_id.as_deref(), + subject.as_deref(), + ) + ); + } response } +/// The access-log line: one compact JSON object, so it greps and parses like +/// the error lines. `user` is absent rather than `"-"` when nobody was +/// identified -- an unauthenticated request has no subject, and a dash would be +/// a value a reader could mistake for a user name. +fn request_log_line( + method: &str, + path: &str, + status: u16, + took_ms: u128, + request_id: Option<&str>, + user: Option<&str>, +) -> String { + let mut line = serde_json::json!({ + "event": "request", + "method": method, + "path": path, + "status": status, + "took_ms": took_ms, + }); + if let (Some(request_id), Some(object)) = (request_id, line.as_object_mut()) { + object.insert("request_id".to_string(), serde_json::json!(request_id)); + } + if let (Some(user), Some(object)) = (user, line.as_object_mut()) { + object.insert("user".to_string(), serde_json::json!(user)); + } + line.to_string() +} + /// Build the application router. Public so integration tests (tests/) and /// the binary (src/main.rs) can both use it without binding a real socket. pub fn app() -> Router { @@ -303,3 +358,31 @@ async fn version(ctx: Ctx) -> Json<Envelope<VersionInfo>> { } Json(envelope.with_links(crate::suggest::root_links())) } + +#[cfg(test)] +mod access_log_tests { + use super::request_log_line; + + #[test] + fn the_line_names_the_user_and_never_the_query() { + let line = request_log_line("GET", "/groups/BXD", 200, 17, Some("abc"), Some("zachs")); + let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); + assert_eq!(parsed["event"], "request"); + assert_eq!(parsed["method"], "GET"); + assert_eq!(parsed["path"], "/groups/BXD"); + assert_eq!(parsed["status"], 200); + assert_eq!(parsed["took_ms"], 17); + assert_eq!(parsed["request_id"], "abc"); + assert_eq!(parsed["user"], "zachs"); + } + + /// An unauthenticated request has no subject; a dash would be a value a + /// reader could mistake for a user name. + #[test] + fn no_user_field_when_nobody_was_identified() { + let line = request_log_line("GET", "/groups", 401, 0, None, None); + let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); + assert!(parsed.get("user").is_none(), "{line}"); + assert!(parsed.get("request_id").is_none(), "{line}"); + } +} |
