diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-14 15:10:28 +0000 |
|---|---|---|
| committer | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-14 15:10:28 +0000 |
| commit | 6daec6b5d03a80af3e2496b6bf666340b3d718fd (patch) | |
| tree | 842d614ba0a5cdd72473ea0d96eb061fd8fef0f5 | |
| parent | 586b0f63ef31fde987e00a305e91ee4e2136332e (diff) | |
| download | genenetwork4-6daec6b5d03a80af3e2496b6bf666340b3d718fd.tar.gz | |
log: name the person and the credential, and resolve handles from the registry
The access log said who (`user`) but not with what: with short tokens a
request can be made by a shared credential, so "which person" and "which
credential" are now separate fields -- `scheme` ("jwt" | "opaque") and,
for an opaque token, `token` (its registry handle, e.g.
`agent-ravanan-3`). Never the token or its hash, and the path still
carries no query string.
The line also gains `ts` (RFC 3339 UTC), so a redirected stderr file is
self-describing rather than relying on journald's prefix. Hand-rolled
civil-from-days rather than a new crate: one format, and no Cargo.lock
drift.
scripts/gn4-log.py reads such a log and shows it as a table with the
handle joined against tokens.sqlite: the subject as the registry has it
now (flagging a handle whose subject has been repointed), and the token's
status today -- [revoked], [expired], [unknown] -- which is how "an agent
was working at 14:02" is told apart from "an agent was working at 14:02
with a credential revoked since". It reads the registry read-only, passes
non-JSON lines through in table mode (the process log interleaves
backtraces), and offers --json and --summary for jq and for counting.
CallerSlot now carries the whole Caller (scheme, id, subject) rather than
just the subject string.
| -rw-r--r-- | README.md | 18 | ||||
| -rw-r--r-- | docs/www/SKILL.md | 7 | ||||
| -rwxr-xr-x | scripts/gn4-log.py | 242 | ||||
| -rw-r--r-- | src/auth.rs | 34 | ||||
| -rw-r--r-- | src/lib.rs | 101 |
5 files changed, 388 insertions, 14 deletions
diff --git a/README.md b/README.md index 55374c0..92abb02 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,24 @@ token reads **public data only**: it works everywhere a token suffices, and on token. Send it as `Authorization: Bearer gn4ai_...` and never in a query string, which would land in nginx's log and in `next` links. +**What a request looks like in the log.** One JSON line per request on stderr +(`GN4_ACCESS_LOG`), carrying the credentials, never the credential: + +```json +{"event":"request","ts":"2026-11-14T14:02:11Z","method":"POST", + "path":"/compute/gemma/ravanan","status":200,"took_ms":912, + "request_id":"…","user":"zachs","scheme":"opaque","token":"agent-ravanan-3"} +``` + +`user` is the gn-auth user id, so the line already answers *who*; `scheme` and +`token` say *with which credential* (absent for a JWT, which has no registry +handle). `scripts/gn4-log.py` reads such a log and shows it as a table with the +handle resolved against `tokens.sqlite` — the subject as the registry has it +now, plus the token's status *today* (`[revoked]`, `[expired]`, `[unknown]`) and +its note, which is how "an agent was working at 14:02" is told apart from "an +agent was working at 14:02 with a credential revoked since". The path is logged +without its query string, and no secret or hash is ever written. + A missing or invalid token is a 401; which further, resource-level authorization (if any) an endpoint checks once a token is valid is a separate, per-endpoint matter covered in each diff --git a/docs/www/SKILL.md b/docs/www/SKILL.md index b4454ec..2fa2385 100644 --- a/docs/www/SKILL.md +++ b/docs/www/SKILL.md @@ -179,6 +179,13 @@ SQLite database, `tokens.sqlite`). - 64 characters, `gn4ai_` + 56 body characters + a 2-character checksum, from an alphabet with no look-alikes (`0/O`, `1/l/I`) — a typo is refused before the registry is asked. +- **In the log**, one JSON line per request names the person and the credential: + `{"event":"request","ts":…,"user":"zachs","scheme":"opaque","token":"agent-1"}` + — never the token or its hash. `scripts/gn4-log.py -f LOG` renders that as a + table with the handle resolved against the registry, so it shows the subject + as the registry has it now and the token's status *today* (`[revoked]`, + `[expired]`, `[unknown]`); `--json` enriches the records for `jq`, and + `--summary` counts requests per caller and credential. ### Which GEMMA endpoint: ravanan by default diff --git a/scripts/gn4-log.py b/scripts/gn4-log.py new file mode 100755 index 0000000..a14e653 --- /dev/null +++ b/scripts/gn4-log.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 +"""Read the server's access log and show it with usernames. + +Every request writes one JSON line on stderr (src/lib.rs, `request_log_line`): + + {"event":"request","method":"POST","path":"/compute/gemma","status":200, + "took_ms":912,"request_id":"...","user":"zachs", + "scheme":"opaque","token":"agent-ravanan-3"} + +`user` is already the gn-auth user id, so most lines need no translation. The +`token` handle does: this script joins it against the token registry +(`tokens.sqlite`, `GN4_API_TOKENS_DB`) and shows + +- the subject **as the registry has it now** -- a token's row is authoritative, + so a handle whose target changed is visible; +- the token's status *today* -- `active`, `expired` or `revoked` -- which is + how you tell "an agent was working at 14:02" from "an agent was working at + 14:02 with a credential that has since been revoked"; +- the note on the row, e.g. what the token was minted for. + +Use it on a process log or a proxy log that carries `x-gn4-user`: + + journalctl -u genenetwork4 | scripts/gn4-log.py + scripts/gn4-log.py -f /var/log/gn4.log --since 2026-11-14 --grep gemma + scripts/gn4-log.py -f log.jsonl --json # enriched JSON, for jq + scripts/gn4-log.py -f log.jsonl --summary # who ran what, counted + +Lines that are not JSON (a Ruby backtrace, a GEMMA progress bar) pass through +unchanged unless --quiet; that is deliberate, because the process log +interleaves them and dropping them would hide the interesting failures. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import sqlite3 +import sys +import time +from collections import Counter +from pathlib import Path + +DATE = re.compile(r"^(?P<day>\d{4}-\d{2}-\d{2})") +TIME = re.compile(r"(?P<time>\d{2}:\d{2}:\d{2})") + + +def registry_path(explicit: str | None) -> Path: + if explicit: + return Path(explicit) + return Path(os.environ.get("GN4_API_TOKENS_DB", "tokens.sqlite")) + + +class Registry: + """Read-only view of the token registry, for translating handles.""" + + def __init__(self, path: Path): + self.path = path + self.connection = None + self.error = None + if not path.exists(): + self.error = f"no registry at {path} (set GN4_API_TOKENS_DB or --db)" + return + try: + # Read-only, and never creating: this must not touch a live + # database's write path. + uri = f"file:{path}?mode=ro" + self.connection = sqlite3.connect(uri, uri=True, timeout=5) + self.connection.row_factory = sqlite3.Row + except sqlite3.Error as error: # pragma: no cover - environment + self.error = f"cannot read {path}: {error}" + + def by_id(self, identifier: str) -> sqlite3.Row | None: + if self.connection is None: + return None + try: + return self.connection.execute( + "SELECT id, subject, scope, prefix, created_at, expires_at," + " last_used_at, revoked_at, note FROM token WHERE id = ?", + (identifier,), + ).fetchone() + except sqlite3.Error: + return None + + def status(self, row: sqlite3.Row | None, at: int | None = None) -> str: + if row is None: + return "unknown" + if row["revoked_at"] is not None: + return "revoked" + expires = row["expires_at"] + if expires is not None and expires <= (at or int(time.time())): + return "expired" + return "active" + + +def read_lines(handle) -> list[str]: + return [line.rstrip("\n") for line in handle] + + +def parse(line: str) -> dict | None: + if '"event":"request"' not in line and '"event": "request"' not in line: + return None + start = line.find("{") + if start < 0: + return None + try: + record = json.loads(line[start:]) + except json.JSONDecodeError: + return None + return record if record.get("event") == "request" else None + + +def when_of(record: dict, line: str) -> str: + """The record's own `ts` wins; a journald/nginx prefix is the fallback.""" + stamp = record.get("ts") + if isinstance(stamp, str) and len(stamp) >= 19: + return f"{stamp[:10]} {stamp[11:19]}" + return timestamp_of(line) + + +def timestamp_of(line: str) -> str: + day = DATE.search(line) + clock = TIME.search(line) + if day and clock: + return f"{day.group('day')} {clock.group('time')}" + return "" + + +def enrich(record: dict, registry: Registry, when: int | None) -> dict: + out = dict(record) + handle = record.get("token") + if handle: + row = registry.by_id(handle) + if row is None: + out["token_status"] = "unknown" + else: + out["token_status"] = registry.status(row, when) + out["token_subject"] = row["subject"] + out["token_scope"] = row["scope"] + if row["note"]: + out["token_note"] = row["note"] + if row["expires_at"]: + out["token_expires_at"] = row["expires_at"] + # A row whose subject differs from the logged one is worth + # seeing: the registry is authoritative, and this is the only + # way an operator notices a token was repointed. + if record.get("user") and row["subject"] != record["user"]: + out["token_subject_changed"] = True + out["user"] = row["subject"] + return out + + +def format_line(record: dict, when: str) -> str: + who = record.get("user") or "-" + credential = record.get("scheme") or "-" + if record.get("token"): + credential += f"/{record['token']}" + status = record.get("token_status") + if status and status != "active": + credential += f" [{status}]" + if record.get("token_subject_changed"): + credential += " [subject changed]" + took = record.get("took_ms", 0) + return ( + f"{when or '-':<19} {who:<20} {credential:<34} " + f"{record.get('method', '-'):<6} {record.get('status', '-'):>4} " + f"{took:>6} ms {record.get('path', '')}" + ) + + +def main() -> int: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("files", nargs="*", help="log files (default: stdin)") + parser.add_argument("-f", "--file", action="append", default=[], help="a log file") + parser.add_argument("--db", default=None, help="the token registry (default GN4_API_TOKENS_DB, else ./tokens.sqlite)") + parser.add_argument("--since", default=None, help="only lines whose date prefix is at or after this (YYYY-MM-DD)") + parser.add_argument("--grep", default=None, help="only lines containing this text (matches the raw line)") + parser.add_argument("--json", action="store_true", help="emit enriched JSON instead of a table") + parser.add_argument("--summary", action="store_true", help="count requests per caller and credential") + parser.add_argument("--quiet", action="store_true", help="drop lines that are not request records") + args = parser.parse_args() + + registry = Registry(registry_path(args.db)) + if registry.error and (args.json or args.summary): + print(f"gn4-log: {registry.error}", file=sys.stderr) + + files = args.files + args.file + handles = [open(path) for path in files] or [sys.stdin] + try: + lines = [line for handle in handles for line in read_lines(handle)] + finally: + for handle in handles: + if handle is not sys.stdin: + handle.close() + + rows: list[tuple[str, dict]] = [] + for line in lines: + if args.grep and args.grep not in line: + continue + record = parse(line) + when = when_of(record, line) if record else timestamp_of(line) + if args.since and when: + # Compare like with like: the table shows "YYYY-MM-DD HH:MM:SS", + # and --since accepts a bare date or a date and a time. + stamp = when.replace(" ", "T") + if stamp < args.since: + continue + if record is None: + # Non-JSON lines (a Ruby backtrace, a GEMMA progress bar) pass + # through in table mode -- the process log interleaves them, and + # dropping them would hide the interesting failures -- but never + # in a machine-readable mode. + if not args.quiet and not args.json and not args.summary: + print(line) + continue + rows.append((when, enrich(record, registry, None))) + + if args.summary: + callers = Counter( + (record.get("user") or "-", record.get("scheme") or "-", record.get("token") or "-") + for _, record in rows + ) + width = max((len(" ".join(key)) for key in callers), default=10) + for (user, scheme, handle), count in callers.most_common(): + credential = scheme if handle == "-" else f"{scheme}/{handle}" + label = f"{user} {credential}" + print(f"{count:>7} {label:<{width}}") + print(f"{len(rows):>7} {'total':<{width}}") + return 0 + + for when, record in rows: + if args.json: + print(json.dumps(record)) + else: + print(format_line(record, when)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/auth.rs b/src/auth.rs index a2036e1..23ef582 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -62,18 +62,36 @@ pub const USER_HEADER: &str = "x-gn4-user"; /// [`crate::lib::tag_caller`] to put on the response, since the extractor /// runs inside the handler and the middleware outside it. #[derive(Debug, Clone, Default)] -pub struct CallerSlot(std::sync::Arc<std::sync::Mutex<Option<String>>>); +pub struct CallerSlot(std::sync::Arc<std::sync::Mutex<Option<Caller>>>); + +/// Who a request ran as, and with which credential. The subject is a +/// gn-auth user id; `id` is the registry handle of an opaque token +/// (`agent-ravanan-3`) and `None` for a JWT. Both go to the access log, +/// because "which person, with which credential" is two different +/// questions -- a shared token and a personal one can carry the same +/// subject, and a token's handle is what `scripts/gn4-log.py` resolves +/// against the registry. +#[derive(Debug, Clone)] +pub struct Caller { + pub scheme: Scheme, + pub id: Option<String>, + pub subject: String, +} impl CallerSlot { - /// Record the subject of the verified token. - pub fn set(&self, subject: &str) { + /// Record the identity of the verified credential. + pub fn set(&self, scheme: Scheme, id: Option<&str>, subject: &str) { if let Ok(mut slot) = self.0.lock() { - *slot = Some(subject.to_string()); + *slot = Some(Caller { + scheme, + id: id.map(str::to_string), + subject: subject.to_string(), + }); } } - /// The subject, if a handler got as far as verifying a token. - pub fn get(&self) -> Option<String> { + /// The caller, if a handler got as far as verifying a token. + pub fn get(&self) -> Option<Caller> { self.0.lock().ok().and_then(|slot| slot.clone()) } } @@ -161,7 +179,7 @@ impl<S: Send + Sync> FromRequestParts<S> for AuthToken { .map_err(|e| unauthorized(&format!("token registry error: {e}")))? .ok_or_else(|| unauthorized("That token is not valid, has been revoked or has expired."))?; if let Some(slot) = parts.extensions.get::<CallerSlot>() { - slot.set(&record.subject); + slot.set(Scheme::Opaque, Some(&record.id), &record.subject); } return Ok(AuthToken { scheme: Scheme::Opaque, @@ -176,7 +194,7 @@ impl<S: Send + Sync> FromRequestParts<S> for AuthToken { verify(token, &config.auth_server_url).map_err(|e| unauthorized(&e.to_string()))?; // For the response header the proxy logs (see `CallerSlot`). if let Some(slot) = parts.extensions.get::<CallerSlot>() { - slot.set(&claims.sub); + slot.set(Scheme::Jwt, None, &claims.sub); } Ok(AuthToken { scheme: Scheme::Jwt, diff --git a/src/lib.rs b/src/lib.rs index 3222369..273554d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -94,7 +94,8 @@ async fn tag_caller( .and_then(|value| value.to_str().ok()) .map(str::to_string); let mut response = next.run(request).await; - let subject = slot.get(); + let caller = slot.get(); + let subject = caller.as_ref().map(|caller| caller.subject.clone()); 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. @@ -116,7 +117,7 @@ async fn tag_caller( response.status().as_u16(), started.elapsed().as_millis(), request_id.as_deref(), - subject.as_deref(), + caller.as_ref(), ) ); } @@ -127,13 +128,19 @@ async fn tag_caller( /// 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. +/// +/// `scheme` and (for an opaque token) `token` say which credential was +/// used, never the credential itself: `{"scheme":"opaque","token":"agent-1"}` +/// lets `scripts/gn4-log.py` resolve the handle against the registry -- the +/// subject as it is *now*, the token's status and its note -- without the log +/// ever holding a secret or a hash. fn request_log_line( method: &str, path: &str, status: u16, took_ms: u128, request_id: Option<&str>, - user: Option<&str>, + caller: Option<&crate::auth::Caller>, ) -> String { let mut line = serde_json::json!({ "event": "request", @@ -142,15 +149,55 @@ fn request_log_line( "status": status, "took_ms": took_ms, }); + if let Some(object) = line.as_object_mut() { + object.insert("ts".to_string(), serde_json::json!(rfc3339_utc_now())); + } 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)); + if let (Some(caller), Some(object)) = (caller, line.as_object_mut()) { + object.insert("user".to_string(), serde_json::json!(caller.subject)); + object.insert("scheme".to_string(), serde_json::json!(caller.scheme.as_str())); + if let Some(id) = &caller.id { + object.insert("token".to_string(), serde_json::json!(id)); + } } line.to_string() } +/// The current time as RFC 3339 UTC, e.g. `2026-11-14T14:02:11Z`. +/// +/// Hand-rolled rather than pulling in a date crate: the access log needs +/// one format, `time` is only a transitive dependency (see docs/dev/SKILL.md +/// on Cargo.lock drift), and this is the civil-from-days inverse of +/// `auth.rs`'s `days_from_civil`. +fn rfc3339_utc_now() -> String { + let seconds = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|since| since.as_secs() as i64) + .unwrap_or(0); + let days = seconds.div_euclid(86_400); + let of_day = seconds.rem_euclid(86_400); + // Howard Hinnant's civil_from_days. + let z = days + 719_468; + let era = z.div_euclid(146_097); + let day_of_era = z - era * 146_097; + let year_of_era = + (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let year = year_of_era + era * 400; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let mp = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = if month <= 2 { year + 1 } else { year }; + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", + of_day / 3600, + (of_day % 3600) / 60, + of_day % 60 + ) +} + /// 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 { @@ -377,10 +424,26 @@ async fn version(ctx: Ctx) -> Json<Envelope<VersionInfo>> { #[cfg(test)] mod access_log_tests { use super::request_log_line; + use crate::auth::{Caller, Scheme}; + + fn caller(scheme: Scheme, id: Option<&str>, subject: &str) -> Caller { + Caller { + scheme, + id: id.map(str::to_string), + subject: subject.to_string(), + } + } #[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 line = request_log_line( + "GET", + "/groups/BXD", + 200, + 17, + Some("abc"), + Some(&caller(Scheme::Jwt, None, "zachs")), + ); let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); assert_eq!(parsed["event"], "request"); assert_eq!(parsed["method"], "GET"); @@ -389,6 +452,32 @@ mod access_log_tests { assert_eq!(parsed["took_ms"], 17); assert_eq!(parsed["request_id"], "abc"); assert_eq!(parsed["user"], "zachs"); + assert_eq!(parsed["scheme"], "jwt"); + assert!( + parsed["ts"].as_str().is_some_and(|ts| ts.len() == 20 && ts.ends_with('Z')), + "the line is self-describing: {}", + parsed["ts"] + ); + assert!(parsed.get("token").is_none(), "a JWT has no registry handle"); + } + + /// An opaque token names its registry handle, never the token or its + /// hash: the handle is what a reader resolves against `tokens.sqlite`. + #[test] + fn an_opaque_token_logs_its_handle_and_not_the_secret() { + let line = request_log_line( + "POST", + "/compute/gemma", + 200, + 900, + None, + Some(&caller(Scheme::Opaque, Some("agent-ravanan-3"), "zachs")), + ); + let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); + assert_eq!(parsed["user"], "zachs"); + assert_eq!(parsed["scheme"], "opaque"); + assert_eq!(parsed["token"], "agent-ravanan-3"); + assert!(!line.contains("gn4ai_"), "{line}"); } /// An unauthenticated request has no subject; a dash would be a value a |
