Skip to content

Commit 76427e7

Browse files
author
easonLiangWorldedtech
committed
u5 CR round: pin confined-root identity, fence post-commit rollback, recover dangling alias
- safeWriteJson: capture the confinement root's dev/ino when the pre-lock check authorizes it and re-verify after the commit rename, so a root swapped at the same spelling is reported instead of silently accepted - safeWriteJson: committedBeforeTeardown fence - a transient post-commit failure can no longer rename the pre-commit backup over committed bytes; a non-escape probe error logs and keeps the known-good publish - safeWriteJson: a dangling publish target runs interrupted-replacement recovery before rejecting, then re-resolves (dangling-alias writes now succeed) - safeWriteJson: flush before the target-mode copy (r+ descriptor vs restrictive mode); stage with mode 0o600 so bytes are never world-readable pre-chmod - safeWriteText: reject a staging path that names the publish target; backup doc states copy-never-restore semantics - tests: root-swap, committed-rollback, dangling-recovery, 0444-flush, staging-is- target unit rows; readFileTool token assertions computed from the bigint fixture - Task: cancellationGeneration comments state the real fence (abort flag is never cleared on resume) Refs: #1914 (CodeRabbit round 2026-11-08)
1 parent 281c245 commit 76427e7

7 files changed

Lines changed: 324 additions & 47 deletions

File tree

‎src/core/task/Task.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3602,9 +3602,12 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
36023602
}
36033603
this.abort = true
36043604
// The S4a write guard compares this counter with the value a queued write
3605-
// captured when it started, so every cancellation must advance it; it must
3606-
// never go backwards because resumeAfterDelegation() clears `abort` (the
3607-
// flag alone cannot keep the cancelled run and the resumed run apart).
3605+
// captured when it started, so every cancellation must advance it and it
3606+
// must never go backwards: the abort flag is set here and no resume path
3607+
// clears it, so on a resumed task it only says that some cancellation
3608+
// happened - never WHICH cancellation a queued write belongs to. Only the
3609+
// generation keeps a cancelled run's queued writes apart from the
3610+
// resumed run's, and only if it advances monotonically.
36083611
this.cancellationGeneration++
36093612
this.driveRunEvent({ tag: "abortRequested", abandoned: isAbandoned })
36103613
}

‎src/core/task/__tests__/Task.spec.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4770,10 +4770,11 @@ describe("Cline", () => {
47704770

47714771
it("advances the cancellation generation on each cancellation and keeps it advanced across a resume", async () => {
47724772
// The S4a write guard compares the cancellation generation a queued write
4773-
// captured against the generation at publish time. The abort FLAG cannot do that
4774-
// on its own: resumeAfterDelegation() clears it, and a write that belongs to the
4775-
// cancelled run would then publish as if nothing had been cancelled. Only the
4776-
// generation keeps the two runs apart, so it must never go backwards.
4773+
// captured against the generation at publish time. The abort FLAG cannot do
4774+
// that on its own: it is set on cancellation and no resume path clears it,
4775+
// so on a resumed task it says only that some cancellation happened, not
4776+
// which run a queued write belongs to. Only the generation keeps the two
4777+
// runs apart, so it must never go backwards.
47774778
const task = new Task({
47784779
provider: mockProvider,
47794780
apiConfiguration: mockApiConfig,

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

Lines changed: 54 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1803,13 +1803,27 @@ describe("ReadFileTool", () => {
18031803
const callbacks = createMockCallbacks()
18041804

18051805
// Override the beforeEach default stat mock with proper BigIntStats.
1806-
mockedFsStat.mockResolvedValue({
1807-
isDirectory: () => false,
1806+
const statFields = {
18081807
dev: BigInt(1),
18091808
ino: BigInt(2),
18101809
size: BigInt(300),
18111810
mtimeNs: BigInt(4_000_000_000n),
18121811
ctimeNs: BigInt(5_000_000_000n),
1812+
}
1813+
// The expected token is computed from the same fixture the mock returns,
1814+
// so a stored "0:0:0:0:0" cannot pass this assertion.
1815+
const expectedVersionToken = [
1816+
statFields.dev,
1817+
statFields.ino,
1818+
statFields.size,
1819+
statFields.mtimeNs,
1820+
statFields.ctimeNs,
1821+
]
1822+
.map((value) => value.toString())
1823+
.join(":")
1824+
mockedFsStat.mockResolvedValue({
1825+
isDirectory: () => false,
1826+
...statFields,
18131827
// Cast: the mock only implements the members the tool and versionToken read.
18141828
} as unknown as Stats)
18151829
mockedIsBinaryFile.mockResolvedValue(false)
@@ -1825,7 +1839,7 @@ describe("ReadFileTool", () => {
18251839
expect(observeSpy).toHaveBeenCalledTimes(1)
18261840
const [calledPath, calledVersion] = observeSpy.mock.calls[0]
18271841
expect(calledPath).toContain("existing.ts")
1828-
expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/)
1842+
expect(calledVersion).toBe(expectedVersionToken)
18291843

18301844
// Verify get() returns the same data using the spy-captured key.
18311845
const obs = reg.get(calledPath)
@@ -1869,13 +1883,27 @@ describe("ReadFileTool", () => {
18691883
})
18701884
const callbacks = createMockCallbacks()
18711885

1872-
mockedFsStat.mockResolvedValue({
1873-
isDirectory: () => false,
1886+
const statFields = {
18741887
dev: BigInt(1),
18751888
ino: BigInt(2),
18761889
size: BigInt(300),
18771890
mtimeNs: BigInt(4_000_000_000n),
18781891
ctimeNs: BigInt(5_000_000_000n),
1892+
}
1893+
// The expected token is computed from the same fixture the mock returns,
1894+
// so a stored "0:0:0:0:0" cannot pass this assertion.
1895+
const expectedVersionToken = [
1896+
statFields.dev,
1897+
statFields.ino,
1898+
statFields.size,
1899+
statFields.mtimeNs,
1900+
statFields.ctimeNs,
1901+
]
1902+
.map((value) => value.toString())
1903+
.join(":")
1904+
mockedFsStat.mockResolvedValue({
1905+
isDirectory: () => false,
1906+
...statFields,
18791907
// Cast: the mock only implements the members the tool and versionToken read.
18801908
} as unknown as Stats)
18811909
mockedIsBinaryFile.mockResolvedValue(false)
@@ -1896,7 +1924,7 @@ describe("ReadFileTool", () => {
18961924
expect(observeSpy).toHaveBeenCalledTimes(1)
18971925
const [calledPath, calledVersion] = observeSpy.mock.calls[0]
18981926
expect(calledPath).toContain("legacy.ts")
1899-
expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/)
1927+
expect(calledVersion).toBe(expectedVersionToken)
19001928
// Regression evidence, same contract on the legacy path: count the
19011929
// matching calls (correct path AND { bigint: true }) instead of
19021930
// asserting membership, which the directory-check stat alone satisfies.
@@ -2295,16 +2323,26 @@ describe("ReadFileTool", () => {
22952323
})
22962324

22972325
describe("read completeness scope (S4b follow-up #46)", () => {
2326+
const statFields = {
2327+
dev: BigInt(1),
2328+
ino: BigInt(2),
2329+
size: BigInt(300),
2330+
mtimeNs: BigInt(4_000_000_000n),
2331+
ctimeNs: BigInt(5_000_000_000n),
2332+
}
2333+
// Computed from the fixture, not a regex shape: a stored all-zero token
2334+
// must not satisfy this.
2335+
const expectedVersionToken = [
2336+
statFields.dev,
2337+
statFields.ino,
2338+
statFields.size,
2339+
statFields.mtimeNs,
2340+
statFields.ctimeNs,
2341+
]
2342+
.map((value) => value.toString())
2343+
.join(":")
22982344
// The stat mock only implements the members the tool and versionToken read.
2299-
const bigintStats = (): Stats =>
2300-
({
2301-
isDirectory: () => false,
2302-
dev: BigInt(1),
2303-
ino: BigInt(2),
2304-
size: BigInt(300),
2305-
mtimeNs: BigInt(4_000_000_000n),
2306-
ctimeNs: BigInt(5_000_000_000n),
2307-
}) as unknown as Stats
2345+
const bigintStats = (): Stats => ({ isDirectory: () => false, ...statFields }) as unknown as Stats
23082346

23092347
it("native: a full, untruncated slice read from line 1 records a complete observation", async () => {
23102348
const mockTask = createMockTask({
@@ -2331,7 +2369,7 @@ describe("ReadFileTool", () => {
23312369
expect(observeSpy).toHaveBeenCalledTimes(1)
23322370
const [calledPath, calledVersion, calledComplete] = observeSpy.mock.calls[0]
23332371
expect(calledPath).toContain("full.ts")
2334-
expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/)
2372+
expect(calledVersion).toBe(expectedVersionToken)
23352373
expect(calledComplete).toBe(true)
23362374
expect(reg.get(calledPath)!.complete).toBe(true)
23372375
})

‎src/services/file-safety/__tests__/safeWriteText.spec.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,24 @@ describe("safeWriteText", () => {
289289
expect(fs.unlink).toHaveBeenCalledWith(callerTemp)
290290
expect(fs.rmdir).not.toHaveBeenCalled()
291291
})
292+
293+
it("rejects a supplied staging path that names the publish target", async () => {
294+
// resolvePublishTarget realpaths the target (identity here) and compares
295+
// the supplied staging path against that resolved target, so both sides
296+
// must use this platform's path module rather than a posix literal.
297+
vi.mocked(fs.realpath).mockImplementation(async (p) => p.toString())
298+
const targetPath = path.resolve("/tmp/test-dir/target.txt")
299+
vi.mocked(fsSync.openSync).mockReturnValue(1)
300+
301+
await expect(
302+
safeWriteText(targetPath, "hello", { platform: "linux", tempPath: targetPath }),
303+
).rejects.toThrow(StagingPathError)
304+
305+
// Rejected before staging touches anything: the target file stays the
306+
// target's own, never a staging candidate that could rename onto itself.
307+
expect(fsSync.openSync).not.toHaveBeenCalled()
308+
expect(fs.rename).not.toHaveBeenCalled()
309+
})
292310
})
293311

294312
// ── Test 2: fsync ordering ───────────────────────────────────────────────

‎src/services/file-safety/safeWriteText.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,15 @@ import { getErrorCode } from "../../utils/errorCode"
88
export interface SafeWriteTextOptions {
99
/**
1010
* When true, preserve the old-file semantics: rename target -> backup first,
11-
* after commit rename delete the backup; on failure roll the backup back to
12-
* the target path. When false (default) the atomic rename simply replaces
13-
* the target -- crash-safe window is zero.
11+
* then stage and commit; after a successful commit delete the backup copy.
12+
* On failure the backup is never rolled back to the target: it is a copy taken
13+
* before staging began, not a restore source - the teardown discards it and the
14+
* original error propagates. What the target holds after a rejected write
15+
* depends on where the failure landed: the original file, the staged
16+
* replacement, or - if the process died between the two renames - nothing,
17+
* until a later writer's recovery pass restores the orphaned backup.
18+
* When false (default) the atomic rename simply replaces the target --
19+
* crash-safe window is zero.
1420
*/
1521
backup?: boolean
1622

@@ -467,6 +473,16 @@ export async function safeWriteText(
467473
supplied,
468474
)
469475
}
476+
// Naming the target is not staging it: a staging file that resolves onto
477+
// the publish target would let the commit rename move the target file
478+
// onto itself, and the fsync and permission steps below would then act on
479+
// the target as if it were the staged bytes.
480+
if (supplied === targetPath) {
481+
throw new StagingPathError(
482+
`Staging file must not name the publish target (${targetPath}), got ${supplied}`,
483+
supplied,
484+
)
485+
}
470486
const stagingStat = await fs.lstat(supplied)
471487
if (stagingStat.isSymbolicLink() || !stagingStat.isFile()) {
472488
throw new StagingPathError(

‎src/utils/__tests__/safeWriteJson.test.ts‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ vi.mock("fs/promises", async () => {
3434
rm: vi.fn(actual.rm),
3535
readdir: vi.fn(actual.readdir),
3636
mkdir: vi.fn(actual.mkdir),
37+
realpath: vi.fn(actual.realpath),
3738
}
3839
// fs.lstat is available via { ...actual }
3940

@@ -1071,6 +1072,131 @@ describe("safeWriteJson", () => {
10711072
expect(await readFileContent(currentTestFilePath)).toEqual({ after: true })
10721073
},
10731074
)
1075+
// 2242: a dangling alias is not always an absent file. This row drives the
1076+
// interrupted-EPERM-fallback state directly instead of crashing a process.
1077+
// Needs symlinks, which are unprivileged on the Windows CI lane.
1078+
test.skipIf(process.platform === "win32")(
1079+
"restores an interrupted backup rename so a write through the dangling alias succeeds",
1080+
async () => {
1081+
const dir = path.join(tempDir, "alias-recovery")
1082+
await fs.mkdir(dir)
1083+
const canonical = path.join(dir, "t.json")
1084+
const alias = path.join(dir, "alias.json")
1085+
// The state left between the EPERM fallback's two renames when the process
1086+
// dies after the backup rename: the canonical referent is gone, its backup
1087+
// sits beside it, and every write through the alias rejects as dangling.
1088+
const backup = path.join(dir, ".t.json.bak_1700000000000_interrupted.tmp")
1089+
await fsPromisesActuals.writeFile!(backup, JSON.stringify({ old: 1 }))
1090+
await fs.symlink("t.json", alias)
1091+
1092+
await safeWriteJson(alias, { after: true }, { confineTo: dir })
1093+
1094+
const published = JSON.parse(await fs.readFile(canonical, "utf8"))
1095+
expect(published).toEqual({ after: true })
1096+
expect(JSON.parse(await fs.readFile(alias, "utf8"))).toEqual({ after: true })
1097+
const entries = await fs.readdir(dir)
1098+
expect(entries).not.toContain(path.basename(backup))
1099+
},
1100+
)
1101+
1102+
// 2247: the flush opens the staged file with r+. It must run while the
1103+
// staged file is still in its creation mode, before a restrictive copied
1104+
// mode can deny that descriptor and silently skip the sync.
1105+
test.skipIf(process.platform === "win32")(
1106+
"flushes the staged file before the copied target mode can deny the sync descriptor",
1107+
async () => {
1108+
await fsPromisesActuals.writeFile!(currentTestFilePath, JSON.stringify({ before: true }))
1109+
fsSyncActual.chmodSync(currentTestFilePath, 0o444)
1110+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
1111+
1112+
await safeWriteJson(currentTestFilePath, { after: true })
1113+
1114+
expect(consoleErrorSpy).not.toHaveBeenCalledWith(expect.stringContaining("Failed to flush"))
1115+
expect(await readFileContent(currentTestFilePath)).toEqual({ after: true })
1116+
expect(fsSyncActual.statSync(currentTestFilePath).mode & 0o777).toBe(0o444)
1117+
consoleErrorSpy.mockRestore()
1118+
},
1119+
)
1120+
1121+
// 2228: spelling is not containment. The root swap happens between the
1122+
// commit rename and the post-commit re-check - the exact window the
1123+
// confineTo doc says the checks cannot prevent - and must still report.
1124+
test("reports the escape when the confinement root is replaced after the commit rename", async () => {
1125+
const scope = path.join(tempDir, "swap-root")
1126+
await fs.mkdir(scope)
1127+
const target = path.join(scope, "mcp.json")
1128+
const moved = path.join(tempDir, "moved-root")
1129+
1130+
await expect(
1131+
safeWriteJson(
1132+
target,
1133+
{ mcpServers: {} },
1134+
{
1135+
confineTo: scope,
1136+
trace: (event) => {
1137+
// Synchronously, inside the trace hook fired after the commit rename:
1138+
// move the authorized directory out and drop a fresh empty one at
1139+
// the same spelling. Every relative check still passes; only the
1140+
// authorized root's identity can tell the two directories apart.
1141+
if (event.stage === "write-complete") {
1142+
fsSyncActual.renameSync(scope, moved)
1143+
fsSyncActual.mkdirSync(scope)
1144+
}
1145+
},
1146+
},
1147+
),
1148+
).rejects.toThrow(ConfinedPathEscapeError)
1149+
1150+
// The committed bytes travelled with the moved directory - that is the
1151+
// physically-moved variant the option doc names: detection holds, the
1152+
// undo cannot address the moved file, and the write still fails closed.
1153+
const movedContent = JSON.parse(fsSyncActual.readFileSync(path.join(moved, "mcp.json"), "utf8"))
1154+
expect(movedContent).toEqual({ mcpServers: {} })
1155+
expect(fsSyncActual.existsSync(target)).toBe(false)
1156+
})
1157+
1158+
// 2220: after the commit rename the backup is superseded content. A transient
1159+
// failure of the post-commit re-check must not rename it back over bytes
1160+
// that are already published.
1161+
test("keeps committed content when a transient post-commit failure reaches the rollback path", async () => {
1162+
const scope = path.join(tempDir, "committed-scope")
1163+
await fs.mkdir(scope)
1164+
const target = path.join(scope, "x.json")
1165+
await fsPromisesActuals.writeFile!(target, JSON.stringify({ old: 1 }))
1166+
// Force the EPERM fallback so a backup of the old content exists when the
1167+
// post-commit check fails: the first commit rename rejects and the
1168+
// fallback's two renames (the pass-through defaults) land the new content
1169+
// and keep the backup beside it.
1170+
vi.mocked(fs.rename).mockImplementationOnce(async () => {
1171+
throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" })
1172+
})
1173+
const escapee = path.join(tempDir, "fake-escape.json")
1174+
await expect(
1175+
safeWriteJson(
1176+
target,
1177+
{ new: 2 },
1178+
{
1179+
confineTo: scope,
1180+
trace: (event) => {
1181+
// The first scope resolution after the commit rename is shown an
1182+
// escaped spelling that never existed; the target itself stayed in
1183+
// place the whole time, so this is the transient-failure shape.
1184+
if (event.stage === "write-complete") {
1185+
vi.mocked(fs.realpath).mockImplementationOnce(async () => escapee)
1186+
}
1187+
},
1188+
},
1189+
),
1190+
).rejects.toThrow(ConfinedPathEscapeError)
1191+
// The escaped spelling never existed, so the undo removed nothing - and
1192+
// the rollback must not resurrect {old:1} where {new:2} already committed.
1193+
expect(JSON.parse(await fs.readFile(target, "utf8"))).toEqual({ new: 2 })
1194+
expect(fsSyncActual.existsSync(escapee)).toBe(false)
1195+
// The orphaned backup is kept for the next writer's recovery pass, which
1196+
// cleans leftovers beside an existing canonical file without restoring them.
1197+
const entries = await fs.readdir(scope)
1198+
expect(entries.some((entry) => entry.includes(".x.json.bak_"))).toBe(true)
1199+
})
10741200
// The two failure paths of _copyTargetMode: a target whose mode cannot be read, and a staged
10751201
// file whose mode cannot be set. Both have to log and let the write finish, because the
10761202
// replacement protocol - not the mode - is what makes the publish atomic. They are driven
@@ -1123,6 +1249,12 @@ describe("safeWriteJson", () => {
11231249
await safeWriteJson(currentTestFilePath, { after: true })
11241250

11251251
expect(await readFileContent(currentTestFilePath)).toEqual({ after: true })
1252+
// The staged file is created 0o600, so the mode that survives a failed chmod
1253+
// is the private staging mode - never the umask-derived default a 0o600
1254+
// target used to be published with when the copy failed.
1255+
if (process.platform !== "win32") {
1256+
expect(fsSyncActual.statSync(currentTestFilePath).mode & 0o777).toBe(0o600)
1257+
}
11261258
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to copy mode"), expect.anything())
11271259
consoleErrorSpy.mockRestore()
11281260
}, 20_000)

0 commit comments

Comments
 (0)