Skip to content

Commit 0558c2a

Browse files
committed
fix(checkpoints): reject unverified journal tails and double-encoded card paths
- loadChanges discarded a parse failure on the final line as a torn tail without evidence, so a corrupted final record made rollback report an incomplete history as valid (restore-latest no-oped over the lost write). Torn-tail repair is verified truncation owned by the append path; a read now rejects, and rollbackFile, rollbackStep, and restoreLatestFile surface an explicit failure without restoring. - Change-card openFile paths were decoded once at the containment boundary while openFile decodes again afterwards: a double-encoded request (./%252e%252e/%252e%252e/.env) passed containment as a literal and escaped only after that later decode. Card paths now decode to a fixed point at the boundary (same rule as markdown); literal names with a bare percent keep the historical fallback and non-stabilizing encodings reject. Regression tests: torn final line and entirely torn journal reject at load; corrupt final records fail restore-latest, rollbackFile, and rollbackStep without a restore call; a double-encoded change-card traversal is rejected before openFile runs. Negative controls: restoring the silent discard turns exactly the new-behavior tests red; reverting the card path to a single decode turns exactly the double-encode test red.
1 parent 5b32095 commit 0558c2a

5 files changed

Lines changed: 83 additions & 22 deletions

File tree

‎src/core/checkpoints/__tests__/changeJournal.spec.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -402,15 +402,16 @@ describe("changeJournal", () => {
402402
expect(result[0].checkpointId).toBe("ok")
403403
})
404404

405-
it("discards a torn final line and returns the complete entries", async () => {
405+
it("rejects a torn final line instead of silently dropping it", async () => {
406406
await appendChange(tmpRoot, taskId, entry({ checkpointId: "ok" }))
407407

408-
// Append a second line truncated mid-content, with no trailing newline.
408+
// Append a second line truncated mid-content, with no trailing
409+
// newline. Without verified truncation there is no evidence this
410+
// is a crash tail rather than a corrupted record, and silently
411+
// dropping it would report an incomplete history as valid.
409412
await fs.appendFile(journalPath(tmpRoot, taskId), '{"path":"src/half.ts","operation":"upd')
410413

411-
const result = await loadChanges(tmpRoot, taskId)
412-
expect(result).toHaveLength(1)
413-
expect(result[0].checkpointId).toBe("ok")
414+
await expect(loadChanges(tmpRoot, taskId)).rejects.toThrow(/Corrupt change journal entry at line 2/)
414415
})
415416

416417
it("rejects a corrupt middle line instead of silently losing history", async () => {
@@ -428,13 +429,15 @@ describe("changeJournal", () => {
428429
// rollback completeness is unknown and the load fails loudly.
429430
await expect(loadChanges(tmpRoot, taskId)).rejects.toThrow(/Corrupt change journal entry at line 1/)
430431
})
431-
it("does not throw when the entire journal is torn", async () => {
432+
it("rejects a journal whose only record is torn", async () => {
432433
await appendChange(tmpRoot, taskId, entry({ checkpointId: "first" }))
433434

434-
// Truncate to a single character — definitely invalid JSON.
435+
// Truncate to a single character — definitely invalid JSON. The
436+
// append path repairs such a tail on the next write; a read must
437+
// not report the lost record as a complete (empty) history.
435438
await fs.writeFile(journalPath(tmpRoot, taskId), "{")
436439

437-
expect(await loadChanges(tmpRoot, taskId)).toEqual([])
440+
await expect(loadChanges(tmpRoot, taskId)).rejects.toThrow(/Corrupt change journal entry at line 1/)
438441
})
439442

440443
it("rejects a final line that parses but is not entry-shaped", async () => {

‎src/core/checkpoints/__tests__/rollback.spec.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,38 @@ describe("restoreLatestFile (B3c: forward direction)", () => {
429429
expect(service.restoreFile).not.toHaveBeenCalled()
430430
})
431431

432+
it("fails restore-latest on a corrupt final journal record without restoring", async () => {
433+
// A committed write whose final journal record was truncated or
434+
// corrupted must surface as an explicit failure: reporting a
435+
// successful no-op would hide that rollback metadata is incomplete.
436+
await seedJournal([{ path: "src/a.ts", operation: "update", checkpointId: "sha-1" }])
437+
await fs.appendFile(journalPath(globalStorageDir, "task-rollback"), '{"path":"src/a.ts","ope')
438+
const service = serviceWith("base-0")
439+
mockedGetCheckpointService.mockResolvedValue(service)
440+
441+
const outcome = await restoreLatestFile(makeTask(), "src/a.ts")
442+
443+
expect(outcome.success).toBe(false)
444+
expect(outcome.error).toContain("Corrupt change journal entry at line 2")
445+
expect(service.restoreFile).not.toHaveBeenCalled()
446+
})
447+
448+
it("fails rollbackFile and rollbackStep on a corrupt final journal record without restoring", async () => {
449+
await seedJournal([{ path: "src/a.ts", operation: "update", checkpointId: "sha-1" }])
450+
await fs.appendFile(journalPath(globalStorageDir, "task-rollback"), '{"path":"src/a.ts","ope')
451+
const service = serviceWith("base-0")
452+
mockedGetCheckpointService.mockResolvedValue(service)
453+
454+
const single = await rollbackFile(makeTask(), "sha-1", "src/a.ts")
455+
expect(single.success).toBe(false)
456+
expect(single.error).toContain("Corrupt change journal entry at line 2")
457+
458+
const step = await rollbackStep(makeTask(), ["src/a.ts"], "sha-1")
459+
expect(step.files[0].success).toBe(false)
460+
expect(step.files[0].error).toContain("Corrupt change journal entry at line 2")
461+
expect(service.restoreFile).not.toHaveBeenCalled()
462+
})
463+
432464
it("fails cleanly when checkpoints are not enabled", async () => {
433465
mockedGetCheckpointService.mockResolvedValue(undefined)
434466

‎src/core/checkpoints/changeJournal.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -263,14 +263,15 @@ export async function loadChanges(globalStorageDir: string, taskId: string): Pro
263263
try {
264264
parsed = JSON.parse(lines[i])
265265
} catch {
266-
// Only the final line may be a torn tail from a crash mid-append;
267-
// truncating it is verified recovery. A corrupt MIDDLE line means a
268-
// write was lost from the history, so journal completeness is
269-
// unknown and rollback must fail loudly instead of picking an
270-
// older entry as the restore target.
271-
if (i === lines.length - 1) {
272-
break
273-
}
266+
// A parse failure anywhere - including the final line - means
267+
// journal completeness is unknown. Silently dropping an
268+
// unverified final record can report an incomplete history as
269+
// valid: restore-latest would no-op over the lost write.
270+
// Torn-tail repair is verified truncation and belongs to the
271+
// append path (which re-terminates or truncates the tail before
272+
// writing); a read must reject instead. A corrupt MIDDLE line
273+
// means a write was lost from the history, so rollback must fail
274+
// loudly instead of picking an older entry as the restore target.
274275
throw new Error(`Corrupt change journal entry at line ${i + 1} of ${filePath}`)
275276
}
276277
// A parsed line that is not entry-shaped is malformed, not a torn

‎src/core/webview/__tests__/webviewMessageHandler.openFile.spec.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,23 @@ describe("webviewMessageHandler - openFile markdown workspace containment", () =
323323
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(cannotAccessPathError("./%2e%2e/%2e%2e/.env"))
324324
})
325325

326+
it("rejects a double-encoded traversal posted by a change card", async () => {
327+
// The single boundary decode left `./%2e%2e/%2e%2e/.env` inside the
328+
// workspace as a literal; openFile's later decode would then escape
329+
// to `../../.env`. Decoding to a fixed point at the containment
330+
// boundary rejects the request before openFile ever runs.
331+
await webviewMessageHandler(mockProvider, {
332+
type: "openFile",
333+
text: "./%252e%252e/%252e%252e/.env",
334+
values: { fromChangeCard: true },
335+
})
336+
337+
expect(openFile).not.toHaveBeenCalled()
338+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(
339+
cannotAccessPathError("./%252e%252e/%252e%252e/.env"),
340+
)
341+
})
342+
326343
it("opens a change-card file whose name legitimately contains a percent sign", async () => {
327344
// "100%.txt" is not a valid percent-encoding: the best-effort decode
328345
// keeps the literal name (the same fallback openFile applies).

‎src/core/webview/webviewMessageHandler.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1587,13 +1587,21 @@ export const webviewMessageHandler = async (
15871587
}
15881588
filePath = decoded
15891589
} else if (fromChangeCard) {
1590-
try {
1591-
filePath = decodeURIComponent(rawPath)
1592-
} catch {
1593-
// Not a valid percent-encoding: a literal filesystem name
1594-
// (e.g. "100%.txt"). openFile applies the same fallback.
1595-
filePath = rawPath
1590+
// Change-card rows post raw workspace paths, but a path may
1591+
// still carry percent-escapes. Decode to a fixed point at the
1592+
// containment boundary (same rule as markdown) so openFile's
1593+
// later single decode cannot shift a validated path outside
1594+
// the workspace: a double-encoded request such as
1595+
// `./%252e%252e/%252e%252e/.env` passes containment as a
1596+
// literal and escapes only after that later decode. A bare
1597+
// `%` that is not a valid escape stays unchanged (literal
1598+
// names like "100%.txt"); a non-stabilizing encoding rejects.
1599+
const decoded = decodeUntrustedPathToStable(rawPath)
1600+
if (decoded === null) {
1601+
rejectOutsideWorkspace()
1602+
break
15961603
}
1604+
filePath = decoded
15971605
}
15981606
if (!path.isAbsolute(filePath)) {
15991607
const cwd = getCurrentCwd()

0 commit comments

Comments
 (0)