lean-ctx 3.12.10

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
// SPDX-License-Identifier: Apache-2.0
//! Carrying out a key-sync plan on the computer: Unix users, their
//! `authorized_keys`, and the state file naming every user this daemon
//! created (`/var/lib/leanctx-users/computer-users.json`, root, `0600`).
//! Runs as root in `lean-ctx computer sync-users` only, never in the
//! unprivileged agent.
//!
//! Safety rules:
//! - Only names of the strict `lc-…` form are used, and only as single
//!   arguments to fixed programs (no shell); a user that already exists but
//!   is not in the state file is never touched.
//! - Nobody is deleted: a revoked user's keys are emptied, the account
//!   expires and its sessions end; the home directory stays.
//! - No sudo and no privileged group: grantees join `lc-users` (and
//!   `lc-diag` on a `weave_host` computer) only.
//! - Keys are written through directory handles opened without following
//!   symlinks, so a user cannot redirect root's write.

use std::path::Path;

use super::grants::{ManagedUsers, Step};

/// Load the state file; a missing file is an empty state, anything
/// unreadable or malformed stops the sync (no user is changed).
pub(crate) fn load_state(path: &Path, owner: u32) -> Result<ManagedUsers, String> {
    match std::fs::symlink_metadata(path) {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(ManagedUsers::default()),
        Err(e) => return Err(format!("{}: {}", path.display(), e.kind())),
        Ok(_) => {}
    }
    let bytes = super::secret_file::read_checked(
        path,
        owner,
        super::secret_file::Exposure::Private,
        1024 * 1024,
    )?;
    let state: ManagedUsers = serde_json::from_slice(&bytes)
        .map_err(|e| format!("{}: not a user state file: {e}", path.display()))?;
    if let Some(bad) = state
        .users
        .keys()
        .find(|u| !super::grants::valid_unix_user(u))
    {
        return Err(format!(
            "{}: holds a user name of the wrong form ({} characters)",
            path.display(),
            bad.len()
        ));
    }
    Ok(state)
}

/// Carry out `steps`, recording each change in `state` and the state file.
/// Returns one line per step that failed; the others still run.
#[cfg(target_os = "linux")]
pub(crate) fn apply(
    role: super::config::Role,
    steps: &[Step],
    state: &mut ManagedUsers,
    state_path: &Path,
) -> Result<Vec<String>, String> {
    linux::apply(role, steps, state, state_path)
}

#[cfg(not(target_os = "linux"))]
pub(crate) fn apply(
    _role: super::config::Role,
    steps: &[Step],
    _state: &mut ManagedUsers,
    _state_path: &Path,
) -> Result<Vec<String>, String> {
    if steps.is_empty() {
        return Ok(Vec::new());
    }
    Err("Unix users of a cloud computer are managed on Linux only".into())
}

#[cfg(target_os = "linux")]
mod linux {
    use std::ffi::CString;
    use std::io::Write;
    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
    use std::path::Path;
    use std::process::{Command, Stdio};

    use super::super::config::Role;
    use super::super::grants::{
        GROUP_DIAG, GROUP_USERS, Managed, ManagedUsers, Step, keys_digest, valid_unix_user,
    };

    const PATH: &str = "/usr/sbin:/usr/bin:/sbin:/bin";
    const USERADD: &str = "/usr/sbin/useradd";
    const USERMOD: &str = "/usr/sbin/usermod";
    const GROUPADD: &str = "/usr/sbin/groupadd";
    const GETENT: &str = "/usr/bin/getent";
    const LOGINCTL: &str = "/usr/bin/loginctl";
    /// A `weave_host` grantee gets `/bin/sh` only so that sshd can run the
    /// forced `lean-ctx computer diag` (sshd runs every command through the
    /// login shell, and `nologin` would refuse it). The key's `restrict,
    /// command=` and sshd's `Match Group lc-diag` `ForceCommand` keep the
    /// login on the diag menu.
    const SHELL_WEAVE_HOST: &str = "/bin/sh";
    const SHELL_GENERAL: &str = "/bin/bash";
    const COMMENT: &str = "lean-ctx cloud computer user";

    fn run(program: &str, args: &[&str]) -> Result<std::process::Output, String> {
        Command::new(program)
            .args(args)
            .env_clear()
            .env("PATH", PATH)
            .env("LC_ALL", "C")
            .stdin(Stdio::null())
            .output()
            .map_err(|e| format!("{program}: {}", e.kind()))
    }

    fn run_ok(program: &str, args: &[&str]) -> Result<(), String> {
        let out = run(program, args)?;
        if out.status.success() {
            return Ok(());
        }
        let stderr = String::from_utf8_lossy(&out.stderr);
        let first = stderr
            .lines()
            .next()
            .unwrap_or("")
            .chars()
            .take(200)
            .collect::<String>();
        Err(format!("{program} failed ({}): {first}", out.status))
    }

    fn ensure_group(name: &str) -> Result<(), String> {
        if run(GETENT, &["group", name])?.status.success() {
            return Ok(());
        }
        run_ok(GROUPADD, &["--system", name])
    }

    /// `(uid, gid, home)` of `user`, or `None` when there is no such user.
    fn passwd(user: &str) -> Result<Option<(u32, u32, String)>, String> {
        let out = run(GETENT, &["passwd", user])?;
        // getent: 2 = no such key.
        if out.status.code() == Some(2) {
            return Ok(None);
        }
        if !out.status.success() {
            return Err(format!("getent passwd failed ({})", out.status));
        }
        let line = String::from_utf8_lossy(&out.stdout);
        let fields: Vec<&str> = line.trim_end().split(':').collect();
        match fields.as_slice() {
            [name, _, uid, gid, _, home, _] if *name == user => {
                let uid = uid.parse().map_err(|_| "getent: bad uid".to_string())?;
                let gid = gid.parse().map_err(|_| "getent: bad gid".to_string())?;
                Ok(Some((uid, gid, (*home).to_string())))
            }
            _ => Err("getent passwd: unexpected answer".into()),
        }
    }

    pub(super) fn apply(
        role: Role,
        steps: &[Step],
        state: &mut ManagedUsers,
        state_path: &Path,
    ) -> Result<Vec<String>, String> {
        if steps.is_empty() {
            return Ok(Vec::new());
        }
        ensure_group(GROUP_USERS)?;
        if role == Role::WeaveHost {
            ensure_group(GROUP_DIAG)?;
        }
        let mut failures = Vec::new();
        for step in steps {
            if let Err(why) = apply_one(role, step, state, state_path) {
                failures.push(why);
            }
        }
        Ok(failures)
    }

    fn apply_one(
        role: Role,
        step: &Step,
        state: &mut ManagedUsers,
        state_path: &Path,
    ) -> Result<(), String> {
        match step {
            Step::Create { user, keys } => {
                check_name(user)?;
                if passwd(user)?.is_some() {
                    return Err(format!(
                        "{user}: exists but was not created by this service; left alone"
                    ));
                }
                // Recorded before useradd, without keys: a crash or a failed
                // useradd leaves a record (the next sync creates the user
                // again), and a user without keys gives no access.
                state.users.insert(user.clone(), Managed::pending());
                save_state(state_path, state)?;
                create_user(role, user)?;
                set_keys(user, keys, state, state_path)
            }
            Step::Reactivate { user, keys } => {
                check_managed(user, state)?;
                if passwd(user)?.is_none() {
                    // A pending record whose useradd did not finish.
                    create_user(role, user)?;
                } else {
                    run_ok(USERMOD, &["--expiredate", "", user])?;
                }
                if let Some(m) = state.users.get_mut(user) {
                    m.active = true;
                }
                save_state(state_path, state)?;
                set_keys(user, keys, state, state_path)
            }
            Step::SetKeys { user, keys } => {
                check_managed(user, state)?;
                set_keys(user, keys, state, state_path)
            }
            Step::Revoke { user } => {
                check_managed(user, state)?;
                if passwd(user)?.is_none() {
                    // Only a pending record: nothing to lock.
                    state.users.remove(user);
                    return save_state(state_path, state);
                }
                // Keys first: from this write on, no new login works.
                let emptied = write_keys(user, "");
                let expired = run_ok(USERMOD, &["--expiredate", "1", user]);
                // Fails when the user has no session; that is fine.
                let _ = run(LOGINCTL, &["terminate-user", user]);
                // Revoked only when both held; otherwise the user stays
                // active and the next sync revokes it again.
                if let Some(m) = state.users.get_mut(user) {
                    m.record_revoke(emptied.is_ok(), expired.is_ok());
                }
                save_state(state_path, state)?;
                emptied.and(expired)
            }
        }
    }

    fn create_user(role: Role, user: &str) -> Result<(), String> {
        let (shell, groups) = match role {
            Role::WeaveHost => (SHELL_WEAVE_HOST, format!("{GROUP_USERS},{GROUP_DIAG}")),
            Role::General => (SHELL_GENERAL, GROUP_USERS.to_string()),
        };
        run_ok(
            USERADD,
            &[
                "--create-home",
                "--user-group",
                "--shell",
                shell,
                "--groups",
                &groups,
                "--comment",
                COMMENT,
                user,
            ],
        )
    }

    fn check_name(user: &str) -> Result<(), String> {
        if valid_unix_user(user) {
            Ok(())
        } else {
            Err("a user name of the wrong form was refused".into())
        }
    }

    fn check_managed(user: &str, state: &ManagedUsers) -> Result<(), String> {
        check_name(user)?;
        if state.users.contains_key(user) {
            Ok(())
        } else {
            Err(format!("{user}: not created by this service; left alone"))
        }
    }

    fn set_keys(
        user: &str,
        keys: &str,
        state: &mut ManagedUsers,
        state_path: &Path,
    ) -> Result<(), String> {
        write_keys(user, keys)?;
        if let Some(m) = state.users.get_mut(user) {
            m.keys = keys_digest(keys);
        }
        save_state(state_path, state)
    }

    fn cstr(s: &str) -> Result<CString, String> {
        CString::new(s).map_err(|_| "a path with a NUL byte".to_string())
    }

    fn last_os_error(what: &str) -> String {
        format!("{what}: {}", std::io::Error::last_os_error().kind())
    }

    fn open_dir_at(dir: libc::c_int, name: &str) -> Result<OwnedFd, String> {
        let c = cstr(name)?;
        // SAFETY: `c` is a valid NUL-terminated string; the flags never create.
        let fd = unsafe {
            libc::openat(
                dir,
                c.as_ptr(),
                libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
            )
        };
        if fd < 0 {
            return Err(last_os_error(name));
        }
        // SAFETY: `fd` was just opened and is owned by nobody else.
        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
    }

    fn fstat(fd: &OwnedFd) -> Result<libc::stat, String> {
        // SAFETY: a zeroed `stat` is a valid out-parameter for fstat.
        let mut st: libc::stat = unsafe { std::mem::zeroed() };
        // SAFETY: `fd` is open; `st` is a valid pointer.
        if unsafe { libc::fstat(fd.as_raw_fd(), &raw mut st) } != 0 {
            return Err(last_os_error("fstat"));
        }
        Ok(st)
    }

    /// Replace `/home/<user>/.ssh/authorized_keys` with `content`, owned by
    /// the user, mode `0600`, without following any symlink the user made.
    fn write_keys(user: &str, content: &str) -> Result<(), String> {
        check_name(user)?;
        let (uid, gid, home) = passwd(user)?.ok_or_else(|| format!("{user}: no such user"))?;
        if home != format!("/home/{user}") || uid == 0 {
            return Err(format!("{user}: unexpected account (home or uid)"));
        }
        let root = open_dir_at(libc::AT_FDCWD, "/home")?;
        let home_fd = open_dir_at(root.as_raw_fd(), user)?;
        let st = fstat(&home_fd)?;
        if st.st_uid != uid {
            return Err(format!("{user}: home directory not owned by the user"));
        }
        // Grantees never read each other's homes.
        // SAFETY: `home_fd` is an open directory.
        if unsafe { libc::fchmod(home_fd.as_raw_fd(), 0o700) } != 0 {
            return Err(last_os_error("chmod home"));
        }
        let ssh = cstr(".ssh")?;
        // SAFETY: valid fd and string; mkdirat never follows a final symlink.
        if unsafe { libc::mkdirat(home_fd.as_raw_fd(), ssh.as_ptr(), 0o700) } != 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() != std::io::ErrorKind::AlreadyExists {
                return Err(format!(".ssh: {}", err.kind()));
            }
        }
        let ssh_fd = open_dir_at(home_fd.as_raw_fd(), ".ssh")?;
        let st = fstat(&ssh_fd)?;
        if st.st_uid != uid && st.st_uid != 0 {
            return Err(format!("{user}: .ssh owned by someone else"));
        }
        // SAFETY: `ssh_fd` is an open directory.
        if unsafe { libc::fchown(ssh_fd.as_raw_fd(), uid, gid) } != 0 {
            return Err(last_os_error("chown .ssh"));
        }
        // SAFETY: `ssh_fd` is an open directory.
        if unsafe { libc::fchmod(ssh_fd.as_raw_fd(), 0o700) } != 0 {
            return Err(last_os_error("chmod .ssh"));
        }
        let tmp = cstr(".authorized_keys.lean-ctx")?;
        // A leftover (or planted) file of that name goes first; a directory
        // of that name makes the write fail.
        // SAFETY: valid fd and string; unlinkat never follows symlinks.
        unsafe { libc::unlinkat(ssh_fd.as_raw_fd(), tmp.as_ptr(), 0) };
        // SAFETY: valid fd and string; O_EXCL|O_NOFOLLOW create a new file only.
        let fd = unsafe {
            libc::openat(
                ssh_fd.as_raw_fd(),
                tmp.as_ptr(),
                libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC,
                0o600 as libc::c_uint,
            )
        };
        if fd < 0 {
            return Err(last_os_error("authorized_keys"));
        }
        // SAFETY: `fd` was just created and is owned by nobody else.
        let mut file = std::fs::File::from(unsafe { OwnedFd::from_raw_fd(fd) });
        file.write_all(content.as_bytes())
            .and_then(|()| file.sync_all())
            .map_err(|e| format!("authorized_keys: {}", e.kind()))?;
        // SAFETY: `file` is open.
        if unsafe { libc::fchown(file.as_raw_fd(), uid, gid) } != 0 {
            return Err(last_os_error("chown authorized_keys"));
        }
        let target = cstr("authorized_keys")?;
        // SAFETY: valid fds and strings; renameat replaces the name only.
        if unsafe {
            libc::renameat(
                ssh_fd.as_raw_fd(),
                tmp.as_ptr(),
                ssh_fd.as_raw_fd(),
                target.as_ptr(),
            )
        } != 0
        {
            return Err(last_os_error("rename authorized_keys"));
        }
        Ok(())
    }

    /// Write the state file atomically, root-only.
    fn save_state(path: &Path, state: &ManagedUsers) -> Result<(), String> {
        use std::os::unix::fs::OpenOptionsExt;
        let body = serde_json::to_vec_pretty(state).map_err(|e| e.to_string())?;
        let tmp = path.with_extension("json.tmp");
        let _ = std::fs::remove_file(&tmp);
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o600)
            .custom_flags(libc::O_NOFOLLOW)
            .open(&tmp)
            .map_err(|e| format!("{}: {}", tmp.display(), e.kind()))?;
        file.write_all(&body)
            .and_then(|()| file.sync_all())
            .map_err(|e| format!("{}: {}", tmp.display(), e.kind()))?;
        std::fs::rename(&tmp, path).map_err(|e| format!("{}: {}", path.display(), e.kind()))
    }
}

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

    #[cfg(unix)]
    #[test]
    fn the_state_file_is_read_strictly() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let me = super::super::secret_file::effective_uid();
        let path = dir.path().join("computer-users.json");
        assert_eq!(load_state(&path, me).unwrap(), ManagedUsers::default());

        let write = |body: &str, mode: u32| {
            std::fs::write(&path, body).unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
        };
        write(
            r#"{"users":{"lc-0123456789ab":{"active":true,"keys":"d"}}}"#,
            0o600,
        );
        let state = load_state(&path, me).unwrap();
        assert!(state.users["lc-0123456789ab"].active);

        write(
            r#"{"users":{"lc-0123456789ab":{"active":true,"keys":"d"}}}"#,
            0o644,
        );
        assert!(load_state(&path, me).is_err());
        write(r#"{"users":{"root":{"active":true,"keys":"d"}}}"#, 0o600);
        assert!(load_state(&path, me).is_err());
        write(r#"{"users":{},"extra":1}"#, 0o600);
        assert!(load_state(&path, me).is_err());
        write("garbage", 0o600);
        assert!(load_state(&path, me).is_err());
    }
}