diff --git a/config/scripts/pr-package-test-paths.mjs b/config/scripts/pr-package-test-paths.mjs index 2717f67f41e3..3e0dc149916e 100644 --- a/config/scripts/pr-package-test-paths.mjs +++ b/config/scripts/pr-package-test-paths.mjs @@ -106,7 +106,8 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'src/main/managed-server/install/remote-node-runtime-store-windows.test.ts', 'src/main/skills/skill-windows-rename-contention.integration.test.ts', 'src/main/skills/bundled-skill-install/local-host.test.ts', - 'src/main/skills/bundled-skill-install/plan-selection.test.ts' + 'src/main/skills/bundled-skill-install/plan-selection.test.ts', + 'src/main/ipc/filesystem/filesystem-read-dir-unc-drive.test.ts' ] const WINDOWS_PROCESS_PROBE_PREFIXES = [ diff --git a/src/main/hooks-orca-yaml-unc-drive.test.ts b/src/main/hooks-orca-yaml-unc-drive.test.ts new file mode 100644 index 000000000000..1aba51458e05 --- /dev/null +++ b/src/main/hooks-orca-yaml-unc-drive.test.ts @@ -0,0 +1,44 @@ +import type * as NodeFs from 'node:fs' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const fsMock = vi.hoisted(() => ({ existsSync: vi.fn(), readFileSync: vi.fn() })) +vi.mock('node:fs', async (importOriginal) => ({ + ...(await importOriginal()), + ...fsMock +})) + +import { hasHooksFile, hasUnrecognizedOrcaYamlKeys, loadHooks } from './hooks' + +const UNC = String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\app` +const DRIVE_YAML = String.raw`C:\src\app\orca.yaml` +const originalPlatform = process.platform + +describe('orca.yaml of a UNC drive-mount repo', () => { + beforeEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + // WSL 2.7 refuses Windows access to a drive mount over UNC (existsSync swallows it as false). + fsMock.existsSync.mockImplementation((path: string) => path === DRIVE_YAML) + fsMock.readFileSync.mockImplementation((path: string) => { + if (path !== DRIVE_YAML) { + throw Object.assign(new Error(`EPERM: operation not permitted, open '${path}'`), { + code: 'EPERM' + }) + } + return 'scripts:\n setup: pnpm install\nfutureKey: 1\n' + }) + }) + + afterEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) + }) + + it('reads the setup hooks through the drive path', () => { + expect(hasHooksFile(UNC)).toBe(true) + expect(loadHooks(UNC)?.scripts?.setup).toBe('pnpm install') + expect(hasUnrecognizedOrcaYamlKeys(UNC)).toBe(true) + expect(fsMock.readFileSync).not.toHaveBeenCalledWith( + expect.stringMatching(/^\\\\/), + expect.anything() + ) + }) +}) diff --git a/src/main/hooks.ts b/src/main/hooks.ts index c1fed732ec3f..07728e4cc540 100644 --- a/src/main/hooks.ts +++ b/src/main/hooks.ts @@ -10,6 +10,7 @@ import { promptGuardShellEnv } from './git/runner' import { dropIncoherentCondaActivationEnv } from './pty/conda-activation-env' import { toLinuxPath } from './wsl' import { runWslProcess } from './wsl/wsl-runner' +import { windowsFsPath } from './wsl/wsl-unc-drive-fs-path' import type { HookRuntimeTarget } from './hook-runtime-target' import type { OrcaHooks } from '../shared/orca-yaml-hook-types' import type { Repo } from '../shared/repo-types' @@ -98,8 +99,13 @@ function getHookShell(): string | undefined { export { parseOrcaYaml } +// A UNC drive-mount repo's file opens only through its drive path. +function orcaYamlPath(repoPath: string): string { + return windowsFsPath(join(repoPath, 'orca.yaml')) +} + export function loadHooks(repoPath: string): OrcaHooks | null { - const yamlPath = join(repoPath, 'orca.yaml') + const yamlPath = orcaYamlPath(repoPath) if (!existsSync(yamlPath)) { return null } @@ -113,7 +119,7 @@ export function loadHooks(repoPath: string): OrcaHooks | null { } export function hasHooksFile(repoPath: string): boolean { - return existsSync(join(repoPath, 'orca.yaml')) + return existsSync(orcaYamlPath(repoPath)) } // Unknown keys suggest a newer config format; let the UI offer an update. @@ -128,7 +134,7 @@ const RECOGNIZED_ORCA_YAML_KEYS = new Set([ export function hasUnrecognizedOrcaYamlKeys(repoPath: string): boolean { try { - const content = readFileSync(join(repoPath, 'orca.yaml'), 'utf-8') + const content = readFileSync(orcaYamlPath(repoPath), 'utf-8') for (const line of iterateLfScriptLines(content)) { // A bare key: is valid YAML when its block value follows on the next line. const m = line.match(/^([A-Za-z][A-Za-z0-9_-]*):(\s|$)/) diff --git a/src/main/ipc/filesystem/filesystem-auth.ts b/src/main/ipc/filesystem/filesystem-auth.ts index 35fb9711f6b7..fa3fb311a446 100644 --- a/src/main/ipc/filesystem/filesystem-auth.ts +++ b/src/main/ipc/filesystem/filesystem-auth.ts @@ -1,6 +1,7 @@ import { resolve, dirname, basename } from 'node:path' import type { RuntimeStore } from '../../runtime/runtime-store-contract' -import { lstat, realpath } from 'node:fs/promises' +import { lstat } from 'node:fs/promises' +import { realpathAcrossWslDriveMount } from '../../wsl/wsl-unc-drive-fs-path' import { PATH_OUTSIDE_ALLOWED_DIRECTORIES } from '../../../shared/local-file-access' import { getAllowedRoots } from './filesystem-allowed-roots' import { isDescendantOrEqual, isENOENT, normalizeExistingPath } from './filesystem-path-containment' @@ -58,7 +59,7 @@ export async function resolveAuthorizedPath( // Canonicalize the parent so ancestor symlinks can't redirect outside allowed roots, but keep the leaf so delete/rename act on the link itself. let realParent: string try { - realParent = await realpath(dirname(resolvedTarget)) + realParent = await realpathAcrossWslDriveMount(dirname(resolvedTarget)) } catch (error) { if (isENOENT(error)) { return resolveAuthorizedMissingPath(resolvedTarget, store, allowedRoots) @@ -79,7 +80,7 @@ export async function resolveAuthorizedPath( try { // Normalize Windows/WSL realpath output before comparing allow-list roots. - const realTarget = resolve(await realpath(resolvedTarget)) + const realTarget = resolve(await realpathAcrossWslDriveMount(resolvedTarget)) if ( !(await isPathAllowedIncludingRegisteredWorktrees(realTarget, store, { canonicalSourcePath: resolvedTarget, @@ -107,7 +108,7 @@ async function resolveAuthorizedMissingPath( while (true) { try { - const realAncestor = await realpath(existingAncestor) + const realAncestor = await realpathAcrossWslDriveMount(existingAncestor) const candidateTarget = resolve(realAncestor, ...missingSegments) if ( !(await isPathAllowedIncludingRegisteredWorktrees(candidateTarget, store, { diff --git a/src/main/ipc/filesystem/filesystem-path-containment.ts b/src/main/ipc/filesystem/filesystem-path-containment.ts index 2726315e44a4..8ed72d91c665 100644 --- a/src/main/ipc/filesystem/filesystem-path-containment.ts +++ b/src/main/ipc/filesystem/filesystem-path-containment.ts @@ -1,6 +1,6 @@ import { resolve, relative, isAbsolute, sep, dirname } from 'node:path' import { statSync } from 'node:fs' -import { realpath } from 'node:fs/promises' +import { realpathAcrossWslDriveMount } from '../../wsl/wsl-unc-drive-fs-path' import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' /** Check native-path containment; accept Unicode-equivalent spellings only after proving filesystem identity. */ @@ -81,7 +81,7 @@ export function isPathAbsentError(error: unknown): boolean { export async function normalizeExistingPath(resolvedPath: string): Promise { try { - return resolve(await realpath(resolvedPath)) + return resolve(await realpathAcrossWslDriveMount(resolvedPath)) } catch (error) { if (isENOENT(error)) { return resolvedPath diff --git a/src/main/ipc/filesystem/filesystem-read-dir-unc-drive.test.ts b/src/main/ipc/filesystem/filesystem-read-dir-unc-drive.test.ts new file mode 100644 index 000000000000..75edab580df6 --- /dev/null +++ b/src/main/ipc/filesystem/filesystem-read-dir-unc-drive.test.ts @@ -0,0 +1,126 @@ +import path from 'node:path' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + handlers, + store, + dirEntry, + readdirMock, + realpathMock, + resetFilesystemIpcMocks +} from './filesystem-test-harness' + +const diskPreconditionMock = vi.hoisted(() => ({ writeLocalTextFileWithDiskPrecondition: vi.fn() })) +vi.mock('./local-disk-write-precondition', () => diskPreconditionMock) +vi.mock('electron', async () => (await import('./filesystem-test-harness')).electronMock) +vi.mock('fs/promises', async () => (await import('./filesystem-test-harness')).fsPromisesMock) +vi.mock('node:fs/promises', async () => (await import('./filesystem-test-harness')).fsPromisesMock) +vi.mock( + '../../wsl-unc-delete', + async () => (await import('./filesystem-test-harness')).wslUncDeleteMock +) +vi.mock( + '../../crash-reporting/crash-breadcrumb-store', + async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock +) +vi.mock( + '../../git/status', + async () => (await import('./filesystem-test-harness')).gitStatusModuleMock +) +vi.mock( + '../../git/check-ignored-paths', + async () => (await import('./filesystem-test-harness')).gitIgnoredPathsMock +) +vi.mock( + '../../git/worktree', + async () => (await import('./filesystem-test-harness')).gitWorktreeMock +) +vi.mock( + '../../text-generation/commit-message-text-generation', + async () => (await import('./filesystem-test-harness')).textGenerationModuleMock +) +vi.mock( + '../../text-generation/pull-request-context', + async () => (await import('./filesystem-test-harness')).pullRequestContextMock +) +vi.mock( + '../../source-control/pull-request-template', + async () => (await import('./filesystem-test-harness')).pullRequestTemplateMock +) +vi.mock( + '../../source-control/pull-request-linked-issue', + async () => (await import('./filesystem-test-harness')).pullRequestLinkedIssueMock +) + +import { PATH_OUTSIDE_ALLOWED_DIRECTORIES } from '../../../shared/local-file-access' +import { registerFilesystemHandlers } from './filesystem' +import { + invalidateAuthorizedRootsCache, + registerWorktreeRootsForRepo +} from '../registered-worktree-roots-cache' + +function eperm(syscall: string, target: string): Error { + return Object.assign(new Error(`EPERM: operation not permitted, ${syscall} '${target}'`), { + code: 'EPERM' + }) +} + +// Handler UNC authorization needs native Windows path resolution; runs in the Windows package lane. +describe.runIf(process.platform === 'win32')('fs:readDir on a UNC drive-mount project', () => { + beforeEach(() => { + resetFilesystemIpcMocks() + invalidateAuthorizedRootsCache() + }) + + it('lists the folder through its drive path, since WSL refuses the UNC one', async () => { + const unc = path.win32.join('\\\\wsl.localhost\\Ubuntu', 'mnt', 'c', 'src', 'app') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The harness store implements the accessors root registration reads. + registerWorktreeRootsForRepo(store as never, 'repo-1', [unc]) + // WSL 2.7 answers EPERM for every Windows access to a drive mount over UNC. + realpathMock.mockImplementation(async (target: string) => { + if (target.startsWith('\\\\')) { + throw eperm('realpath', target) + } + return target + }) + readdirMock.mockImplementation(async (target: string) => { + if (target.startsWith('\\\\')) { + throw eperm('scandir', target) + } + return [dirEntry({ name: 'src', directory: true }), dirEntry({ name: 'README.md' })] + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The harness store implements the accessors these handlers read. + registerFilesystemHandlers(store as never) + + await expect(handlers.get('fs:readDir')!(null, { dirPath: unc })).resolves.toEqual([ + { name: 'src', isDirectory: true, isSymlink: false }, + { name: 'README.md', isDirectory: false, isSymlink: false } + ]) + expect(readdirMock).toHaveBeenCalledWith('C:\\src\\app', { withFileTypes: true }) + }) + + it('still refuses a junction under the project that lands on another drive or outside it', async () => { + const unc = path.win32.join('\\\\wsl.localhost\\Ubuntu', 'mnt', 'c', 'src', 'app') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The harness store implements the accessors root registration reads. + registerWorktreeRootsForRepo(store as never, 'repo-1', [unc]) + const junctions: Record = { + 'C:\\src\\app\\other-drive': 'D:\\elsewhere', + 'C:\\src\\app\\outside': 'C:\\Users\\me\\secrets' + } + realpathMock.mockImplementation(async (target: string) => { + if (target.startsWith('\\\\')) { + throw eperm('realpath', target) + } + return junctions[target] ?? target + }) + readdirMock.mockResolvedValue([]) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The harness store implements the accessors these handlers read. + registerFilesystemHandlers(store as never) + + for (const name of ['other-drive', 'outside']) { + await expect( + handlers.get('fs:readDir')!(null, { dirPath: path.win32.join(unc, name) }) + ).rejects.toThrow(PATH_OUTSIDE_ALLOWED_DIRECTORIES) + } + expect(readdirMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/ipc/filesystem/filesystem-read-handlers.ts b/src/main/ipc/filesystem/filesystem-read-handlers.ts index 02c3f5f2a076..1f64bb5768b1 100644 --- a/src/main/ipc/filesystem/filesystem-read-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-read-handlers.ts @@ -24,6 +24,7 @@ import { buildReadDirErrorBreadcrumb, type ReadDirThrowSite } from '../readdir-e import type { FilesystemHandlerContext } from './filesystem-handler-context' import { registerFilesystemChunkReadHandler } from './filesystem-chunk-read-handler' import { readMediaPreview } from '../../media/media-preview-protocol' +import { windowsFsPath } from '../../wsl/wsl-unc-drive-fs-path' import { readLocalFileContent, readLocalLogSnapshot, @@ -49,7 +50,7 @@ export function registerFilesystemReadHandlers(context: FilesystemHandlerContext } const dirPath = await resolveDesktopAuthorizedPath(args.dirPath, store) throwSite = 'readdir' - const entries = await readdir(dirPath, { withFileTypes: true }) + const entries = await readdir(windowsFsPath(dirPath), { withFileTypes: true }) const mapped = await classifyFilesystemDirectoryEntries( args.dirPath, entries, diff --git a/src/main/ipc/filesystem/filesystem-symlink-directory-entries.ts b/src/main/ipc/filesystem/filesystem-symlink-directory-entries.ts index a9f4350e7a93..5dbdf03dc762 100644 --- a/src/main/ipc/filesystem/filesystem-symlink-directory-entries.ts +++ b/src/main/ipc/filesystem/filesystem-symlink-directory-entries.ts @@ -3,6 +3,7 @@ import { stat } from 'node:fs/promises' import { join } from 'node:path' import type { DirEntry } from '../../../shared/filesystem-entry-types' import { mapWithConcurrency } from '../../../shared/map-with-concurrency' +import { windowsFsPath } from '../../wsl/wsl-unc-drive-fs-path' export function classifyFilesystemDirectoryEntries( dirPath: string, @@ -15,7 +16,9 @@ export function classifyFilesystemDirectoryEntries( let isDirectory = !isSymlink && entry.isDirectory() if (isSymlink && followSymlinks) { try { - isDirectory = (await stat(await authorize(join(dirPath, entry.name)))).isDirectory() + isDirectory = ( + await stat(windowsFsPath(await authorize(join(dirPath, entry.name)))) + ).isDirectory() } catch { // Broken or unauthorized targets remain file-like. } diff --git a/src/main/ipc/hooks/register-worktree-hook-inspection-handler.ts b/src/main/ipc/hooks/register-worktree-hook-inspection-handler.ts index 699d022136fb..12ebcd751e70 100644 --- a/src/main/ipc/hooks/register-worktree-hook-inspection-handler.ts +++ b/src/main/ipc/hooks/register-worktree-hook-inspection-handler.ts @@ -3,6 +3,7 @@ import { getRepoDialableSshTargetId, type ExecutionHostId } from '../../../share import { isFolderRepo } from '../../../shared/repo-kind' import { inspectSetupScriptImportCandidates } from '../../../shared/setup-script-imports' import { joinWorktreeRelativePath } from '../../runtime/runtime-relative-paths' +import { windowsFsPath } from '../../wsl/wsl-unc-drive-fs-path' import { readFile, stat } from 'node:fs/promises' import { isENOENT } from '../filesystem/filesystem-path-containment' import { resolveRepoForExecutionHost } from '../worktrees/repo-host-ownership' @@ -22,7 +23,7 @@ export function registerWorktreeHookInspectionHandler(context: WorktreeIpcContex return inspectSetupScriptImportCandidates( async (relativePath) => { - const filePath = joinWorktreeRelativePath(repo.path, relativePath) + const filePath = windowsFsPath(joinWorktreeRelativePath(repo.path, relativePath)) try { return await readFile(filePath, 'utf-8') } catch (error) { @@ -34,7 +35,7 @@ export function registerWorktreeHookInspectionHandler(context: WorktreeIpcContex }, { fileExists: async (relativePath) => { - const filePath = joinWorktreeRelativePath(repo.path, relativePath) + const filePath = windowsFsPath(joinWorktreeRelativePath(repo.path, relativePath)) try { const fileStat = await stat(filePath) return !fileStat.isDirectory() diff --git a/src/main/ipc/hooks/worktree-hook-inspection-unc-drive.test.ts b/src/main/ipc/hooks/worktree-hook-inspection-unc-drive.test.ts new file mode 100644 index 000000000000..54715d93fe6f --- /dev/null +++ b/src/main/ipc/hooks/worktree-hook-inspection-unc-drive.test.ts @@ -0,0 +1,73 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { Repo } from '../../../shared/repo-types' + +const mocks = vi.hoisted(() => ({ + handlers: new Map unknown>(), + readFile: vi.fn(), + stat: vi.fn() +})) + +vi.mock('electron', () => ({ + ipcMain: { + handle: (channel: string, handler: (event: unknown, args: unknown) => unknown) => + mocks.handlers.set(channel, handler) + } +})) +vi.mock('node:fs/promises', () => ({ readFile: mocks.readFile, stat: mocks.stat })) + +import { registerWorktreeHookInspectionHandler } from './register-worktree-hook-inspection-handler' + +const UNC = String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\app` +const CONDUCTOR = JSON.stringify({ scripts: { setup: 'pnpm install' } }) +const originalPlatform = process.platform + +function eperm(path: string): Error { + return Object.assign(new Error(`EPERM: operation not permitted, open '${path}'`), { + code: 'EPERM' + }) +} + +function enoent(path: string): Error { + return Object.assign(new Error(`ENOENT: no such file, open '${path}'`), { code: 'ENOENT' }) +} + +describe('setup script import inspection of a UNC drive-mount project', () => { + beforeEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + // WSL 2.7 refuses Windows access to a drive mount over UNC; the drive path opens. + mocks.readFile.mockImplementation(async (path: string) => { + if (path.startsWith('\\\\')) { + throw eperm(path) + } + if (path === String.raw`C:\src\app\conductor.json`) { + return CONDUCTOR + } + throw enoent(path) + }) + mocks.stat.mockImplementation(async (path: string) => { + throw path.startsWith('\\\\') ? eperm(path) : enoent(path) + }) + }) + + afterEach(() => { + Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) + vi.restoreAllMocks() + }) + + it('reads the candidates through the drive path, without EPERM warnings', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const repo: Partial = { id: 'repo', path: UNC, kind: 'git', executionHostId: 'local' } + const store = { getRepos: () => [repo], getRepo: () => repo } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The handler reads only these store accessors. + registerWorktreeHookInspectionHandler({ store } as never) + + const candidates = await mocks.handlers.get('hooks:inspectSetupScriptImports')!(null, { + repoId: 'repo' + }) + + expect(candidates).toEqual([expect.objectContaining({ provider: 'conductor' })]) + expect(mocks.readFile).toHaveBeenCalledWith(String.raw`C:\src\app\conductor.json`, 'utf-8') + expect(mocks.readFile).not.toHaveBeenCalledWith(expect.stringMatching(/^\\\\/), 'utf-8') + expect(warn).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/runtime/runtime-repository-hooks-commands.ts b/src/main/runtime/runtime-repository-hooks-commands.ts index 702d7b659386..456fd1d0e305 100644 --- a/src/main/runtime/runtime-repository-hooks-commands.ts +++ b/src/main/runtime/runtime-repository-hooks-commands.ts @@ -1,5 +1,6 @@ import { getRepoDialableSshTargetId } from '../../shared/execution-host' import { createHash } from 'node:crypto' +import { windowsFsPath } from '../wsl/wsl-unc-drive-fs-path' import { readFile } from 'node:fs/promises' import type { Repo } from '../../shared/repo-types' import { getEffectiveHooks, hasHooksFile, hasUnrecognizedOrcaYamlKeys, loadHooks } from '../hooks' @@ -68,7 +69,7 @@ export class RuntimeRepositoryHooksCommands { return [] } return inspectSetupScriptImportCandidates(async (relativePath) => { - const filePath = joinWorktreeRelativePath(repo.path, relativePath) + const filePath = windowsFsPath(joinWorktreeRelativePath(repo.path, relativePath)) if (getRepoDialableSshTargetId(repo)) { return null } diff --git a/src/main/wsl/wsl-unc-drive-fs-path.test.ts b/src/main/wsl/wsl-unc-drive-fs-path.test.ts new file mode 100644 index 000000000000..3d478a9693e9 --- /dev/null +++ b/src/main/wsl/wsl-unc-drive-fs-path.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it, vi } from 'vitest' +import { + realpathAcrossWslDriveMount, + windowsFsPath, + wslUncDriveFsPath +} from './wsl-unc-drive-fs-path' + +const UNC = String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\app` + +// WSL 2.7 refuses every Windows access to a drive mount over UNC. +const deniedOnUnc = vi.fn(async (path: string): Promise => { + if (path.startsWith('\\\\') || path.startsWith('//')) { + throw Object.assign(new Error(`EPERM: operation not permitted, realpath '${path}'`), { + code: 'EPERM' + }) + } + return path +}) + +describe('wslUncDriveFsPath', () => { + it('opens a UNC drive-mount path through its drive, in either UNC spelling', () => { + expect(wslUncDriveFsPath(UNC, 'win32')).toBe(String.raw`C:\src\app`) + expect(wslUncDriveFsPath('//wsl$/Ubuntu/mnt/d/x', 'win32')).toBe(String.raw`D:\x`) + expect(wslUncDriveFsPath(String.raw`\\wsl.localhost\Ubuntu\mnt\c`, 'win32')).toBe('C:\\') + }) + + it('leaves distro folders, other paths and other platforms alone', () => { + expect(wslUncDriveFsPath(String.raw`\\wsl.localhost\Ubuntu\home\me\app`, 'win32')).toBeNull() + expect(wslUncDriveFsPath(String.raw`C:\src\app`, 'win32')).toBeNull() + expect(wslUncDriveFsPath(String.raw`\\server\share\mnt\c`, 'win32')).toBeNull() + expect(wslUncDriveFsPath(UNC, 'linux')).toBeNull() + expect(windowsFsPath('/home/me/app', 'darwin')).toBe('/home/me/app') + }) +}) + +describe('realpathAcrossWslDriveMount', () => { + it('resolves through the drive and answers in the caller’s UNC spelling', async () => { + const deps = { realpath: deniedOnUnc, platform: 'win32' as const } + await expect(realpathAcrossWslDriveMount(UNC, deps)).resolves.toBe(UNC) + await expect( + realpathAcrossWslDriveMount(String.raw`\\wsl$\Ubuntu\mnt\c\src\app`, deps) + ).resolves.toBe(String.raw`\\wsl$\Ubuntu\mnt\c\src\app`) + }) + + it('follows a link to another drive, and keeps a target off any drive as it is', async () => { + const linked = { + realpath: async (path: string) => (path === String.raw`C:\src\app` ? 'D:\\real' : path), + platform: 'win32' as const + } + await expect(realpathAcrossWslDriveMount(UNC, linked)).resolves.toBe( + String.raw`\\wsl.localhost\Ubuntu\mnt\d\real` + ) + const share = { + realpath: async () => String.raw`\\server\share\app`, + platform: 'win32' as const + } + await expect(realpathAcrossWslDriveMount(UNC, share)).resolves.toBe( + String.raw`\\server\share\app` + ) + }) + + it('realpaths a distro folder as it is', async () => { + const home = String.raw`\\wsl.localhost\Ubuntu\home\me` + const realpath = vi.fn(async (path: string) => path) + await expect(realpathAcrossWslDriveMount(home, { realpath, platform: 'win32' })).resolves.toBe( + home + ) + expect(realpath).toHaveBeenCalledWith(home) + }) +}) diff --git a/src/main/wsl/wsl-unc-drive-fs-path.ts b/src/main/wsl/wsl-unc-drive-fs-path.ts new file mode 100644 index 000000000000..35c492922faa --- /dev/null +++ b/src/main/wsl/wsl-unc-drive-fs-path.ts @@ -0,0 +1,52 @@ +/** + * WSL refuses Windows file access to its drive mounts over UNC: `\\wsl.localhost\\mnt\c\x` + * answers EPERM (WSL 2.7). The same folder opens through its drive path, `C:\x`. + */ +import { realpath as fsRealpath } from 'node:fs/promises' +import { parseWslUncPath, toWindowsWslDrivePath } from '../../shared/wsl-paths' + +const WSL_UNC_PREFIX = /^[\\/]{2}(?:wsl\.localhost|wsl\$)[\\/][^\\/]+/i +const DRIVE_PATH = /^([A-Za-z]):(?:[\\/](.*))?$/ + +/** The drive path Windows opens for a UNC path into a distro's drive mount; null for any other. */ +export function wslUncDriveFsPath( + path: string, + platform: NodeJS.Platform = process.platform +): string | null { + if (platform !== 'win32') { + return null + } + const info = parseWslUncPath(path) + return info ? toWindowsWslDrivePath(info.linuxPath) : null +} + +/** The path to hand to fs: the drive path for a UNC drive-mount path, else `path` itself. */ +export function windowsFsPath(path: string, platform: NodeJS.Platform = process.platform): string { + return wslUncDriveFsPath(path, platform) ?? path +} + +/** + * realpath that resolves a UNC drive-mount path through its drive and answers in the caller's UNC + * spelling, so allow-list checks against UNC roots are unchanged. + */ +export async function realpathAcrossWslDriveMount( + path: string, + deps: { realpath: (path: string) => Promise; platform: NodeJS.Platform } = { + realpath: fsRealpath, + platform: process.platform + } +): Promise { + const drive = wslUncDriveFsPath(path, deps.platform) + if (!drive) { + return deps.realpath(path) + } + const real = await deps.realpath(drive) + const prefix = WSL_UNC_PREFIX.exec(path)?.[0] + const match = DRIVE_PATH.exec(real) + // A junction off the drive keeps its own spelling; authorization judges it as it is. + if (!prefix || !match) { + return real + } + const tail = match[2] ? `\\${match[2].replace(/\//g, '\\')}` : '' + return `${prefix.replace(/\//g, '\\')}\\mnt\\${match[1].toLowerCase()}${tail}` +}