1use std::{
7 fs,
8 path::{Component, MAIN_SEPARATOR, Path, PathBuf},
9};
10
11use alloy_primitives::keccak256;
12use eyre::Result;
13use foundry_common::fs::{canonicalize_path, normalize_path};
14use foundry_compilers::artifacts::remappings::{RelativeRemapping, Remapping};
15use foundry_config::{
16 Config, fs_permissions::FsAccessKind, providers::relative_remapping_preserving_context_boundary,
17};
18
19#[cfg(windows)]
20use std::os::windows::fs::FileTypeExt;
21
22pub fn is_safe_relative_path(p: &Path) -> bool {
25 !p.is_absolute()
26 && p.components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
27}
28
29pub fn ensure_safe_relative_path(rel: &Path, label: &str, orig: &Path) -> Result<()> {
32 if !is_safe_relative_path(rel) {
33 eyre::bail!("requires {label} directory under project root, got: {}", orig.display());
34 }
35 Ok(())
36}
37
38pub fn relative_to_root(root: &Path, path: &Path) -> PathBuf {
40 let root = normalize_existing_ancestor(root);
41 let path = normalize_existing_ancestor(path);
42 path.strip_prefix(root).map(|p| p.to_path_buf()).unwrap_or(path)
43}
44
45fn resolve_against_root(root: &Path, path: &Path) -> PathBuf {
46 let path = if path.is_absolute() { path.to_path_buf() } else { root.join(path) };
47 normalize_existing_ancestor(&path)
48}
49
50pub fn rebase_config_paths(config: &Config, temp_path: &Path) -> Config {
55 let temp_root = normalize_existing_ancestor(temp_path);
58 let temp_path = temp_root.as_path();
59 let mut temp_config = config.clone();
60 temp_config.root = temp_path.to_path_buf();
61 temp_config.src = rebase_project_path(&config.root, temp_path, &config.src);
62 temp_config.test = rebase_project_path(&config.root, temp_path, &config.test);
63 temp_config.script = rebase_project_path(&config.root, temp_path, &config.script);
64 temp_config.out = rebase_project_path(&config.root, temp_path, &config.out);
65 temp_config.cache_path = rebase_project_path(&config.root, temp_path, &config.cache_path);
66 temp_config.snapshots = rebase_project_path(&config.root, temp_path, &config.snapshots);
67 temp_config.broadcast = rebase_project_path(&config.root, temp_path, &config.broadcast);
68 temp_config.mutation_dir = rebase_project_path(&config.root, temp_path, &config.mutation_dir);
69 temp_config.test_failures_file =
70 rebase_project_path(&config.root, temp_path, &config.test_failures_file);
71 temp_config.build_info_path = config
72 .build_info_path
73 .as_ref()
74 .map(|path| rebase_project_path(&config.root, temp_path, path));
75 temp_config.libs =
76 config.libs.iter().map(|lib| rebase_project_path(&config.root, temp_path, lib)).collect();
77 temp_config.remappings = config
78 .remappings
79 .iter()
80 .map(|remapping| rebase_remapping(&config.root, temp_path, remapping))
81 .collect();
82 temp_config.include_paths = config
83 .include_paths
84 .iter()
85 .map(|path| rebase_project_path(&config.root, temp_path, path))
86 .collect();
87 temp_config.allow_paths = config
88 .allow_paths
89 .iter()
90 .map(|path| rebase_project_path(&config.root, temp_path, path))
91 .collect();
92 temp_config.ignored_error_codes_from = config
93 .ignored_error_codes_from
94 .iter()
95 .map(|(path, codes)| (rebase_source_prefix(&config.root, temp_path, path), codes.clone()))
96 .collect();
97 temp_config.ignored_file_paths = config
98 .ignored_file_paths
99 .iter()
100 .map(|path| rebase_source_prefix(&config.root, temp_path, path))
101 .collect();
102
103 if let Some(path) = &config.fuzz.failure_persist_dir {
104 temp_config.fuzz.failure_persist_dir =
105 Some(rebase_mutable_project_path(config, temp_path, path));
106 }
107 if let Some(path) = &config.fuzz.corpus.corpus_dir {
108 temp_config.fuzz.corpus.corpus_dir =
109 Some(rebase_mutable_project_path(config, temp_path, path));
110 }
111 if let Some(path) = &config.fuzz.corpus.frontier_dir {
112 temp_config.fuzz.corpus.frontier_dir =
113 Some(rebase_mutable_project_path(config, temp_path, path));
114 }
115 if let Some(path) = &config.invariant.failure_persist_dir {
116 temp_config.invariant.failure_persist_dir =
117 Some(rebase_mutable_project_path(config, temp_path, path));
118 }
119 if let Some(path) = &config.invariant.corpus.corpus_dir {
120 temp_config.invariant.corpus.corpus_dir =
121 Some(rebase_mutable_project_path(config, temp_path, path));
122 }
123 if let Some(path) = &config.invariant.corpus.frontier_dir {
124 temp_config.invariant.corpus.frontier_dir =
125 Some(rebase_mutable_project_path(config, temp_path, path));
126 }
127 for permission in &mut temp_config.fs_permissions.permissions {
128 let path = rebase_project_path(&config.root, temp_path, &permission.path);
129 permission.path = normalize_existing_ancestor(&path);
130 }
131 if let Some(model_checker) = &mut temp_config.model_checker {
132 model_checker.contracts = std::mem::take(&mut model_checker.contracts)
133 .into_iter()
134 .map(|(path, contracts)| {
135 let path = rebase_project_path(&config.root, temp_path, Path::new(&path));
136 (path.display().to_string(), contracts)
137 })
138 .collect();
139 }
140
141 temp_config
142}
143
144fn rebase_project_path(root: &Path, temp_path: &Path, path: &Path) -> PathBuf {
145 let lexical = normalize_path(&root.join(path));
147 if let Ok(rel) = lexical.strip_prefix(normalize_path(root))
150 && temp_path.join(rel).exists()
151 && !normalize_existing_ancestor(&temp_path.join(rel))
152 .starts_with(normalize_existing_ancestor(temp_path))
153 {
154 return temp_path.join(rel);
155 }
156 let resolved = resolve_against_root(root, path);
157 let rel = relative_to_root(root, &resolved);
158 if rel.is_absolute() { resolved } else { temp_path.join(rel) }
159}
160
161fn rebase_source_prefix(root: &Path, temp_path: &Path, path: &Path) -> PathBuf {
164 if path.is_relative() {
165 return path.to_path_buf();
166 }
167 rebase_project_path(root, temp_path, path)
168}
169
170fn rebase_mutable_project_path(config: &Config, temp_path: &Path, path: &Path) -> PathBuf {
171 let resolved = resolve_against_root(&config.root, path);
172 let rel = relative_to_root(&config.root, &resolved);
173 if rel.is_absolute() || is_covered_by_symlinked_project_root(config, &rel) {
174 return temp_path.join(isolated_mutable_path_rel(&resolved));
175 }
176 temp_path.join(rel)
177}
178
179fn isolated_mutable_path_rel(resolved: &Path) -> PathBuf {
180 PathBuf::from(".foundry_mutable")
181 .join(format!("{:x}", keccak256(resolved.as_os_str().as_encoded_bytes())))
182}
183
184fn is_covered_by_symlinked_project_root(config: &Config, rel: &Path) -> bool {
185 config.libs.iter().any(|path| {
186 let resolved = resolve_against_root(&config.root, path);
187 let lib_rel = relative_to_root(&config.root, &resolved);
188 !lib_rel.is_absolute() && !lib_rel.as_os_str().is_empty() && rel.starts_with(lib_rel)
189 }) || ["node_modules", "dependencies"].iter().any(|dep_dir| rel.starts_with(dep_dir))
190}
191
192fn normalize_existing_ancestor(path: &Path) -> PathBuf {
193 if path.exists() {
194 return canonicalize_path(path).unwrap_or_else(|_| path.to_path_buf());
195 }
196
197 let mut ancestor = path;
198 let mut missing = Vec::new();
199 while let Some(parent) = ancestor.parent() {
200 if ancestor.exists() {
201 break;
202 }
203 missing.push(ancestor.strip_prefix(parent).unwrap().to_path_buf());
204 ancestor = parent;
205 }
206
207 let mut normalized = canonicalize_path(ancestor).unwrap_or_else(|_| ancestor.to_path_buf());
208 for component in missing.iter().rev() {
209 normalized.push(component);
210 }
211 normalize_path(&normalized)
212}
213
214fn rebase_remapping(
215 root: &Path,
216 temp_path: &Path,
217 remapping: &RelativeRemapping,
218) -> RelativeRemapping {
219 let context_has_boundary =
220 remapping.context.as_deref().is_some_and(|context| context.ends_with(['/', '\\']));
221 let mut remapping: Remapping = remapping.clone().into();
222 remapping.path =
223 rebase_project_path(root, temp_path, Path::new(&remapping.path)).display().to_string();
224 if let Some(context) = &mut remapping.context {
225 *context = rebase_project_path(root, temp_path, Path::new(context)).display().to_string();
226 if context_has_boundary && !context.ends_with(['/', '\\']) {
227 context.push(MAIN_SEPARATOR);
228 }
229 }
230 relative_remapping_preserving_context_boundary(remapping, temp_path)
231}
232
233pub(crate) fn ensure_within_root(
239 allowed_root: &Path,
240 candidate: &Path,
241 label: &str,
242 orig: &Path,
243) -> Result<()> {
244 if !candidate.exists() {
246 return Ok(());
247 }
248 let canon_root = allowed_root.canonicalize().map_err(|e| {
249 eyre::eyre!("failed to canonicalize project root {}: {e}", allowed_root.display())
250 })?;
251 let canon_candidate = candidate.canonicalize().map_err(|e| {
252 eyre::eyre!("failed to canonicalize {label} path {}: {e}", candidate.display())
253 })?;
254 if !canon_candidate.starts_with(&canon_root) {
255 eyre::bail!(
256 "{label} path {} escapes project root {} (resolved to {})",
257 orig.display(),
258 allowed_root.display(),
259 canon_candidate.display()
260 );
261 }
262 Ok(())
263}
264
265pub fn copy_project(config: &Config, temp_dir: &Path) -> Result<()> {
270 let src_rel = relative_to_root(&config.root, &config.src);
271 ensure_safe_relative_path(&src_rel, "src", &config.src)?;
272 ensure_within_root(&config.root, &config.src, "src", &config.src)?;
273
274 let test_rel = relative_to_root(&config.root, &config.test);
275 ensure_safe_relative_path(&test_rel, "test", &config.test)?;
276 ensure_within_root(&config.root, &config.test, "test", &config.test)?;
277
278 copy_project_dir_recursive(&config.root, &config.src, &temp_dir.join(&src_rel))?;
279
280 if config.test != config.src {
281 copy_project_dir_recursive(&config.root, &config.test, &temp_dir.join(&test_rel))?;
282 }
283
284 let handled_extra_roots = handled_project_roots(config)?;
285 for extra_path in config.include_paths.iter().chain(config.allow_paths.iter()) {
286 copy_extra_project_path(
287 &config.root,
288 temp_dir,
289 extra_path,
290 &handled_extra_roots,
291 "include/allow",
292 )?;
293 }
294 for remapping in &config.remappings {
295 let remapping: Remapping = remapping.clone().into();
296 copy_extra_project_path(
297 &config.root,
298 temp_dir,
299 Path::new(&remapping.path),
300 &handled_extra_roots,
301 "remapping",
302 )?;
303 if let Some(context) = remapping.context {
304 copy_extra_project_path(
305 &config.root,
306 temp_dir,
307 Path::new(&context),
308 &handled_extra_roots,
309 "remapping context",
310 )?;
311 }
312 }
313 for permission in &config.fs_permissions.permissions {
314 if permission.is_granted(FsAccessKind::Read) {
315 copy_project_local_permission_path(
316 &config.root,
317 temp_dir,
318 &permission.path,
319 &handled_extra_roots,
320 )?;
321 }
322 if permission.is_granted(FsAccessKind::Write) {
323 create_project_local_permission_dir(
324 &config.root,
325 temp_dir,
326 &permission.path,
327 &handled_extra_roots,
328 )?;
329 }
330 }
331
332 copy_project_local_optional_path(
333 &config.root,
334 temp_dir,
335 &config.fuzz.failure_persist_dir,
336 &handled_extra_roots,
337 )?;
338 copy_project_local_optional_path(
339 &config.root,
340 temp_dir,
341 &config.fuzz.corpus.corpus_dir,
342 &handled_extra_roots,
343 )?;
344 copy_project_local_optional_path(
345 &config.root,
346 temp_dir,
347 &config.fuzz.corpus.frontier_dir,
348 &handled_extra_roots,
349 )?;
350 copy_project_local_optional_path(
351 &config.root,
352 temp_dir,
353 &config.invariant.failure_persist_dir,
354 &handled_extra_roots,
355 )?;
356 copy_project_local_optional_path(
357 &config.root,
358 temp_dir,
359 &config.invariant.corpus.corpus_dir,
360 &handled_extra_roots,
361 )?;
362 copy_project_local_optional_path(
363 &config.root,
364 temp_dir,
365 &config.invariant.corpus.frontier_dir,
366 &handled_extra_roots,
367 )?;
368
369 if config.script.exists() && config.script != config.src && config.script != config.test {
375 let script_rel = relative_to_root(&config.root, &config.script);
376 ensure_safe_relative_path(&script_rel, "script", &config.script)?;
377 ensure_within_root(&config.root, &config.script, "script", &config.script)?;
378 copy_project_dir_recursive(&config.root, &config.script, &temp_dir.join(&script_rel))?;
379 }
380
381 for lib_path in &config.libs {
382 let resolved = resolve_against_root(&config.root, lib_path);
383 if resolved.exists() {
384 let lib_rel = relative_to_root(&config.root, &resolved);
385 if lib_rel.is_absolute() {
386 continue;
387 }
388 ensure_safe_relative_path(&lib_rel, "lib", lib_path)?;
389 ensure_within_root(&config.root, &resolved, "lib", lib_path)?;
390 let target = temp_dir.join(&lib_rel);
391
392 if !target.exists() {
393 if let Some(parent) = target.parent() {
394 fs::create_dir_all(parent)?;
395 }
396 if symlink_dir(&resolved, &target).is_err() {
397 copy_dir_recursive(&resolved, &target)?;
398 }
399 }
400
401 symlink_nested_libs(&resolved, &target, 0)?;
402 }
403 }
404
405 for dep_dir in ["node_modules", "dependencies"] {
406 let dep_path = config.root.join(dep_dir);
407 if dep_path.exists() && dep_path.is_dir() {
408 ensure_within_root(&config.root, &dep_path, dep_dir, &dep_path)?;
410 let target = temp_dir.join(dep_dir);
411 if !target.exists() && symlink_dir(&dep_path, &target).is_err() {
412 copy_dir_recursive(&dep_path, &target)?;
413 }
414 }
415 }
416
417 let foundry_toml = config.root.join("foundry.toml");
418 if foundry_toml.exists() {
419 fs::copy(&foundry_toml, temp_dir.join("foundry.toml"))?;
420 }
421
422 let remappings = config.root.join("remappings.txt");
423 if remappings.exists() {
424 fs::copy(&remappings, temp_dir.join("remappings.txt"))?;
425 }
426
427 Ok(())
428}
429
430pub(crate) fn handled_project_roots(config: &Config) -> Result<Vec<PathBuf>> {
431 let mut roots = Vec::new();
432 push_handled_project_root(&mut roots, &config.root, &config.src, "src")?;
433 push_handled_project_root(&mut roots, &config.root, &config.test, "test")?;
434
435 if config.script.exists() && config.script != config.src && config.script != config.test {
436 push_handled_project_root(&mut roots, &config.root, &config.script, "script")?;
437 }
438
439 for lib_path in &config.libs {
440 let resolved = resolve_against_root(&config.root, lib_path);
441 if resolved.exists() {
442 let lib_rel = relative_to_root(&config.root, &resolved);
443 if lib_rel.is_absolute() {
444 continue;
445 }
446 push_handled_project_root(&mut roots, &config.root, &resolved, "lib")?;
447 }
448 }
449
450 for dep_dir in ["node_modules", "dependencies"] {
451 let dep_path = config.root.join(dep_dir);
452 if dep_path.exists() && dep_path.is_dir() {
453 roots.push(PathBuf::from(dep_dir));
454 }
455 }
456
457 Ok(roots)
458}
459
460fn push_handled_project_root(
461 roots: &mut Vec<PathBuf>,
462 root: &Path,
463 path: &Path,
464 label: &str,
465) -> Result<()> {
466 let rel = relative_to_root(root, path);
467 ensure_safe_relative_path(&rel, label, path)?;
468 ensure_within_root(root, path, label, path)?;
469 roots.push(rel);
470 Ok(())
471}
472
473fn is_covered_by_handled_root(rel: &Path, handled_roots: &[PathBuf]) -> bool {
474 handled_roots.iter().any(|root| !root.as_os_str().is_empty() && rel.starts_with(root))
475}
476
477fn copy_extra_project_path(
478 root: &Path,
479 temp_dir: &Path,
480 path: &Path,
481 handled_roots: &[PathBuf],
482 label: &str,
483) -> Result<()> {
484 let resolved = resolve_against_root(root, path);
485 let rel = relative_to_root(root, &resolved);
486 if rel.is_absolute() {
487 return Ok(());
488 }
489 ensure_safe_relative_path(&rel, label, path)?;
490 ensure_within_root(root, &resolved, label, path)?;
491
492 if is_covered_by_handled_root(&rel, handled_roots) {
493 return Ok(());
494 }
495
496 if !resolved.exists() {
497 return Ok(());
498 }
499
500 let target = temp_dir.join(rel);
501 if resolved.is_dir() {
502 copy_project_dir_recursive(root, &resolved, &target)
503 } else {
504 if let Some(parent) = target.parent() {
505 fs::create_dir_all(parent)?;
506 }
507 fs::copy(&resolved, target)?;
508 Ok(())
509 }
510}
511
512fn copy_project_local_permission_path(
513 root: &Path,
514 temp_dir: &Path,
515 path: &Path,
516 handled_roots: &[PathBuf],
517) -> Result<()> {
518 let resolved = resolve_against_root(root, path);
519 let rel = relative_to_root(root, &resolved);
520 if rel.is_absolute() || rel.as_os_str().is_empty() {
521 return Ok(());
522 }
523 copy_extra_project_path(root, temp_dir, path, handled_roots, "fs permission")
524}
525
526fn create_project_local_permission_dir(
527 root: &Path,
528 temp_dir: &Path,
529 path: &Path,
530 handled_roots: &[PathBuf],
531) -> Result<()> {
532 let resolved = resolve_against_root(root, path);
533 let rel = relative_to_root(root, &resolved);
534 if rel.is_absolute() || rel.as_os_str().is_empty() {
535 return Ok(());
536 }
537 ensure_safe_relative_path(&rel, "fs permission", path)?;
538 ensure_within_root(root, &resolved, "fs permission", path)?;
539
540 if resolved.exists() && resolved.is_dir() {
541 if !is_covered_by_handled_root(&rel, handled_roots) {
542 fs::create_dir_all(temp_dir.join(rel))?;
543 }
544 return Ok(());
545 }
546
547 let Some(parent) = rel.parent() else { return Ok(()) };
548 let resolved_parent = root.join(parent);
549 if !resolved_parent.exists() || !resolved_parent.is_dir() {
550 return Ok(());
551 }
552 ensure_within_root(root, &resolved_parent, "fs permission", path)?;
553
554 if parent.as_os_str().is_empty() || is_covered_by_handled_root(parent, handled_roots) {
555 return Ok(());
556 }
557
558 fs::create_dir_all(temp_dir.join(parent))?;
559 if resolved.exists() && resolved.is_file() {
560 fs::copy(&resolved, temp_dir.join(rel))?;
561 }
562
563 Ok(())
564}
565
566fn copy_project_local_optional_path(
567 root: &Path,
568 temp_dir: &Path,
569 path: &Option<PathBuf>,
570 handled_roots: &[PathBuf],
571) -> Result<()> {
572 let Some(path) = path else { return Ok(()) };
573 let resolved = resolve_against_root(root, path);
574 let rel = relative_to_root(root, &resolved);
575 if rel.as_os_str().is_empty() || !resolved.exists() {
576 return Ok(());
577 }
578 let is_external = rel.is_absolute();
579 let target = if is_external || is_covered_by_handled_root(&rel, handled_roots) {
580 temp_dir.join(isolated_mutable_path_rel(&resolved))
581 } else {
582 ensure_safe_relative_path(&rel, "corpus/frontier", path)?;
583 ensure_within_root(root, &resolved, "corpus/frontier", path)?;
584 temp_dir.join(rel)
585 };
586 if resolved.is_dir() {
587 if is_external {
588 copy_dir_recursive(&resolved, &target)
589 } else {
590 copy_project_dir_recursive(root, &resolved, &target)
591 }
592 } else {
593 if let Some(parent) = target.parent() {
594 fs::create_dir_all(parent)?;
595 }
596 fs::copy(&resolved, target)?;
597 Ok(())
598 }
599}
600
601pub fn symlink_dir(src: &Path, dst: &Path) -> Result<()> {
603 #[cfg(unix)]
604 {
605 std::os::unix::fs::symlink(src, dst)?;
606 }
607 #[cfg(windows)]
608 {
609 std::os::windows::fs::symlink_dir(src, dst)?;
610 }
611 Ok(())
612}
613
614const MAX_SYMLINK_DEPTH: usize = 10;
616
617fn symlink_nested_libs(lib_src: &Path, lib_dst: &Path, depth: usize) -> Result<()> {
619 if depth >= MAX_SYMLINK_DEPTH {
620 return Ok(());
621 }
622
623 let nested_lib_dirs: Vec<PathBuf> =
624 if let Ok(config) = Config::load_with_root_and_fallback(lib_src) {
625 config.libs
626 } else {
627 vec![PathBuf::from("lib")]
628 };
629
630 for nested_lib_dir in nested_lib_dirs {
631 if !is_safe_relative_path(&nested_lib_dir) {
635 continue;
636 }
637 let nested_lib = lib_src.join(&nested_lib_dir);
638 if !nested_lib.exists() {
639 continue;
640 }
641 let Ok(meta) = fs::symlink_metadata(&nested_lib) else { continue };
643 if meta.file_type().is_symlink() || !meta.is_dir() {
644 continue;
645 }
646 if ensure_within_root(lib_src, &nested_lib, "nested lib", &nested_lib).is_err() {
647 continue;
648 }
649 process_nested_lib_dir(&nested_lib, lib_dst, &nested_lib_dir, depth)?;
650 }
651
652 Ok(())
653}
654
655fn process_nested_lib_dir(
656 nested_lib: &Path,
657 lib_dst: &Path,
658 lib_rel: &Path,
659 depth: usize,
660) -> Result<()> {
661 if !nested_lib.exists() || !nested_lib.is_dir() {
662 return Ok(());
663 }
664
665 let entries = match fs::read_dir(nested_lib) {
666 Ok(e) => e,
667 Err(_) => return Ok(()),
668 };
669
670 for entry in entries.flatten() {
671 let Ok(file_type) = entry.file_type() else { continue };
675 if file_type.is_symlink() || !file_type.is_dir() {
676 continue;
677 }
678
679 let entry_path = entry.path();
680 let entry_name = entry.file_name();
681 let nested_dst = lib_dst.join(lib_rel).join(&entry_name);
682
683 if !nested_dst.exists() {
684 if let Some(parent) = nested_dst.parent() {
685 let _ = fs::create_dir_all(parent);
686 }
687 let _ = symlink_dir(&entry_path, &nested_dst);
688 }
689
690 symlink_nested_libs(&entry_path, &nested_dst, depth + 1)?;
691 }
692
693 Ok(())
694}
695
696pub fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
698 let mut visited = Vec::new();
699 copy_dir_recursive_inner(src, dst, src, &mut visited)
700}
701
702fn copy_project_dir_recursive(root: &Path, src: &Path, dst: &Path) -> Result<()> {
703 let mut visited = Vec::new();
704 copy_dir_recursive_inner(src, dst, root, &mut visited)
705}
706
707fn copy_dir_recursive_inner(
708 src: &Path,
709 dst: &Path,
710 allowed_root: &Path,
711 visited: &mut Vec<PathBuf>,
712) -> Result<()> {
713 if !src.exists() {
714 return Ok(());
715 }
716 ensure_within_root(allowed_root, src, "copied directory", src)?;
717 let canonical = src.canonicalize()?;
718 if visited.contains(&canonical) {
719 return Ok(());
720 }
721 visited.push(canonical);
722
723 let result = (|| {
724 fs::create_dir_all(dst)?;
725
726 for entry in fs::read_dir(src)? {
727 let entry = entry?;
728 let path = entry.path();
729 let dest_path = dst.join(entry.file_name());
730
731 let meta = fs::symlink_metadata(&path)?;
732
733 if meta.file_type().is_symlink() {
734 if path.is_dir() {
735 if ensure_within_root(allowed_root, &path, "symlinked directory", &path).is_ok()
736 {
737 copy_dir_recursive_inner(&path, &dest_path, allowed_root, visited)?;
738 }
739 } else {
740 fs::copy(&path, &dest_path)?;
741 }
742 } else if meta.is_dir() {
743 copy_dir_recursive_inner(&path, &dest_path, allowed_root, visited)?;
744 } else {
745 fs::copy(&path, &dest_path)?;
746 }
747 }
748
749 Ok(())
750 })();
751
752 visited.pop();
753 result
754}
755
756pub fn unshare_path(project_root: &Path, root: &Path, rel: &Path) -> Result<()> {
762 let root = canonicalize_path(root)?;
763 let mut current = root.clone();
764 let mut components = rel.components().peekable();
765 while let Some(component) = components.next() {
766 current.push(component);
767 let Ok(metadata) = fs::symlink_metadata(¤t) else { return Ok(()) };
768 if !metadata.file_type().is_symlink() {
769 continue;
770 }
771 if components.peek().is_none() {
772 fs::remove_file(¤t)?;
773 return Ok(());
774 }
775 let source = canonicalize_path(¤t)?;
776 eyre::ensure!(
779 !root.starts_with(&source),
780 "mutation workspace {} is inside linked dependency {}",
781 root.display(),
782 source.display()
783 );
784 #[cfg(unix)]
785 fs::remove_file(¤t)?;
786 #[cfg(windows)]
787 fs::remove_dir(¤t)?;
788 copy_unshared_dir(project_root, &root, ¤t, &source, ¤t)?;
789 }
790 Ok(())
791}
792
793fn copy_unshared_dir(
794 project_root: &Path,
795 root: &Path,
796 isolated_root: &Path,
797 src: &Path,
798 dst: &Path,
799) -> Result<()> {
800 fs::create_dir_all(dst)?;
801 for entry in fs::read_dir(src)? {
802 let entry = entry?;
803 let destination = dst.join(entry.file_name());
804 let file_type = entry.file_type()?;
805 if file_type.is_symlink() {
806 let target = resolve_against_root(src, &fs::read_link(entry.path())?);
808 let rebased = rebase_project_path(project_root, root, &target);
809 let target = if rebased.starts_with(isolated_root) || rebased.is_file() {
812 rebased
813 } else {
814 target
815 };
816 symlink_entry(&target, &destination, file_type)?;
817 } else if file_type.is_dir() {
818 copy_unshared_dir(project_root, root, isolated_root, &entry.path(), &destination)?;
819 } else {
820 fs::copy(entry.path(), &destination)?;
821 }
822 }
823 Ok(())
824}
825
826pub(crate) fn symlink_entry(target: &Path, dst: &Path, _file_type: fs::FileType) -> Result<()> {
828 #[cfg(unix)]
829 std::os::unix::fs::symlink(target, dst)?;
830 #[cfg(windows)]
831 {
832 if _file_type.is_symlink_dir() {
833 std::os::windows::fs::symlink_dir(target, dst)?;
834 } else {
835 std::os::windows::fs::symlink_file(target, dst)?;
836 }
837 }
838 Ok(())
839}
840
841#[cfg(test)]
842mod tests {
843 use super::*;
844 use std::{collections::BTreeMap, str::FromStr};
845
846 use foundry_compilers::artifacts::ModelCheckerSettings;
847 use foundry_config::fs_permissions::PathPermission;
848 use tempfile::TempDir;
849
850 #[cfg(unix)]
851 use std::os::unix::fs::symlink as symlink_file;
852 #[cfg(windows)]
853 use std::os::windows::fs::symlink_file;
854
855 fn create_test_dir_structure(base: &Path, structure: &[&str]) {
856 for path in structure {
857 let full_path = base.join(path);
858 if path.ends_with('/') {
859 fs::create_dir_all(&full_path).unwrap();
860 } else {
861 if let Some(parent) = full_path.parent() {
862 fs::create_dir_all(parent).unwrap();
863 }
864 fs::write(&full_path, format!("// {path}")).unwrap();
865 }
866 }
867 }
868
869 #[test]
870 fn test_unshare_path_preserves_nested_aliases_and_external_links() {
871 let temp = TempDir::new().unwrap();
872 let root = temp.path().join("project");
873 let workspace = temp.path().join("deeper/workspace");
874 let dependency = root.join("lib/bucket");
875 create_test_dir_structure(
876 &root,
877 &[
878 "lib/bucket/Arithmetic.sol",
879 "lib/bucket/nested/",
880 "src/Local.sol",
881 "uncopied/Local.sol",
882 ],
883 );
884 create_test_dir_structure(temp.path(), &["shared/Helper.sol"]);
885 fs::create_dir_all(workspace.join("src")).unwrap();
886 fs::copy(root.join("src/Local.sol"), workspace.join("src/Local.sol")).unwrap();
887 symlink_dir(&root.join("lib"), &workspace.join("lib")).unwrap();
888 symlink_file("Arithmetic.sol", dependency.join("Alias.sol")).unwrap();
889 symlink_file("../Arithmetic.sol", dependency.join("nested/Alias.sol")).unwrap();
890 symlink_file(dependency.join("Arithmetic.sol"), dependency.join("Absolute.sol")).unwrap();
891 symlink_file("../../../shared/Helper.sol", dependency.join("Helper.sol")).unwrap();
892 symlink_file("../../src/Local.sol", dependency.join("Local.sol")).unwrap();
893 symlink_file("../../uncopied/Local.sol", dependency.join("Uncopied.sol")).unwrap();
894 symlink_file("nonexistent", dependency.join("unused")).unwrap();
895 symlink_dir(Path::new("nested"), &dependency.join("a_alias")).unwrap();
896 symlink_dir(Path::new("missing-directory"), &dependency.join("unused_dir")).unwrap();
897
898 unshare_path(&root, &workspace, Path::new("lib/bucket/Arithmetic.sol")).unwrap();
899 fs::write(workspace.join("lib/bucket/Arithmetic.sol"), "mutant").unwrap();
900 fs::write(workspace.join("src/Local.sol"), "workspace local").unwrap();
901
902 for alias in ["Alias.sol", "nested/Alias.sol", "Absolute.sol", "a_alias/Alias.sol"] {
903 assert_eq!(
904 fs::read_to_string(workspace.join("lib/bucket").join(alias)).unwrap(),
905 "mutant",
906 "{alias}",
907 );
908 }
909 assert_eq!(
910 fs::read_to_string(dependency.join("Arithmetic.sol")).unwrap(),
911 "// lib/bucket/Arithmetic.sol",
912 );
913 assert_eq!(
914 fs::read_to_string(workspace.join("lib/bucket/Helper.sol")).unwrap(),
915 "// shared/Helper.sol",
916 );
917 assert_eq!(
918 fs::read_to_string(workspace.join("lib/bucket/Local.sol")).unwrap(),
919 "workspace local",
920 );
921 assert_eq!(
922 fs::read_to_string(workspace.join("lib/bucket/Uncopied.sol")).unwrap(),
923 "// uncopied/Local.sol",
924 );
925 for link in ["unused", "unused_dir"] {
926 let path = workspace.join("lib/bucket").join(link);
927 assert!(fs::symlink_metadata(&path).unwrap().file_type().is_symlink());
928 assert!(!path.exists());
929 }
930 #[cfg(windows)]
931 assert!(
932 fs::symlink_metadata(workspace.join("lib/bucket/unused_dir"))
933 .unwrap()
934 .file_type()
935 .is_symlink_dir()
936 );
937 }
938
939 #[test]
940 fn test_unshare_path_keeps_links_to_partially_copied_dirs() {
941 let temp = TempDir::new().unwrap();
942 let root = temp.path().join("project");
943 let workspace = temp.path().join("workspace");
944 create_test_dir_structure(
945 &root,
946 &["lib/bucket/Arithmetic.sol", "shared/visible/V.sol", "shared/hidden/H.sol"],
947 );
948 create_test_dir_structure(&workspace, &["shared/visible/V.sol"]);
950 symlink_dir(&root.join("lib"), &workspace.join("lib")).unwrap();
951 symlink_dir(Path::new("../../shared"), &root.join("lib/bucket/helpers")).unwrap();
952
953 unshare_path(&root, &workspace, Path::new("lib/bucket/Arithmetic.sol")).unwrap();
954
955 assert_eq!(
956 fs::read_to_string(workspace.join("lib/bucket/helpers/hidden/H.sol")).unwrap(),
957 "// shared/hidden/H.sol",
958 );
959 }
960
961 #[test]
962 fn test_unshare_path_rejects_workspace_inside_linked_tree() {
963 let temp = TempDir::new().unwrap();
964 let root = temp.path().join("project");
965 let workspace = root.join("lib/.tmp/workspace");
966 create_test_dir_structure(&root, &["lib/bucket/Arithmetic.sol", "lib/.tmp/workspace/"]);
967 symlink_dir(&root.join("lib"), &workspace.join("lib")).unwrap();
968
969 let err = unshare_path(&root, &workspace, Path::new("lib/bucket/Arithmetic.sol"))
970 .unwrap_err()
971 .to_string();
972 assert!(err.contains("is inside linked dependency"), "{err}");
973 }
974
975 #[cfg(windows)]
976 #[test]
977 fn test_symlink_entry_preserves_directory_type_before_target_exists() {
978 let temp = TempDir::new().unwrap();
979 let original = temp.path().join("original");
980 symlink_dir(Path::new("z_real"), &original).unwrap();
981 let file_type = fs::symlink_metadata(original).unwrap().file_type();
982 let alias = temp.path().join("a_alias");
983 symlink_entry(Path::new("z_real"), &alias, file_type).unwrap();
984 assert!(fs::symlink_metadata(&alias).unwrap().file_type().is_symlink_dir());
985 fs::create_dir(temp.path().join("z_real")).unwrap();
986 assert!(alias.is_dir());
987 }
988
989 #[test]
990 fn test_rebase_remapping_preserves_context_directory_boundary() {
991 let remapping = RelativeRemapping::from(Remapping {
992 context: Some(format!("lib{MAIN_SEPARATOR}outer{MAIN_SEPARATOR}")),
993 name: "inner/".to_string(),
994 path: format!("lib{MAIN_SEPARATOR}outer{MAIN_SEPARATOR}lib{MAIN_SEPARATOR}inner"),
995 });
996
997 let remapping = rebase_remapping(Path::new("project"), Path::new("workspace"), &remapping);
998 assert!(remapping.context.unwrap().ends_with(MAIN_SEPARATOR));
999 }
1000
1001 #[cfg(unix)]
1002 #[test]
1003 fn test_rebase_config_paths_canonicalizes_workspace_alias() {
1004 let temp = TempDir::new().unwrap();
1005 let root = temp.path().join("project");
1006 let workspace = temp.path().join("workspace");
1007 let alias = temp.path().join("alias");
1008 create_test_dir_structure(&root, &["src/Target.sol", "test/Target.t.sol"]);
1009 fs::create_dir(&workspace).unwrap();
1010 symlink_dir(&workspace, &alias).unwrap();
1011
1012 let config = Config {
1013 root: root.clone(),
1014 src: root.join("src"),
1015 test: root.join("test"),
1016 remappings: vec![Remapping::from_str("@src/=src/").unwrap().into()],
1017 ..Default::default()
1018 };
1019 copy_project(&config, &alias).unwrap();
1020 let config = rebase_config_paths(&config, &alias).sanitized();
1021 let canonical_root = canonicalize_path(&workspace).unwrap();
1022 assert_eq!(config.root, canonical_root);
1023 assert_eq!(config.src, canonical_root.join("src"));
1024 assert_eq!(config.test, canonical_root.join("test"));
1025 let remapping = Remapping::from(config.remappings[0].clone());
1026 assert_eq!(Path::new(&remapping.path), canonical_root.join("src"));
1027 }
1028
1029 #[cfg(unix)]
1030 #[test]
1031 fn test_rebase_copied_alias_and_linked_library() {
1032 let temp = TempDir::new().unwrap();
1033 let root = normalize_existing_ancestor(&temp.path().join("project"));
1034 let real_workspace = temp.path().join("real-workspace");
1036 let workspace = temp.path().join("workspace");
1037 fs::create_dir(&real_workspace).unwrap();
1038 symlink_dir(&real_workspace, &workspace).unwrap();
1039 create_test_dir_structure(&root, &["src/Real.sol", "lib/example/Lib.sol"]);
1040 symlink_file("Real.sol", root.join("src/Alias.sol")).unwrap();
1041 let config = Config { root: root.clone(), ..Default::default() }.sanitized();
1042 copy_project(&config, &workspace).unwrap();
1043 assert_eq!(
1044 rebase_project_path(&root, &workspace, Path::new("src/Alias.sol")),
1045 workspace.join("src/Real.sol")
1046 );
1047 assert_eq!(
1048 rebase_project_path(&root, &workspace, Path::new("lib/example/Lib.sol")),
1049 workspace.join("lib/example/Lib.sol")
1050 );
1051 }
1052
1053 #[test]
1054 fn test_rebase_config_paths_rebases_materialized_project_paths() {
1055 let temp = TempDir::new().unwrap();
1056 let root = temp.path().join("project");
1057 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1058 let external = temp.path().join("external");
1059
1060 let mut contracts = BTreeMap::new();
1061 contracts.insert(root.join("src/Target.sol").display().to_string(), vec!["Target".into()]);
1062 contracts
1063 .insert(external.join("External.sol").display().to_string(), vec!["External".into()]);
1064
1065 let config = Config {
1066 root: root.clone(),
1067 src: root.join("contracts"),
1068 test: root.join("checks"),
1069 script: root.join("deploy"),
1070 out: root.join("custom-out"),
1071 cache_path: root.join("custom-cache"),
1072 snapshots: root.join("custom-snapshots"),
1073 broadcast: root.join("custom-broadcast"),
1074 mutation_dir: root.join("custom-cache/mutation"),
1075 test_failures_file: root.join("custom-cache/test-failures"),
1076 build_info_path: Some(root.join("custom-build-info")),
1077 libs: vec![root.join("vendor"), external.join("lib")],
1078 include_paths: vec![root.join("shared"), PathBuf::from("../external/include")],
1079 allow_paths: vec![root.join("fixtures"), PathBuf::from("../external/fixtures")],
1080 ignored_error_codes_from: vec![
1081 (
1082 root.join("contracts"),
1083 vec![foundry_config::SolidityErrorCode::UnusedLocalVariable],
1084 ),
1085 (
1086 external.join("contracts"),
1087 vec![foundry_config::SolidityErrorCode::UnusedFunctionParameter],
1088 ),
1089 ],
1090 ignored_file_paths: vec![
1091 root.join("contracts/Ignored.sol"),
1092 external.join("Ignored.sol"),
1093 ],
1094 remappings: vec![
1095 Remapping::from_str(&format!("@src/={}/", root.join("src").display()))
1096 .unwrap()
1097 .into(),
1098 Remapping::from_str(&format!("@ext/={}/", external.join("src").display()))
1099 .unwrap()
1100 .into(),
1101 ],
1102 fs_permissions: foundry_config::FsPermissions::new([
1103 PathPermission::read(root.join("fixtures")),
1104 PathPermission::read("../external/fixtures"),
1105 ]),
1106 fuzz: foundry_config::FuzzConfig {
1107 corpus: foundry_config::FuzzCorpusConfig {
1108 corpus_dir: Some(root.join("fuzz-corpus")),
1109 frontier_dir: Some(root.join("fuzz-frontier")),
1110 ..Default::default()
1111 },
1112 ..Default::default()
1113 },
1114 invariant: foundry_config::InvariantConfig {
1115 corpus: foundry_config::FuzzCorpusConfig {
1116 corpus_dir: Some(PathBuf::from("invariant-corpus")),
1117 frontier_dir: Some(PathBuf::from("invariant-frontier")),
1118 ..Default::default()
1119 },
1120 ..Default::default()
1121 },
1122 model_checker: Some(ModelCheckerSettings {
1123 contracts,
1124 engine: None,
1125 timeout: None,
1126 targets: None,
1127 invariants: None,
1128 show_unproved: None,
1129 div_mod_with_slacks: None,
1130 solvers: None,
1131 show_unsupported: None,
1132 show_proved_safe: None,
1133 }),
1134 ..Default::default()
1135 };
1136
1137 let temp_config = rebase_config_paths(&config, &workspace);
1138 let external = normalize_existing_ancestor(&external);
1139
1140 assert_eq!(temp_config.root, workspace);
1141 assert_eq!(temp_config.src, workspace.join("contracts"));
1142 assert_eq!(temp_config.test, workspace.join("checks"));
1143 assert_eq!(temp_config.script, workspace.join("deploy"));
1144 assert_eq!(temp_config.out, workspace.join("custom-out"));
1145 assert_eq!(temp_config.cache_path, workspace.join("custom-cache"));
1146 assert_eq!(temp_config.snapshots, workspace.join("custom-snapshots"));
1147 assert_eq!(temp_config.broadcast, workspace.join("custom-broadcast"));
1148 assert_eq!(temp_config.mutation_dir, workspace.join("custom-cache/mutation"));
1149 assert_eq!(temp_config.test_failures_file, workspace.join("custom-cache/test-failures"));
1150 assert_eq!(temp_config.build_info_path, Some(workspace.join("custom-build-info")));
1151 assert_eq!(temp_config.libs, vec![workspace.join("vendor"), external.join("lib")]);
1152 assert_eq!(
1153 temp_config.include_paths,
1154 vec![workspace.join("shared"), external.join("include")]
1155 );
1156 assert_eq!(
1157 temp_config.allow_paths,
1158 vec![workspace.join("fixtures"), external.join("fixtures")]
1159 );
1160 assert_eq!(
1161 temp_config.ignored_error_codes_from,
1162 vec![
1163 (
1164 workspace.join("contracts"),
1165 vec![foundry_config::SolidityErrorCode::UnusedLocalVariable]
1166 ),
1167 (
1168 external.join("contracts"),
1169 vec![foundry_config::SolidityErrorCode::UnusedFunctionParameter]
1170 )
1171 ]
1172 );
1173 assert_eq!(
1174 temp_config.ignored_file_paths,
1175 vec![workspace.join("contracts/Ignored.sol"), external.join("Ignored.sol")]
1176 );
1177
1178 let remappings =
1179 temp_config.remappings.into_iter().map(Remapping::from).collect::<Vec<_>>();
1180 assert_eq!(remappings[0].path, format!("{}/", workspace.join("src").display()));
1181 assert_eq!(remappings[1].path, format!("{}/", external.join("src").display()));
1182
1183 assert_eq!(
1184 temp_config.fs_permissions.permissions[0].path,
1185 normalize_existing_ancestor(&workspace.join("fixtures"))
1186 );
1187 assert_eq!(
1188 temp_config.fs_permissions.permissions[1].path,
1189 normalize_existing_ancestor(&external.join("fixtures"))
1190 );
1191 assert_eq!(temp_config.fuzz.corpus.corpus_dir, Some(workspace.join("fuzz-corpus")));
1192 assert_eq!(temp_config.fuzz.corpus.frontier_dir, Some(workspace.join("fuzz-frontier")));
1193 assert_eq!(
1194 temp_config.invariant.corpus.corpus_dir,
1195 Some(workspace.join("invariant-corpus"))
1196 );
1197 assert_eq!(
1198 temp_config.invariant.corpus.frontier_dir,
1199 Some(workspace.join("invariant-frontier"))
1200 );
1201
1202 let contracts = temp_config.model_checker.unwrap().contracts;
1203 assert!(
1204 contracts.contains_key(&workspace.join("src").join("Target.sol").display().to_string())
1205 );
1206 assert!(contracts.contains_key(&external.join("External.sol").display().to_string()));
1207 }
1208
1209 #[test]
1212 fn test_rebase_config_paths_keeps_relative_ignored_warning_paths() {
1213 let temp = TempDir::new().unwrap();
1214 let root = temp.path().join("project");
1215 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1216 let config = Config {
1217 root: root.clone(),
1218 ignored_error_codes_from: vec![(
1219 PathBuf::from("src/test"),
1220 vec![foundry_config::SolidityErrorCode::UnusedLocalVariable],
1221 )],
1222 ignored_file_paths: vec![PathBuf::from("src/test"), root.join("src/Ignored.sol")],
1223 ..Default::default()
1224 };
1225
1226 let temp_config = rebase_config_paths(&config, &workspace);
1227
1228 assert_eq!(temp_config.ignored_error_codes_from[0].0, PathBuf::from("src/test"));
1229 assert_eq!(
1230 temp_config.ignored_file_paths,
1231 vec![PathBuf::from("src/test"), workspace.join("src/Ignored.sol")]
1232 );
1233 }
1234
1235 #[test]
1236 fn test_copy_project_preserves_external_read_only_paths() {
1237 let temp = TempDir::new().unwrap();
1238 let root = temp.path().join("project");
1239 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1240 let external = temp.path().join("shared-solidity");
1241 create_test_dir_structure(&root, &["src/Target.sol", "test/Target.t.sol"]);
1242 create_test_dir_structure(&external, &["Shared.sol"]);
1243
1244 let config = Config {
1245 root: root.clone(),
1246 src: root.join("src"),
1247 test: root.join("test"),
1248 include_paths: vec![PathBuf::from("../shared-solidity")],
1249 allow_paths: vec![PathBuf::from("../shared-solidity")],
1250 remappings: vec![Remapping::from_str("shared/=../shared-solidity/").unwrap().into()],
1251 ..Default::default()
1252 };
1253
1254 copy_project(&config, &workspace).unwrap();
1255 let temp_config = rebase_config_paths(&config, &workspace);
1256 let external = normalize_existing_ancestor(&external);
1257 let remappings =
1258 temp_config.remappings.into_iter().map(Remapping::from).collect::<Vec<_>>();
1259
1260 assert!(workspace.join("src/Target.sol").exists());
1261 assert!(!workspace.join("shared-solidity/Shared.sol").exists());
1262 assert_eq!(temp_config.include_paths, vec![external.clone()]);
1263 assert_eq!(temp_config.allow_paths, vec![external.clone()]);
1264 assert_eq!(remappings[0].path, format!("{}/", external.display()));
1265 }
1266
1267 #[test]
1268 fn test_copy_project_copies_project_local_corpus_and_frontier_paths() {
1269 let temp = TempDir::new().unwrap();
1270 let root = temp.path().join("project");
1271 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1272 create_test_dir_structure(
1273 &root,
1274 &[
1275 "src/Target.sol",
1276 "test/Target.t.sol",
1277 "fuzz-corpus/seed.json",
1278 "fuzz-frontier/frontier.json",
1279 "invariant-corpus/seed.json",
1280 "invariant-frontier/frontier.json",
1281 ],
1282 );
1283
1284 let config = Config {
1285 root: root.clone(),
1286 src: root.join("src"),
1287 test: root.join("test"),
1288 fuzz: foundry_config::FuzzConfig {
1289 corpus: foundry_config::FuzzCorpusConfig {
1290 corpus_dir: Some(PathBuf::from("fuzz-corpus")),
1291 frontier_dir: Some(PathBuf::from("fuzz-frontier")),
1292 ..Default::default()
1293 },
1294 ..Default::default()
1295 },
1296 invariant: foundry_config::InvariantConfig {
1297 corpus: foundry_config::FuzzCorpusConfig {
1298 corpus_dir: Some(PathBuf::from("invariant-corpus")),
1299 frontier_dir: Some(PathBuf::from("invariant-frontier")),
1300 ..Default::default()
1301 },
1302 ..Default::default()
1303 },
1304 ..Default::default()
1305 };
1306
1307 copy_project(&config, &workspace).unwrap();
1308 let temp_config = rebase_config_paths(&config, &workspace);
1309
1310 assert!(workspace.join("fuzz-corpus/seed.json").exists());
1311 assert!(workspace.join("fuzz-frontier/frontier.json").exists());
1312 assert!(workspace.join("invariant-corpus/seed.json").exists());
1313 assert!(workspace.join("invariant-frontier/frontier.json").exists());
1314 assert_eq!(temp_config.fuzz.corpus.corpus_dir, Some(workspace.join("fuzz-corpus")));
1315 assert_eq!(temp_config.fuzz.corpus.frontier_dir, Some(workspace.join("fuzz-frontier")));
1316 assert_eq!(
1317 temp_config.invariant.corpus.corpus_dir,
1318 Some(workspace.join("invariant-corpus"))
1319 );
1320 assert_eq!(
1321 temp_config.invariant.corpus.frontier_dir,
1322 Some(workspace.join("invariant-frontier"))
1323 );
1324 }
1325
1326 #[test]
1327 fn test_copy_project_isolates_external_corpus_and_frontier_paths() {
1328 let temp = TempDir::new().unwrap();
1329 let root = temp.path().join("project");
1330 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1331 let corpus = temp.path().join("shared-corpus");
1332 let frontier = temp.path().join("shared-frontier");
1333 create_test_dir_structure(&root, &["src/Target.sol", "test/Target.t.sol"]);
1334 create_test_dir_structure(&corpus, &["seed.json"]);
1335 create_test_dir_structure(&frontier, &["frontier.json"]);
1336
1337 let config = Config {
1338 root: root.clone(),
1339 src: root.join("src"),
1340 test: root.join("test"),
1341 invariant: foundry_config::InvariantConfig {
1342 corpus: foundry_config::FuzzCorpusConfig {
1343 corpus_dir: Some(PathBuf::from("../shared-corpus")),
1344 frontier_dir: Some(PathBuf::from("../shared-frontier")),
1345 ..Default::default()
1346 },
1347 ..Default::default()
1348 },
1349 ..Default::default()
1350 };
1351
1352 copy_project(&config, &workspace).unwrap();
1353 let temp_config = rebase_config_paths(&config, &workspace);
1354 let rebased_corpus = temp_config.invariant.corpus.corpus_dir.unwrap();
1355 let rebased_frontier = temp_config.invariant.corpus.frontier_dir.unwrap();
1356
1357 assert!(rebased_corpus.starts_with(workspace.join(".foundry_mutable")));
1358 assert!(rebased_frontier.starts_with(workspace.join(".foundry_mutable")));
1359 assert!(rebased_corpus.join("seed.json").exists());
1360 assert!(rebased_frontier.join("frontier.json").exists());
1361 }
1362
1363 #[test]
1364 fn test_copy_project_merges_overlapping_mutable_paths() {
1365 let temp = TempDir::new().unwrap();
1366 let root = temp.path().join("project");
1367 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1368 create_test_dir_structure(
1369 &root,
1370 &[
1371 "src/Target.sol",
1372 "test/Target.t.sol",
1373 "state/corpus/seed.json",
1374 "state/frontier.json",
1375 ],
1376 );
1377
1378 let config = Config {
1379 root: root.clone(),
1380 src: root.join("src"),
1381 test: root.join("test"),
1382 fuzz: foundry_config::FuzzConfig {
1383 corpus: foundry_config::FuzzCorpusConfig {
1384 corpus_dir: Some(PathBuf::from("state/corpus")),
1385 frontier_dir: Some(PathBuf::from("state")),
1386 ..Default::default()
1387 },
1388 ..Default::default()
1389 },
1390 ..Default::default()
1391 };
1392
1393 copy_project(&config, &workspace).unwrap();
1394
1395 assert!(workspace.join("state/corpus/seed.json").exists());
1396 assert!(workspace.join("state/frontier.json").exists());
1397 }
1398
1399 #[test]
1400 fn test_copy_project_isolates_external_failure_persist_dirs() {
1401 let temp = TempDir::new().unwrap();
1402 let root = temp.path().join("project");
1403 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1404 let fuzz_failures = temp.path().join("shared-fuzz-failures");
1405 let invariant_failures = temp.path().join("shared-invariant-failures");
1406 create_test_dir_structure(&root, &["src/Target.sol", "test/Target.t.sol"]);
1407 create_test_dir_structure(&fuzz_failures, &["Target/test/fuzz-failure"]);
1408 create_test_dir_structure(&invariant_failures, &["Target/invariant/invariant-failure"]);
1409
1410 let config = Config {
1411 root: root.clone(),
1412 src: root.join("src"),
1413 test: root.join("test"),
1414 fuzz: foundry_config::FuzzConfig {
1415 failure_persist_dir: Some(fuzz_failures),
1416 ..Default::default()
1417 },
1418 invariant: foundry_config::InvariantConfig {
1419 failure_persist_dir: Some(invariant_failures),
1420 ..Default::default()
1421 },
1422 ..Default::default()
1423 };
1424
1425 copy_project(&config, &workspace).unwrap();
1426 let temp_config = rebase_config_paths(&config, &workspace);
1427 let fuzz_failure_dir = temp_config.fuzz.failure_persist_dir.unwrap();
1428 let invariant_failure_dir = temp_config.invariant.failure_persist_dir.unwrap();
1429
1430 assert!(
1431 fuzz_failure_dir.starts_with(workspace.join(".foundry_mutable")),
1432 "{}",
1433 fuzz_failure_dir.display()
1434 );
1435 assert!(
1436 invariant_failure_dir.starts_with(workspace.join(".foundry_mutable")),
1437 "{}",
1438 invariant_failure_dir.display()
1439 );
1440 assert!(fuzz_failure_dir.join("Target/test/fuzz-failure").exists());
1441 assert!(invariant_failure_dir.join("Target/invariant/invariant-failure").exists());
1442 }
1443
1444 #[cfg(not(target_os = "windows"))]
1445 #[test]
1446 fn test_copy_project_isolates_corpus_under_symlinked_lib_root() {
1447 let temp = TempDir::new().unwrap();
1448 let root = temp.path().join("project");
1449 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1450 create_test_dir_structure(
1451 &root,
1452 &[
1453 "src/Target.sol",
1454 "test/Target.t.sol",
1455 ".real-lib/mycorpus/seed.json",
1456 ".real-lib/Dependency.sol",
1457 ],
1458 );
1459 symlink_dir(Path::new(".real-lib"), &root.join("lib")).unwrap();
1460
1461 let config = Config {
1462 root: root.clone(),
1463 src: root.join("src"),
1464 test: root.join("test"),
1465 libs: vec![root.join("lib")],
1466 invariant: foundry_config::InvariantConfig {
1467 corpus: foundry_config::FuzzCorpusConfig {
1468 corpus_dir: Some(PathBuf::from("lib/mycorpus")),
1469 ..Default::default()
1470 },
1471 ..Default::default()
1472 },
1473 ..Default::default()
1474 };
1475
1476 copy_project(&config, &workspace).unwrap();
1477 let temp_config = rebase_config_paths(&config, &workspace);
1478 let rebased_corpus = temp_config.invariant.corpus.corpus_dir.unwrap();
1479
1480 assert!(rebased_corpus.starts_with(workspace.join(".foundry_mutable")));
1481 assert!(rebased_corpus.join("seed.json").exists());
1482 assert!(!rebased_corpus.starts_with(workspace.join("lib")));
1483 }
1484
1485 #[cfg(not(target_os = "windows"))]
1486 #[test]
1487 fn test_rebase_config_paths_preserves_symlink_parent_semantics() {
1488 let temp = TempDir::new().unwrap();
1489 let root = temp.path().join("project");
1490 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1491 let external = temp.path().join("external");
1492 create_test_dir_structure(&root, &["src/Target.sol", "test/Target.t.sol"]);
1493 create_test_dir_structure(
1494 &external,
1495 &["pkg/Dependency.sol", "include/Shared.sol", "pkg/corpus/seed.json"],
1496 );
1497 symlink_dir(&external.join("pkg"), &root.join("link")).unwrap();
1498
1499 let config = Config {
1500 root: root.clone(),
1501 src: root.join("src"),
1502 test: root.join("test"),
1503 libs: vec![PathBuf::from("link")],
1504 include_paths: vec![PathBuf::from("link/../include")],
1505 invariant: foundry_config::InvariantConfig {
1506 corpus: foundry_config::FuzzCorpusConfig {
1507 corpus_dir: Some(PathBuf::from("link/corpus")),
1508 ..Default::default()
1509 },
1510 ..Default::default()
1511 },
1512 ..Default::default()
1513 };
1514
1515 copy_project(&config, &workspace).unwrap();
1516 let temp_config = rebase_config_paths(&config, &workspace);
1517 let rebased_corpus = temp_config.invariant.corpus.corpus_dir.unwrap();
1518 let external = normalize_existing_ancestor(&external);
1519
1520 assert_eq!(temp_config.libs, vec![external.join("pkg")]);
1521 assert_eq!(temp_config.include_paths, vec![external.join("include")]);
1522 assert!(rebased_corpus.starts_with(workspace.join(".foundry_mutable")));
1523 assert!(rebased_corpus.join("seed.json").exists());
1524 }
1525
1526 #[cfg(windows)]
1527 #[test]
1528 fn test_isolated_mutable_paths_include_windows_prefix_in_identity() {
1529 let c_drive = isolated_mutable_path_rel(Path::new(r"C:\shared\state"));
1530 let d_drive = isolated_mutable_path_rel(Path::new(r"D:\shared\state"));
1531
1532 assert_ne!(c_drive, d_drive);
1533 }
1534
1535 #[test]
1536 fn test_copy_project_copies_project_local_remapping_targets() {
1537 let temp = TempDir::new().unwrap();
1538 let root = temp.path().join("project");
1539 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1540 create_test_dir_structure(
1541 &root,
1542 &["src/Target.sol", "test/Target.t.sol", "packages/shared/src/Shared.sol"],
1543 );
1544
1545 let config = Config {
1546 root: root.clone(),
1547 src: root.join("src"),
1548 test: root.join("test"),
1549 remappings: vec![Remapping::from_str("shared/=packages/shared/src/").unwrap().into()],
1550 ..Default::default()
1551 };
1552
1553 copy_project(&config, &workspace).unwrap();
1554 let temp_config = rebase_config_paths(&config, &workspace);
1555 let remappings =
1556 temp_config.remappings.into_iter().map(Remapping::from).collect::<Vec<_>>();
1557
1558 assert!(workspace.join("packages/shared/src/Shared.sol").exists());
1559 assert_eq!(
1560 remappings[0].path,
1561 format!("{}/", workspace.join("packages").join("shared").join("src").display())
1562 );
1563 }
1564
1565 #[test]
1566 fn test_copy_project_preserves_external_libs() {
1567 let temp = TempDir::new().unwrap();
1568 let root = temp.path().join("project");
1569 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1570 let external = temp.path().join("shared-lib");
1571 create_test_dir_structure(&root, &["src/Target.sol", "test/Target.t.sol", "lib/Local.sol"]);
1572 create_test_dir_structure(&external, &["External.sol"]);
1573
1574 let config = Config {
1575 root: root.clone(),
1576 src: root.join("src"),
1577 test: root.join("test"),
1578 libs: vec![PathBuf::from("lib"), PathBuf::from("../shared-lib")],
1579 ..Default::default()
1580 };
1581
1582 copy_project(&config, &workspace).unwrap();
1583 let temp_config = rebase_config_paths(&config, &workspace);
1584 let external = normalize_existing_ancestor(&external);
1585
1586 assert!(workspace.join("lib/Local.sol").exists());
1587 assert!(!workspace.join("shared-lib/External.sol").exists());
1588 assert_eq!(temp_config.libs, vec![workspace.join("lib"), external]);
1589 }
1590
1591 #[test]
1592 fn test_rebase_config_paths_rebases_relative_fs_permissions() {
1593 let temp = TempDir::new().unwrap();
1594 let root = temp.path().join("project");
1595 let workspace = normalize_existing_ancestor(&temp.path().join("workspace"));
1596 fs::create_dir_all(root.join("writes")).unwrap();
1597 fs::create_dir_all(workspace.join("writes")).unwrap();
1598 fs::create_dir_all(workspace.join("logs/sub")).unwrap();
1599
1600 let config = Config {
1601 root,
1602 fs_permissions: foundry_config::FsPermissions::new([
1603 PathPermission::write("./writes"),
1604 PathPermission::read_write("./logs/sub/a.txt"),
1605 ]),
1606 ..Default::default()
1607 };
1608
1609 let temp_config = rebase_config_paths(&config, &workspace).sanitized();
1610
1611 assert_eq!(temp_config.root, workspace);
1612 assert_eq!(
1613 temp_config.fs_permissions.permissions[0].path,
1614 canonicalize_path(workspace.join("writes")).unwrap()
1615 );
1616 assert_eq!(
1617 temp_config.fs_permissions.permissions[1].path,
1618 canonicalize_path(workspace.join("logs/sub")).unwrap().join("a.txt")
1619 );
1620 }
1621
1622 #[test]
1623 fn test_symlink_dir_creates_symlink() {
1624 let temp = TempDir::new().unwrap();
1625 let src = temp.path().join("source_dir");
1626 let dst = temp.path().join("target_link");
1627
1628 fs::create_dir(&src).unwrap();
1629 fs::write(src.join("file.txt"), "content").unwrap();
1630
1631 symlink_dir(&src, &dst).unwrap();
1632
1633 assert!(dst.exists());
1634 assert!(dst.is_symlink());
1635 assert!(dst.join("file.txt").exists());
1636 }
1637
1638 #[test]
1639 fn test_symlink_nested_libs_single_level() {
1640 let temp = TempDir::new().unwrap();
1641
1642 let lib_src = temp.path().join("lib_src");
1643 create_test_dir_structure(
1644 &lib_src,
1645 &[
1646 "src/Contract.sol",
1647 "lib/",
1648 "lib/openzeppelin/contracts/token/ERC20.sol",
1649 "lib/solmate/src/tokens/ERC20.sol",
1650 ],
1651 );
1652
1653 let lib_dst = temp.path().join("lib_dst");
1654 fs::create_dir(&lib_dst).unwrap();
1655
1656 symlink_nested_libs(&lib_src, &lib_dst, 0).unwrap();
1657
1658 assert!(lib_dst.join("lib/openzeppelin").exists());
1659 assert!(lib_dst.join("lib/solmate").exists());
1660 assert!(lib_dst.join("lib/openzeppelin/contracts/token/ERC20.sol").exists());
1661 assert!(lib_dst.join("lib/solmate/src/tokens/ERC20.sol").exists());
1662 }
1663
1664 #[test]
1665 fn test_symlink_nested_libs_deeply_nested() {
1666 let temp = TempDir::new().unwrap();
1667
1668 let lib_src = temp.path().join("lib_src");
1669 create_test_dir_structure(
1670 &lib_src,
1671 &[
1672 "src/Main.sol",
1673 "lib/",
1674 "lib/dep-a/src/A.sol",
1675 "lib/dep-a/lib/",
1676 "lib/dep-a/lib/dep-b/src/B.sol",
1677 "lib/dep-a/lib/dep-b/lib/",
1678 "lib/dep-a/lib/dep-b/lib/dep-c/src/C.sol",
1679 ],
1680 );
1681
1682 let lib_dst = temp.path().join("lib_dst");
1683 fs::create_dir(&lib_dst).unwrap();
1684
1685 symlink_nested_libs(&lib_src, &lib_dst, 0).unwrap();
1686
1687 assert!(lib_dst.join("lib/dep-a").exists());
1688 assert!(lib_dst.join("lib/dep-a/lib/dep-b").exists());
1689 assert!(lib_dst.join("lib/dep-a/lib/dep-b/lib/dep-c").exists());
1690 assert!(lib_dst.join("lib/dep-a/lib/dep-b/lib/dep-c/src/C.sol").exists());
1691 }
1692
1693 #[test]
1694 fn test_symlink_nested_libs_no_nested_lib_dir() {
1695 let temp = TempDir::new().unwrap();
1696
1697 let lib_src = temp.path().join("lib_src");
1698 create_test_dir_structure(&lib_src, &["src/Contract.sol", "test/Test.sol"]);
1699
1700 let lib_dst = temp.path().join("lib_dst");
1701 fs::create_dir(&lib_dst).unwrap();
1702
1703 symlink_nested_libs(&lib_src, &lib_dst, 0).unwrap();
1704
1705 assert!(!lib_dst.join("lib").exists());
1706 }
1707
1708 #[test]
1709 fn test_symlink_nested_libs_skips_existing() {
1710 let temp = TempDir::new().unwrap();
1711
1712 let lib_src = temp.path().join("lib_src");
1713 create_test_dir_structure(&lib_src, &["lib/", "lib/existing/src/File.sol"]);
1714
1715 let lib_dst = temp.path().join("lib_dst");
1716 fs::create_dir_all(lib_dst.join("lib/existing")).unwrap();
1717 fs::write(lib_dst.join("lib/existing/marker.txt"), "pre-existing").unwrap();
1718
1719 symlink_nested_libs(&lib_src, &lib_dst, 0).unwrap();
1720
1721 assert!(lib_dst.join("lib/existing/marker.txt").exists());
1722 }
1723
1724 #[test]
1725 fn test_copy_dir_recursive_basic() {
1726 let temp = TempDir::new().unwrap();
1727
1728 let src = temp.path().join("src");
1729 create_test_dir_structure(
1730 &src,
1731 &["file1.sol", "subdir/file2.sol", "subdir/nested/file3.sol"],
1732 );
1733
1734 let dst = temp.path().join("dst");
1735 copy_dir_recursive(&src, &dst).unwrap();
1736
1737 assert!(dst.join("file1.sol").exists());
1738 assert!(dst.join("subdir/file2.sol").exists());
1739 assert!(dst.join("subdir/nested/file3.sol").exists());
1740 }
1741
1742 #[cfg(not(target_os = "windows"))]
1743 #[test]
1744 fn test_copy_project_dir_recursive_preserves_in_root_symlink_aliases() {
1745 let temp = TempDir::new().unwrap();
1746
1747 let root = temp.path().join("project");
1748 let src = root.join("src");
1749 let shared = root.join(".shared/pkg");
1750 fs::create_dir_all(&shared).unwrap();
1751 fs::create_dir_all(src.join("nested")).unwrap();
1752 fs::write(shared.join("Y.sol"), "contract Y {}").unwrap();
1753 symlink_dir(Path::new("../.shared/pkg"), &src.join("first")).unwrap();
1754 symlink_dir(Path::new("../../.shared/pkg"), &src.join("nested/second")).unwrap();
1755
1756 let dst = temp.path().join("dst/src");
1757 copy_project_dir_recursive(&root, &src, &dst).unwrap();
1758
1759 assert!(dst.join("first/Y.sol").exists());
1760 assert!(dst.join("nested/second/Y.sol").exists());
1761 }
1762
1763 #[test]
1764 fn test_copy_dir_recursive_skips_symlinked_dirs() {
1765 let temp = TempDir::new().unwrap();
1766
1767 let src = temp.path().join("src");
1768 let external = temp.path().join("external");
1769
1770 fs::create_dir_all(&external).unwrap();
1771 fs::write(external.join("secret.txt"), "should not be copied").unwrap();
1772
1773 fs::create_dir_all(&src).unwrap();
1774 fs::write(src.join("file.sol"), "content").unwrap();
1775
1776 symlink_dir(&external, &src.join("external_link")).unwrap();
1777
1778 let dst = temp.path().join("dst");
1779 copy_dir_recursive(&src, &dst).unwrap();
1780
1781 assert!(dst.join("file.sol").exists());
1782 assert!(!dst.join("external_link").exists());
1783 }
1784
1785 #[test]
1786 fn test_copy_dir_recursive_nonexistent_src() {
1787 let temp = TempDir::new().unwrap();
1788
1789 let src = temp.path().join("nonexistent");
1790 let dst = temp.path().join("dst");
1791
1792 copy_dir_recursive(&src, &dst).unwrap();
1793 assert!(!dst.exists());
1794 }
1795
1796 #[test]
1797 fn test_copy_project_copies_include_paths_under_root() {
1798 let temp = TempDir::new().unwrap();
1799 let root = temp.path().join("project");
1800 let out = temp.path().join("workspace");
1801 create_test_dir_structure(
1802 &root,
1803 &["src/Counter.sol", "test/Counter.t.sol", "include/Shared.sol"],
1804 );
1805
1806 let config = Config {
1807 root: root.clone(),
1808 src: root.join("src"),
1809 test: root.join("test"),
1810 script: root.join("script"),
1811 include_paths: vec![root.join("include")],
1812 ..Default::default()
1813 };
1814
1815 copy_project(&config, &out).unwrap();
1816
1817 assert!(out.join("include/Shared.sol").exists());
1818 }
1819
1820 #[test]
1821 fn test_copy_project_skips_include_paths_covered_by_libs() {
1822 let temp = TempDir::new().unwrap();
1823 let root = temp.path().join("project");
1824 let out = temp.path().join("workspace");
1825 create_test_dir_structure(
1826 &root,
1827 &["src/Counter.sol", "test/Counter.t.sol", "lib/foo/Foo.sol", "lib/bar/Bar.sol"],
1828 );
1829
1830 let config = Config {
1831 root: root.clone(),
1832 src: root.join("src"),
1833 test: root.join("test"),
1834 script: root.join("script"),
1835 libs: vec![root.join("lib")],
1836 include_paths: vec![root.join("lib/foo")],
1837 ..Default::default()
1838 };
1839
1840 copy_project(&config, &out).unwrap();
1841
1842 assert!(out.join("lib/foo/Foo.sol").exists());
1843 assert!(out.join("lib/bar/Bar.sol").exists());
1844 }
1845
1846 #[test]
1847 fn test_copy_project_preserves_absolute_external_include_paths() {
1848 let temp = TempDir::new().unwrap();
1849 let root = temp.path().join("project");
1850 let outside = temp.path().join("outside");
1851 let out = temp.path().join("workspace");
1852 create_test_dir_structure(&root, &["src/Counter.sol", "test/Counter.t.sol"]);
1853 create_test_dir_structure(&outside, &["Shared.sol"]);
1854
1855 let config = Config {
1856 root: root.clone(),
1857 src: root.join("src"),
1858 test: root.join("test"),
1859 script: root.join("script"),
1860 include_paths: vec![outside.clone()],
1861 ..Default::default()
1862 };
1863
1864 copy_project(&config, &out).unwrap();
1865 let temp_config = rebase_config_paths(&config, &out);
1866 let outside = normalize_existing_ancestor(&outside);
1867
1868 assert_eq!(temp_config.include_paths, vec![outside]);
1869 assert!(!out.join("outside/Shared.sol").exists());
1870 }
1871
1872 #[test]
1873 fn test_relative_to_root_basic() {
1874 let root = PathBuf::from("/project");
1875 let path = PathBuf::from("/project/src/contracts");
1876
1877 let rel = relative_to_root(&root, &path);
1878 assert_eq!(rel, PathBuf::from("src/contracts"));
1879 }
1880
1881 #[test]
1882 fn test_relative_to_root_same_path() {
1883 let root = PathBuf::from("/project");
1884 let path = PathBuf::from("/project");
1885
1886 let rel = relative_to_root(&root, &path);
1887 assert_eq!(rel, PathBuf::from(""));
1888 }
1889
1890 #[test]
1891 fn test_relative_to_root_outside_root() {
1892 let root = PathBuf::from("/project");
1893 let path = PathBuf::from("/other/location");
1894
1895 let rel = relative_to_root(&root, &path);
1896 assert_eq!(rel, normalize_existing_ancestor(&path));
1897 }
1898
1899 #[test]
1900 fn test_ensure_within_root_rejects_symlink_escape() {
1901 let temp = TempDir::new().unwrap();
1902 let root = temp.path().join("project");
1903 let outside = temp.path().join("outside");
1904 fs::create_dir_all(&root).unwrap();
1905 fs::create_dir_all(&outside).unwrap();
1906 fs::write(outside.join("secret.txt"), "shhh").unwrap();
1907
1908 let src = root.join("src");
1910 symlink_dir(&outside, &src).unwrap();
1911
1912 let err = ensure_within_root(&root, &src, "src", &src).unwrap_err();
1913 assert!(err.to_string().contains("escapes project root"), "unexpected error: {err}");
1914 }
1915
1916 #[test]
1917 fn test_ensure_within_root_accepts_in_root_symlink() {
1918 let temp = TempDir::new().unwrap();
1919 let root = temp.path().join("project");
1920 let real_src = root.join("real_src");
1921 fs::create_dir_all(&real_src).unwrap();
1922
1923 let src_link = root.join("src");
1925 symlink_dir(&real_src, &src_link).unwrap();
1926
1927 ensure_within_root(&root, &src_link, "src", &src_link).unwrap();
1928 }
1929
1930 #[test]
1931 fn test_symlink_nested_libs_rejects_traversal_in_dependency_config() {
1932 let temp = TempDir::new().unwrap();
1933
1934 let malicious: PathBuf = PathBuf::from("../../escape");
1940 assert!(!is_safe_relative_path(&malicious));
1941
1942 let benign: PathBuf = PathBuf::from("lib");
1944 assert!(is_safe_relative_path(&benign));
1945
1946 let lib_src = temp.path().join("lib_src");
1948 let lib_dst = temp.path().join("lib_dst");
1949 fs::create_dir_all(&lib_src).unwrap();
1950 fs::create_dir_all(&lib_dst).unwrap();
1951 symlink_nested_libs(&lib_src, &lib_dst, 0).unwrap();
1952 }
1953
1954 #[test]
1955 fn test_process_nested_lib_dir_skips_symlinks() {
1956 let temp = TempDir::new().unwrap();
1957 let outside = temp.path().join("outside");
1958 fs::create_dir_all(outside.join("secret_pkg/src")).unwrap();
1959 fs::write(outside.join("secret_pkg/src/Secret.sol"), "secret").unwrap();
1960
1961 let lib_src = temp.path().join("lib_src");
1962 let nested = lib_src.join("lib");
1963 fs::create_dir_all(&nested).unwrap();
1964 symlink_dir(&outside.join("secret_pkg"), &nested.join("evil")).unwrap();
1966
1967 let lib_dst = temp.path().join("lib_dst");
1968 fs::create_dir_all(&lib_dst).unwrap();
1969
1970 process_nested_lib_dir(&nested, &lib_dst, Path::new("lib"), 0).unwrap();
1971
1972 assert!(!lib_dst.join("lib/evil").exists(), "symlinked dep was followed");
1974 }
1975}