lonca-daemon 0.2.2

The Lonca daemon: the single writer every operation goes through (decide, sign, log, apply)
Documentation
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
//! Security events outside the operation log (issue #56).
//!
//! The operation log records every decided operation, denials included.
//! Much of what an attacker tries never reaches a decision: a refused peer, a
//! bad token, an oversized or malformed request, a request over its rate, a
//! hook refusal, an error while reconciling refs. Those land here, as one JSON
//! object per line in `<home>/security.log` (mode 0600), together with the
//! events a human should hear of at once: freezes and integrity alarms.
//!
//! An event carries what happened and to whom, never a token, a request body
//! or file contents: its fields are fixed, its free text is short, has no
//! control characters, and anything shaped like a Lonca token is masked. The
//! daemon writes events around decisions, never inside `decide()`.

use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::Duration;

use serde::{Deserialize, Serialize};

/// Past this size the log moves to `security.log.1` (replacing the one
/// there) and a new one starts: at most twice this much is kept.
pub const ROTATE_BYTES: u64 = 8 << 20;

/// The longest free text of an event, in characters.
const MAX_DETAIL: usize = 300;

/// How long a notification command may run.
const NOTIFY_TIMEOUT: Duration = Duration::from_secs(10);

/// What kind of thing happened. The names are the `kind` field.
pub mod kind {
    /// A connection from a uid the socket does not serve.
    pub const REFUSED_PEER: &str = "refused_peer";
    /// `unauthenticated` or `forbidden`.
    pub const AUTH_FAILURE: &str = "auth_failure";
    /// A line past its method's limit.
    pub const OVERSIZED: &str = "oversized_request";
    /// A line that is not a request.
    pub const MALFORMED: &str = "malformed_request";
    pub const RATE_LIMITED: &str = "rate_limited";
    /// An isolated session's token used outside its sandbox.
    pub const OUTSIDE_SANDBOX: &str = "outside_sandbox";
    /// A harness hook refused a tool call.
    pub const HOOK_DENIED: &str = "hook_denied";
    /// `reconcile()` failed for a repository.
    pub const RECONCILE_ERROR: &str = "reconcile_error";
    /// A ref changed behind the daemon's back (`import.unmediated`).
    pub const UNMEDIATED: &str = "unmediated_import";
    /// A repository froze.
    pub const FREEZE: &str = "freeze";
    /// The auditor asked for a freeze (`--freeze-flag`).
    pub const INTEGRITY_ALARM: &str = "integrity_alarm";
    /// A session was tainted by the daemon.
    pub const TAINT: &str = "taint";
    /// A bind whose hook reports sudo without a password.
    pub const SUDO_WITHOUT_PASSWORD: &str = "sudo_without_password";
    /// A session got a new token (`session.rotate`).
    pub const TOKEN_ROTATED: &str = "token_rotated";
    /// A call to `lonca mcp` came with no before-tool event: the session's
    /// hooks are not running (#190).
    pub const UNHOOKED: &str = "unhooked";

    /// Every kind, for `docs/decisions.md` and the tests.
    pub const ALL: [&str; 15] = [
        REFUSED_PEER,
        AUTH_FAILURE,
        OVERSIZED,
        MALFORMED,
        RATE_LIMITED,
        OUTSIDE_SANDBOX,
        HOOK_DENIED,
        RECONCILE_ERROR,
        UNMEDIATED,
        FREEZE,
        INTEGRITY_ALARM,
        TAINT,
        SUDO_WITHOUT_PASSWORD,
        TOKEN_ROTATED,
        UNHOOKED,
    ];

    /// The kinds a human is told of as they happen.
    pub fn alarming(k: &str) -> bool {
        matches!(k, FREEZE | INTEGRITY_ALARM)
    }
}

/// One security event.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Event {
    pub time_ms: i64,
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repo: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    /// The uid of the peer, where the socket told it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uid: Option<u32>,
    /// The error code answered, where there was one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
    /// Short words on what happened: never a request, a token or content.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub detail: String,
}

impl Event {
    pub fn new(time_ms: i64, kind: &str) -> Self {
        Self {
            time_ms,
            kind: kind.into(),
            ..Self::default()
        }
    }

    pub fn repo(mut self, repo: &str) -> Self {
        self.repo = Some(clean(repo, 64));
        self
    }

    pub fn session(mut self, session: &str) -> Self {
        self.session = Some(clean(session, 64));
        self
    }

    pub fn method(mut self, method: &str) -> Self {
        self.method = Some(clean(method, 64));
        self
    }

    pub fn uid(mut self, uid: Option<u32>) -> Self {
        self.uid = uid;
        self
    }

    pub fn code(mut self, code: &str) -> Self {
        self.code = Some(clean(code, 64));
        self
    }

    pub fn detail(mut self, detail: &str) -> Self {
        self.detail = clean(detail, MAX_DETAIL);
        self
    }
}

/// Text fit for an event: no control characters, at most `max`
/// characters, and every `lonca_…` token masked, in case a message ever
/// quotes one.
pub fn clean(text: &str, max: usize) -> String {
    let kept: String = text
        .chars()
        .map(|c| if c.is_control() { ' ' } else { c })
        .take(max)
        .collect();
    mask_tokens(&kept)
}

fn mask_tokens(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(at) = rest.find("lonca_") {
        out.push_str(&rest[..at]);
        let tail = &rest[at + "lonca_".len()..];
        let tail = tail.strip_prefix("h_").unwrap_or(tail);
        let hex = tail.bytes().take_while(u8::is_ascii_hexdigit).count();
        if hex >= 16 {
            out.push_str("lonca_[token]");
            rest = &tail[hex..];
        } else {
            out.push_str("lonca_");
            rest = &rest[at + "lonca_".len()..];
        }
    }
    out.push_str(rest);
    out
}

/// What happens when a human must hear of an event at once.
#[derive(Clone, Debug)]
pub enum Notify {
    /// Nothing: the event is in the log and `lonca status` shows a freeze.
    Off,
    /// The desktop's notification (macOS `osascript`, Linux `notify-send`),
    /// where there is one.
    Desktop,
    /// This program, given the event as one JSON line on its stdin (a
    /// webhook, a pager: outside the core).
    Command(PathBuf),
}

/// The security log of one daemon.
pub struct SecurityLog {
    path: PathBuf,
    rotate_bytes: u64,
    notify: Notify,
    write: Mutex<()>,
}

impl SecurityLog {
    pub fn new(home: &Path, notify: Notify) -> Self {
        Self {
            path: home.join("security.log"),
            rotate_bytes: ROTATE_BYTES,
            notify,
            write: Mutex::new(()),
        }
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Records `event`. Failing to write is said on stderr, the daemon's only
    /// other voice; it never stops the request that caused it.
    pub fn record(&self, event: Event) {
        let alarming = kind::alarming(&event.kind);
        if let Err(e) = self.append(&event) {
            eprintln!("lonca: security log {}: {e}", self.path.display());
        }
        if alarming {
            self.tell(&event);
        }
    }

    fn append(&self, event: &Event) -> std::io::Result<()> {
        let _held = self.write.lock().unwrap_or_else(|e| e.into_inner());
        if fs::metadata(&self.path).is_ok_and(|m| m.len() >= self.rotate_bytes) {
            fs::rename(&self.path, self.path.with_extension("log.1"))?;
        }
        let mut opts = fs::OpenOptions::new();
        opts.create(true).append(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        let mut f = opts.open(&self.path)?;
        let mut line = serde_json::to_vec(event).map_err(std::io::Error::other)?;
        line.push(b'\n');
        f.write_all(&line)
    }

    /// The events at `since_ms` or later, oldest first, from both files.
    pub fn read_since(&self, since_ms: i64) -> Vec<Event> {
        let _held = self.write.lock().unwrap_or_else(|e| e.into_inner());
        let mut out = Vec::new();
        for p in [self.path.with_extension("log.1"), self.path.clone()] {
            let Ok(text) = fs::read_to_string(&p) else {
                continue;
            };
            let events = text
                .lines()
                .filter_map(|l| serde_json::from_str::<Event>(l).ok());
            out.extend(events.filter(|e| e.time_ms >= since_ms));
        }
        out
    }

    /// Tells a human, without waiting for it: a notification is best effort
    /// and runs on a thread of its own, killed after a few seconds.
    fn tell(&self, event: &Event) {
        let message = format!(
            "{}{}: {}",
            event.kind,
            event
                .repo
                .as_ref()
                .map(|r| format!(" in {r}"))
                .unwrap_or_default(),
            event.detail
        );
        let line = serde_json::to_string(event).unwrap_or_default();
        let notify = self.notify.clone();
        std::thread::spawn(move || {
            let child = match notify {
                Notify::Off => return,
                Notify::Desktop => desktop(&message),
                Notify::Command(p) => command(&p, &line),
            };
            if let Some(mut child) = child {
                let started = std::time::Instant::now();
                while started.elapsed() < NOTIFY_TIMEOUT {
                    if child.try_wait().ok().flatten().is_some() {
                        return;
                    }
                    std::thread::sleep(Duration::from_millis(50));
                }
                let _ = child.kill();
                let _ = child.wait();
            }
        });
    }
}

fn desktop(message: &str) -> Option<std::process::Child> {
    use std::process::{Command, Stdio};
    let mut cmd = if cfg!(target_os = "macos") {
        let mut c = Command::new("/usr/bin/osascript");
        // The text goes in as an argument, never into the script.
        c.args([
            "-e",
            "on run argv",
            "-e",
            "display notification (item 1 of argv) with title \"Lonca\"",
            "-e",
            "end run",
            message,
        ]);
        c
    } else {
        let mut c = Command::new("notify-send");
        c.args(["--app-name=Lonca", "Lonca", message]);
        c
    };
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    cmd.spawn().ok()
}

fn command(program: &Path, line: &str) -> Option<std::process::Child> {
    use std::process::{Command, Stdio};
    let mut child = Command::new(program)
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;
    if let Some(mut stdin) = child.stdin.take() {
        let _ = writeln!(stdin, "{line}");
    }
    Some(child)
}

/// Counts of `events` by kind.
pub fn summary(events: &[Event]) -> std::collections::BTreeMap<String, usize> {
    let mut out = std::collections::BTreeMap::new();
    for e in events {
        *out.entry(e.kind.clone()).or_insert(0) += 1;
    }
    out
}

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

    #[test]
    fn free_text_holds_no_token_and_no_control() {
        let token = format!("lonca_{}", "ab".repeat(32));
        let human = format!("lonca_h_{}", "cd".repeat(32));
        let said = clean(&format!("a {token} b {human}\x1b[2J\nc lonca_x"), 300);
        assert_eq!(said, "a lonca_[token] b lonca_[token] [2J c lonca_x");
        assert_eq!(clean("abcdef", 3), "abc");
    }

    #[test]
    fn events_go_to_a_private_file_that_rotates() {
        let dir = tempfile::tempdir().unwrap();
        let mut log = SecurityLog::new(dir.path(), Notify::Off);
        log.rotate_bytes = 200;
        for i in 0..10 {
            log.record(
                Event::new(i, kind::AUTH_FAILURE)
                    .method("status")
                    .code("unauthenticated"),
            );
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = fs::metadata(log.path()).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600);
        }
        assert!(dir.path().join("security.log.1").exists());
        let all = log.read_since(0);
        assert!(!all.is_empty() && all.len() <= 10);
        assert!(
            all.windows(2).all(|w| w[0].time_ms < w[1].time_ms),
            "oldest first"
        );
        assert_eq!(log.read_since(9).len(), 1);
        assert_eq!(summary(&all)[kind::AUTH_FAILURE], all.len());
    }

    #[test]
    fn an_alarm_runs_the_notify_command_with_the_event() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("told");
        let script = dir.path().join("notify.sh");
        fs::write(&script, format!("#!/bin/sh\ncat > {}\n", out.display())).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        }
        let log = SecurityLog::new(dir.path(), Notify::Command(script));
        log.record(Event::new(1, kind::AUTH_FAILURE));
        log.record(
            Event::new(2, kind::FREEZE)
                .repo("demo")
                .detail("refs/heads/main moved"),
        );
        let mut told = String::new();
        for _ in 0..200 {
            told = fs::read_to_string(&out).unwrap_or_default();
            if told.ends_with('\n') {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        let event: Event = serde_json::from_str(told.trim()).unwrap();
        assert_eq!(event.kind, kind::FREEZE);
        assert_eq!(event.repo.as_deref(), Some("demo"));
    }
}