Skip to main content

lean_ctx_server/tools/
server_paths.rs

1// SPDX-License-Identifier: Apache-2.0
2use super::server::LeanCtxServer;
3use super::startup::{
4    has_project_marker, is_suspicious_root, maybe_derive_project_root_from_absolute,
5};
6
7/// Bound on the filesystem probes that judge an adoption: a hung network
8/// mount refuses the adoption instead of stalling the call (same bound as
9/// the jail's own canonicalization).
10const ADOPTION_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
11
12/// Adoption probes still running on the blocking pool, timed out ones
13/// included. A probe stuck on a hung mount keeps its thread; past this bound
14/// no new probe starts and the adoption fails closed, so hung probes never
15/// pile up threads.
16const MAX_ADOPTION_PROBES: usize = 2;
17static ADOPTION_PROBES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18
19/// One in-flight probe; released when the probe's thread finishes.
20struct ProbeSlot;
21
22impl ProbeSlot {
23    fn take() -> Option<Self> {
24        use std::sync::atomic::Ordering;
25        ADOPTION_PROBES
26            .try_update(Ordering::AcqRel, Ordering::Acquire, |n| {
27                (n < MAX_ADOPTION_PROBES).then_some(n + 1)
28            })
29            .ok()
30            .map(|_| Self)
31    }
32}
33
34impl Drop for ProbeSlot {
35    fn drop(&mut self) {
36        ADOPTION_PROBES.fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
37    }
38}
39
40#[cfg(test)]
41tokio::task_local! {
42    /// Racing adoptions in a test meet at this barrier before the lock, once
43    /// per task.
44    pub(crate) static ADOPTION_BARRIER:
45        std::cell::RefCell<Option<std::sync::Arc<tokio::sync::Barrier>>>;
46}
47
48impl LeanCtxServer {
49    pub fn checkpoint_interval_effective() -> usize {
50        if let Ok(v) = std::env::var("LEAN_CTX_CHECKPOINT_INTERVAL")
51            && let Ok(parsed) = v.trim().parse::<usize>()
52        {
53            return parsed;
54        }
55        let profile_interval = lean_ctx::core::profiles::active_profile()
56            .autonomy
57            .checkpoint_interval_effective();
58        if profile_interval > 0 {
59            return profile_interval as usize;
60        }
61        lean_ctx::core::config::Config::load().checkpoint_interval as usize
62    }
63
64    /// Resolves a (possibly relative) tool path against the session's project_root.
65    /// Absolute paths and "." are returned as-is. Relative paths like "src/main.rs"
66    /// are joined with project_root so tools work regardless of the server's cwd.
67    pub async fn resolve_path(&self, path: &str) -> Result<String, String> {
68        self.resolve_path_refusing(path)
69            .await
70            .map_err(|refusal| refusal.message)
71    }
72
73    /// Records a classified boundary refusal once, with the calling `tool`:
74    /// its class only, never the path.
75    pub(crate) async fn record_path_refusal(
76        &self,
77        tool: &str,
78        refusal: &lean_ctx::core::path_resolve::PathRefusal,
79    ) {
80        let Some(class) = refusal.class else {
81            return;
82        };
83        let agent_id = self
84            .agent_id
85            .read()
86            .await
87            .clone()
88            .unwrap_or_else(|| "unknown".to_string());
89        lean_ctx::core::security_events::record_refusals(tool, &agent_id, class, 1);
90    }
91
92    /// [`Self::resolve_path`], saying which boundary refused the path. The
93    /// dispatch layer records a classified refusal once, with the calling
94    /// tool (the same path may be resolved again for planning).
95    pub(crate) async fn resolve_path_refusing(
96        &self,
97        path: &str,
98    ) -> Result<String, lean_ctx::core::path_resolve::PathRefusal> {
99        // A handler resolving a path dispatch did not pre-resolve (an array
100        // or non-string argument) does not know its tool here: an adoption
101        // it triggers is audited as `unknown`, never under a plausible name.
102        self.resolve_path_for_tool(path, "unknown").await
103    }
104
105    /// [`Self::resolve_path_refusing`] on behalf of the dispatching `tool`,
106    /// which a project adoption records in the audit trail.
107    pub(crate) async fn resolve_path_for_tool(
108        &self,
109        path: &str,
110        tool: &str,
111    ) -> Result<String, lean_ctx::core::path_resolve::PathRefusal> {
112        use lean_ctx::core::path_resolve::PathRefusal;
113        let normalized = lean_ctx::core::pathutil::normalize_tool_path(path);
114        if normalized.is_empty() || normalized == "." {
115            let root = self.session.read().await.project_root.clone();
116            return Ok(lean_ctx::core::workspace_authority::project_dot(
117                &normalized,
118                root.as_deref(),
119            )?);
120        }
121        let p = std::path::Path::new(&normalized);
122
123        let (resolved, jail_root, extra_roots) = {
124            let session = self.session.read().await;
125            let jail_root = session
126                .project_root
127                .as_deref()
128                .or(session.shell_cwd.as_deref())
129                .unwrap_or(".")
130                .to_string();
131
132            // #707: a shell_cwd tracking a mid-session worktree switch
133            // (different git checkout) outranks the stale project_root — same
134            // precedence as core::path_resolve. Checked BEFORE the `p.exists()`
135            // probe below: that probe runs against the *process* CWD, which
136            // IDEs routinely set to the original project root, so it would
137            // short-circuit every relative path back to the stale checkout and
138            // the divergence rule could never apply.
139            let worktree_cwd = if p.is_absolute() {
140                None
141            } else {
142                session
143                    .project_root
144                    .as_deref()
145                    .zip(session.shell_cwd.as_deref())
146                    .filter(|(root, cwd)| {
147                        lean_ctx::core::path_resolve::shell_cwd_is_divergent_checkout(root, cwd)
148                    })
149                    .map(|(_, cwd)| std::path::Path::new(cwd).join(&normalized))
150            };
151
152            let resolved = if let Some(overridden) = worktree_cwd {
153                overridden
154            } else if p.is_absolute() || p.exists() {
155                std::path::PathBuf::from(&normalized)
156            } else if let Some(ref root) = session.project_root {
157                let joined = std::path::Path::new(root).join(&normalized);
158                if joined.exists() {
159                    joined
160                } else if let Some(ref cwd) = session.shell_cwd {
161                    std::path::Path::new(cwd).join(&normalized)
162                } else {
163                    std::path::Path::new(&jail_root).join(&normalized)
164                }
165            } else if let Some(ref cwd) = session.shell_cwd {
166                std::path::Path::new(cwd).join(&normalized)
167            } else {
168                std::path::Path::new(&jail_root).join(&normalized)
169            };
170
171            // Session-scoped trusted roots (MCP roots/list, config extra_roots,
172            // git worktrees) must widen the jail for an explicit path (#403).
173            if session.project_root.is_none()
174                && let Some(error) =
175                    lean_ctx::core::path_resolve::unbound_relative_path(path, &resolved, &jail_root)
176            {
177                return Err(error.into());
178            }
179            (resolved, jail_root, session.extra_roots.clone())
180        };
181
182        let jail_root_path = std::path::Path::new(&jail_root);
183        let jailed = match lean_ctx::core::pathjail::jail_path_with_roots(
184            &resolved,
185            jail_root_path,
186            &extra_roots,
187        ) {
188            Ok(p) => self
189                .maybe_reroot_for_absolute_path(&resolved, jail_root_path, &extra_roots, tool)
190                .await?
191                .unwrap_or(p),
192            Err(e) => {
193                // #899: a refused path in a language cache or an agent
194                // instruction folder is admitted read-only for the session
195                // and resolved again (see `jail_path_auto_admitting`). If it
196                // is still refused, report why — "retry" would only repeat
197                // the same refusal.
198                if lean_ctx::core::pathjail::detect_language_cache_root(&resolved).is_some() {
199                    match lean_ctx::core::pathjail::jail_path_auto_admitting(
200                        &resolved,
201                        jail_root_path,
202                        &extra_roots,
203                    ) {
204                        Ok(jailed) => jailed,
205                        Err(retry) => {
206                            lean_ctx_cloud::metrics_v2::signals::blocked(
207                                &lean_ctx_cloud::metrics_v2::signals::path_jail_rule(),
208                            );
209                            return Err(PathRefusal::jail(&retry));
210                        }
211                    }
212                } else if let Some(jailed) = self
213                    .maybe_reroot_for_absolute_path(&resolved, jail_root_path, &extra_roots, tool)
214                    .await?
215                {
216                    jailed
217                } else {
218                    lean_ctx_cloud::metrics_v2::signals::blocked(
219                        &lean_ctx_cloud::metrics_v2::signals::path_jail_rule(),
220                    );
221                    return Err(PathRefusal::jail(&e));
222                }
223            }
224        };
225
226        lean_ctx::core::io_boundary::check_secret_path_for_tool("resolve_path", &jailed)
227            .map_err(PathRefusal::secret_path)?;
228
229        Ok(lean_ctx::core::pathutil::normalize_tool_path(
230            &jailed.to_string_lossy().replace('\\', "/"),
231        ))
232    }
233
234    async fn maybe_reroot_for_absolute_path(
235        &self,
236        resolved: &std::path::Path,
237        jail_root_path: &std::path::Path,
238        extra_roots: &[String],
239        tool: &str,
240    ) -> Result<Option<std::path::PathBuf>, String> {
241        // A shared session is every client's: one client's path never moves
242        // it (AP04-G5/G6).
243        if !resolved.is_absolute() || self.session_mode == super::SessionMode::Shared {
244            return Ok(None);
245        }
246        // Under a Workspace the session root follows the snapshot only
247        // (#2120); a path never moves it.
248        if lean_ctx::core::workspace_authority::is_configured() {
249            return Ok(None);
250        }
251        // A root pinned with `LEAN_CTX_PROJECT_ROOT` is a boundary the operator
252        // set, not a guess to correct: a markerless pinned directory inside a
253        // larger checkout must not be widened to that checkout — and every
254        // index, policy and receipt moved with it — by the first absolute path.
255        if crate::server::roots::pinned_root().is_some_and(|pinned| {
256            lean_ctx::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(&pinned))
257                == lean_ctx::core::pathutil::safe_canonicalize_or_self(jail_root_path)
258        }) {
259            return Ok(None);
260        }
261        // The session moved while this path was resolved (another call
262        // adopted a project, or the host changed roots): judge the path by the
263        // root it has now, never by the stale one it was jailed to.
264        let bound = self.session.read().await.project_root.clone();
265        if bound
266            .as_deref()
267            .is_some_and(|root| std::path::Path::new(root) != jail_root_path)
268            && let Some(rejailed) =
269                Self::rejail_in_bound_root(resolved, bound.as_deref(), extra_roots)
270        {
271            return rejailed.map(Some);
272        }
273        // No project bound (none, or `~`, `/`, an agent directory): the
274        // first absolute path inside a project binds it through the hardened
275        // adoption, once per session. Without a usable home (`HOME=/`) the
276        // previous re-root below stays in charge.
277        if self.session_is_unbound().await
278            && lean_ctx::core::pathjail_autobind::hardened_adoption_available()
279        {
280            return self.adopt_project_root(resolved, extra_roots, tool).await;
281        }
282        self.reroot_to_derived_project(resolved, jail_root_path, extra_roots)
283            .await
284    }
285
286    /// The re-root of a markerless session root (a client cwd such as
287    /// `/mnt/c/Users`, #649) — and of an unbound session when the hardened
288    /// adoption is unavailable — unchanged from before activation #3.
289    async fn reroot_to_derived_project(
290        &self,
291        resolved: &std::path::Path,
292        jail_root_path: &std::path::Path,
293        extra_roots: &[String],
294    ) -> Result<Option<std::path::PathBuf>, String> {
295        // The outermost marker above a path can be `~` itself (a dotfiles
296        // repository) or an agent directory: never a project to move to
297        // (AP04-G6).
298        let Some(new_root) = maybe_derive_project_root_from_absolute(resolved)
299            .filter(|root| !lean_ctx::core::pathutil::is_broad_or_unsafe_root(root))
300        else {
301            return Ok(None);
302        };
303        let jail_is_real_project =
304            has_project_marker(jail_root_path) && !is_suspicious_root(jail_root_path);
305        let candidate_under_jail = resolved.starts_with(jail_root_path);
306        // #1437: never reroot to a child when jail is a real project. Skip when
307        // jail is suspicious (/, home, agent-config) — not a real boundary.
308        if jail_is_real_project
309            && new_root.starts_with(jail_root_path)
310            && new_root != jail_root_path
311        {
312            return Ok(None);
313        }
314        // Universal auto-reroot: when the jail root is not a real project
315        // (suspicious, None, or markerless), correct to derived project root.
316        // No IDE-specific logic — works for all IDEs and daemon.
317        let allow_reroot = if candidate_under_jail && jail_is_real_project {
318            false
319        } else {
320            !jail_is_real_project || self.session.read().await.project_root.is_none()
321        };
322
323        if !allow_reroot {
324            return Ok(None);
325        }
326
327        if !self.reroot_to_project(&new_root).await {
328            return Ok(None);
329        }
330        lean_ctx::core::pathjail::jail_path_with_roots(resolved, &new_root, extra_roots)
331            .map(Some)
332            .map_err(|e| e.to_string())
333    }
334
335    /// The session has no real project: no root, or a root no project can
336    /// be (`~`, `/`, an agent or IDE config directory).
337    async fn session_is_unbound(&self) -> bool {
338        self.session
339            .read()
340            .await
341            .project_root
342            .as_deref()
343            .is_none_or(|root| is_suspicious_root(std::path::Path::new(root)))
344    }
345
346    /// Adopt the project containing `resolved` as the unbound session's
347    /// writable project (`lean_ctx::core::pathjail_autobind::adoptable_root`),
348    /// once per session, audited with the dispatching `tool`. `None` keeps
349    /// today's refusal.
350    ///
351    /// Adoptions are serialized: a call that queued behind another one
352    /// re-checks the session; when the winner bound a project the path is
353    /// resolved against that root, or refused when it lies outside it.
354    ///
355    /// The adoption is committed and its audit write started without an await
356    /// in between: `switch_to_project` installs the new session after its
357    /// last await and returns synchronously, and the flag, the spawned audit
358    /// write and the log line follow before the next await. A request dropped
359    /// at any await point (client cancel, shutdown) therefore either left the
360    /// session unbound or left it adopted with the audit write under way on
361    /// the blocking pool, never adopted silently.
362    async fn adopt_project_root(
363        &self,
364        resolved: &std::path::Path,
365        extra_roots: &[String],
366        tool: &str,
367    ) -> Result<Option<std::path::PathBuf>, String> {
368        // The filesystem probes (canonicalize, markers, ownership) run on the
369        // blocking pool, bounded, before the lock: a hung mount neither parks
370        // a runtime worker nor every adoption queued behind this one. The
371        // verdict depends on the path alone, so judging it before the lock
372        // changes nothing; the session is re-checked under the lock.
373        // A session that already adopted never probes again (the lock below
374        // refuses anyway); too many hung probes in flight adopt nothing.
375        let already = self.autobind.try_lock().is_ok_and(|adopted| *adopted);
376        let slot = (!already).then(ProbeSlot::take).flatten();
377        let adoptable = match slot {
378            None => None,
379            Some(slot) => {
380                let candidate = resolved.to_path_buf();
381                let judged = tokio::time::timeout(
382                    ADOPTION_PROBE_TIMEOUT,
383                    tokio::task::spawn_blocking(move || {
384                        let _slot = slot;
385                        lean_ctx::core::pathjail_autobind::adoptable_root(&candidate)
386                            .filter(|root| !lean_ctx::core::pathutil::is_broad_or_unsafe_root(root))
387                    }),
388                )
389                .await;
390                // A probe that timed out or failed adopts nothing (fail closed).
391                judged.ok().and_then(Result::ok).flatten()
392            }
393        };
394        let agent_id = self
395            .agent_id
396            .read()
397            .await
398            .clone()
399            .unwrap_or_else(|| "unknown".to_string());
400
401        // Tests force racing calls to meet here, past the unbound check and
402        // before the lock, so the lock alone decides the race.
403        #[cfg(test)]
404        if let Some(barrier) = ADOPTION_BARRIER
405            .try_with(|barrier| barrier.borrow_mut().take())
406            .ok()
407            .flatten()
408        {
409            barrier.wait().await;
410        }
411        let mut adopted = self.autobind.lock().await;
412        let bound = self.session.read().await.project_root.clone();
413        let still_open = !*adopted
414            && bound
415                .as_deref()
416                .is_none_or(|root| is_suspicious_root(std::path::Path::new(root)));
417        if !still_open {
418            drop(adopted);
419            return Self::rejail_in_bound_root(resolved, bound.as_deref(), extra_roots).transpose();
420        }
421        let Some(root) = adoptable else {
422            return Ok(None);
423        };
424        let Some(saves) = self.switch_to_project(&root).await else {
425            return Ok(None);
426        };
427        // The session is switched. No await until the adoption is marked and
428        // its audit write is spawned (B1). The write takes the trail lock
429        // (bounded, up to 750 ms), so it runs on the blocking pool, not on a
430        // runtime worker; a spawned blocking task runs to completion even when
431        // this request is dropped. The lock is held until it finished, so the
432        // event is on disk before any later call sees the adoption settled.
433        // The local audit trail names the root; the log line does not.
434        *adopted = true;
435        lean_ctx::core::pathjail_autobind::mark_adopted(&root);
436        let audit = {
437            let (tool, agent_id, root) = (tool.to_string(), agent_id, root.clone());
438            tokio::task::spawn_blocking(move || {
439                lean_ctx::core::pathjail_autobind::record_autobind(&tool, &agent_id, &root);
440            })
441        };
442        tracing::warn!(
443            "[SECURITY] PathJail: unbound session adopted the project of its first path (tool {tool})"
444        );
445        let _ = audit.await;
446        drop(adopted);
447        // Queued calls re-resolve against the adopted root while the stale
448        // session is saved.
449        for save in saves {
450            let _ = save.await;
451        }
452        lean_ctx::core::pathjail::jail_path_with_roots(resolved, &root, extra_roots)
453            .map(Some)
454            .map_err(|e| e.to_string())
455    }
456
457    /// `resolved` jailed to the real project the session is bound to now.
458    /// `None` when the session has no real project (none, or a suspicious
459    /// root); `Some(Err)` when the path lies outside the bound project — a
460    /// refusal, never a fallback to the root the path was first jailed to.
461    fn rejail_in_bound_root(
462        resolved: &std::path::Path,
463        bound: Option<&str>,
464        extra_roots: &[String],
465    ) -> Option<Result<std::path::PathBuf, String>> {
466        let root = std::path::Path::new(bound?);
467        if is_suspicious_root(root) {
468            return None;
469        }
470        Some(
471            lean_ctx::core::pathjail::jail_path_with_roots(resolved, root, extra_roots)
472                .map_err(|e| e.to_string()),
473        )
474    }
475
476    /// Move the session — and the request that corrected it — to `new_root`
477    /// through the same switch as a host's root change: that project's own
478    /// session, the stale one saved where it was (AP04 review S4). Refused
479    /// under a pinned source view, whose request project cannot follow.
480    async fn reroot_to_project(&self, new_root: &std::path::Path) -> bool {
481        let Some(saves) = self.switch_to_project(new_root).await else {
482            return false;
483        };
484        for save in saves {
485            let _ = save.await;
486        }
487        true
488    }
489
490    /// [`Self::reroot_to_project`] without awaiting the saves of the stale
491    /// session: the session is switched when this returns `Some`.
492    async fn switch_to_project(
493        &self,
494        new_root: &std::path::Path,
495    ) -> Option<Vec<tokio::task::JoinHandle<()>>> {
496        if lean_ctx::core::policy::runtime::inherited_source_view().is_some() {
497            return None;
498        }
499        let new_root_str = new_root.to_string_lossy().to_string();
500        let shell_cwd = self
501            .startup_shell_cwd
502            .as_ref()
503            .filter(|cwd| std::path::Path::new(cwd).starts_with(new_root))
504            .cloned()
505            .or_else(|| Some(new_root_str.clone()));
506        let current = self.session.instance();
507        let extra_roots = current.read().await.extra_roots.clone();
508        let switch = crate::server::SessionSwitch {
509            new_root: &new_root_str,
510            extra_roots,
511            shell_cwd,
512            rebind_request: true,
513        };
514        self.switch_session_root(&current, switch).await
515    }
516
517    /// Like `resolve_path`, but returns the original path on failure instead of an error.
518    pub async fn resolve_path_or_passthrough(&self, path: &str) -> String {
519        self.resolve_path(path)
520            .await
521            .unwrap_or_else(|_| path.to_string())
522    }
523}