Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/main/ipc/filesystem/filesystem-auth.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down Expand Up @@ -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, {
Expand Down
4 changes: 2 additions & 2 deletions src/main/ipc/filesystem/filesystem-path-containment.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand Down Expand Up @@ -81,7 +81,7 @@ export function isPathAbsentError(error: unknown): boolean {

export async function normalizeExistingPath(resolvedPath: string): Promise<string> {
try {
return resolve(await realpath(resolvedPath))
return resolve(await realpathAcrossWslDriveMount(resolvedPath))
} catch (error) {
if (isENOENT(error)) {
return resolvedPath
Expand Down
102 changes: 102 additions & 0 deletions src/main/ipc/filesystem/filesystem-read-dir-unc-drive.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
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 { 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'
})
}

describe('fs:readDir on a UNC drive-mount project', () => {
beforeEach(() => {
resetFilesystemIpcMocks()
invalidateAuthorizedRootsCache()
})

// Handler UNC authorization needs native Windows path resolution.
it.runIf(process.platform === 'win32')(
'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 })
}
)
})
3 changes: 2 additions & 1 deletion src/main/ipc/filesystem/filesystem-read-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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) {
Expand All @@ -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()
Expand Down
73 changes: 73 additions & 0 deletions src/main/ipc/hooks/worktree-hook-inspection-unc-drive.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, (event: unknown, args: unknown) => 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<Repo> = { 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()
})
})
3 changes: 2 additions & 1 deletion src/main/runtime/runtime-repository-hooks-commands.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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
}
Expand Down
70 changes: 70 additions & 0 deletions src/main/wsl/wsl-unc-drive-fs-path.test.ts
Original file line number Diff line number Diff line change
@@ -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<string> => {
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)
})
})
Loading
Loading