1use std::path::{Path, PathBuf};
43use std::sync::{Arc, Mutex, OnceLock};
44
45use super::{Config, ShellApproval};
46
47enum Source {
49 #[cfg_attr(
51 not(any(test, debug_assertions, feature = "test-support")),
52 allow(dead_code)
53 )]
54 Ambient,
55 #[cfg_attr(all(debug_assertions, not(test)), allow(dead_code))]
58 Pinned(Option<PathBuf>),
59}
60
61#[cfg(any(test, feature = "test-support"))]
63#[derive(Clone)]
64enum TestPin {
65 Home(PathBuf),
67 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 #[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#[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#[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#[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#[must_use]
148pub fn pinned() -> bool {
149 matches!(source(), Source::Pinned(_))
150}
151
152#[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 let uid = unsafe { libc::geteuid() };
166 #[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#[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 let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
191 let mut result: *mut libc::passwd = std::ptr::null_mut();
192 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 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#[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 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#[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#[cfg(not(unix))]
295fn lookup_real_user_home() -> Option<PathBuf> {
296 dirs::home_dir().filter(|p| p.is_absolute())
297}
298
299#[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
314fn 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#[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#[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#[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 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 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
407fn 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#[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#[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#[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#[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#[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#[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 #[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 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 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 #[cfg(target_os = "linux")]
545 #[test]
546 fn gh2236_getent_agrees_with_the_account_database() {
547 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}