Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(cli): compare workdir paths in one namespace (MUL-4252, MUL-7193) (#8028)

VvV2b62b2b52ef2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 3597b7347b..fd70e99629 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -636,6 +636,45 @@ jobs:
# silently as "ok".
run: go test ./internal/daemon/execenv -v -run '^TestWindowsOpenclawShim' -count=1 -timeout=5m
+ - name: Test Windows workdir containment guard in the CLI
+ if: ${{ needs.changes.outputs.backend == 'true' }}
+ working-directory: server
+ # The CLI's --content-file / --attachment guard decides whether a path is
+ # inside the task workdir by canonicalizing both sides. Two of the things
+ # that decision rests on are Windows-only and covered nowhere else: a
+ # candidate on another volume, where filepath.Rel returns an error rather
+ # than a "..", so the guard has to read that as "outside" instead of
+ # surfacing `Rel: can't make Z:\... relative to C:\...` as a resolve
+ # failure; and a directory junction — the containment-relevant link shape
+ # that needs no elevation, so the one real hosts have — which resolves to
+ # itself rather than to its target under this module's go directive. The
+ # junction test pins that gap deliberately, records the observations it
+ # rests on, and fails with instructions if the platform ever starts
+ # resolving them.
+ # cmd/multica has no Windows job otherwise, so these windows-tagged
+ # tests run nowhere else. It matters twice over on a non-admin host,
+ # where the package's cross-platform cases skip for want of the symlink
+ # privilege; the ubuntu backend job covers those shapes instead.
+ # -v so a silent skip (or a -run pattern that stops matching) is visible
+ # in the log instead of passing as "ok".
+ run: go test ./cmd/multica -v -run '^TestFileWithinWorkingDirWindows' -count=1 -timeout=5m
+
+ - name: Test Windows link-target classification in internal/util
+ if: ${{ needs.changes.outputs.backend == 'true' }}
+ working-directory: server
+ # The guard's Windows correctness rests on internal/util's link-target
+ # grammar (classifyTarget), whose branch ordering is load-bearing:
+ # VolumeName is non-empty for drive-absolute paths too, so asking it
+ # before IsAbs misreads a junction's absolute target as drive-relative
+ # and resolves it against the working directory — exactly how a
+ # junction escape read as inside the workdir for one CI run. The
+ # fixture-free table pins every branch without needing a filesystem,
+ # but windows-tagged util tests run nowhere else. Scoped to the table
+ # by name; the package's symlinked-workdir cases belong to the ubuntu
+ # backend job, which runs the whole package.
+ # -v so a silent skip or a pattern that stops matching is visible.
+ run: go test ./internal/util -v -run '^TestClassifyTarget' -count=1 -timeout=5m
+
- name: Test Windows isolated repo checkout is committable
working-directory: server
# #6449: on Windows the daemon now hands Codex tasks a checkout whose
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index e469af20e5..3fc152baec 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -110,6 +110,13 @@ func ensureFileFlagWithinWorkdir(cmd *cobra.Command, fileFlag, flagName, filePat
return fmt.Errorf("resolve --%s path %q: %w", fileFlag, filePath, err)
}
if !within {
+ if !pathExists(filePath) {
+ return fmt.Errorf(
+ "--%s path %q does not exist; it also resolves outside the current working directory, "+
+ "so --allow-external-file would not make this read succeed. Write the file inside the "+
+ "task workdir (e.g. ./%s.md) and pass that path.",
+ fileFlag, filePath, flagName)
+ }
return fmt.Errorf(
"--%s path %q resolves outside the current working directory; "+
"write agent temp files inside the run workdir (e.g. ./%s.md) rather than machine-shared "+
@@ -120,42 +127,89 @@ func ensureFileFlagWithinWorkdir(cmd *cobra.Command, fileFlag, flagName, filePat
return nil
}
+// pathExists reports whether filePath names something on disk. It exists to
+// separate the two facts the containment guard used to merge: a rejected path
+// that is ALSO missing has no stale file behind it for anyone to read by
+// mistake, so leading with --allow-external-file sends the caller to disable
+// the guard and hit an unrelated not-found error on the retry. Any stat error
+// other than "not exists" (a permission wall, a broken mount) is treated as
+// "exists" so the guard keeps its own wording and stays fail-closed.
+func pathExists(filePath string) bool {
+ _, err := os.Stat(filePath)
+ return !errors.Is(err, os.ErrNotExist)
+}
+
// fileWithinWorkingDir reports whether filePath resolves to a location inside
-// the process working directory. Both sides are symlink-resolved so aliased
-// roots (e.g. macOS /tmp -> /private/tmp) and symlinks planted inside the
-// workdir fail closed. A path that does not exist yet is judged on its cleaned
-// absolute form so the caller's os.ReadFile still surfaces the real not-found
-// error afterwards.
+// the process working directory. Both sides are canonicalized the same way, so
+// aliased roots (e.g. macOS /tmp -> /private/tmp), symlinks planted inside the
+// workdir, and directory junctions pointing out of it all fail closed. A path
+// that does not exist yet is resolved as far as it exists, so the caller's
+// os.ReadFile still surfaces the real not-found error afterwards.
+//
+// Windows relative paths are handed over for what they are, not for what they
+// look like: `\tmp\desc.md` resolves against the workdir's volume ROOT and
+// `C:tmp\desc.md` against the current directory on C:, so prefixing the
+// workdir onto either would judge a shadow file while os.ReadFile opens the
+// real one. util.ResolveSymlinksBestEffort preserves those kinds, for link
+// targets as well as for the input itself.
func fileWithinWorkingDir(filePath string) (bool, error) {
cwd, err := os.Getwd()
if err != nil {
return false, err
}
- base := cwd
- if resolved, err := filepath.EvalSymlinks(cwd); err == nil {
- base = resolved
- }
- abs := filePath
- if !filepath.IsAbs(abs) {
- abs = filepath.Join(cwd, abs)
+ base, err := util.ResolveSymlinksBestEffort(cwd)
+ if err != nil {
+ // The workdir's own resolution cannot be determined (an unobservable
+ // drive, a reparse point no query can name). Comparing a candidate
+ // against a root that cannot be named judges whatever string the
+ // resolver would have guessed, so fail closed.
+ return false, nil
}
- if resolved, err := filepath.EvalSymlinks(abs); err == nil {
- abs = resolved
- } else {
- // The file may not exist yet (the caller's os.ReadFile surfaces that).
- // Resolve symlinks on the parent directory instead so the comparison
- // base and the candidate share the same canonical prefix — otherwise a
- // workdir under a symlinked root (e.g. macOS temp dirs) would falsely
- // read as "outside". A missing parent falls back to a plain clean.
- if resolvedParent, perr := filepath.EvalSymlinks(filepath.Dir(abs)); perr == nil {
- abs = filepath.Join(resolvedParent, filepath.Base(abs))
- } else {
- abs = filepath.Clean(abs)
- }
+ // Canonicalize the candidate exactly the way the base was, and hand it over
+ // as typed: util.ResolveSymlinksBestEffort makes it absolute itself, because
+ // pre-joining it here would clean the string first and collapse a ".."
+ // across a symlink — judging a different path than the one os.ReadFile then
+ // opens.
+ //
+ // os.Getwd() returns the LOGICAL working directory when $PWD names it (a
+ // shell's `cd`, and the PWD the daemon exports to agent processes, both
+ // carry unresolved symlinks), so the two sides only agree once both are
+ // resolved. Resolving best-effort is what makes that possible for a
+ // candidate that does not exist yet — a typo, or an artifact a build step
+ // never produced — and every cheaper approximation gets one direction wrong:
+ //
+ // - Leaving the candidate unresolved (filepath.Clean) reads a path inside
+ // the workdir as outside it, which reports a missing file as a
+ // guardrail violation and points the caller at --allow-external-file
+ // instead of at the real error.
+ // - Resolving only one level up (filepath.Dir) still breaks once an
+ // intermediate directory is missing, and worse: with an already-
+ // canonical cwd it reads `escape/sub/x.md` — under a symlink pointing
+ // out of the workdir — as INSIDE it, because the unresolvable tail
+ // falls back to a lexical clean that never sees the symlink.
+ abs, err := util.ResolveSymlinksBestEffort(filePath)
+ if err != nil {
+ // ErrUnresolvablePath: the kernel may open this path somewhere this
+ // process cannot name — a reparse point that redirects but survives
+ // both os.Readlink and a handle query, or a drive-relative path on a
+ // drive whose current directory is unobservable. The string the input
+ // spells is not evidence of where the kernel would read, so fail
+ // closed; the caller's own os.ReadFile would surface a plain error
+ // for the same path.
+ return false, nil
}
rel, err := filepath.Rel(base, abs)
if err != nil {
- return false, err
+ // Two absolute paths that filepath.Rel cannot relate are on different
+ // volumes, which is as far outside the workdir as a path can get. Only
+ // Windows produces this: with a workdir on C:, `--content-file
+ // Z:\report.md` used to surface `Rel: can't make Z:\report.md relative
+ // to C:\...` as an internal resolve failure instead of the guardrail's
+ // own explanation — the same misleading-diagnosis shape this guard is
+ // being fixed for. Measured on 10.0.19045 / go1.26.6. There is no Unix
+ // input that reaches this branch, so the windows-tagged test in this
+ // package is the only thing that covers it.
+ return false, nil
}
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return false, nil
@@ -1229,6 +1283,13 @@ func ensureAttachmentWithinWorkdir(cmd *cobra.Command, filePath string) error {
return fmt.Errorf("resolve --attachment path %q: %w", filePath, err)
}
if !within {
+ if !pathExists(filePath) {
+ return fmt.Errorf(
+ "--attachment path %q does not exist; it also resolves outside the current working "+
+ "directory, so --allow-external-file would not make this upload succeed. Generate the "+
+ "file inside the task workdir and attach that path.",
+ filePath)
+ }
return fmt.Errorf(
"--attachment path %q resolves outside the current working directory; "+
"attach files generated inside the run workdir rather than machine-shared "+
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index 25ce83865a..5464645c15 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -302,6 +302,203 @@ func TestResolveTextFlag(t *testing.T) {
})
}
+// withWorkdirShape chdirs into a workdir that is either reached through a
+// symlink (logical) or is its own canonical path, and returns the temp dir the
+// case may use as "outside". BOTH shapes matter, and for opposite reasons:
+//
+// - logical: os.Getwd() prefers $PWD when it names the current directory, and
+// everything that sets $PWD carries the path as typed — a shell's `cd`,
+// testing.T.Chdir, and the PWD the daemon exports to agent processes (see
+// pkg/agent/opencode.go). This is the shape where an unresolved candidate
+// reads as "outside the workdir" though it plainly is not.
+// - canonical: this is the shape where an unresolved candidate reads as
+// "inside the workdir" although a symlink takes it out — so it is the only
+// shape in which the escape-hatch cases below can fail. Run them only under
+// the logical shape and they pass no matter what the code does, because
+// there everything unresolved looks outside.
+func withWorkdirShape(t *testing.T, canonical bool) (outside string) {
+ t.Helper()
+ root := t.TempDir()
+ physical := filepath.Join(root, "physical")
+ if err := os.MkdirAll(physical, 0o755); err != nil {
+ t.Fatalf("mkdir workdir: %v", err)
+ }
+ workdir := filepath.Join(root, "logical")
+ if err := os.Symlink(physical, workdir); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ if canonical {
+ resolved, err := filepath.EvalSymlinks(physical)
+ if err != nil {
+ t.Fatalf("resolve workdir: %v", err)
+ }
+ workdir = resolved
+ }
+ t.Chdir(workdir)
+ return t.TempDir()
+}
+
+// TestFileWithinWorkingDir covers the containment predicate behind the
+// MUL-4252 guardrail directly, because the callers only ever exercise it with
+// files that already exist — and existence is precisely what used to hide the
+// bug. A candidate that does not exist yet cannot go through
+// filepath.EvalSymlinks, and the fallbacks it used to have (one filepath.Dir
+// step, then filepath.Clean) left it unresolved as soon as an intermediate
+// directory was missing too. That failed in both directions:
+//
+// - Against a workdir reached through a symlink, `subdir/report.md` read as
+// outside the workdir. The command then reported a missing file as a
+// guardrail violation and advised --allow-external-file — the one move that
+// makes things worse, since it only disables the guard.
+// - Against a canonical workdir, `escape/sub/report.md` — where `escape` is a
+// symlink out of the workdir — read as INSIDE it, so the guard admitted a
+// path that resolves to a machine-shared directory.
+func TestFileWithinWorkingDir(t *testing.T) {
+ for _, shape := range []struct {
+ name string
+ canonical bool
+ }{
+ {name: "workdir reached through a symlink", canonical: false},
+ {name: "canonical workdir", canonical: true},
+ } {
+ t.Run(shape.name, func(t *testing.T) {
+ outside := withWorkdirShape(t, shape.canonical)
+ sep := string(filepath.Separator)
+ if err := os.WriteFile("exists.txt", []byte("x"), 0o644); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ // `nested` exists so the ".."-comes-back-inside row exercises real
+ // resolution. It deliberately is NOT the directory the
+ // missing-intermediate rows name: give those an existing parent and
+ // a one-level fallback handles them, so the rows stop failing
+ // against unresolved comparisons and stop covering the regression
+ // they exist for.
+ if err := os.Mkdir("nested", 0o755); err != nil {
+ t.Fatalf("mkdir fixture: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(outside, "stale.md"), []byte("x"), 0o644); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ // sibling.md sits NEXT TO the symlink's target, i.e. one ".." away
+ // from it, and it exists — so a guard that collapses ".." lexically
+ // does not merely misjudge, it admits a readable outside file.
+ escapeTarget := filepath.Join(outside, "shared")
+ if err := os.Mkdir(escapeTarget, 0o755); err != nil {
+ t.Fatalf("mkdir fixture: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(outside, "sibling.md"), []byte("another run's file"), 0o644); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(escapeTarget, "stale.md"), []byte("x"), 0o644); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ // A symlink inside the workdir pointing out of it: the escape hatch
+ // the resolution exists to close. It has to stay closed however much
+ // of the path below it is missing.
+ if err := os.Symlink(escapeTarget, "escape"); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+
+ cases := []struct {
+ name string
+ path string
+ want bool
+ }{
+ {name: "existing file in the workdir", path: "exists.txt", want: true},
+ {name: "missing leaf in the workdir", path: "missing.txt", want: true},
+ {name: "missing intermediate directory", path: "subdir/report.md", want: true},
+ {name: "several missing levels", path: "a/b/c/d/report.md", want: true},
+ {name: "the workdir itself", path: ".", want: true},
+ {name: "existing file outside the workdir", path: filepath.Join(outside, "stale.md"), want: false},
+ {name: "missing file outside the workdir", path: filepath.Join(outside, "gone", "stale.md"), want: false},
+ {name: "relative traversal out of the workdir", path: filepath.Join("..", "escaped.md"), want: false},
+ {name: "traversal that comes back inside", path: "nested" + sep + ".." + sep + "exists.txt", want: true},
+ {name: "symlinked escape hatch", path: filepath.Join("escape", "stale.md"), want: false},
+ {name: "symlinked escape hatch with a missing leaf", path: filepath.Join("escape", "missing.md"), want: false},
+ {name: "symlinked escape hatch with a missing directory", path: filepath.Join("escape", "sub", "missing.md"), want: false},
+ {name: "symlinked escape hatch with several missing levels", path: filepath.Join("escape", "a", "b", "missing.md"), want: false},
+ // ".." AFTER a symlink is the case a lexical clean gets wrong:
+ // the string collapses to a path inside the workdir, while the
+ // kernel follows `escape` out of it first and then goes up. The
+ // file it lands on exists, so os.ReadFile really would read
+ // another run's file — no race needed.
+ {name: "dot-dot across the symlinked escape hatch", path: "escape" + sep + ".." + sep + "sibling.md", want: false},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := fileWithinWorkingDir(tc.path)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q): %v", tc.path, err)
+ }
+ if got != tc.want {
+ t.Errorf("fileWithinWorkingDir(%q) = %v, want %v", tc.path, got, tc.want)
+ }
+ })
+ }
+ })
+ }
+}
+
+// TestEnsureFileFlagWithinWorkdirReportsMissingFileAsMissing is the
+// caller-level shape of the same bug: the guardrail must not intercept a path
+// that is inside the workdir, or the error the agent reads points at
+// --allow-external-file instead of at the file it forgot to write.
+func TestEnsureFileFlagWithinWorkdirReportsMissingFileAsMissing(t *testing.T) {
+ withWorkdirShape(t, false)
+ cmd := &cobra.Command{Use: "test"}
+ cmd.Flags().Bool("allow-external-file", false, "")
+
+ if err := ensureFileFlagWithinWorkdir(cmd, "content-file", "content", "subdir/report.md"); err != nil {
+ t.Fatalf("in-workdir path must pass the guardrail, got %v", err)
+ }
+ if err := ensureAttachmentWithinWorkdir(cmd, "out/chart.png"); err != nil {
+ t.Fatalf("in-workdir attachment must pass the guardrail, got %v", err)
+ }
+}
+
+// TestExternalFileErrorLeadsWithMissingFile pins the remaining half of the
+// misleading diagnosis. For a path that is genuinely outside the workdir AND
+// does not exist, the guard used to advise --allow-external-file and nothing
+// else, so the agent's reasonable next move was to disable the guard and retry
+// — earning a second, unrelated "no such file" error. There is no stale file to
+// protect anyone from when the path does not exist, so the missing file is the
+// fact that leads.
+func TestExternalFileErrorLeadsWithMissingFile(t *testing.T) {
+ outside := withWorkdirShape(t, false)
+ cmd := &cobra.Command{Use: "test"}
+ cmd.Flags().Bool("allow-external-file", false, "")
+
+ missing := filepath.Join(outside, "desc.md")
+ err := ensureFileFlagWithinWorkdir(cmd, "description-file", "description", missing)
+ if err == nil {
+ t.Fatal("expected an error for a missing path outside the workdir")
+ }
+ if !strings.Contains(err.Error(), "does not exist") {
+ t.Errorf("error should lead with the missing file, got: %v", err)
+ }
+ if !strings.Contains(err.Error(), "outside the current working directory") {
+ t.Errorf("error should still record that the path is external, got: %v", err)
+ }
+
+ // An existing external file is the case the guard was built for: the
+ // wording must keep pointing at the escape hatch.
+ stale := filepath.Join(outside, "stale.md")
+ if err := os.WriteFile(stale, []byte("x"), 0o644); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ err = ensureAttachmentWithinWorkdir(cmd, stale)
+ if err == nil {
+ t.Fatal("expected an error for an existing path outside the workdir")
+ }
+ if strings.Contains(err.Error(), "does not exist") {
+ t.Errorf("an existing file must not be reported as missing, got: %v", err)
+ }
+ if !strings.Contains(err.Error(), "allow-external-file") {
+ t.Errorf("error should point at --allow-external-file, got: %v", err)
+ }
+}
+
// TestEnsureAttachmentWithinWorkdir covers the MUL-4252 guardrail extended to
// --attachment: a local attachment path outside the task workdir is rejected
// (so an agent can't attach another run's stale /tmp file), with the same
diff --git a/server/cmd/multica/local_path_link_lint_test.go b/server/cmd/multica/local_path_link_lint_test.go
index 5e7854724e..8529b3a2b7 100644
--- a/server/cmd/multica/local_path_link_lint_test.go
+++ b/server/cmd/multica/local_path_link_lint_test.go
@@ -197,6 +197,33 @@ func TestFindLocalPathLinksIgnoresDirectories(t *testing.T) {
}
}
+// The workdir signal has to hold for paths that do not exist on disk — that is
+// the whole reason it exists next to the "names a file that exists here" one.
+// An agent writes paths as its own $PWD spells them, which keeps unresolved
+// symlinks (the daemon exports PWD=<workdir> to agent processes), so the
+// classifier has to canonicalize the candidate even when the file is missing.
+// While it did not, a workdir path with a missing intermediate directory
+// matched neither signal and the link was published — unreadable for everyone
+// but the runtime it names.
+func TestFindLocalPathLinksReportsMissingWorkdirPaths(t *testing.T) {
+ root := t.TempDir()
+ physical := filepath.Join(root, "physical")
+ if err := os.MkdirAll(physical, 0o755); err != nil {
+ t.Fatalf("mkdir workdir: %v", err)
+ }
+ logical := filepath.Join(root, "logical")
+ if err := os.Symlink(physical, logical); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ t.Chdir(logical)
+
+ target := filepath.Join(logical, "artifacts", "report.md")
+ got := targets(findLocalPathLinks("see [the report](" + target + ")"))
+ if len(got) != 1 || got[0] != target {
+ t.Errorf("a missing path inside the workdir should be reported, got %v", got)
+ }
+}
+
func TestGuardLocalPathLinksOnlyFiresInAgentContext(t *testing.T) {
workdir := withWorkdir(t)
shot := filepath.Join(workdir, "shot.png")
diff --git a/server/cmd/multica/workdir_guard_windows_test.go b/server/cmd/multica/workdir_guard_windows_test.go
new file mode 100644
index 0000000000..5e8cc78ec9
--- /dev/null
+++ b/server/cmd/multica/workdir_guard_windows_test.go
@@ -0,0 +1,435 @@
+//go:build windows
+
+package main
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// createJunction makes dst a directory junction to src and reports what the Go
+// runtime makes of it. mklink /J needs no elevation, unlike a directory
+// symlink, which is why the junction shape is the one that actually shows up on
+// Windows hosts — pnpm's node_modules layout is built from them, and this
+// repo's own GC tests use the same fixture.
+//
+// It deliberately does NOT assert on the mode bits. Whether os.Lstat reports a
+// junction with ModeSymlink depends on the GODEBUG winsymlink setting (see the
+// junction test below), so a fixture that fatals on that observation would
+// destroy the coverage of the test it sets up. The bits are logged instead, so
+// a CI run records what the platform did.
+func createJunction(t *testing.T, src, dst string) {
+ t.Helper()
+ if out, err := exec.Command("cmd", "/c", "mklink", "/J", dst, src).CombinedOutput(); err != nil {
+ t.Fatalf("mklink /J %s %s: %s: %v", dst, src, out, err)
+ }
+ fi, err := os.Lstat(dst)
+ if err != nil {
+ t.Fatalf("lstat junction: %v", err)
+ }
+ target, err := os.Stat(dst)
+ if err != nil {
+ t.Fatalf("stat through junction: %v", err)
+ }
+ if !target.IsDir() {
+ t.Fatalf("junction %s does not lead to a directory", dst)
+ }
+ t.Logf("junction %s: Lstat mode=%v symlinkBit=%v irregular=%v",
+ dst, fi.Mode(), fi.Mode()&os.ModeSymlink != 0, fi.Mode()&os.ModeIrregular != 0)
+}
+
+// TestFileWithinWorkingDirWindowsPaths runs the containment guard's core
+// judgments on Windows, where the path grammar the resolution walks is not the
+// one the Linux and macOS jobs exercise: paths carry a volume, both `\` and `/`
+// separate, and several relative kinds do not resolve against the working
+// directory at all. cmd/multica is not part of any Windows job otherwise, so
+// without this file none of that is covered anywhere. It matters twice over on
+// a non-admin host, where the cross-platform cases skip for want of the symlink
+// privilege while a junction needs none.
+func TestFileWithinWorkingDirWindowsPaths(t *testing.T) {
+ workdir := t.TempDir()
+ t.Chdir(workdir)
+ if err := os.WriteFile("exists.txt", []byte("x"), 0o644); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ outside := t.TempDir()
+
+ cases := []struct {
+ name string
+ path string
+ want bool
+ }{
+ {name: "existing file", path: "exists.txt", want: true},
+ {name: "missing leaf", path: "missing.txt", want: true},
+ {name: "missing intermediate directory", path: `subdir\report.md`, want: true},
+ {name: "several missing levels", path: `a\b\c\d\report.md`, want: true},
+ {name: "forward slashes are separators too", path: "a/b/report.md", want: true},
+ {name: "traversal out of the workdir", path: `..\escaped.md`, want: false},
+ {name: "absolute path outside", path: filepath.Join(outside, "stale.md"), want: false},
+ {name: "missing absolute path outside", path: filepath.Join(outside, "gone", "stale.md"), want: false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := fileWithinWorkingDir(tc.path)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q): %v", tc.path, err)
+ }
+ if got != tc.want {
+ t.Errorf("fileWithinWorkingDir(%q) = %v, want %v", tc.path, got, tc.want)
+ }
+ })
+ }
+
+ t.Run("a root-relative path is judged against its volume root, not the workdir", func(t *testing.T) {
+ // `\tmp\desc.md` is not relative to the working directory: the loader
+ // resolves it against the root of the current directory's volume, so
+ // os.ReadFile opens `C:\tmp\desc.md` no matter where the workdir sits.
+ // A guard that prefixes the workdir instead inspects
+ // `C:\task\workdir\tmp\desc.md` — and with that shadow present, an
+ // outside read passes on the shadow. The drive-relative sibling case
+ // (`C:tmp\desc.md`) is the same trap one level up. Both must read as
+ // outside here, and the drive-relative same-drive case below pins the
+ // one shape that legitimately DOES resolve into the workdir.
+ if err := os.MkdirAll(filepath.Join(workdir, "tmp"), 0o755); err != nil {
+ t.Fatalf("mkdir shadow dir: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(workdir, "tmp", "desc.md"), []byte("shadow"), 0o644); err != nil {
+ t.Fatalf("write shadow: %v", err)
+ }
+ for _, candidate := range []string{`\tmp\desc.md`, "/tmp/desc.md"} {
+ within, err := fileWithinWorkingDir(candidate)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q): %v", candidate, err)
+ }
+ if within {
+ t.Errorf("fileWithinWorkingDir(%q) = true; the loader would read the volume root's %q, not the in-workdir shadow", candidate, candidate)
+ }
+ }
+ })
+
+ t.Run("a drive-relative path on the current drive resolves against the workdir", func(t *testing.T) {
+ // `C:tmp\desc.md` resolves against the current directory on C:, which
+ // for the current drive IS the process working directory — so this
+ // genuinely reads workdir\tmp\desc.md, and the guard admits it.
+ if err := os.MkdirAll(filepath.Join(workdir, "tmp"), 0o755); err != nil {
+ t.Fatalf("mkdir fixture dir: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(workdir, "tmp", "desc.md"), []byte("x"), 0o644); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ vol := filepath.VolumeName(workdir)
+ if vol == "" {
+ t.Fatalf("workdir %q carries no volume name", workdir)
+ }
+ candidate := vol + `tmp\desc.md`
+ within, err := fileWithinWorkingDir(candidate)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q): %v", candidate, err)
+ }
+ if !within {
+ t.Errorf("fileWithinWorkingDir(%q) = false; on the current drive this resolves against the workdir itself", candidate)
+ }
+ })
+
+ t.Run("a drive-relative path on another drive reads as outside the workdir", func(t *testing.T) {
+ // The per-drive current directory of a drive the process is not on
+ // cannot be observed, so the resolution hands the path back
+ // uncanonicalized and the guard must fail closed: filepath.Rel
+ // refuses to relate it to the workdir's volume.
+ letter := unusedDriveLetter(t)
+ candidate := letter + `:report.md`
+ within, err := fileWithinWorkingDir(candidate)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q) must report the cross-drive path as outside, not as an error: %v", candidate, err)
+ }
+ if within {
+ t.Errorf("fileWithinWorkingDir(%q) = true, want false", candidate)
+ }
+ })
+
+ t.Run("a path on another volume reads as outside the workdir", func(t *testing.T) {
+ // The Windows-only branch of the guard: filepath.Rel cannot relate two
+ // paths on different volumes, and returns an error rather than a "..".
+ // Reporting that error as a resolve failure — `Rel: can't make Z:\...
+ // relative to C:\...` — tells the caller nothing about the workdir rule
+ // it just broke. No Unix input reaches this branch, so this is the only
+ // coverage it has.
+ //
+ // The resolution comes back purely lexical here, because the walk
+ // starts from the root without needing it to resolve: a drive letter
+ // with no volume behind it never has to answer for itself (measured on
+ // 10.0.19045 / go1.26.6: os.Stat fails at such a root while
+ // filepath.EvalSymlinks reports success).
+ letter := unusedDriveLetter(t)
+ in := letter + `:\multica-does-not-exist-0d1f\a\b`
+ got, err := util.ResolveSymlinksBestEffort(in)
+ if err != nil {
+ t.Fatalf("ResolveSymlinksBestEffort(%q): %v", in, err)
+ }
+ if got != filepath.Clean(in) {
+ t.Errorf("ResolveSymlinksBestEffort(%q) = %q, want %q", in, got, filepath.Clean(in))
+ }
+ within, err := fileWithinWorkingDir(in)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q) must report a cross-volume path as outside, not as an error: %v", in, err)
+ }
+ if within {
+ t.Errorf("fileWithinWorkingDir(%q) = true, want false", in)
+ }
+ })
+
+ t.Run("a root-relative symlink target is judged against the volume root", func(t *testing.T) {
+ // A symlink whose stored target is root-relative (`\Users\...\out`) is
+ // resolved by the kernel from the root of the volume the link sits on,
+ // NOT from the link's directory. A resolver that splices the target
+ // onto the link's parent judges the shadow created below, while
+ // os.ReadFile opens the volume-root path — so the shadow exists on
+ // purpose and this test fails while the resolution is
+ // link-parent-relative.
+ outside := t.TempDir()
+ out := filepath.Join(outside, "out")
+ if err := os.MkdirAll(out, 0o755); err != nil {
+ t.Fatalf("mkdir out: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(out, "stale.md"), []byte("outside"), 0o644); err != nil {
+ t.Fatalf("write out: %v", err)
+ }
+ rel := strings.TrimPrefix(out, filepath.VolumeName(out))
+ if err := os.MkdirAll(filepath.Join(workdir, rel), 0o755); err != nil {
+ t.Fatalf("mkdir shadow: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(workdir, rel, "stale.md"), []byte("shadow"), 0o644); err != nil {
+ t.Fatalf("write shadow: %v", err)
+ }
+ createDirSymlink(t, rel, filepath.Join(workdir, "rrel"))
+ candidate := `rrel\stale.md`
+ if got, err := os.ReadFile(candidate); err != nil {
+ t.Fatalf("read through the link: %v", err)
+ } else if string(got) != "outside" {
+ t.Fatalf("the kernel opened the shadow (%q), not the volume-root target — mklink stored the root-relative target as link-relative on this host, and the test's premise does not hold", got)
+ }
+ within, err := fileWithinWorkingDir(candidate)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q): %v", candidate, err)
+ }
+ if within {
+ t.Errorf("fileWithinWorkingDir(%q) = true; the kernel resolves the root-relative target %q from the volume root, not from the link's directory", candidate, rel)
+ }
+ })
+
+ t.Run("a volume-GUID mount target is judged in its own namespace", func(t *testing.T) {
+ // A junction whose substitute name is `\\?\Volume{GUID}\...` is
+ // absolute in the device namespace: the kernel jumps to that volume
+ // directly, and the file through it is really readable — this is not
+ // an inert shape. There is no Win32 spelling to relate to a
+ // drive-letter workdir, so the guard must reject; a resolver that
+ // strips the `\\?\` prefix turns the absolute mount target into a
+ // relative path it splices under the workdir, where the shadow below
+ // would pass for the real outside read.
+ out := filepath.Join(t.TempDir(), "out")
+ if err := os.MkdirAll(out, 0o755); err != nil {
+ t.Fatalf("mkdir out: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(out, "stale.md"), []byte("outside"), 0o644); err != nil {
+ t.Fatalf("write out: %v", err)
+ }
+ guid := volumeGUIDOfSystemDrive(t)
+ vol := filepath.VolumeName(out)
+ guidTarget := guid + strings.TrimPrefix(out, vol+`\`)
+ createJunction(t, guidTarget, filepath.Join(workdir, "vg"))
+ shadow := filepath.Join(workdir, strings.TrimPrefix(guid, `\\?\`)+strings.TrimPrefix(out, vol+`\`))
+ if err := os.MkdirAll(filepath.Dir(shadow), 0o755); err != nil {
+ t.Fatalf("mkdir shadow: %v", err)
+ }
+ if err := os.WriteFile(shadow, []byte("shadow"), 0o644); err != nil {
+ t.Fatalf("write shadow: %v", err)
+ }
+ candidate := `vg\stale.md`
+ if got, err := os.ReadFile(candidate); err != nil {
+ t.Fatalf("read through the junction: %v", err)
+ } else if string(got) != "outside" {
+ t.Fatalf("the kernel opened the shadow (%q), not the GUID-mounted target; the fixture does not hold on this host", got)
+ }
+ within, err := fileWithinWorkingDir(candidate)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q): %v", candidate, err)
+ }
+ if within {
+ t.Errorf("fileWithinWorkingDir(%q) = true; the junction's target %q is a device-namespace mount the kernel opens outside the workdir", candidate, guidTarget)
+ }
+ })
+}
+
+// unusedDriveLetter returns a drive letter with no volume behind it. os.Stat is
+// the test, not filepath.EvalSymlinks: on go1.26.2 the latter reports success
+// for such a root, which is exactly the observation the cross-volume case
+// records.
+func unusedDriveLetter(t *testing.T) string {
+ t.Helper()
+ for _, letter := range "ZYXWVU" {
+ root := string(letter) + `:\`
+ if _, err := os.Stat(root); err != nil {
+ return string(letter)
+ }
+ }
+ t.Skip("every candidate drive letter is mounted on this host; cannot build a path on an absent volume")
+ return ""
+}
+
+// createDirSymlink makes link a directory symlink to the target string as
+// given. os.Symlink is not used for this: it decides the relative flag from
+// filepath.IsAbs, and a root-relative spelling (`\Users\...`) is not IsAbs,
+// while mklink marks a rooted target absolute — which is the kernel behavior
+// the root-relative case pins. Directory symlinks need the symlink privilege;
+// CI runners have it and non-admin hosts do not, which is why the fixture
+// skips rather than fails there.
+func createDirSymlink(t *testing.T, target, link string) {
+ t.Helper()
+ if out, err := exec.Command("cmd", "/c", "mklink", "/D", link, target).CombinedOutput(); err != nil {
+ if strings.Contains(strings.ToLower(string(out)), "privilege") {
+ t.Skipf("symlink privilege unavailable on this host: %s", out)
+ }
+ t.Fatalf("mklink /D %s -> %s: %s: %v", link, target, out, err)
+ }
+}
+
+// volumeGUIDRe matches the `\\?\Volume{GUID}\` form mountvol prints for a
+// mounted volume.
+var volumeGUIDRe = regexp.MustCompile(`\\\\\?\\Volume\{[0-9a-fA-F-]+\}\\`)
+
+// volumeGUIDOfSystemDrive returns the device-namespace spelling of the system
+// drive's volume, the form a junction can carry as its substitute name and a
+// plain Win32 comparison cannot relate to a drive-letter workdir.
+func volumeGUIDOfSystemDrive(t *testing.T) string {
+ t.Helper()
+ drive := os.Getenv("SystemDrive")
+ if drive == "" {
+ drive = `C:`
+ }
+ out, err := exec.Command("mountvol", drive, "/L").CombinedOutput()
+ if err != nil {
+ t.Fatalf("mountvol %s /L: %s: %v", drive, out, err)
+ }
+ guid := volumeGUIDRe.FindString(string(out))
+ if guid == "" {
+ t.Fatalf("mountvol %s /L printed no volume GUID: %s", drive, out)
+ }
+ return guid
+}
+
+// TestFileWithinWorkingDirWindowsJunctions pins how the guard treats directory
+// junctions — the one containment-relevant link shape Windows has that needs no
+// elevation to create, which is why it is the shape that actually shows up on
+// real hosts (pnpm's node_modules layout is built from them).
+//
+// The resolution behind the guard follows junctions itself, because under the
+// winsymlink semantics this module's go directive selects (Go 1.23+) it is
+// filepath.EvalSymlinks that refuses to descend through them: it resolves the
+// junction to its own name, which used to let `workdir\escape\stale.md` —
+// escape a junction pointing out of the workdir — read as inside. Which
+// semantics apply is not a property of the host but of the GODEBUG setting
+// (internal/godebugs/table.go: `winsymlink, Changed: 23, Old: "0"`), so
+// os.Readlink, which answers on a junction under both, is what the resolution
+// uses (see internal/util/path_windows.go). The same refusal is asserted
+// daemon-side in internal/daemon/config_windows_test.go, which is about
+// filepath.EvalSymlinks and unaffected by this.
+//
+// A junction pointing INSIDE the workdir — the pnpm shape — must keep reading
+// as inside: resolving costs no false rejections there, measured alongside the
+// escape facts on the same host.
+func TestFileWithinWorkingDirWindowsJunctions(t *testing.T) {
+ workdir := t.TempDir()
+ t.Chdir(workdir)
+ outside := t.TempDir()
+ if err := os.WriteFile(filepath.Join(outside, "stale.md"), []byte("x"), 0o644); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ createJunction(t, outside, filepath.Join(workdir, "escape"))
+
+ t.Run("a junction out of the workdir is rejected", func(t *testing.T) {
+ candidate := `escape\stale.md`
+ within, err := fileWithinWorkingDir(candidate)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q): %v", candidate, err)
+ }
+ if within {
+ t.Errorf("fileWithinWorkingDir(%q) = true; the junction resolves to %q, outside the workdir", candidate, outside)
+ }
+ })
+
+ t.Run("a junction into the workdir is still admitted", func(t *testing.T) {
+ // The false-rejection direction: a junction whose target stays inside
+ // the workdir resolves to a path that is still inside it, and the
+ // guard must not start rejecting the pnpm shape.
+ if err := os.MkdirAll(filepath.Join(workdir, "inner"), 0o755); err != nil {
+ t.Fatalf("mkdir inner: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(workdir, "inner", "file.md"), []byte("x"), 0o644); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ createJunction(t, filepath.Join(workdir, "inner"), filepath.Join(workdir, "link"))
+ candidate := `link\file.md`
+ within, err := fileWithinWorkingDir(candidate)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q): %v", candidate, err)
+ }
+ if !within {
+ t.Errorf("fileWithinWorkingDir(%q) = false; the junction's target is inside the workdir", candidate)
+ }
+ })
+
+ t.Run("a junction chain out of the workdir is rejected", func(t *testing.T) {
+ // One Readlink step only reaches the next link, so the resolution
+ // splices targets back into the walk; a chain must not fall off the
+ // end of that into a lexical judgment.
+ mid := filepath.Join(workdir, "mid")
+ if err := os.Mkdir(mid, 0o755); err != nil {
+ t.Fatalf("mkdir mid: %v", err)
+ }
+ createJunction(t, outside, filepath.Join(mid, "hop"))
+ createJunction(t, mid, filepath.Join(workdir, "chain"))
+ candidate := `chain\hop\stale.md`
+ within, err := fileWithinWorkingDir(candidate)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q): %v", candidate, err)
+ }
+ if within {
+ t.Errorf("fileWithinWorkingDir(%q) = true; the junction chain resolves to %q, outside the workdir", candidate, outside)
+ }
+ })
+
+ t.Run("a junction whose target is gone resolves lexically and stays inert", func(t *testing.T) {
+ // os.Readlink still answers when the target no longer exists, but the
+ // walk cannot resolve THROUGH the dead target, so the junction becomes
+ // the first unresolvable component and the tail is re-attached
+ // lexically — reading as inside. That is the documented inert shape,
+ // not a hole: the kernel stops at the junction too, so nothing after
+ // it can be opened and os.ReadFile surfaces the not-found error. The
+ // containment risk only exists while the target resolves, which the
+ // first case rejects. If this ever starts reading as outside — the
+ // resolution learned to carry the target's missing tail through a
+ // dead junction — the guard's answer gets stricter, which is safe.
+ dangling := t.TempDir()
+ createJunction(t, dangling, filepath.Join(workdir, "dangle"))
+ if err := os.Remove(dangling); err != nil {
+ t.Fatalf("remove junction target: %v", err)
+ }
+ candidate := `dangle\stale.md`
+ within, err := fileWithinWorkingDir(candidate)
+ if err != nil {
+ t.Fatalf("fileWithinWorkingDir(%q): %v", candidate, err)
+ }
+ if !within {
+ t.Errorf("fileWithinWorkingDir(%q) = false; a dead junction resolves nothing and the kernel cannot open the path either way", candidate)
+ }
+ if _, err := os.ReadFile(candidate); !strings.Contains(err.Error(), "cannot find") {
+ t.Logf("os.ReadFile(%q) = %v (the guard's admission is inert only while that is a not-found)", candidate, err)
+ }
+ })
+}
diff --git a/server/internal/daemon/execenv/hermes_home.go b/server/internal/daemon/execenv/hermes_home.go
index b34a0add77..3002a93a18 100644
--- a/server/internal/daemon/execenv/hermes_home.go
+++ b/server/internal/daemon/execenv/hermes_home.go
@@ -10,6 +10,8 @@ import (
"strings"
"gopkg.in/yaml.v3"
+
+ "github.com/multica-ai/multica/server/internal/util"
)
// Hermes discovers skills from exactly two places (verified against the bundled
@@ -278,30 +280,17 @@ func hermesRootFromHomeFor(base, native string) string {
// resolvePathBestEffort resolves symlinks like Python's Path.resolve(strict=False):
// it follows every symlink in the existing prefix of p and appends the remaining
// non-existent tail unchanged, rather than failing (as filepath.EvalSymlinks does)
-// when p doesn't fully exist. The result is absolute.
+// when p doesn't fully exist. The result is absolute. When the kernel's own
+// resolution cannot be determined (util.ErrUnresolvablePath — an unknown
+// redirecting reparse point, an unobservable drive), the input is returned
+// unchanged: the containment comparison downstream then fails to relate it and
+// treats it as under nothing, which is the conservative answer.
func resolvePathBestEffort(p string) string {
- if p == "" {
+ resolved, err := util.ResolveSymlinksBestEffort(p)
+ if err != nil {
return p
}
- if abs, err := filepath.Abs(p); err == nil {
- p = abs
- }
- if resolved, err := filepath.EvalSymlinks(p); err == nil {
- return resolved
- }
- dir := p
- var tail []string
- for {
- parent := filepath.Dir(dir)
- if parent == dir {
- return p // reached the root without an existing ancestor
- }
- tail = append([]string{filepath.Base(dir)}, tail...)
- dir = parent
- if resolved, err := filepath.EvalSymlinks(dir); err == nil {
- return filepath.Join(append([]string{resolved}, tail...)...)
- }
- }
+ return resolved
}
// isPathUnder reports whether child is parent or nested under it.
diff --git a/server/internal/util/path.go b/server/internal/util/path.go
new file mode 100644
index 0000000000..f9ae109046
--- /dev/null
+++ b/server/internal/util/path.go
@@ -0,0 +1,178 @@
+package util
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+)
+
+// ErrUnresolvablePath is returned by ResolveSymlinksBestEffort when the
+// operating system's own resolution of the path cannot be determined well
+// enough to compare against a root: an unknown redirecting reparse point whose
+// final location even a handle query cannot name, or a Windows drive-relative
+// path on a drive whose current directory this process cannot observe. A
+// caller that uses the result as a containment check must treat the error as
+// OUTSIDE — "cannot say where this opens" is not "opens where the string
+// says". A caller that only wants a canonical form should fall back to the
+// input unchanged.
+var ErrUnresolvablePath = errors.New("path resolution cannot be determined")
+
+// ResolveSymlinksBestEffort canonicalizes p the way the operating system would
+// open it, as far as the filesystem allows: it follows every symlink in the
+// existing prefix of p — on Windows directory junctions and other reparse
+// points too — applying ".." segments to the FOLLOWED path, not to the string,
+// and re-attaches the part that does not exist yet. The result is absolute,
+// and the error is ErrUnresolvablePath when even a fail-closed answer is
+// impossible to compute (see above).
+//
+// Windows path kinds are preserved rather than flattened onto the working
+// directory. A root-relative path (`\tmp\desc.md`) resolves against the root
+// of the working directory's volume, and a drive-relative path (`C:tmp\desc`)
+// against the working directory only when that drive IS the working
+// directory's drive, because those are the files os.ReadFile actually opens.
+// Prefixing either with the working directory instead would let a same-named
+// file inside the workdir shadow the outside file the kernel reads, and a
+// containment check would pass on the shadow. The same grammar applies to
+// link targets, which the kernel resolves by the same rules rather than
+// relative to the link.
+//
+// Two properties matter to callers that compare the result against a root.
+//
+// First, a path that does not fully exist still has to land in the same
+// namespace as the root. filepath.EvalSymlinks fails outright when any
+// component is missing, and falling back to filepath.Clean does not follow
+// symlinks at all, so the two sides of the comparison end up in different
+// namespaces (on macOS every /tmp and /var path is a symlink into /private) and
+// a path inside the root reads as outside it. Falling back one level via
+// filepath.Dir only narrows that to "the leaf is missing" — and inverts the
+// error for a deeper miss, since an unresolvable tail then reads as inside a
+// root it actually escapes. The walk below resolves the longest prefix the
+// filesystem can speak for and re-attaches the rest, so every component that
+// exists is still resolved and a symlink or junction planted inside the root
+// cannot smuggle a candidate past a containment check. Any resolution error
+// stops the descent, not just "not exists" — permission-denied on an ancestor
+// is equally a "cannot canonicalize here".
+//
+// Second, ".." is resolved physically wherever the filesystem can say so. The
+// path is never lexically cleaned before resolution, because filepath.Clean
+// (and filepath.Abs, and filepath.Join across the whole input) collapse
+// "escape/.." into nothing and thereby cross a symlink boundary invisibly: a
+// caller comparing the cleaned string sees a path inside its root while the
+// kernel would open one outside it. The walk applies each ".." to the resolved
+// prefix, which is the order the kernel uses. Only the tail after the first
+// unresolvable component is joined lexically, where a mismatch is inert — a
+// path with an unresolvable prefix cannot be opened at all.
+//
+// This mirrors Python's Path.resolve(strict=False).
+func ResolveSymlinksBestEffort(p string) (string, error) {
+ if p == "" {
+ return "", nil
+ }
+ abs := absNoClean(p)
+ if !filepath.IsAbs(abs) {
+ // absNoClean could not say what the path is relative to: a working
+ // directory that cannot be observed, or a Windows drive-relative path
+ // on a drive this process has no observable directory for. There is no
+ // honest string to return — the kernel may well open something this
+ // process cannot name — so this is the error, not a guess.
+ return "", fmt.Errorf("%w: %q has no observable base to resolve against", ErrUnresolvablePath, p)
+ }
+ // Resolve the path as given first. This is the only step that can see a
+ // ".." the way the kernel does, so it must not be preceded by cleaning.
+ resolved, err := evalPath(abs)
+ if errors.Is(err, ErrUnresolvablePath) {
+ return "", err
+ }
+ if err == nil {
+ return resolved, nil
+ }
+ // Walk the UNCLEANED path one component at a time: resolve what exists,
+ // apply ".." to what has been resolved, and re-attach everything after the
+ // first component the filesystem cannot speak for. The root is the walk's
+ // starting point without being resolved — "/" always resolves on Unix, and
+ // on Windows (measured on go1.26.2, 10.0.19045) a drive letter with no
+ // volume behind it is equally served by treating it as resolved: the tail
+ // is unreachable for the kernel either way, so the lexical form is the
+ // best answer available.
+ root, segs := splitNoClean(abs)
+ walked := root
+ for i, seg := range segs {
+ switch seg {
+ case "..":
+ walked = dropLastSegment(walked)
+ continue
+ case ".", "":
+ continue
+ }
+ next, err := evalPath(joinSegment(walked, seg))
+ if errors.Is(err, ErrUnresolvablePath) {
+ // A component the kernel may resolve somewhere this process cannot
+ // name. Lexically re-attaching the tail would read as inside a
+ // workdir the kernel is not confined to, so this error propagates
+ // instead of degrading into an answer.
+ return "", err
+ }
+ if err != nil {
+ // seg is the first unresolvable component: missing, a permission
+ // wall, too many links, a junction whose target is gone. The
+ // kernel stops there too, so the rest is re-attached lexically —
+ // nothing after an unresolvable component can be opened, which
+ // makes any divergence inside the tail inert.
+ for _, tail := range segs[i:] {
+ walked = joinSegment(walked, tail)
+ }
+ return walked, nil
+ }
+ walked = next
+ }
+ return walked, nil
+}
+
+// splitNoClean splits an absolute path into its root and its components
+// WITHOUT cleaning: "/a/../b" gives root "/" and segments ["a", "..", "b"],
+// `C:\a\b` gives root `C:\` and segments ["a", "b"]. Empty segments from
+// doubled or trailing separators are dropped, which is how the kernel treats
+// them. On a relative path the root comes back empty and the segments are the
+// components as given.
+func splitNoClean(p string) (root string, segs []string) {
+ vol := filepath.VolumeName(p)
+ rest := p[len(vol):]
+ i := 0
+ for i < len(rest) && os.IsPathSeparator(rest[i]) {
+ i++
+ }
+ root = vol + rest[:i]
+ rest = rest[i:]
+ for len(rest) > 0 {
+ j := 0
+ for j < len(rest) && !os.IsPathSeparator(rest[j]) {
+ j++
+ }
+ if j > 0 {
+ segs = append(segs, rest[:j])
+ }
+ for j < len(rest) && os.IsPathSeparator(rest[j]) {
+ j++
+ }
+ rest = rest[j:]
+ }
+ return root, segs
+}
+
+// dropLastSegment returns the parent of a resolved, canonical, symlink-free
+// path, fixpointing at the root: the kernel's ".." from `/`, `C:\`, or a UNC
+// share stays there. The name carries the invariant — the argument must
+// already be free of "." and "..", because filepath.Dir cleans, and cleaning
+// a not-yet-resolved path is the exact trap this file exists to avoid.
+func dropLastSegment(resolved string) string {
+ return filepath.Dir(resolved)
+}
+
+// joinSegment appends one raw component to a resolved prefix. The component
+// may legitimately be ".." or "." — inside the unresolvable tail the lexical
+// meaning is the point — and filepath.Join applies it to the prefix without
+// disturbing the rest, because a resolved prefix has nothing left to clean.
+func joinSegment(resolved, seg string) string {
+ return filepath.Join(resolved, seg)
+}
diff --git a/server/internal/util/path_other.go b/server/internal/util/path_other.go
new file mode 100644
index 0000000000..d5f560b0cb
--- /dev/null
+++ b/server/internal/util/path_other.go
@@ -0,0 +1,37 @@
+//go:build !windows
+
+package util
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// absNoClean makes p absolute by prefixing the working directory verbatim,
+// without filepath.Abs's implied Clean, so any ".." survives for evalPath to
+// apply after following symlinks. Unix has exactly one relative kind —
+// relative to the working directory — so there is nothing to classify; the
+// Windows counterpart preserves several (see path_windows.go).
+func absNoClean(p string) string {
+ if filepath.IsAbs(p) {
+ return p
+ }
+ cwd, err := os.Getwd()
+ if err != nil {
+ return p
+ }
+ sep := string(filepath.Separator)
+ return strings.TrimSuffix(cwd, sep) + sep + p
+}
+
+// evalPath resolves p the way the kernel opens it: every symlink followed and
+// every ".." applied to the followed path. filepath.EvalSymlinks already does
+// exactly that; the Windows counterpart is a component-wise resolver because
+// EvalSymlinks refuses to descend through directory junctions (see
+// path_windows.go). Like EvalSymlinks, it fails when any component is missing
+// or unreadable — the signal ResolveSymlinksBestEffort's walk switches to its
+// lexical tail on.
+func evalPath(p string) (string, error) {
+ return filepath.EvalSymlinks(p)
+}
diff --git a/server/internal/util/path_test.go b/server/internal/util/path_test.go
new file mode 100644
index 0000000000..af4d34bfb0
--- /dev/null
+++ b/server/internal/util/path_test.go
@@ -0,0 +1,202 @@
+package util
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// TestResolveSymlinksBestEffort pins the property every containment check built
+// on this helper depends on: the returned path is in the SAME namespace as
+// filepath.EvalSymlinks would produce for the existing part of the input, no
+// matter how much of the tail is missing. filepath.EvalSymlinks alone fails on
+// any missing component, and the obvious fallbacks (Clean, or a single Dir
+// step) silently return an unresolved path, which makes a path inside a
+// symlinked root compare as outside it.
+func TestResolveSymlinksBestEffort(t *testing.T) {
+ // realRoot is the canonical form of a directory reached through a symlink,
+ // so every expectation below can be written against the resolved namespace.
+ root := t.TempDir()
+ physical := filepath.Join(root, "physical")
+ if err := os.MkdirAll(filepath.Join(physical, "existing"), 0o755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(physical, "existing", "file.txt"), []byte("x"), 0o644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+ logical := filepath.Join(root, "logical")
+ if err := os.Symlink(physical, logical); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ realPhysical, err := filepath.EvalSymlinks(physical)
+ if err != nil {
+ t.Fatalf("resolve physical: %v", err)
+ }
+ if err := os.Symlink(filepath.Join(physical, "nowhere"), filepath.Join(physical, "dangling")); err != nil {
+ t.Fatalf("symlink dangling: %v", err)
+ }
+
+ cases := []struct {
+ name string
+ in string
+ want string
+ }{
+ {
+ name: "existing file behind a symlinked ancestor",
+ in: filepath.Join(logical, "existing", "file.txt"),
+ want: filepath.Join(realPhysical, "existing", "file.txt"),
+ },
+ {
+ name: "missing leaf keeps the resolved parent",
+ in: filepath.Join(logical, "existing", "missing.txt"),
+ want: filepath.Join(realPhysical, "existing", "missing.txt"),
+ },
+ {
+ name: "missing intermediate directory still resolves the ancestor",
+ in: filepath.Join(logical, "subdir", "file.txt"),
+ want: filepath.Join(realPhysical, "subdir", "file.txt"),
+ },
+ {
+ name: "several missing levels still resolve the ancestor",
+ in: filepath.Join(logical, "a", "b", "c", "d", "file.txt"),
+ want: filepath.Join(realPhysical, "a", "b", "c", "d", "file.txt"),
+ },
+ {
+ name: "dangling symlink is not followed but its parent is resolved",
+ in: filepath.Join(logical, "dangling"),
+ want: filepath.Join(realPhysical, "dangling"),
+ },
+ {
+ name: "directory itself",
+ in: logical,
+ want: realPhysical,
+ },
+ {
+ name: "empty input is returned unchanged",
+ in: "",
+ want: "",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := ResolveSymlinksBestEffort(tc.in)
+ if err != nil {
+ t.Fatalf("ResolveSymlinksBestEffort(%q): %v", tc.in, err)
+ }
+ if got != tc.want {
+ t.Errorf("ResolveSymlinksBestEffort(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ })
+ }
+
+ t.Run("relative input is made absolute against the working directory", func(t *testing.T) {
+ t.Chdir(logical)
+ got, err := ResolveSymlinksBestEffort(filepath.Join("subdir", "file.txt"))
+ if err != nil {
+ t.Fatalf("ResolveSymlinksBestEffort(relative): %v", err)
+ }
+ want := filepath.Join(realPhysical, "subdir", "file.txt")
+ if got != want {
+ t.Errorf("ResolveSymlinksBestEffort(relative) = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("dot-dot is applied after following a symlink, not to the string", func(t *testing.T) {
+ // The distinction a containment check lives or dies by: lexically
+ // "link/.." cancels out and the path looks like it never left, while the
+ // kernel follows the link first and then goes up — landing next to the
+ // link's TARGET. Anything that cleans before resolving reports the wrong
+ // namespace here, and does so for a path that exists and can be read.
+ sep := string(filepath.Separator)
+ got, err := ResolveSymlinksBestEffort(filepath.Join(logical, "existing") + sep + ".." + sep + "sibling.md")
+ if err != nil {
+ t.Fatalf("ResolveSymlinksBestEffort(dot-dot): %v", err)
+ }
+ want := filepath.Join(realPhysical, "sibling.md")
+ if got != want {
+ t.Errorf("ResolveSymlinksBestEffort(dot-dot) = %q, want %q", got, want)
+ }
+
+ outsideRoot := t.TempDir()
+ target := filepath.Join(outsideRoot, "shared")
+ if err := os.MkdirAll(target, 0o755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(outsideRoot, "other-run.md"), []byte("x"), 0o644); err != nil {
+ t.Fatalf("write: %v", err)
+ }
+ link := filepath.Join(physical, "escape")
+ if err := os.Symlink(target, link); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ realOutside, err := filepath.EvalSymlinks(outsideRoot)
+ if err != nil {
+ t.Fatalf("resolve outside: %v", err)
+ }
+ got, err = ResolveSymlinksBestEffort(link + sep + ".." + sep + "other-run.md")
+ if err != nil {
+ t.Fatalf("ResolveSymlinksBestEffort(escape/..): %v", err)
+ }
+ want = filepath.Join(realOutside, "other-run.md")
+ if got != want {
+ t.Errorf("ResolveSymlinksBestEffort(escape/..) = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("dot-dot in the walk applies to the followed path even when the tail is missing", func(t *testing.T) {
+ // The phase-one resolution only sees a ".." when the whole path exists.
+ // Once something is missing the walk takes over, and it must apply the
+ // ".." to the RESOLVED prefix there too: cleaning first would collapse
+ // "esc/.." against the string and report the tail under the workdir,
+ // while the kernel — if the missing components were ever created —
+ // would place them next to the link's target.
+ outsideRoot := t.TempDir()
+ target := filepath.Join(outsideRoot, "out")
+ if err := os.MkdirAll(target, 0o755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ link := filepath.Join(physical, "esc")
+ if err := os.Symlink(target, link); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ realOutsideRoot, err := filepath.EvalSymlinks(outsideRoot)
+ if err != nil {
+ t.Fatalf("resolve outside root: %v", err)
+ }
+ // Concatenated, not filepath.Join: Join would clean "esc/.." out of
+ // the input and the walk would never see the link at all — the very
+ // mistake this file exists to catch.
+ sep := string(filepath.Separator)
+ in := filepath.Join(logical, "esc") + sep + ".." + sep + filepath.Join("missingdir", "x.md")
+ want := filepath.Join(realOutsideRoot, "missingdir", "x.md")
+ got, err := ResolveSymlinksBestEffort(in)
+ if err != nil {
+ t.Fatalf("ResolveSymlinksBestEffort(%q): %v", in, err)
+ }
+ if got != want {
+ t.Errorf("ResolveSymlinksBestEffort(%q) = %q, want %q", in, got, want)
+ }
+ })
+
+ t.Run("a fully missing path keeps its lexical tail under the resolved root", func(t *testing.T) {
+ // "/" always resolves, so the walk starts from it and re-attaches
+ // everything below it lexically. The root itself is never resolved by
+ // the walk — it is the starting point — which is what serves the
+ // Windows shape in cmd/multica's cross-volume test: a drive letter
+ // with no volume behind it yields the cleaned lexical form rather
+ // than depending on what EvalSymlinks does at a root.
+ in := filepath.Join(string(filepath.Separator), "multica-does-not-exist-0d1f", "a", "b")
+ want, err := filepath.Abs(in)
+ if err != nil {
+ t.Fatalf("abs: %v", err)
+ }
+ got, err := ResolveSymlinksBestEffort(in)
+ if err != nil {
+ t.Fatalf("ResolveSymlinksBestEffort(%q): %v", in, err)
+ }
+ if got != want {
+ t.Errorf("ResolveSymlinksBestEffort(%q) = %q, want %q", in, got, want)
+ }
+ })
+}
diff --git a/server/internal/util/path_windows.go b/server/internal/util/path_windows.go
new file mode 100644
index 0000000000..c07a469264
--- /dev/null
+++ b/server/internal/util/path_windows.go
@@ -0,0 +1,306 @@
+//go:build windows
+
+package util
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+
+ "golang.org/x/sys/windows"
+)
+
+// absNoClean makes p absolute the way the Windows loader would resolve it,
+// without cleaning, so any ".." survives for evalPath to apply after following
+// links. Windows has several relative kinds and they do NOT all resolve
+// against the working directory, so they are preserved rather than prefixed:
+//
+// - drive-absolute `C:\x` and UNC `\\srv\share\x` are already absolute.
+// - root-relative `\x` (or `/x`) resolves against the ROOT of the current
+// directory's volume — for a UNC current directory, against the share.
+// Prefixing the working directory instead would let `C:\task\workdir\tmp`
+// shadow the `C:\tmp` that os.ReadFile actually opens, and a containment
+// check would pass on the shadow while the kernel reads past it.
+// - drive-relative `C:x` resolves against the current directory ON C:. Only
+// the current drive's directory is observable to this process — it IS
+// os.Getwd() — so for that drive the prefix is dropped and the working
+// directory substituted. Any other drive's per-drive directory cannot be
+// read, so the path is handed back unresolved: ResolveSymlinksBestEffort
+// reports ErrUnresolvablePath for it rather than guessing.
+func absNoClean(p string) string {
+ if filepath.IsAbs(p) {
+ return p
+ }
+ cwd, err := os.Getwd()
+ if err != nil {
+ return p
+ }
+ sep := string(filepath.Separator)
+ if len(p) > 0 && os.IsPathSeparator(p[0]) {
+ return filepath.VolumeName(cwd) + filepath.FromSlash(p)
+ }
+ if vol := filepath.VolumeName(p); vol != "" {
+ if strings.EqualFold(vol, filepath.VolumeName(cwd)) {
+ return strings.TrimSuffix(cwd, sep) + sep + p[len(vol):]
+ }
+ return p
+ }
+ return strings.TrimSuffix(cwd, sep) + sep + p
+}
+
+// maxFollowedLinks bounds how many reparse points one resolution may follow —
+// the budget filepath.EvalSymlinks works with on Unix — so a junction chain
+// that closes on itself turns into an error rather than a hang.
+const maxFollowedLinks = 255
+
+var errTooManyLinks = errors.New("too many levels of symbolic links")
+
+// evalPath resolves p the way the kernel opens it, following both NTFS
+// symlinks and directory junctions. filepath.EvalSymlinks cannot serve here:
+// under the winsymlink semantics this module's go directive selects (Go 1.23+)
+// it refuses to descend through a junction — it resolves the junction to its
+// own name — which is what let an out-of-workdir junction read as inside the
+// workdir. os.Readlink answers on a junction under both winsymlink settings,
+// with a clean absolute target and no \??\ prefix (measured on 10.0.19045 /
+// go1.26.6), and it answers even when the target no longer exists.
+//
+// Components are walked one at a time so the first missing or unreadable
+// component is the error ResolveSymlinksBestEffort's walk switches to its
+// lexical tail on, and ".." is applied to the resolved prefix, which is the
+// order the kernel uses. When a reparse point cannot be resolved at all —
+// including by handle — the error wraps ErrUnresolvablePath, because the
+// kernel may still open the path somewhere this process cannot name.
+func evalPath(p string) (string, error) {
+ if strings.HasPrefix(p, `\\?\`) || strings.HasPrefix(p, `\\.\`) {
+ // The walk never descends into a device namespace: components below a
+ // volume GUID or a raw device are joined lexically (see the verbatim
+ // branch below), and reparse resolution has nothing to add there.
+ // Splitting the string would misread it — `?` is not a component — so
+ // a device-namespace path is its own resolution.
+ return p, nil
+ }
+ root, segs := splitNoClean(p)
+ resolved := root
+ follows := 0
+ for i := 0; i < len(segs); {
+ seg := segs[i]
+ i++
+ switch seg {
+ case "..":
+ resolved = dropLastSegment(resolved)
+ continue
+ case ".", "":
+ continue
+ }
+ cand := joinSegment(resolved, seg)
+ fi, err := os.Lstat(cand)
+ if err != nil {
+ return "", err
+ }
+ if fi.Mode()&(os.ModeSymlink|os.ModeIrregular) == 0 {
+ resolved = cand
+ continue
+ }
+ follows++
+ if follows > maxFollowedLinks {
+ return "", errTooManyLinks
+ }
+ target, rerr := os.Readlink(cand)
+ if rerr != nil {
+ // os.Readlink decodes only the symlink and mount-point tags. A
+ // name-surrogate it cannot decode — a container-isolation link,
+ // say — still redirects: the kernel follows it wherever the filter
+ // points, so a Readlink failure cannot mean "does not redirect".
+ // Resolve the component through a handle instead; the error case
+ // is ErrUnresolvablePath, never "keep the lexical location".
+ final, ferr := finalPathByHandle(cand)
+ if ferr != nil {
+ return "", fmt.Errorf("%w: reparse point %q: %w", ErrUnresolvablePath, cand, ferr)
+ }
+ if sameWin32Path(final, cand) {
+ // The component resolves to itself: it redirects nothing (a
+ // OneDrive placeholder, a deduplicated file). The kernel opens
+ // it where it stands.
+ resolved = cand
+ continue
+ }
+ // It redirects: adopt the path the handle names and keep walking
+ // from there, through the same classification as any link target.
+ target = final
+ }
+ base, tSegs, verbatim, ok := classifyTarget(target, resolved)
+ if !ok {
+ return "", fmt.Errorf("%w: link target %q cannot be placed on an observable volume", ErrUnresolvablePath, target)
+ }
+ if verbatim {
+ // A device-namespace target (`\\?\Volume{GUID}\...`) has no Win32
+ // spelling to walk or to compare; the kernel jumps to it directly.
+ // Join the remaining components lexically and stop: a containment
+ // comparison against a drive-letter root fails closed across the
+ // namespace, which is the honest answer for a mount target.
+ for _, tail := range segs[i:] {
+ base = joinSegment(base, tail)
+ }
+ return base, nil
+ }
+ // Splice the target's components ahead of the remaining ones and keep
+ // walking: a target can itself contain links, and its missing tail is
+ // resolved in the same pass instead of being mistaken for a missing
+ // component of the original path.
+ resolved = base
+ segs = append(tSegs, segs[i:]...)
+ i = 0
+ }
+ return resolved, nil
+}
+
+// classifyTarget makes a link target absolute the way the kernel resolves it
+// and splits it for the walk. The kernel does NOT resolve targets against the
+// link's directory by default — it applies the same grammar as any path:
+//
+// - device-namespace forms are absolute. `\\?\C:\dir` and `\\?\UNC\srv\share`
+// have a plain Win32 spelling to walk and compare; a volume GUID or a raw
+// device does not, and is returned verbatim so the containment comparison
+// fails closed across the namespace instead of splicing a mangled
+// "relative" path under the workdir. The prefix rules match
+// internal/daemon/canonical_path_windows.go (#6883), which needs the same
+// distinction for launchability rather than containment.
+// - `\??\` (the object-manager root a junction's substitute name carries)
+// is stripped and the remainder re-classified; mklink junctions normally
+// arrive from os.Readlink without it (measured).
+// - a root-relative target (`\outside`) resolves against the root of the
+// volume the link sits on — NOT against the link's directory. Judging it
+// from the link's parent is how a same-named shadow under the workdir
+// passes while os.ReadFile opens the volume-root path.
+// - a drive-relative target (`C:x`) resolves against the current directory
+// on C:. Only the current drive's directory is observable (it is
+// os.Getwd()); any other drive reports !ok and fails closed.
+// - a plain-relative target resolves against the directory containing the
+// link — the caller's resolved prefix stays the base.
+func classifyTarget(target, linkDir string) (base string, tSegs []string, verbatim bool, ok bool) {
+ if strings.HasPrefix(target, `\\?\`) || strings.HasPrefix(target, `\\.\`) {
+ if conv, converted := win32FromExtendedLength(target); converted {
+ root, segs := splitNoClean(conv)
+ return root, segs, false, true
+ }
+ return target, nil, true, true
+ }
+ if strings.HasPrefix(target, `\??\`) || strings.HasPrefix(target, `\\??\`) {
+ // Strip the object-manager root and re-classify the remainder. The
+ // two spellings differ in length, so the longer one strips first.
+ t := target
+ switch {
+ case strings.HasPrefix(t, `\\??\`):
+ t = t[len(`\\??\`):]
+ default:
+ t = t[len(`\??\`):]
+ }
+ if rest, found := strings.CutPrefix(t, `UNC\`); found {
+ t = `\\` + rest
+ }
+ return classifyTarget(t, linkDir)
+ }
+ if filepath.IsAbs(target) {
+ // Drive-absolute and UNC. This MUST precede the VolumeName check
+ // below: VolumeName is non-empty for `C:\dir` too, and misreading a
+ // drive-absolute target as drive-relative resolves it against the
+ // working directory instead of the volume root — which is how a
+ // junction escape read as inside the workdir on CI.
+ root, segs := splitNoClean(target)
+ return root, segs, false, true
+ }
+ if len(target) > 0 && os.IsPathSeparator(target[0]) {
+ conv := filepath.VolumeName(linkDir) + filepath.FromSlash(target)
+ root, segs := splitNoClean(conv)
+ return root, segs, false, true
+ }
+ if vol := filepath.VolumeName(target); vol != "" {
+ cwd, err := os.Getwd()
+ if err != nil {
+ return "", nil, false, false
+ }
+ if strings.EqualFold(vol, filepath.VolumeName(cwd)) {
+ sep := string(filepath.Separator)
+ root, segs := splitNoClean(strings.TrimSuffix(cwd, sep) + sep + target[len(vol):])
+ return root, segs, false, true
+ }
+ return "", nil, false, false
+ }
+ _, segs := splitNoClean(target)
+ return linkDir, segs, false, true
+}
+
+// win32FromExtendedLength converts a `\\?\`- or `\\.\`-prefixed path to its
+// plain Win32 form when one exists: a drive-qualified path (`\\?\C:\dir`) or a
+// UNC path (`\\?\UNC\srv\share`). Anything else under the prefix — a volume
+// GUID, a raw device — has no Win32 spelling, and is returned unchanged with
+// false so the caller keeps it verbatim. The conversion ignores path length
+// on purpose: the form is only ever compared here, never handed to an API,
+// and Rel across a mismatched prefix would read a long in-workdir path as
+// outside it.
+func win32FromExtendedLength(p string) (string, bool) {
+ if rest, found := strings.CutPrefix(p, `\\?\UNC\`); found {
+ return `\\` + rest, true
+ }
+ for _, prefix := range []string{`\\?\`, `\\.\`} {
+ if rest, found := strings.CutPrefix(p, prefix); found {
+ if len(rest) >= 3 && rest[1] == ':' && os.IsPathSeparator(rest[2]) {
+ return rest, true
+ }
+ return p, false
+ }
+ }
+ return p, false
+}
+
+// sameWin32Path compares the path a handle names with the path the walk is
+// standing on. GetFinalPathNameByHandle answers in extended-length form; both
+// sides are reduced to plain Win32 before comparing, case-insensitively, the
+// way Win32 matches paths.
+func sameWin32Path(final, cand string) bool {
+ if conv, ok := win32FromExtendedLength(final); ok {
+ final = conv
+ }
+ return strings.EqualFold(final, cand)
+}
+
+// finalPathByHandle names the path the kernel actually opens for p, following
+// every reparse point in it — including the tags os.Readlink cannot decode.
+// It opens p with zero desired access, so it performs no reads and no writes
+// (a cloud placeholder is not hydrated), and passes FILE_FLAG_BACKUP_SEMANTICS
+// because directories cannot be opened without it. An error here means the
+// resolution is genuinely unknowable to this process; it is the caller's
+// fail-closed signal, not a license to judge the lexical form.
+func finalPathByHandle(p string) (string, error) {
+ pUTF16, err := windows.UTF16PtrFromString(p)
+ if err != nil {
+ return "", err
+ }
+ handle, err := windows.CreateFile(
+ pUTF16,
+ 0,
+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,
+ nil,
+ windows.OPEN_EXISTING,
+ windows.FILE_FLAG_BACKUP_SEMANTICS,
+ 0,
+ )
+ if err != nil {
+ return "", err
+ }
+ defer windows.CloseHandle(handle)
+ buffer := make([]uint16, syscall.MAX_PATH)
+ for {
+ length, err := windows.GetFinalPathNameByHandle(handle, &buffer[0], uint32(len(buffer)), 0)
+ if err != nil {
+ return "", err
+ }
+ if length < uint32(len(buffer)) {
+ return windows.UTF16ToString(buffer[:length]), nil
+ }
+ buffer = make([]uint16, length+1)
+ }
+}
diff --git a/server/internal/util/path_windows_test.go b/server/internal/util/path_windows_test.go
new file mode 100644
index 0000000000..e1651f6ced
--- /dev/null
+++ b/server/internal/util/path_windows_test.go
@@ -0,0 +1,151 @@
+//go:build windows
+
+package util
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// TestClassifyTarget pins the link-target grammar on pure string inputs, with
+// no filesystem fixture: every branch is a classification decision the walk
+// relies on, and the ordering between them is load-bearing — VolumeName is
+// non-empty for drive-absolute paths too, so the IsAbs branch must be asked
+// before the drive-relative one or a junction's absolute target resolves
+// against the working directory (which is exactly how a junction escape read
+// as inside the workdir before this table existed).
+func TestClassifyTarget(t *testing.T) {
+ t.Chdir(t.TempDir())
+ cwd, err := filepath.Abs(".")
+ if err != nil {
+ t.Fatalf("abs: %v", err)
+ }
+ vol := filepath.VolumeName(cwd)
+ sep := string(filepath.Separator)
+
+ cases := []struct {
+ name string
+ target string
+ wantBase string
+ wantTail string
+ wantVerbatim bool
+ wantOK bool
+ }{
+ {
+ name: "drive-absolute target is walked from its own volume root",
+ target: vol + `\outside\dir`,
+ wantBase: vol + sep,
+ wantTail: `outside\dir`,
+ wantOK: true,
+ },
+ {
+ name: "UNC target is walked from the share root",
+ target: `\\srv\share\dir`,
+ wantBase: `\\srv\share` + sep,
+ wantTail: `dir`,
+ wantOK: true,
+ },
+ {
+ name: "root-relative target resolves from the link's volume root, not the link's directory",
+ target: `\outside\dir`,
+ wantBase: vol + sep,
+ wantTail: `outside\dir`,
+ wantOK: true,
+ },
+ {
+ name: "drive-relative target on the current drive resolves against the working directory",
+ target: vol + `outside\dir`,
+ wantBase: vol + sep,
+ // The working directory's components are part of the walked tail,
+ // not of the root the walk starts from.
+ wantTail: strings.TrimPrefix(cwd, vol+sep) + sep + `outside` + sep + `dir`,
+ wantOK: true,
+ },
+ {
+ name: "drive-relative target on another drive is unobservable",
+ target: `Q:outside\dir`,
+ wantOK: false,
+ },
+ {
+ name: "plain-relative target keeps the link's directory as base",
+ target: `relative\dir`,
+ wantBase: cwd,
+ wantTail: `relative\dir`,
+ wantOK: true,
+ },
+ {
+ name: "extended-length drive path reduces to its Win32 spelling",
+ target: `\\?\` + vol + `\outside\dir`,
+ wantBase: vol + sep,
+ wantTail: `outside\dir`,
+ wantOK: true,
+ },
+ {
+ name: "extended-length UNC path reduces to its Win32 spelling",
+ target: `\\?\UNC\srv\share\dir`,
+ wantBase: `\\srv\share` + sep,
+ wantTail: `dir`,
+ wantOK: true,
+ },
+ {
+ name: "volume-GUID target has no Win32 spelling and stays verbatim",
+ target: `\\?\Volume{01234567-89ab-cdef-0123-456789abcdef}\dir`,
+ wantBase: `\\?\Volume{01234567-89ab-cdef-0123-456789abcdef}\dir`,
+ wantVerbatim: true,
+ wantOK: true,
+ },
+ {
+ name: "object-manager root is stripped before classification",
+ target: `\??\` + vol + `\outside\dir`,
+ wantBase: vol + sep,
+ wantTail: `outside\dir`,
+ wantOK: true,
+ },
+ {
+ name: "object-manager UNC target becomes a Win32 UNC path",
+ target: `\??\UNC\srv\share\dir`,
+ wantBase: `\\srv\share` + sep,
+ wantTail: `dir`,
+ wantOK: true,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ base, segs, verbatim, ok := classifyTarget(tc.target, cwd)
+ if ok != tc.wantOK {
+ t.Fatalf("classifyTarget(%q) ok = %v, want %v", tc.target, ok, tc.wantOK)
+ }
+ if !tc.wantOK {
+ return
+ }
+ if verbatim != tc.wantVerbatim {
+ t.Fatalf("classifyTarget(%q) verbatim = %v, want %v", tc.target, verbatim, tc.wantVerbatim)
+ }
+ if base != tc.wantBase {
+ t.Errorf("classifyTarget(%q) base = %q, want %q", tc.target, base, tc.wantBase)
+ }
+ if tc.wantVerbatim {
+ return
+ }
+ if got := filepath.Join(segs...); !strings.EqualFold(got, tc.wantTail) {
+ t.Errorf("classifyTarget(%q) segs = %q, want %q", tc.target, got, tc.wantTail)
+ }
+ })
+ }
+
+ t.Run("a drive-absolute target is never misread as drive-relative", func(t *testing.T) {
+ // The regression the table exists to catch, spelled out: VolumeName is
+ // non-empty for `C:\dir` too, so if the IsAbs branch is not asked
+ // first, a junction's absolute target resolves against the working
+ // directory and an escape reads as inside the workdir.
+ base, _, _, ok := classifyTarget(vol+`\outside\dir`, cwd)
+ if !ok {
+ t.Fatal("classifyTarget reported !ok for a drive-absolute target")
+ }
+ if !strings.EqualFold(base, vol+sep) {
+ t.Fatalf("classifyTarget(%q) base = %q, want the volume root %q", vol+`\outside\dir`, base, vol+sep)
+ }
+ })
+}