1use std::path::{Path, PathBuf};
41use std::sync::{Arc, Mutex, OnceLock};
42
43use super::{Config, ShellApproval};
44
45enum Source {
47 #[cfg_attr(not(any(test, debug_assertions)), allow(dead_code))]
49 Ambient,
50 #[cfg_attr(all(debug_assertions, not(test)), allow(dead_code))]
53 Pinned(Option<PathBuf>),
54}
55
56#[cfg(any(test, feature = "test-support"))]
58#[derive(Clone)]
59enum TestPin {
60 Home(PathBuf),
62 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#[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#[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#[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#[must_use]
140pub fn pinned() -> bool {
141 matches!(source(), Source::Pinned(_))
142}
143
144#[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 let uid = unsafe { libc::geteuid() };
158 #[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#[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 let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
183 let mut result: *mut libc::passwd = std::ptr::null_mut();
184 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 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#[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 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#[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#[cfg(not(unix))]
287fn lookup_real_user_home() -> Option<PathBuf> {
288 dirs::home_dir().filter(|p| p.is_absolute())
289}
290
291#[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
306fn 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#[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#[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#[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 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 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
399fn 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#[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#[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#[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#[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#[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#[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 #[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 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 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 #[cfg(target_os = "linux")]
537 #[test]
538 fn gh2236_getent_agrees_with_the_account_database() {
539 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}