Skip to content

Commit 3fd1af2

Browse files
file-safety: accept a two-dotted directory name under a pin and pin created dirs by their own name
_isInside refused every name beginning with two dots, so a directory named ..cache sitting under a sole pin read as a walk out of it and the created-directory guard refused the write. It now refuses only an absolute answer and a traversal segment - ".." alone or ".." as the first segment - and accepts an ordinary child whose name happens to begin with two dots. The created-directory guard selected the authorized location by the created directory's resolved path, so with pins for /ws and /ws/a a created /ws/a/new that resolves into /ws/other selected the shallower /ws and then passed its own containment check. Selection is now made by the name the caller pinned (_deepestPinnedDirectory, which also honours the location a pinned alias was authorized against) and the resolved directory is only compared against that selection. The path-form parent branch is untouched. Regression rows: safeWriteText.spec.ts:2155 (two-dotted name publishes), :2181 (two pins, shallower resolved pin refused), :2217 (pinned-alias chain still publishes). The existing created-directory row at :2127 and the UNC row keep refusing the same scenarios and now assert the message the selection change produces. Legs: named services selection 4 failed | 100 passed over the head production with the new rows, 104 passed with the change; prettier 3.9.10 --check . exit 0; knip and src tsc byte-identical to the same host run at the untouched head.
1 parent e0f2186 commit 3fd1af2

2 files changed

Lines changed: 147 additions & 8 deletions

File tree

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

Lines changed: 92 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2131,7 +2131,9 @@ describe("asks landed at the refreshed 2357 footing", () => {
21312131
expectedAncestorIdentities: pin(pinned),
21322132
})
21332133
await expect(promise).rejects.toBeInstanceOf(AncestorReplacedError)
2134-
await expect(promise).rejects.toThrow(/nothing the caller authorized/)
2134+
// The pin covers the name mkdir reported, so the refusal now lands on the containment
2135+
// check that compares the resolved directory against the selected location.
2136+
await expect(promise).rejects.toThrow(/outside the authorized location/)
21352137
expect(fs.rename).not.toHaveBeenCalled()
21362138
expect(fs.link).not.toHaveBeenCalled()
21372139
})
@@ -2150,6 +2152,92 @@ describe("asks landed at the refreshed 2357 footing", () => {
21502152
await expect(promise).resolves.toBeUndefined()
21512153
expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), target)
21522154
})
2155+
it("publishes when a created directory merely has a name that begins with two dots under the pinned location", async () => {
2156+
// A directory named ..cache is an ordinary child of the location the caller pinned. The
2157+
// containment predicate read every name beginning with two dots as a walk out of the pin,
2158+
// so this write was refused with AncestorReplacedError before anything was staged, even
2159+
// though the pin the caller handed in covers it by its own name.
2160+
const pinned = path.resolve("/ws")
2161+
const created = path.join(pinned, "..cache")
2162+
const target = path.join(created, "new", "target.txt")
2163+
const enoent = () => Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
2164+
vi.mocked(fs.realpath).mockImplementation(async (p) => {
2165+
const s = String(p)
2166+
if (s === target) throw enoent()
2167+
// Nothing on this chain moved: the name carrying two leading dots is the only thing
2168+
// that separates this scenario from the one above.
2169+
return s
2170+
})
2171+
// The outermost directory mkdir created, in the spelling Node answers with.
2172+
vi.mocked(fs.mkdir).mockImplementation(async () => created)
2173+
vi.mocked(fsSync.openSync).mockReturnValue(1)
2174+
const promise = safeWriteText(target, "data", {
2175+
platform: "linux",
2176+
expectedAncestorIdentities: pin(pinned),
2177+
})
2178+
await expect(promise).resolves.toBeUndefined()
2179+
expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), target)
2180+
})
2181+
it("refuses to publish when a created directory resolves under a shallower pin than the name it was created under", async () => {
2182+
// Two ancestor pins, /ws and /ws/a. mkdir reports creating /ws/a/new, and the link is
2183+
// planted only when mkdir answers, so the name the chain carries is still the one the
2184+
// caller walked while the directory it resolves to now sits under the shallower pin.
2185+
// A pin selected by the resolved path finds /ws, whose containment check the redirected
2186+
// directory passes, so the write publishes through grounds the caller never authorized
2187+
// for that name.
2188+
const shallow = path.resolve("/ws")
2189+
const deep = path.resolve("/ws/a")
2190+
const created = path.join(deep, "new")
2191+
const redirected = path.join(shallow, "other", "new")
2192+
const target = path.join(created, "target.txt")
2193+
let linkPlanted = false
2194+
const enoent = () => Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
2195+
vi.mocked(fs.realpath).mockImplementation(async (p) => {
2196+
const s = String(p)
2197+
if (s === target || (s === created && !linkPlanted)) throw enoent()
2198+
return s === created ? redirected : s
2199+
})
2200+
vi.mocked(fs.mkdir).mockImplementation(async () => {
2201+
linkPlanted = true
2202+
return created
2203+
})
2204+
vi.mocked(fsSync.openSync).mockReturnValue(1)
2205+
const promise = safeWriteText(target, "data", {
2206+
platform: "linux",
2207+
expectedAncestorIdentities: [
2208+
{ dir: shallow, dev: 1n, ino: 100n, resolvedPath: shallow },
2209+
{ dir: deep, dev: 1n, ino: 100n, resolvedPath: deep },
2210+
],
2211+
})
2212+
await expect(promise).rejects.toBeInstanceOf(AncestorReplacedError)
2213+
await expect(promise).rejects.toThrow(/outside the authorized location/)
2214+
expect(fs.rename).not.toHaveBeenCalled()
2215+
expect(fs.link).not.toHaveBeenCalled()
2216+
})
2217+
it("publishes when the created chain sits under the location a pinned alias resolved to", async () => {
2218+
// The control on selecting by name. A caller that authorized a chain THROUGH an alias
2219+
// records the alias spelling as dir and the location that alias resolves to as
2220+
// resolvedPath, and mkdir answers on the location side. Selecting by dir alone would find
2221+
// no pin for this chain and refuse a write whose ancestry never moved.
2222+
const aliasDir = path.resolve("/ws/alias")
2223+
const authorizedLocation = path.resolve("/ws/real")
2224+
const created = path.join(authorizedLocation, "new")
2225+
const target = path.join(created, "target.txt")
2226+
const enoent = () => Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
2227+
vi.mocked(fs.realpath).mockImplementation(async (p) => {
2228+
const s = String(p)
2229+
if (s === target) throw enoent()
2230+
return path.resolve(s) === aliasDir ? authorizedLocation : s
2231+
})
2232+
vi.mocked(fs.mkdir).mockImplementation(async () => created)
2233+
vi.mocked(fsSync.openSync).mockReturnValue(1)
2234+
const promise = safeWriteText(target, "data", {
2235+
platform: "linux",
2236+
expectedAncestorIdentities: [{ dir: aliasDir, dev: 1n, ino: 100n, resolvedPath: authorizedLocation }],
2237+
})
2238+
await expect(promise).resolves.toBeUndefined()
2239+
expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), target)
2240+
})
21532241
})
21542242
describe("target group carried onto the staging descriptor before publication", () => {
21552243
// The commit publishes the staging inode, so the group the published file ends up in is whatever
@@ -2281,7 +2369,9 @@ describe("created root in the extended-length namespace", () => {
22812369
expectedAncestorIdentities: pin,
22822370
})
22832371
await expect(promise).rejects.toBeInstanceOf(AncestorReplacedError)
2284-
await expect(promise).rejects.toThrow(/nothing the caller authorized/)
2372+
// Selection is by the name the created chain carries, and the pin covers that name, so the
2373+
// refusal lands on the containment check rather than on the absence of any pin.
2374+
await expect(promise).rejects.toThrow(/outside the authorized location/)
22852375
expect(fs.rename).not.toHaveBeenCalled()
22862376
expect(fs.link).not.toHaveBeenCalled()
22872377
},

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

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,19 @@ function _authorizedAncestorLocations(options?: SafeWriteTextOptions): Authorize
380380
/** True when *target* is *dir* itself or under it on the same spelling. */
381381
function _isInside(dir: string, target: string): boolean {
382382
const rel = path.relative(dir, target)
383-
return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel))
383+
// A relative answer that comes back absolute is on another root - another drive on
384+
// Windows - and no descendant of *dir* spells itself that way.
385+
if (path.isAbsolute(rel)) {
386+
return false
387+
}
388+
// Only a traversal segment on its own leaves *dir*. A name that merely begins with two
389+
// dots, the way a directory named ..cache does, is an ordinary child of *dir*, and the
390+
// blanket test above refused descendants the caller had pinned by its own name. The first
391+
// segment is taken the way the platform that produced this path divides segments: both
392+
// spellings of the separator divide them on Windows, only the slash divides them
393+
// elsewhere. An empty first segment is *dir* itself, which is inside it.
394+
const firstSegment = rel.split(path.sep === "\\" ? /[\\/]/ : path.sep)[0]
395+
return firstSegment !== ".."
384396
}
385397

386398
/** The deepest pinned location that contains *target*, if the caller pinned one. */
@@ -397,6 +409,36 @@ function _deepestAuthorizedLocation(locations: AuthorizedLocation[], target: str
397409
return deepest
398410
}
399411

412+
/** The deepest location the caller pinned that contains the *name* at *target*.
413+
*
414+
* Selection here is by the spelling the caller authorized, never by where the thing on
415+
* disk happens to resolve to. For a pin built from expectedResolvedPath those are the same
416+
* string. For an identity pin the caller walked a name, so the name is the comparison, and
417+
* where the caller walked through a symlink alias it recorded the location that alias
418+
* resolved to, which stands for the same decision and is compared as well. What the
419+
* resolved path of *target* is reserved for is the containment check the caller's decision
420+
* feeds: a selection that used it would let a directory created under a deep pin move
421+
* itself under a shallower one by becoming a link, and pass the check that was supposed to
422+
* catch exactly that.
423+
*/
424+
function _deepestPinnedDirectory(locations: AuthorizedLocation[], target: string): AuthorizedLocation | undefined {
425+
let deepest: AuthorizedLocation | undefined
426+
for (const candidate of locations) {
427+
// Either spelling is the caller's own decision: the name it walked, or the location
428+
// it recorded that name resolving to when it walked through a symlink alias. A
429+
// path-form pin has no separate spelling, so its two fields are the same string.
430+
const underTheNamedSpelling = _isInside(candidate.dir, target)
431+
const underTheAuthorizedLocation = _isInside(candidate.location, target)
432+
if (!underTheNamedSpelling && !underTheAuthorizedLocation) {
433+
continue
434+
}
435+
if (!deepest || candidate.dir.length > deepest.dir.length) {
436+
deepest = candidate
437+
}
438+
}
439+
return deepest
440+
}
441+
400442
/** Re-apply the target's group to the staging descriptor before publication.
401443
*
402444
* The commit publishes this inode, so whatever the staging file carries when the descriptor closes is
@@ -673,10 +715,14 @@ export async function safeWriteText(
673715
// caller never walked - because it was not there when the caller authorized - can be a link
674716
// by the time mkdir reaches it, so the parent this write created sits outside the authorized
675717
// chain while still being reported as this write's parent, and the fsync chain alone would
676-
// then sync and publish through it. Compare each created directory with the deepest location
677-
// the caller pinned; a created directory under nothing the caller pinned has left the
678-
// authorized chain by construction. A caller that pinned no location has nothing to compare
679-
// against and keeps its current behaviour.
718+
// then sync and publish through it. Pick the location the caller pinned by the NAME each
719+
// created directory carries - never by where that name happens to resolve to - and only
720+
// then compare the resolved directory against it. A created directory under nothing the
721+
// caller pinned has left the authorized chain by construction, and so has one that resolves
722+
// out of the location its own name selected, which is the bypass a resolved-path selection
723+
// hid: a created directory under a deep pin that becomes a link into a shallower pin's
724+
// grounds passed the check meant to catch it. A caller that pinned no location has nothing
725+
// to compare against and keeps its current behaviour.
680726
if (createdAncestors.length > 0) {
681727
const authorized = _authorizedAncestorLocations(options)
682728
if (authorized.length > 0) {
@@ -691,7 +737,10 @@ export async function safeWriteText(
691737
}
692738
throw error
693739
})
694-
const pinned = _deepestAuthorizedLocation(authorized, createdReal ?? created)
740+
// Selected by the name, so a redirect of the created directory cannot move the
741+
// answer to a shallower pin; the resolved directory is compared against the
742+
// selection below rather than feeding it.
743+
const pinned = _deepestPinnedDirectory(authorized, created)
695744
if (pinned === undefined) {
696745
throw new AncestorReplacedError(created, "was created under nothing the caller authorized")
697746
}

0 commit comments

Comments
 (0)