Skip to content

Commit 3a8ddb6

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 two 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. `LocalFilesystem.resolvePath` passes a blank key to the namespace prefix unchanged, so it resolves to the workspace root; the physical layout is reachable whenever the caller names 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 see nothing there — reads, edits, writes, downloads and existence checks answer "not found". Explicitly addressing a hidden subtree as a search root yields nothing rather than walking it. - `LocalFilesystemSpec` hides the workspace from the project layer when the workspace is a proper subtree of the project and namespace scoping is on. A workspace equal to or outside the project has no nesting to hide, a shared workspace belongs to every caller equally, and the projectFs write route carries the namespace factory itself, so physical-layout spellings resolve under the caller's own prefix either way. Project files outside the workspace subtree stay shared, like `AGENTS.md` and `knowledge/`. Absolute paths and `..` segments are out of scope: #3292 covers the former, #3378 the latter, and the shell keeps its own project-rooted working directory (#2329). ### 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: 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 by spelling the physical layout. - `mvn -pl agentscope-harness test`: 1622 tests, 0 failures.
1 parent c52d1fc commit 3a8ddb6

4 files changed

Lines changed: 403 additions & 37 deletions

File tree

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

Lines changed: 155 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,17 @@ 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 #exists}, {@link #move}, {@link #downloadFiles},
100+
* {@link #uploadFiles}) do not see them. The overlay layers use this: the user project can
101+
* contain the agent workspace as a subtree, and without the boundary the project layer would
102+
* expose every caller's namespace under it — by walking it, or by resolving the physical
103+
* layout directly.
104+
*/
105+
private final Set<Path> excludedSubtrees = ConcurrentHashMap.newKeySet();
106+
95107
/**
96108
* Same as {@link #LocalFilesystem(Path)} with {@link Path#of(String, String...) Path.of(path)}
97109
* after {@link String#strip()}. Pass {@code null} for the same CWD semantics as a {@code null}
@@ -237,6 +249,9 @@ public PathPolicy getPathPolicy() {
237249
@Override
238250
public LsResult ls(RuntimeContext runtimeContext, String path) {
239251
Path dirPath = resolvePath(runtimeContext, path);
252+
if (isSubtreeExcluded(dirPath)) {
253+
return LsResult.success(List.of());
254+
}
240255
if (!Files.exists(dirPath)) {
241256
return LsResult.fail("Path does not exist: " + path);
242257
}
@@ -247,6 +262,9 @@ public LsResult ls(RuntimeContext runtimeContext, String path) {
247262
List<FileInfo> results = new ArrayList<>();
248263
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dirPath)) {
249264
for (Path entry : ds) {
265+
if (isSubtreeExcluded(entry)) {
266+
continue;
267+
}
250268
try {
251269
BasicFileAttributes attrs =
252270
Files.readAttributes(entry, BasicFileAttributes.class);
@@ -274,6 +292,9 @@ public LsResult ls(RuntimeContext runtimeContext, String path) {
274292
@Override
275293
public ReadResult read(RuntimeContext runtimeContext, String filePath, int offset, int limit) {
276294
Path resolved = resolvePath(runtimeContext, filePath);
295+
if (isSubtreeExcluded(resolved)) {
296+
return ReadResult.fail("File '" + filePath + "' not found");
297+
}
277298

278299
if (!Files.exists(resolved) || !Files.isRegularFile(resolved)) {
279300
return ReadResult.fail("File '" + filePath + "' not found");
@@ -324,6 +345,9 @@ public ReadResult read(RuntimeContext runtimeContext, String filePath, int offse
324345
@Override
325346
public WriteResult write(RuntimeContext runtimeContext, String filePath, String content) {
326347
Path resolved = resolvePath(runtimeContext, filePath);
348+
if (isSubtreeExcluded(resolved)) {
349+
return WriteResult.fail("Cannot write to '" + filePath + "': path is not visible here");
350+
}
327351

328352
if (Files.exists(resolved)) {
329353
return WriteResult.fail(
@@ -357,6 +381,9 @@ public EditResult edit(
357381
}
358382

359383
Path resolved = resolvePath(runtimeContext, filePath);
384+
if (isSubtreeExcluded(resolved)) {
385+
return EditResult.fail("Error: File '" + filePath + "' not found");
386+
}
360387

361388
if (!Files.exists(resolved) || !Files.isRegularFile(resolved)) {
362389
return EditResult.fail("Error: File '" + filePath + "' not found");
@@ -403,6 +430,9 @@ public GrepResult grep(
403430
if (!Files.exists(basePath)) {
404431
return GrepResult.success(List.of());
405432
}
433+
if (isSubtreeExcluded(basePath)) {
434+
return GrepResult.success(List.of());
435+
}
406436

407437
List<GrepMatch> matches = ripgrepSearch(runtimeContext, pattern, basePath, glob);
408438
if (matches == null) {
@@ -428,6 +458,9 @@ public GlobResult glob(RuntimeContext runtimeContext, String pattern, String pat
428458
if (!Files.exists(searchPath) || !Files.isDirectory(searchPath)) {
429459
return GlobResult.success(List.of());
430460
}
461+
if (isSubtreeExcluded(searchPath)) {
462+
return GlobResult.success(List.of());
463+
}
431464

432465
String globExpr =
433466
effectivePattern.startsWith("**") ? effectivePattern : "**/" + effectivePattern;
@@ -451,8 +484,19 @@ public GlobResult glob(RuntimeContext runtimeContext, String pattern, String pat
451484
Files.walkFileTree(
452485
searchPath,
453486
new SimpleFileVisitor<>() {
487+
@Override
488+
public FileVisitResult preVisitDirectory(
489+
Path dir, BasicFileAttributes attrs) {
490+
return isSubtreeExcluded(dir)
491+
? FileVisitResult.SKIP_SUBTREE
492+
: FileVisitResult.CONTINUE;
493+
}
494+
454495
@Override
455496
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
497+
if (isSubtreeExcluded(file)) {
498+
return FileVisitResult.CONTINUE;
499+
}
456500
Path rel = searchPath.relativize(file);
457501
if (matcher.matches(rel) || directMatcher.matches(rel)) {
458502
String filePath = resolveEntryPath(runtimeContext, file);
@@ -486,6 +530,10 @@ public List<FileUploadResponse> uploadFiles(
486530
byte[] content = entry.getValue();
487531
try {
488532
Path resolved = resolvePath(runtimeContext, filePath);
533+
if (isSubtreeExcluded(resolved)) {
534+
responses.add(FileUploadResponse.fail(filePath, "path is not visible here"));
535+
continue;
536+
}
489537
if (resolved.getParent() != null) {
490538
Files.createDirectories(resolved.getParent());
491539
}
@@ -507,7 +555,7 @@ public List<FileDownloadResponse> downloadFiles(
507555
for (String filePath : paths) {
508556
try {
509557
Path resolved = resolvePath(runtimeContext, filePath);
510-
if (!Files.exists(resolved)) {
558+
if (isSubtreeExcluded(resolved) || !Files.exists(resolved)) {
511559
responses.add(FileDownloadResponse.fail(filePath, "file_not_found"));
512560
continue;
513561
}
@@ -530,7 +578,9 @@ public List<FileDownloadResponse> downloadFiles(
530578
public WriteResult delete(RuntimeContext runtimeContext, String path) {
531579
AbstractFilesystem.validatePath(path);
532580
Path resolved = resolvePath(runtimeContext, path);
533-
if (!Files.exists(resolved)) {
581+
// An excluded subtree does not exist for this caller, so delete stays an idempotent
582+
// no-op instead of walking a shared layer it must never reach.
583+
if (isSubtreeExcluded(resolved) || !Files.exists(resolved)) {
534584
return WriteResult.ok(path); // idempotent
535585
}
536586
try {
@@ -561,9 +611,12 @@ public WriteResult move(RuntimeContext runtimeContext, String fromPath, String t
561611
AbstractFilesystem.validatePath(toPath);
562612
Path from = resolvePath(runtimeContext, fromPath);
563613
Path to = resolvePath(runtimeContext, toPath);
564-
if (!Files.exists(from)) {
614+
if (isSubtreeExcluded(from) || !Files.exists(from)) {
565615
return WriteResult.fail("Source does not exist: " + fromPath);
566616
}
617+
if (isSubtreeExcluded(to)) {
618+
return WriteResult.fail("Destination is not visible here: " + toPath);
619+
}
567620
try {
568621
if (to.getParent() != null) {
569622
Files.createDirectories(to.getParent());
@@ -582,7 +635,8 @@ public boolean exists(RuntimeContext runtimeContext, String path) {
582635
return false;
583636
}
584637
try {
585-
return Files.exists(resolvePath(runtimeContext, path));
638+
Path resolved = resolvePath(runtimeContext, path);
639+
return !isSubtreeExcluded(resolved) && Files.exists(resolved);
586640
} catch (SecurityException e) {
587641
return false;
588642
}
@@ -600,12 +654,42 @@ public io.agentscope.core.session.AtomicSessionStorage sessionStorage(RuntimeCon
600654
resolvePath(rc, ".").resolve(".agentscope-runtime"));
601655
}
602656

657+
/**
658+
* Hides a subtree from this filesystem entirely: enumeration skips it, and reads, writes
659+
* and every other content operation treat it as absent. This keeps a shared lower layer
660+
* from exposing files that belong to a namespace it does not own.
661+
*
662+
* @param root absolute root to hide; relative paths and {@code null} are ignored
663+
* @return this filesystem, for chaining
664+
*/
665+
public LocalFilesystem excludeSubtree(Path root) {
666+
if (root != null && root.isAbsolute()) {
667+
excludedSubtrees.add(root.normalize());
668+
}
669+
return this;
670+
}
671+
672+
private boolean isSubtreeExcluded(Path path) {
673+
if (excludedSubtrees.isEmpty() || path == null) {
674+
return false;
675+
}
676+
Path absolute = path.toAbsolutePath().normalize();
677+
for (Path excluded : excludedSubtrees) {
678+
if (absolute.startsWith(excluded)) {
679+
return true;
680+
}
681+
}
682+
return false;
683+
}
684+
603685
protected Path resolvePath(RuntimeContext rc, String key) {
604686
if (key != null
605687
&& java.util.Arrays.stream(key.replace('\\', '/').split("/"))
606688
.anyMatch(".agentscope-runtime"::equalsIgnoreCase))
607689
throw new SecurityException("Session journal is reserved for the runtime");
608-
String effectiveKey = applyNamespacePrefix(rc, key);
690+
// A blank key means "the root of the caller's view", not the shared workspace root:
691+
// resolving it to cwd would let a relative list/search escape the namespace.
692+
String effectiveKey = applyNamespacePrefix(rc, (key == null || key.isBlank()) ? "." : key);
609693
if (effectiveKey == null || effectiveKey.isBlank()) {
610694
return cwd;
611695
}
@@ -780,6 +864,22 @@ private String stripNamespacePrefix(RuntimeContext rc, Path absolutePath) {
780864

781865
// ==================== Grep implementations ====================
782866

867+
/**
868+
* Path of {@code excluded} relative to {@code base} for a ripgrep {@code --glob} argument,
869+
* or {@code null} when it is not a descendant (nothing to exclude).
870+
*/
871+
private static String relativeForGlob(Path base, Path excluded) {
872+
try {
873+
Path relative = base.toAbsolutePath().normalize().relativize(excluded);
874+
String value = relative.toString().replace('\\', '/');
875+
// Compare the first name rather than the string: a legitimate directory literally
876+
// named "..cache" is a descendant, not a traversal escape.
877+
return value.isEmpty() || relative.getName(0).toString().equals("..") ? null : value;
878+
} catch (IllegalArgumentException e) {
879+
return null;
880+
}
881+
}
882+
783883
private List<GrepMatch> ripgrepSearch(
784884
RuntimeContext rc, String pattern, Path basePath, String includeGlob) {
785885
List<String> cmd = new ArrayList<>();
@@ -790,6 +890,13 @@ private List<GrepMatch> ripgrepSearch(
790890
cmd.add("--glob");
791891
cmd.add(includeGlob);
792892
}
893+
for (Path excluded : excludedSubtrees) {
894+
String relative = relativeForGlob(basePath, excluded);
895+
if (relative != null) {
896+
cmd.add("--glob");
897+
cmd.add("!" + relative + "/**");
898+
}
899+
}
793900
cmd.add("--");
794901
cmd.add(pattern);
795902
cmd.add(basePath.toString());
@@ -889,44 +996,55 @@ private List<GrepMatch> javaSearch(
889996
if (includeGlob != null && !includeGlob.isBlank()) {
890997
globMatcher = FileSystems.getDefault().getPathMatcher("glob:" + includeGlob);
891998
}
999+
PathMatcher finalGlobMatcher = globMatcher;
8921000

8931001
List<GrepMatch> matches = new ArrayList<>();
8941002
Path root = Files.isDirectory(basePath) ? basePath : basePath.getParent();
8951003

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-
}
1004+
try {
1005+
Files.walkFileTree(
1006+
root,
1007+
new SimpleFileVisitor<>() {
1008+
@Override
1009+
public FileVisitResult preVisitDirectory(
1010+
Path dir, BasicFileAttributes attrs) {
1011+
return isSubtreeExcluded(dir)
1012+
? FileVisitResult.SKIP_SUBTREE
1013+
: FileVisitResult.CONTINUE;
1014+
}
1015+
1016+
@Override
1017+
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
1018+
if (isSubtreeExcluded(file)) {
1019+
return FileVisitResult.CONTINUE;
1020+
}
1021+
if (finalGlobMatcher != null
1022+
&& !finalGlobMatcher.matches(file.getFileName())) {
1023+
return FileVisitResult.CONTINUE;
1024+
}
1025+
if (attrs.size() > maxFileSizeBytes) {
1026+
return FileVisitResult.CONTINUE;
1027+
}
1028+
try {
1029+
List<String> lines =
1030+
Files.readAllLines(file, StandardCharsets.UTF_8);
1031+
for (int i = 0; i < lines.size(); i++) {
1032+
if (compiledPattern.matcher(lines.get(i)).find()) {
1033+
String filePath = resolveEntryPath(rc, file);
1034+
matches.add(new GrepMatch(filePath, i + 1, lines.get(i)));
9251035
}
926-
} catch (IOException e) {
927-
// Skip binary/unreadable files
9281036
}
929-
});
1037+
} catch (IOException e) {
1038+
// Skip binary/unreadable files
1039+
}
1040+
return FileVisitResult.CONTINUE;
1041+
}
1042+
1043+
@Override
1044+
public FileVisitResult visitFileFailed(Path file, IOException exc) {
1045+
return FileVisitResult.CONTINUE;
1046+
}
1047+
});
9301048
} catch (IOException e) {
9311049
log.warn("Java search failed: {}", e.getMessage());
9321050
}

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/spec/LocalFilesystemSpec.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,21 @@ public AbstractFilesystem toFilesystem(Path workspace, NamespaceFactory localNam
338338
inheritEnv,
339339
effectiveNamespaceFactory,
340340
effectiveProject);
341+
// When the workspace is a proper subtree of the project — the default layout — the
342+
// namespaced lower layer must not see it: enumerating the project walks every
343+
// namespace under the workspace, and a relative path spelling the physical layout
344+
// reaches a sibling caller's files. A workspace equal to or outside the project has
345+
// no nesting to hide, a shared workspace (no namespace factory) belongs to every
346+
// caller equally, and the projectFs route carries the namespace factory itself, so
347+
// physical-layout spellings resolve under the caller's own prefix either way.
341348
LocalFilesystem lower = new LocalFilesystem(effectiveProject, true, 10, null);
349+
Path workspaceRoot = workspace.toAbsolutePath().normalize();
350+
Path projectRoot = effectiveProject.toAbsolutePath().normalize();
351+
boolean workspaceNestedInProject =
352+
!workspaceRoot.equals(projectRoot) && workspaceRoot.startsWith(projectRoot);
353+
if (effectiveNamespaceFactory != null && workspaceNestedInProject) {
354+
lower = lower.excludeSubtree(workspaceRoot);
355+
}
342356
if (projectWritable) {
343357
LocalFilesystem projectFs =
344358
new LocalFilesystem(

0 commit comments

Comments
 (0)