Skip to content

Commit 8a8483e

Browse files
fix(tools): report isOutsideWorkspace in apply_diff approvals
apply_diff did not set isOutsideWorkspace in its approval payload. Auto-approval read the missing value as inside the workspace, so with alwaysAllowWrite on it approved diffs to files outside the workspace even when alwaysAllowWriteOutsideWorkspace was off. Compute the flag in execute and handlePartial, as write_to_file and edit already do. Closes #2249 Co-authored-by: Cursor <[email protected]>
1 parent d2a59a8 commit 8a8483e

3 files changed

Lines changed: 207 additions & 0 deletions

File tree

‎src/core/tools/ApplyDiffTool.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types"
55
import { TelemetryService } from "@roo-code/telemetry"
66

77
import { getReadablePath } from "../../utils/path"
8+
import { isPathOutsideWorkspace } from "../../utils/pathUtils"
89
import { Task } from "../task/Task"
910
import { formatResponse } from "../prompts/responses"
1011
import { fileExistsAtPath } from "../../utils/fs"
@@ -138,11 +139,13 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
138139

139140
// Check if file is write-protected
140141
const isWriteProtected = task.rooProtectedController?.isWriteProtected(relPath) || false
142+
const isOutsideWorkspace = isPathOutsideWorkspace(absolutePath)
141143

142144
const sharedMessageProps: ClineSayTool = {
143145
tool: "appliedDiff",
144146
path: getReadablePath(task.cwd, relPath),
145147
diff: diffContent,
148+
isOutsideWorkspace,
146149
}
147150

148151
if (isPreventFocusDisruptionEnabled) {
@@ -332,10 +335,14 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
332335
return
333336
}
334337

338+
// relPath is guaranteed non-null after hasPathStabilized
339+
const absolutePath = path.resolve(task.cwd, relPath!)
340+
335341
const sharedMessageProps: ClineSayTool = {
336342
tool: "appliedDiff",
337343
path: getReadablePath(task.cwd, relPath),
338344
diff: diffContent,
345+
isOutsideWorkspace: isPathOutsideWorkspace(absolutePath),
339346
}
340347

341348
let toolProgressStatus

‎src/core/tools/__tests__/applyDiffTool.failureReporting.spec.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ vi.mock("../../../utils/path", () => ({
2626
getReadablePath: vi.fn().mockReturnValue("test/file.txt"),
2727
}))
2828

29+
vi.mock("../../../utils/pathUtils", () => ({
30+
isPathOutsideWorkspace: vi.fn().mockReturnValue(false),
31+
}))
32+
2933
vi.mock("../../prompts/responses", () => ({
3034
formatResponse: {
3135
toolError: vi.fn((message: string) => `Error: ${message}`),
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
// npx vitest run core/tools/__tests__/applyDiffTool.outsideWorkspace.spec.ts
2+
3+
import fs from "fs/promises"
4+
import path from "path"
5+
6+
import type { ClineSayTool } from "@roo-code/types"
7+
8+
import type { ToolUse } from "../../../shared/tools"
9+
import { isPathOutsideWorkspace } from "../../../utils/pathUtils"
10+
import { checkAutoApproval } from "../../auto-approval"
11+
import { baseState } from "../../auto-approval/__tests__/fixtures"
12+
import type { Task } from "../../task/Task"
13+
import type { ToolCallbacks } from "../BaseTool"
14+
import { applyDiffTool } from "../ApplyDiffTool"
15+
16+
vi.mock("@roo-code/telemetry", () => ({
17+
TelemetryService: { instance: { captureDiffApplicationError: vi.fn() } },
18+
}))
19+
20+
vi.mock("fs/promises", () => ({
21+
default: {
22+
readFile: vi.fn(),
23+
},
24+
}))
25+
26+
vi.mock("../../../utils/fs", () => ({
27+
fileExistsAtPath: vi.fn().mockResolvedValue(true),
28+
}))
29+
30+
vi.mock("../../../utils/path", () => ({
31+
getReadablePath: vi.fn((_cwd: string, relPath?: string) => relPath ?? ""),
32+
}))
33+
34+
vi.mock("../../../utils/pathUtils", () => ({
35+
isPathOutsideWorkspace: vi.fn(),
36+
}))
37+
38+
vi.mock("../../prompts/responses", () => ({
39+
formatResponse: {
40+
toolError: vi.fn((message: string) => `Error: ${message}`),
41+
rooIgnoreError: vi.fn((filePath: string) => `Access denied: ${filePath}`),
42+
createPrettyPatch: vi.fn(() => "mock-diff"),
43+
},
44+
}))
45+
46+
vi.mock("../../diff/stats", () => ({
47+
sanitizeUnifiedDiff: vi.fn((diff: string) => diff),
48+
computeDiffStats: vi.fn(() => ({ additions: 1, deletions: 1 })),
49+
}))
50+
51+
vi.mock("vscode", () => ({
52+
window: { showWarningMessage: vi.fn() },
53+
env: { openExternal: vi.fn() },
54+
Uri: { parse: vi.fn() },
55+
}))
56+
57+
const CWD = "/workspace"
58+
const INSIDE_PATH = "src/index.ts"
59+
const OUTSIDE_PATH = "/home/me/.zshrc"
60+
const DIFF = "<<<<<<< SEARCH\nold\n=======\nnew\n>>>>>>> REPLACE"
61+
62+
const cases = [
63+
{ name: "a file outside the workspace", relPath: OUTSIDE_PATH, isOutside: true },
64+
{ name: "a file inside the workspace", relPath: INSIDE_PATH, isOutside: false },
65+
]
66+
67+
const approvalPaths = [
68+
{ name: "diff view", preventFocusDisruption: false },
69+
{ name: "preventFocusDisruption", preventFocusDisruption: true },
70+
]
71+
72+
describe("ApplyDiffTool isOutsideWorkspace", () => {
73+
let askApproval: ReturnType<typeof vi.fn<ToolCallbacks["askApproval"]>>
74+
75+
function createTask(preventFocusDisruption = false): Task {
76+
const task = {
77+
cwd: CWD,
78+
consecutiveMistakeCount: 0,
79+
consecutiveMistakeCountForApplyDiff: new Map<string, number>(),
80+
didEditFile: false,
81+
api: { getModel: () => ({ id: "claude-test" }) },
82+
rooIgnoreController: { validateAccess: vi.fn().mockReturnValue(true) },
83+
rooProtectedController: { isWriteProtected: vi.fn().mockReturnValue(false) },
84+
providerRef: {
85+
deref: vi.fn().mockReturnValue({
86+
getState: vi.fn().mockResolvedValue({
87+
diagnosticsEnabled: false,
88+
writeDelayMs: 0,
89+
experiments: { preventFocusDisruption },
90+
}),
91+
}),
92+
},
93+
diffStrategy: {
94+
getName: () => "test",
95+
applyDiff: vi.fn().mockResolvedValue({ success: true, content: "new\n" }),
96+
},
97+
diffViewProvider: {
98+
editType: undefined,
99+
originalContent: "",
100+
open: vi.fn().mockResolvedValue(undefined),
101+
update: vi.fn().mockResolvedValue(undefined),
102+
reset: vi.fn().mockResolvedValue(undefined),
103+
revertChanges: vi.fn().mockResolvedValue(undefined),
104+
saveChanges: vi.fn().mockResolvedValue(undefined),
105+
saveDirectly: vi.fn().mockResolvedValue(undefined),
106+
scrollToFirstDiff: vi.fn(),
107+
pushToolWriteResult: vi.fn().mockResolvedValue("Changes successfully applied."),
108+
},
109+
fileContextTracker: { trackFileContext: vi.fn().mockResolvedValue(undefined) },
110+
say: vi.fn().mockResolvedValue(undefined),
111+
ask: vi.fn().mockResolvedValue(undefined),
112+
recordToolError: vi.fn(),
113+
processQueuedMessages: vi.fn(),
114+
sayAndCreateMissingParamError: vi.fn().mockResolvedValue("Missing param error"),
115+
}
116+
// The double provides only the Task members that ApplyDiffTool.execute and handlePartial read.
117+
return task as unknown as Task
118+
}
119+
120+
async function runExecute(relPath: string, isOutside: boolean, preventFocusDisruption = false): Promise<string> {
121+
vi.mocked(isPathOutsideWorkspace).mockReturnValue(isOutside)
122+
123+
await applyDiffTool.execute({ path: relPath, diff: DIFF }, createTask(preventFocusDisruption), {
124+
askApproval,
125+
handleError: vi.fn().mockResolvedValue(undefined),
126+
pushToolResult: vi.fn(),
127+
toolCallId: "tool-call-1",
128+
})
129+
130+
expect(askApproval).toHaveBeenCalledTimes(1)
131+
return String(askApproval.mock.calls[0][1])
132+
}
133+
134+
beforeEach(() => {
135+
vi.clearAllMocks()
136+
applyDiffTool.resetPartialState()
137+
vi.mocked(fs.readFile).mockResolvedValue("old\n")
138+
askApproval = vi.fn<ToolCallbacks["askApproval"]>().mockResolvedValue(true)
139+
})
140+
141+
describe.each(approvalPaths)("approval payload ($name)", ({ preventFocusDisruption }) => {
142+
it.each(cases)("reports isOutsideWorkspace for $name", async ({ relPath, isOutside }) => {
143+
const payload = JSON.parse(await runExecute(relPath, isOutside, preventFocusDisruption)) as ClineSayTool
144+
145+
expect(isPathOutsideWorkspace).toHaveBeenCalledWith(path.resolve(CWD, relPath))
146+
expect(payload.tool).toBe("appliedDiff")
147+
expect(payload.isOutsideWorkspace).toBe(isOutside)
148+
})
149+
})
150+
151+
it.each(cases)("reports isOutsideWorkspace in the partial preview for $name", async ({ relPath, isOutside }) => {
152+
vi.mocked(isPathOutsideWorkspace).mockReturnValue(isOutside)
153+
const task = createTask()
154+
const block: ToolUse<"apply_diff"> = {
155+
type: "tool_use",
156+
name: "apply_diff",
157+
params: { path: relPath, diff: DIFF },
158+
partial: true,
159+
}
160+
161+
// The first call records the path; the second call sees it stable and asks.
162+
await applyDiffTool.handlePartial(task, block)
163+
await applyDiffTool.handlePartial(task, block)
164+
165+
expect(task.ask).toHaveBeenCalledTimes(1)
166+
const payload = JSON.parse(String(vi.mocked(task.ask).mock.calls[0][1])) as ClineSayTool
167+
expect(isPathOutsideWorkspace).toHaveBeenCalledWith(path.resolve(CWD, relPath))
168+
expect(payload.isOutsideWorkspace).toBe(isOutside)
169+
})
170+
171+
describe("auto-approval decision with alwaysAllowWrite on", () => {
172+
it.each([
173+
{ ...cases[0], allowOutside: false, expected: "ask" },
174+
{ ...cases[0], allowOutside: true, expected: "approve" },
175+
{ ...cases[1], allowOutside: false, expected: "approve" },
176+
])(
177+
"returns $expected for $name when alwaysAllowWriteOutsideWorkspace is $allowOutside",
178+
async ({ relPath, isOutside, allowOutside, expected }) => {
179+
const text = await runExecute(relPath, isOutside)
180+
181+
const result = await checkAutoApproval({
182+
state: {
183+
...baseState,
184+
alwaysAllowWrite: true,
185+
alwaysAllowWriteOutsideWorkspace: allowOutside,
186+
},
187+
cwd: CWD,
188+
ask: "tool",
189+
text,
190+
})
191+
192+
expect(result).toEqual({ decision: expected })
193+
},
194+
)
195+
})
196+
})

0 commit comments

Comments
 (0)