Skip to content

Commit bf09481

Browse files
fix(guarded-write): bind the allowlist decision to the retained publish target
The apply-diff save path validated only the caller's alias: the tool layer ran validateAccess on relPath, while the guard resolved that alias under the lock and published the resolved target without re-running the access decision. A symlink retargeted after the tool's check - or a hard-link alias whose new referent keeps the expected version token - could therefore receive the approved bytes in an ignored or external file. The guard also held only the referent lock, so a protocol writer that swaps the link entry itself was not serialized against the publish. replaceIfVersion and createIfAbsent now take an authorizeTarget callback, run under the lock on the RETAINED publish target before the version comparison and the publish, and take both identity locks - the referent key and the alias-entry key (resolveLinkPathLockKey, the same pair and folding safeWriteJson's dual-link path uses) - in the shared sorted order when they differ. The guarded-write entry passes a callback that re-runs rooIgnoreController.validateAccess on the retained target, so the allowlist decision covers the exact file the publish acts on; the retained target is what safeWriteText already receives, unchanged. Tests: denial before the version comparison (no token read, no publish), the decision running on the retained target rather than the alias, the end-to-end alias-passes/referent-ignored rejection through guardedWrite, and the sorted dual-key acquisition with the single-lock fold case. Negative controls: removing either authorize call reddens its path's tests, authorizing the alias instead of the retained target reddens exactly the binding test, and dropping to a single referent lock reddens exactly the sorted-order test. 62/62 guardedWrite, 239/239 with the diff-view suites.
1 parent 096abc2 commit bf09481

3 files changed

Lines changed: 190 additions & 8 deletions

File tree

‎src/core/tools/__tests__/guardedWrite.spec.ts‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ vi.mock("../../../utils/versionToken", () => ({
3636
vi.mock("../../../services/file-safety/safeWriteText", () => ({
3737
safeWriteText: vi.fn(),
3838
resolveLockKey: vi.fn(async (p: string) => p),
39+
// The dual-identity lock takes this alias-entry key beside the referent
40+
// key; the identity default folds both to one (a single lock, as every
41+
// pre-existing test expects), and the sorted-order test overrides it.
42+
resolveLinkPathLockKey: vi.fn(async (p: string) => p),
3943
// The guard fixes the publish target inside the lock through this helper;
4044
// the default identity keeps every other test's path unchanged.
4145
resolvePublishTarget: vi.fn(async (p: string) => p),
@@ -75,6 +79,10 @@ interface MockTaskOptions {
7579
cwd?: string
7680
observationRegistry?: ObservationRegistry
7781
abort?: boolean
82+
// The guard re-runs the allowlist decision on the retained publish target;
83+
// the default double allows everything, and the alias-binding tests supply a
84+
// controller that denies the resolved target.
85+
rooIgnoreController?: { validateAccess: (filePath: string) => boolean }
7886
}
7987

8088
/**
@@ -87,6 +95,7 @@ function createMockTask(options: MockTaskOptions = {}): Task {
8795
cwd: options.cwd ?? WORKSPACE,
8896
abort: options.abort ?? false,
8997
observationRegistry: options.observationRegistry ?? new ObservationRegistry(),
98+
...(options.rooIgnoreController ? { rooIgnoreController: options.rooIgnoreController } : {}),
9099
}
91100
return task as unknown as Task
92101
}
@@ -1022,4 +1031,109 @@ describe("guardedWrite (S4a, epic #1375)", () => {
10221031
expect(staleError?.path).toBe("src/thing.ts")
10231032
expect(mockedSafeWriteText).not.toHaveBeenCalled()
10241033
})
1034+
1035+
describe("allowlist binding to the retained publish target", () => {
1036+
// The tool layer validates the alias the caller named. The guard must
1037+
// re-run that decision on the retained target under the lock, and lock
1038+
// both the alias entry and the resolved referent, or a link retargeted
1039+
// after the tool's check sends the approved bytes to an ignored or
1040+
// external file.
1041+
1042+
it("replaceIfVersion stops when the retained target fails the allowlist, before the version comparison", async () => {
1043+
const authorize = vi.fn(() => {
1044+
throw new GuardRejectedError("denied", "alias.txt")
1045+
})
1046+
mockedResolvePublishTarget.mockResolvedValue(abs("outside/ref.txt"))
1047+
1048+
await expect(
1049+
replaceIfVersion(abs("alias.txt"), "v1", "hello", "alias.txt", undefined, authorize),
1050+
).rejects.toBeInstanceOf(GuardRejectedError)
1051+
1052+
// The decision runs on the retained target, not the alias, and it
1053+
// precedes the version comparison and the publish.
1054+
expect(authorize).toHaveBeenCalledWith(abs("outside/ref.txt"))
1055+
expect(mockedComputeVersionToken).not.toHaveBeenCalled()
1056+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
1057+
})
1058+
1059+
it("replaceIfVersion publishes when the retained target passes the allowlist", async () => {
1060+
const authorize = vi.fn()
1061+
mockedFsAccess.mockResolvedValue(undefined)
1062+
mockedComputeVersionToken.mockResolvedValue("v1")
1063+
mockedResolvePublishTarget.mockResolvedValue(abs("alias.txt"))
1064+
1065+
await replaceIfVersion(abs("alias.txt"), "v1", "hello", "alias.txt", undefined, authorize)
1066+
1067+
expect(authorize).toHaveBeenCalledWith(abs("alias.txt"))
1068+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("alias.txt"), "hello")
1069+
})
1070+
1071+
it("createIfAbsent stops when the retained target fails the allowlist", async () => {
1072+
const authorize = vi.fn(() => {
1073+
throw new GuardRejectedError("denied", "alias.txt")
1074+
})
1075+
mockedResolvePublishTarget.mockResolvedValue(abs("outside/ref.txt"))
1076+
1077+
await expect(
1078+
createIfAbsent(abs("alias.txt"), "hello", "alias.txt", undefined, authorize),
1079+
).rejects.toBeInstanceOf(GuardRejectedError)
1080+
1081+
expect(authorize).toHaveBeenCalledWith(abs("outside/ref.txt"))
1082+
expect(mockedFsAccess).not.toHaveBeenCalled()
1083+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
1084+
})
1085+
1086+
it("guardedWrite rejects when the alias passes the allowlist but the resolved target is ignored", async () => {
1087+
// The row's scenario: a symlink passes validateAccess while it points
1088+
// at an allowed file; the retained referent is outside the allowlist,
1089+
// and the guarded publish must not write there.
1090+
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
1091+
mockedComputeVersionToken.mockResolvedValue("v1")
1092+
mockedResolvePublishTarget.mockResolvedValue(abs("ignored/secret.txt"))
1093+
const validateAccess = vi.fn((p: string) => p === abs("link.txt"))
1094+
const task = createMockTask({ rooIgnoreController: { validateAccess } })
1095+
1096+
await expect(guardedWrite(task, "link.txt", "hello", "create")).rejects.toBeInstanceOf(GuardRejectedError)
1097+
1098+
expect(validateAccess).toHaveBeenCalledWith(abs("ignored/secret.txt"))
1099+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
1100+
})
1101+
1102+
it("guardedWrite publishes when the retained target passes the allowlist", async () => {
1103+
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
1104+
mockedComputeVersionToken.mockResolvedValue("v1")
1105+
mockedResolvePublishTarget.mockResolvedValue(abs("ok.txt"))
1106+
const validateAccess = vi.fn().mockReturnValue(true)
1107+
const task = createMockTask({ rooIgnoreController: { validateAccess } })
1108+
1109+
await guardedWrite(task, "ok.txt", "hello", "create")
1110+
1111+
expect(validateAccess).toHaveBeenCalledWith(abs("ok.txt"))
1112+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("ok.txt"), "hello")
1113+
})
1114+
1115+
it("takes both the alias and the referent lock in sorted order when they differ", async () => {
1116+
// A protocol writer that swaps the link itself holds the alias entry
1117+
// lock; a guarded write holding only the referent lock could publish
1118+
// through a link mid-swap. Distinct keys are taken in sorted order,
1119+
// the shared order safeWriteJson's dual-link path uses.
1120+
mockedResolveLockKey.mockResolvedValue(abs("aaa-referent.txt"))
1121+
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
1122+
mockedComputeVersionToken.mockResolvedValue("v1")
1123+
1124+
await guardedWrite(createMockTask(), "zzz-alias.txt", "hello", "create")
1125+
1126+
const keys = mockedWithFileLock.mock.calls.map((call) => String(call[0]))
1127+
expect(keys).toEqual([abs("aaa-referent.txt"), abs("zzz-alias.txt")])
1128+
})
1129+
1130+
it("takes a single lock when the alias and referent keys fold to one", async () => {
1131+
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
1132+
mockedComputeVersionToken.mockResolvedValue("v1")
1133+
1134+
await guardedWrite(createMockTask(), "plain.txt", "hello", "create")
1135+
1136+
expect(mockedWithFileLock).toHaveBeenCalledTimes(1)
1137+
})
1138+
})
10251139
})

‎src/core/tools/guardedWrite.ts‎

Lines changed: 72 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import { computeVersionToken } from "../../utils/versionToken"
2929
import { withFileLock } from "../../utils/fileLock"
3030
import { resolveLockKey } from "../../services/file-safety/safeWriteText"
3131
import { resolvePublishTarget } from "../../services/file-safety/safeWriteText"
32+
import { resolveLinkPathLockKey } from "../../services/file-safety/safeWriteText"
3233
import type { Task } from "../task/Task"
3334

3435
// -- Types ------------------------------------------------------------------
@@ -191,19 +192,47 @@ async function fixedPublishTarget(absolutePath: string): Promise<string> {
191192
})
192193
}
193194

195+
/**
196+
* Acquire the advisory locks covering BOTH identities of a guarded write:
197+
* the resolved referent key every writer to the file uses, and the alias
198+
* entry key (resolveLinkPathLockKey: canonical parent, final component never
199+
* followed) that a protocol writer swapping the link itself holds - the same
200+
* pair and folding safeWriteJson's dual-link path uses. Distinct keys are
201+
* taken in sorted order, the shared order of that path, so two guarded
202+
* writes can never deadlock, and withFileLock's own unwinding releases them
203+
* inner-first.
204+
*/
205+
async function withBothIdentityLocks<T>(absolutePath: string, operation: () => Promise<T>): Promise<T> {
206+
const referentKey = await resolveLockKey(absolutePath)
207+
const aliasKey = await resolveLinkPathLockKey(absolutePath)
208+
if (aliasKey === referentKey) {
209+
return withFileLock(referentKey, operation)
210+
}
211+
const [first, second] = aliasKey < referentKey ? [aliasKey, referentKey] : [referentKey, aliasKey]
212+
return withFileLock(first, () => withFileLock(second, operation))
213+
}
214+
194215
export async function createIfAbsent(
195216
absolutePath: string,
196217
content: string | Uint8Array,
197218
displayPath: string,
198219
// Re-checked under the lock: a link that waited on the FIFO chain can outlive
199220
// the task that queued it.
200221
isCancelled?: () => boolean,
222+
// Called under the lock with the RETAINED publish target before any check:
223+
// the caller's allowlist decision was made about the alias, and a link
224+
// retargeted (or a hard-link alias swapped in) since then names a different
225+
// file. The callback re-runs the access decision on the retained target and
226+
// throws to stop the publish.
227+
authorizeTarget?: (retainedTarget: string) => void,
201228
): Promise<string | undefined> {
202-
// Lock the key every other writer to this file uses: the resolved publish
203-
// target, so a symlink alias and its referent share one lock.
204-
return withFileLock(await resolveLockKey(absolutePath), async () => {
229+
// Lock both identities of the write: the resolved referent every other
230+
// writer to this file uses, and the alias entry a link-swapping protocol
231+
// writer holds.
232+
return withBothIdentityLocks(absolutePath, async () => {
205233
cancelledBeforePublish(absolutePath, displayPath, isCancelled)
206234
const publishTarget = await fixedPublishTarget(absolutePath)
235+
authorizeTarget?.(publishTarget)
207236
try {
208237
await fs.access(publishTarget)
209238
} catch (error: unknown) {
@@ -263,16 +292,24 @@ export async function replaceIfVersion(
263292
// Re-checked under the lock: a link that waited on the FIFO chain can outlive
264293
// the task that queued it.
265294
isCancelled?: () => boolean,
295+
// Called under the lock with the RETAINED publish target before the version
296+
// comparison: the caller's allowlist decision was made about the alias, and
297+
// a link retargeted (or a hard-link alias swapped in) since then names a
298+
// different file. The callback re-runs the access decision on the retained
299+
// target and throws to stop the publish.
300+
authorizeTarget?: (retainedTarget: string) => void,
266301
): Promise<string | undefined> {
267-
// Lock the key every other writer to this file uses: the resolved publish
268-
// target, so a symlink alias and its referent share one lock.
269-
return withFileLock(await resolveLockKey(absolutePath), async () => {
302+
// Lock both identities of the write: the resolved referent every other
303+
// writer to this file uses, and the alias entry a link-swapping protocol
304+
// writer holds.
305+
return withBothIdentityLocks(absolutePath, async () => {
270306
cancelledBeforePublish(absolutePath, displayPath, isCancelled)
271307
// Resolve and retain the publish target inside the lock: the version
272308
// comparison and the publish below both act on this fixed target, so a
273309
// symlink retargeted after the caller's allowlist check cannot send the
274310
// write to a file the version check never covered.
275311
const publishTarget = await fixedPublishTarget(absolutePath)
312+
authorizeTarget?.(publishTarget)
276313
let currentVersion: string
277314
try {
278315
currentVersion = await computeVersionToken(publishTarget)
@@ -392,6 +429,19 @@ export async function guardedWrite(
392429
// a write queued before an abort can still reach its turn on the chain after the
393430
// task is gone, and the caller has already reported the write to the model.
394431
const displayPath = relPathOrAbsolute
432+
// The tool layer validated the caller's alias before the write; re-run that
433+
// decision on the retained publish target under the lock, so a link
434+
// retargeted after the tool's check - or a hard-link alias whose new
435+
// referent the version token cannot tell apart - cannot send the approved
436+
// bytes to an ignored or external file.
437+
const authorizeTarget = (retainedTarget: string): void => {
438+
if (task.rooIgnoreController && !task.rooIgnoreController.validateAccess(retainedTarget)) {
439+
throw new GuardRejectedError(
440+
"The ignore allowlist denied access to the resolved publish target -- nothing was written.",
441+
displayPath,
442+
)
443+
}
444+
}
395445

396446
if (task.abort) {
397447
throw new GuardRejectedError(
@@ -425,6 +475,7 @@ export async function guardedWrite(
425475
content,
426476
displayPath,
427477
() => task.abort,
478+
authorizeTarget,
428479
)
429480
}
430481
} else {
@@ -448,10 +499,22 @@ export async function guardedWrite(
448499

449500
if (obs === undefined) {
450501
// Never read: only an absent target may be created.
451-
publishedToken = await createIfAbsent(absolutePath, content, displayPath, () => task.abort)
502+
publishedToken = await createIfAbsent(
503+
absolutePath,
504+
content,
505+
displayPath,
506+
() => task.abort,
507+
authorizeTarget,
508+
)
452509
} else if (absent) {
453510
// A "create" on a file that vanished after the read recreates it.
454-
publishedToken = await createIfAbsent(absolutePath, content, displayPath, () => task.abort)
511+
publishedToken = await createIfAbsent(
512+
absolutePath,
513+
content,
514+
displayPath,
515+
() => task.abort,
516+
authorizeTarget,
517+
)
455518
} else {
456519
// The version recorded at read time must still match the on-disk
457520
// token.
@@ -461,6 +524,7 @@ export async function guardedWrite(
461524
content,
462525
displayPath,
463526
() => task.abort,
527+
authorizeTarget,
464528
)
465529
}
466530
}

‎src/integrations/editor/__tests__/DiffViewProvider.spec.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@ vi.mock("../../../services/file-safety/safeWriteText", () => ({
4747
// The guard fixes the publish target inside the lock through this helper;
4848
// the identity default keeps every path in this file unchanged.
4949
resolvePublishTarget: vi.fn(async (p: string) => p),
50+
// The dual-identity lock takes this alias-entry key beside the referent
51+
// key; the identity default folds both to one, as every path here is a
52+
// plain file.
53+
resolveLinkPathLockKey: vi.fn(async (p: string) => p),
5054
// The guarded write recognises a landed-but-not-durable publish by this error's
5155
// identity, and this spec replaces the whole module, so the class is restated
5256
// here with the real constructor shape rather than imported.

0 commit comments

Comments
 (0)