interplane.Get Omega
Read in your language

readings-window

aien-dev/readings-window

Brought by drakestapleton

branch main Branches Tags History

readings-window / src / main.rs

573 lines · 23662 bytes Raw Blame History
1//! readings-window: read-only HTTPS endpoint for Spark readings.
2//! `collect` appends one reading to the history file; `serve` publishes it.
3use serde_json::Value;
4mod tls;
5use std::fs;
6use std::io::Write;
7use std::process::Command;
8use std::time::{SystemTime, UNIX_EPOCH};
9
10const HISTORY: &str = "/var/lib/readings-window/history.jsonl";
11const TOKEN: &str = "/etc/readings-window/token";
12const CERT: &str = "/etc/readings-window/fullchain.pem";
13const KEY: &str = "/etc/readings-window/key.pem";
14const STATUS: &str = "/var/lib/readings-window/status.json";
15const RESULTS: &str = "/var/lib/readings-window/results.json";
16const STATUS_DEFAULT: &str = r#"{"ts":0,"label":"unknown"}"#;
17const RESULTS_DEFAULT: &str = r#"{"updated":0,"results":[]}"#;
18const EXPOSURE: &str = "/var/lib/readings-window/exposure.json";
19const EXPOSURE_DEFAULT: &str = r#"{"status":"unknown"}"#;
20const EXPOSURE_STALE_SECS: u64 = 3600;
21const KEEP_SECS: u64 = 30 * 86400;
22const MAX_HOURS: u64 = 720;
23const DEFAULT_HOURS: u64 = 24;
24const FIELDS: [&str; 10] = [
25 "ts", "gpu_util_pct", "gpu_temp_c", "gpu_power_w", "load1", "load5", "load15",
26 "cpu_temp_c", "mem_used_mb", "mem_total_mb",
27];
28
29fn now() -> u64 {
30 SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
31}
32
33/// Constant-time equality (length leak only).
34fn ct_eq(a: &[u8], b: &[u8]) -> bool {
35 if a.len() != b.len() {
36 return false;
37 }
38 a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
39}
40
41fn auth_ok(header: Option<&str>, token: &str) -> bool {
42 match header.and_then(|h| h.strip_prefix("Bearer ")) {
43 Some(t) => ct_eq(t.trim().as_bytes(), token.as_bytes()),
44 None => false,
45 }
46}
47
48fn clamp_hours(q: Option<&str>) -> u64 {
49 let h = q
50 .and_then(|q| q.split('&').find_map(|kv| kv.strip_prefix("hours=")))
51 .and_then(|v| v.parse::<u64>().ok())
52 .unwrap_or(DEFAULT_HOURS);
53 h.clamp(1, MAX_HOURS)
54}
55
56fn ts_of(line: &str) -> Option<u64> {
57 serde_json::from_str::<Value>(line).ok()?.get("ts")?.as_u64()
58}
59
60/// Lines whose ts is at or after `cutoff`.
61fn filter_since<'a>(lines: impl Iterator<Item = &'a str>, cutoff: u64) -> Vec<&'a str> {
62 lines.filter(|l| ts_of(l).is_some_and(|t| t >= cutoff)).collect()
63}
64
65fn validate(line: &str) -> Result<Value, String> {
66 let v: Value = serde_json::from_str(line.trim()).map_err(|e| format!("bad json: {e}"))?;
67 for f in FIELDS {
68 if v.get(f).is_none() {
69 return Err(format!("missing field {f}"));
70 }
71 }
72 v["ts"].as_u64().ok_or("ts not integer")?;
73 Ok(v)
74}
75
76/// Spark ssh targets (`user@host`, tried in order), one per `target=` line in SPARK_CONF.
77/// The real file is local-only; see `spark.conf.example`.
78const SPARK_CONF: &str = "/etc/readings-window/spark.conf";
79
80fn spark_targets(conf: &str) -> Vec<String> {
81 conf.lines()
82 .filter_map(|l| l.trim().strip_prefix("target="))
83 .map(|t| t.trim().to_string())
84 .filter(|t| !t.is_empty())
85 .collect()
86}
87
88/// First nonempty identity wins; omission leaves identity selection to OpenSSH.
89fn spark_identity(conf: &str) -> Option<&str> {
90 conf.lines()
91 .filter_map(|l| l.trim().strip_prefix("identity="))
92 .map(str::trim)
93 .find(|identity| !identity.is_empty())
94}
95
96fn spark_ssh(target: &str, remote: &str, identity: Option<&str>) -> Command {
97 let mut command = Command::new("ssh");
98 if let Some(identity) = identity {
99 command.args(["-i", identity]);
100 }
101 command.args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", target, remote]);
102 command
103}
104
105/// Remote paths are relative: ssh runs the command in the Spark user's home directory.
106fn fetch(remote: &str) -> Result<std::process::Output, String> {
107 let conf = fs::read_to_string(SPARK_CONF).map_err(|e| format!("{SPARK_CONF}: {e}"))?;
108 let identity = spark_identity(&conf);
109 let mut last = String::from("no hosts");
110 for target in spark_targets(&conf) {
111 let host = &target;
112 let r = spark_ssh(target.as_str(), remote, identity).output();
113 match r {
114 Ok(o) if o.status.success() => return Ok(o),
115 Ok(o) => last = format!("{host}: ssh exit {}", o.status),
116 Err(e) => last = format!("{host}: ssh failed to start: {e}"),
117 }
118 }
119 Err(last)
120}
121
122/// Status feed: object with integer ts and string label.
123fn validate_status(s: &str) -> Result<Value, String> {
124 let v: Value = serde_json::from_str(s.trim()).map_err(|e| format!("bad json: {e}"))?;
125 v.get("ts").and_then(Value::as_u64).ok_or("status: ts not integer")?;
126 v.get("label").and_then(Value::as_str).ok_or("status: label not string")?;
127 if v.get("detail").is_some_and(|d| !d.is_string()) {
128 return Err("status: detail not string".into());
129 }
130 Ok(v)
131}
132
133/// Results feed: integer updated, list of {name, verdict, date, receipt, note?}.
134fn validate_results(s: &str) -> Result<Value, String> {
135 let v: Value = serde_json::from_str(s.trim()).map_err(|e| format!("bad json: {e}"))?;
136 v.get("updated").and_then(Value::as_u64).ok_or("results: updated not integer")?;
137 let list = v.get("results").and_then(Value::as_array).ok_or("results: results not a list")?;
138 for r in list {
139 for k in ["name", "date", "receipt"] {
140 r.get(k).and_then(Value::as_str).ok_or(format!("results: {k} not string"))?;
141 }
142 match r.get("verdict").and_then(Value::as_str) {
143 Some("PASS" | "FAIL" | "INCONCLUSIVE") => {}
144 _ => return Err("results: bad verdict".into()),
145 }
146 if r.get("note").is_some_and(|n| !n.is_string()) {
147 return Err("results: note not string".into());
148 }
149 }
150 Ok(v)
151}
152
153/// Best-effort copy of one feed file to the hub; a bad or missing file keeps the old cache.
154fn collect_feed(remote_path: &str, dest: &str, check: fn(&str) -> Result<Value, String>) {
155 let res = fetch(&format!("cat {remote_path}")).and_then(|o| {
156 let v = check(&String::from_utf8_lossy(&o.stdout))?;
157 let body = serde_json::to_string(&v).map_err(|e| e.to_string())?;
158 let tmp = format!("{dest}.tmp");
159 fs::write(&tmp, body).map_err(|e| e.to_string())?;
160 fs::rename(&tmp, dest).map_err(|e| e.to_string())
161 });
162 if let Err(e) = res {
163 eprintln!("readings-window: feed {dest}: {e}");
164 }
165}
166
167/// Serve a cached feed, or the default if missing or invalid.
168fn feed_body(path: &str, check: fn(&str) -> Result<Value, String>, default: &str) -> String {
169 fs::read_to_string(path)
170 .ok()
171 .and_then(|s| check(&s).ok())
172 .and_then(|v| serde_json::to_string(&v).ok())
173 .unwrap_or_else(|| default.into())
174}
175
176fn validate_exposure(s: &str) -> Result<Value, String> {
177 let v: Value = serde_json::from_str(s).map_err(|e| e.to_string())?;
178 match v.get("status").and_then(Value::as_str) {
179 Some("ok") | Some("changed") => Ok(v),
180 _ => Err("bad status".into()),
181 }
182}
183
184/// "ok", "changed" or "unknown" (missing, invalid, or older than an hour).
185fn exposure_state(s: Option<&str>, now_s: u64) -> &'static str {
186 let Some(v) = s.and_then(|s| validate_exposure(s).ok()) else { return "unknown" };
187 let ts = v.get("ts").and_then(Value::as_u64).unwrap_or(0);
188 if ts == 0 || now_s.saturating_sub(ts) > EXPOSURE_STALE_SECS {
189 return "unknown";
190 }
191 if v["status"] == "ok" { "ok" } else { "changed" }
192}
193
194fn collect() -> Result<(), String> {
195 let out = fetch("/usr/local/bin/spark-readings")?;
196 let text = String::from_utf8_lossy(&out.stdout);
197 let line = text.lines().next().unwrap_or("");
198 let v = validate(line)?;
199 let compact = serde_json::to_string(&v).map_err(|e| e.to_string())?;
200 let old = fs::read_to_string(HISTORY).unwrap_or_default();
201 let cutoff = now().saturating_sub(KEEP_SECS);
202 let mut keep = filter_since(old.lines(), cutoff).join("\n");
203 if !keep.is_empty() {
204 keep.push('\n');
205 }
206 keep.push_str(&compact);
207 keep.push('\n');
208 let tmp = format!("{HISTORY}.tmp");
209 fs::File::create(&tmp).and_then(|mut f| f.write_all(keep.as_bytes())).map_err(|e| e.to_string())?;
210 fs::rename(&tmp, HISTORY).map_err(|e| e.to_string())
211}
212
213fn last_line() -> Option<String> {
214 fs::read_to_string(HISTORY).ok()?.lines().rev().find(|l| ts_of(l).is_some()).map(String::from)
215}
216
217const CHAT_DEFAULT_LINES: u64 = 500;
218const CHAT_MAX_LINES: u64 = 50000;
219const JSON_TYPE: &str = "application/json";
220const TEXT_TYPE: &str = "text/plain; charset=utf-8";
221const NDJSON_TYPE: &str = "application/x-ndjson";
222
223/// One allowed agent: every remote path is a constant, never built from request input.
224struct Agent {
225 name: &'static str,
226 latest_txt: &'static str,
227 latest_jsonl: &'static str,
228 records_glob: &'static str,
229}
230
231macro_rules! agent {
232 ($n:literal) => {
233 Agent {
234 name: $n,
235 latest_txt: concat!("archive/agent-chats/latest/", $n, ".txt"),
236 latest_jsonl: concat!("archive/agent-chats/latest/", $n, ".jsonl"),
237 records_glob: concat!("archive/agent-chats/records/", $n, "/*.jsonl"),
238 }
239 };
240}
241
242/// The fixed allow-list, matched exactly.
243const AGENTS: [Agent; 5] = [agent!("claude"), agent!("codex"), agent!("opencode"), agent!("gemini"), agent!("muse")];
244const AGENTS_JSON: &str = r#"{"agents":["claude","codex","opencode","gemini","muse"]}"#;
245
246/// What one chat request reads on the Spark.
247#[derive(Debug, PartialEq)]
248struct ChatFeed {
249 /// Rolling window file, read with `tail` (and with `cat` for `?all=1` on plain text).
250 latest: &'static str,
251 /// What `?all=1` reads: the same file (plain) or the records glob (jsonl).
252 all: &'static str,
253 ctype: &'static str,
254}
255
256/// Number of lines asked for in `?lines=N`: default 500, clamped to 1..=50000.
257fn clamp_lines(q: Option<&str>) -> u64 {
258 let n = q
259 .and_then(|q| q.split('&').find_map(|kv| kv.strip_prefix("lines=")))
260 .and_then(|v| v.parse::<u64>().ok())
261 .unwrap_or(CHAT_DEFAULT_LINES);
262 n.clamp(1, CHAT_MAX_LINES)
263}
264
265/// Remote command for a chat feed: only constant paths and a validated integer reach the shell.
266fn chat_command(feed: &ChatFeed, q: Option<&str>) -> String {
267 if q.is_some_and(|q| q.split('&').any(|kv| kv == "all=1")) {
268 format!("cat {}", feed.all)
269 } else {
270 format!("tail -n {} {}", clamp_lines(q), feed.latest)
271 }
272}
273
274/// `/v1/chat/<agent>` and `/v1/chat/<agent>.jsonl` for allow-listed agents only.
275fn chat_route(path: &str) -> Option<ChatFeed> {
276 let rest = path.strip_prefix("/v1/chat/")?;
277 let (name, jsonl) = match rest.strip_suffix(".jsonl") {
278 Some(n) => (n, true),
279 None => (rest, false),
280 };
281 let a = AGENTS.iter().find(|a| a.name == name)?;
282 Some(if jsonl {
283 ChatFeed { latest: a.latest_jsonl, all: a.records_glob, ctype: NDJSON_TYPE }
284 } else {
285 ChatFeed { latest: a.latest_txt, all: a.latest_txt, ctype: TEXT_TYPE }
286 })
287}
288
289/// Proxy a chat feed live from the Spark; nothing is written or cached on the hub.
290fn chat_feed(feed: &ChatFeed, q: Option<&str>) -> (u16, String, &'static str) {
291 match fetch(&chat_command(feed, q)) {
292 Ok(o) => (200, String::from_utf8_lossy(&o.stdout).into_owned(), feed.ctype),
293 Err(e) => {
294 eprintln!("readings-window: chat feed {}: {e}", feed.latest);
295 (502, r#"{"error":"spark unreachable"}"#.into(), JSON_TYPE)
296 }
297 }
298}
299
300fn handle(method: &str, url: &str, auth: Option<&str>, token: &str) -> (u16, String, &'static str) {
301 let (path, query) = match url.split_once('?') {
302 Some((p, q)) => (p, Some(q)),
303 None => (url, None),
304 };
305 let chat = chat_route(path);
306 let known = chat.is_some() || matches!(path, "/health" | "/v1/readings/current" | "/v1/readings/history" | "/v1/status" | "/v1/results" | "/v1/exposure" | "/v1/chat");
307 if !known {
308 return (404, r#"{"error":"not found"}"#.into(), JSON_TYPE);
309 }
310 if method != "GET" {
311 return (405, r#"{"error":"method not allowed"}"#.into(), JSON_TYPE);
312 }
313 if path == "/health" {
314 let ex = exposure_state(fs::read_to_string(EXPOSURE).ok().as_deref(), now());
315 let age = match last_line().and_then(|l| ts_of(&l)) {
316 Some(t) => now().saturating_sub(t).to_string(),
317 None => "null".into(),
318 };
319 return (200, format!(r#"{{"status":"ok","last_reading_age_s":{age},"exposure":"{ex}"}}"#), JSON_TYPE);
320 }
321 if !auth_ok(auth, token) {
322 return (401, r#"{"error":"unauthorized"}"#.into(), JSON_TYPE);
323 }
324 if path == "/v1/exposure" {
325 return (200, feed_body(EXPOSURE, validate_exposure, EXPOSURE_DEFAULT), JSON_TYPE);
326 }
327 if path == "/v1/status" {
328 return (200, feed_body(STATUS, validate_status, STATUS_DEFAULT), JSON_TYPE);
329 }
330 if path == "/v1/results" {
331 return (200, feed_body(RESULTS, validate_results, RESULTS_DEFAULT), JSON_TYPE);
332 }
333 if path == "/v1/chat" {
334 return (200, AGENTS_JSON.into(), JSON_TYPE);
335 }
336 if let Some(feed) = &chat {
337 return chat_feed(feed, query);
338 }
339 if path == "/v1/readings/current" {
340 return match last_line() {
341 Some(l) => (200, l, JSON_TYPE),
342 None => (503, r#"{"error":"no readings yet"}"#.into(), JSON_TYPE),
343 };
344 }
345 let cutoff = now().saturating_sub(clamp_hours(query) * 3600);
346 let all = fs::read_to_string(HISTORY).unwrap_or_default();
347 let rows = filter_since(all.lines(), cutoff);
348 (200, format!("[{}]", rows.join(",")), JSON_TYPE)
349}
350
351fn serve() -> Result<(), String> {
352 let token = fs::read_to_string(TOKEN).map_err(|e| format!("token: {e}"))?.trim().to_string();
353 if token.len() < 32 {
354 return Err("token too short".into());
355 }
356 let cfg = tls::tls_config(&fs::read(CERT).map_err(|e| format!("cert: {e}"))?, &fs::read(KEY).map_err(|e| format!("key: {e}"))?)?;
357 let listener = std::net::TcpListener::bind("0.0.0.0:9443").map_err(|e| format!("bind: {e}"))?;
358 tls::serve_on(listener, cfg, token);
359 Ok(())
360}
361
362fn main() {
363 let r = match std::env::args().nth(1).as_deref() {
364 Some("collect") => {
365 let r = collect();
366 collect_feed("status/current.json", STATUS, validate_status);
367 collect_feed("status/results.json", RESULTS, validate_results);
368 r
369 }
370 Some("serve") => serve(),
371 _ => Err("usage: readings-window collect|serve".into()),
372 };
373 if let Err(e) = r {
374 eprintln!("readings-window: {e}");
375 std::process::exit(1);
376 }
377}
378
379#[cfg(test)]
380mod tests {
381 use super::*;
382 /// The exposure-watch baseline parser regression test runs with every `cargo test`.
383 #[test]
384 fn exposure_watch_baseline_script() {
385 let script = concat!(env!("CARGO_MANIFEST_DIR"), "/scripts/test-exposure-baseline.sh");
386 let out = std::process::Command::new("bash").arg(script).output().expect("run bash");
387 assert!(
388 out.status.success(),
389 "{}{}",
390 String::from_utf8_lossy(&out.stdout),
391 String::from_utf8_lossy(&out.stderr)
392 );
393 }
394 #[test]
395 fn exposure_parsing() {
396 let n = 10_000;
397 let ok = format!(r#"{{"ts":{},"status":"ok"}}"#, n - 60);
398 let ch = format!(r#"{{"ts":{},"status":"changed"}}"#, n - 60);
399 let old = format!(r#"{{"ts":{},"status":"ok"}}"#, n - 4000);
400 assert_eq!(exposure_state(Some(&ok), n), "ok");
401 assert_eq!(exposure_state(Some(&ch), n), "changed");
402 assert_eq!(exposure_state(Some(&old), n), "unknown");
403 assert_eq!(exposure_state(None, n), "unknown");
404 assert_eq!(exposure_state(Some("junk"), n), "unknown");
405 assert_eq!(exposure_state(Some(r#"{"ts":9990,"status":"weird"}"#), n), "unknown");
406 }
407
408 #[test]
409 fn token_compare() {
410 assert!(ct_eq(b"abc", b"abc"));
411 assert!(!ct_eq(b"abc", b"abd"));
412 assert!(!ct_eq(b"abc", b"ab"));
413 assert!(auth_ok(Some("Bearer s3cret"), "s3cret"));
414 assert!(!auth_ok(Some("Bearer nope"), "s3cret"));
415 assert!(!auth_ok(Some("s3cret"), "s3cret"));
416 assert!(!auth_ok(None, "s3cret"));
417 }
418 #[test]
419 fn hours_clamp() {
420 assert_eq!(clamp_hours(None), 24);
421 assert_eq!(clamp_hours(Some("hours=5")), 5);
422 assert_eq!(clamp_hours(Some("hours=99999")), 720);
423 assert_eq!(clamp_hours(Some("hours=0")), 1);
424 assert_eq!(clamp_hours(Some("hours=abc")), 24);
425 }
426 #[test]
427 fn history_filter() {
428 let l = ["{\"ts\":100}", "{\"ts\":200}", "garbage", "{\"ts\":300}"];
429 assert_eq!(filter_since(l.into_iter(), 200), vec!["{\"ts\":200}", "{\"ts\":300}"]);
430 }
431 #[test]
432 fn validate_rejects_partial() {
433 assert!(validate("{\"ts\":1}").is_err());
434 assert!(validate("nope").is_err());
435 }
436 #[test]
437 fn status_validation() {
438 assert!(validate_status(r#"{"ts":5,"label":"x","detail":"d"}"#).is_ok());
439 assert!(validate_status(r#"{"ts":5,"label":"x"}"#).is_ok());
440 assert!(validate_status(r#"{"ts":"5","label":"x"}"#).is_err());
441 assert!(validate_status(r#"{"ts":5}"#).is_err());
442 assert!(validate_status(r#"{"ts":5,"label":"x","detail":1}"#).is_err());
443 assert!(validate_status("").is_err());
444 }
445 #[test]
446 fn results_validation() {
447 let ok = r#"{"updated":1,"results":[{"name":"a","verdict":"PASS","date":"2026-10-04","receipt":"r","note":"n"}]}"#;
448 assert!(validate_results(ok).is_ok());
449 assert!(validate_results(r#"{"updated":0,"results":[]}"#).is_ok());
450 assert!(validate_results(&ok.replace("PASS", "MAYBE")).is_err());
451 assert!(validate_results(r#"{"updated":1}"#).is_err());
452 assert!(validate_results(r#"{"updated":1,"results":[{"name":"a"}]}"#).is_err());
453 assert!(validate_results("[]").is_err());
454 }
455 #[test]
456 fn lines_clamp() {
457 assert_eq!(clamp_lines(None), 500);
458 assert_eq!(clamp_lines(Some("lines=0")), 1);
459 assert_eq!(clamp_lines(Some("lines=1")), 1);
460 assert_eq!(clamp_lines(Some("lines=500")), 500);
461 assert_eq!(clamp_lines(Some("lines=60000")), 50000);
462 assert_eq!(clamp_lines(Some("lines=abc")), 500);
463 assert_eq!(clamp_lines(Some("lines=1;rm -rf /")), 500);
464 assert_eq!(clamp_lines(Some("lines=-5")), 500);
465 }
466 const A: &str = "archive/agent-chats";
467 #[test]
468 fn spark_targets_parse() {
469 let c = "# comment\ntarget=u@a\n target= u@b \ntarget=\nother=x\n";
470 assert_eq!(spark_targets(c), vec!["u@a".to_string(), "u@b".to_string()]);
471 }
472 #[test]
473 fn spark_identity_parse() {
474 assert_eq!(spark_identity("# identity=ignored\ntarget=u@a\nother=x\n"), None);
475 assert_eq!(spark_identity("identity=\n identity= \n"), None);
476 assert_eq!(
477 spark_identity("identity=\n identity= /example/key with spaces \nidentity=/ignored\n"),
478 Some("/example/key with spaces")
479 );
480 }
481 #[test]
482 fn spark_ssh_argv() {
483 let remote = "cat archive/status.json";
484 let command = spark_ssh("u@example", remote, Some("/example/key with spaces"));
485 assert_eq!(command.get_program(), "ssh");
486 assert_eq!(command.get_args().collect::<Vec<_>>(), vec![
487 "-i", "/example/key with spaces", "-o", "BatchMode=yes",
488 "-o", "ConnectTimeout=5", "u@example", remote,
489 ]);
490 let command = spark_ssh("u@example", remote, None);
491 assert_eq!(command.get_args().collect::<Vec<_>>(), vec![
492 "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "u@example", remote,
493 ]);
494 }
495 #[test]
496 fn spark_ssh_local_stub_smoke() {
497 // printf is a local stub: no ssh process, network access or remote shell.
498 for identity in [None, Some("/example/key with spaces")] {
499 let command = spark_ssh("u@example", "cat archive/status.json", identity);
500 let output = Command::new("printf").arg("%s\\n")
501 .args(command.get_args()).output().unwrap();
502 assert!(output.status.success());
503 let expected = if identity.is_some() {
504 "-i\n/example/key with spaces\n-o\nBatchMode=yes\n-o\nConnectTimeout=5\nu@example\ncat archive/status.json\n"
505 } else {
506 "-o\nBatchMode=yes\n-o\nConnectTimeout=5\nu@example\ncat archive/status.json\n"
507 };
508 assert_eq!(String::from_utf8(output.stdout).unwrap(), expected);
509 }
510 }
511 fn route(p: &str) -> ChatFeed {
512 chat_route(p).unwrap()
513 }
514 #[test]
515 fn chat_commands_plain() {
516 let f = route("/v1/chat/codex");
517 let t = format!("{A}/latest/codex.txt");
518 assert_eq!(chat_command(&f, None), format!("tail -n 500 {t}"));
519 assert_eq!(chat_command(&f, Some("lines=60000")), format!("tail -n 50000 {t}"));
520 assert_eq!(chat_command(&f, Some("lines=7")), format!("tail -n 7 {t}"));
521 assert_eq!(chat_command(&f, Some("all=1")), format!("cat {t}"));
522 assert_eq!(chat_command(&f, Some("all=1;id")), format!("tail -n 500 {t}"));
523 }
524 #[test]
525 fn chat_commands_jsonl() {
526 let f = route("/v1/chat/opencode.jsonl");
527 assert_eq!(chat_command(&f, None), format!("tail -n 500 {A}/latest/opencode.jsonl"));
528 assert_eq!(chat_command(&f, Some("lines=7&all=1")), format!("cat {A}/records/opencode/*.jsonl"));
529 assert_eq!(chat_command(&f, Some("all=1")), format!("cat {A}/records/opencode/*.jsonl"));
530 }
531 #[test]
532 fn chat_allow_list() {
533 for a in ["claude", "codex", "opencode", "gemini", "muse"] {
534 assert_eq!(route(&format!("/v1/chat/{a}")).ctype, "text/plain; charset=utf-8");
535 assert_eq!(route(&format!("/v1/chat/{a}.jsonl")).ctype, "application/x-ndjson");
536 assert_eq!(route(&format!("/v1/chat/{a}")).latest, format!("{A}/latest/{a}.txt"));
537 }
538 for bad in ["/v1/chat/other", "/v1/chat/claude.txt", "/v1/chat/", "/v1/chat/claude/", "/v1/chat/Claude",
539 "/v1/chat/../claude", "/v1/chat/claude.jsonl.jsonl", "/v1/chat/.jsonl", "/v1/chat/claude;id"] {
540 assert_eq!(chat_route(bad), None, "{bad}");
541 }
542 let tok = "s3cret";
543 assert_eq!(handle("GET", "/v1/chat/other", Some("Bearer s3cret"), tok).0, 404);
544 assert_eq!(handle("GET", "/v1/chat/claude.txt", None, tok).0, 404);
545 }
546 #[test]
547 fn chat_auth_and_method() {
548 let tok = "s3cret";
549 let mut paths: Vec<String> = vec!["/v1/chat".into()];
550 for a in ["claude", "codex", "opencode", "gemini", "muse"] {
551 paths.push(format!("/v1/chat/{a}"));
552 paths.push(format!("/v1/chat/{a}.jsonl"));
553 }
554 for p in &paths {
555 assert_eq!(handle("GET", p, None, tok).0, 401, "{p}");
556 assert_eq!(handle("GET", &format!("{p}?lines=5"), Some("Bearer wrong"), tok).0, 401, "{p}");
557 assert_eq!(handle("POST", p, None, tok).0, 405, "{p}");
558 }
559 }
560 #[test]
561 fn chat_agent_list() {
562 let (code, body, ctype) = handle("GET", "/v1/chat", Some("Bearer s3cret"), "s3cret");
563 assert_eq!((code, ctype), (200, "application/json"));
564 assert_eq!(body, r#"{"agents":["claude","codex","opencode","gemini","muse"]}"#);
565 let v: Value = serde_json::from_str(&body).unwrap();
566 assert_eq!(v["agents"].as_array().unwrap().len(), AGENTS.len());
567 }
568 #[test]
569 fn feed_defaults() {
570 assert_eq!(feed_body("/nonexistent/x", validate_status, STATUS_DEFAULT), STATUS_DEFAULT);
571 assert_eq!(feed_body("/nonexistent/x", validate_results, RESULTS_DEFAULT), RESULTS_DEFAULT);
572 }
573}