1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
use std::path::{Path, PathBuf};
use crate::core::error::PathJailError;
/// `allow_paths` / `extra_roots` come from `config.toml`, where no shell ever
/// runs — users writing `"$HOME/code"` or `"~/code"` got a literal,
/// never-matching prefix and concluded the whole option was broken (GH #392).
/// Unset variables are left verbatim (and warned about) so the entry fails
/// loudly in `lean-ctx doctor` instead of silently matching something else.
pub fn expand_user_path(raw: &str) -> PathBuf {
let mut s = raw.to_string();
if (s == "~" || s.starts_with("~/"))
&& let Some(home) = dirs::home_dir()
{
s = format!("{}{}", home.to_string_lossy(), &s[1..]);
}
while let Some(start) = s.find('$') {
let rest = &s[start + 1..];
let (name, token_len) = if let Some(stripped) = rest.strip_prefix('{') {
match stripped.find('}') {
Some(end) => (stripped[..end].to_string(), end + 3),
None => break,
}
} else {
let end = rest
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.unwrap_or(rest.len());
(rest[..end].to_string(), end + 1)
};
if name.is_empty() {
break;
}
if let Ok(val) = std::env::var(&name) {
s.replace_range(start..start + token_len, &val);
} else {
tracing::warn!(
"allow_paths/extra_roots entry '{raw}' references unset variable ${name} — entry will never match"
);
break;
}
}
PathBuf::from(s)
}
pub fn allow_paths_from_env_and_config() -> Vec<PathBuf> {
let mut out = Vec::new();
let cfg = crate::core::config::Config::load();
// The allow-list defines the jail boundary, so it must be canonicalized the
// same (security, symlink-resolving) way as the candidate it is compared
// against — otherwise a guarded (lexical) root vs a resolved candidate would
// break `is_under_prefix`. These entries are data_dir / IDE-config dirs /
// user-configured paths, virtually never under ~/Documents.
//
// This is also lean-ctx's own state dir (sessions, knowledge, …) — always
// readable even while foreign editor dirs stay jailed. On a legacy install
// the resolver returns `~/.lean-ctx`; on a split install it returns the XDG
// data dir. Going through the resolver (not a hardcoded `~/.lean-ctx` join)
// is what keeps `home_allow_dirs` free of the legacy-path firewall trip.
if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
out.push(canonicalize_secure(&data_dir));
}
if let Some(home) = dirs::home_dir() {
let ide_dirs_allowed = cfg.allow_ide_config_dirs.unwrap_or(false)
|| std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
out.extend(home_allow_dirs(&home, ide_dirs_allowed));
}
for p in &cfg.allow_paths {
out.push(canonicalize_secure(&expand_user_path(p)));
}
for p in &cfg.extra_roots {
out.push(canonicalize_secure(&expand_user_path(p)));
}
// Env entries are expanded too: MCP host configs pass env blocks verbatim
// (no shell), so "$HOME/code" arrives literally there as well.
let v = std::env::var("LCTX_ALLOW_PATH")
.or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
.unwrap_or_default();
if !v.trim().is_empty() {
for p in std::env::split_paths(&v) {
out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
}
}
let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
if !extra.trim().is_empty() {
for p in std::env::split_paths(&extra) {
out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
}
}
// Read-only roots are *readable* (the whole point is read access to sibling
// repos); writes into them are denied separately by `enforce_writable`
// (#475). Add them to the read allow-list so reads resolve, exactly like
// `extra_roots`, without granting write access.
out.extend(canonicalized_roots(
&cfg.read_only_roots,
"LEAN_CTX_READ_ONLY_ROOTS",
));
out
}
/// Canonicalize a set of config-supplied root entries plus an env override
/// (path-list separated), expanding `~`/`$VAR` first. Shared by the read
/// allow-list and the read-only-roots collector so both tiers parse roots
/// identically.
fn canonicalized_roots(config_entries: &[String], env_var: &str) -> Vec<PathBuf> {
let mut out = Vec::new();
for p in config_entries {
out.push(canonicalize_secure(&expand_user_path(p)));
}
let v = std::env::var(env_var).unwrap_or_default();
if !v.trim().is_empty() {
for p in std::env::split_paths(&v) {
out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
}
}
out
}
/// A read-only root is a sibling subtree the agent may **read** but never
/// **write** — e.g. a reference repo mounted next to the project. Empty by
/// default, so [`is_read_only_path`]/[`enforce_writable`] are zero-cost no-ops
/// for everyone who hasn't opted in (#475).
pub fn read_only_roots_from_env_and_config() -> Vec<PathBuf> {
let cfg = crate::core::config::Config::load();
let mut roots = canonicalized_roots(&cfg.read_only_roots, "LEAN_CTX_READ_ONLY_ROOTS");
// #899: session-scoped roots auto-detected from language caches. Consulted
// by both the read allow-list (jail) and `is_read_only_path` (write-deny),
// so a cache root is readable but never writable — exactly like a configured
// read-only root, minus the config-file edit.
roots.extend(session_read_only_roots());
roots
}
static SESSION_READ_ONLY_ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> =
std::sync::OnceLock::new();
fn session_read_only_roots_cell() -> &'static std::sync::Mutex<Vec<PathBuf>> {
SESSION_READ_ONLY_ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
}
/// The session-scoped read-only roots auto-registered this process (#899).
pub fn session_read_only_roots() -> Vec<PathBuf> {
session_read_only_roots_cell()
.lock()
.map(|g| g.clone())
.unwrap_or_default()
}
/// Register a session-scoped read-only root (an auto-detected language cache).
/// Returns `true` when newly added. Idempotent on the canonicalized path.
///
/// ponytail: process-global set, not per-session — language caches
/// (`~/go/pkg/mod`, `~/.cargo/registry`, …) are machine-global read-only dirs,
/// so sharing read access across sessions grants nothing a session couldn't
/// already get by reading them; per-session isolation would be plumbing for no
/// security gain. Upgrade to a session-keyed map only if writable roots ever go
/// down this path.
pub fn register_session_read_only_root(root: &Path) -> bool {
let canon = canonicalize_secure(root);
let mut guard = match session_read_only_roots_cell().lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
if guard.iter().any(|r| r == &canon) {
return false;
}
guard.push(canon);
true
}
/// A single active relaxation of the path jail. Each one widens or disables what
/// tools can reach beyond the project root, so it is surfaced loudly (GH security
/// audit, finding 3): the MCP/HTTP server inherits its process env from the
/// IDE/launchd, so a globally-set `LEAN_CTX_ALLOW_PATH` / `LEAN_CTX_EXTRA_ROOTS`
/// / `LEAN_CTX_ALLOW_IDE_DIRS` (or `path_jail = false`) silently loosens the
/// boundary with no in-band signal otherwise.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JailRelaxation {
/// The knob that activated it (env var name, config key, or build feature).
pub source: &'static str,
/// Human-readable effect of the relaxation.
pub detail: &'static str,
}
fn env_is_set(var: &str) -> bool {
std::env::var(var).is_ok_and(|v| !v.trim().is_empty())
}
/// Collect every currently-active path-jail relaxation. An empty result means
/// the jail is fully in force. This is the single source of truth shared by the
/// startup warning ([`warn_if_relaxed`]) and `lean-ctx doctor`.
#[must_use]
pub fn active_relaxations() -> Vec<JailRelaxation> {
let mut out = Vec::new();
if cfg!(feature = "no-jail") {
out.push(JailRelaxation {
source: "no-jail (build feature)",
detail: "path jail compiled out — every tool path is allowed",
});
}
if crate::core::config::Config::load().path_jail == Some(false) {
out.push(JailRelaxation {
source: "path_jail = false (config.toml)",
detail: "path jail disabled — every tool path is allowed",
});
}
if env_is_set("LEAN_CTX_ALLOW_PATH") || env_is_set("LCTX_ALLOW_PATH") {
out.push(JailRelaxation {
source: "LEAN_CTX_ALLOW_PATH",
detail: "widens the read/write allow-list beyond the project root",
});
}
if env_is_set("LEAN_CTX_EXTRA_ROOTS") {
out.push(JailRelaxation {
source: "LEAN_CTX_EXTRA_ROOTS",
detail: "adds extra accessible roots beyond the project root",
});
}
let ide_env = std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
if ide_env
|| crate::core::config::Config::load()
.allow_ide_config_dirs
.unwrap_or(false)
{
out.push(JailRelaxation {
source: if ide_env {
"LEAN_CTX_ALLOW_IDE_DIRS=1"
} else {
"allow_ide_config_dirs = true (config.toml)"
},
detail: "exposes ~/.cursor, ~/.claude, … (other agents' sessions/credentials) to tools",
});
}
out
}
/// Emit a loud `tracing::warn!` for every active path-jail relaxation. Called
/// once at MCP/HTTP server startup so a trusted-but-loosening env/config leaves
/// an in-band audit signal instead of silently defeating the jail (finding 3).
pub fn warn_if_relaxed() {
for relaxation in active_relaxations() {
tracing::warn!(
"[SECURITY] path jail relaxed via {}: {} — intended for trusted local use only",
relaxation.source,
relaxation.detail
);
}
}
/// True when `candidate` resolves to a location inside a configured read-only
/// root. The candidate's nearest existing ancestor is canonicalized (so a
/// not-yet-existing file inherits the read-only status of the directory it
/// would be created in — closing the "create a new file in a read-only repo"
/// hole) and matched against the (symlink-resolved) read-only roots.
///
/// A `false` return is only authoritative when the roots list is empty or the
/// path provably sits outside every root; an unresolvable candidate (no
/// existing ancestor) is treated as *not* read-only here and is rejected later
/// by the ordinary write/jail error, never silently written.
pub fn is_read_only_path(candidate: &Path) -> bool {
let roots = read_only_roots_from_env_and_config();
if roots.is_empty() {
return false;
}
// Compare the canonicalized nearest-existing-ancestor (resolves symlinks so
// a symlink *into* a read-only root can't launder a write past the prefix
// check), reconstructing the full path for the comparison.
let base = match canonicalize_existing_ancestor(candidate) {
Some((base, remainder)) => {
let mut p = base;
for part in remainder.iter().rev() {
p.push(part);
}
p
}
None => canonicalize_or_self(candidate),
};
roots.iter().any(|r| is_under_prefix(&base, r))
}
/// Default-deny write guard for the read-only tier (#475): returns an error if
/// `candidate` is inside a configured read-only root, `Ok(())` otherwise.
///
/// This is the single read-only-aware choke point. Every filesystem write that
/// can target a caller-supplied path routes through it (the atomic writers in
/// `ctx_edit`/`edit_apply`, the handoff/session export bundle writers, the
/// in-place memory-compaction writer, and the refactor IDE pre-write gate), so
/// a "read-only" root cannot be written through any tool. Reads are unaffected.
pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
if is_read_only_path(candidate) {
return Err(format!(
"path is inside a read-only root — writes are denied (read_only_roots): {}",
candidate.display()
));
}
Ok(())
}
/// Foreign editor config dirs for the jail (~/.cursor, ~/.claude, VS Code, …).
///
/// These expose other projects' sessions, MCP configs and credentials to any
/// agent, so they are opt-in only (config `allow_ide_config_dirs = true` or
/// `LEAN_CTX_ALLOW_IDE_DIRS=1`). lean-ctx's *own* state dir is intentionally NOT
/// handled here: the caller already adds it via the sanctioned `data_dir`
/// resolver (the legacy `~/.lean-ctx` is just one resolution of it). Keeping this
/// a pure foreign-editor list means no legacy `~/.lean-ctx` literal is built in
/// this module, so the legacy-path firewall (tests/legacy_path_firewall) has
/// nothing to flag.
fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
let mut out = Vec::new();
if ide_dirs_allowed {
let targets = crate::core::editor_registry::build_targets(home);
collect_ide_allow_dirs(home, &targets, &mut out);
}
out
}
/// Collect the in-home config/detect directories of every supported editor.
///
/// Derived from the editor registry (the single source of truth) so it covers
/// non-dotfile layouts too — VS Code's `Library/Application Support/Code/User`,
/// Cline/Roo globalStorage, JetBrains — and never drifts as editors are added.
/// A config file that sits directly in `$HOME` (`~/.claude.json`,
/// `~/.jb-mcp.json`) resolves its parent to `$HOME`; those entries are skipped
/// so the jail is never widened to the entire home directory.
fn collect_ide_allow_dirs(
home: &Path,
targets: &[crate::core::editor_registry::EditorTarget],
out: &mut Vec<PathBuf>,
) {
let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
for target in targets {
let candidates = [
target.config_path.parent().map(Path::to_path_buf),
Some(target.detect_path.clone()),
];
for cand in candidates.into_iter().flatten() {
if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
continue;
}
let resolved = canonicalize_secure(&cand);
if seen.insert(resolved.clone()) {
out.push(resolved);
}
}
}
}
fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
path.starts_with(prefix)
}
/// Heuristic canonicalize — honours the #356 TCC guard. Used by the
/// jail-disabled bypass and by external callers (session/startup/server roots)
/// that must not pop a privacy prompt on their own initiative.
pub fn canonicalize_or_self(path: &Path) -> PathBuf {
super::pathutil::safe_canonicalize_bounded(path, 2000)
}
/// SECURITY canonicalize for the jail boundary itself (roots + candidate +
/// escape re-check). Deliberately bypasses the #356 TCC guard: the jail must
/// keep resolving symlinks to detect escapes, and it only ever runs on a path
/// the client explicitly asked to access, where a one-time prompt is legitimate.
fn canonicalize_secure(path: &Path) -> PathBuf {
super::pathutil::canonicalize_secure_bounded(path, 2000)
}
fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
let mut cur = path.to_path_buf();
let mut remainder: Vec<std::ffi::OsString> = Vec::new();
loop {
if cur.exists() {
return Some((canonicalize_secure(&cur), remainder));
}
let name = cur.file_name()?.to_os_string();
remainder.push(name);
if !cur.pop() {
return None;
}
}
}
pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
jail_path_with_roots(candidate, jail_root, &[])
}
/// Known language-cache markers (#899): (path substring, human label, config
/// example). Single source of truth shared by [`detected_cache_hint`] (the
/// jail-error suggestion) and [`detect_language_cache_root`] (session
/// auto-registration), so the two never drift.
const LANGUAGE_CACHE_PATTERNS: &[(&str, &str, &str)] = &[
("/go/pkg/mod/", "Go module cache", "~/go/pkg/mod"),
(
"/.cargo/registry/",
"Rust crate registry",
"~/.cargo/registry",
),
(
"/site-packages/",
"Python site-packages",
"<venv>/lib/pythonX.Y/site-packages",
),
("/node_modules/", "Node modules", "<project>/node_modules"),
(
"/.m2/repository/",
"Maven local repository",
"~/.m2/repository",
),
("/.gradle/caches/", "Gradle cache", "~/.gradle/caches"),
(
"/.nuget/packages/",
"NuGet package cache",
"~/.nuget/packages",
),
];
/// Detect well-known language cache paths and return a targeted hint. Used for
/// jail callers that don't auto-register (e.g. batch reads); the single-path
/// ctx_read flow instead auto-registers via [`detect_language_cache_root`].
fn detected_cache_hint(candidate: &std::path::Path) -> Option<String> {
let s = candidate.to_string_lossy();
for &(pattern, name, example) in LANGUAGE_CACHE_PATTERNS {
if s.contains(pattern) {
return Some(format!(
". Detected {name} — add read_only_roots = [\"{example}\"] to \
~/.config/lean-ctx/config.toml for cached, compressed reads without write access"
));
}
}
None
}
/// If `candidate` sits inside a known language cache, return `(label, root)`
/// where `root` is the path truncated at the end of the marker directory (no
/// trailing slash). resolve_path uses this to auto-register a session read-only
/// root so the retry resolves without a config edit or a subprocess (#899).
pub fn detect_language_cache_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
let s = candidate.to_string_lossy().replace('\\', "/");
for &(marker, label, _) in LANGUAGE_CACHE_PATTERNS {
if let Some(idx) = s.find(marker) {
let end = idx + marker.len() - 1; // keep the marker dir, drop trailing '/'
return Some((label, PathBuf::from(&s[..end])));
}
}
None
}
/// Like [`jail_path`], but also accepts paths under any of `extra_roots`.
///
/// `extra_roots` are session-scoped trusted roots (MCP `roots/list` and config
/// `extra_roots`, surfaced via `session.extra_roots`) — e.g. sibling git
/// worktrees the agent legitimately spans. They widen the allow-list for *this
/// call only*, so an explicit `path` under a worktree resolves instead of
/// failing with "path escapes project root", without loosening the global jail
/// (#403). `path_jail = false` still bypasses entirely and an empty slice is
/// byte-for-byte identical to the old single-root behaviour.
pub fn jail_path_with_roots(
candidate: &Path,
jail_root: &Path,
extra_roots: &[String],
) -> Result<PathBuf, PathJailError> {
if candidate.to_string_lossy().as_bytes().contains(&0) {
return Err(PathJailError::NullByte);
}
#[cfg(feature = "no-jail")]
{
let _ = (jail_root, extra_roots);
return Ok(canonicalize_or_self(candidate));
}
#[allow(unreachable_code)]
{
let cfg = crate::core::config::Config::load();
if cfg.path_jail == Some(false) {
return Ok(canonicalize_or_self(candidate));
}
let root = canonicalize_secure(jail_root);
// Resolve relative candidates against the (absolute) jail root — never the process
// CWD. The daemon's CWD is not the project, so CWD-relative resolution made
// graph-relative paths (e.g. auto-preload candidates like `rust/src/core/foo.rs`)
// spuriously fail with "no existing ancestor". Absolute candidates are unchanged.
let resolved: PathBuf;
let candidate: &Path = if candidate.is_absolute() {
candidate
} else {
resolved = root.join(candidate);
resolved.as_path()
};
let mut allow = allow_paths_from_env_and_config();
// Session-scoped roots widen the allow-list for this call only.
allow.extend(
extra_roots
.iter()
.filter(|r| !r.is_empty())
.map(|r| canonicalize_secure(Path::new(r))),
);
// #820: lean-ctx's own state dir (tee files, artifacts, tool-results)
// must be readable even when outside the project root. ctx_shell
// tells agents to read tee-file paths, so the jail must allow them.
if let Ok(state) = crate::core::paths::state_dir() {
allow.push(canonicalize_secure(&state));
}
// Read-only roots are also allowed for reads (they only block writes
// via enforce_writable, not reads via the jail).
allow.extend(
read_only_roots_from_env_and_config()
.into_iter()
.map(|p| canonicalize_secure(&p)),
);
let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
PathJailError::NoExistingAncestor {
path: candidate.to_path_buf(),
}
})?;
let allowed =
is_under_prefix(&base, &root) || allow.iter().any(|p| is_under_prefix(&base, p));
#[cfg(windows)]
let allowed = allowed || is_under_prefix_windows(&base, &root);
if !allowed {
let mut hint = if crate::core::protocol::meta_visible() {
let dir = candidate.parent().unwrap_or(candidate).display();
format!(
". Hint: set LEAN_CTX_ALLOW_PATH={dir} for read-write access \
(colon-separated for multiple: /path/a:/path/b), \
LEAN_CTX_READ_ONLY_ROOTS={dir} for read-only, \
or add entries to allow_paths = [\"{dir}\"] or extra_roots = [\"{dir}\"] \
in ~/.config/lean-ctx/config.toml"
)
} else {
// Agents otherwise get a bare rejection and shell out to work
// around the jail; name the config keys the same way the
// shell-allowlist block message names its key. The env-var and
// config-path detail above stays meta-gated (#540, #887).
". Fix (additive): add the directory to extra_roots or allow_paths in \
~/.config/lean-ctx/config.toml — `lean-ctx doctor` shows the config in effect"
.to_string()
};
// An untrusted workspace's project-local `allow_paths` is silently
// withheld; always surface that reason (the stderr warning is
// invisible over MCP, and the hint above is meta-gated off) (#540).
if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
hint.push_str(". ");
hint.push_str(¬ice);
}
// The global config the runtime reads doesn't exist → on defaults, so
// an `allow_paths` edit made to a config.toml elsewhere (XDG vs legacy
// dir, or a sandboxed/container HOME) is never seen (#540).
if let Some(missing) = crate::core::config::Config::missing_config_path() {
hint.push_str(&format!(
". ⚠lean-ctx reads no config file at {} (running on defaults) — an \
allow_paths edit in a config.toml elsewhere is not read; \
`lean-ctx doctor` shows the path in effect",
missing.display()
));
}
if let Some(cache_hint) = detected_cache_hint(candidate) {
hint.push_str(&cache_hint);
}
return Err(PathJailError::EscapesRoot {
path: candidate.to_path_buf(),
root,
hint,
});
}
#[cfg(windows)]
reject_symlink_on_windows(candidate)?;
let mut out = base;
for part in remainder.iter().rev() {
out.push(part);
}
// Re-validate after reconstruction: if the final path exists, canonicalize
// and re-check to close TOCTOU window (symlink created between check and use).
if out.exists() {
let final_canon = canonicalize_secure(&out);
let final_ok = is_under_prefix(&final_canon, &root)
|| allow.iter().any(|p| is_under_prefix(&final_canon, p));
#[cfg(windows)]
let final_ok = final_ok || is_under_prefix_windows(&final_canon, &root);
if !final_ok {
return Err(PathJailError::PostCanonicalizeEscape {
path: candidate.to_path_buf(),
resolved: final_canon,
});
}
}
Ok(out)
}
}
#[cfg(windows)]
fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
let path_str = normalize_windows_path(&path.to_string_lossy());
let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
path_str.starts_with(&prefix_str)
}
#[cfg(windows)]
fn normalize_windows_path(s: &str) -> String {
let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
stripped.to_lowercase().replace('/', "\\")
}
#[cfg(windows)]
fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
if let Ok(meta) = std::fs::symlink_metadata(path) {
// Junctions and other reparse points redirect like symlinks but are
// invisible to `is_symlink()` — reject them too (GL#442).
if super::pathutil::is_symlink_or_reparse(&meta) {
return Err(PathJailError::Symlink {
path: path.to_path_buf(),
});
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "no-jail"))]
#[test]
fn rejects_path_outside_root() {
// Hermetic config (empty data dir => jail on) so a parallel test that
// flips `path_jail` cannot leak into this enforcement check. The guard
// holds the global test_env_lock, which also serializes against every
// `LEAN_CTX_ALLOW_PATH` mutation (all of them go through that lock).
let _iso = crate::core::data_dir::isolated_data_dir();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(root.join("a.txt"), "ok").unwrap();
std::fs::write(other.join("b.txt"), "no").unwrap();
let ok = jail_path(&root.join("a.txt"), &root);
assert!(ok.is_ok());
let bad = jail_path(&other.join("b.txt"), &root);
assert!(bad.is_err());
}
/// #475: a configured read-only root is readable but never writable. Reads
/// resolve (the root joins the allow-list like an extra_root), while the
/// single write choke point `enforce_writable` default-denies every write
/// inside it — including a not-yet-existing file, which inherits the
/// directory's read-only status. `isolated_data_dir` holds `test_env_lock`,
/// serialising the `LEAN_CTX_READ_ONLY_ROOTS` mutation against other tests.
#[cfg(not(feature = "no-jail"))]
#[test]
fn read_only_roots_deny_writes_but_allow_reads() {
let _iso = crate::core::data_dir::isolated_data_dir();
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("project");
let refrepo = tmp.path().join("refrepo");
std::fs::create_dir_all(&project).unwrap();
std::fs::create_dir_all(refrepo.join("sub")).unwrap();
std::fs::write(refrepo.join("lib.rs"), "pub fn x() {}\n").unwrap();
// Canonicalize the configured root the same (symlink-resolving) way the
// guard does, so macOS /var → /private/var can't defeat the prefix match.
let ro_canon = canonicalize_secure(&refrepo);
crate::test_env::set_var(
"LEAN_CTX_READ_ONLY_ROOTS",
ro_canon.to_string_lossy().as_ref(),
);
let existing = refrepo.join("lib.rs");
let new_file = refrepo.join("sub").join("new.rs");
let proj_file = project.join("main.rs");
// Capture every decision while the env is live (it is cleared below).
let read_existing = jail_path(&existing, &project);
let deny_existing = enforce_writable(&existing);
let deny_new = enforce_writable(&new_file);
let allow_project = enforce_writable(&proj_file);
let ro_existing = is_read_only_path(&existing);
let ro_project = is_read_only_path(&proj_file);
crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");
assert!(
deny_existing.is_err(),
"write to an existing file in a read-only root must be denied"
);
assert!(
deny_new.is_err(),
"creating a new file in a read-only root must be denied"
);
assert!(
allow_project.is_ok(),
"writes into the project root must stay allowed: {allow_project:?}"
);
assert!(
read_existing.is_ok(),
"reads inside a read-only root must resolve (read allow-list): {read_existing:?}"
);
assert!(ro_existing, "the file is inside the read-only root");
assert!(!ro_project, "the project file is not read-only");
}
/// #406 regression: a long-lived process (the MCP server) must honor
/// `path_jail = false` written to config after startup. The config cache is
/// now keyed on content, so even an edit that preserves the file mtime takes
/// effect — a path outside the jail root is accepted once the flag flips.
/// (With the former mtime-only cache the stale `None` kept the jail on.)
#[cfg(not(feature = "no-jail"))]
#[test]
fn honors_path_jail_false_after_mtime_preserving_edit() {
let _iso = crate::core::data_dir::isolated_data_dir();
let cfg_path = crate::core::config::Config::path().unwrap();
if let Some(parent) = cfg_path.parent() {
std::fs::create_dir_all(parent).unwrap();
}
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let secret = outside.join("secret.txt");
std::fs::write(&secret, "x").unwrap();
// Warm the config cache with the jail on (no path_jail key).
std::fs::write(&cfg_path, "# jail on\n").unwrap();
let mtime0 = std::fs::metadata(&cfg_path).unwrap().modified().unwrap();
assert_eq!(crate::core::config::Config::load().path_jail, None);
// Flip path_jail=false but restore the original mtime, so any mtime-only
// cache would keep serving the stale jail-on value.
std::fs::write(&cfg_path, "path_jail = false\n").unwrap();
filetime::set_file_mtime(&cfg_path, filetime::FileTime::from_system_time(mtime0)).unwrap();
assert!(
jail_path(&secret, &root).is_ok(),
"path_jail=false must take effect without a fresh process (#406)"
);
}
#[test]
fn allows_nonexistent_child_under_root() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("a.txt"), "ok").unwrap();
let p = root.join("new").join("file.txt");
let ok = jail_path(&p, &root).unwrap();
assert!(ok.to_string_lossy().contains("file.txt"));
}
#[cfg(not(feature = "no-jail"))]
#[test]
fn relative_candidate_resolves_against_root_not_cwd() {
// Regression: in the daemon (CWD != project) a relative graph path like
// `sub/file.rs` must resolve under the jail root, not the process CWD.
let _iso = crate::core::data_dir::isolated_data_dir();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
std::fs::create_dir_all(root.join("sub")).unwrap();
std::fs::write(root.join("sub").join("file.rs"), "ok").unwrap();
let jailed = jail_path(Path::new("sub/file.rs"), &root)
.expect("relative candidate should resolve under the jail root");
assert!(jailed.ends_with("sub/file.rs"));
assert!(
is_under_prefix(&canonicalize_or_self(&jailed), &canonicalize_or_self(&root)),
"resolved path must live under the jail root: {jailed:?}"
);
}
#[test]
fn ide_allow_dirs_are_registry_derived_and_skip_home() {
use crate::core::editor_registry::{ConfigType, EditorTarget};
let home = tempfile::tempdir().unwrap();
let h = home.path();
// VS Code keeps its config outside a dotfile dir — the old hard-coded
// list missed this entirely.
std::fs::create_dir_all(h.join("Library/Application Support/Code/User")).unwrap();
std::fs::create_dir_all(h.join(".cursor")).unwrap();
let targets = vec![
EditorTarget {
name: "VS Code",
agent_key: "vscode".into(),
config_path: h.join("Library/Application Support/Code/User/mcp.json"),
detect_path: h.join("Library/Application Support/Code"),
config_type: ConfigType::VsCodeMcp,
},
EditorTarget {
name: "Cursor",
agent_key: "cursor".into(),
config_path: h.join(".cursor/mcp.json"),
detect_path: h.join(".cursor"),
config_type: ConfigType::McpJson,
},
// A $HOME-level config file: its parent is $HOME and must be skipped.
EditorTarget {
name: "Claude Code",
agent_key: "claude".into(),
config_path: h.join(".claude.json"),
detect_path: h.join(".no-such-dir"),
config_type: ConfigType::McpJson,
},
];
let mut out = Vec::new();
collect_ide_allow_dirs(h, &targets, &mut out);
assert!(
out.iter().any(|p| p.ends_with("Code/User")),
"non-dotfile VS Code dir must be covered: {out:?}"
);
assert!(out.iter().any(|p| p.ends_with(".cursor")), "{out:?}");
let home_canon = canonicalize_secure(h);
assert!(
!out.contains(&home_canon),
"must never widen the jail to $HOME: {out:?}"
);
}
// P0-10 (#422): foreign editor config dirs are opt-in. lean-ctx's own state
// dir is added by the caller via the data_dir root, NOT by `home_allow_dirs`,
// so the default home allow-list is empty and `~/.lean-ctx` (not an editor)
// never appears here.
#[test]
fn ide_config_dirs_are_excluded_by_default() {
let home = tempfile::tempdir().unwrap();
for d in [".lean-ctx", ".cursor", ".codex"] {
std::fs::create_dir_all(home.path().join(d)).unwrap();
}
let denied = home_allow_dirs(home.path(), false);
assert!(
denied.is_empty(),
"foreign editor dirs must stay jailed by default: {denied:?}"
);
// Opt-in exposes the editor dirs that actually exist under this home.
// Entries are registry-derived (foreign real-$HOME paths are filtered out
// by the in-home guard), so the result stays hermetic — and `~/.lean-ctx`
// is never added here because it is not an editor.
let allowed = home_allow_dirs(home.path(), true);
assert!(
allowed.iter().any(|p| p.ends_with(".cursor")),
"opt-in must expose editor dirs: {allowed:?}"
);
assert!(
!allowed.iter().any(|p| p.ends_with(".lean-ctx")),
"lean-ctx's own dir is covered by the data_dir root, not home_allow_dirs: {allowed:?}"
);
}
#[test]
fn canonicalize_or_self_strips_verbatim() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("project");
std::fs::create_dir_all(&dir).unwrap();
let result = canonicalize_or_self(&dir);
let s = result.to_string_lossy();
assert!(
!s.starts_with(r"\\?\"),
"canonicalize_or_self should strip verbatim prefix, got: {s}"
);
}
#[test]
fn jail_path_accepts_same_dir_different_format() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("file.rs"), "ok").unwrap();
let result = jail_path(&root.join("file.rs"), &root);
assert!(result.is_ok(), "same dir should be accepted: {result:?}");
}
#[cfg(not(feature = "no-jail"))]
#[test]
fn error_message_contains_escape_info() {
// isolated_data_dir holds the global test_env_lock, serializing this
// against any parallel `LEAN_CTX_ALLOW_PATH="/"` mutation.
let _iso = crate::core::data_dir::isolated_data_dir();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("b.txt"), "no").unwrap();
let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
assert!(
err.to_string().contains("path escapes project root"),
"error should mention escape: {err}"
);
}
// GH #887: over MCP (meta hints gated off) the rejection was bare, so
// agents shelled out to work around the jail instead of widening it via
// config. The agent-visible error must name the sanctioned config keys.
#[cfg(not(feature = "no-jail"))]
#[test]
fn escape_error_names_config_keys_without_meta() {
let _iso = crate::core::data_dir::isolated_data_dir();
crate::test_env::remove_var("LEAN_CTX_META");
crate::test_env::remove_var("LEAN_CTX_DIAGNOSTICS");
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("b.txt"), "no").unwrap();
let err = jail_path(&other.join("b.txt"), &root).unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("extra_roots") && msg.contains("allow_paths"),
"agent-visible escape error should name the config keys: {msg}"
);
}
// GH #392: config entries like "$HOME/code" or "~/code" were taken
// literally and never matched.
#[test]
fn expand_user_path_expands_tilde_and_vars() {
let home = dirs::home_dir().expect("home dir");
let home_s = home.to_string_lossy().to_string();
assert_eq!(expand_user_path("~"), home);
assert_eq!(expand_user_path("~/code"), home.join("code"));
assert_eq!(expand_user_path("$HOME/code"), home.join("code"));
assert_eq!(expand_user_path("${HOME}/code"), home.join("code"));
// Multiple variables in one entry.
crate::test_env::set_var("LEAN_CTX_TEST_SUB", "sub");
assert_eq!(
expand_user_path("$HOME/$LEAN_CTX_TEST_SUB/x"),
PathBuf::from(format!("{home_s}/sub/x"))
);
crate::test_env::remove_var("LEAN_CTX_TEST_SUB");
// Absolute paths pass through untouched.
assert_eq!(expand_user_path("/etc"), PathBuf::from("/etc"));
}
#[test]
fn expand_user_path_leaves_unset_vars_verbatim() {
crate::test_env::remove_var("LEAN_CTX_TEST_UNSET_VAR");
let p = expand_user_path("$LEAN_CTX_TEST_UNSET_VAR/code");
assert_eq!(p, PathBuf::from("$LEAN_CTX_TEST_UNSET_VAR/code"));
}
// GH #392: `allow_paths = ["/"]` (via the same env-var channel) must grant
// access to any absolute path — "/" is a prefix of everything.
//
// Env-mutating tests here hold the process-global
// `data_dir::test_env_lock()` (directly, or via `isolated_data_dir()`
// which wraps it) — NOT a module-local mutex. test_env's SAFETY contract
// says *all* test env mutation serializes through that one lock; a local
// lock only serializes this module against itself, so e.g.
// `artifacts::external_corpus_requires_allow_list` (which holds the
// global lock) could observe this test's `LEAN_CTX_ALLOW_PATH="/"` and
// fail its jail-rejection assert (the pre-existing parallel-run flake
// reported in #695).
#[cfg(unix)]
#[test]
fn allow_path_root_slash_permits_everything() {
let _guard = crate::core::data_dir::test_env_lock();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("b.txt"), "allowed").unwrap();
crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/");
let result = jail_path(&other.join("b.txt"), &root);
crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
assert!(result.is_ok(), "allow path '/' must permit all: {result:?}");
}
// Finding 3 (GH security audit): env-channel jail relaxations must be
// detectable so startup + doctor can surface them loudly.
#[test]
fn active_relaxations_detects_allow_path_env() {
let _iso = crate::core::data_dir::isolated_data_dir();
crate::test_env::remove_var("LEAN_CTX_EXTRA_ROOTS");
crate::test_env::remove_var("LEAN_CTX_ALLOW_IDE_DIRS");
crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", "/tmp");
let relaxed = active_relaxations();
crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
assert!(
relaxed.iter().any(|r| r.source == "LEAN_CTX_ALLOW_PATH"),
"LEAN_CTX_ALLOW_PATH must be reported as a jail relaxation: {relaxed:?}"
);
}
#[cfg(not(feature = "no-jail"))]
#[test]
fn active_relaxations_empty_when_jail_intact() {
let _iso = crate::core::data_dir::isolated_data_dir();
for var in [
"LEAN_CTX_ALLOW_PATH",
"LCTX_ALLOW_PATH",
"LEAN_CTX_EXTRA_ROOTS",
"LEAN_CTX_ALLOW_IDE_DIRS",
] {
crate::test_env::remove_var(var);
}
assert!(
active_relaxations().is_empty(),
"an intact jail (clean config, no relaxation env) must report no relaxations: {:?}",
active_relaxations()
);
}
#[test]
fn allow_path_env_permits_outside_root() {
let _guard = crate::core::data_dir::test_env_lock();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("b.txt"), "allowed").unwrap();
let canon = canonicalize_or_self(&other);
crate::test_env::set_var("LEAN_CTX_ALLOW_PATH", canon.to_string_lossy().as_ref());
let result = jail_path(&other.join("b.txt"), &root);
crate::test_env::remove_var("LEAN_CTX_ALLOW_PATH");
assert!(
result.is_ok(),
"LEAN_CTX_ALLOW_PATH should permit access: {result:?}"
);
}
#[cfg(all(unix, not(feature = "no-jail")))]
#[test]
fn rejects_symlink_escape_on_unix() {
use std::os::unix::fs::symlink;
// isolated_data_dir holds the global test_env_lock — no parallel test
// can set `LEAN_CTX_ALLOW_PATH="/"` and let this escape resolve.
let _iso = crate::core::data_dir::isolated_data_dir();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
let other = tmp.path().join("other");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(other.join("secret.txt"), "no").unwrap();
let link = root.join("link.txt");
symlink(other.join("secret.txt"), &link).unwrap();
let bad = jail_path(&link, &root);
assert!(bad.is_err(), "symlink escape must be rejected: {bad:?}");
}
#[test]
fn rejects_null_byte_in_path() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("root");
std::fs::create_dir_all(&root).unwrap();
let bad_path = PathBuf::from("file\0.txt");
let result = jail_path(&bad_path, &root);
assert!(result.is_err(), "null byte in path must be rejected");
assert!(
result.unwrap_err().to_string().contains("null byte"),
"error must mention null byte"
);
}
/// #403 Bug 1: an explicit path under a session-scoped `extra_root` (e.g. a
/// sibling git worktree from MCP `roots/list`) must resolve, while the same
/// path is rejected without it — and a path under *no* root is rejected even
/// when extra roots are present. Holds both env locks so neither a parallel
/// `path_jail` flip nor a `LEAN_CTX_ALLOW_PATH` mutation can leak in.
#[cfg(not(feature = "no-jail"))]
#[test]
fn extra_roots_permit_paths_outside_jail() {
let _iso = crate::core::data_dir::isolated_data_dir();
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("project");
let worktree = tmp.path().join("worktree");
let elsewhere = tmp.path().join("elsewhere");
for d in [&root, &worktree, &elsewhere] {
std::fs::create_dir_all(d).unwrap();
}
let in_worktree = worktree.join("a.txt");
std::fs::write(&in_worktree, "x").unwrap();
let outside = elsewhere.join("b.txt");
std::fs::write(&outside, "y").unwrap();
// Parity: with no extra roots, the worktree path escapes the jail.
assert!(jail_path(&in_worktree, &root).is_err());
assert!(jail_path_with_roots(&in_worktree, &root, &[]).is_err());
// The session-scoped extra root permits it — via the slice alone, with
// nothing in env/config.
let extra = vec![worktree.to_string_lossy().to_string()];
assert!(
jail_path_with_roots(&in_worktree, &root, &extra).is_ok(),
"path under a session extra_root must resolve (#403)"
);
// A path under neither the jail nor any extra root is still rejected.
assert!(
jail_path_with_roots(&outside, &root, &extra).is_err(),
"paths outside ALL roots must still be rejected"
);
// Empty entries are ignored (no accidental allow-all).
assert!(jail_path_with_roots(&outside, &root, &[String::new()]).is_err());
}
/// #820: lean-ctx state dir (tee files) is implicitly allowed by the jail.
#[test]
fn state_dir_tee_files_pass_jail() {
let _lock = crate::core::data_dir::test_env_lock();
let state = crate::core::paths::state_dir().expect("state_dir must be available");
let tee_path = state.join("tee").join("some_command_deadbeef.log");
// Use a root that is clearly NOT the state dir's parent
let fake_root = std::env::temp_dir().join("pathjail_test_820_root");
std::fs::create_dir_all(&fake_root).ok();
// The tee path is outside the fake root, but the state dir allowance
// should make it pass (the state dir itself exists on disk).
let result = jail_path_with_roots(&tee_path, &fake_root, &[]);
// If state_dir exists on disk (it does in dev), the path should be allowed.
// If the tee file itself doesn't exist, canonicalize_existing_ancestor
// resolves to the state_dir (which does exist) + remainder.
if state.exists() {
assert!(
result.is_ok(),
"tee-file path under lean-ctx state dir must be auto-allowed: {result:?}"
);
}
std::fs::remove_dir_all(&fake_root).ok();
}
#[test]
fn detected_cache_hint_recognizes_go_cargo_python() {
use std::path::Path;
let go = detected_cache_hint(Path::new("/Users/x/go/pkg/mod/github.com/foo/bar/main.go"));
assert!(go.is_some(), "Go module cache should be detected");
assert!(go.unwrap().contains("Go module cache"));
let cargo = detected_cache_hint(Path::new(
"/home/x/.cargo/registry/src/crates.io/serde-1.0/lib.rs",
));
assert!(cargo.is_some(), "Rust cargo registry should be detected");
assert!(cargo.unwrap().contains("Rust crate registry"));
let py = detected_cache_hint(Path::new(
"/usr/lib/python3.12/site-packages/requests/api.py",
));
assert!(py.is_some(), "Python site-packages should be detected");
let normal = detected_cache_hint(Path::new("/home/x/projects/myapp/src/main.rs"));
assert!(normal.is_none(), "Normal project path should not match");
}
#[test]
fn detect_cache_root_extracts_marker_dir() {
let cases = [
(
"/Users/x/go/pkg/mod/github.com/foo/bar@v1.2.3/baz.go",
"Go module cache",
"/Users/x/go/pkg/mod",
),
(
"/home/u/.cargo/registry/src/index-abc/serde-1.0/src/lib.rs",
"Rust crate registry",
"/home/u/.cargo/registry",
),
(
"/opt/venv/lib/python3.12/site-packages/requests/api.py",
"Python site-packages",
"/opt/venv/lib/python3.12/site-packages",
),
(
"/w/app/node_modules/react/index.js",
"Node modules",
"/w/app/node_modules",
),
];
for (path, want_label, want_root) in cases {
let (label, root) = detect_language_cache_root(Path::new(path))
.unwrap_or_else(|| panic!("expected cache match for {path}"));
assert_eq!(label, want_label, "label for {path}");
assert_eq!(root, PathBuf::from(want_root), "root for {path}");
}
assert!(
detect_language_cache_root(Path::new("/home/u/proj/src/main.rs")).is_none(),
"a normal project path is not a cache"
);
}
/// The core #899 guarantee: once a detected cache root is registered, a path
/// under it *reads* (jail resolves) but never *writes* (enforce_writable
/// denies), and registration is idempotent.
#[cfg(not(feature = "no-jail"))]
#[test]
fn registered_cache_root_reads_allow_writes_deny() {
let _iso = crate::core::data_dir::isolated_data_dir();
let tmp = tempfile::tempdir().unwrap();
// A fake Go module cache so detect_language_cache_root matches the path.
let dep = tmp.path().join("go/pkg/mod/example.com/lib@v1");
std::fs::create_dir_all(&dep).unwrap();
let file = dep.join("lib.go");
std::fs::write(&file, "package lib").unwrap();
// A project jail that does NOT contain the cache.
let project = tmp.path().join("project");
std::fs::create_dir_all(&project).unwrap();
// Before registration: the read escapes the jail.
assert!(jail_path_with_roots(&file, &project, &[]).is_err());
// Register the detected root; the second call is a no-op.
let (_, root) = detect_language_cache_root(&file).expect("cache match");
assert!(
register_session_read_only_root(&root),
"first register is new"
);
assert!(
!register_session_read_only_root(&root),
"re-register is a no-op"
);
// After: the read resolves, but writes are denied (read-only tier).
assert!(
jail_path_with_roots(&file, &project, &[]).is_ok(),
"registered cache root must be readable"
);
assert!(is_read_only_path(&file), "cache file is read-only");
assert!(
enforce_writable(&file).is_err(),
"writes into the cache root must be denied"
);
}
}