Skip to content

Commit 74f5eb2

Browse files
Merge u4 head 416179d into the guard-core unit
Stacked-unit refresh: the previous merge carried b86511f, so this brings the write-protocol head current and keeps one seam text under the guard-core unit. Two regions conflicted and both have the same shape. This branch rewrote src/services/file-safety/safeWriteText.ts into the guard-core design (conditional failIfExist commit, directory-identity authorization, backup-orphan handling), while the incoming head kept mechanisms from its own copy of the same module. Both sides were read before resolving, and neither drop below is left silent. 1. Staging-file identity. The incoming side carries a (dev, ino) comparison that refuses a staging path which is an alias of the target, because in backup mode the failure handler would unlink the only remaining name. Measured: grepping this branch's pre-merge head 33e9200 for "target itself" returns 0 lines tree-wide in src, source and specs alike, while the incoming head carries the block at src/services/file-safety/safeWriteText.ts:341-356. Resolution: this branch's version, 23 incoming lines not taken. What remains here guards the staging path by directory and by regular-file-not-link only, so the alias hazard is a gap to close in the unit that owns the staging path rather than something to re-add inside a refresh commit. 2. DACL inspection. The incoming side refuses to publish when the target exists but its access rights could not be read (getErrorCode(error) !== "ENOENT" yields DaclInspectionError before anything is committed). This branch's copy clears daclDumpPath and publishes without DACL preservation instead. Measured: DaclInspectionError has 0 references tree-wide at 33e9200, and no spec in either lineage asserts an inspection-failure path. Resolution: this branch's version, 3 lines kept and 5 incoming lines dropped. Stated plainly, the consequence is that on win32 a target whose ACL this call could not read is replaced without preserving its rights, where the incoming head failed first. After the merge, 6 errorCode(...) call sites in this branch's added code had no definition left, because the definition they used was the duplicate that 416179d deletes. They now call the exported getErrorCode from src/utils/errorCode.ts, which this file already imports. All 6 compare the returned code against a string code literal, so the same equivalence argument recorded in 416179d covers them. Gates, the mutation-cap measurement and the two gaps as review-visible text are in the follow-up comment on PR #1914.
2 parents 33e9200 + 416179d commit 74f5eb2

2 files changed

Lines changed: 20 additions & 39 deletions

File tree

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

Lines changed: 18 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import * as fsSync from "fs"
33
import * as path from "path"
44
import { execFile } from "child_process"
55

6+
import { getErrorCode } from "../../utils/errorCode"
7+
68
export interface SafeWriteTextOptions {
79
/**
810
* When true, preserve the old-file semantics: rename target -> backup first,
@@ -261,10 +263,6 @@ function _stagingDir(dir: string): string {
261263
return sd
262264
}
263265

264-
function _fsyncFile(fd: number): void {
265-
fsSync.fsyncSync(fd)
266-
}
267-
268266
/** Save the DACL of *srcPath* to a dump file on Windows.
269267
* Returns true when the dump was written successfully; false otherwise.
270268
* Never throws — callers treat failure as "skip DACL handling". */
@@ -310,31 +308,20 @@ async function _restoreDaclWindows(dirPath: string, dumpPath: string, execFileRu
310308
*/
311309
export async function resolvePublishTarget(absoluteFilePath: string): Promise<string> {
312310
return fs.realpath(absoluteFilePath).catch(async (error: unknown) => {
313-
if (errorCode(error) !== "ENOENT") throw error
311+
if (getErrorCode(error) !== "ENOENT") throw error
314312
// ENOENT also covers a dangling symlink, which must never be written through.
315313
// Only a lstat that also reports the path as absent may fall back to the
316314
// given path; a real lstat failure (EACCES, EIO) says nothing about whether
317315
// the path is a link, so falling back would write through a link we were
318316
// simply not allowed to inspect.
319317
const linkStat = await fs.lstat(absoluteFilePath).catch((lstatError: unknown) => {
320-
if (errorCode(lstatError) === "ENOENT") return undefined
318+
if (getErrorCode(lstatError) === "ENOENT") return undefined
321319
throw lstatError
322320
})
323321
if (linkStat?.isSymbolicLink()) throw error
324322
return await canonicalizeNearestAncestor(absoluteFilePath)
325323
})
326324
}
327-
/**
328-
* Distinguish "the target does not exist" from a real I/O failure (EACCES,
329-
* EIO, ...). The mode-preservation path may only fall back to the fresh-file
330-
* default on ENOENT; any other failure is propagated, otherwise a restrictive
331-
* target (0o600) would be published with the default 0o644 through the rename.
332-
*/
333-
function errorCode(error: unknown): string | undefined {
334-
return typeof error === "object" && error !== null && "code" in error
335-
? String((error as { code: unknown }).code)
336-
: undefined
337-
}
338325

339326
/**
340327
* Canonicalize the parent directory and re-join the basename. fs.realpath
@@ -359,7 +346,7 @@ async function canonicalDirKey(absoluteFilePath: string): Promise<string> {
359346
const missing: string[] = []
360347
for (;;) {
361348
const canonical = await fs.realpath(cursor).catch((error: unknown) => {
362-
if (errorCode(error) === "ENOENT") return undefined
349+
if (getErrorCode(error) === "ENOENT") return undefined
363350
throw error
364351
})
365352
if (canonical !== undefined) {
@@ -391,7 +378,7 @@ async function canonicalizeNearestAncestor(absoluteFilePath: string): Promise<st
391378
const realPath = await fs.realpath(cursor)
392379
return missing.length > 0 ? path.join(realPath, ...missing.reverse()) : realPath
393380
} catch (error: unknown) {
394-
const code = errorCode(error)
381+
const code = getErrorCode(error)
395382
if (code !== "ENOENT" && code !== "ENOTDIR") {
396383
// A real inspection failure (EACCES, EIO) says nothing about the path's
397384
// identity. Returning a lexical key here would silently canonicalize a
@@ -519,7 +506,7 @@ export async function safeWriteText(
519506
targetMode = fsSync.statSync(targetPath).mode & 0o777
520507
targetExists = true
521508
} catch (error: unknown) {
522-
if (errorCode(error) !== "ENOENT") throw error
509+
if (getErrorCode(error) !== "ENOENT") throw error
523510
// target does not exist yet - keep the default
524511
}
525512
// openSync's creation mode is narrowed by the process umask, so an
@@ -538,7 +525,7 @@ export async function safeWriteText(
538525
while (offset < buffer.length) {
539526
offset += fsSync.writeSync(fd, buffer, offset, buffer.length - offset)
540527
}
541-
_fsyncFile(fd)
528+
fsSync.fsyncSync(fd)
542529
} finally {
543530
fsSync.closeSync(fd)
544531
}
@@ -553,15 +540,15 @@ export async function safeWriteText(
553540
try {
554541
targetMode = fsSync.statSync(targetPath).mode & 0o777
555542
} catch (error: unknown) {
556-
if (errorCode(error) !== "ENOENT") throw error
543+
if (getErrorCode(error) !== "ENOENT") throw error
557544
// target does not exist yet - keep the temp's default mode
558545
}
559546
const fd = fsSync.openSync(tempPath, "r+")
560547
try {
561548
if (targetMode !== null) {
562549
fsSync.fchmodSync(fd, targetMode)
563550
}
564-
_fsyncFile(fd)
551+
fsSync.fsyncSync(fd)
565552
} finally {
566553
fsSync.closeSync(fd)
567554
}
@@ -600,7 +587,7 @@ export async function safeWriteText(
600587
if (options?.expectedAncestorIdentities) {
601588
for (const expected of options.expectedAncestorIdentities) {
602589
const current = await fs.stat(expected.dir, { bigint: true }).catch((error: unknown) => {
603-
if (errorCode(error) === "ENOENT") {
590+
if (getErrorCode(error) === "ENOENT") {
604591
throw new AncestorReplacedError(expected.dir, "no longer exists")
605592
}
606593
throw error
@@ -619,7 +606,7 @@ export async function safeWriteText(
619606
// the user at a security problem that is not there - mirror the stat
620607
// call above, which maps only ENOENT and rethrows the rest.
621608
const resolvedDir = await fs.realpath(expected.dir).catch((error: unknown) => {
622-
const code = errorCode(error)
609+
const code = getErrorCode(error)
623610
if (code === "ENOENT" || code === "ENOTDIR") {
624611
return undefined
625612
}
@@ -664,7 +651,7 @@ export async function safeWriteText(
664651
// flag the staged temp file uses above.
665652
const backupFd = fsSync.openSync(backupPath, "r+")
666653
try {
667-
_fsyncFile(backupFd)
654+
fsSync.fsyncSync(backupFd)
668655
} finally {
669656
fsSync.closeSync(backupFd)
670657
}
@@ -682,7 +669,7 @@ export async function safeWriteText(
682669
backupCleanupError = null
683670
break
684671
} catch (cleanupError: unknown) {
685-
if (errorCode(cleanupError) === "ENOENT") {
672+
if (getErrorCode(cleanupError) === "ENOENT") {
686673
// Already gone: that is exactly the outcome the cleanup wanted, so stop
687674
// rather than unlinking the same path a second time.
688675
backupCleanupError = null
@@ -699,7 +686,7 @@ export async function safeWriteText(
699686
}
700687
releaseBackupOnSuccess = true
701688
} catch (err: unknown) {
702-
if (errorCode(err) !== "ENOENT") throw err
689+
if (getErrorCode(err) !== "ENOENT") throw err
703690
}
704691
}
705692

@@ -712,7 +699,7 @@ export async function safeWriteText(
712699
try {
713700
await fs.link(tempPath, targetPath)
714701
} catch (error: unknown) {
715-
const code = errorCode(error)
702+
const code = getErrorCode(error)
716703
if (code === "EEXIST") {
717704
throw new TargetExistsError(targetPath)
718705
}
@@ -753,7 +740,7 @@ export async function safeWriteText(
753740
try {
754741
const dirFd = fsSync.openSync(dirPath, "r")
755742
try {
756-
_fsyncFile(dirFd)
743+
fsSync.fsyncSync(dirFd)
757744
} finally {
758745
fsSync.closeSync(dirFd)
759746
}
@@ -789,7 +776,7 @@ export async function safeWriteText(
789776
backupCleanupError = null
790777
break
791778
} catch (cleanupError: unknown) {
792-
if (errorCode(cleanupError) === "ENOENT") {
779+
if (getErrorCode(cleanupError) === "ENOENT") {
793780
backupCleanupError = null
794781
break
795782
}

‎src/utils/safeWriteJson.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ async function _resolveScopeRoot(confineTo: string): Promise<string> {
118118
// scope cannot be canonicalized at all, and continuing would build a partly
119119
// lexical root that can disagree with the canonical target - the failure has to
120120
// surface rather than decide the scope from a guess.
121-
if (_scopeErrorCode(error) !== "ENOENT") {
121+
if (getErrorCode(error) !== "ENOENT") {
122122
throw error
123123
}
124124
const missing: string[] = []
@@ -134,7 +134,7 @@ async function _resolveScopeRoot(confineTo: string): Promise<string> {
134134
const real = await fs.realpath(ancestor)
135135
return path.join(real, ...missing.reverse())
136136
} catch (innerError: unknown) {
137-
if (_scopeErrorCode(innerError) !== "ENOENT") {
137+
if (getErrorCode(innerError) !== "ENOENT") {
138138
throw innerError
139139
}
140140
}
@@ -155,12 +155,6 @@ function _assertWithinScope(requestedPath: string, candidatePath: string, scopeR
155155
}
156156
}
157157

158-
function _scopeErrorCode(error: unknown): string | undefined {
159-
return typeof error === "object" && error !== null && "code" in error
160-
? (error as { code?: string }).code
161-
: undefined
162-
}
163-
164158
/**
165159
* The scope root a caller declared, or undefined when no scope was declared.
166160
* Confinement is active whenever confineTo is DEFINED: a declared root that is

0 commit comments

Comments
 (0)