Skip to content

Commit d2b65a5

Browse files
easonLiangWorldedtecheasonLiangWorldedtech
authored andcommitted
fix(utils): take a confined write's scope identity from the directory that exists
A confined safeWriteJson call whose confineTo directory did not exist yet failed with a raw ENOENT before the lock was taken. _resolveScopeRoot resolves the nearest existing ancestor on purpose and re-joins the remainder, and the parent-directory creation below the confinement check is what brings that remainder into being, so the identity capture was stat'ing a re-joined path no name occupied yet. It now captures the identity of the deepest directory that does exist and compares that same directory at the post-commit re-check. Containment of the re-joined remainder is still decided by name on the resolved publish target, at the commit point and in the teardown check. Deliberately not changed: the post-commit re-check still compares only dev+ino. Adding safeWriteText's requirement that the authorized name also resolve to the location it named would change behaviour for a scope directory that already exists, which this fix leaves alone. The catch on the capture is a fallback for the lexical path _resolveScopeRoot returns when nothing on the chain canonicalizes; the fix itself is the existing-ancestor selection, and the two are individually sufficient - measured by mutating each one. The added row in safeWriteJson.test.ts drives the same defect with no symlink involved, so it runs on every lane; the symlinked row above it is gated off win32, which is why the hosted ubuntu misc shard was the only leg that ever showed this failure.
1 parent 3dcc4b6 commit d2b65a5

2 files changed

Lines changed: 55 additions & 19 deletions

File tree

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,6 +1060,22 @@ describe("safeWriteJson", () => {
10601060
},
10611061
)
10621062

1063+
// The same shape with no symlink involved, so it runs on every lane including the Windows one:
1064+
// the confined scope directory does not exist yet, and safeWriteJson creates the missing
1065+
// parent itself, below the confinement check. The identity captured for the post-commit
1066+
// re-check therefore cannot come from the re-joined scope path, which no name occupies
1067+
// yet, so it is taken from the nearest directory that does exist.
1068+
test("confines a write whose scope directory does not exist yet, with no symlink involved", async () => {
1069+
const base = path.join(tempDir, "first-run-project")
1070+
await fs.mkdir(base)
1071+
const scope = path.join(base, "nested")
1072+
const target = path.join(scope, "mcp.json")
1073+
1074+
await safeWriteJson(target, { mcpServers: {} }, { confineTo: scope })
1075+
1076+
expect(await readFileContent(target)).toEqual({ mcpServers: {} })
1077+
})
1078+
10631079
test.skipIf(process.platform === "win32")(
10641080
"preserves a restrictive 0o600 target mode through the atomic publish",
10651081
async () => {

‎src/utils/safeWriteJson.ts‎

Lines changed: 39 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -114,12 +114,18 @@ function createTempFilePath(absoluteFilePath: string, kind: "new" | "bak"): stri
114114
* scope path that itself runs through a symlink (macOS /var -> /private/var is the
115115
* common case) would compare lexically against a resolved target and reject every
116116
* legitimate in-scope write. When the scope does not exist yet, the nearest
117-
* existing ancestor is resolved and the remainder re-appended.
117+
* existing ancestor is resolved and the remainder re-appended. The existing ancestor
118+
* is returned alongside the re-joined root because the re-joined remainder has no
119+
* on-disk identity yet - the write creates it below the confinement check - so a
120+
* caller that needs an identity must take it from the prefix that does exist.
118121
*/
119-
async function _resolveScopeRoot(confineTo: string): Promise<string> {
122+
type ResolvedScopeRoot = { root: string; existingAncestor: string }
123+
124+
async function _resolveScopeRoot(confineTo: string): Promise<ResolvedScopeRoot> {
120125
const lexical = path.resolve(confineTo)
121126
try {
122-
return await fs.realpath(lexical)
127+
const real = await fs.realpath(lexical)
128+
return { root: real, existingAncestor: real }
123129
} catch (error: unknown) {
124130
// Only a missing path means "walk up and re-join". EACCES or ELOOP means the
125131
// scope cannot be canonicalized at all, and continuing would build a partly
@@ -133,13 +139,13 @@ async function _resolveScopeRoot(confineTo: string): Promise<string> {
133139
while (true) {
134140
const parent = path.dirname(ancestor)
135141
if (parent === ancestor) {
136-
return lexical
142+
return { root: lexical, existingAncestor: lexical }
137143
}
138144
missing.push(path.basename(ancestor))
139145
ancestor = parent
140146
try {
141147
const real = await fs.realpath(ancestor)
142-
return path.join(real, ...missing.reverse())
148+
return { root: path.join(real, ...missing.reverse()), existingAncestor: real }
143149
} catch (innerError: unknown) {
144150
if (getErrorCode(innerError) !== "ENOENT") {
145151
throw innerError
@@ -252,7 +258,7 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit
252258
// a directory renamed out from under a confined write and replaced at the same
253259
// spelling is a different directory, and only an identity comparison can tell
254260
// that the published bytes no longer sit in the directory the caller named.
255-
let authorizedScopeRoot: { root: string; dev: bigint; ino: bigint } | undefined
261+
let authorizedScopeRoot: { root: string; identityOf: string; dev: bigint; ino: bigint } | undefined
256262

257263
// Lock key: the symlink referent when the path is an existing symlink, so a
258264
// symlink alias and its referent share one lock. The key must be computable
@@ -270,10 +276,24 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit
270276
// ConfinedPathEscapeError). Repeated on the resolved publish target inside the
271277
// lock, since a peer writer may move the referent in between.
272278
if (confinementRoot !== undefined) {
273-
const scopeRoot = await _resolveScopeRoot(confinementRoot)
274-
_assertWithinScope(absoluteFilePath, await _resolveScopeRoot(lockKey), scopeRoot)
275-
const rootIdentity = await fs.stat(scopeRoot, { bigint: true })
276-
authorizedScopeRoot = { root: scopeRoot, dev: rootIdentity.dev, ino: rootIdentity.ino }
279+
const resolvedScope = await _resolveScopeRoot(confinementRoot)
280+
const scopeRoot = resolvedScope.root
281+
_assertWithinScope(absoluteFilePath, (await _resolveScopeRoot(lockKey)).root, scopeRoot)
282+
// The identity is taken from the deepest directory that actually exists, not from the
283+
// re-joined scope root: _resolveScopeRoot resolves the nearest existing ancestor on
284+
// purpose and the parent-directory creation below is what brings the remainder into
285+
// being, so a confined first-run write - a scope the caller declared but nobody has
286+
// created yet - had no name to stat here and threw a raw ENOENT instead of writing.
287+
// Containment of the remainder is still decided by name on the resolved publish
288+
// target, at the commit point and in the teardown check below.
289+
const identityOf = resolvedScope.existingAncestor
290+
const rootIdentity = await fs
291+
.stat(identityOf, { bigint: true })
292+
.catch((error: unknown) => (getErrorCode(error) === "ENOENT" ? undefined : Promise.reject(error)))
293+
authorizedScopeRoot =
294+
rootIdentity === undefined
295+
? undefined
296+
: { root: scopeRoot, identityOf, dev: rootIdentity.dev, ino: rootIdentity.ino }
277297
}
278298

279299
// Ensure directory structure exists with improved reliability
@@ -343,8 +363,8 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit
343363
break
344364
}
345365
if (confinementRoot !== undefined) {
346-
const scopeRoot = await _resolveScopeRoot(confinementRoot)
347-
_assertWithinScope(absoluteFilePath, await _resolveScopeRoot(recomputedLockKey), scopeRoot)
366+
const scopeRoot = (await _resolveScopeRoot(confinementRoot)).root
367+
_assertWithinScope(absoluteFilePath, (await _resolveScopeRoot(recomputedLockKey)).root, scopeRoot)
348368
}
349369
await releaseLock()
350370
releaseLock = async () => {}
@@ -369,8 +389,8 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit
369389
// re-resolves the tree at rename time. See the confineTo option doc for what the
370390
// two outcomes of that window are and why neither is claimed by this option.
371391
if (confinementRoot !== undefined) {
372-
const scopeRoot = await _resolveScopeRoot(confinementRoot)
373-
_assertWithinScope(absoluteFilePath, await _resolveScopeRoot(resolvedTargetPath), scopeRoot)
392+
const scopeRoot = (await _resolveScopeRoot(confinementRoot)).root
393+
_assertWithinScope(absoluteFilePath, (await _resolveScopeRoot(resolvedTargetPath)).root, scopeRoot)
374394
}
375395

376396
// Heal any state an interrupted previous write left behind: an absent
@@ -484,8 +504,8 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit
484504
// replaces the file it lands on, so the undo below is what keeps the escaped publish
485505
// from leaving our bytes in place of somebody else's.)
486506
if (confinementRoot !== undefined) {
487-
const publishedPath = await _resolveScopeRoot(resolvedTargetPath)
488-
const scopeRoot = authorizedScopeRoot?.root ?? (await _resolveScopeRoot(confinementRoot))
507+
const publishedPath = (await _resolveScopeRoot(resolvedTargetPath)).root
508+
const scopeRoot = authorizedScopeRoot?.root ?? (await _resolveScopeRoot(confinementRoot)).root
489509
try {
490510
_assertWithinScope(absoluteFilePath, publishedPath, scopeRoot)
491511
// Spelling is not containment: compare the authorized root's identity with
@@ -494,7 +514,7 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit
494514
// in a different directory than the one this write authorized under its lock.
495515
const authorized = authorizedScopeRoot
496516
if (authorized) {
497-
const liveRoot = await fs.stat(authorized.root, { bigint: true }).catch(() => undefined)
517+
const liveRoot = await fs.stat(authorized.identityOf, { bigint: true }).catch(() => undefined)
498518
if (!liveRoot || liveRoot.dev !== authorized.dev || liveRoot.ino !== authorized.ino) {
499519
throw new ConfinedPathEscapeError(absoluteFilePath, publishedPath, authorized.root)
500520
}
@@ -535,8 +555,8 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit
535555
if (confinementRoot !== undefined && resolvedTargetPath !== undefined) {
536556
let publishedPath: string | undefined
537557
try {
538-
publishedPath = await _resolveScopeRoot(resolvedTargetPath)
539-
_assertWithinScope(absoluteFilePath, publishedPath, await _resolveScopeRoot(confinementRoot))
558+
publishedPath = (await _resolveScopeRoot(resolvedTargetPath)).root
559+
_assertWithinScope(absoluteFilePath, publishedPath, (await _resolveScopeRoot(confinementRoot)).root)
540560
} catch (checkError: unknown) {
541561
if (checkError instanceof ConfinedPathEscapeError && publishedPath !== undefined) {
542562
await undoEscapedPublish(publishedPath, stagedBytes)

0 commit comments

Comments
 (0)