Skip to main content

lean_ctx_ext/core/
agent_runtime_env.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Bridge agent runtime/session environment variables across lean-ctx processes.
3//!
4//! The lean-ctx MCP server is a long-lived child of the agent host. Some agents
5//! (notably Codex) expose runtime/session variables such as `CODEX_THREAD_ID`
6//! only in the *native agent shell* environment, not in the MCP server process
7//! (#370). `ctx_shell` runs inside the MCP server, so it cannot forward those
8//! variables by reading its own `std::env`.
9//!
10//! Short-lived lean-ctx processes that *do* run inside the agent environment —
11//! the hook handlers (`lean-ctx hook …`) and the `lean-ctx -c` shell wrapper —
12//! [`capture`] the relevant variables into a small file in the data dir. The MCP
13//! server then [`load`]s them when constructing the child environment for
14//! `ctx_shell` (see `server::execute`).
15
16use std::collections::BTreeMap;
17use std::path::{Path, PathBuf};
18
19/// Env var name prefixes identifying agent runtime/session state worth forwarding
20/// to `ctx_shell` child processes.
21pub(crate) const FORWARD_PREFIXES: &[&str] = &[
22    "CODEX_",
23    "CLAUDE_",
24    "CODEBUDDY_",
25    "OPENCODE_",
26    "HERMES_",
27    "GEMINI_",
28];
29
30/// Case-insensitive name substrings that mark an env var as credential-shaped.
31///
32/// A variable whose name contains any of these is NEVER forwarded to `ctx_shell`
33/// children — and never captured to disk — even when it matches a forwardable
34/// prefix. Forwarding API keys / tokens / passwords into every child shell is an
35/// exfiltration risk that output redaction cannot stop: a `curl … -d "$KEY"`
36/// child never prints the secret to stdout, so the redactor never sees it (GH
37/// security audit, finding 2). Only non-secret session/thread identifiers
38/// (`*_THREAD_ID`, `*_SESSION`, …) should cross the bridge.
39const CREDENTIAL_MARKERS: &[&str] = &[
40    "_KEY",       // *_API_KEY, *_ACCESS_KEY, *_PRIVATE_KEY, *_SECRET_KEY
41    "APIKEY",     // unseparated spelling
42    "SECRET",     // *_SECRET, *_CLIENT_SECRET
43    "TOKEN",      // *_TOKEN, *_ACCESS_TOKEN, *_REFRESH_TOKEN
44    "PASSWORD",   // *_PASSWORD, *_SERVER_PASSWORD
45    "PASSWD",     // unseparated spelling
46    "CREDENTIAL", // *_CREDENTIAL(S)
47    "AUTH",       // *_AUTH, *_OAUTH, *_AUTHORIZATION
48];
49
50/// Whether `key` looks like a secret/credential that must never be forwarded or
51/// persisted, regardless of any matching forwardable prefix.
52#[must_use]
53pub(crate) fn is_credential_shaped(key: &str) -> bool {
54    let upper = key.to_ascii_uppercase();
55    CREDENTIAL_MARKERS
56        .iter()
57        .any(|marker| upper.contains(marker))
58}
59
60const FILE_NAME: &str = "agent_runtime_env.json";
61
62/// Captured variables older than this are ignored: a stale session/thread id is
63/// worse than forwarding none, and a fresh session re-captures on its first hook.
64const TTL_SECS: u64 = 7_200;
65
66/// Whether `key` is an agent runtime variable lean-ctx forwards to child shells.
67///
68/// A variable qualifies only when it (1) matches a forwardable agent prefix AND
69/// (2) is not credential-shaped — session/thread identifiers cross the bridge,
70/// secrets never do (GH security audit, finding 2).
71#[must_use]
72pub fn is_forwardable(key: &str) -> bool {
73    FORWARD_PREFIXES
74        .iter()
75        .any(|prefix| key.starts_with(prefix))
76        && !is_credential_shaped(key)
77}
78
79/// Canonical capture-file location: the STATE dir (GH #408 / GL #605).
80///
81/// This file holds captured agent **session/thread identifiers** (e.g.
82/// `CODEX_THREAD_ID`); credential-shaped vars are filtered out by
83/// [`is_forwardable`] and never written here (GH security audit, finding 2). It
84/// still lives in the RW state category — never the RO/shareable config dir —
85/// and is always written `0o600` as defence-in-depth.
86fn store_path() -> Option<PathBuf> {
87    crate::core::paths::state_dir()
88        .ok()
89        .map(|dir| dir.join(FILE_NAME))
90}
91
92/// Legacy location: the file historically lived in the (config-shaped) data dir.
93/// Used only to migrate existing captures into [`store_path`].
94fn legacy_store_path() -> Option<PathBuf> {
95    crate::core::data_dir::lean_ctx_data_dir()
96        .ok()
97        .map(|dir| dir.join(FILE_NAME))
98}
99
100/// Relocate a pre-#408 key file from the data dir into the state dir, and never
101/// leave captured keys behind in the config-shaped legacy location.
102///
103/// Idempotent and a no-op in single-dir mode (where state == legacy). Safe to
104/// call on every access: the existence checks make the steady state one `stat`.
105fn migrate_legacy_key_file(state_path: &Path) {
106    let Some(legacy) = legacy_store_path() else {
107        return;
108    };
109    if legacy == *state_path || !legacy.exists() {
110        return;
111    }
112    if state_path.exists() {
113        // A state-dir copy already exists; drop the stale legacy file so keys
114        // never linger in the config-shaped data dir.
115        let _ = std::fs::remove_file(&legacy);
116        return;
117    }
118    if let Some(parent) = state_path.parent() {
119        let _ = std::fs::create_dir_all(parent);
120    }
121    if std::fs::rename(&legacy, state_path).is_err() {
122        // Cross-filesystem move: copy then remove the original.
123        if std::fs::copy(&legacy, state_path).is_ok() {
124            let _ = std::fs::remove_file(&legacy);
125        } else {
126            return;
127        }
128    }
129    restrict_key_file_permissions(state_path);
130}
131
132#[cfg(unix)]
133fn restrict_key_file_permissions(path: &Path) {
134    use std::os::unix::fs::PermissionsExt;
135    let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
136}
137
138#[cfg(not(unix))]
139fn restrict_key_file_permissions(_path: &Path) {}
140
141fn now_secs() -> u64 {
142    std::time::SystemTime::now()
143        .duration_since(std::time::UNIX_EPOCH)
144        .unwrap_or_default()
145        .as_secs()
146}
147
148/// Forwardable variables present in the current process environment.
149#[must_use]
150pub(crate) fn collect_from_process() -> BTreeMap<String, String> {
151    std::env::vars()
152        .filter(|(key, _)| is_forwardable(key))
153        .collect()
154}
155
156fn read_store(path: &Path) -> Option<(BTreeMap<String, String>, u64)> {
157    let content = std::fs::read_to_string(path).ok()?;
158    let value: serde_json::Value = serde_json::from_str(&content).ok()?;
159    let captured_at = value
160        .get("captured_at")
161        .and_then(serde_json::Value::as_u64)?;
162    let vars = value
163        .get("vars")
164        .and_then(serde_json::Value::as_object)?
165        .iter()
166        .filter_map(|(key, val)| val.as_str().map(|s| (key.clone(), s.to_string())))
167        .collect();
168    Some((vars, captured_at))
169}
170
171/// Capture forwardable variables from the current (agent) environment into the
172/// data dir so the MCP server can forward them to `ctx_shell` children.
173///
174/// No-op when the current environment carries no forwardable variables — this
175/// prevents a process with a stripped environment (e.g. the MCP server itself)
176/// from clobbering a good capture. The file is only rewritten when the variable
177/// set actually changes, keeping the cost of capturing on every shell command low.
178pub fn capture() {
179    let vars = collect_from_process();
180    if vars.is_empty() {
181        return;
182    }
183    let Some(path) = store_path() else {
184        return;
185    };
186    migrate_legacy_key_file(&path);
187    if let Some((existing, _)) = read_store(&path)
188        && existing == vars
189    {
190        return;
191    }
192    let payload = serde_json::json!({ "vars": vars, "captured_at": now_secs() });
193    let Ok(json) = serde_json::to_string_pretty(&payload) else {
194        return;
195    };
196    // Atomic write + `0o600` (owner-only): captured keys must never be
197    // group/world-readable. `write_atomic` also rejects symlinks and creates
198    // the state dir if needed.
199    let _ = crate::config_io::write_atomic(&path, &json);
200}
201
202/// Load captured agent runtime variables, honoring the freshness TTL.
203///
204/// When no valid capture exists, falls back to probing the parent process's
205/// environment (#800). This covers the case where the lean-ctx MCP server was
206/// spawned by an agent that sets runtime vars only in native shell commands
207/// (e.g. Codex with CODEX_THREAD_ID) without going through `lean-ctx -c` first.
208#[must_use]
209pub fn load() -> BTreeMap<String, String> {
210    let Some(path) = store_path() else {
211        return BTreeMap::new();
212    };
213    migrate_legacy_key_file(&path);
214    let Some((vars, captured_at)) = read_store(&path) else {
215        // No capture file — try probing the parent process environment (#800).
216        let probed = probe_parent_env();
217        if !probed.is_empty() {
218            persist_probed_vars(&path, &probed);
219        }
220        return probed;
221    };
222    if now_secs().saturating_sub(captured_at) > TTL_SECS {
223        return BTreeMap::new();
224    }
225    // Defense-in-depth: a capture written by a build predating finding 2 may
226    // still hold credential-shaped vars. Drop them from the returned set, and if
227    // any were present rewrite (or delete) the file so the plaintext secret does
228    // not linger at rest — not just out of the forwarded env.
229    let cleaned: BTreeMap<String, String> = vars
230        .iter()
231        .filter(|(key, _)| is_forwardable(key))
232        .map(|(key, val)| (key.clone(), val.clone()))
233        .collect();
234    if cleaned.len() != vars.len() {
235        scrub_store(&path, &cleaned, captured_at);
236    }
237    cleaned
238}
239
240/// Probe the parent process's environment for forwardable agent runtime
241/// variables (#800). On Linux reads `/proc/<ppid>/environ`; on macOS uses
242/// `ps eww`. Returns only non-credential forwardable vars.
243fn probe_parent_env() -> BTreeMap<String, String> {
244    let ppid = parent_pid();
245    if ppid == 0 {
246        return BTreeMap::new();
247    }
248    let raw_env = read_parent_environ(ppid);
249    raw_env
250        .into_iter()
251        .filter(|(key, _)| is_forwardable(key))
252        .collect()
253}
254
255fn parent_pid() -> u32 {
256    #[cfg(unix)]
257    {
258        // SAFETY: getppid() is always safe — it reads the kernel's ppid for
259        // the calling process, has no side effects, and cannot fail.
260        unsafe { libc::getppid() as u32 }
261    }
262    #[cfg(not(unix))]
263    {
264        0
265    }
266}
267
268/// Read environment variables from a process. On Linux, reads
269/// `/proc/<pid>/environ` (NUL-separated key=value pairs). On macOS, falls
270/// back to parsing `ps eww <pid>` output.
271fn read_parent_environ(pid: u32) -> BTreeMap<String, String> {
272    // Linux: /proc/<pid>/environ is most reliable
273    #[cfg(target_os = "linux")]
274    if let Ok(data) = std::fs::read(format!("/proc/{pid}/environ")) {
275        return parse_null_separated_env(&data);
276    }
277
278    // macOS/fallback: ps eww gives env in a less structured format
279    #[cfg(target_os = "macos")]
280    if let Ok(output) = std::process::Command::new("ps")
281        .args(["eww", "-o", "command", "-p", &pid.to_string()])
282        .output()
283        && output.status.success()
284    {
285        return parse_ps_environ(&String::from_utf8_lossy(&output.stdout));
286    }
287
288    let _ = pid;
289    BTreeMap::new()
290}
291
292#[cfg(target_os = "linux")]
293fn parse_null_separated_env(data: &[u8]) -> BTreeMap<String, String> {
294    data.split(|&b| b == 0)
295        .filter_map(|entry| {
296            let s = std::str::from_utf8(entry).ok()?;
297            let (key, val) = s.split_once('=')?;
298            Some((key.to_string(), val.to_string()))
299        })
300        .collect()
301}
302
303#[cfg(target_os = "macos")]
304fn parse_ps_environ(output: &str) -> BTreeMap<String, String> {
305    let mut result = BTreeMap::new();
306    for line in output.lines().skip(1) {
307        for token in line.split_whitespace() {
308            if let Some((key, val)) = token.split_once('=')
309                && FORWARD_PREFIXES
310                    .iter()
311                    .any(|prefix| key.starts_with(prefix))
312            {
313                result.insert(key.to_string(), val.to_string());
314            }
315        }
316    }
317    result
318}
319
320/// Create-only: a hook `capture()` can land while the (slow, `ps`-based) probe
321/// runs, and the probe must never replace it with the parent's older env.
322/// `create_new` is atomic against that race and refuses existing symlinks.
323fn persist_probed_vars(path: &Path, vars: &BTreeMap<String, String>) {
324    use std::io::Write;
325    let payload = serde_json::json!({ "vars": vars, "captured_at": now_secs() });
326    let Ok(json) = serde_json::to_string_pretty(&payload) else {
327        return;
328    };
329    if let Some(parent) = path.parent() {
330        let _ = std::fs::create_dir_all(parent);
331    }
332    let mut options = std::fs::OpenOptions::new();
333    options.write(true).create_new(true);
334    #[cfg(unix)]
335    {
336        use std::os::unix::fs::OpenOptionsExt;
337        options.mode(0o600);
338    }
339    if let Ok(mut file) = options.open(path) {
340        let _ = file.write_all(json.as_bytes());
341    }
342}
343
344/// Rewrite the capture file with `vars` (preserving `captured_at`), or remove it
345/// entirely when nothing forwardable remains. Retroactively strips
346/// credential-shaped vars from captures written by older builds (finding 2).
347fn scrub_store(path: &Path, vars: &BTreeMap<String, String>, captured_at: u64) {
348    if vars.is_empty() {
349        let _ = std::fs::remove_file(path);
350        return;
351    }
352    let payload = serde_json::json!({ "vars": vars, "captured_at": captured_at });
353    if let Ok(json) = serde_json::to_string_pretty(&payload) {
354        let _ = crate::config_io::write_atomic(path, &json);
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    #[test]
363    fn is_forwardable_matches_known_prefixes() {
364        assert!(is_forwardable("CODEX_THREAD_ID"));
365        assert!(is_forwardable("CLAUDE_SESSION"));
366        assert!(is_forwardable("OPENCODE_FOO"));
367        assert!(!is_forwardable("PATH"));
368        assert!(!is_forwardable("HOME"));
369        assert!(!is_forwardable("LEAN_CTX_DATA_DIR"));
370    }
371
372    #[test]
373    fn capture_then_load_roundtrips() {
374        let _iso = crate::core::data_dir::isolated_data_dir();
375        crate::test_env::set_var("CODEX_THREAD_ID", "thread-roundtrip");
376
377        capture();
378        let loaded = load();
379
380        crate::test_env::remove_var("CODEX_THREAD_ID");
381
382        assert_eq!(
383            loaded.get("CODEX_THREAD_ID").map(String::as_str),
384            Some("thread-roundtrip")
385        );
386    }
387
388    #[test]
389    fn probe_persist_never_replaces_a_concurrent_capture() {
390        let _iso = crate::core::data_dir::isolated_data_dir();
391        crate::test_env::set_var("CODEX_THREAD_ID", "thread-from-hook");
392        capture();
393        crate::test_env::remove_var("CODEX_THREAD_ID");
394
395        // A load() that saw no file before the capture finishes its probe now.
396        let probed = BTreeMap::from([("CLAUDE_PID".to_string(), "1".to_string())]);
397        persist_probed_vars(&store_path().unwrap(), &probed);
398
399        assert_eq!(
400            load().get("CODEX_THREAD_ID").map(String::as_str),
401            Some("thread-from-hook")
402        );
403    }
404
405    #[test]
406    fn capture_is_noop_without_forwardable_vars() {
407        let _iso = crate::core::data_dir::isolated_data_dir();
408        // Ensure no forwardable vars leak in from the host test environment.
409        for (key, _) in collect_from_process() {
410            crate::test_env::remove_var(key);
411        }
412
413        capture();
414        let exists = store_path().is_some_and(|p| p.exists());
415
416        assert!(!exists, "capture must not write a store with no vars");
417    }
418
419    #[test]
420    fn load_ignores_expired_capture() {
421        let _iso = crate::core::data_dir::isolated_data_dir();
422        let path = store_path().unwrap();
423        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
424
425        let stale = now_secs().saturating_sub(TTL_SECS + 60);
426        let payload =
427            serde_json::json!({ "vars": { "CODEX_THREAD_ID": "old" }, "captured_at": stale });
428        std::fs::write(&path, serde_json::to_string_pretty(&payload).unwrap()).unwrap();
429
430        let loaded = load();
431
432        assert!(loaded.is_empty(), "expired capture must not be loaded");
433    }
434
435    #[cfg(unix)]
436    #[test]
437    fn capture_sets_owner_only_permissions() {
438        use std::os::unix::fs::PermissionsExt;
439        let _iso = crate::core::data_dir::isolated_data_dir();
440        for (key, _) in collect_from_process() {
441            crate::test_env::remove_var(key);
442        }
443        // A forwardable (non-credential) var so a file is actually written; it
444        // can still hold session ids, so owner-only perms remain a requirement.
445        crate::test_env::set_var("CODEX_THREAD_ID", "session-id");
446
447        capture();
448        let path = store_path().unwrap();
449        crate::test_env::remove_var("CODEX_THREAD_ID");
450
451        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
452        assert_eq!(
453            mode & 0o777,
454            0o600,
455            "captured runtime-env file must be owner-only"
456        );
457    }
458
459    // Finding 2 (GH security audit): credential-shaped vars must never be
460    // forwarded, even when they match a forwardable agent prefix.
461    #[test]
462    fn is_forwardable_rejects_credential_shaped_vars() {
463        // Session/thread identifiers cross the bridge.
464        assert!(is_forwardable("CODEX_THREAD_ID"));
465        assert!(is_forwardable("CLAUDE_SESSION_ID"));
466        assert!(is_forwardable("OPENCODE_SESSION"));
467        // Secrets matching a forwardable prefix do NOT.
468        assert!(!is_forwardable("GEMINI_API_KEY"));
469        assert!(!is_forwardable("OPENCODE_API_KEY"));
470        assert!(!is_forwardable("OPENCODE_SERVER_PASSWORD"));
471        assert!(!is_forwardable("CLAUDE_CODE_OAUTH_TOKEN"));
472        assert!(!is_forwardable("CODEX_ACCESS_TOKEN"));
473        assert!(!is_forwardable("CODEX_CLIENT_SECRET"));
474        assert!(!is_forwardable("CODEX_PRIVATE_KEY"));
475        assert!(!is_forwardable("GEMINI_CREDENTIALS"));
476    }
477
478    #[test]
479    fn capture_excludes_credentials() {
480        let _iso = crate::core::data_dir::isolated_data_dir();
481        for (key, _) in collect_from_process() {
482            crate::test_env::remove_var(key);
483        }
484        crate::test_env::set_var("CODEX_THREAD_ID", "thread-keep");
485        crate::test_env::set_var("GEMINI_API_KEY", "secret-drop");
486
487        capture();
488        let loaded = load();
489
490        crate::test_env::remove_var("CODEX_THREAD_ID");
491        crate::test_env::remove_var("GEMINI_API_KEY");
492
493        assert_eq!(
494            loaded.get("CODEX_THREAD_ID").map(String::as_str),
495            Some("thread-keep")
496        );
497        assert!(
498            !loaded.contains_key("GEMINI_API_KEY"),
499            "API key must never be captured or forwarded"
500        );
501    }
502
503    #[test]
504    fn load_scrubs_legacy_credentials_from_disk() {
505        let _iso = crate::core::data_dir::isolated_data_dir();
506        let path = store_path().unwrap();
507        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
508
509        // Simulate a capture written by an older build: holds a real secret.
510        let payload = serde_json::json!({
511            "vars": { "CODEX_THREAD_ID": "t", "OPENCODE_SERVER_PASSWORD": "p4ssw0rd" },
512            "captured_at": now_secs()
513        });
514        std::fs::write(&path, serde_json::to_string_pretty(&payload).unwrap()).unwrap();
515
516        let loaded = load();
517
518        assert!(
519            !loaded.contains_key("OPENCODE_SERVER_PASSWORD"),
520            "legacy credential must not be loaded"
521        );
522        assert_eq!(loaded.get("CODEX_THREAD_ID").map(String::as_str), Some("t"));
523
524        // The plaintext secret must be scrubbed from disk, not just the env.
525        let on_disk = std::fs::read_to_string(&path).unwrap();
526        assert!(
527            !on_disk.contains("OPENCODE_SERVER_PASSWORD") && !on_disk.contains("p4ssw0rd"),
528            "secret must be removed from the capture file at rest: {on_disk}"
529        );
530    }
531
532    #[test]
533    fn store_path_is_under_state_dir_not_config_dir_when_split() {
534        let _lock = crate::core::data_dir::test_env_lock();
535        let state = tempfile::tempdir().unwrap();
536        let config = tempfile::tempdir().unwrap();
537        crate::test_env::set_var("LEAN_CTX_STATE_DIR", state.path());
538        crate::test_env::set_var("LEAN_CTX_CONFIG_DIR", config.path());
539
540        let path = store_path().unwrap();
541
542        crate::test_env::remove_var("LEAN_CTX_STATE_DIR");
543        crate::test_env::remove_var("LEAN_CTX_CONFIG_DIR");
544
545        assert!(
546            path.starts_with(state.path()),
547            "key file must live under the state dir: {}",
548            path.display()
549        );
550        assert!(
551            !path.starts_with(config.path()),
552            "key file must never resolve under the config dir"
553        );
554    }
555
556    #[test]
557    fn migrates_legacy_key_file_to_state_dir() {
558        let _lock = crate::core::data_dir::test_env_lock();
559        let data = tempfile::tempdir().unwrap();
560        let state = tempfile::tempdir().unwrap();
561        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data.path());
562        crate::test_env::set_var("LEAN_CTX_STATE_DIR", state.path());
563
564        let legacy = data.path().join(FILE_NAME);
565        let payload =
566            serde_json::json!({ "vars": { "GEMINI_API_KEY": "k" }, "captured_at": now_secs() });
567        std::fs::write(&legacy, serde_json::to_string_pretty(&payload).unwrap()).unwrap();
568
569        let state_path = store_path().unwrap();
570        migrate_legacy_key_file(&state_path);
571
572        let legacy_exists = legacy.exists();
573        let migrated = state_path.exists();
574        let parent_ok = state_path.parent() == Some(state.path());
575
576        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
577        crate::test_env::remove_var("LEAN_CTX_STATE_DIR");
578
579        assert!(migrated, "key file must be moved into the state dir");
580        assert!(!legacy_exists, "legacy key file must be removed after move");
581        assert!(
582            parent_ok,
583            "migrated file must sit directly in the state dir"
584        );
585    }
586
587    #[test]
588    fn removes_stale_legacy_when_state_copy_exists() {
589        let _lock = crate::core::data_dir::test_env_lock();
590        let data = tempfile::tempdir().unwrap();
591        let state = tempfile::tempdir().unwrap();
592        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data.path());
593        crate::test_env::set_var("LEAN_CTX_STATE_DIR", state.path());
594
595        let legacy = data.path().join(FILE_NAME);
596        std::fs::write(&legacy, "{}").unwrap();
597        let state_path = store_path().unwrap();
598        std::fs::write(&state_path, "{}").unwrap();
599
600        migrate_legacy_key_file(&state_path);
601
602        let legacy_exists = legacy.exists();
603        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
604        crate::test_env::remove_var("LEAN_CTX_STATE_DIR");
605
606        assert!(
607            !legacy_exists,
608            "stale legacy key file must be removed when a state copy exists"
609        );
610    }
611}