Skip to content

Commit 3289a72

Browse files
author
easonLiangWorldedtech
committed
fix: pin the directories a confined write creates before it commits
Review row, quoted: "src/utils/safeWriteJson.ts:327-331 records only existing ancestor identities before safeWriteText creates directories, and src/services/file-safety/safeWriteText.ts:758-818 rechecks those identities" - the re-check therefore walks a list that omits the components this write itself made. The gap is real and it is in the shared primitive, not in the caller. _confinedAncestorIdentities walks the whole chain from the scope root to the target's parent but records only what it can stat, and a directory that does not exist yet has no dev/ino to record. safeWriteText then measures the missing tail (_missingDirectoryTail, which exists so a failed write can remove what it made) and creates it with a recursive mkdir that reports nothing. So between that mkdir and the commit, a local process that replaces one of the freshly created components with a link to outside the scope sends the rename somewhere the confinement decision never made, while every recorded identity still matches - the names are unchanged. This is a defect whose conditions are not yet met, not a missing feature. safeWriteText now pins what it created: after the mkdir, when the caller supplied expectedAncestorIdentities (a confined publication - an unconfined write has no scope for a swap to escape), it records the identity of each directory in createdDirs and the step-2b re-check walks the recorded list plus those. The stat-with-mapping that step 2b already had is extracted as _statDirectoryIdentity and used by both, so ENOENT still surfaces as AncestorReplacedError and any other failure still propagates as "no evidence, no publish", with one branch set rather than two. Not adopted from the row, deliberately: no-follow directory handles and a descriptor-relative renameat/renameat2. Node has no descriptor-relative rename, which the option's own documentation already records as the reason a swap after the check cannot be eliminated - the pin narrows the window to the commit itself rather than the whole write. Pinning the created components leaves the residual window in exactly the same shape the existing pin already accepts, and it satisfies the property the row is after: validation and publication are bound to one authorized target rather than to a name that may have been repointed underneath them. Red first, then green, then negative controls. Before the change the new test 'refuses the publish when a parent this write created is swapped for a link' was red (the publish went through with no error at all); with the pin it passes, and its companion 'publishes when a parent this write created keeps the identity it was given' shows the pin does not reject the ordinary case of a confined write into a tree it had to make. Two controls, because the fix has two halves: skipping the recording turns the test red, and recording without feeding the list to the re-check also turns it red. Both mutants were restored byte-exact. This is a fix to a shared primitive, so every unit that carries safeWriteText inherits the defect; the ports are recorded as owed and must be re-derived per unit rather than copied, since each unit's call shape differs. Verification: 124 passed / 6 skipped across the file-safety, safeWriteJson and ApplyPatchTool specs; prettier --write then --check with the repo config clean; tsc --noEmit with the local paths override 0 errors; eslint . --ext=ts --max-warnings=0 exits 0; eslint-suppressions.json unchanged.
1 parent 5131bc0 commit 3289a72

2 files changed

Lines changed: 115 additions & 8 deletions

File tree

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

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1574,6 +1574,88 @@ describe("authorized-target pin (confinement TOCTOU)", () => {
15741574
expect((error as AncestorReplacedError).message).toContain("no longer exists")
15751575
expect(fs.rename).not.toHaveBeenCalled()
15761576
})
1577+
1578+
it("refuses the publish when a parent this write created is swapped for a link", async () => {
1579+
// The caller could only pin the directories that existed when it authorized the target,
1580+
// and a recursive mkdir does not report what it made, so the components this write
1581+
// creates had no recorded identity: the re-check walked a list that was missing exactly
1582+
// the directories most likely to appear between the check and the commit. A local process
1583+
// that replaces one of them with a link to outside the scope sends the commit somewhere
1584+
// the confinement decision never made, while every recorded identity still matches - the
1585+
// names are unchanged. So the primitive, which measures the missing tail before creating
1586+
// it, has to pin what it created and hand that to the same re-check.
1587+
const dir = path.resolve("/tmp/test-dir")
1588+
const created = path.join(dir, "new-parent")
1589+
const targetPath = path.join(created, "target.txt")
1590+
vi.mocked(fs.realpath).mockResolvedValue(targetPath)
1591+
vi.mocked(fsSync.openSync).mockReturnValue(1)
1592+
const probes = new Map<string, number>()
1593+
vi.mocked(fs.stat).mockImplementation(async (probe) => {
1594+
const key = String(probe)
1595+
const seen = (probes.get(key) ?? 0) + 1
1596+
probes.set(key, seen)
1597+
if (key === dir) {
1598+
return _fileStatsWithIdentity(100n, 1n)
1599+
}
1600+
if (key === created) {
1601+
// 1: measuring the missing tail, before anything is created.
1602+
if (seen === 1) {
1603+
throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
1604+
}
1605+
// 2: the identity of the directory this write has just created.
1606+
if (seen === 2) {
1607+
return _fileStatsWithIdentity(200n, 1n)
1608+
}
1609+
// 3: at the re-check it is a different directory - the swap.
1610+
return _fileStatsWithIdentity(999n, 1n)
1611+
}
1612+
return _fileStatsWithIdentity(1n, 1n)
1613+
})
1614+
1615+
const error = await safeWriteText(targetPath, "data", {
1616+
expectedResolvedPath: targetPath,
1617+
expectedAncestorIdentities: [{ dir, dev: 1n, ino: 100n }],
1618+
platform: "linux",
1619+
}).catch((caught: unknown) => caught)
1620+
1621+
expect(error).toBeInstanceOf(AncestorReplacedError)
1622+
expect((error as AncestorReplacedError).directory).toBe(created)
1623+
expect(fs.rename).not.toHaveBeenCalled()
1624+
})
1625+
1626+
it("publishes when a parent this write created keeps the identity it was given", async () => {
1627+
// Pinning what was created must not reject the ordinary case: a confined write into a
1628+
// directory tree it had to make itself is the common shape, not an attack.
1629+
const dir = path.resolve("/tmp/test-dir")
1630+
const created = path.join(dir, "new-parent")
1631+
const targetPath = path.join(created, "target.txt")
1632+
vi.mocked(fs.realpath).mockResolvedValue(targetPath)
1633+
vi.mocked(fsSync.openSync).mockReturnValue(1)
1634+
const probes = new Map<string, number>()
1635+
vi.mocked(fs.stat).mockImplementation(async (probe) => {
1636+
const key = String(probe)
1637+
const seen = (probes.get(key) ?? 0) + 1
1638+
probes.set(key, seen)
1639+
if (key === dir) {
1640+
return _fileStatsWithIdentity(100n, 1n)
1641+
}
1642+
if (key === created) {
1643+
if (seen === 1) {
1644+
throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
1645+
}
1646+
return _fileStatsWithIdentity(200n, 1n)
1647+
}
1648+
return _fileStatsWithIdentity(1n, 1n)
1649+
})
1650+
1651+
await safeWriteText(targetPath, "data", {
1652+
expectedResolvedPath: targetPath,
1653+
expectedAncestorIdentities: [{ dir, dev: 1n, ino: 100n }],
1654+
platform: "linux",
1655+
})
1656+
1657+
expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath)
1658+
})
15771659
})
15781660

15791661
// ── Parent directories this write creates must not outlive a failed write ────

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

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,20 @@ async function _missingDirectoryTail(dirPath: string): Promise<string[]> {
212212
}
213213
}
214214

215+
/**
216+
* Stat a directory for identity purposes. "Gone" is reported as the boundary failure the
217+
* caller's re-check already speaks; any other failure is not evidence of absence, so it
218+
* propagates and the write fails rather than publishing under an unverified ancestry.
219+
*/
220+
async function _statDirectoryIdentity(dir: string): Promise<fsSync.BigIntStats> {
221+
return fs.stat(dir, { bigint: true }).catch((error: unknown) => {
222+
if (errorCode(error) === "ENOENT") {
223+
throw new AncestorReplacedError(dir, "no longer exists")
224+
}
225+
throw error
226+
})
227+
}
228+
215229
/**
216230
* Remove directories this write created, innermost outward. rmdir only succeeds on an
217231
* empty directory, which is the guarantee the caller relies on: a directory that
@@ -597,6 +611,10 @@ export async function safeWriteText(
597611
// from here on must not leave an empty directory tree beside the target, and the
598612
// cleanup must not remove a directory that already existed.
599613
const createdDirs = await _missingDirectoryTail(dirPath)
614+
// Identities of the directories created below, filled in after the mkdir. The caller
615+
// could only pin what already existed, so without this the re-check walks a list that
616+
// omits exactly the components that appeared during this write.
617+
let createdIdentities: DirectoryIdentity[] = []
600618

601619
let backupPath: string | null = null
602620
let releaseBackupOnSuccess = false
@@ -611,6 +629,17 @@ export async function safeWriteText(
611629
await fs.mkdir(dirPath, { recursive: true })
612630
await fs.access(dirPath)
613631

632+
if (options?.expectedAncestorIdentities && createdDirs.length > 0) {
633+
// Only for a confined publication, where the directory chain IS the boundary; an
634+
// unconfined write has no scope for a swap to escape.
635+
createdIdentities = await Promise.all(
636+
createdDirs.map(async (dir) => {
637+
const stat = await _statDirectoryIdentity(dir)
638+
return { dir, dev: stat.dev, ino: stat.ino }
639+
}),
640+
)
641+
}
642+
614643
// -- Step 1: write content to staging temp file -------------------
615644
if (!options?.tempPath && !options?.staging) {
616645
// Preserve the existing target's permissions: the staging file must
@@ -755,14 +784,10 @@ export async function safeWriteText(
755784
// caller never authorized, even though expectedResolvedPath still matches (the
756785
// name is unchanged). Compare each recorded identity now, before anything is
757786
// moved into place.
758-
if (options?.expectedAncestorIdentities) {
759-
for (const expected of options.expectedAncestorIdentities) {
760-
const current = await fs.stat(expected.dir, { bigint: true }).catch((error: unknown) => {
761-
if (errorCode(error) === "ENOENT") {
762-
throw new AncestorReplacedError(expected.dir, "no longer exists")
763-
}
764-
throw error
765-
})
787+
const authorizedAncestors = [...(options?.expectedAncestorIdentities ?? []), ...createdIdentities]
788+
if (authorizedAncestors.length > 0) {
789+
for (const expected of authorizedAncestors) {
790+
const current = await _statDirectoryIdentity(expected.dir)
766791
if (current.dev !== expected.dev || current.ino !== expected.ino) {
767792
throw new AncestorReplacedError(expected.dir, "is no longer the directory that was authorized")
768793
}

0 commit comments

Comments
 (0)