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            // #2262: a relative path names a file under the project root,
133            // whatever directory an earlier ctx_shell call ran in and whatever
134            // the process CWD is — the same rule as core::path_resolve, so
135            // ctx_read and ctx_patch always resolve one path to one file. Only
136            // a session without a project root falls back to the client's
137            // start directory.
138            let resolved = if p.is_absolute() {
139                std::path::PathBuf::from(&normalized)
140            } else if let Some(ref root) = session.project_root {
141                std::path::Path::new(root).join(&normalized)
142            } else if p.exists() {
143                std::path::PathBuf::from(&normalized)
144            } else if let Some(ref cwd) = session.shell_cwd {
145                std::path::Path::new(cwd).join(&normalized)
146            } else {
147                std::path::Path::new(&jail_root).join(&normalized)
148            };
149
150            // Session-scoped trusted roots (MCP roots/list, config extra_roots,
151            // git worktrees) must widen the jail for an explicit path (#403).
152            if session.project_root.is_none()
153                && let Some(error) =
154                    lean_ctx::core::path_resolve::unbound_relative_path(path, &resolved, &jail_root)
155            {
156                return Err(error.into());
157            }
158            (resolved, jail_root, session.extra_roots.clone())
159        };
160
161        let jail_root_path = std::path::Path::new(&jail_root);
162        let jailed = match lean_ctx::core::pathjail::jail_path_with_roots(
163            &resolved,
164            jail_root_path,
165            &extra_roots,
166        ) {
167            Ok(p) => self
168                .maybe_reroot_for_absolute_path(&resolved, jail_root_path, &extra_roots, tool)
169                .await?
170                .unwrap_or(p),
171            Err(e) => {
172                // #899: a refused path in a language cache or an agent
173                // instruction folder is admitted read-only for the session
174                // and resolved again (see `jail_path_auto_admitting`). If it
175                // is still refused, report why — "retry" would only repeat
176                // the same refusal.
177                if lean_ctx::core::pathjail::detect_language_cache_root(&resolved).is_some() {
178                    match lean_ctx::core::pathjail::jail_path_auto_admitting(
179                        &resolved,
180                        jail_root_path,
181                        &extra_roots,
182                    ) {
183                        Ok(jailed) => jailed,
184                        Err(retry) => {
185                            lean_ctx_cloud::metrics_v2::signals::blocked(
186                                &lean_ctx_cloud::metrics_v2::signals::path_jail_rule(),
187                            );
188                            return Err(PathRefusal::jail(&retry));
189                        }
190                    }
191                } else if let Some(jailed) = self
192                    .maybe_reroot_for_absolute_path(&resolved, jail_root_path, &extra_roots, tool)
193                    .await?
194                {
195                    jailed
196                } else {
197                    lean_ctx_cloud::metrics_v2::signals::blocked(
198                        &lean_ctx_cloud::metrics_v2::signals::path_jail_rule(),
199                    );
200                    return Err(PathRefusal::jail(&e));
201                }
202            }
203        };
204
205        lean_ctx::core::io_boundary::check_secret_path_for_tool("resolve_path", &jailed)
206            .map_err(PathRefusal::secret_path)?;
207
208        Ok(lean_ctx::core::pathutil::normalize_tool_path(
209            &jailed.to_string_lossy().replace('\\', "/"),
210        ))
211    }
212
213    async fn maybe_reroot_for_absolute_path(
214        &self,
215        resolved: &std::path::Path,
216        jail_root_path: &std::path::Path,
217        extra_roots: &[String],
218        tool: &str,
219    ) -> Result<Option<std::path::PathBuf>, String> {
220        // A shared session is every client's: one client's path never moves
221        // it (AP04-G5/G6).
222        if !resolved.is_absolute() || self.session_mode == super::SessionMode::Shared {
223            return Ok(None);
224        }
225        // Under a Workspace the session root follows the snapshot only
226        // (#2120); a path never moves it.
227        if lean_ctx::core::workspace_authority::is_configured() {
228            return Ok(None);
229        }
230        // A root pinned with `LEAN_CTX_PROJECT_ROOT` is a boundary the operator
231        // set, not a guess to correct: a markerless pinned directory inside a
232        // larger checkout must not be widened to that checkout — and every
233        // index, policy and receipt moved with it — by the first absolute path.
234        if crate::server::roots::pinned_root().is_some_and(|pinned| {
235            lean_ctx::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(&pinned))
236                == lean_ctx::core::pathutil::safe_canonicalize_or_self(jail_root_path)
237        }) {
238            return Ok(None);
239        }
240        // The session moved while this path was resolved (another call
241        // adopted a project, or the host changed roots): judge the path by the
242        // root it has now, never by the stale one it was jailed to.
243        let bound = self.session.read().await.project_root.clone();
244        if bound
245            .as_deref()
246            .is_some_and(|root| std::path::Path::new(root) != jail_root_path)
247            && let Some(rejailed) =
248                Self::rejail_in_bound_root(resolved, bound.as_deref(), extra_roots)
249        {
250            return rejailed.map(Some);
251        }
252        // No project bound (none, or `~`, `/`, an agent directory): the
253        // first absolute path inside a project binds it through the hardened
254        // adoption, once per session. Without a usable home (`HOME=/`) the
255        // previous re-root below stays in charge.
256        if self.session_is_unbound().await
257            && lean_ctx::core::pathjail_autobind::hardened_adoption_available()
258        {
259            return self.adopt_project_root(resolved, extra_roots, tool).await;
260        }
261        self.reroot_to_derived_project(resolved, jail_root_path, extra_roots)
262            .await
263    }
264
265    /// The re-root of a markerless session root (a client cwd such as
266    /// `/mnt/c/Users`, #649) — and of an unbound session when the hardened
267    /// adoption is unavailable — unchanged from before activation #3.
268    async fn reroot_to_derived_project(
269        &self,
270        resolved: &std::path::Path,
271        jail_root_path: &std::path::Path,
272        extra_roots: &[String],
273    ) -> Result<Option<std::path::PathBuf>, String> {
274        // The outermost marker above a path can be `~` itself (a dotfiles
275        // repository) or an agent directory: never a project to move to
276        // (AP04-G6).
277        let Some(new_root) = maybe_derive_project_root_from_absolute(resolved)
278            .filter(|root| !lean_ctx::core::pathutil::is_broad_or_unsafe_root(root))
279        else {
280            return Ok(None);
281        };
282        let jail_is_real_project =
283            has_project_marker(jail_root_path) && !is_suspicious_root(jail_root_path);
284        let candidate_under_jail = resolved.starts_with(jail_root_path);
285        // #1437: never reroot to a child when jail is a real project. Skip when
286        // jail is suspicious (/, home, agent-config) — not a real boundary.
287        if jail_is_real_project
288            && new_root.starts_with(jail_root_path)
289            && new_root != jail_root_path
290        {
291            return Ok(None);
292        }
293        // Universal auto-reroot: when the jail root is not a real project
294        // (suspicious, None, or markerless), correct to derived project root.
295        // No IDE-specific logic — works for all IDEs and daemon.
296        let allow_reroot = if candidate_under_jail && jail_is_real_project {
297            false
298        } else {
299            !jail_is_real_project || self.session.read().await.project_root.is_none()
300        };
301
302        if !allow_reroot {
303            return Ok(None);
304        }
305
306        if !self.reroot_to_project(&new_root).await {
307            return Ok(None);
308        }
309        lean_ctx::core::pathjail::jail_path_with_roots(resolved, &new_root, extra_roots)
310            .map(Some)
311            .map_err(|e| e.to_string())
312    }
313
314    /// The session has no real project: no root, or a root no project can
315    /// be (`~`, `/`, an agent or IDE config directory).
316    async fn session_is_unbound(&self) -> bool {
317        self.session
318            .read()
319            .await
320            .project_root
321            .as_deref()
322            .is_none_or(|root| is_suspicious_root(std::path::Path::new(root)))
323    }
324
325    /// Adopt the project containing `resolved` as the unbound session's
326    /// writable project (`lean_ctx::core::pathjail_autobind::adoptable_root`),
327    /// once per session, audited with the dispatching `tool`. `None` keeps
328    /// today's refusal.
329    ///
330    /// Adoptions are serialized: a call that queued behind another one
331    /// re-checks the session; when the winner bound a project the path is
332    /// resolved against that root, or refused when it lies outside it.
333    ///
334    /// The adoption is committed and its audit write started without an await
335    /// in between: `switch_to_project` installs the new session after its
336    /// last await and returns synchronously, and the flag, the spawned audit
337    /// write and the log line follow before the next await. A request dropped
338    /// at any await point (client cancel, shutdown) therefore either left the
339    /// session unbound or left it adopted with the audit write under way on
340    /// the blocking pool, never adopted silently.
341    async fn adopt_project_root(
342        &self,
343        resolved: &std::path::Path,
344        extra_roots: &[String],
345        tool: &str,
346    ) -> Result<Option<std::path::PathBuf>, String> {
347        // The filesystem probes (canonicalize, markers, ownership) run on the
348        // blocking pool, bounded, before the lock: a hung mount neither parks
349        // a runtime worker nor every adoption queued behind this one. The
350        // verdict depends on the path alone, so judging it before the lock
351        // changes nothing; the session is re-checked under the lock.
352        // A session that already adopted never probes again (the lock below
353        // refuses anyway); too many hung probes in flight adopt nothing.
354        let already = self.autobind.try_lock().is_ok_and(|adopted| *adopted);
355        let slot = (!already).then(ProbeSlot::take).flatten();
356        let adoptable = match slot {
357            None => None,
358            Some(slot) => {
359                let candidate = resolved.to_path_buf();
360                let judged = tokio::time::timeout(
361                    ADOPTION_PROBE_TIMEOUT,
362                    tokio::task::spawn_blocking(move || {
363                        let _slot = slot;
364                        lean_ctx::core::pathjail_autobind::adoptable_root(&candidate)
365                            .filter(|root| !lean_ctx::core::pathutil::is_broad_or_unsafe_root(root))
366                    }),
367                )
368                .await;
369                // A probe that timed out or failed adopts nothing (fail closed).
370                judged.ok().and_then(Result::ok).flatten()
371            }
372        };
373        let agent_id = self
374            .agent_id
375            .read()
376            .await
377            .clone()
378            .unwrap_or_else(|| "unknown".to_string());
379
380        // Tests force racing calls to meet here, past the unbound check and
381        // before the lock, so the lock alone decides the race.
382        #[cfg(test)]
383        if let Some(barrier) = ADOPTION_BARRIER
384            .try_with(|barrier| barrier.borrow_mut().take())
385            .ok()
386            .flatten()
387        {
388            barrier.wait().await;
389        }
390        let mut adopted = self.autobind.lock().await;
391        let bound = self.session.read().await.project_root.clone();
392        let still_open = !*adopted
393            && bound
394                .as_deref()
395                .is_none_or(|root| is_suspicious_root(std::path::Path::new(root)));
396        if !still_open {
397            drop(adopted);
398            return Self::rejail_in_bound_root(resolved, bound.as_deref(), extra_roots).transpose();
399        }
400        let Some(root) = adoptable else {
401            return Ok(None);
402        };
403        let Some(saves) = self.switch_to_project(&root).await else {
404            return Ok(None);
405        };
406        // The session is switched. No await until the adoption is marked and
407        // its audit write is spawned (B1). The write takes the trail lock
408        // (bounded, up to 750 ms), so it runs on the blocking pool, not on a
409        // runtime worker; a spawned blocking task runs to completion even when
410        // this request is dropped. The lock is held until it finished, so the
411        // event is on disk before any later call sees the adoption settled.
412        // The local audit trail names the root; the log line does not.
413        *adopted = true;
414        lean_ctx::core::pathjail_autobind::mark_adopted(&root);
415        let audit = {
416            let (tool, agent_id, root) = (tool.to_string(), agent_id, root.clone());
417            tokio::task::spawn_blocking(move || {
418                lean_ctx::core::pathjail_autobind::record_autobind(&tool, &agent_id, &root);
419            })
420        };
421        tracing::warn!(
422            "[SECURITY] PathJail: unbound session adopted the project of its first path (tool {tool})"
423        );
424        let _ = audit.await;
425        drop(adopted);
426        // Queued calls re-resolve against the adopted root while the stale
427        // session is saved.
428        for save in saves {
429            let _ = save.await;
430        }
431        lean_ctx::core::pathjail::jail_path_with_roots(resolved, &root, extra_roots)
432            .map(Some)
433            .map_err(|e| e.to_string())
434    }
435
436    /// `resolved` jailed to the real project the session is bound to now.
437    /// `None` when the session has no real project (none, or a suspicious
438    /// root); `Some(Err)` when the path lies outside the bound project — a
439    /// refusal, never a fallback to the root the path was first jailed to.
440    fn rejail_in_bound_root(
441        resolved: &std::path::Path,
442        bound: Option<&str>,
443        extra_roots: &[String],
444    ) -> Option<Result<std::path::PathBuf, String>> {
445        let root = std::path::Path::new(bound?);
446        if is_suspicious_root(root) {
447            return None;
448        }
449        Some(
450            lean_ctx::core::pathjail::jail_path_with_roots(resolved, root, extra_roots)
451                .map_err(|e| e.to_string()),
452        )
453    }
454
455    /// Move the session — and the request that corrected it — to `new_root`
456    /// through the same switch as a host's root change: that project's own
457    /// session, the stale one saved where it was (AP04 review S4). Refused
458    /// under a pinned source view, whose request project cannot follow.
459    async fn reroot_to_project(&self, new_root: &std::path::Path) -> bool {
460        let Some(saves) = self.switch_to_project(new_root).await else {
461            return false;
462        };
463        for save in saves {
464            let _ = save.await;
465        }
466        true
467    }
468
469    /// [`Self::reroot_to_project`] without awaiting the saves of the stale
470    /// session: the session is switched when this returns `Some`.
471    async fn switch_to_project(
472        &self,
473        new_root: &std::path::Path,
474    ) -> Option<Vec<tokio::task::JoinHandle<()>>> {
475        if lean_ctx::core::policy::runtime::inherited_source_view().is_some() {
476            return None;
477        }
478        let new_root_str = new_root.to_string_lossy().to_string();
479        let shell_cwd = self
480            .startup_shell_cwd
481            .as_ref()
482            .filter(|cwd| std::path::Path::new(cwd).starts_with(new_root))
483            .cloned()
484            .or_else(|| Some(new_root_str.clone()));
485        let current = self.session.instance();
486        let extra_roots = current.read().await.extra_roots.clone();
487        let switch = crate::server::SessionSwitch {
488            new_root: &new_root_str,
489            extra_roots,
490            shell_cwd,
491            rebind_request: true,
492        };
493        self.switch_session_root(&current, switch).await
494    }
495
496    /// Like `resolve_path`, but returns the original path on failure instead of an error.
497    pub async fn resolve_path_or_passthrough(&self, path: &str) -> String {
498        self.resolve_path(path)
499            .await
500            .unwrap_or_else(|_| path.to_string())
501    }
502}