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 dependency looked up in a language or package cache (a crate in
231 // the registry, a PlatformIO framework) is read for the project, not
232 // the project itself: it never moves the session, or every later
233 // relative path resolves inside that package.
234 if lean_ctx::core::pathjail::detect_language_cache_root(resolved).is_some() {
235 return Ok(None);
236 }
237 // A root pinned with `LEAN_CTX_PROJECT_ROOT` is a boundary the operator
238 // set, not a guess to correct: a markerless pinned directory inside a
239 // larger checkout must not be widened to that checkout — and every
240 // index, policy and receipt moved with it — by the first absolute path.
241 if crate::server::roots::pinned_root().is_some_and(|pinned| {
242 lean_ctx::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(&pinned))
243 == lean_ctx::core::pathutil::safe_canonicalize_or_self(jail_root_path)
244 }) {
245 return Ok(None);
246 }
247 // The session moved while this path was resolved (another call
248 // adopted a project, or the host changed roots): judge the path by the
249 // root it has now, never by the stale one it was jailed to.
250 let bound = self.session.read().await.project_root.clone();
251 if bound
252 .as_deref()
253 .is_some_and(|root| std::path::Path::new(root) != jail_root_path)
254 && let Some(rejailed) =
255 Self::rejail_in_bound_root(resolved, bound.as_deref(), extra_roots)
256 {
257 return rejailed.map(Some);
258 }
259 // No project bound (none, or `~`, `/`, an agent directory): the
260 // first absolute path inside a project binds it through the hardened
261 // adoption, once per session. Without a usable home (`HOME=/`) the
262 // previous re-root below stays in charge.
263 if self.session_is_unbound().await
264 && lean_ctx::core::pathjail_autobind::hardened_adoption_available()
265 {
266 return self.adopt_project_root(resolved, extra_roots, tool).await;
267 }
268 self.reroot_to_derived_project(resolved, jail_root_path, extra_roots)
269 .await
270 }
271
272 /// The re-root of a markerless session root (a client cwd such as
273 /// `/mnt/c/Users`, #649) — and of an unbound session when the hardened
274 /// adoption is unavailable — unchanged from before activation #3.
275 async fn reroot_to_derived_project(
276 &self,
277 resolved: &std::path::Path,
278 jail_root_path: &std::path::Path,
279 extra_roots: &[String],
280 ) -> Result<Option<std::path::PathBuf>, String> {
281 // The outermost marker above a path can be `~` itself (a dotfiles
282 // repository) or an agent directory: never a project to move to
283 // (AP04-G6).
284 let Some(new_root) = maybe_derive_project_root_from_absolute(resolved)
285 .filter(|root| !lean_ctx::core::pathutil::is_broad_or_unsafe_root(root))
286 else {
287 return Ok(None);
288 };
289 let jail_is_real_project =
290 has_project_marker(jail_root_path) && !is_suspicious_root(jail_root_path);
291 let candidate_under_jail = resolved.starts_with(jail_root_path);
292 // #1437: never reroot to a child when jail is a real project. Skip when
293 // jail is suspicious (/, home, agent-config) — not a real boundary.
294 if jail_is_real_project
295 && new_root.starts_with(jail_root_path)
296 && new_root != jail_root_path
297 {
298 return Ok(None);
299 }
300 // Universal auto-reroot: when the jail root is not a real project
301 // (suspicious, None, or markerless), correct to derived project root.
302 // No IDE-specific logic — works for all IDEs and daemon.
303 let allow_reroot = if candidate_under_jail && jail_is_real_project {
304 false
305 } else {
306 !jail_is_real_project || self.session.read().await.project_root.is_none()
307 };
308
309 if !allow_reroot {
310 return Ok(None);
311 }
312
313 if !self.reroot_to_project(&new_root).await {
314 return Ok(None);
315 }
316 lean_ctx::core::pathjail::jail_path_with_roots(resolved, &new_root, extra_roots)
317 .map(Some)
318 .map_err(|e| e.to_string())
319 }
320
321 /// The session has no real project: no root, or a root no project can
322 /// be (`~`, `/`, an agent or IDE config directory).
323 async fn session_is_unbound(&self) -> bool {
324 self.session
325 .read()
326 .await
327 .project_root
328 .as_deref()
329 .is_none_or(|root| is_suspicious_root(std::path::Path::new(root)))
330 }
331
332 /// Adopt the project containing `resolved` as the unbound session's
333 /// writable project (`lean_ctx::core::pathjail_autobind::adoptable_root`),
334 /// once per session, audited with the dispatching `tool`. `None` keeps
335 /// today's refusal.
336 ///
337 /// Adoptions are serialized: a call that queued behind another one
338 /// re-checks the session; when the winner bound a project the path is
339 /// resolved against that root, or refused when it lies outside it.
340 ///
341 /// The adoption is committed and its audit write started without an await
342 /// in between: `switch_to_project` installs the new session after its
343 /// last await and returns synchronously, and the flag, the spawned audit
344 /// write and the log line follow before the next await. A request dropped
345 /// at any await point (client cancel, shutdown) therefore either left the
346 /// session unbound or left it adopted with the audit write under way on
347 /// the blocking pool, never adopted silently.
348 async fn adopt_project_root(
349 &self,
350 resolved: &std::path::Path,
351 extra_roots: &[String],
352 tool: &str,
353 ) -> Result<Option<std::path::PathBuf>, String> {
354 // The filesystem probes (canonicalize, markers, ownership) run on the
355 // blocking pool, bounded, before the lock: a hung mount neither parks
356 // a runtime worker nor every adoption queued behind this one. The
357 // verdict depends on the path alone, so judging it before the lock
358 // changes nothing; the session is re-checked under the lock.
359 // A session that already adopted never probes again (the lock below
360 // refuses anyway); too many hung probes in flight adopt nothing.
361 let already = self.autobind.try_lock().is_ok_and(|adopted| *adopted);
362 let slot = (!already).then(ProbeSlot::take).flatten();
363 let adoptable = match slot {
364 None => None,
365 Some(slot) => {
366 let candidate = resolved.to_path_buf();
367 let judged = tokio::time::timeout(
368 ADOPTION_PROBE_TIMEOUT,
369 tokio::task::spawn_blocking(move || {
370 let _slot = slot;
371 lean_ctx::core::pathjail_autobind::adoptable_root(&candidate)
372 .filter(|root| !lean_ctx::core::pathutil::is_broad_or_unsafe_root(root))
373 }),
374 )
375 .await;
376 // A probe that timed out or failed adopts nothing (fail closed).
377 judged.ok().and_then(Result::ok).flatten()
378 }
379 };
380 let agent_id = self
381 .agent_id
382 .read()
383 .await
384 .clone()
385 .unwrap_or_else(|| "unknown".to_string());
386
387 // Tests force racing calls to meet here, past the unbound check and
388 // before the lock, so the lock alone decides the race.
389 #[cfg(test)]
390 if let Some(barrier) = ADOPTION_BARRIER
391 .try_with(|barrier| barrier.borrow_mut().take())
392 .ok()
393 .flatten()
394 {
395 barrier.wait().await;
396 }
397 let mut adopted = self.autobind.lock().await;
398 let bound = self.session.read().await.project_root.clone();
399 let still_open = !*adopted
400 && bound
401 .as_deref()
402 .is_none_or(|root| is_suspicious_root(std::path::Path::new(root)));
403 if !still_open {
404 drop(adopted);
405 return Self::rejail_in_bound_root(resolved, bound.as_deref(), extra_roots).transpose();
406 }
407 let Some(root) = adoptable else {
408 return Ok(None);
409 };
410 let Some(saves) = self.switch_to_project(&root).await else {
411 return Ok(None);
412 };
413 // The session is switched. No await until the adoption is marked and
414 // its audit write is spawned (B1). The write takes the trail lock
415 // (bounded, up to 750 ms), so it runs on the blocking pool, not on a
416 // runtime worker; a spawned blocking task runs to completion even when
417 // this request is dropped. The lock is held until it finished, so the
418 // event is on disk before any later call sees the adoption settled.
419 // The local audit trail names the root; the log line does not.
420 *adopted = true;
421 lean_ctx::core::pathjail_autobind::mark_adopted(&root);
422 let audit = {
423 let (tool, agent_id, root) = (tool.to_string(), agent_id, root.clone());
424 tokio::task::spawn_blocking(move || {
425 lean_ctx::core::pathjail_autobind::record_autobind(&tool, &agent_id, &root);
426 })
427 };
428 tracing::warn!(
429 "[SECURITY] PathJail: unbound session adopted the project of its first path (tool {tool})"
430 );
431 let _ = audit.await;
432 drop(adopted);
433 // Queued calls re-resolve against the adopted root while the stale
434 // session is saved.
435 for save in saves {
436 let _ = save.await;
437 }
438 lean_ctx::core::pathjail::jail_path_with_roots(resolved, &root, extra_roots)
439 .map(Some)
440 .map_err(|e| e.to_string())
441 }
442
443 /// `resolved` jailed to the real project the session is bound to now.
444 /// `None` when the session has no real project (none, or a suspicious
445 /// root); `Some(Err)` when the path lies outside the bound project — a
446 /// refusal, never a fallback to the root the path was first jailed to.
447 fn rejail_in_bound_root(
448 resolved: &std::path::Path,
449 bound: Option<&str>,
450 extra_roots: &[String],
451 ) -> Option<Result<std::path::PathBuf, String>> {
452 let root = std::path::Path::new(bound?);
453 if is_suspicious_root(root) {
454 return None;
455 }
456 Some(
457 lean_ctx::core::pathjail::jail_path_with_roots(resolved, root, extra_roots)
458 .map_err(|e| e.to_string()),
459 )
460 }
461
462 /// Move the session — and the request that corrected it — to `new_root`
463 /// through the same switch as a host's root change: that project's own
464 /// session, the stale one saved where it was (AP04 review S4). Refused
465 /// under a pinned source view, whose request project cannot follow.
466 async fn reroot_to_project(&self, new_root: &std::path::Path) -> bool {
467 let Some(saves) = self.switch_to_project(new_root).await else {
468 return false;
469 };
470 for save in saves {
471 let _ = save.await;
472 }
473 true
474 }
475
476 /// [`Self::reroot_to_project`] without awaiting the saves of the stale
477 /// session: the session is switched when this returns `Some`.
478 async fn switch_to_project(
479 &self,
480 new_root: &std::path::Path,
481 ) -> Option<Vec<tokio::task::JoinHandle<()>>> {
482 if lean_ctx::core::policy::runtime::inherited_source_view().is_some() {
483 return None;
484 }
485 let new_root_str = new_root.to_string_lossy().to_string();
486 let shell_cwd = self
487 .startup_shell_cwd
488 .as_ref()
489 .filter(|cwd| std::path::Path::new(cwd).starts_with(new_root))
490 .cloned()
491 .or_else(|| Some(new_root_str.clone()));
492 let current = self.session.instance();
493 let extra_roots = current.read().await.extra_roots.clone();
494 let switch = crate::server::SessionSwitch {
495 new_root: &new_root_str,
496 extra_roots,
497 shell_cwd,
498 rebind_request: true,
499 };
500 self.switch_session_root(¤t, switch).await
501 }
502
503 /// Like `resolve_path`, but returns the original path on failure instead of an error.
504 pub async fn resolve_path_or_passthrough(&self, path: &str) -> String {
505 self.resolve_path(path)
506 .await
507 .unwrap_or_else(|_| path.to_string())
508 }
509}