Skip to content

Commit 1f1e299

Browse files
committed
fix(auto-approval): match symlinked workspace roots
Recognize lexical and verified canonical workspace-root spellings without resolving individual file aliases. Preserve ordered grants, exclusions, literal root names, and lexical-parent rules across POSIX, Windows drives, and UNC shares. Reject ambiguous Windows drive-relative inputs without widening read or write permissions. Centralize platform selection in WorkspaceRootStrategy.forPlatform and cover literal UNC share names with regression tests.
1 parent 1d37994 commit 1f1e299

14 files changed

Lines changed: 997 additions & 72 deletions
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import type { WorkspaceRootStrategy } from "./strategies/WorkspaceRootStrategy"
2+
3+
/** Translate only a verified workspace-root spelling, never a file symlink. */
4+
export class WorkspaceRootCanonicalizer {
5+
private constructor(
6+
private readonly root: string | undefined,
7+
private readonly canonicalRoot: string | undefined,
8+
private readonly strategy: WorkspaceRootStrategy,
9+
) {}
10+
11+
static forStrategy(
12+
cwd: string | undefined,
13+
canonicalCwd: string | undefined,
14+
strategy: WorkspaceRootStrategy,
15+
): WorkspaceRootCanonicalizer {
16+
const root = strategy.normalizeAbsoluteRoot(cwd)
17+
const canonicalRoot = strategy.normalizeAbsoluteRoot(canonicalCwd)
18+
return new WorkspaceRootCanonicalizer(root, canonicalRoot, strategy)
19+
}
20+
21+
canonicalize(value: string): string {
22+
if (this.root === undefined || this.canonicalRoot === undefined) return value
23+
24+
return this.replaceWorkspaceRootPrefix(value, this.root, this.canonicalRoot)
25+
}
26+
27+
/** Keep both verified spellings so globs spanning the root retain their meaning. */
28+
equivalentPaths(value: string): string[] {
29+
if (this.root === undefined || this.canonicalRoot === undefined) return [value]
30+
31+
const canonical = this.canonicalize(value)
32+
const equivalent =
33+
canonical !== value ? canonical : this.replaceWorkspaceRootPrefix(value, this.canonicalRoot, this.root)
34+
return equivalent === value ? [value] : [value, equivalent]
35+
}
36+
37+
private replaceWorkspaceRootPrefix(value: string, root: string, canonicalRoot: string): string {
38+
const comparableValue = this.strategy.comparisonKey(value)
39+
const comparableRoot = this.strategy.comparisonKey(root)
40+
return comparableValue === comparableRoot || comparableValue.startsWith(`${comparableRoot}/`)
41+
? `${canonicalRoot}${value.slice(root.length)}`
42+
: value
43+
}
44+
}
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
import { PosixWorkspaceRootStrategy } from "../strategies/PosixWorkspaceRootStrategy"
2+
import { WindowsWorkspaceRootStrategy } from "../strategies/WindowsWorkspaceRootStrategy"
3+
import { WorkspaceRootStrategy } from "../strategies/WorkspaceRootStrategy"
4+
import { WorkspaceRootCanonicalizer } from "../WorkspaceRootCanonicalizer"
5+
6+
it("normalizes roots once in the factory before any path comparisons", () => {
7+
const normalizeAbsoluteRoot = vi
8+
.fn<WorkspaceRootStrategy["normalizeAbsoluteRoot"]>()
9+
.mockReturnValueOnce("/aliases/project")
10+
.mockReturnValueOnce("/storage/project")
11+
const comparisonKey = vi.fn((value: string) => value)
12+
const strategy: WorkspaceRootStrategy = {
13+
normalizeAbsoluteRoot,
14+
comparisonKey,
15+
toMatcherAbsolutePath: vi.fn((value: string) => value),
16+
}
17+
18+
const canonicalizer = WorkspaceRootCanonicalizer.forStrategy("/aliases/project/", "/storage/project/", strategy)
19+
20+
expect(normalizeAbsoluteRoot).toHaveBeenCalledTimes(2)
21+
expect(normalizeAbsoluteRoot).toHaveBeenNthCalledWith(1, "/aliases/project/")
22+
expect(normalizeAbsoluteRoot).toHaveBeenNthCalledWith(2, "/storage/project/")
23+
expect(comparisonKey).not.toHaveBeenCalled()
24+
25+
expect(canonicalizer.canonicalize("/aliases/project/docs/file.md")).toBe("/storage/project/docs/file.md")
26+
expect(canonicalizer.canonicalize("/aliases/project/notes.md")).toBe("/storage/project/notes.md")
27+
expect(normalizeAbsoluteRoot).toHaveBeenCalledTimes(2)
28+
})
29+
30+
describe.each([
31+
{
32+
platform: "POSIX",
33+
isWindows: false,
34+
cwd: "/aliases/project",
35+
canonicalCwd: "/storage/project",
36+
root: "/aliases/project",
37+
canonicalRoot: "/storage/project",
38+
},
39+
{
40+
platform: "Windows",
41+
isWindows: true,
42+
cwd: "C:\\Aliases\\Project",
43+
canonicalCwd: "D:\\Storage\\Project",
44+
root: "/C/Aliases/Project",
45+
canonicalRoot: "/D/Storage/Project",
46+
},
47+
])("workspace-root canonicalization on $platform", ({ isWindows, cwd, canonicalCwd, root, canonicalRoot }) => {
48+
const strategy = WorkspaceRootStrategy.forPlatform(isWindows)
49+
const canonicalizer = WorkspaceRootCanonicalizer.forStrategy(cwd, canonicalCwd, strategy)
50+
51+
it("translates an exact root and preserves descendant spelling and globs", () => {
52+
expect(canonicalizer.canonicalize(root)).toBe(canonicalRoot)
53+
expect(canonicalizer.canonicalize(`${root}/Docs/NOTES.md`)).toBe(`${canonicalRoot}/Docs/NOTES.md`)
54+
expect(canonicalizer.canonicalize(`${root}/docs/**`)).toBe(`${canonicalRoot}/docs/**`)
55+
})
56+
57+
it("does not translate similarly prefixed siblings or lexical parents", () => {
58+
for (const value of [`${root}-other/docs/file.md`, `${root}2/file.md`, "/elsewhere/docs/file.md"]) {
59+
expect(canonicalizer.canonicalize(value)).toBe(value)
60+
}
61+
})
62+
63+
it("leaves canonical-root paths and relative values unchanged", () => {
64+
for (const value of [canonicalRoot, `${canonicalRoot}/docs/file.md`, "docs/file.md", "../shared/file.md"]) {
65+
expect(canonicalizer.canonicalize(value)).toBe(value)
66+
}
67+
})
68+
69+
it.each([undefined, "", "relative/project", "C:", "C:relative"])(
70+
"does not infer equivalence from an unknown or relative root: %s",
71+
(invalidRoot) => {
72+
const value = `${root}/docs/file.md`
73+
expect(
74+
WorkspaceRootCanonicalizer.forStrategy(invalidRoot, canonicalCwd, strategy).canonicalize(value),
75+
).toBe(value)
76+
expect(WorkspaceRootCanonicalizer.forStrategy(cwd, invalidRoot, strategy).canonicalize(value)).toBe(value)
77+
},
78+
)
79+
})
80+
81+
describe("POSIX workspace-root strategy", () => {
82+
it("compares case-sensitively and keeps backslashes as filename characters", () => {
83+
const canonicalizer = WorkspaceRootCanonicalizer.forStrategy(
84+
"/aliases/My\\Project",
85+
"/storage/My\\Project",
86+
new PosixWorkspaceRootStrategy(),
87+
)
88+
expect(canonicalizer.canonicalize("/aliases/My\\Project/docs/file.md")).toBe(
89+
"/storage/My\\Project/docs/file.md",
90+
)
91+
expect(canonicalizer.canonicalize("/aliases/my\\project/docs/file.md")).toBe(
92+
"/aliases/my\\project/docs/file.md",
93+
)
94+
expect(canonicalizer.canonicalize("/aliases/My/Project/docs/file.md")).toBe("/aliases/My/Project/docs/file.md")
95+
})
96+
97+
it("normalizes root dot segments and trailing separators", () => {
98+
const canonicalizer = WorkspaceRootCanonicalizer.forStrategy(
99+
"/aliases/temporary/../project/",
100+
"/storage/./project/",
101+
new PosixWorkspaceRootStrategy(),
102+
)
103+
expect(canonicalizer.canonicalize("/aliases/project/docs/file.md")).toBe("/storage/project/docs/file.md")
104+
})
105+
106+
it("does not interpret Windows drive paths as absolute roots", () => {
107+
const canonicalizer = WorkspaceRootCanonicalizer.forStrategy(
108+
"C:/aliases/project",
109+
"D:/storage/project",
110+
new PosixWorkspaceRootStrategy(),
111+
)
112+
expect(canonicalizer.canonicalize("/C/aliases/project/docs/file.md")).toBe("/C/aliases/project/docs/file.md")
113+
})
114+
})
115+
116+
describe("Windows workspace-root strategy", () => {
117+
it("compares case-insensitively across drives without changing descendant case", () => {
118+
const canonicalizer = WorkspaceRootCanonicalizer.forStrategy(
119+
"C:\\Aliases\\Project",
120+
"D:\\Storage\\Project",
121+
new WindowsWorkspaceRootStrategy(),
122+
)
123+
expect(canonicalizer.canonicalize("/c/ALIASES/project/Docs/NOTES.md")).toBe("/D/Storage/Project/Docs/NOTES.md")
124+
expect(canonicalizer.canonicalize("/E/Aliases/Project/Docs/NOTES.md")).toBe("/E/Aliases/Project/Docs/NOTES.md")
125+
})
126+
127+
it("normalizes mixed root separators, dot segments, and trailing separators", () => {
128+
const canonicalizer = WorkspaceRootCanonicalizer.forStrategy(
129+
"C:\\Aliases/temporary/../Project\\",
130+
"D:/Storage/./Project/",
131+
new WindowsWorkspaceRootStrategy(),
132+
)
133+
expect(canonicalizer.canonicalize("/C/Aliases/Project/docs/file.md")).toBe("/D/Storage/Project/docs/file.md")
134+
})
135+
136+
it("supports drive roots and drive-less absolute roots in matcher notation", () => {
137+
const strategy = new WindowsWorkspaceRootStrategy()
138+
expect(WorkspaceRootCanonicalizer.forStrategy("C:/", "D:/", strategy).canonicalize("/C/docs/file.md")).toBe(
139+
"/D/docs/file.md",
140+
)
141+
expect(
142+
WorkspaceRootCanonicalizer.forStrategy("\\Aliases\\Project", "/Storage/Project", strategy).canonicalize(
143+
"/ROOT/Aliases/Project/docs/file.md",
144+
),
145+
).toBe("/ROOT/Storage/Project/docs/file.md")
146+
})
147+
148+
it("normalizes network roots into the shared UNC matcher namespace", () => {
149+
const canonicalizer = WorkspaceRootCanonicalizer.forStrategy(
150+
"\\\\server\\share\\project",
151+
"\\\\server\\storage\\project",
152+
new WindowsWorkspaceRootStrategy(),
153+
)
154+
expect(canonicalizer.canonicalize("/UNC/SERVER/SHARE/project/docs/file.md")).toBe(
155+
"/UNC/server/storage/project/docs/file.md",
156+
)
157+
})
158+
})
159+
160+
it.each([false, true])("preserves filesystem-root equivalence (Windows=%s)", (isWindows) => {
161+
const prefix = isWindows ? "/ROOT" : ""
162+
const strategy = WorkspaceRootStrategy.forPlatform(isWindows)
163+
expect(
164+
WorkspaceRootCanonicalizer.forStrategy("/", "/storage", strategy).canonicalize(`${prefix}/docs/file.md`),
165+
).toBe(`${prefix}/storage/docs/file.md`)
166+
expect(
167+
WorkspaceRootCanonicalizer.forStrategy("/aliases", "/", strategy).canonicalize(
168+
`${prefix}/aliases/docs/file.md`,
169+
),
170+
).toBe(`${prefix}/docs/file.md`)
171+
})
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { isFileMatchedByPatterns } from "../filePatterns"
2+
import { WorkspaceRootStrategy } from "../strategies/WorkspaceRootStrategy"
3+
4+
describe("WorkspaceRootStrategy.forPlatform", () => {
5+
afterEach(() => vi.restoreAllMocks())
6+
7+
it("selects POSIX behavior without interpreting drives, network prefixes, or backslashes", () => {
8+
const strategy = WorkspaceRootStrategy.forPlatform(false)
9+
10+
expect(strategy.toMatcherAbsolutePath("/tmp/notes.md", "/C")).toBe("/tmp/notes.md")
11+
expect(strategy.toMatcherAbsolutePath("//server/share/notes.md", "/C")).toBe("//server/share/notes.md")
12+
expect(strategy.toMatcherAbsolutePath("/tmp/my\\file.md", "/C")).toBe("/tmp/my\\file.md")
13+
expect(strategy.comparisonKey("/tmp/NOTES.md")).toBe("/tmp/NOTES.md")
14+
})
15+
16+
it("selects Windows behavior for drives, rooted paths, and the distinct UNC namespace", () => {
17+
const strategy = WorkspaceRootStrategy.forPlatform(true)
18+
19+
expect(strategy.toMatcherAbsolutePath("D:/tmp/notes.md", "/C")).toBe("/D/tmp/notes.md")
20+
expect(strategy.toMatcherAbsolutePath("/tmp/notes.md", "/C")).toBe("/C/tmp/notes.md")
21+
expect(strategy.toMatcherAbsolutePath("//server/share/notes.md", "/C")).toBe("/UNC/server/share/notes.md")
22+
expect(strategy.toMatcherAbsolutePath("//C/share/notes.md", "/C")).not.toBe("/C/share/notes.md")
23+
expect(strategy.comparisonKey("/D/Tmp/NOTES.md")).toBe("/d/tmp/notes.md")
24+
})
25+
26+
it("uses one selected strategy for candidates, every pattern, and both workspace roots", () => {
27+
const toMatcherAbsolutePath = vi.fn((value: string) => value)
28+
const normalizeAbsoluteRoot = vi
29+
.fn<WorkspaceRootStrategy["normalizeAbsoluteRoot"]>()
30+
.mockReturnValueOnce("/aliases/project")
31+
.mockReturnValueOnce("/storage/project")
32+
const comparisonKey = vi.fn((value: string) => value)
33+
const strategy: WorkspaceRootStrategy = { toMatcherAbsolutePath, normalizeAbsoluteRoot, comparisonKey }
34+
const selectStrategy = vi.spyOn(WorkspaceRootStrategy, "forPlatform").mockReturnValue(strategy)
35+
36+
expect(
37+
isFileMatchedByPatterns({
38+
filePath: "/storage/project/docs/notes.md",
39+
cwd: "/aliases/project",
40+
canonicalCwd: "/storage/project",
41+
patterns: ["docs/**", "!/aliases/project/docs/private.md", "/aliases/project/docs/notes.md"],
42+
isWindows: false,
43+
}),
44+
).toBe(true)
45+
46+
expect(selectStrategy).toHaveBeenCalledOnce()
47+
expect(selectStrategy).toHaveBeenCalledWith(false)
48+
expect(toMatcherAbsolutePath).toHaveBeenCalledWith("/storage/project/docs/notes.md", "")
49+
expect(toMatcherAbsolutePath).toHaveBeenCalledWith("/aliases/project", "")
50+
expect(toMatcherAbsolutePath).toHaveBeenCalledWith("/aliases/project/docs/private.md", "")
51+
expect(toMatcherAbsolutePath).toHaveBeenCalledWith("/aliases/project/docs/notes.md", "")
52+
expect(normalizeAbsoluteRoot).toHaveBeenCalledTimes(2)
53+
expect(normalizeAbsoluteRoot).toHaveBeenNthCalledWith(1, "/aliases/project")
54+
expect(normalizeAbsoluteRoot).toHaveBeenNthCalledWith(2, "/storage/project")
55+
expect(comparisonKey).toHaveBeenCalled()
56+
})
57+
})

‎src/core/auto-approval/__tests__/filePatterns.spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ describe("toMatcherPattern", () => {
8686
// name, so `C:/tmp/notes.md` names a file inside it, relative to the workspace.
8787
describe("on Windows", () => {
8888
// The colon is dropped, leaving the drive as an ordinary leading path
89-
// segment; see `toPosixAbsolutePath` for why it cannot stay.
89+
// segment: the Windows strategy avoids drive-rooted paths rejected by `ignore`.
9090
it("keeps the drive of an absolute pattern as its first path segment", () => {
9191
expect(toWindowsPattern("D:/tmp/notes.md")).toBe("/D/tmp/notes.md")
9292
})

‎src/core/auto-approval/__tests__/posixPaths.spec.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,25 @@ describe("matching off Windows", () => {
2020
const matches = (filePath: string, patterns: string[]) =>
2121
matcher().isFileMatchedByPatterns({ filePath, cwd: CWD, patterns })
2222

23+
it("keeps backslashes in a workspace root literal", () => {
24+
const rootMatch = (filePath: string) =>
25+
matcher().isFileMatchedByPatterns({
26+
filePath,
27+
cwd: "/aliases/my\\project",
28+
canonicalCwd: "/storage/my\\project",
29+
patterns: ["docs/**"],
30+
})
31+
expect(rootMatch("/aliases/my\\project/docs/notes.md")).toBe(true)
32+
expect(rootMatch("/storage/my\\project/docs/notes.md")).toBe(true)
33+
expect(rootMatch("/aliases/my/project/docs/notes.md")).toBe(false)
34+
})
35+
36+
it("matches a relative grant at the filesystem root", () => {
37+
expect(matcher().isFileMatchedByPatterns({ filePath: "/docs/notes.md", cwd: "/", patterns: ["docs/**"] })).toBe(
38+
true,
39+
)
40+
})
41+
2342
// A backslash is a legal filename character here, where `my\file` is one file
2443
// rather than `file` inside `my`.
2544
it("reads a backslash as part of the filename, not as a separator", () => {
@@ -39,6 +58,18 @@ describe("matching off Windows", () => {
3958
expect(matches("/tmp/notes.md", ["C:/tmp/notes.md"])).toBe(false)
4059
})
4160

61+
it("keeps drive-relative-looking names usable as literal POSIX paths", () => {
62+
expect(matches("C:notes.md", ["C:notes.md"])).toBe(true)
63+
expect(matches("D:docs/notes.md", ["D:docs/**"])).toBe(true)
64+
expect(
65+
matcher().isFileMatchedByPatterns({
66+
filePath: "docs/notes.md",
67+
cwd: "/workspace/C:",
68+
patterns: ["docs/**"],
69+
}),
70+
).toBe(true)
71+
})
72+
4273
it("matches a bare pattern anywhere in the workspace, and nowhere else", () => {
4374
expect(matches("notes.md", ["notes.md"])).toBe(true)
4475
expect(matches("deeply/nested/notes.md", ["notes.md"])).toBe(true)
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import * as fs from "fs/promises"
2+
import { baseState } from "./fixtures"
3+
import { matcherForPlatform } from "./matcherForPlatform"
4+
5+
vi.mock("fs/promises", async (importOriginal) => {
6+
const actual = await importOriginal<typeof import("fs/promises")>()
7+
return { ...actual, realpath: vi.fn() }
8+
})
9+
10+
describe("approval with a drive-relative Windows workspace", () => {
11+
matcherForPlatform("win32")
12+
13+
beforeEach(() => {
14+
vi.mocked(fs.realpath).mockReset().mockResolvedValue("C:/repo")
15+
})
16+
17+
it.each(["readFile", "newFileCreated"] as const)(
18+
"does not approve %s outside the actual workspace through relative grants",
19+
async (tool) => {
20+
const { checkAutoApproval } = await import("../index")
21+
const state = { ...baseState, allowedReadFiles: ["docs/**"], allowedWriteFiles: ["docs/**"] }
22+
for (const path of ["C:/docs/private.md", "../docs/private.md"]) {
23+
expect(
24+
await checkAutoApproval({
25+
state,
26+
cwd: "C:",
27+
ask: "tool",
28+
text: JSON.stringify({ tool, path, isOutsideWorkspace: true }),
29+
}),
30+
).toEqual({ decision: "ask" })
31+
}
32+
33+
const text = JSON.stringify({ tool, path: "C:/docs/private.md", isOutsideWorkspace: true })
34+
expect(
35+
await checkAutoApproval({
36+
state: { ...state, allowedReadFiles: ["C:/docs/**"], allowedWriteFiles: ["C:/docs/**"] },
37+
cwd: "C:",
38+
ask: "tool",
39+
text,
40+
}),
41+
).toEqual({ decision: "approve" })
42+
expect(
43+
await checkAutoApproval({
44+
state: {
45+
...state,
46+
allowedReadFiles: ["C:/docs/**", "!C:/docs/private.md"],
47+
allowedWriteFiles: ["C:/docs/**", "!C:/docs/private.md"],
48+
},
49+
cwd: "C:",
50+
ask: "tool",
51+
text,
52+
}),
53+
).toEqual({ decision: "ask" })
54+
},
55+
)
56+
})

0 commit comments

Comments
 (0)