Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7801 fix(daemon): follow directory junctions when authorizing repo checkout workdirs (#8958)
Bohan Jiange31da86c9079
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d398907b2f..1c959524e3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -738,6 +738,22 @@ jobs:# the command interpreter can run.run: go test ./internal/daemon -v -run '^(TestCanonicalExecutablePath|TestTrimExtendedLengthPrefix|TestResolveAgentExecutablePathKeeps|TestResolveAgentExecutablePath_ProfileOverride|TestResolveAgentEntry(FollowsRetargetedInstallerJunction|CanonicalizesRediscoveredJunction|ForLaunchKeepsCmdShimLaunchable|ForLaunchRejectsUnverifiedInitialJunctionTarget|ForLaunchRejectsRediscoveredJunctionWhenFinalPathResolutionFails|DoesNotSharePreRetargetSingleflightResult|ForLaunchFailsWhenJunctionKeepsRetargeting)|TestHandleTaskReportsWindowsCodexProcessStartFailure)' -count=1 -timeout=5m+ - name: Test Windows task workdirs under a junctioned workspaces root+ working-directory: server+ # #8946: a workspaces root moved to another drive and left behind as a+ # directory junction puts a junction in the middle of every task path.+ # filepath.EvalSymlinks fails with ENOTDIR there, so every repo checkout+ # was refused as "not owned by the active task" and every follow-up+ # silently lost its workdir. The strict resolver also has to walk+ # extended-length (`\\?\`) spellings instead of comparing them as+ # strings, and refuse volume-GUID paths it cannot walk. Only a real+ # Windows filesystem has junctions; the ubuntu backend job covers the+ # symlink shapes.+ # -v so a skip or a pattern that stops matching is visible.+ run: |+ go test ./internal/util -v -run '^(TestResolveSymlinksFollowsJunctions|TestResolveSymlinksExtendedLengthPaths)$' -count=1 -timeout=5m+ go test ./internal/daemon -v -run '^(TestAuthorizeRepoCheckoutWorkDirThroughJunctionedRoot|TestAuthorizeRepoCheckoutWorkDirFollowsJunctionsInsideTheWorkdir|TestAuthorizeRepoCheckoutWorkDirExtendedLengthSpelling|TestShouldReusePriorWorkdirThroughJunctionedRoot)$' -count=1 -timeout=5m+- name: Build Windows CLI helper entrypointworking-directory: serverrun: go build ./cmd/multicadiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 94e32fca3f..85745dab5c 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -31,6 +31,7 @@ import ("github.com/multica-ai/multica/server/internal/daemon/execenv""github.com/multica-ai/multica/server/internal/daemon/repocache""github.com/multica-ai/multica/server/internal/selfexec"+ "github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/pkg/agent""github.com/multica-ai/multica/server/pkg/protocol""github.com/multica-ai/multica/server/pkg/redact"@@ -6806,11 +6807,15 @@ func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignmenreturn "", false}- root, err := filepath.EvalSymlinks(workspacesRoot)+ // util.ResolveSymlinks, not filepath.EvalSymlinks: on Windows the latter+ // cannot pass through a directory junction, so a junctioned workspaces+ // root silently declined every reuse and each follow-up lost its session+ // (#8946).+ root, err := util.ResolveSymlinks(workspacesRoot)if err != nil {return "", false}- workdir, err := filepath.EvalSymlinks(task.PriorWorkDir)+ workdir, err := util.ResolveSymlinks(task.PriorWorkDir)if err != nil {return "", false}@@ -7256,11 +7261,12 @@ func (d *Daemon) lockReusablePriorEnvRoot(ctx context.Context, task Task, localAreturn nil, "", nil, false, nil}priorRoot := filepath.Dir(workDir)- // workDir came back through EvalSymlinks, so the root it is measured- // against has to be resolved the same way — otherwise a symlinked- // workspaces root (macOS /tmp -> /private/tmp, a home on a linked volume)- // makes the two look unrelated and every reuse is refused.- canonicalWorkspacesRoot, err := filepath.EvalSymlinks(d.cfg.WorkspacesRoot)+ // workDir came back through util.ResolveSymlinks, so the root it is+ // measured against has to be resolved the same way — otherwise a symlinked+ // workspaces root (macOS /tmp -> /private/tmp, a home on a linked volume,+ // a Windows junction to another drive) makes the two look unrelated and+ // every reuse is refused.+ canonicalWorkspacesRoot, err := util.ResolveSymlinks(d.cfg.WorkspacesRoot)if err != nil {return nil, "", nil, false, nil}diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex 2faed3264a..8e3ebed674 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -14,6 +14,7 @@ import ("time""github.com/multica-ai/multica/server/internal/daemon/repocache"+ "github.com/multica-ai/multica/server/internal/util")// HealthResponse is returned by the daemon's local health endpoint.@@ -274,26 +275,32 @@ func (d *Daemon) writeRepoCheckoutAuthError(w http.ResponseWriter, result repoChhttp.Error(w, message, http.StatusUnauthorized)}+// authorizeRepoCheckoutWorkDir proves the requested checkout directory lies+// inside the active task's workdir and returns its resolved form. Both sides+// are resolved the way the kernel opens them — util.ResolveSymlinks, not+// filepath.EvalSymlinks, which on Windows cannot pass through a directory+// junction: a workspaces root moved to another drive and left behind as a+// junction made every checkout fail here (#8946). Any path that cannot be+// resolved is refused; the error says which side and why, because the caller+// surfaces it instead of a bare "not owned".func authorizeRepoCheckoutWorkDir(activeRoot, requested string) (string, error) {root, err := filepath.Abs(activeRoot)- if err != nil {- return "", err+ if err == nil {+ root, err = util.ResolveSymlinks(root)}- root, err = filepath.EvalSymlinks(root)if err != nil {- return "", err+ return "", fmt.Errorf("resolve active task workdir: %w", err)}workdir, err := filepath.Abs(requested)- if err != nil {- return "", err+ if err == nil {+ workdir, err = util.ResolveSymlinks(workdir)}- workdir, err = filepath.EvalSymlinks(workdir)if err != nil {- return "", err+ return "", fmt.Errorf("resolve requested workdir: %w", err)}rel, err := filepath.Rel(root, workdir)if err != nil || !filepath.IsLocal(rel) {- return "", errors.New("workdir is outside the active task workdir")+ return "", fmt.Errorf("%s is outside the active task workdir %s", workdir, root)}return workdir, nil}@@ -457,7 +464,17 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {}authorizedWorkDir, authErr := authorizeRepoCheckoutWorkDir(activeTask.WorkDir, req.WorkDir)if authErr != nil {- http.Error(w, "repo checkout workdir is not owned by the active task", http.StatusForbidden)+ // The reason goes to both the agent and daemon.log: a refusal that+ // says only "not owned" sent #8946 looking at ownership when the+ // real failure was resolving a junctioned path. Both paths come from+ // the requesting task — its own workdir and the path it sent — so+ // the message tells it nothing it could not read for itself.+ d.logger.Warn("repo checkout rejected",+ "reason", "workdir_not_owned",+ "task_id", activeTask.TaskID,+ "error", authErr,+ )+ http.Error(w, "repo checkout workdir is not owned by the active task: "+authErr.Error(), http.StatusForbidden)return}// Identity is derived from the token-bound active task. AgentName and thediff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.goindex 616569170b..88268717e1 100644--- a/server/internal/daemon/health_test.go+++ b/server/internal/daemon/health_test.go@@ -523,6 +523,8 @@ func TestRepoCheckoutRejectsAnotherTaskWorkdir(t *testing.T) {cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}workDir := t.TempDir()d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)+ var logs bytes.Buffer+ d.logger = captureLogger(&logs)otherWorkDir := t.TempDir()rec := httptest.NewRecorder()@@ -535,6 +537,44 @@ func TestRepoCheckoutRejectsAnotherTaskWorkdir(t *testing.T) {if got := cache.lastCreateParams(); got != (repocache.WorktreeParams{}) {t.Fatalf("cross-task workdir checkout reached repo cache: %+v", got)}+ // #8946: a bare "not owned" with nothing in daemon.log hid that the real+ // failure was resolving a junctioned path. The agent and the log both get+ // the reason now.+ if !strings.Contains(rec.Body.String(), "outside the active task workdir") {+ t.Fatalf("rejection body should say why the workdir was refused: %s", rec.Body.String())+ }+ for _, want := range []string{"repo checkout rejected", "workdir_not_owned", "level=WARN"} {+ if !strings.Contains(logs.String(), want) {+ t.Fatalf("rejection log missing %q, got: %s", want, logs.String())+ }+ }+}++// A workdir that cannot be resolved at all is refused, and the refusal names+// the resolution failure instead of reading as an ownership question.+func TestRepoCheckoutRejectsUnresolvableWorkdirWithTheReason(t *testing.T) {+ t.Parallel()++ const workspaceID = "ws-checkout"+ const repoURL = "https://github.com/org/repo.git"+ cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}+ workDir := t.TempDir()+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, workDir, cache)+ missing := filepath.Join(workDir, "does-not-exist")++ rec := httptest.NewRecorder()+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"` + missing + `","task_id":"task-1"}`)+ d.repoCheckoutHandler().ServeHTTP(rec, authorizedRepoCheckoutRequest(body))++ if rec.Code != http.StatusForbidden {+ t.Fatalf("expected 403, got %d: %s", rec.Code, rec.Body.String())+ }+ if got := cache.lastCreateParams(); got != (repocache.WorktreeParams{}) {+ t.Fatalf("unresolvable workdir checkout reached repo cache: %+v", got)+ }+ if !strings.Contains(rec.Body.String(), "resolve requested workdir") {+ t.Fatalf("rejection body should name the resolution failure: %s", rec.Body.String())+ }}func TestRepoCheckoutExplicitRefOverridesProjectDefault(t *testing.T) {diff --git a/server/internal/daemon/workdir_junction_windows_test.go b/server/internal/daemon/workdir_junction_windows_test.gonew file mode 100644index 0000000000..9dfe0605d8--- /dev/null+++ b/server/internal/daemon/workdir_junction_windows_test.go@@ -0,0 +1,173 @@+//go:build windows++package daemon++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++// #8946: moving the workspaces root to another drive and leaving a directory+// junction in its place is the no-elevation way to free space on C:, and it+// put a junction in the middle of every task path. filepath.EvalSymlinks fails+// with ENOTDIR on such a path under this module's winsymlink semantics, so the+// repo checkout authorization refused every checkout ("not owned by the active+// task") and the workdir-reuse check silently declined every follow-up. These+// run on a real Windows filesystem in the windows-execenv CI job; createJunction+// lives in gc_junction_windows_test.go.++// junctionedWorkspacesRoot returns a workspaces root that is a junction to a+// real directory, plus that directory, the way the #8946 reporter set it up.+func junctionedWorkspacesRoot(t *testing.T) (root, target string) {+ t.Helper()+ target = t.TempDir()+ root = filepath.Join(t.TempDir(), "multica_workspaces")+ createJunction(t, target, root)+ return root, target+}++func TestAuthorizeRepoCheckoutWorkDirThroughJunctionedRoot(t *testing.T) {+ root, target := junctionedWorkspacesRoot(t)+ rel := filepath.Join("ws-1", "0123456789ab", "workdir")+ viaTarget := filepath.Join(target, rel)+ if err := os.MkdirAll(filepath.Join(viaTarget, "sub"), 0o755); err != nil {+ t.Fatalf("mkdir workdir: %v", err)+ }+ viaRoot := filepath.Join(root, rel)+ wantWorkdir, err := filepath.EvalSymlinks(viaTarget)+ if err != nil {+ t.Fatalf("resolve target workdir: %v", err)+ }++ cases := []struct {+ name string+ active string+ requested string+ want string+ }{+ {name: "both spelled through the junction", active: viaRoot, requested: viaRoot, want: wantWorkdir},+ {name: "request spelled through the junction target", active: viaRoot, requested: viaTarget, want: wantWorkdir},+ {name: "active workdir spelled through the junction target", active: viaTarget, requested: viaRoot, want: wantWorkdir},+ {name: "subdirectory through the junction", active: viaRoot, requested: filepath.Join(viaRoot, "sub"), want: filepath.Join(wantWorkdir, "sub")},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got, err := authorizeRepoCheckoutWorkDir(tc.active, tc.requested)+ if err != nil {+ t.Fatalf("authorizeRepoCheckoutWorkDir(%q, %q): %v", tc.active, tc.requested, err)+ }+ if !strings.EqualFold(got, tc.want) {+ t.Fatalf("authorized workdir = %q, want %q", got, tc.want)+ }+ })+ }+}++// A junction at the END of the requested path is the opposite failure: the old+// check resolved it to its own name, so a junction inside the workdir pointing+// elsewhere passed as inside. One pointing back inside the workdir (the pnpm+// shape) must keep passing.+func TestAuthorizeRepoCheckoutWorkDirFollowsJunctionsInsideTheWorkdir(t *testing.T) {+ workDir := t.TempDir()+ outside := t.TempDir()+ if err := os.MkdirAll(filepath.Join(outside, "sub"), 0o755); err != nil {+ t.Fatalf("mkdir outside: %v", err)+ }+ escape := filepath.Join(workDir, "escape")+ createJunction(t, outside, escape)+ for _, requested := range []string{escape, filepath.Join(escape, "sub")} {+ got, err := authorizeRepoCheckoutWorkDir(workDir, requested)+ if err == nil {+ t.Fatalf("authorizeRepoCheckoutWorkDir accepted %q (resolved %q), a junction out of the workdir", requested, got)+ }+ if !strings.Contains(err.Error(), "outside the active task workdir") {+ t.Fatalf("rejection of %q should say it is outside the workdir, got: %v", requested, err)+ }+ }++ inside := filepath.Join(workDir, "real")+ if err := os.MkdirAll(inside, 0o755); err != nil {+ t.Fatalf("mkdir inside: %v", err)+ }+ link := filepath.Join(workDir, "link")+ createJunction(t, inside, link)+ if _, err := authorizeRepoCheckoutWorkDir(workDir, link); err != nil {+ t.Fatalf("a junction that stays inside the workdir was refused: %v", err)+ }+}++// With the active workdir spelled in extended-length form (a workspaces_root+// configured as `\\?\C:\...`), both sides of the check are device-namespace+// strings. A resolver that hands those back unwalked compares them lexically,+// and a junction inside the workdir then escapes it; the old EvalSymlinks+// check refused that path, and so must this one.+func TestAuthorizeRepoCheckoutWorkDirExtendedLengthSpelling(t *testing.T) {+ workDir := t.TempDir()+ if err := os.MkdirAll(filepath.Join(workDir, "sub"), 0o755); err != nil {+ t.Fatalf("mkdir workdir: %v", err)+ }+ outside := t.TempDir()+ if err := os.MkdirAll(filepath.Join(outside, "sub"), 0o755); err != nil {+ t.Fatalf("mkdir outside: %v", err)+ }+ createJunction(t, outside, filepath.Join(workDir, "escape"))+ active := `\\?\` + workDir+ want, err := filepath.EvalSymlinks(filepath.Join(workDir, "sub"))+ if err != nil {+ t.Fatalf("resolve workdir: %v", err)+ }++ got, err := authorizeRepoCheckoutWorkDir(active, `\\?\`+filepath.Join(workDir, "sub"))+ if err != nil {+ t.Fatalf("an extended-length subdirectory of the workdir was refused: %v", err)+ }+ if !strings.EqualFold(got, want) {+ t.Fatalf("authorized workdir = %q, want %q", got, want)+ }++ for _, requested := range []string{+ `\\?\` + filepath.Join(workDir, "escape", "sub"),+ `\\?\` + filepath.Join(workDir, "missing"),+ } {+ if got, err := authorizeRepoCheckoutWorkDir(active, requested); err == nil {+ t.Fatalf("authorizeRepoCheckoutWorkDir(%q, %q) accepted %q", active, requested, got)+ }+ }+}++func TestShouldReusePriorWorkdirThroughJunctionedRoot(t *testing.T) {+ root, target := junctionedWorkspacesRoot(t)+ workDir := filepath.Join(root, "ws-leader", "12345678", "workdir")+ writeLeaderTaskMarker(t, workDir, "agent-leader", "issue-leader")+ writeLeaderManagedEnvProvenance(t, workDir, "ws-leader", "issue-leader", "agent-leader")+ want, err := filepath.EvalSymlinks(filepath.Join(target, "ws-leader", "12345678", "workdir"))+ if err != nil {+ t.Fatalf("resolve target workdir: %v", err)+ }++ task := leaderReuseTestTask("task-junction-root")+ task.PriorWorkDir = workDir+ got, ok := shouldReusePriorWorkdir(task, nil, root)+ if !ok {+ t.Fatalf("a fully provenanced workdir under a junctioned workspaces root was refused for reuse")+ }+ if !strings.EqualFold(got, want) {+ t.Fatalf("reused workdir = %q, want %q", got, want)+ }++ // The whole reuse path, lock included, has to hold up too: it opens the+ // root by its configured (junction) name and locks the resolved env root.+ d := &Daemon{logger: discardLogger()}+ d.cfg.WorkspacesRoot = root+ claim, canonical, _, ok, err := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")+ if err != nil || !ok {+ t.Fatalf("lockReusablePriorEnvRoot under a junctioned root: ok=%v err=%v", ok, err)+ }+ defer claim.Release()+ if !strings.EqualFold(canonical, want) {+ t.Fatalf("locked workdir = %q, want %q", canonical, want)+ }+}diff --git a/server/internal/util/path.go b/server/internal/util/path.goindex f9ae109046..0419b75c7e 100644--- a/server/internal/util/path.go+++ b/server/internal/util/path.go@@ -7,17 +7,51 @@ import ("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.+// ErrUnresolvablePath is returned by ResolveSymlinks and+// 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")+// ResolveSymlinks is the strict counterpart of ResolveSymlinksBestEffort: it+// resolves p the way the operating system opens it — every symlink followed,+// and on Windows every directory junction too — and fails when any component+// is missing, unreadable, or cannot be resolved. It is for callers that must+// prove a path lies inside a root before trusting it, where+// filepath.EvalSymlinks cannot serve on Windows: under the winsymlink+// semantics this module's go directive selects, it fails with ENOTDIR on any+// path that passes THROUGH a junction (a workspaces root moved to another+// drive and left behind as a junction, #8946), and returns a junction at the+// END of a path unfollowed, so a link out of the root reads as inside it.+//+// Every location it returns was walked component by component. On Windows a+// path that can only be spelled in the device namespace — a volume GUID, a raw+// device, or a link into one — is ErrUnresolvablePath rather than a lexical+// answer, because two such strings can compare as nested while a junction+// between them leads somewhere else entirely (see evalPathStrict).+//+// On Unix this is filepath.EvalSymlinks. On Windows a path with no junction in+// it keeps the spelling filepath.EvalSymlinks gives it (see canonicalSpelling),+// so switching a caller over changes nothing for such paths.+//+// This mirrors Python's Path.resolve(strict=True).+func ResolveSymlinks(p string) (string, error) {+ abs := absNoClean(p)+ if !filepath.IsAbs(abs) {+ return "", fmt.Errorf("%w: %q has no observable base to resolve against", ErrUnresolvablePath, p)+ }+ resolved, err := evalPathStrict(abs)+ if err != nil {+ return "", err+ }+ return canonicalSpelling(resolved), nil+}+// 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 reparsediff --git a/server/internal/util/path_other.go b/server/internal/util/path_other.goindex d5f560b0cb..04612ce5a3 100644--- a/server/internal/util/path_other.go+++ b/server/internal/util/path_other.go@@ -35,3 +35,15 @@ func absNoClean(p string) string {func evalPath(p string) (string, error) {return filepath.EvalSymlinks(p)}++// evalPathStrict is evalPath on Unix: filepath.EvalSymlinks already walks every+// component and has no namespace it returns unwalked.+func evalPathStrict(p string) (string, error) {+ return evalPath(p)+}++// canonicalSpelling is the identity on Unix: evalPath is filepath.EvalSymlinks+// here, so its result is already the spelling callers compare against.+func canonicalSpelling(resolved string) string {+ return resolved+}diff --git a/server/internal/util/path_test.go b/server/internal/util/path_test.goindex af4d34bfb0..4528665ec8 100644--- a/server/internal/util/path_test.go+++ b/server/internal/util/path_test.go@@ -200,3 +200,41 @@ func TestResolveSymlinksBestEffort(t *testing.T) {}})}++// TestResolveSymlinks pins the strict contract containment checks rely on:+// every link in the path is followed, and a path that does not fully exist is+// an error rather than a lexical guess — the opposite of+// ResolveSymlinksBestEffort, which re-attaches a missing tail. The Windows+// junction shapes it exists for are covered in path_windows_test.go.+func TestResolveSymlinks(t *testing.T) {+ root := t.TempDir()+ physical := filepath.Join(root, "physical")+ if err := os.MkdirAll(filepath.Join(physical, "existing"), 0o755); err != nil {+ t.Fatalf("mkdir: %v", err)+ }+ logical := filepath.Join(root, "logical")+ if err := os.Symlink(physical, logical); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }+ realExisting, err := filepath.EvalSymlinks(filepath.Join(physical, "existing"))+ if err != nil {+ t.Fatalf("resolve physical: %v", err)+ }++ got, err := ResolveSymlinks(filepath.Join(logical, "existing"))+ if err != nil {+ t.Fatalf("ResolveSymlinks through a symlinked ancestor: %v", err)+ }+ if got != realExisting {+ t.Fatalf("ResolveSymlinks = %q, want %q", got, realExisting)+ }++ for _, missing := range []string{+ filepath.Join(logical, "existing", "missing"),+ filepath.Join(logical, "missing", "deeper"),+ } {+ if got, err := ResolveSymlinks(missing); err == nil {+ t.Fatalf("ResolveSymlinks(%q) = %q; a missing component must be an error", missing, got)+ }+ }+}diff --git a/server/internal/util/path_windows.go b/server/internal/util/path_windows.goindex c07a469264..b6d292575e 100644--- a/server/internal/util/path_windows.go+++ b/server/internal/util/path_windows.go@@ -256,6 +256,57 @@ func win32FromExtendedLength(p string) (string, bool) {return p, false}+// evalPathStrict is evalPath for ResolveSymlinks, which must never return a+// location the walk did not verify. evalPath has two exits that skip the walk:+// an input already in the device namespace is returned as given, and a link+// whose target has no Win32 spelling (`\\?\Volume{GUID}\...`) has the rest of+// the path joined onto that target lexically. For the best-effort resolver+// both are the fail-closed answer — a device path never compares as inside a+// drive-letter root. A strict caller can be comparing two device paths with+// each other, though: with the active workdir spelled `\\?\C:\task\workdir`,+// the lexical `\\?\C:\task\workdir\escape\sub` reads as inside it even when+// escape is a junction to another drive. So an extended-length path that has+// a plain Win32 spelling is walked in that spelling, and anything that is, or+// resolves into, the device namespace is ErrUnresolvablePath.+func evalPathStrict(p string) (string, error) {+ if conv, ok := win32FromExtendedLength(p); ok {+ p = conv+ }+ if isDeviceNamespacePath(p) {+ return "", fmt.Errorf("%w: %q has no Win32 spelling to walk", ErrUnresolvablePath, p)+ }+ resolved, err := evalPath(p)+ if err != nil {+ return "", err+ }+ if isDeviceNamespacePath(resolved) {+ return "", fmt.Errorf("%w: %q leads into %q, which has no Win32 spelling to walk", ErrUnresolvablePath, p, resolved)+ }+ return resolved, nil+}++func isDeviceNamespacePath(p string) bool {+ return strings.HasPrefix(p, `\\?\`) || strings.HasPrefix(p, `\\.\`)+}++// canonicalSpelling gives a path evalPathStrict already resolved the spelling+// filepath.EvalSymlinks would: the on-disk case and long name of every+// component. evalPath keeps each component as written, so without this a+// caller switching from EvalSymlinks would see the same directory spelled+// differently — an 8.3 short name on one side of a containment check and the+// long name on the other would read as two directories. It changes spelling+// only, never location: its input was walked and verified component by+// component, with every link already followed, which is the one shape+// EvalSymlinks handles correctly here. When EvalSymlinks still cannot answer —+// a reparse point the walk proved redirects nowhere, which EvalSymlinks will+// not pass through — the walk's own spelling of that verified path stands.+func canonicalSpelling(resolved string) string {+ if norm, err := filepath.EvalSymlinks(resolved); err == nil {+ return norm+ }+ return resolved+}+// 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, thediff --git a/server/internal/util/path_windows_test.go b/server/internal/util/path_windows_test.goindex e1651f6ced..682053d917 100644--- a/server/internal/util/path_windows_test.go+++ b/server/internal/util/path_windows_test.go@@ -3,9 +3,14 @@package utilimport (+ "errors"+ "os"+ "os/exec""path/filepath""strings""testing"++ "golang.org/x/sys/windows")// TestClassifyTarget pins the link-target grammar on pure string inputs, with@@ -149,3 +154,164 @@ func TestClassifyTarget(t *testing.T) {}})}++// mklinkJunction makes dst a directory junction to src. mklink /J is used+// directly so the junction shape is exercised even on a runner where symlinks+// are permitted.+func mklinkJunction(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)+ }+}++// TestResolveSymlinksFollowsJunctions is #8946. A workspaces root moved to+// another drive and left behind as a junction put a junction in the MIDDLE of+// every task path, where filepath.EvalSymlinks fails with ENOTDIR, and the+// checkout authorization built on it refused every checkout. A junction at the+// END of a path is the opposite failure: EvalSymlinks returns it unfollowed,+// so a junction pointing out of a workdir reads as inside it. ResolveSymlinks+// must follow both, fail on a missing component, and — for the spelling+// callers compare — land on exactly what EvalSymlinks gives the junction-free+// path (t.TempDir sits under an 8.3 short name on hosted runners, which is+// what the spelling check exercises).+func TestResolveSymlinksFollowsJunctions(t *testing.T) {+ target := t.TempDir()+ workdirViaTarget := filepath.Join(target, "ws", "task", "workdir")+ if err := os.MkdirAll(workdirViaTarget, 0o755); err != nil {+ t.Fatalf("mkdir: %v", err)+ }+ root := filepath.Join(t.TempDir(), "multica_workspaces")+ mklinkJunction(t, target, root)+ outside := t.TempDir()+ escape := filepath.Join(workdirViaTarget, "escape")+ mklinkJunction(t, outside, escape)++ workdirViaRoot := filepath.Join(root, "ws", "task", "workdir")+ if _, err := filepath.EvalSymlinks(workdirViaRoot); err == nil {+ t.Logf("filepath.EvalSymlinks now passes through a junction on this platform; ResolveSymlinks is still required for a junction at the end of a path")+ }++ wantWorkdir, err := filepath.EvalSymlinks(workdirViaTarget)+ if err != nil {+ t.Fatalf("resolve target workdir: %v", err)+ }+ wantOutside, err := filepath.EvalSymlinks(outside)+ if err != nil {+ t.Fatalf("resolve outside: %v", err)+ }++ cases := []struct {+ name string+ in string+ want string+ }{+ {name: "junction in the middle of the path", in: workdirViaRoot, want: wantWorkdir},+ {name: "junction-free path keeps EvalSymlinks' spelling", in: workdirViaTarget, want: wantWorkdir},+ {name: "junction at the end of the path is followed", in: escape, want: wantOutside},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got, err := ResolveSymlinks(tc.in)+ if err != nil {+ t.Fatalf("ResolveSymlinks(%q): %v", tc.in, err)+ }+ if got != tc.want {+ t.Fatalf("ResolveSymlinks(%q) = %q, want %q", tc.in, got, tc.want)+ }+ })+ }++ missing := filepath.Join(root, "ws", "missing")+ if got, err := ResolveSymlinks(missing); err == nil {+ t.Fatalf("ResolveSymlinks(%q) = %q; a missing component behind a junction must be an error", missing, got)+ }+}++// volumeGUIDRoot returns the `\\?\Volume{GUID}\` name of the volume dir lives+// on — a spelling of it with no Win32 form to walk.+func volumeGUIDRoot(t *testing.T, dir string) string {+ t.Helper()+ mountPoint, err := windows.UTF16PtrFromString(filepath.VolumeName(dir) + `\`)+ if err != nil {+ t.Fatalf("encode mount point: %v", err)+ }+ buf := make([]uint16, 64)+ if err := windows.GetVolumeNameForVolumeMountPoint(mountPoint, &buf[0], uint32(len(buf))); err != nil {+ t.Fatalf("volume GUID of %s: %v", dir, err)+ }+ return windows.UTF16ToString(buf)+}++// TestResolveSymlinksExtendedLengthPaths pins the device-namespace exits of+// the walk. evalPath hands back a `\\?\` input unwalked and joins a path+// lexically onto a volume-GUID link target; for the best-effort resolver that+// fails closed against a drive-letter root, but a strict caller can compare two+// device spellings with each other, where `\\?\C:\w\escape\sub` reads as inside+// `\\?\C:\w` although escape leads to another directory. ResolveSymlinks must+// walk every extended-length path that has a Win32 spelling and refuse the ones+// that do not.+func TestResolveSymlinksExtendedLengthPaths(t *testing.T) {+ workdir := t.TempDir()+ if err := os.MkdirAll(filepath.Join(workdir, "sub"), 0o755); err != nil {+ t.Fatalf("mkdir workdir: %v", err)+ }+ outside := t.TempDir()+ if err := os.MkdirAll(filepath.Join(outside, "sub"), 0o755); err != nil {+ t.Fatalf("mkdir outside: %v", err)+ }+ mklinkJunction(t, outside, filepath.Join(workdir, "escape"))++ wantWorkdir, err := filepath.EvalSymlinks(workdir)+ if err != nil {+ t.Fatalf("resolve workdir: %v", err)+ }+ wantOutsideSub, err := filepath.EvalSymlinks(filepath.Join(outside, "sub"))+ if err != nil {+ t.Fatalf("resolve outside: %v", err)+ }++ resolves := []struct {+ name string+ in string+ want string+ }{+ {name: "extended-length directory", in: `\\?\` + workdir, want: wantWorkdir},+ {name: "extended-length path through a junction is walked, not joined", in: `\\?\` + filepath.Join(workdir, "escape", "sub"), want: wantOutsideSub},+ }+ for _, tc := range resolves {+ t.Run(tc.name, func(t *testing.T) {+ got, err := ResolveSymlinks(tc.in)+ if err != nil {+ t.Fatalf("ResolveSymlinks(%q): %v", tc.in, err)+ }+ if got != tc.want {+ t.Fatalf("ResolveSymlinks(%q) = %q, want %q", tc.in, got, tc.want)+ }+ })+ }++ missing := `\\?\` + filepath.Join(workdir, "missing")+ if got, err := ResolveSymlinks(missing); err == nil {+ t.Fatalf("ResolveSymlinks(%q) = %q; a missing extended-length path must be an error", missing, got)+ }++ guidOutside := volumeGUIDRoot(t, outside) + strings.TrimPrefix(outside, filepath.VolumeName(outside)+`\`)+ guidLink := filepath.Join(workdir, "vg")+ mklinkJunction(t, guidOutside, guidLink)+ refused := []struct {+ name string+ in string+ }{+ {name: "volume-GUID path", in: guidOutside},+ {name: "junction into a volume GUID", in: filepath.Join(guidLink, "sub")},+ }+ for _, tc := range refused {+ t.Run(tc.name, func(t *testing.T) {+ got, err := ResolveSymlinks(tc.in)+ if !errors.Is(err, ErrUnresolvablePath) {+ t.Fatalf("ResolveSymlinks(%q) = %q, %v; want ErrUnresolvablePath", tc.in, got, err)+ }+ })+ }+}