Skip to content

Commit a54c342

Browse files
committed
fix(harness): keep the workspace subtree invisible to the project layer
## Description With the default local filesystem, the project layer reaches across namespaces in three ways: - Enumeration: `grep(pattern, "")` returns matches from another user's `MEMORY.md`, content included; `ls("")` and `glob("**/*.md", "")` list the sibling namespaces. The overlay hands the same path to the upper (workspace) and lower (project) layers, the default workspace is a subtree of the project directory, and the lower layer carries no namespace. - Direct content access: `read`, `exists`, `edit` (copy-on-write), `downloadFiles` and `move` fall back to the lower layer too, so a relative path spelling the physical layout - `.agentscope/workspace/alice/MEMORY.md` - reads alice's file, and `edit` copies it into the caller's namespace before modifying it. - Absolute paths: the namespace prefix is skipped for absolute spellings, so without a boundary the `projectFs` write route would run a delete or move against an absolute path inside the workspace subtree. Previously `LocalFilesystem.resolvePath` passed a blank key to the namespace prefix unchanged, so it resolved to the workspace root; the physical layout was reachable whenever the caller named it. ### What changed - A blank key is resolved as `.` before the namespace is applied, so an empty path means "the caller's root" instead of the shared workspace root. Deployments without a namespace resolve to the same directory as before. - `LocalFilesystem` can hide a subtree entirely: enumeration skips it while walking, and the content operations - reads, edits, writes, deletes, moves, downloads, uploads and existence checks - see nothing there. `delete` treats the subtree as absent (an idempotent no-op that never walks it), `move` can neither move a file out of or into the subtree, and both `move` and recursive `delete` refuse a directory that contains it outright rather than partially touch it. Explicitly addressing a hidden subtree as a search root yields nothing rather than walking it, and a `walkFileTree` visitor that cannot enter a directory skips and continues instead of propagating. - `LocalFilesystemSpec` hides the workspace from the project layers when the workspace is a proper subtree of the project and namespace scoping is on - both the read-only lower layer and, for the same reason, the `projectFs` write route, whose absolute paths skip the namespace prefix. A workspace equal to or outside the project has no nesting to hide, a shared workspace belongs to every caller equally, and project files outside the workspace subtree stay shared, like `AGENTS.md` and `knowledge/`. - `relativeForGlob` compares the first path name instead of the string, so a legitimate directory literally named `..cache` is a descendant, not a traversal escape. - `docs/v2/{zh,en}/docs/harness/filesystem.md` note the boundary in the Overlay filesystem section, the project-writable read behavior, and the mode table. Absolute paths in the upper (workspace) layer and `..` segments are out of scope: #3292 covers the former, #3378 the latter. The shell keeps its own project-rooted working directory, so `execute` is not bound by these guards (#2329). The ripgrep `--glob` exclusions assume rg matches globs against paths relative to the search root; where that does not hold, the boundary still holds because the default workspace lives under a hidden directory that rg skips by default, and the `walkFileTree` fallback applies the same exclusions directly. ### Tests - New: as one user, a blank, relative or glob search sees nothing under another user's namespace - in both the default and the writable-project construction - and the content operations answer "not found" for a sibling namespace spelled through the physical layout, while project files outside the workspace and the caller's own namespace stay readable. - New: direct use of the hidden lower layer - `delete` leaves the subtree untouched, `move` cannot cross the boundary in either direction, writes cannot land inside it (the target does not exist yet, so the assertion cannot pass merely because the file is there), and operations that start at an ancestor (recursive delete, directory move) are refused outright instead of partially touching the hidden subtree. Each of these assertions was verified to fail with its guard removed. - New: a shared workspace stays enumerable through the project layer, so the boundary does not over-reach into single-tenant deployments. - New: `memory_get` cannot fetch a sibling namespace's content. This test's workspace is a standalone temp directory, so it pins the blank-key and namespace-prefix resolution end to end; the real project-layer boundary is exercised by the boundary tests below. - `mvn -pl agentscope-harness test`: 1626 tests, 0 failures. Fixes #4069
1 parent c52d1fc commit a54c342

6 files changed

Lines changed: 479 additions & 43 deletions

File tree

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystem.java‎

Lines changed: 182 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
import java.util.Comparator;
5353
import java.util.List;
5454
import java.util.Map;
55+
import java.util.Set;
5556
import java.util.concurrent.ConcurrentHashMap;
5657
import java.util.concurrent.locks.ReentrantLock;
5758
import java.util.regex.Pattern;
@@ -92,6 +93,19 @@ public class LocalFilesystem implements AbstractFilesystem {
9293
*/
9394
private final ConcurrentHashMap<String, ReentrantLock> fileLocks = new ConcurrentHashMap<>();
9495

96+
/**
97+
* Absolute subtrees that are invisible to this filesystem: {@link #ls}, {@link #glob} and
98+
* {@link #grep} do not descend into them, and the content operations ({@link #read},
99+
* {@link #edit}, {@link #write}, {@link #delete}, {@link #move}, {@link #exists},
100+
* {@link #downloadFiles}, {@link #uploadFiles}) do not see them. Recursive operations
101+
* refuse a directory that contains a hidden subtree rather than touch it. The overlay
102+
* layers use this: the user project can
103+
* contain the agent workspace as a subtree, and without the boundary the project layer would
104+
* expose every caller's namespace under it — by walking it, or by resolving the physical
105+
* layout directly.
106+
*/
107+
private final Set<Path> excludedSubtrees = ConcurrentHashMap.newKeySet();
108+
95109
/**
96110
* Same as {@link #LocalFilesystem(Path)} with {@link Path#of(String, String...) Path.of(path)}
97111
* after {@link String#strip()}. Pass {@code null} for the same CWD semantics as a {@code null}
@@ -237,6 +251,9 @@ public PathPolicy getPathPolicy() {
237251
@Override
238252
public LsResult ls(RuntimeContext runtimeContext, String path) {
239253
Path dirPath = resolvePath(runtimeContext, path);
254+
if (isSubtreeExcluded(dirPath)) {
255+
return LsResult.success(List.of());
256+
}
240257
if (!Files.exists(dirPath)) {
241258
return LsResult.fail("Path does not exist: " + path);
242259
}
@@ -247,6 +264,9 @@ public LsResult ls(RuntimeContext runtimeContext, String path) {
247264
List<FileInfo> results = new ArrayList<>();
248265
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dirPath)) {
249266
for (Path entry : ds) {
267+
if (isSubtreeExcluded(entry)) {
268+
continue;
269+
}
250270
try {
251271
BasicFileAttributes attrs =
252272
Files.readAttributes(entry, BasicFileAttributes.class);
@@ -274,6 +294,9 @@ public LsResult ls(RuntimeContext runtimeContext, String path) {
274294
@Override
275295
public ReadResult read(RuntimeContext runtimeContext, String filePath, int offset, int limit) {
276296
Path resolved = resolvePath(runtimeContext, filePath);
297+
if (isSubtreeExcluded(resolved)) {
298+
return ReadResult.fail("File '" + filePath + "' not found");
299+
}
277300

278301
if (!Files.exists(resolved) || !Files.isRegularFile(resolved)) {
279302
return ReadResult.fail("File '" + filePath + "' not found");
@@ -324,6 +347,9 @@ public ReadResult read(RuntimeContext runtimeContext, String filePath, int offse
324347
@Override
325348
public WriteResult write(RuntimeContext runtimeContext, String filePath, String content) {
326349
Path resolved = resolvePath(runtimeContext, filePath);
350+
if (isSubtreeExcluded(resolved)) {
351+
return WriteResult.fail("Cannot write to '" + filePath + "': path is not visible here");
352+
}
327353

328354
if (Files.exists(resolved)) {
329355
return WriteResult.fail(
@@ -357,6 +383,9 @@ public EditResult edit(
357383
}
358384

359385
Path resolved = resolvePath(runtimeContext, filePath);
386+
if (isSubtreeExcluded(resolved)) {
387+
return EditResult.fail("Error: File '" + filePath + "' not found");
388+
}
360389

361390
if (!Files.exists(resolved) || !Files.isRegularFile(resolved)) {
362391
return EditResult.fail("Error: File '" + filePath + "' not found");
@@ -403,6 +432,9 @@ public GrepResult grep(
403432
if (!Files.exists(basePath)) {
404433
return GrepResult.success(List.of());
405434
}
435+
if (isSubtreeExcluded(basePath)) {
436+
return GrepResult.success(List.of());
437+
}
406438

407439
List<GrepMatch> matches = ripgrepSearch(runtimeContext, pattern, basePath, glob);
408440
if (matches == null) {
@@ -428,6 +460,9 @@ public GlobResult glob(RuntimeContext runtimeContext, String pattern, String pat
428460
if (!Files.exists(searchPath) || !Files.isDirectory(searchPath)) {
429461
return GlobResult.success(List.of());
430462
}
463+
if (isSubtreeExcluded(searchPath)) {
464+
return GlobResult.success(List.of());
465+
}
431466

432467
String globExpr =
433468
effectivePattern.startsWith("**") ? effectivePattern : "**/" + effectivePattern;
@@ -451,8 +486,19 @@ public GlobResult glob(RuntimeContext runtimeContext, String pattern, String pat
451486
Files.walkFileTree(
452487
searchPath,
453488
new SimpleFileVisitor<>() {
489+
@Override
490+
public FileVisitResult preVisitDirectory(
491+
Path dir, BasicFileAttributes attrs) {
492+
return isSubtreeExcluded(dir)
493+
? FileVisitResult.SKIP_SUBTREE
494+
: FileVisitResult.CONTINUE;
495+
}
496+
454497
@Override
455498
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
499+
if (isSubtreeExcluded(file)) {
500+
return FileVisitResult.CONTINUE;
501+
}
456502
Path rel = searchPath.relativize(file);
457503
if (matcher.matches(rel) || directMatcher.matches(rel)) {
458504
String filePath = resolveEntryPath(runtimeContext, file);
@@ -486,6 +532,10 @@ public List<FileUploadResponse> uploadFiles(
486532
byte[] content = entry.getValue();
487533
try {
488534
Path resolved = resolvePath(runtimeContext, filePath);
535+
if (isSubtreeExcluded(resolved)) {
536+
responses.add(FileUploadResponse.fail(filePath, "path is not visible here"));
537+
continue;
538+
}
489539
if (resolved.getParent() != null) {
490540
Files.createDirectories(resolved.getParent());
491541
}
@@ -507,7 +557,7 @@ public List<FileDownloadResponse> downloadFiles(
507557
for (String filePath : paths) {
508558
try {
509559
Path resolved = resolvePath(runtimeContext, filePath);
510-
if (!Files.exists(resolved)) {
560+
if (isSubtreeExcluded(resolved) || !Files.exists(resolved)) {
511561
responses.add(FileDownloadResponse.fail(filePath, "file_not_found"));
512562
continue;
513563
}
@@ -530,11 +580,20 @@ public List<FileDownloadResponse> downloadFiles(
530580
public WriteResult delete(RuntimeContext runtimeContext, String path) {
531581
AbstractFilesystem.validatePath(path);
532582
Path resolved = resolvePath(runtimeContext, path);
533-
if (!Files.exists(resolved)) {
583+
// An excluded subtree does not exist for this caller, so delete stays an idempotent
584+
// no-op instead of walking a shared layer it must never reach.
585+
if (isSubtreeExcluded(resolved) || !Files.exists(resolved)) {
534586
return WriteResult.ok(path); // idempotent
535587
}
588+
if (Files.isDirectory(resolved) && containsExcludedSubtree(resolved)) {
589+
// Same stance as move: a directory that contains a hidden subtree is refused
590+
// outright instead of partially deleted around it.
591+
return WriteResult.fail("Cannot delete '" + path + "': contains hidden content");
592+
}
536593
try {
537594
if (Files.isDirectory(resolved)) {
595+
// The refusal above guarantees no hidden subtree sits under this directory,
596+
// so the walk cannot enter one.
538597
try (Stream<Path> walk = Files.walk(resolved)) {
539598
walk.sorted(Comparator.reverseOrder())
540599
.forEach(
@@ -561,9 +620,16 @@ public WriteResult move(RuntimeContext runtimeContext, String fromPath, String t
561620
AbstractFilesystem.validatePath(toPath);
562621
Path from = resolvePath(runtimeContext, fromPath);
563622
Path to = resolvePath(runtimeContext, toPath);
564-
if (!Files.exists(from)) {
623+
if (isSubtreeExcluded(from) || !Files.exists(from)) {
565624
return WriteResult.fail("Source does not exist: " + fromPath);
566625
}
626+
if (isSubtreeExcluded(to)) {
627+
return WriteResult.fail("Destination is not visible here: " + toPath);
628+
}
629+
if (Files.isDirectory(from) && containsExcludedSubtree(from)) {
630+
// Moving the directory would carry hidden content out of its hidden location.
631+
return WriteResult.fail("Cannot move '" + fromPath + "': contains hidden content");
632+
}
567633
try {
568634
if (to.getParent() != null) {
569635
Files.createDirectories(to.getParent());
@@ -582,7 +648,8 @@ public boolean exists(RuntimeContext runtimeContext, String path) {
582648
return false;
583649
}
584650
try {
585-
return Files.exists(resolvePath(runtimeContext, path));
651+
Path resolved = resolvePath(runtimeContext, path);
652+
return !isSubtreeExcluded(resolved) && Files.exists(resolved);
586653
} catch (SecurityException e) {
587654
return false;
588655
}
@@ -600,12 +667,56 @@ public io.agentscope.core.session.AtomicSessionStorage sessionStorage(RuntimeCon
600667
resolvePath(rc, ".").resolve(".agentscope-runtime"));
601668
}
602669

670+
/**
671+
* Hides a subtree from this filesystem entirely: enumeration skips it, and reads, writes
672+
* and every other content operation treat it as absent. This keeps a shared lower layer
673+
* from exposing files that belong to a namespace it does not own.
674+
*
675+
* @param root absolute root to hide; relative paths and {@code null} are ignored
676+
* @return this filesystem, for chaining
677+
*/
678+
public LocalFilesystem excludeSubtree(Path root) {
679+
if (root != null && root.isAbsolute()) {
680+
excludedSubtrees.add(root.normalize());
681+
}
682+
return this;
683+
}
684+
685+
private boolean isSubtreeExcluded(Path path) {
686+
if (excludedSubtrees.isEmpty() || path == null) {
687+
return false;
688+
}
689+
Path absolute = path.toAbsolutePath().normalize();
690+
for (Path excluded : excludedSubtrees) {
691+
if (absolute.startsWith(excluded)) {
692+
return true;
693+
}
694+
}
695+
return false;
696+
}
697+
698+
/** True when {@code path} is an ancestor of a hidden subtree root, or the root itself. */
699+
private boolean containsExcludedSubtree(Path path) {
700+
if (excludedSubtrees.isEmpty() || path == null) {
701+
return false;
702+
}
703+
Path absolute = path.toAbsolutePath().normalize();
704+
for (Path excluded : excludedSubtrees) {
705+
if (excluded.startsWith(absolute)) {
706+
return true;
707+
}
708+
}
709+
return false;
710+
}
711+
603712
protected Path resolvePath(RuntimeContext rc, String key) {
604713
if (key != null
605714
&& java.util.Arrays.stream(key.replace('\\', '/').split("/"))
606715
.anyMatch(".agentscope-runtime"::equalsIgnoreCase))
607716
throw new SecurityException("Session journal is reserved for the runtime");
608-
String effectiveKey = applyNamespacePrefix(rc, key);
717+
// A blank key means "the root of the caller's view", not the shared workspace root:
718+
// resolving it to cwd would let a relative list/search escape the namespace.
719+
String effectiveKey = applyNamespacePrefix(rc, (key == null || key.isBlank()) ? "." : key);
609720
if (effectiveKey == null || effectiveKey.isBlank()) {
610721
return cwd;
611722
}
@@ -780,6 +891,22 @@ private String stripNamespacePrefix(RuntimeContext rc, Path absolutePath) {
780891

781892
// ==================== Grep implementations ====================
782893

894+
/**
895+
* Path of {@code excluded} relative to {@code base} for a ripgrep {@code --glob} argument,
896+
* or {@code null} when it is not a descendant (nothing to exclude).
897+
*/
898+
private static String relativeForGlob(Path base, Path excluded) {
899+
try {
900+
Path relative = base.toAbsolutePath().normalize().relativize(excluded);
901+
String value = relative.toString().replace('\\', '/');
902+
// Compare the first name rather than the string: a legitimate directory literally
903+
// named "..cache" is a descendant, not a traversal escape.
904+
return value.isEmpty() || relative.getName(0).toString().equals("..") ? null : value;
905+
} catch (IllegalArgumentException e) {
906+
return null;
907+
}
908+
}
909+
783910
private List<GrepMatch> ripgrepSearch(
784911
RuntimeContext rc, String pattern, Path basePath, String includeGlob) {
785912
List<String> cmd = new ArrayList<>();
@@ -790,6 +917,13 @@ private List<GrepMatch> ripgrepSearch(
790917
cmd.add("--glob");
791918
cmd.add(includeGlob);
792919
}
920+
for (Path excluded : excludedSubtrees) {
921+
String relative = relativeForGlob(basePath, excluded);
922+
if (relative != null) {
923+
cmd.add("--glob");
924+
cmd.add("!" + relative + "/**");
925+
}
926+
}
793927
cmd.add("--");
794928
cmd.add(pattern);
795929
cmd.add(basePath.toString());
@@ -889,44 +1023,55 @@ private List<GrepMatch> javaSearch(
8891023
if (includeGlob != null && !includeGlob.isBlank()) {
8901024
globMatcher = FileSystems.getDefault().getPathMatcher("glob:" + includeGlob);
8911025
}
1026+
PathMatcher finalGlobMatcher = globMatcher;
8921027

8931028
List<GrepMatch> matches = new ArrayList<>();
8941029
Path root = Files.isDirectory(basePath) ? basePath : basePath.getParent();
8951030

896-
try (Stream<Path> walk = Files.walk(root)) {
897-
PathMatcher finalGlobMatcher = globMatcher;
898-
walk.filter(Files::isRegularFile)
899-
.filter(
900-
p -> {
901-
if (finalGlobMatcher != null) {
902-
return finalGlobMatcher.matches(p.getFileName());
903-
}
904-
return true;
905-
})
906-
.filter(
907-
p -> {
908-
try {
909-
return Files.size(p) <= maxFileSizeBytes;
910-
} catch (IOException e) {
911-
return false;
912-
}
913-
})
914-
.forEach(
915-
file -> {
916-
try {
917-
List<String> lines =
918-
Files.readAllLines(file, StandardCharsets.UTF_8);
919-
for (int i = 0; i < lines.size(); i++) {
920-
if (compiledPattern.matcher(lines.get(i)).find()) {
921-
String filePath = resolveEntryPath(rc, file);
922-
matches.add(
923-
new GrepMatch(filePath, i + 1, lines.get(i)));
924-
}
1031+
try {
1032+
Files.walkFileTree(
1033+
root,
1034+
new SimpleFileVisitor<>() {
1035+
@Override
1036+
public FileVisitResult preVisitDirectory(
1037+
Path dir, BasicFileAttributes attrs) {
1038+
return isSubtreeExcluded(dir)
1039+
? FileVisitResult.SKIP_SUBTREE
1040+
: FileVisitResult.CONTINUE;
1041+
}
1042+
1043+
@Override
1044+
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
1045+
if (isSubtreeExcluded(file)) {
1046+
return FileVisitResult.CONTINUE;
1047+
}
1048+
if (finalGlobMatcher != null
1049+
&& !finalGlobMatcher.matches(file.getFileName())) {
1050+
return FileVisitResult.CONTINUE;
1051+
}
1052+
if (attrs.size() > maxFileSizeBytes) {
1053+
return FileVisitResult.CONTINUE;
1054+
}
1055+
try {
1056+
List<String> lines =
1057+
Files.readAllLines(file, StandardCharsets.UTF_8);
1058+
for (int i = 0; i < lines.size(); i++) {
1059+
if (compiledPattern.matcher(lines.get(i)).find()) {
1060+
String filePath = resolveEntryPath(rc, file);
1061+
matches.add(new GrepMatch(filePath, i + 1, lines.get(i)));
9251062
}
926-
} catch (IOException e) {
927-
// Skip binary/unreadable files
9281063
}
929-
});
1064+
} catch (IOException e) {
1065+
// Skip binary/unreadable files
1066+
}
1067+
return FileVisitResult.CONTINUE;
1068+
}
1069+
1070+
@Override
1071+
public FileVisitResult visitFileFailed(Path file, IOException exc) {
1072+
return FileVisitResult.CONTINUE;
1073+
}
1074+
});
9301075
} catch (IOException e) {
9311076
log.warn("Java search failed: {}", e.getMessage());
9321077
}

0 commit comments

Comments
 (0)