1use super::server::LeanCtxServer;
3use super::startup::{
4 has_project_marker, is_suspicious_root, maybe_derive_project_root_from_absolute,
5};
6
7const ADOPTION_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
11
12const MAX_ADOPTION_PROBES: usize = 2;
17static ADOPTION_PROBES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18
19struct 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 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 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 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 pub(crate) async fn resolve_path_refusing(
96 &self,
97 path: &str,
98 ) -> Result<String, lean_ctx::core::path_resolve::PathRefusal> {
99 self.resolve_path_for_tool(path, "unknown").await
103 }
104
105 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 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 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 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 if !resolved.is_absolute() || self.session_mode == super::SessionMode::Shared {
223 return Ok(None);
224 }
225 if lean_ctx::core::workspace_authority::is_configured() {
228 return Ok(None);
229 }
230 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 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 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 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 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 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 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 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 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 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 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 #[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 *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 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 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 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 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(¤t, switch).await
494 }
495
496 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}