Skip to content

Commit 79c25fe

Browse files
file-safety: keep the UNC root when the namespace marker is stripped, and validate the parent mkdir left uncreated
Three asks landed on the refreshed link head; all three were edits. _createdAncestorChain stripped only the four marker characters, so the UNC answer Node 22 reports for a created UNC directory ("\\?\UNC\server\share\...") became ("UNC\server\share\...") - a path relative to the current drive. The walk found no root, the chain came back empty, and the created-directory authorization that reads it was skipped with it. The UNC shape is converted as its own case. Rows: "created root in the extended-length namespace" (they run where the marker exists, skip where it cannot). mkdir answers undefined when the final directory already exists - including when it is a link to a directory, since the stat after the create succeeds - and fs.access follows that link. No chain means the created-directory loop never ran, so a parent planted as a link after the caller authorized it was unchecked. When no pin names the parent, the parent's realpath is compared against the authorized locations the way a created directory is; a parent a pin does name stays the ancestry recheck's to report, in its own terms. Rows: "effective parent validated when mkdir created nothing". safeWriteJson.test.ts assigned the lock double through a double assertion; AGENTS.md prefers a checked assignment, so the type of realLockfile.lock now binds at :926.
1 parent a8ea1b4 commit 79c25fe

3 files changed

Lines changed: 152 additions & 4 deletions

File tree

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

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2241,3 +2241,100 @@ describe("asks landed at the refreshed 2357 footing", () => {
22412241
})
22422242
})
22432243
})
2244+
2245+
describe("created root in the extended-length namespace", () => {
2246+
// Node reports the directory mkdir created through the Windows extended-length namespace, and
2247+
// only Windows spells a UNC root that way: the marker plus the "UNC" label stands for the
2248+
// leading backslash pair. These rows run where that marker can appear and are skipped where it
2249+
// cannot, so the spelling the fix answers is tested rather than assumed.
2250+
const markerVisibleHere = process.platform === "win32"
2251+
const conditionalIt = markerVisibleHere ? it : it.skip
2252+
const serverRoot = "\\\\server\\share\\ws"
2253+
const created = "\\\\server\\share\\ws\\new"
2254+
const target = "\\\\server\\share\\ws\\new\\target.txt"
2255+
const escaped = "\\\\outside\\share\\new"
2256+
// The answer mkdir gives for a UNC target on Node 22, in the namespace spelling.
2257+
const mkdirAnswer = "\\\\?\\UNC\\server\\share\\ws\\new"
2258+
function _uncScenario(redirectCreatedDirectory: boolean) {
2259+
vi.mocked(fs.realpath).mockImplementation(async (p) => {
2260+
const s = String(p)
2261+
// The planted redirect makes the created directory resolve under a host nothing pinned.
2262+
if (redirectCreatedDirectory && s === created) return escaped
2263+
return s
2264+
})
2265+
vi.mocked(fs.mkdir).mockResolvedValue(mkdirAnswer)
2266+
vi.mocked(fsSync.openSync).mockReturnValue(1)
2267+
return [{ dir: serverRoot, dev: 1n, ino: 100n, resolvedPath: serverRoot }]
2268+
}
2269+
beforeEach(() => {
2270+
mockDefaults()
2271+
vi.mocked(fsSync.writeSync).mockImplementation((...args: unknown[]) =>
2272+
typeof args[3] === "number" ? args[3] : 0,
2273+
)
2274+
})
2275+
conditionalIt("refuses to publish when the created UNC directory resolves under nothing the caller pinned", async () => {
2276+
const pin = _uncScenario(true)
2277+
const promise = safeWriteText(target, "data", {
2278+
platform: "linux",
2279+
expectedAncestorIdentities: pin,
2280+
})
2281+
await expect(promise).rejects.toBeInstanceOf(AncestorReplacedError)
2282+
await expect(promise).rejects.toThrow(/nothing the caller authorized/)
2283+
expect(fs.rename).not.toHaveBeenCalled()
2284+
expect(fs.link).not.toHaveBeenCalled()
2285+
})
2286+
conditionalIt("publishes when the created UNC directory resolves inside the location the caller pinned", async () => {
2287+
const pin = _uncScenario(false)
2288+
await expect(safeWriteText(target, "data", { platform: "linux", expectedAncestorIdentities: pin })).resolves.toBeUndefined()
2289+
expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), target)
2290+
})
2291+
})
2292+
2293+
describe("effective parent validated when mkdir created nothing", () => {
2294+
// mkdir names no first created directory when the final directory was already there, and a
2295+
// name that is a link to a directory answers the same way because the stat after the create
2296+
// succeeds. Nothing was created, so no created chain exists for the authorization loop, yet
2297+
// the parent this write publishes into can have become a link after the caller authorized it.
2298+
const pinned = path.resolve("/ws/a")
2299+
const parent = path.join(pinned, "new")
2300+
const escapedParent = path.resolve("/outside/new")
2301+
const target = path.join(parent, "target.txt")
2302+
function _scenario(parentResolvesElsewhere: boolean, pinGiven: boolean) {
2303+
vi.mocked(fs.realpath).mockImplementation(async (p) => {
2304+
const s = String(p)
2305+
if (parentResolvesElsewhere && s === parent) return escapedParent
2306+
return s
2307+
})
2308+
// Node 22 reports undefined for a recursive mkdir whose final directory already exists.
2309+
vi.mocked(fs.mkdir).mockResolvedValue(undefined)
2310+
vi.mocked(fsSync.openSync).mockReturnValue(1)
2311+
return pinGiven ? [{ dir: pinned, dev: 1n, ino: 100n, resolvedPath: pinned }] : undefined
2312+
}
2313+
beforeEach(() => {
2314+
mockDefaults()
2315+
vi.mocked(fsSync.writeSync).mockImplementation((...args: unknown[]) =>
2316+
typeof args[3] === "number" ? args[3] : 0,
2317+
)
2318+
})
2319+
it("refuses to publish when the parent that already existed resolves under nothing the caller pinned", async () => {
2320+
const pin = _scenario(true, true)
2321+
const promise = safeWriteText(target, "data", {
2322+
platform: "linux",
2323+
expectedAncestorIdentities: pin,
2324+
})
2325+
await expect(promise).rejects.toBeInstanceOf(AncestorReplacedError)
2326+
await expect(promise).rejects.toThrow(/nothing the caller authorized/)
2327+
expect(fs.rename).not.toHaveBeenCalled()
2328+
expect(fs.link).not.toHaveBeenCalled()
2329+
})
2330+
it("publishes when the parent that already existed resolves inside the location the caller pinned", async () => {
2331+
const pin = _scenario(false, true)
2332+
await expect(safeWriteText(target, "data", { platform: "linux", expectedAncestorIdentities: pin })).resolves.toBeUndefined()
2333+
expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), target)
2334+
})
2335+
it("publishes when the parent already existed and the caller pinned no location", async () => {
2336+
const pin = _scenario(true, false)
2337+
await expect(safeWriteText(target, "data", { platform: "linux", expectedAncestorIdentities: pin })).resolves.toBeUndefined()
2338+
expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), target)
2339+
})
2340+
})

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

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -426,13 +426,29 @@ function _preserveGroup(fd: number, gid: number): void {
426426
* otherwise a crash can drop an ancestor and with it the published file.
427427
*
428428
* On Windows the reported path carries the extended-length namespace marker, which is stripped
429-
* so the chain compares in the spelling the write itself works in. An answer that is not on
430-
* this path yields nothing, rather than syncing directories this write cannot place.
429+
* so the chain compares in the spelling the write itself works in. The marker has two shapes: the
430+
* drive shape \\\?C:\... and the UNC shape \\\?UNC\server\share\...,
431+
* whose root is spelled \\server\share\... once the marker is gone. Removing only the marker
432+
* characters from the UNC shape leaves \UNC\server\share\..., which reads as a path relative
433+
* to the current drive, so the walk below finds no root and yields nothing: the created-directory
434+
* authorization that reads this answer is skipped with it, and a directory this write created
435+
* under a planted link goes unchecked. The UNC shape is therefore converted as its own case. An
436+
* answer that is not on this path yields nothing, rather than syncing directories this write
437+
* cannot place.
431438
*/
432439
function _createdAncestorChain(createdRoot: string | undefined, dirPath: string): string[] {
433440
if (typeof createdRoot !== "string") return []
434441
const namespacePrefix = "\\\\?\\"
435-
const unprefixed = createdRoot.startsWith(namespacePrefix) ? createdRoot.slice(namespacePrefix.length) : createdRoot
442+
const uncNamespacePrefix = "\\\\?\\UNC\\"
443+
let unprefixed = createdRoot
444+
if (createdRoot.startsWith(uncNamespacePrefix)) {
445+
// The marker and the "UNC" label together stand for the leading \\, so the
446+
// converted spelling restores that root instead of leaving the label as a relative
447+
// first segment.
448+
unprefixed = "\\\\" + createdRoot.slice(uncNamespacePrefix.length)
449+
} else if (createdRoot.startsWith(namespacePrefix)) {
450+
unprefixed = createdRoot.slice(namespacePrefix.length)
451+
}
436452
const root = path.resolve(unprefixed)
437453
const chain: string[] = []
438454
let cursor = dirPath
@@ -683,6 +699,41 @@ export async function safeWriteText(
683699
}
684700
}
685701
}
702+
} else {
703+
// Nothing was created, which is what Node 22 reports when the final directory was already
704+
// there -- including when it is a symbolic link to a directory, because the stat that follows
705+
// the create succeeds and names no first created path. No chain means the loop above never
706+
// ran, yet the parent this write publishes into can still have become a link after the caller
707+
// authorized it: /ws/a pinned, /ws/a/new absent while the target was resolved, the name
708+
// planted as a link to /outside before the mkdir, and the access check above follows that link
709+
// and passes. The effective parent is checked the way the created chain is checked, so a
710+
// parent that resolves under nothing the caller pinned is refused before anything is staged.
711+
const authorized = _authorizedAncestorLocations(options)
712+
// A parent the caller named itself belongs to the ancestry recheck below: that check holds the
713+
// identity and the resolution the caller authorized against, and it reports a moved or re-pointed
714+
// pin in those terms. Only a parent no pin names -- the case the loop above would have judged had
715+
// anything been created -- is this branch's to judge.
716+
const resolvedParent = path.resolve(dirPath)
717+
const namedByCaller = authorized.some((pin) => pin.dir === resolvedParent)
718+
if (authorized.length > 0 && !namedByCaller) {
719+
const parentReal = await fs.realpath(dirPath).catch((error: unknown) => {
720+
const code = getErrorCode(error)
721+
// A parent that vanished since the mkdir is reported by the ancestry recheck below, which
722+
// knows whether the caller authorized that name; only a real inspection failure is this
723+
// write's to report here.
724+
if (code === "ENOENT" || code === "ENOTDIR") {
725+
return undefined
726+
}
727+
throw error
728+
})
729+
const pinned = _deepestAuthorizedLocation(authorized, parentReal ?? dirPath)
730+
if (pinned === undefined) {
731+
throw new AncestorReplacedError(dirPath, "resolves under nothing the caller authorized")
732+
}
733+
if (parentReal !== undefined && !_isInside(pinned.location, parentReal)) {
734+
throw new AncestorReplacedError(dirPath, "resolves outside the authorized location")
735+
}
736+
}
686737
}
687738

688739
// Create the staging directory only when we generate the temp file there;

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -923,7 +923,7 @@ describe("safeWriteJson", () => {
923923
}
924924
},
925925
)
926-
const lockMock = lockMockFn as unknown as typeof realLockfile.lock
926+
const lockMock: typeof realLockfile.lock = lockMockFn
927927
vi.doMock("proper-lockfile", () => ({
928928
...realLockfile,
929929
lock: lockMock,

0 commit comments

Comments
 (0)