Skip to main content

lean_ctx_ext/core/
security_posture.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Unified, human-facing view of lean-ctx's **two independent security planes**:
3//!
4//! 1. **Containment** — the path jail + shell-command gating. Protects *the
5//!    machine from the agent* (what files a tool may touch, what binaries the
6//!    shell may run).
7//! 2. **Secret-exfiltration defense** — secret/`.env` redaction. Protects *your
8//!    secrets from the LLM provider* (API keys masked before they reach the
9//!    model).
10//!
11//! These are orthogonal by design: a usability-first user can drop containment
12//! (`lean-ctx yolo`) while still never leaking credentials to the provider, and
13//! vice-versa. This module is the single source of truth both the
14//! `lean-ctx security` command and `lean-ctx doctor` read from, so the CLI
15//! status screen and the doctor board can never disagree.
16//!
17//! It is a **pure read** of config + env (no side effects), which keeps it cheap
18//! to call and safe to use inside deterministic output paths.
19
20use crate::core::config::Config;
21use crate::core::shell_allowlist::ShellSecurity;
22use std::path::Path;
23
24/// Effective state of the filesystem path jail.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum JailState {
27    /// Fully enforced: tools are confined to the project root (+ any configured
28    /// `allow_paths`/`extra_roots`), with no blanket relaxation active.
29    Enforced,
30    /// Enforced, but widened by one or more knobs (e.g. `LEAN_CTX_ALLOW_PATH`,
31    /// `extra_roots`, IDE-config dirs). Carries the source labels for display.
32    Relaxed(Vec<String>),
33    /// Disabled outright — every tool path is allowed. Carries the knob that
34    /// turned it off (`path_jail = false`, the `no-jail` build, or
35    /// `allow_paths = ["/"]`).
36    Disabled(String),
37    /// Bound to a launcher Workspace (#2120): only its roots, regardless of
38    /// every widening knob and off-switch. Carries the binding for display.
39    Workspace(String),
40}
41
42impl JailState {
43    /// True when containment over the filesystem is effectively gone.
44    #[must_use]
45    pub fn is_disabled(&self) -> bool {
46        matches!(self, JailState::Disabled(_))
47    }
48}
49
50/// Coarse, derived label summarising the whole posture for at-a-glance display.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum PostureLevel {
53    /// Both containment planes fully enforced (the secure default).
54    Strict,
55    /// Partially relaxed (e.g. jail widened, or shell in `warn`).
56    Relaxed,
57    /// Containment fully off (`yolo`) — jail disabled *and* shell gating off.
58    Open,
59}
60
61impl PostureLevel {
62    /// Lower-case, stable name (used in status output and tests).
63    #[must_use]
64    pub fn as_str(self) -> &'static str {
65        match self {
66            PostureLevel::Strict => "strict",
67            PostureLevel::Relaxed => "relaxed",
68            PostureLevel::Open => "open",
69        }
70    }
71}
72
73/// A snapshot of every security-relevant switch, resolved exactly the way the
74/// runtime enforces it (env → config → secure default).
75#[derive(Debug, Clone)]
76pub struct SecurityPosture {
77    /// Filesystem path-jail state.
78    pub jail: JailState,
79    /// Shell-command gating mode.
80    pub shell: ShellSecurity,
81    /// Whether secret/`.env` detection runs on tool output.
82    pub secrets_enabled: bool,
83    /// Whether detected secrets are actually masked (vs only flagged).
84    pub secrets_redact: bool,
85}
86
87impl SecurityPosture {
88    /// Resolve the live posture from config + env. Pure read, no side effects.
89    #[must_use]
90    pub fn detect() -> Self {
91        let cfg = Config::load();
92        Self {
93            jail: detect_jail(&cfg),
94            shell: ShellSecurity::resolve(),
95            secrets_enabled: cfg.secret_detection.enabled,
96            secrets_redact: cfg.secret_detection.redact,
97        }
98    }
99
100    /// Derived coarse label. `Open` only when *both* containment planes are off,
101    /// so it precisely reflects what `lean-ctx yolo` produces.
102    #[must_use]
103    pub fn level(&self) -> PostureLevel {
104        let containment_off = self.jail.is_disabled() && self.shell == ShellSecurity::Off;
105        if containment_off {
106            return PostureLevel::Open;
107        }
108        let strict = matches!(self.jail, JailState::Enforced | JailState::Workspace(_))
109            && self.shell == ShellSecurity::Enforce;
110        if strict {
111            PostureLevel::Strict
112        } else {
113            PostureLevel::Relaxed
114        }
115    }
116
117    /// True when secrets still cannot leak to the provider (detection + masking
118    /// both on). This stays independent of [`Self::level`] on purpose.
119    #[must_use]
120    pub fn secrets_protected(&self) -> bool {
121        self.secrets_enabled && self.secrets_redact
122    }
123}
124
125/// Mirror of the precedence in `pathjail` + the doctor `path_jail_outcome`, kept
126/// here as the single classifier so CLI and doctor agree on what "disabled"
127/// means.
128fn detect_jail(cfg: &Config) -> JailState {
129    match crate::core::workspace_authority::load_current() {
130        crate::core::workspace_authority::Authority::Legacy => {}
131        crate::core::workspace_authority::Authority::Workspace(snapshot) => {
132            return JailState::Workspace(format!(
133                "Workspace {} rev {}",
134                snapshot.id, snapshot.revision
135            ));
136        }
137        crate::core::workspace_authority::Authority::Unavailable(_) => {
138            return JailState::Workspace("Workspace unavailable — every path denied".to_string());
139        }
140    }
141    if cfg!(feature = "no-jail") {
142        return JailState::Disabled("no-jail build feature".to_string());
143    }
144    if cfg.path_jail == Some(false) {
145        return JailState::Disabled("path_jail = false".to_string());
146    }
147    // `allow_paths`/`extra_roots` containing "/" is a prefix of everything, so
148    // it grants blanket access just like `path_jail = false` (GH #392).
149    let grants_everything = cfg
150        .allow_paths
151        .iter()
152        .chain(cfg.extra_roots.iter())
153        .any(|raw| crate::core::pathjail::expand_user_path(raw) == Path::new("/"));
154    if grants_everything {
155        return JailState::Disabled("allow_paths contains \"/\"".to_string());
156    }
157
158    // Remaining relaxations (env channels, IDE-config dirs) only *widen* the
159    // jail; the full-disable sources above are handled by the early returns.
160    let relaxed: Vec<String> = crate::core::pathjail::active_relaxations()
161        .into_iter()
162        .map(|r| r.source.to_string())
163        .collect();
164    if relaxed.is_empty() {
165        JailState::Enforced
166    } else {
167        JailState::Relaxed(relaxed)
168    }
169}
170
171#[cfg(test)]
172pub mod tests {
173    use super::*;
174
175    fn posture(
176        jail: JailState,
177        shell: ShellSecurity,
178        secrets: bool,
179        redact: bool,
180    ) -> SecurityPosture {
181        SecurityPosture {
182            jail,
183            shell,
184            secrets_enabled: secrets,
185            secrets_redact: redact,
186        }
187    }
188
189    #[test]
190    fn level_strict_when_both_planes_enforced() {
191        let p = posture(JailState::Enforced, ShellSecurity::Enforce, true, true);
192        assert_eq!(p.level(), PostureLevel::Strict);
193    }
194
195    #[test]
196    fn level_open_only_when_jail_disabled_and_shell_off() {
197        let p = posture(
198            JailState::Disabled("path_jail = false".into()),
199            ShellSecurity::Off,
200            true,
201            true,
202        );
203        assert_eq!(p.level(), PostureLevel::Open);
204    }
205
206    #[test]
207    fn level_relaxed_when_only_one_plane_dropped() {
208        // Jail off but shell still enforcing → not fully open.
209        let jail_only = posture(
210            JailState::Disabled("path_jail = false".into()),
211            ShellSecurity::Enforce,
212            true,
213            true,
214        );
215        assert_eq!(jail_only.level(), PostureLevel::Relaxed);
216
217        // Shell off but jail enforced → not fully open.
218        let shell_only = posture(JailState::Enforced, ShellSecurity::Off, true, true);
219        assert_eq!(shell_only.level(), PostureLevel::Relaxed);
220
221        // Jail merely widened (not disabled) → relaxed.
222        let widened = posture(
223            JailState::Relaxed(vec!["LEAN_CTX_ALLOW_PATH".into()]),
224            ShellSecurity::Enforce,
225            true,
226            true,
227        );
228        assert_eq!(widened.level(), PostureLevel::Relaxed);
229    }
230
231    #[test]
232    fn secrets_protection_is_independent_of_containment() {
233        // Fully open containment, yet secrets are still protected.
234        let open_but_secret_safe = posture(
235            JailState::Disabled("path_jail = false".into()),
236            ShellSecurity::Off,
237            true,
238            true,
239        );
240        assert_eq!(open_but_secret_safe.level(), PostureLevel::Open);
241        assert!(open_but_secret_safe.secrets_protected());
242
243        // Strict containment, yet redaction explicitly turned off.
244        let strict_but_leaky = posture(JailState::Enforced, ShellSecurity::Enforce, false, true);
245        assert_eq!(strict_but_leaky.level(), PostureLevel::Strict);
246        assert!(!strict_but_leaky.secrets_protected());
247    }
248
249    #[test]
250    fn jail_state_is_disabled_helper() {
251        assert!(JailState::Disabled("x".into()).is_disabled());
252        assert!(!JailState::Enforced.is_disabled());
253        assert!(!JailState::Relaxed(vec!["y".into()]).is_disabled());
254    }
255
256    #[test]
257    fn posture_level_names_are_stable() {
258        assert_eq!(PostureLevel::Strict.as_str(), "strict");
259        assert_eq!(PostureLevel::Relaxed.as_str(), "relaxed");
260        assert_eq!(PostureLevel::Open.as_str(), "open");
261    }
262}