11// Tests path boundary enforcement for safe file access.
2+ import fsSync from "node:fs" ;
23import fs from "node:fs/promises" ;
34import path from "node:path" ;
4- import { describe , expect , it } from "vitest" ;
5+ import { afterEach , describe , expect , it , vi } from "vitest" ;
56import { withTestDir } from "../test-helpers/temp-dir.js" ;
6- import { resolveRootPath , resolveRootPathSync } from "./boundary-path.js" ;
7+ import {
8+ resolveIdentityPathViaExistingAncestorSync ,
9+ resolveRootPath ,
10+ resolveRootPathSync ,
11+ } from "./boundary-path.js" ;
712import { isPathInside } from "./path-guards.js" ;
813
14+ afterEach ( ( ) => {
15+ vi . restoreAllMocks ( ) ;
16+ } ) ;
17+
918function createSeededRandom ( seed : number ) : ( ) => number {
1019 let state = seed >>> 0 ;
1120 return ( ) => {
@@ -14,6 +23,53 @@ function createSeededRandom(seed: number): () => number {
1423 } ;
1524}
1625
26+ describe ( "resolveIdentityPathViaExistingAncestorSync" , ( ) => {
27+ it ( "continues through native realpath failures to preserve ancestor identity" , ( ) => {
28+ const aliasRoot = path . resolve ( "identity-alias" ) ;
29+ const targetPath = path . join ( aliasRoot , "locked" , "leaf" ) ;
30+ const lockedPath = path . dirname ( targetPath ) ;
31+ const canonicalRoot = path . resolve ( "identity-real" ) ;
32+ const calls : string [ ] = [ ] ;
33+
34+ vi . spyOn ( fsSync . realpathSync , "native" ) . mockImplementation ( ( candidate ) => {
35+ const resolved = path . resolve ( String ( candidate ) ) ;
36+ calls . push ( resolved ) ;
37+ if ( resolved === aliasRoot ) {
38+ return canonicalRoot ;
39+ }
40+ throw new Error ( "simulated realpath failure" ) ;
41+ } ) ;
42+
43+ expect ( resolveIdentityPathViaExistingAncestorSync ( targetPath ) ) . toBe (
44+ path . join ( canonicalRoot , "locked" , "leaf" ) ,
45+ ) ;
46+ expect ( calls ) . toEqual ( [ targetPath , lockedPath , aliasRoot ] ) ;
47+ } ) ;
48+
49+ it ( "falls back lexically only after native realpath fails through the root" , ( ) => {
50+ const targetPath = path . resolve ( "identity-alias" , "locked" , "leaf" ) ;
51+ const calls : string [ ] = [ ] ;
52+ const expectedCalls : string [ ] = [ ] ;
53+ let cursor = targetPath ;
54+ while ( true ) {
55+ expectedCalls . push ( cursor ) ;
56+ const parent = path . dirname ( cursor ) ;
57+ if ( parent === cursor ) {
58+ break ;
59+ }
60+ cursor = parent ;
61+ }
62+
63+ vi . spyOn ( fsSync . realpathSync , "native" ) . mockImplementation ( ( candidate ) => {
64+ calls . push ( path . resolve ( String ( candidate ) ) ) ;
65+ throw new Error ( "simulated realpath failure" ) ;
66+ } ) ;
67+
68+ expect ( resolveIdentityPathViaExistingAncestorSync ( targetPath ) ) . toBe ( targetPath ) ;
69+ expect ( calls ) . toEqual ( expectedCalls ) ;
70+ } ) ;
71+ } ) ;
72+
1773describe ( "resolveRootPath" , ( ) => {
1874 it ( "resolves symlink parents with non-existent leafs inside root" , async ( ) => {
1975 if ( process . platform === "win32" ) {
0 commit comments