@@ -34,6 +34,7 @@ vi.mock("fs/promises", async () => {
3434 rm : vi . fn ( actual . rm ) ,
3535 readdir : vi . fn ( actual . readdir ) ,
3636 mkdir : vi . fn ( actual . mkdir ) ,
37+ realpath : vi . fn ( actual . realpath ) ,
3738 }
3839 // fs.lstat is available via { ...actual }
3940
@@ -1071,6 +1072,131 @@ describe("safeWriteJson", () => {
10711072 expect ( await readFileContent ( currentTestFilePath ) ) . toEqual ( { after : true } )
10721073 } ,
10731074 )
1075+ // 2242: a dangling alias is not always an absent file. This row drives the
1076+ // interrupted-EPERM-fallback state directly instead of crashing a process.
1077+ // Needs symlinks, which are unprivileged on the Windows CI lane.
1078+ test . skipIf ( process . platform === "win32" ) (
1079+ "restores an interrupted backup rename so a write through the dangling alias succeeds" ,
1080+ async ( ) => {
1081+ const dir = path . join ( tempDir , "alias-recovery" )
1082+ await fs . mkdir ( dir )
1083+ const canonical = path . join ( dir , "t.json" )
1084+ const alias = path . join ( dir , "alias.json" )
1085+ // The state left between the EPERM fallback's two renames when the process
1086+ // dies after the backup rename: the canonical referent is gone, its backup
1087+ // sits beside it, and every write through the alias rejects as dangling.
1088+ const backup = path . join ( dir , ".t.json.bak_1700000000000_interrupted.tmp" )
1089+ await fsPromisesActuals . writeFile ! ( backup , JSON . stringify ( { old : 1 } ) )
1090+ await fs . symlink ( "t.json" , alias )
1091+
1092+ await safeWriteJson ( alias , { after : true } , { confineTo : dir } )
1093+
1094+ const published = JSON . parse ( await fs . readFile ( canonical , "utf8" ) )
1095+ expect ( published ) . toEqual ( { after : true } )
1096+ expect ( JSON . parse ( await fs . readFile ( alias , "utf8" ) ) ) . toEqual ( { after : true } )
1097+ const entries = await fs . readdir ( dir )
1098+ expect ( entries ) . not . toContain ( path . basename ( backup ) )
1099+ } ,
1100+ )
1101+
1102+ // 2247: the flush opens the staged file with r+. It must run while the
1103+ // staged file is still in its creation mode, before a restrictive copied
1104+ // mode can deny that descriptor and silently skip the sync.
1105+ test . skipIf ( process . platform === "win32" ) (
1106+ "flushes the staged file before the copied target mode can deny the sync descriptor" ,
1107+ async ( ) => {
1108+ await fsPromisesActuals . writeFile ! ( currentTestFilePath , JSON . stringify ( { before : true } ) )
1109+ fsSyncActual . chmodSync ( currentTestFilePath , 0o444 )
1110+ const consoleErrorSpy = vi . spyOn ( console , "error" ) . mockImplementation ( ( ) => { } )
1111+
1112+ await safeWriteJson ( currentTestFilePath , { after : true } )
1113+
1114+ expect ( consoleErrorSpy ) . not . toHaveBeenCalledWith ( expect . stringContaining ( "Failed to flush" ) )
1115+ expect ( await readFileContent ( currentTestFilePath ) ) . toEqual ( { after : true } )
1116+ expect ( fsSyncActual . statSync ( currentTestFilePath ) . mode & 0o777 ) . toBe ( 0o444 )
1117+ consoleErrorSpy . mockRestore ( )
1118+ } ,
1119+ )
1120+
1121+ // 2228: spelling is not containment. The root swap happens between the
1122+ // commit rename and the post-commit re-check - the exact window the
1123+ // confineTo doc says the checks cannot prevent - and must still report.
1124+ test ( "reports the escape when the confinement root is replaced after the commit rename" , async ( ) => {
1125+ const scope = path . join ( tempDir , "swap-root" )
1126+ await fs . mkdir ( scope )
1127+ const target = path . join ( scope , "mcp.json" )
1128+ const moved = path . join ( tempDir , "moved-root" )
1129+
1130+ await expect (
1131+ safeWriteJson (
1132+ target ,
1133+ { mcpServers : { } } ,
1134+ {
1135+ confineTo : scope ,
1136+ trace : ( event ) => {
1137+ // Synchronously, inside the trace hook fired after the commit rename:
1138+ // move the authorized directory out and drop a fresh empty one at
1139+ // the same spelling. Every relative check still passes; only the
1140+ // authorized root's identity can tell the two directories apart.
1141+ if ( event . stage === "write-complete" ) {
1142+ fsSyncActual . renameSync ( scope , moved )
1143+ fsSyncActual . mkdirSync ( scope )
1144+ }
1145+ } ,
1146+ } ,
1147+ ) ,
1148+ ) . rejects . toThrow ( ConfinedPathEscapeError )
1149+
1150+ // The committed bytes travelled with the moved directory - that is the
1151+ // physically-moved variant the option doc names: detection holds, the
1152+ // undo cannot address the moved file, and the write still fails closed.
1153+ const movedContent = JSON . parse ( fsSyncActual . readFileSync ( path . join ( moved , "mcp.json" ) , "utf8" ) )
1154+ expect ( movedContent ) . toEqual ( { mcpServers : { } } )
1155+ expect ( fsSyncActual . existsSync ( target ) ) . toBe ( false )
1156+ } )
1157+
1158+ // 2220: after the commit rename the backup is superseded content. A transient
1159+ // failure of the post-commit re-check must not rename it back over bytes
1160+ // that are already published.
1161+ test ( "keeps committed content when a transient post-commit failure reaches the rollback path" , async ( ) => {
1162+ const scope = path . join ( tempDir , "committed-scope" )
1163+ await fs . mkdir ( scope )
1164+ const target = path . join ( scope , "x.json" )
1165+ await fsPromisesActuals . writeFile ! ( target , JSON . stringify ( { old : 1 } ) )
1166+ // Force the EPERM fallback so a backup of the old content exists when the
1167+ // post-commit check fails: the first commit rename rejects and the
1168+ // fallback's two renames (the pass-through defaults) land the new content
1169+ // and keep the backup beside it.
1170+ vi . mocked ( fs . rename ) . mockImplementationOnce ( async ( ) => {
1171+ throw Object . assign ( new Error ( "EPERM: operation not permitted" ) , { code : "EPERM" } )
1172+ } )
1173+ const escapee = path . join ( tempDir , "fake-escape.json" )
1174+ await expect (
1175+ safeWriteJson (
1176+ target ,
1177+ { new : 2 } ,
1178+ {
1179+ confineTo : scope ,
1180+ trace : ( event ) => {
1181+ // The first scope resolution after the commit rename is shown an
1182+ // escaped spelling that never existed; the target itself stayed in
1183+ // place the whole time, so this is the transient-failure shape.
1184+ if ( event . stage === "write-complete" ) {
1185+ vi . mocked ( fs . realpath ) . mockImplementationOnce ( async ( ) => escapee )
1186+ }
1187+ } ,
1188+ } ,
1189+ ) ,
1190+ ) . rejects . toThrow ( ConfinedPathEscapeError )
1191+ // The escaped spelling never existed, so the undo removed nothing - and
1192+ // the rollback must not resurrect {old:1} where {new:2} already committed.
1193+ expect ( JSON . parse ( await fs . readFile ( target , "utf8" ) ) ) . toEqual ( { new : 2 } )
1194+ expect ( fsSyncActual . existsSync ( escapee ) ) . toBe ( false )
1195+ // The orphaned backup is kept for the next writer's recovery pass, which
1196+ // cleans leftovers beside an existing canonical file without restoring them.
1197+ const entries = await fs . readdir ( scope )
1198+ expect ( entries . some ( ( entry ) => entry . includes ( ".x.json.bak_" ) ) ) . toBe ( true )
1199+ } )
10741200 // The two failure paths of _copyTargetMode: a target whose mode cannot be read, and a staged
10751201 // file whose mode cannot be set. Both have to log and let the write finish, because the
10761202 // replacement protocol - not the mode - is what makes the publish atomic. They are driven
@@ -1123,6 +1249,12 @@ describe("safeWriteJson", () => {
11231249 await safeWriteJson ( currentTestFilePath , { after : true } )
11241250
11251251 expect ( await readFileContent ( currentTestFilePath ) ) . toEqual ( { after : true } )
1252+ // The staged file is created 0o600, so the mode that survives a failed chmod
1253+ // is the private staging mode - never the umask-derived default a 0o600
1254+ // target used to be published with when the copy failed.
1255+ if ( process . platform !== "win32" ) {
1256+ expect ( fsSyncActual . statSync ( currentTestFilePath ) . mode & 0o777 ) . toBe ( 0o600 )
1257+ }
11261258 expect ( consoleErrorSpy ) . toHaveBeenCalledWith ( expect . stringContaining ( "Failed to copy mode" ) , expect . anything ( ) )
11271259 consoleErrorSpy . mockRestore ( )
11281260 } , 20_000 )
0 commit comments