Skip to main content

lean_ctx/shell/
redact.rs

1//! Tee logging for shell output.
2//!
3//! Secret masking is delegated to [`crate::core::redaction`] — the single
4//! source of truth shared with `ctx_read` redaction — so the regex set can
5//! never drift between the two layers again (it used to be a hand-copied
6//! duplicate). `save_tee` then runs the config-driven secret scanner on top
7//! for defense in depth.
8
9pub fn save_tee(command: &str, output: &str) -> Option<String> {
10    // Shell output has no complete source authority; do not create a protected
11    // recovery copy or advertise a handle that cannot be reauthorized.
12    if crate::core::policy::runtime::is_active() {
13        return None;
14    }
15    // Inspect both content and filename inputs before any recovery copy exists.
16    let command = crate::core::policy::content::protect_active(command).ok()?;
17    let output = crate::core::policy::content::protect_active(output).ok()?;
18    let command = command.as_ref();
19    let output = output.as_ref();
20    let tee_dir = crate::core::paths::state_dir().ok()?.join("tee");
21    // Owner-only (0700 on Unix): log names reveal which commands ran. An
22    // existing, wider directory is tightened on the next write.
23    crate::core::secure_fs::private_dir(&tee_dir).ok()?;
24
25    // #950: cleanup is an O(N) read_dir + per-file metadata() scan of the
26    // whole tee directory. Running it on every save_tee (i.e. every
27    // compressed shell call) means its cost scales with directory size on
28    // every single invocation under heavy shell activity. Entries already
29    // carry a 24h TTL, so throttling the scan to once per interval is enough
30    // to keep the directory bounded without paying the O(N) cost every time.
31    if let Ok(now) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)
32        && TEE_CLEANUP_THROTTLE.is_due(now.as_secs())
33    {
34        cleanup_old_tee_logs(&tee_dir);
35    }
36
37    let cmd_slug: String = command
38        .chars()
39        .take(40)
40        .map(|c| {
41            if c.is_alphanumeric() || c == '-' {
42                c
43            } else {
44                '_'
45            }
46        })
47        .collect();
48    // Content-addressed path (#498): the same command always maps to the same
49    // file, so repeated tool outputs stay byte-identical (provider prompt
50    // caches reward stable text). Re-runs overwrite — newest output wins;
51    // the 24h TTL cleanup works on mtime, not the filename.
52    let cmd_hash = blake3::hash(command.as_bytes()).to_hex();
53    let filename = format!("{cmd_slug}_{}.log", &cmd_hash.as_str()[..8]);
54    let path = tee_dir.join(&filename);
55
56    crate::core::ccr::write_tee(&path, output)?;
57    let handle = path.to_string_lossy().to_string();
58    crate::core::relevance_tracker::register_compressed(
59        handle.clone(),
60        output,
61        "ctx_shell",
62        crate::core::tokens::count_tokens(output),
63        0,
64    );
65    Some(handle)
66}
67
68/// Lock-free gate that lets [`cleanup_old_tee_logs`]'s directory scan run at
69/// most once per `interval_secs`, no matter how many `save_tee` calls land
70/// concurrently. Only the caller whose compare-exchange wins gets `true`.
71struct CleanupThrottle {
72    last_run_unix_secs: std::sync::atomic::AtomicU64,
73    interval_secs: u64,
74}
75
76impl CleanupThrottle {
77    const fn new(interval_secs: u64) -> Self {
78        Self {
79            last_run_unix_secs: std::sync::atomic::AtomicU64::new(0),
80            interval_secs,
81        }
82    }
83
84    /// `0` means "never run" and is always due, regardless of `now_unix_secs`
85    /// — avoids the throttle depending on `now` being a large real epoch time.
86    fn is_due(&self, now_unix_secs: u64) -> bool {
87        use std::sync::atomic::Ordering;
88        let last = self.last_run_unix_secs.load(Ordering::Relaxed);
89        let due = last == 0 || now_unix_secs.saturating_sub(last) >= self.interval_secs;
90        due && self
91            .last_run_unix_secs
92            .compare_exchange(last, now_unix_secs, Ordering::Relaxed, Ordering::Relaxed)
93            .is_ok()
94    }
95}
96
97static TEE_CLEANUP_THROTTLE: CleanupThrottle = CleanupThrottle::new(10 * 60);
98
99/// Removes tee log entries older than 24h. Throttled by [`TEE_CLEANUP_THROTTLE`]
100/// (called from `save_tee`) rather than run on every call — the read_dir +
101/// per-file metadata() scan is O(N) in directory size.
102pub(crate) fn cleanup_old_tee_logs(tee_dir: &std::path::Path) {
103    let cutoff = std::time::SystemTime::now().checked_sub(std::time::Duration::from_hours(24));
104    let Some(cutoff) = cutoff else { return };
105
106    if let Ok(entries) = std::fs::read_dir(tee_dir) {
107        for entry in entries.flatten() {
108            if let Ok(meta) = entry.metadata()
109                && let Ok(modified) = meta.modified()
110                && modified < cutoff
111            {
112                let _ = std::fs::remove_file(entry.path());
113            }
114        }
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    // --- #950: tee cleanup throttle ---
123
124    #[test]
125    fn cleanup_throttle_gates_by_interval() {
126        let throttle = CleanupThrottle::new(600);
127        assert!(
128            throttle.is_due(1_000),
129            "never run before: first call is always due"
130        );
131        assert!(
132            !throttle.is_due(1_100),
133            "only 100s elapsed of a 600s interval"
134        );
135        assert!(!throttle.is_due(1_599), "still short of the interval by 1s");
136        assert!(
137            throttle.is_due(1_600),
138            "exactly interval-elapsed must be due again"
139        );
140    }
141
142    #[test]
143    fn cleanup_throttle_lets_only_one_racer_through_per_interval() {
144        let throttle = CleanupThrottle::new(600);
145        let hits = std::thread::scope(|scope| {
146            let handles: Vec<_> = (0..16)
147                .map(|_| scope.spawn(|| throttle.is_due(1_000)))
148                .collect();
149            handles
150                .into_iter()
151                .map(|h| h.join().unwrap())
152                .filter(|&due| due)
153                .count()
154        });
155        assert_eq!(hits, 1, "exactly one racer should win the cleanup slot");
156    }
157
158    /// Determinism contract (#498): the tee path must be content-addressed —
159    /// the same command always maps to the same file so repeated tool outputs
160    /// stay byte-identical for provider prompt caching.
161    #[test]
162    fn tee_path_is_content_addressed() {
163        // Serialize against tests that repoint LEAN_CTX_DATA_DIR (isolated_data_dir);
164        // without the lock the resolved tee base races and the paths diverge.
165        let _lock = crate::core::data_dir::test_env_lock();
166        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
167        let first = save_tee("cargo test --lib", "output run 1").expect("tee saved");
168        let second = save_tee("cargo test --lib", "output run 2").expect("tee saved");
169        assert_eq!(first, second, "same command must map to the same tee path");
170
171        let other = save_tee("cargo build", "output").expect("tee saved");
172        assert_ne!(first, other, "different commands get different tee paths");
173
174        // Latest output wins on overwrite.
175        let content = std::fs::read_to_string(&second).unwrap();
176        assert!(content.contains("run 2"));
177
178        for p in [first, other] {
179            let _ = std::fs::remove_file(p);
180        }
181    }
182
183    /// The tee directory is created owner-only, and an existing wider one is
184    /// tightened on the next write; the log itself stays 0600.
185    #[cfg(unix)]
186    #[test]
187    fn tee_dir_is_owner_only() {
188        use std::os::unix::fs::PermissionsExt as _;
189        let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
190        let _isolated = crate::core::data_dir::isolated_data_dir();
191        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
192
193        let log = std::path::PathBuf::from(save_tee("echo tee-perms", "out").expect("tee saved"));
194        let dir = log.parent().unwrap().to_path_buf();
195        assert_eq!(mode(&dir), 0o700, "new tee dir must be owner-only");
196        assert_eq!(mode(&log), 0o600, "tee log must be owner-only");
197
198        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
199        save_tee("echo tee-perms", "out 2").expect("tee saved");
200        assert_eq!(mode(&dir), 0o700, "existing wide tee dir must be tightened");
201    }
202}