zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Admin log access: list and tail this node's zc logs
//! (`<agent dir>/*.log` and `<agent dir>/workers/*.log`).
//!
//! A name is only ever resolved by looking it up in the listing, so a
//! traversal (`..`, an absolute path, another directory) can never reach a
//! file. A tail reads from the end of the file in chunks: memory stays
//! bounded however large the log is.

use chrono::SecondsFormat;
use serde::Serialize;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

pub const DEFAULT_TAIL: usize = 500;
pub const MAX_TAIL: usize = 5000;
const WORKERS_DIR: &str = "workers";
/// The most bytes one tail reads, so a log with huge lines stays bounded.
const MAX_SCAN: u64 = 8 * 1024 * 1024;
const CHUNK: u64 = 64 * 1024;
const REDACTED: &str = "…redacted";

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct LogFile {
    pub name: String,
    pub size: u64,
    pub modified: String,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Tail {
    pub name: String,
    pub lines: Vec<String>,
    pub truncated: bool,
    pub size: u64,
    pub modified: String,
}

pub fn clamp_tail(n: Option<usize>) -> usize {
    n.unwrap_or(DEFAULT_TAIL).clamp(1, MAX_TAIL)
}

fn modified_of(md: &std::fs::Metadata) -> String {
    md.modified()
        .map(|t| {
            chrono::DateTime::<chrono::Utc>::from(t).to_rfc3339_opts(SecondsFormat::Secs, true)
        })
        .unwrap_or_default()
}

/// Sort key: agent.log, broker*.log, other top-level logs, workers by number.
fn rank(name: &str) -> (u8, u64, String) {
    if name == "agent.log" {
        return (0, 0, String::new());
    }
    if let Some(w) = name.strip_prefix("workers/") {
        let num = w
            .strip_prefix('w')
            .and_then(|r| r.strip_suffix(".log"))
            .and_then(|r| r.parse::<u64>().ok());
        return match num {
            Some(n) => (3, n, String::new()),
            None => (4, 0, w.to_string()),
        };
    }
    if name.starts_with("broker") {
        return (1, 0, name.to_string());
    }
    (2, 0, name.to_string())
}

fn collect(dir: &Path, prefix: &str, out: &mut Vec<LogFile>) {
    let Ok(rd) = std::fs::read_dir(dir) else {
        return;
    };
    for e in rd.flatten() {
        let Ok(fname) = e.file_name().into_string() else {
            continue;
        };
        // symlink_metadata: a link out of the dir is not a log of ours.
        let Ok(md) = std::fs::symlink_metadata(e.path()) else {
            continue;
        };
        if !md.is_file() || !fname.ends_with(".log") {
            continue;
        }
        out.push(LogFile {
            name: format!("{prefix}{fname}"),
            size: md.len(),
            modified: modified_of(&md),
        });
    }
}

pub fn list(dir: &Path) -> Vec<LogFile> {
    let mut out = vec![];
    collect(dir, "", &mut out);
    collect(&dir.join(WORKERS_DIR), "workers/", &mut out);
    out.sort_by_key(|f| rank(&f.name));
    out
}

/// The last `n` lines of the listed log `name`; `None` when it is not listed.
pub fn tail(dir: &Path, name: &str, n: usize) -> Option<Tail> {
    let f = list(dir).into_iter().find(|f| f.name == name)?;
    let path: PathBuf = dir.join(&f.name);
    let (lines, truncated, size) = read_tail(&path, n).ok()?;
    Some(Tail {
        name: f.name,
        lines,
        truncated,
        size,
        modified: f.modified,
    })
}

fn read_tail(path: &Path, n: usize) -> std::io::Result<(Vec<String>, bool, u64)> {
    let mut file = std::fs::File::open(path)?;
    let size = file.metadata()?.len();
    let mut buf: Vec<u8> = vec![];
    let mut pos = size;
    let floor = size.saturating_sub(MAX_SCAN);
    // Lines wanted plus one, so the first is known to be complete (or the
    // start of the file).
    while pos > floor && count_newlines(&buf) <= n {
        let step = CHUNK.min(pos - floor);
        pos -= step;
        file.seek(SeekFrom::Start(pos))?;
        let mut chunk = vec![0u8; step as usize];
        file.read_exact(&mut chunk)?;
        chunk.extend_from_slice(&buf);
        buf = chunk;
    }
    let mut truncated = pos > 0;
    let mut text: &[u8] = &buf;
    if text.last() == Some(&b'\n') {
        text = &text[..text.len() - 1];
    }
    let mut parts: Vec<&[u8]> = text.split(|b| *b == b'\n').collect();
    if truncated && !parts.is_empty() {
        // The first part may be a line cut in the middle.
        parts.remove(0);
    }
    if size == 0 {
        parts.clear();
    }
    if parts.len() > n {
        parts.drain(..parts.len() - n);
        truncated = true;
    }
    let lines = parts
        .into_iter()
        .map(|l| {
            let s = String::from_utf8_lossy(l);
            redact(&strip_ansi(s.trim_end_matches('\r')))
        })
        .collect();
    Ok((lines, truncated, size))
}

fn count_newlines(b: &[u8]) -> usize {
    b.iter().filter(|c| **c == b'\n').count()
}

/// Remove ANSI escape sequences (CSI, OSC and two-byte escapes).
pub fn strip_ansi(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut it = s.chars().peekable();
    while let Some(c) = it.next() {
        if c != '\u{1b}' {
            out.push(c);
            continue;
        }
        match it.next() {
            Some('[') => {
                for x in it.by_ref() {
                    if ('\u{40}'..='\u{7e}').contains(&x) {
                        break;
                    }
                }
            }
            Some(']') => {
                while let Some(x) = it.next() {
                    if x == '\u{7}' {
                        break;
                    }
                    if x == '\u{1b}' {
                        it.next(); // ST: ESC \
                        break;
                    }
                }
            }
            _ => {}
        }
    }
    out
}

/// Names whose value is a secret, matched case-insensitively at a word start
/// and followed by `=` or `:` (optionally quoted, as in JSON).
const SECRET_KEYS: [&str; 11] = [
    "authorization",
    "client_secret",
    "refresh_token",
    "access_token",
    "password",
    "api_key",
    "api-key",
    "apikey",
    "passwd",
    "secret",
    "token",
];

/// Replace secrets with `…redacted`: `zk_<id>` keys, `Bearer <x>`, and the
/// value of any [`SECRET_KEYS`] name in `key=v`, `key: v` or `"key": "v"`
/// form (an `Authorization: Basic|Bearer <x>` value includes the scheme).
pub fn redact(line: &str) -> String {
    let mut out = String::with_capacity(line.len());
    let mut rest = line;
    let mut after_word = false;
    while !rest.is_empty() {
        match secret_len(rest, after_word) {
            Some(n) => {
                out.push_str(REDACTED);
                rest = &rest[n..];
                after_word = false;
            }
            None => {
                let c = rest.chars().next().unwrap();
                out.push(c);
                rest = &rest[c.len_utf8()..];
                after_word = c.is_alphanumeric() || c == '_' || c == '-';
            }
        }
    }
    out
}

fn starts_with_ci(s: &str, p: &str) -> bool {
    s.len() >= p.len() && s.as_bytes()[..p.len()].eq_ignore_ascii_case(p.as_bytes())
}

/// Byte length of a secret starting exactly at `s`, if there is one.
/// `after_word`: the previous character continues a word, so no name starts here.
fn secret_len(s: &str, after_word: bool) -> Option<usize> {
    let word = |t: &str| {
        t.bytes()
            .take_while(|b| b.is_ascii_alphanumeric() || *b == b'_')
            .count()
    };
    // A value ends at whitespace, a quote, a comma or a closing brace.
    let value = |t: &str| {
        t.find(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | ',' | '}'))
            .unwrap_or(t.len())
    };
    let spaces = |t: &str| t.len() - t.trim_start_matches([' ', '\t']).len();
    if after_word {
        return None;
    }
    if starts_with_ci(s, "zk_") {
        let w = word(&s[3..]);
        return (w > 0).then_some(3 + w);
    }
    if starts_with_ci(s, "bearer ") {
        let w = value(&s[7..]);
        return (w > 0).then_some(7 + w);
    }
    let key = SECRET_KEYS.iter().find(|k| starts_with_ci(s, k))?;
    let mut i = key.len();
    // The name must end here (`tokens=` is not `token=`).
    if s[i..].starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '-') {
        return None;
    }
    i += usize::from(s[i..].starts_with('"'));
    i += spaces(&s[i..]);
    let colon = s[i..].starts_with(':');
    if !colon && !s[i..].starts_with('=') {
        return None;
    }
    i += 1;
    // `key: value` puts a space after the colon; `key= value` is not a pair.
    if colon {
        i += spaces(&s[i..]);
    }
    i += usize::from(s[i..].starts_with('"'));
    for scheme in ["bearer ", "basic "] {
        if starts_with_ci(&s[i..], scheme) {
            i += scheme.len();
        }
    }
    let w = value(&s[i..]);
    (w > 0).then_some(i + w)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn dir(tag: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("zc-logs-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(d.join("workers")).unwrap();
        d
    }

    #[test]
    fn list_orders_agent_broker_then_workers_by_number() {
        let d = dir("order");
        for f in [
            "workers/w10.log",
            "workers/w2.log",
            "broker.log",
            "agent.log",
            "zzz.log",
            "notes.txt",
            "workers/x.txt",
        ] {
            std::fs::write(d.join(f), "x\n").unwrap();
        }
        let names: Vec<_> = list(&d).into_iter().map(|f| f.name).collect();
        assert_eq!(
            names,
            [
                "agent.log",
                "broker.log",
                "zzz.log",
                "workers/w2.log",
                "workers/w10.log"
            ]
        );
    }

    #[test]
    fn tail_returns_last_n_and_flags_truncation() {
        let d = dir("tail");
        let body: String = (1..=10).map(|i| format!("line {i}\n")).collect();
        std::fs::write(d.join("agent.log"), body).unwrap();
        let t = tail(&d, "agent.log", 3).unwrap();
        assert_eq!(t.lines, ["line 8", "line 9", "line 10"]);
        assert!(t.truncated);
        let t = tail(&d, "agent.log", 50).unwrap();
        assert_eq!(t.lines.len(), 10);
        assert!(!t.truncated);
        assert_eq!(t.lines[0], "line 1");
        assert_eq!(t.size, 71);
    }

    #[test]
    fn tail_of_a_big_file_reads_only_the_end() {
        let d = dir("big");
        let body: String = (0..200_000).map(|i| format!("row {i}\n")).collect();
        std::fs::write(d.join("agent.log"), &body).unwrap();
        let t = tail(&d, "agent.log", 2).unwrap();
        assert_eq!(t.lines, ["row 199998", "row 199999"]);
        assert!(t.truncated);
    }

    #[test]
    fn empty_file_and_no_trailing_newline() {
        let d = dir("edge");
        std::fs::write(d.join("agent.log"), "").unwrap();
        std::fs::write(d.join("broker.log"), "a\nb").unwrap();
        let t = tail(&d, "agent.log", 5).unwrap();
        assert!(t.lines.is_empty() && !t.truncated);
        assert_eq!(tail(&d, "broker.log", 5).unwrap().lines, ["a", "b"]);
    }

    #[test]
    fn clamp() {
        assert_eq!(clamp_tail(None), 500);
        assert_eq!(clamp_tail(Some(0)), 1);
        assert_eq!(clamp_tail(Some(99_999)), 5000);
    }

    #[test]
    fn unlisted_names_are_not_found() {
        let d = dir("trav");
        std::fs::write(d.join("agent.log"), "x\n").unwrap();
        std::fs::write(d.join("credentials"), "api_key=zk_1\n").unwrap();
        for n in [
            "../credentials",
            "/etc/passwd",
            "workers/../../x",
            "..",
            "credentials",
            "workers/../agent.log",
            "",
        ] {
            assert!(tail(&d, n, 5).is_none(), "{n}");
        }
    }

    #[test]
    fn redacts_secrets() {
        assert_eq!(
            redact("key zk_12_abcDEF9 and Bearer abc.def token=xyz&x api_key=Q end"),
            "key …redacted and …redacted …redacted …redacted end"
        );
        assert_eq!(redact("zk_ alone, a token= b"), "zk_ alone, a token= b");
        assert_eq!(redact("héllo zk_a"), "héllo …redacted");
    }

    #[test]
    fn redacts_any_case_and_the_key_value_and_json_forms() {
        for (line, want) in [
            ("bearer abc.def", "…redacted"),
            ("Authorization: Basic dXNlcjpwYXNz", "…redacted"),
            ("authorization: Bearer abc", "…redacted"),
            ("token: x1", "…redacted"),
            (r#"{"token":"x1","n":2}"#, r#"{"…redacted","n":2}"#),
            (r#"{"Password": "p w"}"#, r#"{"…redacted w"}"#),
            ("password=hunter2 next", "…redacted next"),
            ("SECRET=s3", "…redacted"),
            ("api-key: k", "…redacted"),
            ("client_secret=c refresh_token=r", "…redacted …redacted"),
        ] {
            assert_eq!(redact(line), want, "{line}");
        }
        // Names inside other words, and names without a value, stay.
        for line in [
            "tokens=3",
            "mytoken=3",
            "the password is set",
            "secretary: x",
        ] {
            assert_eq!(redact(line), line);
        }
    }

    #[test]
    fn strips_ansi() {
        assert_eq!(
            strip_ansi("\u{1b}[31mERROR\u{1b}[0m x \u{1b}]0;title\u{7}y"),
            "ERROR x y"
        );
    }
}