Skip to main content

lean_ctx/core/config/
shell_policy.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Where shell-security decisions come from.
3//!
4//! The shell gate (`check_shell_allowlist`, run by the hooks, inside
5//! `lean-ctx -c` / `-t` and by `ctx_shell`) decides what an agent's shell may
6//! run. A command line from that shell can set environment variables for the
7//! lean-ctx it starts (`export`, `env -S`, `set -a`, `declare -n`, `printf -v`,
8//! names built by expansion, …) and can write files under any directory it
9//! names in `HOME`, `XDG_CONFIG_HOME` or `LEAN_CTX_CONFIG_DIR`. Blocking each
10//! of those spellings is a race the gate cannot win. So in release builds the
11//! policy that can loosen the gate is read only from places a command line
12//! cannot move:
13//!
14//! - the compiled defaults;
15//! - the global `config.toml` of the user this process runs as, at that
16//!   user's home as the operating system records it (the passwd database on
17//!   Unix, the profile folder from `SHGetKnownFolderPath` on Windows) — never
18//!   `$HOME`, `%USERPROFILE%`, `XDG_CONFIG_HOME`, `LEAN_CTX_CONFIG_DIR` or
19//!   `LEAN_CTX_DATA_DIR`;
20//! - a project's `.lean-ctx.toml`, for a workspace trusted in the trust store
21//!   next to that config (the trust environment variables are ignored).
22//!
23//! No `LEAN_CTX_SHELL_*` (or other gate-loosening) environment variable is
24//! read for these decisions.
25//!
26//! Trade-off: someone who relocates lean-ctx's config with
27//! `LEAN_CTX_CONFIG_DIR` (or a non-default `XDG_CONFIG_HOME`) keeps every
28//! other setting there, but the shell-security settings (`shell_security`,
29//! `shell_allowlist`, `shell_allowlist_extra`, `shell_strict_mode`,
30//! `shell_allow_inline_scripts`, `shell_allow_writes`, `shell_approval`,
31//! `shell_hook_mode`, `shell_allowlist_subcommand_scoping`) are read from the
32//! default location in the real home. Without a file there the secure
33//! defaults apply.
34//!
35//! Tests and debug builds (`cfg(test)` / `debug_assertions`, and the
36//! dev-dependency-only `test-support` feature, so release test builds of
37//! dependent crates behave the same, #2273) keep the ambient
38//! resolution (`Config::load` plus the environment variables) so the test
39//! suites stay hermetic through `isolated_data_dir` and the env helpers. A
40//! unit test pins the release resolution with `pin_for_test`.
41
42use std::path::{Path, PathBuf};
43use std::sync::{Arc, Mutex, OnceLock};
44
45use super::{Config, ShellApproval};
46
47/// The source the gate reads its policy from.
48enum Source {
49    /// `Config::load()` and the environment: test and debug builds only.
50    #[cfg_attr(
51        not(any(test, debug_assertions, feature = "test-support")),
52        allow(dead_code)
53    )]
54    Ambient,
55    /// The real user's home (`None`: unresolvable, so built-in defaults).
56    /// Debug builds outside tests never construct it.
57    #[cfg_attr(all(debug_assertions, not(test)), allow(dead_code))]
58    Pinned(Option<PathBuf>),
59}
60
61/// A test's stand-in for the release resolution.
62#[cfg(any(test, feature = "test-support"))]
63#[derive(Clone)]
64enum TestPin {
65    /// The account database names this home.
66    Home(PathBuf),
67    /// The account database has no home for this user (#2236).
68    Unresolvable,
69}
70
71#[cfg(any(test, feature = "test-support"))]
72static TEST_PIN: Mutex<Option<TestPin>> = Mutex::new(None);
73
74fn source() -> Source {
75    #[cfg(any(test, feature = "test-support"))]
76    {
77        let pin = TEST_PIN
78            .lock()
79            .unwrap_or_else(std::sync::PoisonError::into_inner)
80            .clone();
81        match pin {
82            Some(TestPin::Home(home)) => return Source::Pinned(Some(home)),
83            Some(TestPin::Unresolvable) => return Source::Pinned(None),
84            None => {}
85        }
86    }
87    // `test-support` is enabled only as a dev-dependency feature, so a
88    // `cargo test --release` of a dependent crate keeps the ambient source
89    // its env-override tests rely on (#2273); shipped binaries never set it.
90    #[cfg(any(test, debug_assertions, feature = "test-support"))]
91    {
92        Source::Ambient
93    }
94    #[cfg(not(any(test, debug_assertions, feature = "test-support")))]
95    {
96        Source::Pinned(real_user_home())
97    }
98}
99
100/// Test-only: resolve the policy as a release build does, with `home`
101/// standing in for the passwd/profile home. Hold the test env lock while the
102/// guard lives; dropping it restores the ambient resolution.
103#[cfg(any(test, feature = "test-support"))]
104#[must_use]
105pub fn pin_for_test(home: &Path) -> PinGuard {
106    assert!(
107        crate::core::data_dir::holds_test_env_lock(),
108        "pin_for_test requires test_env_lock()"
109    );
110    *TEST_PIN
111        .lock()
112        .unwrap_or_else(std::sync::PoisonError::into_inner) =
113        Some(TestPin::Home(home.to_path_buf()));
114    PinGuard(())
115}
116
117/// Test-only: resolve the policy as a release build does for an account the
118/// operating system cannot resolve to a home (#2236). Hold the test env lock
119/// while the guard lives.
120#[cfg(any(test, feature = "test-support"))]
121#[must_use]
122pub fn pin_unresolvable_for_test() -> PinGuard {
123    assert!(
124        crate::core::data_dir::holds_test_env_lock(),
125        "pin_unresolvable_for_test requires test_env_lock()"
126    );
127    *TEST_PIN
128        .lock()
129        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(TestPin::Unresolvable);
130    PinGuard(())
131}
132
133/// Restores the ambient policy source when dropped.
134#[cfg(any(test, feature = "test-support"))]
135pub struct PinGuard(());
136
137#[cfg(any(test, feature = "test-support"))]
138impl Drop for PinGuard {
139    fn drop(&mut self) {
140        *TEST_PIN
141            .lock()
142            .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
143    }
144}
145
146/// True when the gate reads the pinned (release) policy.
147#[must_use]
148pub fn pinned() -> bool {
149    matches!(source(), Source::Pinned(_))
150}
151
152/// The home directory of the user this process runs as, from the operating
153/// system's account database — never from `$HOME`. Resolved once per process:
154/// the effective uid does not change during a run, and the Linux fallback
155/// below starts a process.
156#[must_use]
157pub fn real_user_home() -> Option<PathBuf> {
158    static HOME: OnceLock<Option<PathBuf>> = OnceLock::new();
159    HOME.get_or_init(lookup_real_user_home).clone()
160}
161
162#[cfg(unix)]
163fn lookup_real_user_home() -> Option<PathBuf> {
164    // SAFETY: geteuid has no arguments or failure state.
165    let uid = unsafe { libc::geteuid() };
166    // #2236: the static musl build reads only `/etc/passwd` and has no NSS,
167    // so an account served by SSSD, LDAP, NIS or winbind is not found there.
168    // `getent` is the system's dynamically linked NSS client and sees it.
169    // `$HOME` is never a fallback: that is the bypass the pin exists to close.
170    #[cfg(target_os = "linux")]
171    {
172        passwd_home(uid).or_else(|| getent_home(uid))
173    }
174    #[cfg(not(target_os = "linux"))]
175    {
176        passwd_home(uid)
177    }
178}
179
180/// `getpwuid_r(uid)`'s home directory, when it is absolute.
181#[cfg(unix)]
182fn passwd_home(uid: libc::uid_t) -> Option<PathBuf> {
183    use std::ffi::{CStr, OsStr};
184    use std::os::unix::ffi::OsStrExt;
185
186    let mut buf = vec![0_u8; 4096];
187    loop {
188        // SAFETY: `passwd` is a plain C struct; all-zero is a valid value
189        // that getpwuid_r overwrites.
190        let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
191        let mut result: *mut libc::passwd = std::ptr::null_mut();
192        // SAFETY: every pointer refers to live, writable memory of the
193        // advertised size for the duration of the call.
194        let rc = unsafe {
195            libc::getpwuid_r(
196                uid,
197                &raw mut pwd,
198                buf.as_mut_ptr().cast(),
199                buf.len(),
200                &raw mut result,
201            )
202        };
203        if rc == libc::ERANGE && buf.len() < (1 << 20) {
204            buf.resize(buf.len() * 2, 0);
205            continue;
206        }
207        if rc != 0 || result.is_null() || pwd.pw_dir.is_null() {
208            return None;
209        }
210        // SAFETY: on success pw_dir points to a NUL-terminated string inside
211        // `buf`, which outlives this borrow.
212        let dir = unsafe { CStr::from_ptr(pwd.pw_dir) };
213        let path = PathBuf::from(OsStr::from_bytes(dir.to_bytes()));
214        return (path.is_absolute()).then_some(path);
215    }
216}
217
218/// The account database as NSS sees it, through `getent passwd <uid>` (#2236).
219///
220/// Nothing here comes from the caller's environment: `getent` is taken only
221/// from fixed absolute paths, must be a root-owned file no group or other
222/// user can write, and runs with an empty environment, so `PATH`,
223/// `LD_PRELOAD` and friends cannot pick the program or the answer. The answer
224/// counts only when it names this uid and an absolute home.
225#[cfg(target_os = "linux")]
226fn getent_home(uid: libc::uid_t) -> Option<PathBuf> {
227    use std::io::Read;
228    use std::os::unix::fs::MetadataExt;
229    use std::process::{Command, Stdio};
230    use std::time::{Duration, Instant};
231
232    const CANDIDATES: [&str; 2] = ["/usr/bin/getent", "/bin/getent"];
233    const TIMEOUT: Duration = Duration::from_secs(3);
234
235    let getent = CANDIDATES.iter().map(Path::new).find(|path| {
236        std::fs::metadata(path)
237            .is_ok_and(|meta| meta.is_file() && meta.uid() == 0 && meta.mode() & 0o022 == 0)
238    })?;
239    let mut child = Command::new(getent)
240        .arg("passwd")
241        .arg(uid.to_string())
242        .env_clear()
243        .current_dir("/")
244        .stdin(Stdio::null())
245        .stdout(Stdio::piped())
246        .stderr(Stdio::null())
247        .spawn()
248        .ok()?;
249    // A directory service that hangs must not hang the gate: give up and
250    // fall back to the built-in defaults, which enforce.
251    let deadline = Instant::now() + TIMEOUT;
252    let status = loop {
253        match child.try_wait() {
254            Ok(Some(status)) => break status,
255            Ok(None) if Instant::now() < deadline => {
256                std::thread::sleep(Duration::from_millis(10));
257            }
258            _ => {
259                let _ = child.kill();
260                let _ = child.wait();
261                return None;
262            }
263        }
264    };
265    if !status.success() {
266        return None;
267    }
268    let mut out = Vec::new();
269    child
270        .stdout
271        .take()?
272        .take(64 * 1024)
273        .read_to_end(&mut out)
274        .ok()?;
275    parse_passwd_home(&out, uid)
276}
277
278/// The home field of a `passwd` line (`name:pw:uid:gid:gecos:dir:shell`) when
279/// the line names `uid` and an absolute directory. Only the first line counts.
280#[cfg(any(all(test, unix), target_os = "linux"))]
281fn parse_passwd_home(out: &[u8], uid: u32) -> Option<PathBuf> {
282    let line = std::str::from_utf8(out).ok()?.lines().next()?;
283    let fields: Vec<&str> = line.split(':').collect();
284    if fields.len() < 7 || fields[2].parse::<u32>().ok()? != uid {
285        return None;
286    }
287    let dir = PathBuf::from(fields[5]);
288    dir.is_absolute().then_some(dir)
289}
290
291/// The home directory of the user this process runs as. `dirs` asks
292/// `SHGetKnownFolderPath(FOLDERID_Profile)` on Windows and never reads
293/// `%USERPROFILE%` or `%HOME%`.
294#[cfg(not(unix))]
295fn lookup_real_user_home() -> Option<PathBuf> {
296    dirs::home_dir().filter(|p| p.is_absolute())
297}
298
299/// The config location for messages: the pinned or ambient `config.toml`,
300/// or — for an account the OS cannot resolve (#2236) — a statement that no
301/// location exists, instead of a path the gate never reads.
302#[must_use]
303pub fn config_path_display() -> String {
304    match config_path() {
305        Some(path) => path.display().to_string(),
306        None if pinned() => "none — this user has no account-database entry with a home \
307                             directory, so no config.toml location can be derived; the \
308                             built-in defaults apply"
309            .to_string(),
310        None => "~/.lean-ctx/config.toml".to_string(),
311    }
312}
313
314/// lean-ctx's config directory inside `home`, laid out as an install without
315/// any directory override resolves it (legacy `~/.lean-ctx` or a pre-split
316/// `~/.config/lean-ctx` still count; otherwise `~/.config/lean-ctx`).
317fn config_dir_in(home: &Path) -> PathBuf {
318    let xdg_config = home.join(".config");
319    let xdg_data = home.join(".local").join("share");
320    crate::core::paths::single_dir_override_fs(home, &xdg_config, Some(&xdg_data))
321        .unwrap_or_else(|| xdg_config.join("lean-ctx"))
322}
323
324/// The global `config.toml` the gate reads its policy from, for messages.
325#[must_use]
326pub fn config_path() -> Option<PathBuf> {
327    match source() {
328        Source::Ambient => Config::path(),
329        Source::Pinned(home) => home.map(|h| config_dir_in(&h).join("config.toml")),
330    }
331}
332
333/// The home whose `.claude/settings.json` the gate may mirror.
334#[must_use]
335pub fn settings_home() -> Option<PathBuf> {
336    match source() {
337        Source::Ambient => crate::core::home::resolve_home_dir(),
338        Source::Pinned(home) => home,
339    }
340}
341
342type PinnedCache = Option<(String, Arc<Config>)>;
343
344/// The configuration shell-security decisions are made from.
345#[must_use]
346pub fn config() -> Arc<Config> {
347    match source() {
348        Source::Ambient => Config::load_arc(),
349        Source::Pinned(None) => Arc::new(Config::default()),
350        Source::Pinned(Some(home)) => pinned_config(&home),
351    }
352}
353
354fn pinned_config(home: &Path) -> Arc<Config> {
355    static CACHE: Mutex<PinnedCache> = Mutex::new(None);
356    let dir = config_dir_in(home);
357    let global = std::fs::read_to_string(dir.join("config.toml")).ok();
358    // The project is the working directory's checkout: neither
359    // `LEAN_CTX_PROJECT_ROOT` nor a session's root decides it here.
360    let root = project_root_from_cwd();
361    let local = root.as_deref().and_then(|r| {
362        let path = Config::local_path(r);
363        crate::core::pathutil::may_probe_path(&path)
364            .then(|| std::fs::read_to_string(path).ok())
365            .flatten()
366    });
367    let local_hash = local.as_deref().map(crate::core::hasher::hash_str);
368    let trusted = match (root.as_deref(), local_hash.as_deref()) {
369        (Some(r), Some(hash)) => crate::core::workspace_trust::is_pinned_in_store(
370            &dir.join(crate::core::workspace_trust::FILE_NAME),
371            Path::new(r),
372            hash,
373        ),
374        _ => false,
375    };
376    let key = format!(
377        "{}\0{}\0{}\0{}\0{trusted}",
378        dir.display(),
379        global
380            .as_deref()
381            .map(crate::core::hasher::hash_str)
382            .unwrap_or_default(),
383        root.as_deref().unwrap_or_default(),
384        local_hash.as_deref().unwrap_or_default(),
385    );
386    let mut guard = CACHE
387        .lock()
388        .unwrap_or_else(std::sync::PoisonError::into_inner);
389    if let Some((cached_key, cfg)) = guard.as_ref()
390        && *cached_key == key
391    {
392        return Arc::clone(cfg);
393    }
394    // An unparsable file falls back to the defaults, which enforce.
395    let mut cfg = global
396        .as_deref()
397        .and_then(|raw| super::loader::parse_config_with_profile(raw, None).ok())
398        .unwrap_or_default();
399    if let Some(local) = local.as_deref() {
400        super::loader::without_env_profile(|| cfg.merge_local(local, trusted));
401    }
402    let cfg = Arc::new(cfg);
403    *guard = Some((key, Arc::clone(&cfg)));
404    cfg
405}
406
407/// The nearest directory at or above the working directory that holds a
408/// `.git` entry, else the working directory itself.
409fn project_root_from_cwd() -> Option<String> {
410    let cwd = std::env::current_dir().ok()?;
411    let root = cwd
412        .ancestors()
413        .find(|dir| dir.join(".git").exists())
414        .unwrap_or(&cwd);
415    Some(root.to_string_lossy().into_owned())
416}
417
418/// A gate-loosening environment variable, honoured only by the ambient
419/// (test/debug) source. Release builds never read it.
420#[must_use]
421pub fn env(name: &str) -> Option<String> {
422    match source() {
423        Source::Ambient => std::env::var(name).ok(),
424        Source::Pinned(_) => None,
425    }
426}
427
428fn env_flag(name: &str) -> Option<bool> {
429    env(name).map(|raw| {
430        matches!(
431            raw.trim().to_ascii_lowercase().as_str(),
432            "1" | "true" | "yes" | "on"
433        )
434    })
435}
436
437/// `shell_allow_inline_scripts` for the gate.
438#[must_use]
439pub fn allow_inline_scripts() -> bool {
440    env_flag("LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS")
441        .unwrap_or_else(|| config().shell_allow_inline_scripts)
442}
443
444/// `shell_allow_writes` for `ctx_shell`.
445#[must_use]
446pub fn allow_writes() -> bool {
447    env_flag("LEAN_CTX_SHELL_ALLOW_WRITES").unwrap_or_else(|| config().shell_allow_writes)
448}
449
450/// `shell_approval` for the gate.
451#[must_use]
452pub fn approval() -> ShellApproval {
453    match source() {
454        Source::Ambient => ShellApproval::effective(&config()),
455        Source::Pinned(_) => config().shell_approval,
456    }
457}
458
459/// `shell_hook_mode` for the hooks (empty when unset).
460#[must_use]
461pub fn shell_hook_mode() -> String {
462    env("LEAN_CTX_SHELL_HOOK_MODE")
463        .filter(|v| !v.trim().is_empty())
464        .or_else(|| config().shell_hook_mode.clone())
465        .unwrap_or_default()
466}
467
468/// `LEAN_CTX_ALLOWLIST_WARN_ONLY`: the test/debug opt-out of the CLI gate.
469#[must_use]
470pub fn cli_warn_only_requested() -> bool {
471    env("LEAN_CTX_ALLOWLIST_WARN_ONLY").is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
472}
473
474#[cfg(test)]
475mod tests {
476    use super::*;
477
478    #[test]
479    fn real_user_home_ignores_home_env() {
480        let _lock = crate::core::data_dir::test_env_lock();
481        let before = real_user_home();
482        let _home = crate::test_env::VarGuard::set("HOME", "/tmp/forged-home");
483        assert_eq!(real_user_home(), before);
484        assert_ne!(
485            real_user_home().as_deref(),
486            Some(Path::new("/tmp/forged-home"))
487        );
488    }
489
490    #[test]
491    fn pinned_source_ignores_env_and_relocated_config() {
492        let _lock = crate::core::data_dir::test_env_lock();
493        let real = tempfile::tempdir().unwrap();
494        let forged = tempfile::tempdir().unwrap();
495        std::fs::create_dir_all(forged.path().join(".config/lean-ctx")).unwrap();
496        std::fs::write(
497            forged.path().join(".config/lean-ctx/config.toml"),
498            "shell_security = \"off\"\nshell_allow_inline_scripts = true\n",
499        )
500        .unwrap();
501        let _pin = pin_for_test(real.path());
502        let _a = crate::test_env::VarGuard::set("LEAN_CTX_SHELL_SECURITY", "off");
503        let _b = crate::test_env::VarGuard::set("LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS", "1");
504        let _c = crate::test_env::VarGuard::set("HOME", forged.path());
505        let _d = crate::test_env::VarGuard::set("LEAN_CTX_CONFIG_DIR", forged.path());
506        assert_eq!(env("LEAN_CTX_SHELL_SECURITY"), None);
507        assert!(!allow_inline_scripts());
508        assert_eq!(config().shell_security, None);
509        assert_eq!(
510            config_path(),
511            Some(real.path().join(".config/lean-ctx/config.toml"))
512        );
513    }
514
515    /// `passwd` homes are Unix paths; on Windows `/home/jdoe` is not absolute
516    /// (and the parser only runs on Linux).
517    #[cfg(unix)]
518    #[test]
519    fn gh2236_passwd_line_yields_the_home_of_this_uid_only() {
520        let line = b"jdoe:*:123456:100:J Doe:/home/jdoe:/bin/bash\n";
521        assert_eq!(
522            parse_passwd_home(line, 123_456),
523            Some(PathBuf::from("/home/jdoe"))
524        );
525        // A line for another uid, a relative home, a short line, a
526        // non-numeric uid and empty output are all refused.
527        assert_eq!(parse_passwd_home(line, 1000), None);
528        assert_eq!(parse_passwd_home(b"jdoe:*:7:7::home/jdoe:/bin/sh", 7), None);
529        assert_eq!(parse_passwd_home(b"jdoe:*:7:7::", 7), None);
530        assert_eq!(
531            parse_passwd_home(b"jdoe:*:x7:7::/home/jdoe:/bin/sh", 7),
532            None
533        );
534        assert_eq!(parse_passwd_home(b"", 7), None);
535        // Only the first line counts.
536        assert_eq!(
537            parse_passwd_home(b"a:*:8:8::/home/a:/bin/sh\nb:*:7:7::/home/b:/bin/sh", 7),
538            None
539        );
540    }
541
542    /// The real `getent` path (fixed program, owner check, spawn, wait)
543    /// agrees with the account database wherever both answer.
544    #[cfg(target_os = "linux")]
545    #[test]
546    fn gh2236_getent_agrees_with_the_account_database() {
547        // SAFETY: geteuid only reads this process identity.
548        let uid = unsafe { libc::geteuid() };
549        if let (Some(getent), Some(passwd)) = (getent_home(uid), passwd_home(uid)) {
550            assert_eq!(getent, passwd);
551        }
552    }
553
554    #[test]
555    fn gh2236_unresolvable_pin_reads_defaults_and_names_no_config() {
556        let _lock = crate::core::data_dir::test_env_lock();
557        let _pin = pin_unresolvable_for_test();
558        assert!(pinned());
559        assert_eq!(config_path(), None);
560        assert_eq!(settings_home(), None);
561        assert_eq!(config().shell_security, None);
562        let shown = config_path_display();
563        assert!(shown.contains("no account-database entry"), "{shown}");
564        assert!(!shown.contains("~/.lean-ctx"), "{shown}");
565    }
566
567    #[test]
568    fn pinned_source_reads_the_real_home_config() {
569        let _lock = crate::core::data_dir::test_env_lock();
570        let real = tempfile::tempdir().unwrap();
571        std::fs::create_dir_all(real.path().join(".config/lean-ctx")).unwrap();
572        std::fs::write(
573            real.path().join(".config/lean-ctx/config.toml"),
574            "shell_security = \"warn\"\n",
575        )
576        .unwrap();
577        let _pin = pin_for_test(real.path());
578        assert_eq!(config().shell_security.as_deref(), Some("warn"));
579    }
580}