1use std::path::{Path, PathBuf};
2
3use crate::core::error::PathJailError;
4
5pub fn expand_user_path(raw: &str) -> PathBuf {
13 let mut s = raw.to_string();
14
15 if (s == "~" || s.starts_with("~/"))
16 && let Some(home) = dirs::home_dir()
17 {
18 s = format!("{}{}", home.to_string_lossy(), &s[1..]);
19 }
20
21 while let Some(start) = s.find('$') {
22 let rest = &s[start + 1..];
23 let (name, token_len) = if let Some(stripped) = rest.strip_prefix('{') {
24 match stripped.find('}') {
25 Some(end) => (stripped[..end].to_string(), end + 3),
26 None => break,
27 }
28 } else {
29 let end = rest
30 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
31 .unwrap_or(rest.len());
32 (rest[..end].to_string(), end + 1)
33 };
34 if name.is_empty() {
35 break;
36 }
37 if let Ok(val) = std::env::var(&name) {
38 s.replace_range(start..start + token_len, &val);
39 } else if name == "HOME"
40 && let Some(home) = dirs::home_dir()
41 {
42 let home = home.to_string_lossy();
43 s.replace_range(start..start + token_len, home.as_ref());
44 } else {
45 tracing::warn!(
46 "allow_paths/extra_roots entry '{raw}' references unset variable ${name} — entry will never match"
47 );
48 break;
49 }
50 }
51
52 PathBuf::from(s)
53}
54
55pub fn allow_paths_from_env_and_config() -> Vec<PathBuf> {
56 let mut out = Vec::new();
57 let cfg = crate::core::config::Config::load();
58
59 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
71 out.push(canonicalize_secure(&data_dir));
72 }
73
74 if let Some(home) = dirs::home_dir() {
75 let ide_dirs_allowed = cfg.allow_ide_config_dirs.unwrap_or(false)
76 || std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
77 out.extend(home_allow_dirs(&home, ide_dirs_allowed));
78 }
79
80 for p in &cfg.allow_paths {
81 out.push(canonicalize_secure(&expand_user_path(p)));
82 }
83 for p in &cfg.extra_roots {
84 out.push(canonicalize_secure(&expand_user_path(p)));
85 }
86
87 for path in crate::core::runtime_flags::allow_paths() {
88 out.push(canonicalize_secure(&path));
89 }
90 let v = std::env::var("LCTX_ALLOW_PATH")
93 .or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
94 .unwrap_or_default();
95 if !v.trim().is_empty() {
96 for p in std::env::split_paths(&v) {
97 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
98 }
99 }
100
101 let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
102 if !extra.trim().is_empty() {
103 for p in std::env::split_paths(&extra) {
104 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
105 }
106 }
107
108 out.extend(canonicalized_roots(
113 &cfg.read_only_roots,
114 "LEAN_CTX_READ_ONLY_ROOTS",
115 ));
116
117 out
118}
119
120fn canonicalized_roots(config_entries: &[String], env_var: &str) -> Vec<PathBuf> {
125 let mut out = Vec::new();
126 for p in config_entries {
127 out.push(canonicalize_secure(&expand_user_path(p)));
128 }
129 let v = std::env::var(env_var).unwrap_or_default();
130 if !v.trim().is_empty() {
131 for p in std::env::split_paths(&v) {
132 out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
133 }
134 }
135 out
136}
137
138pub fn read_only_roots_from_env_and_config() -> Vec<PathBuf> {
143 let cfg = crate::core::config::Config::load();
144 let mut roots = canonicalized_roots(&cfg.read_only_roots, "LEAN_CTX_READ_ONLY_ROOTS");
145 roots.extend(session_read_only_roots());
150 roots
151}
152
153static SESSION_READ_ONLY_ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> =
154 std::sync::OnceLock::new();
155
156fn session_read_only_roots_cell() -> &'static std::sync::Mutex<Vec<PathBuf>> {
157 SESSION_READ_ONLY_ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
158}
159
160pub fn session_read_only_roots() -> Vec<PathBuf> {
162 session_read_only_roots_cell()
163 .lock()
164 .map(|g| g.clone())
165 .unwrap_or_default()
166}
167
168pub fn register_session_read_only_root(root: &Path) -> bool {
178 let canon = canonicalize_secure(root);
179 let mut guard = match session_read_only_roots_cell().lock() {
180 Ok(g) => g,
181 Err(poisoned) => poisoned.into_inner(),
182 };
183 if guard.iter().any(|r| r == &canon) {
184 return false;
185 }
186 guard.push(canon);
187 true
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub struct JailRelaxation {
198 pub source: &'static str,
200 pub detail: &'static str,
202}
203
204fn env_is_set(var: &str) -> bool {
205 std::env::var(var).is_ok_and(|v| !v.trim().is_empty())
206}
207
208#[must_use]
212pub fn active_relaxations() -> Vec<JailRelaxation> {
213 let mut out = Vec::new();
214
215 if cfg!(feature = "no-jail") {
216 out.push(JailRelaxation {
217 source: "no-jail (build feature)",
218 detail: "path jail compiled out — every tool path is allowed",
219 });
220 }
221
222 if crate::core::config::Config::load().path_jail == Some(false) {
223 out.push(JailRelaxation {
224 source: "path_jail = false (config.toml)",
225 detail: "path jail disabled — every tool path is allowed",
226 });
227 }
228
229 if crate::core::runtime_flags::allow_path_enabled() {
230 out.push(JailRelaxation {
231 source: "LEAN_CTX_ALLOW_PATH",
232 detail: "widens the read/write allow-list beyond the project root",
233 });
234 }
235
236 if env_is_set("LEAN_CTX_EXTRA_ROOTS") {
237 out.push(JailRelaxation {
238 source: "LEAN_CTX_EXTRA_ROOTS",
239 detail: "adds extra accessible roots beyond the project root",
240 });
241 }
242
243 let ide_env = std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
244 if ide_env
245 || crate::core::config::Config::load()
246 .allow_ide_config_dirs
247 .unwrap_or(false)
248 {
249 out.push(JailRelaxation {
250 source: if ide_env {
251 "LEAN_CTX_ALLOW_IDE_DIRS=1"
252 } else {
253 "allow_ide_config_dirs = true (config.toml)"
254 },
255 detail: "exposes ~/.cursor, ~/.claude, … (other agents' sessions/credentials) to tools",
256 });
257 }
258
259 out
260}
261
262pub fn warn_if_relaxed() {
266 for relaxation in active_relaxations() {
267 tracing::warn!(
268 "[SECURITY] path jail relaxed via {}: {} — intended for trusted local use only",
269 relaxation.source,
270 relaxation.detail
271 );
272 }
273}
274
275pub fn is_read_only_path(candidate: &Path) -> bool {
286 let roots = read_only_roots_from_env_and_config();
287 if roots.is_empty() {
288 return false;
289 }
290 let base = canonical_target(candidate);
291 roots.iter().any(|r| is_under_prefix(&base, r))
292}
293
294fn canonical_target(candidate: &Path) -> PathBuf {
298 match canonicalize_existing_ancestor(candidate) {
299 Some((mut p, remainder)) => {
300 for part in remainder.iter().rev() {
301 p.push(part);
302 }
303 p
304 }
305 None => canonicalize_or_self(candidate),
306 }
307}
308
309pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
318 crate::cli::enforce_protected_store_path(candidate)?;
321 if is_read_only_path(candidate) {
322 return Err(format!(
323 "path is inside a read-only root — writes are denied (read_only_roots): {}",
324 candidate.display()
325 ));
326 }
327 match super::pathjail_scope::home_scope_write_denial(&canonical_target(candidate)) {
328 Some(denial) => Err(denial),
329 None => Ok(()),
330 }
331}
332
333fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
344 let mut out = Vec::new();
345 if ide_dirs_allowed {
346 let targets = crate::core::editor_registry::build_targets(home);
347 collect_ide_allow_dirs(home, &targets, &mut out);
348 }
349 out
350}
351
352fn collect_ide_allow_dirs(
361 home: &Path,
362 targets: &[crate::core::editor_registry::EditorTarget],
363 out: &mut Vec<PathBuf>,
364) {
365 let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
366 for target in targets {
367 let candidates = [
368 target.config_path.parent().map(Path::to_path_buf),
369 Some(target.detect_path.clone()),
370 ];
371 for cand in candidates.into_iter().flatten() {
372 if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
373 continue;
374 }
375 let resolved = canonicalize_secure(&cand);
376 if seen.insert(resolved.clone()) {
377 out.push(resolved);
378 }
379 }
380 }
381}
382
383fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
384 path.starts_with(prefix)
385}
386
387pub fn is_harness_auto_memory_path(path: &Path) -> bool {
396 let lower = path.to_string_lossy().replace('\\', "/").to_lowercase();
397 for marker in ["/.claude/projects/", "/.codebuddy/projects/"] {
398 if let Some(idx) = lower.find(marker) {
399 let after = &lower[idx + marker.len()..];
400 let mut parts = after.split('/');
401 let Some(_slug) = parts.next() else {
402 continue;
403 };
404 if parts.next() == Some("memory") {
405 return true;
406 }
407 }
408 }
409 false
410}
411
412fn path_allowed_by_jail(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
413 if is_harness_auto_memory_path(base) {
414 return true;
415 }
416 let allowed = is_under_prefix(base, root)
417 || allow.iter().any(|p| is_under_prefix(base, p))
418 || super::pathjail_scope::home_scope_admits(base);
419 #[cfg(windows)]
420 let allowed = allowed || is_under_prefix_windows(base, root);
421 allowed && super::pathjail_scope::protected_zone_permits(base, root, allow)
422}
423
424pub fn canonicalize_or_self(path: &Path) -> PathBuf {
428 super::pathutil::safe_canonicalize_bounded(path, 2000)
429}
430
431pub(crate) fn canonicalize_secure(path: &Path) -> PathBuf {
436 super::pathutil::canonicalize_secure_bounded(path, 2000)
437}
438
439fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
440 let mut cur = path.to_path_buf();
441 let mut remainder: Vec<std::ffi::OsString> = Vec::new();
442 loop {
443 if cur.exists() {
444 return Some((canonicalize_secure(&cur), remainder));
445 }
446 let name = cur.file_name()?.to_os_string();
447 remainder.push(name);
448 if !cur.pop() {
449 return None;
450 }
451 }
452}
453
454pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
455 jail_path_with_roots(candidate, jail_root, &[])
456}
457
458const LANGUAGE_CACHE_PATTERNS: &[(&str, &str, &str)] = &[
463 ("/go/pkg/mod/", "Go module cache", "~/go/pkg/mod"),
464 (
465 "/.cargo/registry/",
466 "Rust crate registry",
467 "~/.cargo/registry",
468 ),
469 (
470 "/site-packages/",
471 "Python site-packages",
472 "<venv>/lib/pythonX.Y/site-packages",
473 ),
474 ("/node_modules/", "Node modules", "<project>/node_modules"),
475 (
476 "/.m2/repository/",
477 "Maven local repository",
478 "~/.m2/repository",
479 ),
480 ("/.gradle/caches/", "Gradle cache", "~/.gradle/caches"),
481 (
482 "/.nuget/packages/",
483 "NuGet package cache",
484 "~/.nuget/packages",
485 ),
486 (
490 "/.rustup/toolchains/",
491 "Rust toolchain source",
492 "~/.rustup/toolchains",
493 ),
494 (
495 "/.cargo/git/checkouts/",
496 "Cargo git dependencies",
497 "~/.cargo/git/checkouts",
498 ),
499 (
500 "/.bun/install/cache/",
501 "Bun package cache",
502 "~/.bun/install/cache",
503 ),
504 (
505 "/.pub-cache/hosted/",
506 "Dart pub cache",
507 "~/.pub-cache/hosted",
508 ),
509 ("/.gem/ruby/", "Ruby gems", "~/.gem/ruby"),
510];
511
512const AGENT_INSTRUCTION_ROOTS: &[(&str, &str)] = &[
521 (".claude/skills", "Claude Code skills"),
522 (".claude/commands", "Claude Code commands"),
523 (".claude/agents", "Claude Code agents"),
524 (".claude/plans", "Claude Code plans"),
525 (".claude/rules", "Claude Code rules"),
526 (".claude/plugins/marketplaces", "Claude Code plugins"),
527 (".claude/plugins/cache", "Claude Code plugins"),
528 (".claude/CLAUDE.md", "Claude Code instructions"),
529 (".codex/skills", "Codex skills"),
530 (".codex/prompts", "Codex prompts"),
531 (".codex/AGENTS.md", "Codex instructions"),
532 (".agents/skills", "agent skills"),
533 (".cursor/rules", "Cursor rules"),
534 (".cursor/skills", "Cursor skills"),
535 (".cursor/commands", "Cursor commands"),
536 (".gemini/GEMINI.md", "Gemini instructions"),
537 (".gemini/commands", "Gemini commands"),
538 (".config/opencode/agent", "OpenCode agents"),
539 (".config/opencode/command", "OpenCode commands"),
540 (".config/opencode/AGENTS.md", "OpenCode instructions"),
541];
542
543fn detect_agent_instruction_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
547 let home = dirs::home_dir()?;
548 let canon_home = canonicalize_secure(&home);
549 let rel = candidate
550 .strip_prefix(&home)
551 .or_else(|_| candidate.strip_prefix(&canon_home))
552 .ok()?;
553 if rel
555 .components()
556 .any(|c| !matches!(c, std::path::Component::Normal(_)))
557 {
558 return None;
559 }
560 AGENT_INSTRUCTION_ROOTS
561 .iter()
562 .find(|(root, _)| rel.starts_with(root))
563 .map(|&(root, label)| (label, canon_home.join(root)))
564}
565
566pub fn register_symlink_target_read_only(candidate: &Path, root: &Path) -> bool {
578 if detect_agent_instruction_root(root).is_none()
579 || (!candidate.starts_with(root) && !candidate.starts_with(canonicalize_secure(root)))
580 {
581 return false;
582 }
583 let Ok(target) = std::fs::canonicalize(candidate) else {
584 return false;
585 };
586 let root = canonicalize_secure(root);
587 if target.starts_with(&root) {
588 return false;
589 }
590 if let Some((_, agent_root)) = detect_agent_instruction_root(&target) {
593 return register_session_read_only_root(&agent_root);
594 }
595 let dir = if target.is_dir() {
596 target
597 } else {
598 match target.parent() {
599 Some(parent) => parent.to_path_buf(),
600 None => return false,
601 }
602 };
603 let below_home =
604 dirs::home_dir().is_some_and(|home| dir.starts_with(canonicalize_secure(&home)));
605 if !below_home
606 || crate::core::pathutil::is_broad_or_unsafe_root(&dir)
607 || super::pathjail_scope::in_protected_zone(&dir)
608 {
609 return false;
610 }
611 register_session_read_only_root(&dir)
612}
613
614pub fn jail_path_auto_admitting(
622 candidate: &Path,
623 jail_root: &Path,
624 extra_roots: &[String],
625) -> Result<PathBuf, PathJailError> {
626 let first = jail_path_with_roots(candidate, jail_root, extra_roots);
627 let Err(refused) = first else {
628 return first;
629 };
630 let Some((label, root)) = detect_language_cache_root(candidate) else {
631 return Err(refused);
632 };
633 if register_session_read_only_root(&root) {
634 tracing::info!(
635 "auto-registered {label} at {} as a read-only root",
636 root.display()
637 );
638 }
639 let retry = jail_path_with_roots(candidate, jail_root, extra_roots);
640 if retry.is_err() && register_symlink_target_read_only(candidate, &root) {
644 return jail_path_with_roots(candidate, jail_root, extra_roots);
645 }
646 retry
647}
648
649fn detected_cache_hint(candidate: &std::path::Path) -> Option<String> {
653 let s = candidate.to_string_lossy();
654 for &(pattern, name, example) in LANGUAGE_CACHE_PATTERNS {
655 if s.contains(pattern) {
656 return Some(format!(
657 ". Detected {name} — add read_only_roots = [\"{example}\"] to \
658 ~/.config/lean-ctx/config.toml for cached, compressed reads without write access"
659 ));
660 }
661 }
662 None
663}
664
665pub fn detect_language_cache_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
670 if let Some(found) = detect_agent_instruction_root(candidate) {
671 return Some(found);
672 }
673 let s = candidate.to_string_lossy().replace('\\', "/");
674 for &(marker, label, _) in LANGUAGE_CACHE_PATTERNS {
675 if let Some(idx) = s.find(marker) {
676 let end = idx + marker.len() - 1; return Some((label, PathBuf::from(&s[..end])));
678 }
679 }
680 None
681}
682
683pub fn jail_path_with_roots(
693 candidate: &Path,
694 jail_root: &Path,
695 extra_roots: &[String],
696) -> Result<PathBuf, PathJailError> {
697 if candidate.to_string_lossy().as_bytes().contains(&0) {
698 return Err(PathJailError::NullByte);
699 }
700
701 let absolute = if candidate.is_absolute() {
705 candidate.to_path_buf()
706 } else {
707 jail_root.join(candidate)
708 };
709 crate::cli::enforce_protected_store_path(&absolute)
710 .map_err(|reason| PathJailError::ProtectedContext { reason })?;
711
712 #[cfg(feature = "no-jail")]
713 {
714 let _ = (jail_root, extra_roots);
715 return Ok(canonicalize_or_self(candidate));
716 }
717
718 #[allow(unreachable_code)]
719 {
720 let cfg = crate::core::config::Config::load();
721 if cfg.path_jail == Some(false) {
722 return Ok(canonicalize_or_self(candidate));
723 }
724
725 let root = canonicalize_secure(jail_root);
726
727 let resolved: PathBuf;
732 let candidate: &Path = if candidate.is_absolute() {
733 candidate
734 } else {
735 resolved = root.join(candidate);
736 resolved.as_path()
737 };
738
739 let mut allow = allow_paths_from_env_and_config();
740 allow.extend(
742 extra_roots
743 .iter()
744 .filter(|r| !r.is_empty())
745 .map(|r| canonicalize_secure(Path::new(r))),
746 );
747
748 if let Ok(state) = crate::core::paths::state_dir() {
752 allow.push(canonicalize_secure(&state));
753 }
754 allow.extend(
757 read_only_roots_from_env_and_config()
758 .into_iter()
759 .map(|p| canonicalize_secure(&p)),
760 );
761
762 let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
763 PathJailError::NoExistingAncestor {
764 path: candidate.to_path_buf(),
765 }
766 })?;
767
768 let allowed = path_allowed_by_jail(&base, &root, &allow);
769
770 if !allowed {
771 let is_suspicious = crate::tools::startup::is_suspicious_root(&root);
772 let mut hint = if is_suspicious || root == std::path::Path::new("/") {
773 ". lean-ctx has not bound this session to a project yet (the host reported \
774 no project directory). Any path inside a project binds it; if it \
775 persists: lean-ctx doctor --fix"
776 .to_string()
777 } else {
778 super::pathjail_scope::escape_hint(candidate, &base, &root)
779 };
780 if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
784 hint.push_str(". ");
785 hint.push_str(¬ice);
786 }
787 if let Some(missing) = crate::core::config::Config::missing_config_path() {
791 hint.push_str(&format!(
792 ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
793 allow_paths edit in a config.toml elsewhere is not read; \
794 `lean-ctx doctor` shows the path in effect",
795 missing.display()
796 ));
797 }
798 if let Some(cache_hint) = detected_cache_hint(candidate) {
799 hint.push_str(&cache_hint);
800 }
801 return Err(PathJailError::EscapesRoot {
802 path: candidate.to_path_buf(),
803 root,
804 hint,
805 });
806 }
807
808 #[cfg(windows)]
809 reject_symlink_on_windows(candidate)?;
810
811 let mut out = base;
812 for part in remainder.iter().rev() {
813 out.push(part);
814 }
815
816 if out.exists() {
819 let final_canon = canonicalize_secure(&out);
820 let final_ok = path_allowed_by_jail(&final_canon, &root, &allow);
821 if !final_ok {
822 return Err(PathJailError::PostCanonicalizeEscape {
823 path: candidate.to_path_buf(),
824 resolved: final_canon,
825 });
826 }
827 }
828
829 crate::cli::enforce_protected_store_path(&out)
830 .map_err(|reason| PathJailError::ProtectedContext { reason })?;
831 Ok(out)
832 }
833}
834
835#[cfg(all(test, target_os = "macos"))]
836mod protected_store_tests {
837 use super::*;
838
839 #[test]
840 fn runtime_store_is_not_reopened_by_implicit_or_explicit_roots() {
841 let isolated = crate::core::data_dir::isolated_data_dir();
842 let project = tempfile::tempdir().unwrap();
843 let store = isolated.path().join("knowledge");
844 std::fs::create_dir_all(&store).unwrap();
845 let fact = store.join("facts.json");
846 std::fs::write(&fact, "private stored context").unwrap();
847 let code = project.path().join("main.rs");
848 std::fs::write(&code, "fn main() {}\n").unwrap();
849 assert!(
850 jail_path(&fact, project.path()).is_ok(),
851 "Community keeps its existing runtime access"
852 );
853 let _protected = crate::cli::pin_synthetic_session(isolated.path()).unwrap();
854 let roots = vec![isolated.path().to_string_lossy().into_owned()];
855 for candidate in [&fact, &store, &isolated.path().to_path_buf()] {
856 assert!(
857 matches!(
858 jail_path_with_roots(candidate, project.path(), &roots),
859 Err(PathJailError::ProtectedContext { .. })
860 ),
861 "{candidate:?}"
862 );
863 }
864 assert!(jail_path(&code, project.path()).is_ok());
865 assert!(jail_path_with_roots(Path::new("facts.json"), &store, &roots).is_err());
866 for target in [&fact, &store.join("new/backup.json")] {
869 assert!(
870 crate::tools::edit_io::write_atomic_bytes_with_permissions(
871 target,
872 b"forged local context",
873 None,
874 )
875 .is_err()
876 );
877 }
878 assert_eq!(
879 std::fs::read_to_string(&fact).unwrap(),
880 "private stored context"
881 );
882 assert!(!store.join("new").exists());
883 crate::tools::edit_io::write_atomic_bytes_with_permissions(&code, b"fn main() {}\n", None)
884 .unwrap();
885 std::fs::write(&fact, "retained internal update").unwrap();
887 assert_eq!(
888 std::fs::read_to_string(&fact).unwrap(),
889 "retained internal update"
890 );
891 }
892
893 #[test]
894 fn missing_child_profile_never_falls_back_to_the_normal_jail() {
895 let isolated = crate::core::data_dir::isolated_data_dir();
896 let project = tempfile::tempdir().unwrap();
897 let code = project.path().join("main.rs");
898 std::fs::write(&code, "fn main() {}\n").unwrap();
899 let _protected = crate::cli::pin_synthetic_session(isolated.path()).unwrap();
900 crate::test_env::remove_var(crate::cli::CHILD_PROFILE_ENV);
901 assert!(matches!(
902 jail_path(&code, project.path()),
903 Err(PathJailError::ProtectedContext { .. })
904 ));
905 }
906}
907
908#[cfg(windows)]
909fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
910 let path_str = normalize_windows_path(&path.to_string_lossy());
911 let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
912 let prefix_str = prefix_str.trim_end_matches('\\');
913 path_str == prefix_str
915 || path_str
916 .strip_prefix(prefix_str)
917 .is_some_and(|rest| rest.starts_with('\\'))
918}
919
920#[cfg(windows)]
921fn normalize_windows_path(s: &str) -> String {
922 let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
923 stripped.to_lowercase().replace('/', "\\")
924}
925
926#[cfg(windows)]
927fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
928 if let Ok(meta) = std::fs::symlink_metadata(path) {
929 if super::pathutil::is_symlink_or_reparse(&meta) {
932 return Err(PathJailError::Symlink {
933 path: path.to_path_buf(),
934 });
935 }
936 }
937 Ok(())
938}
939
940#[cfg(all(test, windows))]
941#[path = "pathjail_windows_tests.rs"]
942mod windows_prefix_tests;
943
944#[cfg(test)]
945#[path = "pathjail_tests.rs"]
946mod tests;