lean-ctx 3.12.11

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
// SPDX-License-Identifier: Apache-2.0
//! `lean-ctx computer`: the agent on a LeanCTX cloud computer.
//!
//! The computer's cloud-init writes `/etc/leanctx/computer.json` and two
//! root-only tokens, installs this binary and starts
//! `lean-ctx-computer.service`, which runs `lean-ctx computer run` as the
//! unprivileged system user `leanctx` (no capabilities, read-only system):
//!
//! 1. **Enrol** once with the single-use `het_` token, as a Host of the
//!    computer's team.
//! 2. **Meter** every minute with the computer's `lcm_` token
//!    (`POST /api/v1/computer-meter/computers/{id}/tick`), reporting whether
//!    a grantee is active so the idle stop waits.
//! 3. **Grants** every minute: the granted public keys of this computer are
//!    checked and handed to the root side in `/var/lib/leanctx/grants.json`.
//!
//! `lean-ctx computer sync-users` (root, `lean-ctx-computer-users.service`,
//! started by a path unit when the grants change) turns the grants into
//! `lc-…` Unix users without sudo. `lean-ctx computer diag` is the
//! diagnostic menu grantees reach over SSH.
//!
//! The tokens reach the agent only through systemd credentials
//! (`LoadCredential=`); they never appear in arguments, logs or output.

mod config;
mod diag;
mod grants;
mod host;
mod meter;
mod secret_file;
mod users;

use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use lean_ctx_cloud::CloudStore;

/// Where the unit points at the identity file.
const CONFIG_ENV: &str = "LEANCTX_COMPUTER_CONFIG";
const CONFIG_DEFAULT: &str = "/etc/leanctx/computer.json";
/// The credential names of `LoadCredential=`.
const ENROL_CREDENTIAL: &str = "enrol.token";
const METER_CREDENTIAL: &str = "meter.token";
/// The agent's service user and its state (`StateDirectory=leanctx`).
const SERVICE_USER: &str = "leanctx";
const STATE_DIR: &str = "/var/lib/leanctx";
/// The checked grants, from the agent to the root user sync.
const GRANTS_FILE: &str = "/var/lib/leanctx/grants.json";
/// What `diag status` shows; no secrets.
const STATUS_FILE: &str = "/var/lib/leanctx/computer-status.json";
/// The users the root sync created (`StateDirectory=leanctx-users`, `0700`).
const USERS_FILE: &str = "/var/lib/leanctx-users/computer-users.json";
const SSH_DIR: &str = "/etc/ssh";
const UNIT: &str = "lean-ctx-computer.service";
/// The authorized-keys read of the enrolled Host (design §2.3a).
const KEYS_PATH: &str = "/me/computer/authorized-keys";
const PERIOD: Duration = Duration::from_secs(60);
/// After a failed start, wait before systemd restarts the agent, so a
/// broken enrolment does not hammer the cloud every five seconds.
const FAILED_START_PAUSE: Duration = Duration::from_secs(60);
/// The agent unit, identical to the one the computer's cloud-init writes.
const UNIT_FILE: &str = include_str!("lean-ctx-computer.service");
/// The root user sync and the path unit that starts it.
const USERS_UNIT_FILE: &str = include_str!("lean-ctx-computer-users.service");
const USERS_PATH_FILE: &str = include_str!("lean-ctx-computer-users.path");

const HELP: &str = "The cloud computer agent (runs on the computer itself)\n\n\
Usage: lean-ctx computer run          Enrol once, then meter and fetch SSH grants every minute (lean-ctx-computer.service)\n\
\x20      lean-ctx computer sync-users   Turn the fetched grants into Unix users (root; lean-ctx-computer-users.service)\n\
\x20      lean-ctx computer diag         Diagnostic menu for SSH logins: status, help\n\
\x20      lean-ctx computer unit [users|path]  Print a systemd unit\n\n\
Reads the identity file of LEANCTX_COMPUTER_CONFIG (default /etc/leanctx/computer.json) and the tokens systemd passes as credentials.\n";

pub(crate) fn cmd_computer(args: &[String]) {
    let code = match args.first().map(String::as_str) {
        Some("run") => run_service(),
        Some("sync-users") => sync_users(),
        Some("diag") => diag::run(&args[1..]),
        Some("unit") => match args.get(1).map(String::as_str) {
            None => print_unit(UNIT_FILE),
            Some("users") => print_unit(USERS_UNIT_FILE),
            Some("path") => print_unit(USERS_PATH_FILE),
            Some(_) => {
                eprint!("{HELP}");
                2
            }
        },
        None | Some("help" | "--help" | "-h") => {
            print!("{HELP}");
            0
        }
        Some(_) => {
            eprint!("{HELP}");
            2
        }
    };
    if code != 0 {
        std::process::exit(code);
    }
}

fn print_unit(text: &str) -> i32 {
    print!("{text}");
    0
}

fn log(line: &str) {
    eprintln!("lean-ctx computer: {line}");
}

/// What the service last saw, for `diag status`.
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Status {
    role: String,
    enrolled: bool,
    /// The cloud's state of this computer after the last tick, or why the
    /// tick failed.
    meter: String,
    /// Unix seconds of the last successful tick.
    last_tick: Option<u64>,
    /// Users the last grants fetch named.
    users: usize,
    /// `ok`, or why the last grants fetch failed.
    key_sync: String,
}

impl Status {
    fn lines(&self) -> String {
        let clean =
            |s: &str| -> String { s.chars().filter(|c| !c.is_control()).take(160).collect() };
        let ago = self.last_tick.map_or_else(
            || "never".to_string(),
            |t| format!("{} s ago", now_secs().saturating_sub(t)),
        );
        format!(
            "  role       {}\n  enrolled   {}\n  meter      {} (last tick {ago})\n  granted    {} user(s)\n  grants     {}\n",
            clean(&self.role),
            if self.enrolled { "yes" } else { "no" },
            clean(&self.meter),
            self.users,
            clean(&self.key_sync),
        )
    }
}

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

fn write_status(status: &Status) {
    let Ok(body) = serde_json::to_vec(status) else {
        return;
    };
    let path = Path::new(STATUS_FILE);
    let tmp = path.with_extension("json.tmp");
    let written = std::fs::write(&tmp, body)
        .and_then(|()| set_mode(&tmp, 0o644))
        .and_then(|()| std::fs::rename(&tmp, path));
    if let Err(e) = written {
        log(&format!("{STATUS_FILE}: {}", e.kind()));
    }
}

#[cfg(unix)]
fn set_mode(path: &Path, mode: u32) -> std::io::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
}

#[cfg(not(unix))]
fn set_mode(_path: &Path, _mode: u32) -> std::io::Result<()> {
    Ok(())
}

fn store() -> CloudStore {
    let dir = Path::new(STATE_DIR);
    CloudStore::at(dir.join("config/cloud"), dir.join("data/cloud"))
}

/// The uid of `name` in a `/etc/passwd` text.
fn uid_in_passwd(passwd: &str, name: &str) -> Option<u32> {
    passwd.lines().find_map(|line| {
        let mut fields = line.split(':');
        (fields.next()? == name).then_some(())?;
        fields.nth(1)?.parse().ok()
    })
}

/// The uid of the agent's service user, which owns its files; `None` when
/// the user is missing (then nothing it wrote is trusted).
fn service_uid() -> Option<u32> {
    let passwd = std::fs::read_to_string("/etc/passwd").ok()?;
    uid_in_passwd(&passwd, SERVICE_USER).filter(|&uid| uid != 0)
}

fn config_path() -> PathBuf {
    std::env::var_os(CONFIG_ENV).map_or_else(|| PathBuf::from(CONFIG_DEFAULT), PathBuf::from)
}

/// The identity file: root-owned, not writable by others.
fn load_config() -> Result<config::ComputerConfig, String> {
    secret_file::read_checked(&config_path(), 0, secret_file::Exposure::Readable, 4096)
        .and_then(|bytes| config::parse(&bytes))
}

/// A systemd credential: inside `$CREDENTIALS_DIRECTORY`, owned by this
/// process's user and readable by nobody else. Without the directory the
/// agent was not started by its unit and refuses.
fn credential(name: &str, prefix: &str) -> Result<zeroize::Zeroizing<String>, String> {
    let dir = std::env::var_os("CREDENTIALS_DIRECTORY")
        .filter(|d| Path::new(d).is_absolute())
        .ok_or("no systemd credentials (start the agent as lean-ctx-computer.service)")?;
    secret_file::read_token(
        &Path::new(&dir).join(name),
        secret_file::effective_uid(),
        prefix,
    )
}

/// A start that failed: logged, then a pause before systemd restarts us.
fn failed_start(why: &str) -> i32 {
    log(why);
    std::thread::sleep(FAILED_START_PAUSE);
    1
}

fn run_service() -> i32 {
    if secret_file::effective_uid() == 0 {
        return failed_start("the agent never runs as root; start it as lean-ctx-computer.service");
    }
    let config = match load_config() {
        Ok(config) => config,
        Err(why) => return failed_start(&why),
    };
    let cloud = lean_ctx::core::config::Config::load().cloud.clone();
    let mut status = Status {
        role: config.role.as_str().into(),
        ..Status::default()
    };
    if let Err(why) = ensure_enrolled(&config, &cloud) {
        status.meter = "not started".into();
        status.key_sync = "not enrolled".into();
        write_status(&status);
        return failed_start(&format!("enrolment: {why}"));
    }
    status.enrolled = true;
    let meter = match credential(METER_CREDENTIAL, "lcm_")
        .and_then(|token| meter::Meter::new(&config.origin, &config.computer_id, &token))
    {
        Ok(meter) => meter,
        Err(why) => return failed_start(&why),
    };
    log(&format!(
        "enrolled; metering and fetching SSH grants every {} s",
        PERIOD.as_secs()
    ));
    let mut host_keys_sent = false;
    let mut last_meter = String::new();
    let mut last_sync = String::new();
    let mut last_grants: Option<Vec<u8>> = None;
    loop {
        let started = std::time::Instant::now();
        let seen = match meter.tick(host::grantee_active()) {
            Ok(tick) => {
                status.last_tick = Some(now_secs());
                status.meter.clone_from(&tick.state);
                match tick.action {
                    meter::Action::Run => format!("run ({})", tick.state),
                    // The cloud powers a suspended computer off itself.
                    meter::Action::Stop => format!("stop requested ({})", tick.state),
                }
            }
            Err(e) => {
                status.meter = e.to_string();
                e.to_string()
            }
        };
        if seen != last_meter {
            log(&format!("meter: {seen}"));
            last_meter = seen;
        }
        if !host_keys_sent {
            host_keys_sent = report_host_keys(&meter);
        }
        let synced = match fetch_grants(&config, &mut last_grants) {
            Ok((granted, summary)) => {
                status.users = granted;
                status.key_sync = "ok".into();
                summary
            }
            Err(why) => {
                status.key_sync.clone_from(&why);
                why
            }
        };
        if synced != last_sync {
            log(&format!("grants: {synced}"));
            last_sync = synced;
        }
        write_status(&status);
        std::thread::sleep(PERIOD.saturating_sub(started.elapsed()));
    }
}

/// Send the SSH host key fingerprints once; `true` when done (or there is
/// nothing to send), so a failure is retried on the next tick.
fn report_host_keys(meter: &meter::Meter) -> bool {
    let fingerprints = host::host_key_fingerprints(Path::new(SSH_DIR));
    if fingerprints.is_empty() {
        log("no SSH host keys found to report");
        return true;
    }
    match meter.host_keys(&fingerprints) {
        Ok(()) => {
            log(&format!("reported {} SSH host key(s)", fingerprints.len()));
            true
        }
        Err(e) => {
            log(&format!("host keys: {e}"));
            false
        }
    }
}

/// Enrol this computer once with the `het_` token. An enrolment with
/// another cloud is refused. The token file stays (root-only, spent).
fn ensure_enrolled(
    config: &config::ComputerConfig,
    cloud: &lean_ctx_cloud::CloudConfig,
) -> Result<(), String> {
    let store = store();
    if let Some(existing) = store.instance().map_err(|e| e.to_string())? {
        if existing.url != config.origin {
            return Err("this computer is enrolled with another cloud".into());
        }
        return Ok(());
    }
    let raw = credential(ENROL_CREDENTIAL, "het_")?;
    let token = lean_ctx_cloud::auth::EnrollmentToken::parse(&raw).map_err(|e| e.to_string())?;
    drop(raw);
    let client =
        lean_ctx_cloud::transport::CloudClient::new(&config.origin).map_err(|e| e.to_string())?;
    let trust = lean_ctx_cloud::root_cert::for_connect(&client, cloud, &config.origin)
        .map_err(|e| e.to_string())?;
    let label = format!("Cloud computer {}", &config.computer_id[..8]);
    lean_ctx_cloud::auth::enroll_with_token(&store, &client, &token, &label, &trust.root)
        .map_err(|e| e.to_string())?;
    if let Some(certificate) = &trust.certificate {
        lean_ctx_cloud::root_cert::store_certificate(&store, certificate)
            .map_err(|e| e.to_string())?;
    }
    lean_ctx_cloud::revoked::clear(&store).map_err(|e| e.to_string())?;
    lean_ctx_cloud::throttle::clear_connect(&store);
    // Prove the enrolment works before metering on it.
    lean_ctx_cloud::auth::Session::load(store, trust.root)
        .and_then(|session| session.client())
        .map_err(|e| e.to_string())?;
    log("enrolled with the cloud");
    Ok(())
}

/// Fetch and check the grants, and hand them to the root sync when they
/// changed. Any failure leaves the last hand-off (and so every user) as is.
fn fetch_grants(
    config: &config::ComputerConfig,
    last: &mut Option<Vec<u8>>,
) -> Result<(usize, String), String> {
    let store = store();
    let cloud = lean_ctx::core::config::Config::load().cloud.clone();
    let root = lean_ctx_cloud::root_cert::trust_root(&store, &cloud, &config.origin)
        .map_err(|e| format!("trust root: {e}"))?;
    let session =
        lean_ctx_cloud::auth::Session::load(store, root).map_err(|e| format!("session: {e}"))?;
    let answer = session
        .client()
        .and_then(|client| client.get(KEYS_PATH))
        .map_err(|e| format!("authorized keys unavailable: {e}"))?;
    let body = serde_json::to_vec(&answer).map_err(|e| e.to_string())?;
    let desired = grants::desired(&body)?;
    let handoff = grants::handoff(&desired);
    if last.as_deref() != Some(handoff.as_slice()) {
        write_private(Path::new(GRANTS_FILE), &handoff)
            .map_err(|e| format!("{GRANTS_FILE}: {}", e.kind()))?;
        *last = Some(handoff);
    }
    let granted = desired.users.len();
    let mut summary = format!("{granted} user(s) granted");
    if desired.dropped > 0 {
        summary.push_str(&format!(", {} malformed grant(s) ignored", desired.dropped));
    }
    Ok((granted, summary))
}

/// Write `body` to `path` atomically, `0600`, never through a symlink.
#[cfg(unix)]
fn write_private(path: &Path, body: &[u8]) -> std::io::Result<()> {
    use std::io::Write as _;
    use std::os::unix::fs::OpenOptionsExt;
    let tmp = path.with_extension("json.tmp");
    if let Err(e) = std::fs::remove_file(&tmp)
        && e.kind() != std::io::ErrorKind::NotFound
    {
        return Err(e);
    }
    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(&tmp)?;
    file.write_all(body)?;
    file.sync_all()?;
    std::fs::rename(&tmp, path)
}

#[cfg(not(unix))]
fn write_private(_path: &Path, _body: &[u8]) -> std::io::Result<()> {
    Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
}

/// `lean-ctx computer sync-users`: as root, turn the agent's checked grants
/// into Unix users. The grants file must be the agent's own (owned by the
/// service user, or root), private and no symlink; it is parsed again here.
/// Without it nothing changes.
fn sync_users() -> i32 {
    match sync_users_once() {
        Ok(summary) => {
            log(&format!("users: {summary}"));
            0
        }
        Err(why) => {
            log(&format!("users: {why}"));
            1
        }
    }
}

fn sync_users_once() -> Result<String, String> {
    if secret_file::effective_uid() != 0 {
        return Err("runs as root only, as lean-ctx-computer-users.service".into());
    }
    let config = load_config()?;
    let agent = service_uid().ok_or("the service user leanctx does not exist")?;
    let path = Path::new(GRANTS_FILE);
    let bytes =
        match secret_file::read_checked(path, agent, secret_file::Exposure::Private, 1024 * 1024) {
            Ok(bytes) => bytes,
            Err(_) if !path.exists() => return Ok("no grants fetched yet".into()),
            Err(why) => return Err(why),
        };
    let desired = grants::desired(&bytes)?;
    let mut managed = users::load_state(Path::new(USERS_FILE), 0)?;
    let steps = grants::diff(config.role, &desired, &managed);
    let failures = users::apply(config.role, &steps, &mut managed, Path::new(USERS_FILE))?;
    let active = managed.users.values().filter(|m| m.active).count();
    let mut summary = format!("{active} user(s) with access, {} change(s)", steps.len());
    for failure in &failures {
        summary.push_str("; ");
        summary.push_str(failure);
    }
    if failures.is_empty() {
        Ok(summary)
    } else {
        Err(summary)
    }
}

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

    #[test]
    fn the_status_shows_no_control_characters() {
        let status = Status {
            role: "weave_host".into(),
            enrolled: true,
            meter: "running\u{1b}[2J".into(),
            last_tick: None,
            users: 2,
            key_sync: "ok".into(),
        };
        let text = status.lines();
        assert!(!text.contains('\u{1b}'));
        assert!(text.contains("meter      running[2J (last tick never)"));
        assert!(text.contains("granted    2 user(s)"));
    }

    #[test]
    fn the_units_split_the_agent_from_the_root_user_sync() {
        // The agent unit is the one cloud-init writes (p37 !195, variant A).
        assert!(UNIT_FILE.contains("\nExecStart=/usr/local/bin/lean-ctx computer run\n"));
        assert!(UNIT_FILE.contains("\nUser=leanctx\n"));
        assert!(UNIT_FILE.contains("\nLoadCredential=enrol.token:/etc/leanctx/enrol.token\n"));
        assert!(UNIT_FILE.contains("\nLoadCredential=meter.token:/etc/leanctx/meter.token\n"));
        assert!(
            UNIT_FILE
                .contains("\nEnvironment=LEANCTX_COMPUTER_CONFIG=/etc/leanctx/computer.json\n")
        );
        assert!(UNIT_FILE.contains("\nCapabilityBoundingSet=\n"));
        assert!(UNIT_FILE.contains("\nProtectSystem=strict\n"));
        for file in [GRANTS_FILE, STATUS_FILE] {
            assert!(file.starts_with(&format!("{STATE_DIR}/")));
        }
        // The root side keeps its state where the agent cannot write.
        assert!(!USERS_FILE.starts_with(&format!("{STATE_DIR}/")));
        assert!(
            USERS_UNIT_FILE.contains("\nExecStart=/usr/local/bin/lean-ctx computer sync-users\n")
        );
        assert!(USERS_UNIT_FILE.contains("\nType=oneshot\n"));
        assert!(USERS_UNIT_FILE.contains("\nStateDirectory=leanctx-users\n"));
        // Read-only system for the root sync, and a failed step is retried.
        assert!(USERS_UNIT_FILE.contains("\nProtectSystem=strict\n"));
        assert!(USERS_UNIT_FILE.contains("\nRestart=on-failure\n"));
        assert!(USERS_PATH_FILE.contains(&format!("\nPathChanged={GRANTS_FILE}\n")));
        assert!(USERS_PATH_FILE.contains("\nUnit=lean-ctx-computer-users.service\n"));
        assert_eq!(UNIT, "lean-ctx-computer.service");
    }

    #[test]
    fn the_service_user_is_found_by_its_exact_name() {
        let passwd = "root:x:0:0:root:/root:/bin/bash\n\
            leanctxx:x:997:997::/:/usr/sbin/nologin\n\
            leanctx:x:998:998::/var/lib/leanctx:/usr/sbin/nologin\n";
        assert_eq!(uid_in_passwd(passwd, "leanctx"), Some(998));
        assert_eq!(uid_in_passwd(passwd, "nobody"), None);
    }

    #[cfg(unix)]
    #[test]
    fn the_grants_handoff_is_private_and_reads_back() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("grants.json");
        let body = grants::handoff(&grants::Desired::default());
        write_private(&path, &body).unwrap();
        write_private(&path, &body).unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o600);
        let read = secret_file::read_checked(
            &path,
            secret_file::effective_uid(),
            secret_file::Exposure::Private,
            1024,
        )
        .unwrap();
        assert_eq!(grants::desired(&read).unwrap(), grants::Desired::default());
    }
}