diff --git a/docs/architecture/tla/WorkspaceContainment.CorruptDisplay.cfg b/docs/architecture/tla/WorkspaceContainment.CorruptDisplay.cfg new file mode 100644 index 0000000000..01d03d106c --- /dev/null +++ b/docs/architecture/tla/WorkspaceContainment.CorruptDisplay.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + OutsideGate <- CorruptDisplay + SourceCandidates <- FixedSource +INVARIANTS TypeOK SymlinkEscapeNeedsConsent InsideWriteApproved DisplayPathNeedsConsent UncheckedCandidateNeedsConsent +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/WorkspaceContainment.NeverInside.cfg b/docs/architecture/tla/WorkspaceContainment.NeverInside.cfg new file mode 100644 index 0000000000..816ca2cdfa --- /dev/null +++ b/docs/architecture/tla/WorkspaceContainment.NeverInside.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + OutsideGate <- NeverInside + SourceCandidates <- FixedSource +INVARIANTS TypeOK SymlinkEscapeNeedsConsent InsideWriteApproved DisplayPathNeedsConsent UncheckedCandidateNeedsConsent +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/WorkspaceContainment.NoContainment.cfg b/docs/architecture/tla/WorkspaceContainment.NoContainment.cfg new file mode 100644 index 0000000000..5345c2d81b --- /dev/null +++ b/docs/architecture/tla/WorkspaceContainment.NoContainment.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + OutsideGate <- NoContainment + SourceCandidates <- FixedSource +INVARIANTS TypeOK SymlinkEscapeNeedsConsent InsideWriteApproved DisplayPathNeedsConsent UncheckedCandidateNeedsConsent +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/WorkspaceContainment.UncheckedCandidate.cfg b/docs/architecture/tla/WorkspaceContainment.UncheckedCandidate.cfg new file mode 100644 index 0000000000..2fda1376a6 --- /dev/null +++ b/docs/architecture/tla/WorkspaceContainment.UncheckedCandidate.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + OutsideGate <- FixedOutsideGate + SourceCandidates <- IncompleteSource +INVARIANTS TypeOK SymlinkEscapeNeedsConsent InsideWriteApproved DisplayPathNeedsConsent UncheckedCandidateNeedsConsent +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/WorkspaceContainment.Unfixed.cfg b/docs/architecture/tla/WorkspaceContainment.Unfixed.cfg new file mode 100644 index 0000000000..4d02166fcf --- /dev/null +++ b/docs/architecture/tla/WorkspaceContainment.Unfixed.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + OutsideGate <- LexicalOnly + SourceCandidates <- FixedSource +INVARIANTS TypeOK SymlinkEscapeNeedsConsent InsideWriteApproved DisplayPathNeedsConsent UncheckedCandidateNeedsConsent +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/WorkspaceContainment.cfg b/docs/architecture/tla/WorkspaceContainment.cfg new file mode 100644 index 0000000000..c887aa287e --- /dev/null +++ b/docs/architecture/tla/WorkspaceContainment.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS + OutsideGate <- FixedOutsideGate + SourceCandidates <- FixedSource +INVARIANTS TypeOK SymlinkEscapeNeedsConsent InsideWriteApproved DisplayPathNeedsConsent UncheckedCandidateNeedsConsent +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/WorkspaceContainment.tla b/docs/architecture/tla/WorkspaceContainment.tla new file mode 100644 index 0000000000..93cf59f999 --- /dev/null +++ b/docs/architecture/tla/WorkspaceContainment.tla @@ -0,0 +1,168 @@ +---- MODULE WorkspaceContainment ---- +(* + +**************************************************************************) +(* Workspace containment for write auto-approval (issue 2344). *) +(* *) +(* Functions. Source: the approval payload of a write tool. It carries *) +(* `isOutsideWorkspace` from `isPathOutsideWorkspace`, a lexical check, *) +(* and its file targets from `resolveApprovalFileTarget` and *) +(* `imageWriteTargets`, the native paths the tool writes. The realpath *) +(* oracle `isRealPathOutsideWorkspace` resolves each target. Sink: the *) +(* write branch of `checkAutoApproval` in src/core/auto-approval/index.ts.*) +(* *) +(* Failure. F1: a write through a symlink inside the workspace to a file *) +(* outside it is auto-approved while `alwaysAllowWriteOutsideWorkspace` *) +(* is off. F2: a write inside the workspace stops being auto-approved. *) +(* F3: the gate decides on a display path that `getReadablePath` rewrote *) +(* (POSIX turns a backslash into a separator), so an inside verdict *) +(* approves a write to a file outside the workspace. F4: a tool writes a *) +(* file the approval did not resolve (`generate_image` appends the *) +(* extension after the approval), and a link at that file escapes. *) +(* *) +(* Invariants. SymlinkEscapeNeedsConsent is the opposite of F1: an *) +(* approved write whose resolved target is outside has a matching *) +(* pattern or the outside-write consent. InsideWriteApproved is the *) +(* opposite of F2. DisplayPathNeedsConsent is the opposite of F3: an *) +(* approved write decided without the native target is not an outside *) +(* write, unless a pattern or the outside consent covers it. *) +(* UncheckedCandidateNeedsConsent is the opposite of F4, for a payload *) +(* with native targets that leaves a candidate out. *) +(* *) +(* Model. One write action. The inputs are the lexical flag, the real *) +(* flag of the resolved targets, whether the payload names the file the *) +(* tool writes (`nativeTarget`), whether it names every file the tool *) +(* may write (`allCandidatesChecked`), the real location of the file *) +(* written (`writtenOutside`), three settings, and two action properties.*) +(* The gate cannot tell a complete target list from a partial one, so *) +(* every candidate is the payload source's duty: `SourceCandidates` *) +(* constrains the payload a tool sends, and the fixed tools list every *) +(* file they may write. The gate is `lexicalOutside \/ realOutside \/ *) +(* ~nativeTarget`: a payload it cannot verify fails closed. The oracle *) +(* is sound for a file it resolved, and only listed targets are resolved.*) +(* *) +(* Cost. Base cfg: 768 distinct states, under one second. Each sabotage *) +(* cfg stops at its first violation. *) +(* Findings. Unfixed fails SymlinkEscapeNeedsConsent: lexical inside, *) +(* real outside, write allowed, no outside consent, no pattern (F1). *) +(* NoContainment fails SymlinkEscapeNeedsConsent. NeverInside fails *) +(* InsideWriteApproved (F2). CorruptDisplay fails DisplayPathNeedsConsent *) +(* (F3). UncheckedCandidate fails UncheckedCandidateNeedsConsent (F4): *) +(* the base cfg cannot reach F4, since the fixed source lists every *) +(* candidate, so that cfg relaxes the source. Each cfg fails only the *) +(* invariant named here. *) +(* *) +(* Review ratchet. covered 0, added 2, gap 0 (PR 2816 round 1: threads *) +(* r4792649128 and r4792649138 added F3 and F4). *) +(* + +**************************************************************************) +EXTENDS Naturals + +(* The containment gate of the write branch: `OutsideGate(lex, real, *) +(* native)` is TRUE when the action counts as outside every workspace *) +(* folder. The MC module gives the fixed gate and each sabotage. *) +CONSTANT OutsideGate(_, _, _) + +(* The payload source: `SourceCandidates(native, all)` constrains the *) +(* payload a write tool sends. FixedSource names every candidate with the *) +(* native target. The MC module gives the source before round 1. *) +CONSTANT SourceCandidates(_, _) + +VARIABLES + lexicalOutside, \* The payload flag `isOutsideWorkspace`. + realOutside, \* The realpath oracle: some resolved target is outside. + nativeTarget, \* The payload names the file the tool writes. + allCandidatesChecked, \* The payload names every file the tool may write. + writtenOutside, \* The file the tool writes is really outside. + allowWrite, \* `alwaysAllowWrite`. + allowOutsideWrite, \* `alwaysAllowWriteOutsideWorkspace`. + allowProtected, \* `alwaysAllowWriteProtected`. + protected, \* The action touches a protected file. + patternMatched, \* Every file of the action matches `allowedWriteFiles`. + decision + +Vars == <> + +(* The fixed gate: a lexical inside is not final. A symlink inside the *) +(* workspace can lead outside it, so the real flag decides too. A payload *) +(* without the native target cannot be verified, so it counts as outside. *) +(* The oracle fails closed: an unresolvable target reports real outside. *) +FixedOutsideGate(lex, real, native) == lex \/ real \/ \lnot native + +(* The fixed write tools: a payload that names the native target also *) +(* names every file the tool may write (`imageWriteTargets`). *) +FixedSource(native, all) == native => all + +Init == + /\ lexicalOutside \in BOOLEAN + /\ realOutside \in BOOLEAN + /\ nativeTarget \in BOOLEAN + /\ allCandidatesChecked \in BOOLEAN + /\ writtenOutside \in BOOLEAN + \* Only listed targets are resolved, so a checked candidate needs a native target. + /\ allCandidatesChecked => nativeTarget + /\ SourceCandidates(nativeTarget, allCandidatesChecked) + \* The oracle is sound for a file it resolved. + /\ allCandidatesChecked => (writtenOutside = realOutside) + /\ allowWrite \in BOOLEAN + /\ allowOutsideWrite \in BOOLEAN + /\ allowProtected \in BOOLEAN + /\ protected \in BOOLEAN + /\ patternMatched \in BOOLEAN + /\ decision = "pending" + +(* The write branch of `checkAutoApproval`: a matching pattern or the *) +(* write permission with containment consent, then the protected check. *) +Decide == + /\ decision = "pending" + /\ decision' = + IF patternMatched \/ + (allowWrite /\ (\lnot OutsideGate(lexicalOutside, realOutside, nativeTarget) \/ allowOutsideWrite)) + THEN IF \lnot protected \/ allowProtected THEN "approve" ELSE "ask" + ELSE "ask" + /\ UNCHANGED <> + +Next == Decide + +Spec == Init /\ [][Next]_Vars + +TypeOK == + /\ decision \in {"pending", "approve", "ask"} + /\ lexicalOutside \in BOOLEAN + /\ realOutside \in BOOLEAN + /\ nativeTarget \in BOOLEAN + /\ allCandidatesChecked \in BOOLEAN + /\ writtenOutside \in BOOLEAN + /\ allowWrite \in BOOLEAN + /\ allowOutsideWrite \in BOOLEAN + /\ allowProtected \in BOOLEAN + /\ protected \in BOOLEAN + /\ patternMatched \in BOOLEAN + +(* F1. An approved write whose resolved target is outside has a pattern *) +(* match or the outside-write consent. *) +SymlinkEscapeNeedsConsent == + decision = "approve" /\ realOutside => patternMatched \/ allowOutsideWrite + +(* F2. A write whose every candidate resolved inside stays auto-approved *) +(* when writes are allowed and the protected check passes. *) +InsideWriteApproved == + \lnot lexicalOutside /\ \lnot realOutside /\ allCandidatesChecked + /\ allowWrite /\ (\lnot protected \/ allowProtected) => decision # "ask" + +(* F3. An approved write decided without the native target is not an *) +(* outside write, unless a pattern or the outside consent covers it. *) +DisplayPathNeedsConsent == + decision = "approve" /\ \lnot nativeTarget /\ writtenOutside => patternMatched \/ allowOutsideWrite + +(* F4. An approved write whose payload has native targets but leaves a *) +(* candidate out is not an outside write, unless a pattern or the outside *) +(* consent covers it. *) +UncheckedCandidateNeedsConsent == + decision = "approve" /\ nativeTarget /\ \lnot allCandidatesChecked /\ writtenOutside + => patternMatched \/ allowOutsideWrite + +==== diff --git a/docs/architecture/tla/WorkspaceContainmentMC.tla b/docs/architecture/tla/WorkspaceContainmentMC.tla new file mode 100644 index 0000000000..f194743b9c --- /dev/null +++ b/docs/architecture/tla/WorkspaceContainmentMC.tla @@ -0,0 +1,21 @@ +---- MODULE WorkspaceContainmentMC ---- +\* Model-checking settings for WorkspaceContainment. Each *Gate and *Source operator is one variant. +EXTENDS WorkspaceContainment + +\* Code before the fix (issue 2344): drops the realpath conjunct. The lexical flag alone decides containment. +LexicalOnly(lex, real, native) == lex \/ \lnot native + +\* The write branch drops containment: a payload it can verify is approved by `alwaysAllowWrite` alone. +NoContainment(lex, real, native) == \lnot native + +\* Over-reject: every write counts as outside. +NeverInside(lex, real, native) == TRUE + +\* PR 2816 round 1, thread r4792649128: drops the native-target conjunct. The gate trusts a display path (F3). +CorruptDisplay(lex, real, native) == lex \/ real + +\* PR 2816 round 1, thread r4792649138: the `generate_image` payload before the round, which named the bare +\* path alone. The gate cannot tell a complete target list from a partial one (F4). +IncompleteSource(native, all) == TRUE + +==== diff --git a/src/core/auto-approval/__tests__/allowedWriteFiles.spec.ts b/src/core/auto-approval/__tests__/allowedWriteFiles.spec.ts index 8013a3b715..9834a1f634 100644 --- a/src/core/auto-approval/__tests__/allowedWriteFiles.spec.ts +++ b/src/core/auto-approval/__tests__/allowedWriteFiles.spec.ts @@ -1,7 +1,7 @@ // npx vitest run core/auto-approval/__tests__/allowedWriteFiles.spec.ts import { checkAutoApproval } from ".." -import { CWD, baseState, type State } from "./fixtures" +import { CWD, baseState, setWorkspaceFolders, type State } from "./fixtures" const askToWrite = async ({ path, @@ -11,6 +11,7 @@ const askToWrite = async ({ isOutsideWorkspace, cwd = CWD, batchDiffs, + fileTargets, }: { path?: string state: Partial @@ -19,6 +20,7 @@ const askToWrite = async ({ isOutsideWorkspace?: boolean cwd?: string batchDiffs?: { path: string }[] + fileTargets?: { absolutePath: string; isOutsideWorkspace: boolean }[] }) => checkAutoApproval({ state: { ...baseState, ...state }, @@ -26,8 +28,13 @@ const askToWrite = async ({ ask: "tool", text: JSON.stringify({ tool, path, isOutsideWorkspace, isProtected, batchDiffs }), isProtected, + fileTargets, }) +// The write branch resolves the real target of a file against the workspace +// folders, so the specs register the folder their paths sit in. +beforeEach(() => setWorkspaceFolders(CWD)) + describe("allowedWriteFiles auto-approval", () => { it("asks when the file is not listed", async () => { expect(await askToWrite({ path: "src/index.ts", state: { allowedWriteFiles: ["notes.md"] } })).toEqual({ @@ -112,7 +119,16 @@ describe("allowedWriteFiles auto-approval", () => { }) it("leaves the alwaysAllowWrite behaviour unchanged when nothing is listed", async () => { - expect(await askToWrite({ path: "src/index.ts", state: { alwaysAllowWrite: true } })).toEqual({ + // The write tools name their file by target (PR 2816): the blanket + // permission approves an inside write as before, and an outside file + // still needs the outside-workspace toggle. + expect( + await askToWrite({ + path: "src/index.ts", + state: { alwaysAllowWrite: true }, + fileTargets: [{ absolutePath: `${CWD}/src/index.ts`, isOutsideWorkspace: false }], + }), + ).toEqual({ decision: "approve", }) @@ -121,6 +137,7 @@ describe("allowedWriteFiles auto-approval", () => { path: "/tmp/notes.md", isOutsideWorkspace: true, state: { alwaysAllowWrite: true }, + fileTargets: [{ absolutePath: "/tmp/notes.md", isOutsideWorkspace: true }], }), ).toEqual({ decision: "ask" }) }) diff --git a/src/core/auto-approval/__tests__/blanket-deny.spec.ts b/src/core/auto-approval/__tests__/blanket-deny.spec.ts index f60380b8cf..651170c4d9 100644 --- a/src/core/auto-approval/__tests__/blanket-deny.spec.ts +++ b/src/core/auto-approval/__tests__/blanket-deny.spec.ts @@ -1,11 +1,14 @@ import { checkAutoApproval } from ".." -import { baseState as sharedBaseState, type State } from "./fixtures" +import { baseState as sharedBaseState, setWorkspaceFolders, type State } from "./fixtures" // Matrix over the blanket auto-deny feature (`alwaysDenyUnapprovedCommands`): // DCG on/off × blanket on/off × command shapes. The blanket setting only // engages while command auto-approval (`autoApprovalEnabled` + // `alwaysAllowExecute`) is on, so the engagement cases keep both gates on; the // disengagement cases turn them off to prove the setting is inert. +// The write ask below sits in `/repo`; the write branch resolves its real target. +beforeEach(() => setWorkspaceFolders("/repo")) + describe("blanket auto-deny for unapproved commands", () => { const baseState = { ...sharedBaseState, @@ -241,12 +244,15 @@ describe("blanket auto-deny for unapproved commands", () => { it("does not affect non-command asks", async () => { const state = { ...baseState, alwaysDenyUnapprovedCommands: true, alwaysAllowWrite: true } + // The tool names its file by target (PR 2816); the blanket setting is + // command-only, so it leaves the write approval untouched. expect( await checkAutoApproval({ state, cwd: "/repo", ask: "tool", text: JSON.stringify({ tool: "editedExistingFile", path: "a.ts" }), + fileTargets: [{ absolutePath: "/repo/a.ts", isOutsideWorkspace: false }], }), ).toEqual({ decision: "approve" }) diff --git a/src/core/auto-approval/__tests__/fileTargets.spec.ts b/src/core/auto-approval/__tests__/fileTargets.spec.ts index d6e83e28e2..5e303d43af 100644 --- a/src/core/auto-approval/__tests__/fileTargets.spec.ts +++ b/src/core/auto-approval/__tests__/fileTargets.spec.ts @@ -4,7 +4,7 @@ import type { ClineSayTool } from "@roo-code/types" import type { ApprovalFileTarget } from "../../../shared/tools" import { checkAutoApproval } from "../index" -import { baseState, CWD, type State } from "./fixtures" +import { baseState, CWD, setWorkspaceFolders, type State } from "./fixtures" vi.mock("fs/promises", async (importOriginal) => { const actual = await importOriginal() @@ -28,6 +28,8 @@ function approval(tool: ClineSayTool, state: Partial, fileTargets?: reado beforeEach(() => { vi.mocked(fs.realpath).mockReset().mockResolvedValue(CWD) + // The write branch resolves the real target of a target against the folders. + setWorkspaceFolders(CWD) }) describe("file targets decide allowlist matches", () => { @@ -98,11 +100,19 @@ describe("invalid or incomplete file targets ask the user", () => { { name: "no targets", fileTargets: [] }, { name: "a relative target", fileTargets: [{ absolutePath: "docs/notes.md", isOutsideWorkspace: false }] }, { name: "an empty target", fileTargets: [{ absolutePath: "", isOutsideWorkspace: false }] }, - { name: "more targets than named files", fileTargets: [inside("docs/notes.md"), inside("docs/other.md")] }, ])("asks for $name", async ({ fileTargets }) => { expect(await approval(message, permissive, fileTargets)).toEqual({ decision: "ask" }) }) + it("approves extra targets beside every named file", async () => { + // A tool that may write a file its message does not name lists that file + // too (`generate_image` names every extension candidate, PR 2816). More + // targets only make the check stricter. + expect(await approval(message, permissive, [inside("docs/notes.md"), inside("docs/other.md")])).toEqual({ + decision: "approve", + }) + }) + it.each([ { name: "a workspace verdict", target: { absolutePath: `${CWD}/docs/notes.md` } }, { name: "a path", target: { isOutsideWorkspace: false } }, diff --git a/src/core/auto-approval/__tests__/fixtures.ts b/src/core/auto-approval/__tests__/fixtures.ts index 96b983135b..26510175a0 100644 --- a/src/core/auto-approval/__tests__/fixtures.ts +++ b/src/core/auto-approval/__tests__/fixtures.ts @@ -6,6 +6,7 @@ // maintaining near-identical literals side by side. import path from "path" +import * as vscode from "vscode" import type { ClineSayTool, ExtensionState } from "@roo-code/types" @@ -76,3 +77,18 @@ export function readFileAsk( })), } } + +/** + * Register `roots` as the workspace folders. The write branch resolves the + * real target of a file against them, so a spec that approves an inside write + * names the folder the file is inside. + */ +export function setWorkspaceFolders(...roots: string[]): void { + Object.assign(vscode.workspace, { + workspaceFolders: roots.map((fsPath, index) => ({ + uri: vscode.Uri.file(fsPath), + name: path.basename(fsPath), + index, + })), + }) +} diff --git a/src/core/auto-approval/__tests__/workspaceContainment.property.spec.ts b/src/core/auto-approval/__tests__/workspaceContainment.property.spec.ts new file mode 100644 index 0000000000..81b070521b --- /dev/null +++ b/src/core/auto-approval/__tests__/workspaceContainment.property.spec.ts @@ -0,0 +1,226 @@ +// npx vitest run core/auto-approval/__tests__/workspaceContainment.property.spec.ts + +import path from "path" + +import type { ApprovalFileTarget } from "../../../shared/tools" +import { checkAutoApproval } from ".." +import { CWD, baseState, type State } from "./fixtures" + +/** + * The realpath oracle stands in for the filesystem: the spec sets its answer + * for one check. A `globalThis` slot gives the hoisted mock factory and the + * test body the same object. + */ +type Oracle = { realOutside: boolean } +const oracleSlot = "__zooWorkspaceContainmentOracle__" +Reflect.set(globalThis, oracleSlot, { realOutside: false }) +const readOracle = (): Oracle => Reflect.get(globalThis, oracleSlot) as Oracle +const writeOracle = (realOutside: boolean) => Reflect.set(globalThis, oracleSlot, { realOutside }) + +vi.mock("../../../utils/pathUtils", async (importOriginal) => ({ + ...(await importOriginal()), + isRealPathOutsideWorkspace: vi.fn(async () => readOracle().realOutside), +})) + +type Input = { + lexicalOutside: boolean + /** The realpath oracle reports a resolved target outside. */ + realOutside: boolean + /** The payload carries the native target of the file written. */ + nativeTarget: boolean + /** The payload carries a target for every file the tool may write. */ + allCandidatesChecked: boolean + /** The file the tool writes is really outside. */ + writtenOutside: boolean + allowWrite: boolean + allowOutsideWrite: boolean + allowProtected: boolean + protected: boolean + patternMatched: boolean +} + +/** + * Every write input. The oracle is sound: when the payload carries the native + * target and every candidate, the written file is where the oracle says. Otherwise + * the display path may name another file, so the written file may be outside + * whatever the oracle reported. + */ +const inputs: Input[] = [] +for (let bits = 0; bits < 512; bits++) { + const at = (bit: number) => (bits & (1 << bit)) !== 0 + const base = { + lexicalOutside: at(0), + realOutside: at(1), + nativeTarget: at(2), + allCandidatesChecked: at(3), + allowWrite: at(4), + allowOutsideWrite: at(5), + allowProtected: at(6), + protected: at(7), + patternMatched: at(8), + } + // The fixed write tools name the native target exactly when they name every + // candidate (`SourceCandidates` in the spec, PR 2816). The gate cannot tell + // a partial list from a complete one, so a partial list is not an input the + // code can produce; the sabotage cfg models it instead. + if (base.nativeTarget !== base.allCandidatesChecked) { + continue + } + const written = base.nativeTarget && base.allCandidatesChecked ? [base.realOutside] : [false, true] + for (const writtenOutside of written) { + inputs.push({ ...base, writtenOutside }) + } +} + +const label = (input: Input) => + [ + `lexical=${input.lexicalOutside}`, + `real=${input.realOutside}`, + `native=${input.nativeTarget}`, + `all=${input.allCandidatesChecked}`, + `written=${input.writtenOutside}`, + `write=${input.allowWrite}`, + `outside=${input.allowOutsideWrite}`, + `protect=${input.allowProtected}/${input.protected}`, + `pattern=${input.patternMatched}`, + ].join(" ") + +const cases = inputs.map((input) => [label(input), input] as const) + +/** + * One write action under one input. The message names `notes.md`; the action + * may also write `notes.png` (as `generate_image` appends an extension), which + * the targets list only when every candidate is checked. + */ +const decide = async (input: Input) => { + writeOracle(input.realOutside) + const state: State = { + ...baseState, + alwaysAllowWrite: input.allowWrite, + alwaysAllowWriteOutsideWorkspace: input.allowOutsideWrite, + alwaysAllowWriteProtected: input.allowProtected, + allowedWriteFiles: input.patternMatched ? ["notes.md"] : [], + } + const target = (relativePath: string): ApprovalFileTarget => ({ + absolutePath: path.resolve(CWD, relativePath), + isOutsideWorkspace: input.lexicalOutside, + }) + + return checkAutoApproval({ + state, + cwd: CWD, + ask: "tool", + text: JSON.stringify({ + tool: "newFileCreated", + path: "notes.md", + isOutsideWorkspace: input.lexicalOutside, + isProtected: input.protected, + }), + isProtected: input.protected, + fileTargets: input.nativeTarget + ? [target("notes.md"), ...(input.allCandidatesChecked ? [target("notes.png")] : [])] + : undefined, + }) +} + +describe("workspace containment invariants over every write input", () => { + it.each(cases)( + "an approved write with a resolved target outside has a pattern or the outside consent (%s)", + async (_, input) => { + const result = await decide(input) + if (result.decision === "approve" && input.realOutside) { + expect(input.patternMatched || input.allowOutsideWrite).toBe(true) + } + }, + ) + + it.each(cases)( + "a write that is inside, with its native target and every candidate resolved, stays approved (%s)", + async (_, input) => { + if ( + !input.lexicalOutside && + !input.realOutside && + input.nativeTarget && + input.allCandidatesChecked && + input.allowWrite && + (!input.protected || input.allowProtected) + ) { + expect(await decide(input)).toEqual({ decision: "approve" }) + } + }, + ) + + it.each(cases)( + "an approved write decided without the native target is not an outside write unless covered (%s)", + async (_, input) => { + const result = await decide(input) + if (result.decision === "approve" && !input.nativeTarget && input.writtenOutside) { + expect(input.patternMatched || input.allowOutsideWrite).toBe(true) + } + }, + ) + + it.each(cases)( + "an approved write with a candidate the gate did not resolve is not an outside write unless covered (%s)", + async (_, input) => { + const result = await decide(input) + if (result.decision === "approve" && !input.allCandidatesChecked && input.writtenOutside) { + expect(input.patternMatched || input.allowOutsideWrite).toBe(true) + } + }, + ) + + describe("the pattern matcher requires every target to match", () => { + // `isWriteAllowedByPatterns` matches with `every` across the whole target + // list (PR 2816 round 2, thread r4797633120). A native-target write + // carries `notes.md` and `notes.png`, so only a pattern per target + // approves; a list that misses one candidate asks. Without the approve + // case, `every` could decay to `some` and the matrix would not notice: + // its approve invariant only checks that a pattern or consent exists. + const patternInput: Input = { + lexicalOutside: true, + realOutside: true, + nativeTarget: true, + allCandidatesChecked: true, + writtenOutside: true, + allowWrite: false, + allowOutsideWrite: false, + allowProtected: false, + protected: false, + patternMatched: true, + } + writeOracle(patternInput.realOutside) + + it.each([ + { name: "a pattern per target approves", files: ["notes.md", "notes.png"], expected: "approve" }, + { name: "a pattern for one target asks", files: ["notes.md"], expected: "ask" }, + ])("with alwaysAllowWrite off and one target outside the workspace, $name", async ({ files, expected }) => { + const result = await checkAutoApproval({ + state: { + ...baseState, + alwaysAllowWrite: false, + alwaysAllowWriteOutsideWorkspace: false, + // A pattern equal to each target's own absolutePath matches under + // both platforms' path rules; a bare name or `**/` glob does not + // match the drive-absolute form `path.resolve` yields on Windows. + allowedWriteFiles: files.map((file) => path.resolve(CWD, file)), + }, + cwd: CWD, + ask: "tool", + text: JSON.stringify({ + tool: "editedExistingFile", + path: "notes.md", + isOutsideWorkspace: true, + isProtected: false, + }), + isProtected: false, + fileTargets: ["notes.md", "notes.png"].map((file): ApprovalFileTarget => ({ + absolutePath: path.resolve(CWD, file), + isOutsideWorkspace: true, + })), + }) + + expect(result.decision).toBe(expected) + }) + }) +}) diff --git a/src/core/auto-approval/__tests__/workspaceContainment.spec.ts b/src/core/auto-approval/__tests__/workspaceContainment.spec.ts new file mode 100644 index 0000000000..0b586ee859 --- /dev/null +++ b/src/core/auto-approval/__tests__/workspaceContainment.spec.ts @@ -0,0 +1,299 @@ +// npx vitest run core/auto-approval/__tests__/workspaceContainment.spec.ts + +import * as fs from "fs/promises" +import os from "os" +import path from "path" + +import { getReadablePath } from "../../../utils/path" +import { isPathOutsideWorkspace } from "../../../utils/pathUtils" +import { checkAutoApproval } from ".." +import { imageWriteTargets } from "../../tools/helpers/approvalFileTarget" +import { baseState, setWorkspaceFolders, type State } from "./fixtures" + +/** + * A workspace with three directory links in its root: one to a folder outside + * the workspace, one to a folder inside it, and one dangling. + */ +async function makeWorkspace() { + const temp = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "zoo-workspace-containment-"))) + const workspace = path.join(temp, "workspace") + const outside = path.join(temp, "outside") + await fs.mkdir(path.join(workspace, "src"), { recursive: true }) + await fs.mkdir(path.join(outside, "config"), { recursive: true }) + // A directory junction also works on Windows without symlink privileges. + await fs.symlink(outside, path.join(workspace, "linked-outside"), "junction") + await fs.symlink(path.join(workspace, "src"), path.join(workspace, "linked-inside"), "junction") + await fs.symlink(path.join(temp, "missing"), path.join(workspace, "dangling"), "junction") + setWorkspaceFolders(workspace) + return { temp, workspace, outside } +} + +type Tree = Awaited> + +/** Run `test` against a fresh workspace, then remove it and the folder list. */ +async function withWorkspace(test: (tree: Tree) => Promise) { + const tree = await makeWorkspace() + try { + await test(tree) + } finally { + setWorkspaceFolders() + await fs.rm(tree.temp, { recursive: true, force: true }) + } +} + +/** + * The ask a write tool sends for `relPath`: the display path, the lexical + * flag, and the native target every write tool passes through the approval + * context. `nativeTarget: false` sends the shape the tools sent before, which + * names the file by display path alone. + */ +const askToWrite = async ( + workspace: string, + relPath: string, + tool: string, + state: Partial, + nativeTarget = true, +) => { + const absolutePath = path.resolve(workspace, relPath) + const isOutsideWorkspace = isPathOutsideWorkspace(absolutePath) + + return checkAutoApproval({ + state: { ...baseState, alwaysAllowWrite: true, ...state }, + cwd: workspace, + ask: "tool", + text: JSON.stringify({ + tool, + path: getReadablePath(workspace, relPath), + isOutsideWorkspace, + isProtected: false, + }), + ...(nativeTarget ? { fileTargets: [{ absolutePath, isOutsideWorkspace }] } : {}), + }) +} + +/** The ask `generate_image` sends for `relPath`, with every file the tool may write. */ +const askToGenerate = async (workspace: string, relPath: string, state: Partial, nativeTarget = true) => { + const [requested, ...suffixed] = imageWriteTargets(workspace, relPath) + + return checkAutoApproval({ + state: { ...baseState, alwaysAllowWrite: true, ...state }, + cwd: workspace, + ask: "tool", + text: JSON.stringify({ + tool: "generateImage", + path: getReadablePath(workspace, relPath), + isOutsideWorkspace: requested.isOutsideWorkspace, + isProtected: false, + }), + ...(nativeTarget ? { fileTargets: [requested, ...suffixed] } : {}), + }) +} + +describe("workspace containment for write auto-approval", () => { + it.each(["newFileCreated", "editedExistingFile", "appliedDiff", "generateImage"])( + "asks before a %s to a new file through a link that leaves the workspace", + async (tool) => + withWorkspace(async ({ workspace }) => { + // The lexical check classifies the path as inside the workspace, + // so `alwaysAllowWrite` alone approved the write before the fix. + expect(isPathOutsideWorkspace(path.resolve(workspace, "linked-outside/config/new.json"))).toBe(false) + expect(await askToWrite(workspace, "linked-outside/config/new.json", tool, {})).toEqual({ + decision: "ask", + }) + }), + ) + + it("asks before a write to an existing file through a link that leaves the workspace", async () => + withWorkspace(async ({ workspace, outside }) => { + await fs.writeFile(path.join(outside, "config", "existing.json"), "{}") + expect(await askToWrite(workspace, "linked-outside/config/existing.json", "newFileCreated", {})).toEqual({ + decision: "ask", + }) + })) + + it("asks before a write through a dangling link in the workspace", async () => + withWorkspace(async ({ workspace }) => { + // Nothing resolves the target, so containment fails closed. + expect(await askToWrite(workspace, "dangling/new.json", "newFileCreated", {})).toEqual({ + decision: "ask", + }) + })) + + it("still approves a write inside the workspace", async () => + withWorkspace(async ({ workspace }) => { + expect(await askToWrite(workspace, "src/new.json", "newFileCreated", {})).toEqual({ + decision: "approve", + }) + })) + + it("still approves a write through a link that stays inside the workspace", async () => + withWorkspace(async ({ workspace }) => { + expect(await askToWrite(workspace, "linked-inside/new.json", "newFileCreated", {})).toEqual({ + decision: "approve", + }) + })) + + it("approves the write through the link when alwaysAllowWriteOutsideWorkspace is on", async () => + withWorkspace(async ({ workspace }) => { + expect( + await askToWrite(workspace, "linked-outside/config/new.json", "newFileCreated", { + alwaysAllowWriteOutsideWorkspace: true, + }), + ).toEqual({ decision: "approve" }) + })) + + it("approves the write through the link when an allowedWriteFiles pattern names it", async () => + withWorkspace(async ({ workspace }) => { + // A pattern names its location, so it also stands in for the outside-workspace toggle. + expect( + await askToWrite(workspace, "linked-outside/config/new.json", "newFileCreated", { + allowedWriteFiles: ["linked-outside/**"], + }), + ).toEqual({ decision: "approve" }) + })) + + it("keeps asking for a write that the lexical check already reports outside", async () => + withWorkspace(async ({ workspace }) => { + expect(await askToWrite(workspace, "../outside/config/new.json", "newFileCreated", {})).toEqual({ + decision: "ask", + }) + })) + + describe("a payload that names no native target", () => { + // The write tools sent this shape before round 1 of PR 2816. The gate + // resolved the display path against the cwd, and a display path is not + // always the file written, so the containment check cannot vouch for + // the write. It fails closed: the write counts as leaving the workspace. + it("asks for a write inside the workspace", async () => + withWorkspace(async ({ workspace }) => { + expect(await askToWrite(workspace, "src/new.json", "newFileCreated", {}, false)).toEqual({ + decision: "ask", + }) + })) + + it("asks for a write through a link that stays inside the workspace", async () => + withWorkspace(async ({ workspace }) => { + expect(await askToWrite(workspace, "linked-inside/new.json", "newFileCreated", {}, false)).toEqual({ + decision: "ask", + }) + })) + + it("approves it when alwaysAllowWriteOutsideWorkspace is on", async () => + withWorkspace(async ({ workspace }) => { + expect( + await askToWrite( + workspace, + "src/new.json", + "newFileCreated", + { alwaysAllowWriteOutsideWorkspace: true }, + false, + ), + ).toEqual({ decision: "approve" }) + })) + }) + + describe.skipIf(process.platform === "win32")("a directory whose name holds a backslash", () => { + // On POSIX a backslash is an ordinary filename character, and + // `getReadablePath` rewrites it into a separator for the chat. A write to + // `a\b/file.json` therefore displays as `a/b/file.json`, a different + // directory. Windows has no such filename: there `a\b` is the directory + // `b` inside `a`, and the display path names the file written. + + /** A workspace where `a\b` links outside and `c\d` links to the inside `src`. */ + async function withBackslashWorkspace( + test: (tree: Tree & { backslash: string; inside: string }) => Promise, + ) { + await withWorkspace(async (tree) => { + const backslash = "a\\b" + const inside = "c\\d" + // `a/b` exists inside the workspace, so the display path resolves to an inside file. + await fs.mkdir(path.join(tree.workspace, "a", "b"), { recursive: true }) + await fs.symlink(tree.outside, path.join(tree.workspace, backslash), "junction") + await fs.symlink(path.join(tree.workspace, "src"), path.join(tree.workspace, inside), "junction") + await test({ ...tree, backslash, inside }) + }) + } + + it("asks before a write through a backslash-named link that leaves the workspace", async () => + withBackslashWorkspace(async ({ workspace, backslash }) => { + const relPath = `${backslash}/file.json` + // The display path names the inside directory `a/b`, so the lexical + // check and the realpath of the display path both say inside. Only the + // native target tells the gate which file the tool writes. + expect(getReadablePath(workspace, relPath)).toBe("a/b/file.json") + expect(isPathOutsideWorkspace(path.resolve(workspace, getReadablePath(workspace, relPath)))).toBe(false) + expect(await askToWrite(workspace, relPath, "appliedDiff", {})).toEqual({ decision: "ask" }) + })) + + it("approves it when alwaysAllowWriteOutsideWorkspace is on", async () => + withBackslashWorkspace(async ({ workspace, backslash }) => { + expect( + await askToWrite(workspace, `${backslash}/file.json`, "appliedDiff", { + alwaysAllowWriteOutsideWorkspace: true, + }), + ).toEqual({ decision: "approve" }) + })) + + it("approves a write through a backslash-named link that stays inside the workspace", async () => + withBackslashWorkspace(async ({ workspace, inside }) => { + expect(await askToWrite(workspace, `${inside}/new.json`, "newFileCreated", {})).toEqual({ + decision: "approve", + }) + })) + + it("asks for the same write when the payload names the display path alone", async () => + withBackslashWorkspace(async ({ workspace, backslash }) => { + // Resolving `a/b/file.json` against the cwd finds the inside directory + // while the tool writes `a\b/file.json`. Nothing in the payload can + // tell the two apart, so the gate fails closed. + expect(await askToWrite(workspace, `${backslash}/file.json`, "appliedDiff", {}, false)).toEqual({ + decision: "ask", + }) + })) + }) + + describe("generate_image", () => { + // The provider picks the format after the approval, and the tool appends + // `.png` or `.jpg` to a path without an image extension. The approval + // carries every candidate, so a link at one of them is resolved too. + it.each(["preview.png", "preview.jpg"])( + "asks before writing %s when it is a link that leaves the workspace", + async (linked) => + withWorkspace(async ({ workspace, outside }) => { + // A directory link also works on Windows without symlink privileges; + // the gate resolves it through to the outside folder as for a file. + await fs.symlink(outside, path.join(workspace, linked), "junction") + expect(await askToGenerate(workspace, "preview", {})).toEqual({ decision: "ask" }) + }), + ) + + it("asks before writing preview.png when it is a dangling link", async () => + withWorkspace(async ({ workspace, temp }) => { + await fs.symlink(path.join(temp, "missing.png"), path.join(workspace, "preview.png"), "junction") + expect(await askToGenerate(workspace, "preview", {})).toEqual({ decision: "ask" }) + })) + + it("approves when every file it may write is inside the workspace", async () => + withWorkspace(async ({ workspace }) => { + expect(await askToGenerate(workspace, "preview", {})).toEqual({ decision: "approve" }) + })) + + it("approves a suffixed path through a link that stays inside the workspace", async () => + withWorkspace(async ({ workspace }) => { + expect(await askToGenerate(workspace, "linked-inside/preview.png", {})).toEqual({ decision: "approve" }) + })) + + it("approves when the suffixed file leaves the workspace and alwaysAllowWriteOutsideWorkspace is on", async () => + withWorkspace(async ({ workspace, outside }) => { + await fs.symlink(outside, path.join(workspace, "preview.png"), "junction") + expect(await askToGenerate(workspace, "preview", { alwaysAllowWriteOutsideWorkspace: true })).toEqual({ + decision: "approve", + }) + })) + + it("asks for the same write when the payload names the display path alone", async () => + withWorkspace(async ({ workspace }) => { + expect(await askToGenerate(workspace, "preview", {}, false)).toEqual({ decision: "ask" }) + })) + }) +}) diff --git a/src/core/auto-approval/index.ts b/src/core/auto-approval/index.ts index dc2b4fa7a8..da4397630c 100644 --- a/src/core/auto-approval/index.ts +++ b/src/core/auto-approval/index.ts @@ -14,6 +14,7 @@ import path from "path" import type { ApprovalFileTarget } from "../../shared/tools" import { ClineAskResponse } from "../../shared/WebviewMessage" +import { isRealPathOutsideWorkspace } from "../../utils/pathUtils" import { isWriteToolAction, isReadOnlyToolAction } from "./tools" import { isMcpToolAlwaysAllowed } from "./mcp" @@ -72,9 +73,12 @@ function namedFiles(tool: ClineSayTool): { paths: string[]; hasUnnamedFiles: boo * The tool's file targets, if they account for every file its message names. * * Targets replace the display paths for every decision, so they must be - * complete: one valid, absolute target per named file, and no unnamed files. - * Returns `undefined` otherwise, and the caller must ask the user, since an - * incomplete list could leave a touched file unchecked. + * complete: at least one valid, absolute target per named file, and no + * unnamed files. A tool that may write a file its message does not name + * (`generate_image` picks the extension after the provider answers) lists + * that file too, so the gate resolves every candidate. More targets only + * make the check stricter; fewer would leave a named file unchecked. + * Returns `undefined` otherwise, and the caller must ask the user. */ function validFileTargets( tool: ClineSayTool, @@ -82,7 +86,7 @@ function validFileTargets( ): readonly ApprovalFileTarget[] | undefined { const { paths, hasUnnamedFiles } = namedFiles(tool) - if (hasUnnamedFiles || !fileTargets.length || fileTargets.length !== paths.length) { + if (hasUnnamedFiles || !fileTargets.length || fileTargets.length < paths.length) { return undefined } @@ -204,6 +208,38 @@ function isWriteAllowedByPatterns( ) } +/** + * Whether a write action reaches a file whose real target is outside every + * workspace folder. The approval payload carries a lexical flag only. A link + * inside the workspace can lead outside it, and a write through it then rides + * the workspace permission. The realpath check resolves each target through + * the link, and fails closed when nothing resolves the target. + * + * Only write actions take this check. Read actions stay on the payload flag. + * + * A payload without file targets fails closed. Its message names the file by + * display path, and `getReadablePath` has already rewritten that for the + * chat: on POSIX a backslash is an ordinary filename character, and the + * display turns it into a separator, so a directory `a\b` linked outside + * displays as `a/b`. Resolving the display path would then check a file + * inside the workspace while the tool writes outside it. The display path + * cannot be verified to be the file written, so the write counts as leaving + * the workspace and needs the outside consent or a pattern. + */ +async function escapesWorkspaceBySymlink(targets: readonly ApprovalFileTarget[] | undefined): Promise { + // Without targets there is nothing whose real target could be verified. + if (!targets) { + return true + } + + for (const { absolutePath } of targets) { + if (await isRealPathOutsideWorkspace(absolutePath)) { + return true + } + } + return false +} + export type CheckAutoApprovalResult = | { decision: "approve" } /** @@ -234,8 +270,8 @@ export async function checkAutoApproval({ }: { state?: Pick /** - * Workspace root the allowlist patterns and the checked path are resolved - * against. + * Workspace root the allowlist patterns and the display paths of a payload + * without file targets are resolved against. * * Must be the `cwd` of the task this ask belongs to, which is the root the * path in `text` was made relative to. It is not read from `state`, because @@ -490,10 +526,15 @@ export async function checkAutoApproval({ // protected files like `AGENTS.md`. const isAllowedWriteFile = isWriteAllowedByPatterns(tool, targets, cwd, state) + // A lexical "inside" is not final: a link inside the workspace can lead + // outside it. The real target of every file the tool writes decides the + // outside-workspace consent. + const escapesWorkspace = isOutsideWorkspace || (await escapesWorkspaceBySymlink(targets)) + const isWriteAllowed = isAllowedWriteFile || (state.alwaysAllowWrite === true && - (!isOutsideWorkspace || state.alwaysAllowWriteOutsideWorkspace === true)) + (!escapesWorkspace || state.alwaysAllowWriteOutsideWorkspace === true)) return isWriteAllowed && (!isProtected || state.alwaysAllowWriteProtected === true) ? { decision: "approve" } diff --git a/src/core/tools/ApplyDiffTool.ts b/src/core/tools/ApplyDiffTool.ts index b08ef9b6e6..a8f0c02e2c 100644 --- a/src/core/tools/ApplyDiffTool.ts +++ b/src/core/tools/ApplyDiffTool.ts @@ -5,6 +5,7 @@ import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { TelemetryService } from "@roo-code/telemetry" import { getReadablePath } from "../../utils/path" +import { resolveApprovalFileTarget } from "./helpers/approvalFileTarget" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" @@ -171,7 +172,9 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { toolProgressStatus = task.diffStrategy.getProgressStatus(block, diffResult) } - const didApprove = await askApproval("tool", completeMessage, toolProgressStatus, isWriteProtected) + const didApprove = await askApproval("tool", completeMessage, toolProgressStatus, isWriteProtected, { + fileTargets: [resolveApprovalFileTarget(task.cwd, relPath)], + }) if (!didApprove) { return @@ -216,7 +219,9 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { toolProgressStatus = task.diffStrategy.getProgressStatus(block, diffResult) } - const didApprove = await askApproval("tool", completeMessage, toolProgressStatus, isWriteProtected) + const didApprove = await askApproval("tool", completeMessage, toolProgressStatus, isWriteProtected, { + fileTargets: [resolveApprovalFileTarget(task.cwd, relPath)], + }) if (!didApprove) { await task.diffViewProvider.revertChanges() diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 2713e08ffe..3f306022d9 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -4,6 +4,7 @@ import path from "path" import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { getReadablePath } from "../../utils/path" +import { resolveApprovalFileTarget } from "./helpers/approvalFileTarget" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" @@ -201,7 +202,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task.diffViewProvider.scrollToFirstDiff() } - const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected) + const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected, { + fileTargets: [resolveApprovalFileTarget(task.cwd, relPath)], + }) if (!didApprove) { if (!isPreventFocusDisruptionEnabled) { @@ -264,7 +267,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { isProtected: isWriteProtected, } satisfies ClineSayTool) - const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected) + const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected, { + fileTargets: [resolveApprovalFileTarget(task.cwd, relPath)], + }) if (!didApprove) { pushToolResult("Delete operation was rejected by the user.") @@ -358,7 +363,12 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task.diffViewProvider.scrollToFirstDiff() } - const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected) + const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected, { + // A move writes the new content to `movePath` as well, so both files are gated. + fileTargets: [relPath, ...(change.movePath ? [change.movePath] : [])].map((file) => + resolveApprovalFileTarget(task.cwd, file), + ), + }) if (!didApprove) { if (!isPreventFocusDisruptionEnabled) { diff --git a/src/core/tools/EditFileTool.ts b/src/core/tools/EditFileTool.ts index a7301e2ac9..865160a9f1 100644 --- a/src/core/tools/EditFileTool.ts +++ b/src/core/tools/EditFileTool.ts @@ -4,6 +4,7 @@ import path from "path" import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { getReadablePath } from "../../utils/path" +import { resolveApprovalFileTarget } from "./helpers/approvalFileTarget" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" @@ -422,7 +423,9 @@ export class EditFileTool extends BaseTool<"edit_file"> { task.diffViewProvider.scrollToFirstDiff() } - const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected) + const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected, { + fileTargets: [resolveApprovalFileTarget(task.cwd, relPath)], + }) if (!didApprove) { // Revert changes if diff view was shown diff --git a/src/core/tools/EditTool.ts b/src/core/tools/EditTool.ts index 895b929ed2..7b6aa2fcb9 100644 --- a/src/core/tools/EditTool.ts +++ b/src/core/tools/EditTool.ts @@ -4,6 +4,7 @@ import path from "path" import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { getReadablePath } from "../../utils/path" +import { resolveApprovalFileTarget } from "./helpers/approvalFileTarget" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" @@ -197,7 +198,9 @@ export class EditTool extends BaseTool<"edit"> { task.diffViewProvider.scrollToFirstDiff() } - const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected) + const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected, { + fileTargets: [resolveApprovalFileTarget(task.cwd, relPath)], + }) if (!didApprove) { // Revert changes if diff view was shown diff --git a/src/core/tools/GenerateImageTool.ts b/src/core/tools/GenerateImageTool.ts index dca63a1ef4..10e2104c62 100644 --- a/src/core/tools/GenerateImageTool.ts +++ b/src/core/tools/GenerateImageTool.ts @@ -12,6 +12,7 @@ import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" import { fileExistsAtPath } from "../../utils/fs" import { getReadablePath } from "../../utils/path" +import { IMAGE_EXTENSION_PATTERN, imageWriteTargets } from "./helpers/approvalFileTarget" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { EXPERIMENT_IDS, experiments } from "../../shared/experiments" import { OpenRouterHandler } from "../../api/providers/openrouter" @@ -161,6 +162,9 @@ export class GenerateImageTool extends BaseTool<"generate_image"> { const fullPath = path.resolve(task.cwd, relPath) const isOutsideWorkspace = isPathOutsideWorkspace(fullPath) + // The provider picks the format after the approval, so every file the tool may + // write is gated, not the requested path alone. + const fileTargets = imageWriteTargets(task.cwd, relPath) const sharedMessageProps = { tool: "generateImage" as const, @@ -179,7 +183,9 @@ export class GenerateImageTool extends BaseTool<"generate_image"> { ...(inputImagePath && { inputImage: getReadablePath(task.cwd, inputImagePath) }), }) - const didApprove = await askApproval("tool", approvalMessage, undefined, isWriteProtected) + const didApprove = await askApproval("tool", approvalMessage, undefined, isWriteProtected, { + fileTargets, + }) if (!didApprove) { return @@ -221,7 +227,7 @@ export class GenerateImageTool extends BaseTool<"generate_image"> { const base64Data = base64Match[2] let finalPath = relPath - if (!finalPath.match(/\.(png|jpg|jpeg)$/i)) { + if (!finalPath.match(IMAGE_EXTENSION_PATTERN)) { finalPath = `${finalPath}.${imageFormat === "jpeg" ? "jpg" : imageFormat}` } diff --git a/src/core/tools/SearchReplaceTool.ts b/src/core/tools/SearchReplaceTool.ts index a0f2dadfcc..404e7bbc02 100644 --- a/src/core/tools/SearchReplaceTool.ts +++ b/src/core/tools/SearchReplaceTool.ts @@ -4,6 +4,7 @@ import path from "path" import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { getReadablePath } from "../../utils/path" +import { resolveApprovalFileTarget } from "./helpers/approvalFileTarget" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" @@ -193,7 +194,9 @@ export class SearchReplaceTool extends BaseTool<"search_replace"> { task.diffViewProvider.scrollToFirstDiff() } - const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected) + const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected, { + fileTargets: [resolveApprovalFileTarget(task.cwd, relPath)], + }) if (!didApprove) { // Revert changes if diff view was shown diff --git a/src/core/tools/WriteToFileTool.ts b/src/core/tools/WriteToFileTool.ts index 0c5c80abb9..4742534e40 100644 --- a/src/core/tools/WriteToFileTool.ts +++ b/src/core/tools/WriteToFileTool.ts @@ -9,6 +9,7 @@ import { RecordSource } from "../context-tracking/FileContextTrackerTypes" import { fileExistsAtPath, createDirectoriesForFile } from "../../utils/fs" import { stripLineNumbers, everyLineHasLineNumbers } from "../../integrations/misc/extract-text" import { getReadablePath } from "../../utils/path" +import { resolveApprovalFileTarget } from "./helpers/approvalFileTarget" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { unescapeHtmlEntities } from "../../utils/text-normalization" import { EXPERIMENT_IDS, experiments } from "../../shared/experiments" @@ -126,7 +127,9 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> { diffStats: computeDiffStats(unified) || undefined, } satisfies ClineSayTool) - const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected) + const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected, { + fileTargets: [resolveApprovalFileTarget(task.cwd, relPath)], + }) if (!didApprove) { return @@ -157,7 +160,9 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> { diffStats: computeDiffStats(unified) || undefined, } satisfies ClineSayTool) - const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected) + const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected, { + fileTargets: [resolveApprovalFileTarget(task.cwd, relPath)], + }) if (!didApprove) { await task.diffViewProvider.revertChanges() diff --git a/src/core/tools/__tests__/applyDiffTool.outsideWorkspace.spec.ts b/src/core/tools/__tests__/applyDiffTool.outsideWorkspace.spec.ts index bf27e65ce6..157b568d8c 100644 --- a/src/core/tools/__tests__/applyDiffTool.outsideWorkspace.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.outsideWorkspace.spec.ts @@ -5,8 +5,8 @@ import path from "path" import type { ClineSayTool } from "@roo-code/types" -import type { ToolUse } from "../../../shared/tools" -import { isPathOutsideWorkspace } from "../../../utils/pathUtils" +import type { ToolUse, AutoApprovalContext } from "../../../shared/tools" +import { isPathOutsideWorkspace, isRealPathOutsideWorkspace } from "../../../utils/pathUtils" import { checkAutoApproval } from "../../auto-approval" import { baseState } from "../../auto-approval/__tests__/fixtures" import type { Task } from "../../task/Task" @@ -39,6 +39,7 @@ vi.mock("../../../utils/path", () => ({ vi.mock("../../../utils/pathUtils", () => ({ isPathOutsideWorkspace: vi.fn(), + isRealPathOutsideWorkspace: vi.fn(), })) vi.mock("../../prompts/responses", () => ({ @@ -150,6 +151,8 @@ describe("ApplyDiffTool isOutsideWorkspace", () => { beforeEach(() => { vi.clearAllMocks() vi.mocked(isPathOutsideWorkspace).mockReset() + // No link escapes the workspace unless a case says so. + vi.mocked(isRealPathOutsideWorkspace).mockReset().mockResolvedValue(false) applyDiffTool.resetPartialState() vi.mocked(fs.readFile).mockResolvedValue("old\n") askApproval = vi.fn().mockResolvedValue(true) @@ -197,6 +200,7 @@ describe("ApplyDiffTool isOutsideWorkspace", () => { ])("marks $name the workspace and returns $expected", async ({ relPath, isOutside, expected }) => { const actual = await vi.importActual("../../../utils/pathUtils") vi.mocked(isPathOutsideWorkspace).mockImplementation(actual.isPathOutsideWorkspace) + vi.mocked(isRealPathOutsideWorkspace).mockImplementation(actual.isRealPathOutsideWorkspace) await applyDiffTool.execute({ path: relPath, diff: DIFF }, createTask(), { askApproval, @@ -209,11 +213,16 @@ describe("ApplyDiffTool isOutsideWorkspace", () => { const payload = JSON.parse(text) as ClineSayTool expect(payload.isOutsideWorkspace).toBe(isOutside) + // The tool passes the native target through the approval context; the + // gate decides on it, so the re-check carries it as the caller does. + const context = askApproval.mock.calls[0][4] as AutoApprovalContext | undefined + const result = await checkAutoApproval({ state: { ...baseState, alwaysAllowWrite: true }, cwd: CWD, ask: "tool", text, + fileTargets: context?.fileTargets, }) expect(result).toEqual({ decision: expected }) }) @@ -224,10 +233,35 @@ describe("ApplyDiffTool isOutsideWorkspace", () => { { ...cases[0], allowOutside: false, expected: "ask" }, { ...cases[0], allowOutside: true, expected: "approve" }, { ...cases[1], allowOutside: false, expected: "approve" }, + // A link inside the workspace leads outside it. The payload keeps the + // lexical verdict, so only the real target can hold the write back. + { + name: "a file behind a link to outside the workspace", + relPath: INSIDE_PATH, + isOutside: false, + realOutside: true, + allowOutside: false, + expected: "ask", + }, + { + name: "a file behind a link to outside the workspace", + relPath: INSIDE_PATH, + isOutside: false, + realOutside: true, + allowOutside: true, + expected: "approve", + }, ])( "returns $expected for $name when alwaysAllowWriteOutsideWorkspace is $allowOutside", - async ({ relPath, isOutside, allowOutside, expected }) => { + async ({ relPath, isOutside, realOutside, allowOutside, expected }) => { const text = await runExecute(relPath, isOutside) + if (realOutside !== undefined) { + vi.mocked(isRealPathOutsideWorkspace).mockResolvedValue(realOutside) + } + + // The tool passes the native target through the approval context; + // the gate decides on it, so the re-check carries it as the caller does. + const context = askApproval.mock.calls[0][4] as AutoApprovalContext | undefined const result = await checkAutoApproval({ state: { @@ -238,6 +272,7 @@ describe("ApplyDiffTool isOutsideWorkspace", () => { cwd: CWD, ask: "tool", text, + fileTargets: context?.fileTargets, }) expect(result).toEqual({ decision: expected }) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index eb89838cad..71b426092f 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -1,15 +1,21 @@ // npx vitest run core/tools/__tests__/applyPatchTool.execute.spec.ts +import fs from "fs/promises" +import path from "path" + import type { MockedFunction } from "vitest" import { fileExistsAtPath } from "../../../utils/fs" import { isPathOutsideWorkspace } from "../../../utils/pathUtils" +import type { ApprovalFileTarget } from "../../../shared/tools" import type { Task } from "../../task/Task" import { ApplyPatchTool } from "../ApplyPatchTool" vi.mock("fs/promises", () => ({ default: { readFile: vi.fn().mockResolvedValue("original file content\n"), + mkdir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), unlink: vi.fn().mockResolvedValue(undefined), }, })) @@ -95,3 +101,157 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockTask.recordToolError).not.toHaveBeenCalled() }) }) + +describe("ApplyPatchTool.execute - approval file targets", () => { + const mockedFileExistsAtPath = fileExistsAtPath as MockedFunction + const mockedIsPathOutsideWorkspace = isPathOutsideWorkspace as MockedFunction + + let tool: ApplyPatchTool + let mockTask: Pick< + Task, + | "cwd" + | "consecutiveMistakeCount" + | "recordToolUsage" + | "recordToolError" + | "rooIgnoreController" + | "rooProtectedController" + | "say" + | "processQueuedMessages" + | "didEditFile" + | "diffViewProvider" + | "fileContextTracker" + | "providerRef" + > + let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise> + let mockHandleError: MockedFunction<(...args: unknown[]) => Promise> + let mockPushToolResult: MockedFunction<(...args: unknown[]) => void> + + // The auto-approval context is the fifth askApproval argument; the + // approval must name every file this call site may write. + const approvalTargets = (): readonly ApprovalFileTarget[] => { + const context = mockAskApproval.mock.calls[0]?.[4] as + { fileTargets?: readonly ApprovalFileTarget[] } | undefined + return context?.fileTargets ?? [] + } + + beforeEach(() => { + vi.clearAllMocks() + + mockedFileExistsAtPath.mockResolvedValue(true) + mockedIsPathOutsideWorkspace.mockReturnValue(false) + + mockTask = { + cwd: "/workspace/project", + consecutiveMistakeCount: 0, + recordToolUsage: vi.fn(), + recordToolError: vi.fn(), + rooIgnoreController: { + validateAccess: vi.fn().mockReturnValue(true), + } as unknown as Task["rooIgnoreController"], + rooProtectedController: { + isWriteProtected: vi.fn().mockReturnValue(false), + } as unknown as Task["rooProtectedController"], + say: vi.fn().mockResolvedValue(undefined), + processQueuedMessages: vi.fn(), + didEditFile: false, + diffViewProvider: { + editType: undefined, + originalContent: undefined, + open: vi.fn().mockResolvedValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + scrollToFirstDiff: vi.fn(), + revertChanges: vi.fn().mockResolvedValue(undefined), + saveChanges: vi.fn().mockResolvedValue({ newProblemsMessage: "", userEdits: null, finalContent: "" }), + pushToolWriteResult: vi.fn().mockResolvedValue("Tool result message"), + reset: vi.fn().mockResolvedValue(undefined), + } as unknown as Task["diffViewProvider"], + fileContextTracker: { + trackFileContext: vi.fn().mockResolvedValue(undefined), + } as unknown as Task["fileContextTracker"], + providerRef: { + deref: vi.fn().mockReturnValue(undefined), + } as unknown as Task["providerRef"], + } + + mockAskApproval = vi.fn().mockResolvedValue(true) + mockHandleError = vi.fn().mockResolvedValue(undefined) + mockPushToolResult = vi.fn() + + tool = new ApplyPatchTool() + }) + + it("gates the created file when an add patch is approved", async () => { + mockedFileExistsAtPath.mockResolvedValue(false) + const patch = `*** Begin Patch +*** Add File: src/new.ts ++export const value = 1 +*** End Patch` + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockAskApproval).toHaveBeenCalled() + expect(mockHandleError).not.toHaveBeenCalled() + expect(approvalTargets()).toStrictEqual([ + { absolutePath: path.resolve("/workspace/project", "src/new.ts"), isOutsideWorkspace: false }, + ]) + expect(mockTask.didEditFile).toBe(true) + }) + + it("gates only the patched file when an in-place update is approved", async () => { + const patch = `*** Begin Patch +*** Update File: src/a.ts +@@ +-original file content ++updated file content +*** End Patch` + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockAskApproval).toHaveBeenCalled() + expect(mockHandleError).not.toHaveBeenCalled() + expect(approvalTargets()).toStrictEqual([ + { absolutePath: path.resolve("/workspace/project", "src/a.ts"), isOutsideWorkspace: false }, + ]) + expect(mockTask.diffViewProvider.saveChanges).toHaveBeenCalled() + }) + + it("gates both the patched file and its move destination when a move is approved", async () => { + const patch = `*** Begin Patch +*** Update File: src/a.ts +*** Move to: src/b.ts +@@ +-original file content ++updated file content +*** End Patch` + + await tool.execute({ patch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockAskApproval).toHaveBeenCalled() + expect(mockHandleError).not.toHaveBeenCalled() + expect(approvalTargets()).toStrictEqual([ + { absolutePath: path.resolve("/workspace/project", "src/a.ts"), isOutsideWorkspace: false }, + { absolutePath: path.resolve("/workspace/project", "src/b.ts"), isOutsideWorkspace: false }, + ]) + expect(vi.mocked(fs.writeFile)).toHaveBeenCalledWith( + path.resolve("/workspace/project", "src/b.ts"), + expect.stringContaining("updated file content"), + "utf8", + ) + expect(vi.mocked(fs.unlink)).toHaveBeenCalledWith(path.resolve("/workspace/project", "src/a.ts")) + }) +}) diff --git a/src/core/tools/__tests__/generateImageTool.test.ts b/src/core/tools/__tests__/generateImageTool.test.ts index 5c4a9d7f72..c26a30a085 100644 --- a/src/core/tools/__tests__/generateImageTool.test.ts +++ b/src/core/tools/__tests__/generateImageTool.test.ts @@ -1,3 +1,4 @@ +import * as path from "path" import { describe, it, expect, vi, beforeEach } from "vitest" import { generateImageTool } from "../GenerateImageTool" import { ToolUse } from "../../../shared/tools" @@ -419,4 +420,48 @@ describe("generateImageTool", () => { expect(OpenRouterHandler).not.toHaveBeenCalled() }) }) + + describe("approval file targets", () => { + it("gates every suffix candidate for an extension-less path and writes the suffixed file", async () => { + const completeBlock: ToolUse = { + type: "tool_use", + name: "generate_image", + params: { prompt: "Generate a test image", path: "test-image" }, + nativeArgs: { prompt: "Generate a test image", path: "test-image" }, + partial: false, + } + + const mockGenerateImage = vi.fn().mockResolvedValue({ + success: true, + imageData: "data:image/jpeg;base64,fakebase64data", + }) + + vi.mocked(OpenRouterHandler).mockImplementation(function () { + // Double assertion: the tool under test only calls generateImage. + return { generateImage: mockGenerateImage } as unknown as OpenRouterHandler + }) + + await generateImageTool.handle(mockCline as Task, completeBlock as ToolUse<"generate_image">, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + // The provider picks the format after the approval, so the approval + // must name the bare path plus every suffixed candidate. + const context = mockAskApproval.mock.calls[0]?.[4] as + { fileTargets?: readonly { absolutePath: string; isOutsideWorkspace: boolean }[] } | undefined + expect(context?.fileTargets?.map((target) => target.absolutePath)).toEqual([ + path.resolve("/test/workspace", "test-image"), + path.resolve("/test/workspace", "test-image.png"), + path.resolve("/test/workspace", "test-image.jpg"), + ]) + expect(context?.fileTargets?.every((target) => target.isOutsideWorkspace === false)).toBe(true) + expect(vi.mocked(fs.writeFile)).toHaveBeenCalledWith( + path.resolve("/test/workspace", "test-image.jpg"), + expect.any(Buffer), + ) + }) + }) }) diff --git a/src/core/tools/__tests__/writeToFileTool.spec.ts b/src/core/tools/__tests__/writeToFileTool.spec.ts index 7cb9d01585..14b8660882 100644 --- a/src/core/tools/__tests__/writeToFileTool.spec.ts +++ b/src/core/tools/__tests__/writeToFileTool.spec.ts @@ -7,6 +7,7 @@ import { isPathOutsideWorkspace } from "../../../utils/pathUtils" import { getReadablePath } from "../../../utils/path" import { unescapeHtmlEntities } from "../../../utils/text-normalization" import { everyLineHasLineNumbers, stripLineNumbers } from "../../../integrations/misc/extract-text" +import { EXPERIMENT_IDS } from "../../../shared/experiments" import { ToolUse, ToolResponse, AskApproval, HandleError, PushToolResult } from "../../../shared/tools" import { writeToFileTool } from "../WriteToFileTool" @@ -473,4 +474,36 @@ describe("writeToFileTool", () => { expect(mockHandleError).toHaveBeenCalledWith("handling partial write_to_file", expect.any(Error)) }) }) + + describe("approval file targets", () => { + it("gates the written file when the focus-disruption experiment saves directly", async () => { + mockCline.providerRef.deref().getState = vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + experiments: { [EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION]: true }, + }) + mockCline.diffViewProvider.saveDirectly = vi.fn().mockResolvedValue(undefined) + mockCline.processQueuedMessages = vi.fn() + + await executeWriteFileTool() + + expect(mockAskApproval).toHaveBeenCalled() + const context = mockAskApproval.mock.calls[0]?.[4] as + { fileTargets?: readonly { absolutePath: string; isOutsideWorkspace: boolean }[] } | undefined + // The helper resolves with the real path module, so pin the resolved + // file by suffix instead of a drive-letter-dependent constant. + expect(context?.fileTargets?.map((target) => target.isOutsideWorkspace)).toStrictEqual([false]) + expect(context?.fileTargets?.map((target) => target.absolutePath)).toEqual([ + expect.stringMatching(/[\\/]test[\\/]file\.txt$/), + ]) + expect(mockCline.diffViewProvider.saveDirectly).toHaveBeenCalledWith( + testFilePath, + testContent, + false, + true, + 1000, + ) + expect(mockCline.diffViewProvider.open).not.toHaveBeenCalled() + }) + }) }) diff --git a/src/core/tools/helpers/approvalFileTarget.ts b/src/core/tools/helpers/approvalFileTarget.ts index 5cfe086d49..dbc2eadc1b 100644 --- a/src/core/tools/helpers/approvalFileTarget.ts +++ b/src/core/tools/helpers/approvalFileTarget.ts @@ -14,3 +14,21 @@ export function resolveApprovalFileTarget(cwd: string, relPath: string): Approva return { absolutePath, isOutsideWorkspace: isPathOutsideWorkspace(absolutePath) } } + +/** The file extensions `generate_image` leaves a path as it is. */ +export const IMAGE_EXTENSION_PATTERN = /\.(png|jpg|jpeg)$/i + +/** + * Every file `generate_image` may write for a requested path. + * + * The provider picks the format after the approval, and the tool appends the + * extension to a path without one (`GenerateImageTool`, where a JPEG is + * written as `.jpg`). The approval therefore has to gate every suffixed + * candidate: a link at `preview.png` must not ride an approval that resolved + * `preview` alone. + */ +export function imageWriteTargets(cwd: string, relPath: string): ApprovalFileTarget[] { + const candidates = IMAGE_EXTENSION_PATTERN.test(relPath) ? [relPath] : [relPath, `${relPath}.png`, `${relPath}.jpg`] + + return candidates.map((candidate) => resolveApprovalFileTarget(cwd, candidate)) +} diff --git a/src/shared/tools.ts b/src/shared/tools.ts index ba799efe9c..e0b0ce0fd5 100644 --- a/src/shared/tools.ts +++ b/src/shared/tools.ts @@ -34,10 +34,15 @@ export type AutoApprovalContext = { */ dcgDecision?: DcgDecision /** - * Every file the tool action will access, one entry per file named in the - * ask message (`tool` asks only). When present, auto-approval decides on - * these targets instead of the message's display paths, and asks the user - * if they are invalid or do not cover every named file. + * Every file the tool action will access, at least one entry per file named + * in the ask message (`tool` asks only). A tool that may write a file its + * message does not name (`generate_image` appends the extension after the + * provider answers) lists that file too, so every candidate is checked. + * When present, auto-approval decides on these targets instead of the + * message's display paths, and asks the user if they are invalid or do not + * cover every named file. A write without targets is never auto-approved + * by the workspace permission alone: a display path cannot be verified to + * be the file written. */ fileTargets?: readonly ApprovalFileTarget[] }