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