1use std::io::{Read, Seek, SeekFrom};
9use std::path::{Path, PathBuf};
10
11use serde_json::{json, Value};
12
13use super::{AppState, RemoteCaller, RemoteRefusal, RemoteResult};
14
15const DEFAULT_LINES: usize = 200;
16const MAX_LINES: usize = 1000;
17const READ_BYTES: u64 = 1024 * 1024;
19const FILTERED_READ_BYTES: u64 = 4 * 1024 * 1024;
22const MAX_CONTAINS: usize = 200;
24const MAX_TEXT_BYTES: usize = 256 * 1024;
26
27fn prefix_of(which: &str) -> Option<&'static str> {
29 match which {
30 "srv" => Some("agentmuxsrv-"),
31 "host" => Some("agentmux-host-"),
32 _ => None,
33 }
34}
35
36fn newest_log(dir: &Path, prefix: &str) -> Option<(PathBuf, std::time::SystemTime)> {
38 std::fs::read_dir(dir)
39 .ok()?
40 .filter_map(Result::ok)
41 .filter(|e| e.file_name().to_string_lossy().starts_with(prefix))
42 .filter_map(|e| Some((e.path(), e.metadata().ok()?.modified().ok()?)))
43 .max_by_key(|(_, modified)| *modified)
44}
45
46const KEY_BEGIN: &str = concat!("-----", "BEGIN ");
48const KEY_END: &str = concat!("-----", "END ");
49
50fn without_open_key(text: &str) -> &str {
54 let Some(end) = text.find(KEY_END) else { return text };
55 if text.find(KEY_BEGIN).is_some_and(|begin| begin < end) {
56 return text;
57 }
58 text[end..].find('\n').map_or("", |nl| &text[end + nl + 1..])
59}
60
61fn window_lines(bytes: &[u8], from_middle: bool) -> Vec<String> {
65 let text = String::from_utf8_lossy(bytes);
66 let text = if from_middle { without_open_key(&text) } else { &text };
67 let masked = agentmux_common::pii_mask::mask_short_text(text);
68 let mut lines: Vec<&str> = masked.lines().collect();
69 if from_middle && !lines.is_empty() {
70 lines.remove(0);
71 }
72 lines.into_iter().map(str::to_string).collect()
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
77enum Level {
78 Trace,
79 Debug,
80 Info,
81 Warn,
82 Error,
83}
84
85fn parse_level(name: &str) -> Option<Level> {
87 match name.trim().to_ascii_lowercase().as_str() {
88 "debug" => Some(Level::Debug),
89 "info" => Some(Level::Info),
90 "warn" => Some(Level::Warn),
91 "error" => Some(Level::Error),
92 _ => None,
93 }
94}
95
96fn level_of(line: &str) -> Option<Level> {
99 const KEY: &[u8] = b"\"level\":\"";
100 let bytes = line.as_bytes();
102 let head = &bytes[..bytes.len().min(160)];
103 let from = head.windows(KEY.len()).position(|w| w == KEY)? + KEY.len();
104 let name: Vec<u8> = head[from..].iter().copied().take_while(|b| *b != b'"').collect();
105 match String::from_utf8_lossy(&name).to_ascii_uppercase().as_str() {
106 "TRACE" => Some(Level::Trace),
107 "DEBUG" => Some(Level::Debug),
108 "INFO" => Some(Level::Info),
109 "WARN" => Some(Level::Warn),
110 "ERROR" => Some(Level::Error),
111 _ => None,
112 }
113}
114
115#[derive(Debug, Default)]
117struct Filter {
118 min_level: Option<Level>,
119 contains: Option<String>,
121}
122
123impl Filter {
124 fn is_empty(&self) -> bool {
125 self.min_level.is_none() && self.contains.is_none()
126 }
127
128 fn keeps(&self, line: &str) -> bool {
130 if let Some(min) = self.min_level {
131 if !level_of(line).is_some_and(|l| l >= min) {
132 return false;
133 }
134 }
135 match &self.contains {
136 Some(text) => line.to_lowercase().contains(text.as_str()),
137 None => true,
138 }
139 }
140
141 fn from_params(params: &Value) -> Result<Self, RemoteRefusal> {
142 let min_level = match params.get("level").and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
143 None => None,
144 Some(name) => Some(
145 parse_level(name).ok_or_else(|| RemoteRefusal::failed(format!("level is \"debug\", \"info\", \"warn\" or \"error\", not {name:?}")))?,
146 ),
147 };
148 let contains = match params.get("contains").and_then(Value::as_str) {
149 None => None,
150 Some(text) if text.is_empty() => None,
151 Some(text) if text.chars().count() > MAX_CONTAINS => {
152 return Err(RemoteRefusal::failed(format!("contains is at most {MAX_CONTAINS} characters")))
153 }
154 Some(text) => Some(text.to_lowercase()),
155 };
156 Ok(Self { min_level, contains })
157 }
158}
159
160fn pick(lines: Vec<String>, filter: &Filter, n: usize) -> (Vec<String>, usize) {
163 let kept: Vec<String> = if filter.is_empty() { lines } else { lines.into_iter().filter(|l| filter.keeps(l)).collect() };
164 let matched = kept.len();
165 let start = matched.saturating_sub(n);
166 (kept[start..].to_vec(), matched)
167}
168
169fn fit(lines: Vec<String>, max: usize) -> (Vec<String>, bool) {
171 let mut total = 0usize;
172 let mut keep = 0usize;
173 for line in lines.iter().rev() {
174 total += line.len() + 1;
175 if total > max {
176 break;
177 }
178 keep += 1;
179 }
180 let skipped = lines.len() - keep;
181 (lines[skipped..].to_vec(), skipped > 0)
182}
183
184fn read_tail(path: &Path, window: u64) -> std::io::Result<(Vec<u8>, bool)> {
186 let mut file = std::fs::File::open(path)?;
187 let len = file.metadata()?.len();
188 let from_middle = len > window;
189 file.seek(SeekFrom::Start(len.saturating_sub(window)))?;
190 let mut buf = Vec::new();
191 file.take(window).read_to_end(&mut buf)?;
192 Ok((buf, from_middle))
193}
194
195pub(super) async fn logs_tail(_state: &AppState, _caller: &RemoteCaller, params: Value) -> RemoteResult {
196 tail(¶ms)
197}
198
199pub(crate) fn tail(params: &Value) -> RemoteResult {
203 let which = params.get("which").and_then(Value::as_str).unwrap_or("srv");
204 let prefix = prefix_of(which).ok_or_else(|| RemoteRefusal::failed(format!("which is \"srv\" or \"host\", not {which:?}")))?;
205 let wanted = params.get("lines").and_then(Value::as_u64).map(|n| n as usize).unwrap_or(DEFAULT_LINES).clamp(1, MAX_LINES);
206 let filter = Filter::from_params(params)?;
207 let dir = agentmux_common::data_paths::DataPaths::from_env()
208 .map(|p| p.logs_dir)
209 .ok_or_else(|| RemoteRefusal::failed("this AgentMux has no log folder"))?;
210 let Some((path, modified)) = newest_log(&dir, prefix) else {
211 return Err(RemoteRefusal::failed(format!("no {which} log file yet")));
212 };
213 let window = if filter.is_empty() { READ_BYTES } else { FILTERED_READ_BYTES };
214 let (bytes, from_middle) = read_tail(&path, window).map_err(|e| RemoteRefusal::failed(format!("reading the {which} log: {e}")))?;
215 let searched = window_lines(&bytes, from_middle);
216 let searched_count = searched.len();
217 let (picked, matched) = pick(searched, &filter, wanted);
218 let (lines, cut) = fit(picked, MAX_TEXT_BYTES);
219 let modified_ms = modified.duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
220 Ok(json!({
221 "which": which,
222 "lines": lines.len(),
223 "matched": matched,
224 "searched": searched_count,
225 "searched_bytes": bytes.len(),
226 "whole_file": !from_middle,
228 "modified_ms": modified_ms,
229 "shortened": cut,
230 "text": lines.join("\n"),
231 }))
232}
233
234pub(crate) async fn handle_local_logs(
237 axum::extract::Query(query): axum::extract::Query<std::collections::HashMap<String, String>>,
238) -> axum::response::Response {
239 use axum::response::IntoResponse;
240 let mut params = json!({ "which": query.get("log").cloned().unwrap_or_else(|| "srv".to_string()) });
241 if let Some(n) = query.get("lines").and_then(|v| v.parse::<u64>().ok()) {
242 params["lines"] = json!(n);
243 }
244 for key in ["level", "contains"] {
245 if let Some(v) = query.get(key) {
246 params[key] = json!(v);
247 }
248 }
249 match tokio::task::spawn_blocking(move || tail(¶ms)).await {
250 Ok(Ok(answer)) => axum::Json(answer).into_response(),
251 Ok(Err(refusal)) => (axum::http::StatusCode::BAD_REQUEST, axum::Json(json!({ "error": refusal.message }))).into_response(),
252 Err(e) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(json!({ "error": format!("reading the log: {e}") }))).into_response(),
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 fn last_lines(bytes: &[u8], n: usize, from_middle: bool) -> Vec<String> {
262 pick(window_lines(bytes, from_middle), &Filter::default(), n).0
263 }
264
265 fn line(level: &str, message: &str) -> String {
266 format!(r#"{{"timestamp":"2026-11-12T11:00:00Z","level":"{level}","fields":{{"message":"{message}"}},"target":"t"}}"#)
267 }
268
269 fn picked(lines: &[String], level: Option<&str>, contains: Option<&str>, n: usize) -> (Vec<String>, usize) {
270 let mut params = json!({});
271 if let Some(l) = level {
272 params["level"] = json!(l);
273 }
274 if let Some(c) = contains {
275 params["contains"] = json!(c);
276 }
277 pick(lines.to_vec(), &Filter::from_params(¶ms).unwrap(), n)
278 }
279
280 #[test]
281 fn the_filter_comes_before_the_cut() {
282 let mut lines = Vec::new();
284 for i in 0..12 {
285 lines.push(line("WARN", &format!("store update {i}")));
286 for _ in 0..12 {
287 lines.push(line("INFO", "[fe] [service] window.ListClosedWindows | 3ms"));
288 }
289 }
290 let (last_ten, matched) = picked(&lines, None, None, 10);
291 assert_eq!((last_ten.len(), matched), (10, 156));
292 assert!(!last_ten.iter().any(|l| l.contains("store update")), "the plain tail is all noise");
293
294 let (warnings, matched) = picked(&lines, Some("warn"), Some("STORE"), 3);
295 assert_eq!(matched, 12, "all twelve passed the filter");
296 assert_eq!(warnings.len(), 3, "and the cut kept the last three of them");
297 assert!(warnings[0].contains("store update 9") && warnings[2].contains("store update 11"), "{warnings:?}");
298 }
299
300 #[test]
301 fn a_minimum_level_keeps_that_level_and_above_and_drops_lines_with_none() {
302 let lines = vec![
303 line("DEBUG", "d"),
304 line("INFO", "i"),
305 line("WARN", "w"),
306 line("ERROR", "e"),
307 "a wrapped continuation with no level".to_string(),
308 ];
309 let levels = |min: &str| picked(&lines, Some(min), None, 10).0.iter().map(|l| level_of(l)).collect::<Vec<_>>();
310 assert_eq!(levels("error"), [Some(Level::Error)]);
311 assert_eq!(levels("warn"), [Some(Level::Warn), Some(Level::Error)]);
312 assert_eq!(levels("info"), [Some(Level::Info), Some(Level::Warn), Some(Level::Error)]);
313 assert_eq!(picked(&lines, Some("debug"), None, 10).1, 4, "a line with no level is not a debug line");
314 assert_eq!(picked(&lines, None, None, 10).1, 5, "with no level asked for, it stays");
315 }
316
317 #[test]
318 fn a_long_line_with_non_ascii_text_still_has_its_level() {
319 let message = format!("{}é{}", "x".repeat(87), "y".repeat(40));
321 let text = line("WARN", &message);
322 assert!(!text.is_char_boundary(160), "the test line must have a character straddling byte 160");
323 assert_eq!(level_of(&text), Some(Level::Warn));
324 assert_eq!(picked(&[text], Some("warn"), None, 10).1, 1);
325 }
326
327 #[test]
328 fn the_text_match_ignores_case_and_both_filters_must_hold() {
329 let lines = vec![line("WARN", "Store update failed"), line("INFO", "store update ok"), line("WARN", "network down")];
330 assert_eq!(picked(&lines, None, Some("STORE UPDATE"), 10).1, 2);
331 assert_eq!(picked(&lines, Some("warn"), Some("store"), 10).1, 1, "level and text together");
332 assert_eq!(picked(&lines, Some("error"), Some("store"), 10).1, 0);
333 }
334
335 #[test]
336 fn a_secret_is_masked_before_the_match_so_it_cannot_be_probed() {
337 let token = format!("ghp_{}", "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8");
338 let lines = window_lines(format!("{}\n", line("INFO", &format!("auth {token} sent"))).as_bytes(), false);
339 assert_eq!(picked(&lines, None, Some("ghp_a1B2"), 10).1, 0, "the token is gone from the line the match sees");
340 assert_eq!(picked(&lines, None, Some("auth"), 10).1, 1);
341 }
342
343 #[test]
344 fn a_bad_level_or_too_long_a_text_is_refused_and_empty_ones_are_no_filter() {
345 assert!(Filter::from_params(&json!({ "level": "loud" })).is_err());
346 assert!(Filter::from_params(&json!({ "contains": "x".repeat(MAX_CONTAINS + 1) })).is_err());
347 assert!(Filter::from_params(&json!({ "level": "", "contains": "" })).unwrap().is_empty());
348 assert!(Filter::from_params(&json!({})).unwrap().is_empty());
349 assert_eq!(parse_level(" Warn "), Some(Level::Warn));
350 }
351
352 #[test]
353 fn only_the_last_lines_come_back_and_a_cut_first_line_is_dropped() {
354 let bytes = b"cut off\none\ntwo\nthree\n";
355 assert_eq!(last_lines(bytes, 2, true), ["two", "three"]);
356 assert_eq!(last_lines(bytes, 10, true), ["one", "two", "three"]);
357 assert_eq!(last_lines(bytes, 10, false), ["cut off", "one", "two", "three"]);
358 }
359
360 #[test]
361 fn a_token_in_a_line_is_hidden() {
362 let line = format!("auth ghp_{} sent", "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8");
363 let out = last_lines(line.as_bytes(), 1, false);
364 assert!(!out[0].contains("ghp_a1B2"), "{}", out[0]);
365 assert!(out[0].starts_with("auth ") && out[0].ends_with(" sent"), "{}", out[0]);
366 }
367
368 #[test]
369 fn a_private_key_spread_over_lines_is_hidden_whole() {
370 let (begin, end) = (format!("-----{} PRIVATE KEY-----", "BEGIN"), format!("-----{} PRIVATE KEY-----", "END"));
372 let log = format!("before
373{begin}
374MIIEvQIBADANBgkqhkiG9w0BAQEFAASC
375abcdEFGHijklMNOPqrstUVWXyz012345
376{end}
377after
378");
379 let out = last_lines(log.as_bytes(), 10, false).join("
380");
381 assert!(!out.contains("MIIEvQIBADAN") && !out.contains("abcdEFGH"), "{out}");
382 assert!(out.starts_with("before") && out.ends_with("after"), "{out}");
383 }
384
385 #[test]
386 fn a_key_that_began_before_the_window_is_cut_off_at_its_end() {
387 let end = format!("{KEY_END}PRIVATE KEY-----");
388 let log = format!("MIIEvQIBADANBgkqhkiG9w0BAQEFAASC
389abcdEFGHijklMNOPqrstUVWXyz012345
390{end}
391kept one
392kept two
393");
394 let out = last_lines(log.as_bytes(), 10, true).join("
396");
397 assert!(!out.contains("MIIEvQIBADAN") && !out.contains("abcdEFGH"), "{out}");
398 assert_eq!(out, "kept two", "the first line after the cut is dropped as a fragment too: {out}");
399 let whole = format!("{KEY_BEGIN}PRIVATE KEY-----
401body
402{end}
403after");
404 assert_eq!(without_open_key(&whole), whole);
405 }
406
407 #[test]
408 fn too_much_text_drops_the_oldest_lines() {
409 let lines: Vec<String> = ["aaaa", "bbbb", "cccc"].iter().map(|s| s.to_string()).collect();
410 assert_eq!(fit(lines.clone(), 100), (lines.clone(), false));
411 assert_eq!(fit(lines, 10), (vec!["bbbb".to_string(), "cccc".to_string()], true));
412 }
413
414 #[test]
415 fn the_newest_file_with_the_prefix_wins() {
416 let dir = tempfile::tempdir().unwrap();
417 std::fs::write(dir.path().join("agentmuxsrv-v1.log.2026-10-29"), "old").unwrap();
418 std::thread::sleep(std::time::Duration::from_millis(20));
419 std::fs::write(dir.path().join("agentmuxsrv-v1.log.2026-10-30"), "new").unwrap();
420 std::fs::write(dir.path().join("agentmux-host-v1.log.2026-10-30"), "host").unwrap();
421 let (path, _) = newest_log(dir.path(), "agentmuxsrv-").unwrap();
422 assert!(path.ends_with("agentmuxsrv-v1.log.2026-10-30"));
423 assert!(newest_log(dir.path(), "nothing-").is_none());
424 }
425
426 #[test]
427 fn an_unknown_log_is_refused_not_guessed() {
428 assert!(prefix_of("srv").is_some() && prefix_of("host").is_some() && prefix_of("cef").is_none());
429 }
430}