Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(mcp-host): verify caller roots before managed access

Alfredo Lopez9762b24a2587
diff --git a/docs/operations/gfs-large-file-host-downloads.md b/docs/operations/gfs-large-file-host-downloads.md
index ce4915a69..e8891a67e 100644
--- a/docs/operations/gfs-large-file-host-downloads.md
+++ b/docs/operations/gfs-large-file-host-downloads.md
@@ -141,7 +141,21 @@ Unix directory modes and random directory names do not provide cross-caller OS i
Shell cleanup signals and waits for the detached process group before releasing a processing lease. Operating systems may reuse a process-group identifier after the original leader has been reaped; Stage 1 narrows that window by signaling immediately on leader close, but stronger executor identity is required to eliminate it.
-Generic workspace tools reject direct and symlink-resolved access to `.gfs-downloads` through `file_read`, `file_write`, memory read/write, list/tree, and search. This prevents accidental dumps; it does not revoke access from an explicitly approved shell command.
+Generic workspace tools reject direct and symlink-resolved access to
+`.gfs-downloads` and the complete `.gfs-download-store` accounting namespace
+through `file_read`, `file_write`, memory read/write, list/tree, and search.
+The protected absolute target is checked before relativizing it against a
+workspace root, including when that root itself was replaced by an alias.
+
+Caller binding canonicalizes the configured Host base, then verifies real
+`users` and caller directories. The `users` parent is checked before creating a
+caller child. Redirected caller namespaces produce unavailable bindings;
+ordinary text tasks continue while managed tools remain denied. A legitimate
+platform alias on the configured Host base is retained. Managed shell also
+revalidates its actual canonical root before lease acquisition and spawning.
+These checks prevent a known redirected root from granting generic tool access
+to accounting. They do not provide FD-anchored executor isolation against all
+shared-UID filesystem races; that remains the Stage 2 boundary.
## Retention, quotas, and recovery
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 9a07b3343..4aa4e61e7 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.492",
+ "version": "0.1.493",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.492",
+ "version": "0.1.493",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 894f4eb5d..20ace91f0 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.492",
+ "version": "0.1.493",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/core/tools/__tests__/shellOutputBounds.test.ts b/mcp-host/src/core/tools/__tests__/shellOutputBounds.test.ts
index ec5faae55..18c307ac0 100644
--- a/mcp-host/src/core/tools/__tests__/shellOutputBounds.test.ts
+++ b/mcp-host/src/core/tools/__tests__/shellOutputBounds.test.ts
@@ -1,4 +1,4 @@
-import { expect, it } from 'vitest'
+import { afterEach, expect, it } from 'vitest'
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
@@ -14,6 +14,20 @@ function executionContext(chunks: string[]): ExecutionContext {
}
}
+const managedHosts: string[] = []
+
+function managedWorkspace(prefix: string): string {
+ const host = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
+ managedHosts.push(host)
+ const workspace = path.join(host, 'users', 'caller')
+ fs.mkdirSync(workspace, { recursive: true })
+ return workspace
+}
+
+afterEach(() => {
+ for (const host of managedHosts.splice(0)) fs.rmSync(host, { recursive: true, force: true })
+})
+
it('bounds retained shell output and live progress independently', async () => {
const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'shell-output-bounds-'))
const progress: string[] = []
@@ -50,7 +64,7 @@ it('resets HOME to the caller workspace after environment merging', async () =>
})
it('does not spawn when processing lease acquisition fails', async () => {
- const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'shell-lease-denied-'))
+ const workspace = managedWorkspace('shell-lease-denied-')
const marker = path.join(workspace, 'started')
const leases: GfsProcessingLeaseProvider = {
acquireProcessingLease: async () => {
@@ -66,12 +80,12 @@ it('does not spawn when processing lease acquisition fails', async () => {
expect(result.content).toContain('download expired')
expect(fs.existsSync(marker)).toBe(false)
} finally {
- fs.rmSync(workspace, { recursive: true, force: true })
+ expect(fs.existsSync(marker)).toBe(false)
}
})
it('releases the processing lease after command completion', async () => {
- const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'shell-lease-release-'))
+ const workspace = managedWorkspace('shell-lease-release-')
const events: string[] = []
const leases: GfsProcessingLeaseProvider = {
acquireProcessingLease: async () => {
@@ -89,12 +103,12 @@ it('releases the processing lease after command completion', async () => {
expect(result.is_error).toBe(false)
expect(events).toEqual(['acquire', 'release'])
} finally {
- fs.rmSync(workspace, { recursive: true, force: true })
+ expect(events).toEqual(['acquire', 'release'])
}
})
it('does not report success when processing lease release fails', async () => {
- const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'shell-lease-failed-release-'))
+ const workspace = managedWorkspace('shell-lease-failed-release-')
const leases: GfsProcessingLeaseProvider = {
acquireProcessingLease: async () => ({
leaseId: 'lease-1',
@@ -111,12 +125,13 @@ it('does not report success when processing lease release fails', async () => {
expect(result.is_error).toBe(true)
expect(result.content).toContain('processing_lease_release_failed')
} finally {
- fs.rmSync(workspace, { recursive: true, force: true })
+ // Cleanup is centralized by managedHosts; keep the operation under try for
+ // symmetrical failure reporting without duplicating the result assertion.
}
})
it('releases the processing lease only after process-group termination', async () => {
- const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'shell-group-lease-'))
+ const workspace = managedWorkspace('shell-group-lease-')
const marker = path.join(workspace, 'group-settled')
const script = path.join(workspace, 'spawn-group-child.js')
const releaseSawSettledMarker: boolean[] = []
@@ -149,6 +164,6 @@ it('releases the processing lease only after process-group termination', async (
expect(fs.readFileSync(marker, 'utf8')).toBe('yes')
expect(releaseSawSettledMarker).toEqual([true])
} finally {
- fs.rmSync(workspace, { recursive: true, force: true })
+ expect(fs.existsSync(marker)).toBe(true)
}
})
diff --git a/mcp-host/src/core/tools/__tests__/shellProcessingLeaseCancellation.test.ts b/mcp-host/src/core/tools/__tests__/shellProcessingLeaseCancellation.test.ts
index d0875926a..c6e7aaca4 100644
--- a/mcp-host/src/core/tools/__tests__/shellProcessingLeaseCancellation.test.ts
+++ b/mcp-host/src/core/tools/__tests__/shellProcessingLeaseCancellation.test.ts
@@ -1,5 +1,7 @@
-import { beforeEach, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import * as fs from 'node:fs'
import * as os from 'node:os'
+import * as path from 'node:path'
import type {
GfsProcessingLease,
GfsProcessingLeaseProvider,
@@ -13,6 +15,20 @@ vi.mock('child_process', () => ({ spawn: mocks.spawn }))
beforeEach(() => vi.clearAllMocks())
+const managedHosts: string[] = []
+
+function managedWorkspace(): string {
+ const host = fs.mkdtempSync(path.join(os.tmpdir(), 'shell-managed-cancellation-'))
+ managedHosts.push(host)
+ const workspace = path.join(host, 'users', 'caller')
+ fs.mkdirSync(workspace, { recursive: true })
+ return workspace
+}
+
+afterEach(() => {
+ for (const host of managedHosts.splice(0)) fs.rmSync(host, { recursive: true, force: true })
+})
+
function delayedLease() {
let finishAcquisition!: (lease: GfsProcessingLease) => void
const pending = new Promise<GfsProcessingLease>(resolve => {
@@ -33,7 +49,7 @@ it('does not spawn and releases a lease acquired after cancellation', async () =
const { provider, lease, finishAcquisition } = delayedLease()
const controller = new AbortController()
const reason = new Error('cancelled during processing lease acquisition')
- const tool = new ShellTool(os.tmpdir(), 5_000, [], () => ({}), undefined, provider)
+ const tool = new ShellTool(managedWorkspace(), 5_000, [], () => ({}), undefined, provider)
const execution = tool.execute(
{ command: 'printf done' },
{ signal: controller.signal, onOutput: vi.fn() }
@@ -52,7 +68,7 @@ it('keeps cancellation before spawn when releasing the admitted lease fails', as
const { provider, lease, finishAcquisition } = delayedLease()
vi.mocked(provider.releaseProcessingLease).mockRejectedValueOnce(new Error('ledger unavailable'))
const controller = new AbortController()
- const tool = new ShellTool(os.tmpdir(), 5_000, [], () => ({}), undefined, provider)
+ const tool = new ShellTool(managedWorkspace(), 5_000, [], () => ({}), undefined, provider)
const execution = tool.execute(
{ command: 'printf done' },
{ signal: controller.signal, onOutput: vi.fn() }
@@ -72,7 +88,7 @@ it('joins the actual late shell lease through the outer cancellation boundary',
const { provider, lease, finishAcquisition } = delayedLease()
const controller = new AbortController()
const reason = new Error('cancelled while acquiring the shell lease')
- const tool = new ShellTool(os.tmpdir(), 5_000, [], () => ({}), undefined, provider)
+ const tool = new ShellTool(managedWorkspace(), 5_000, [], () => ({}), undefined, provider)
let completed = false
const execution = executeWithTimeout(
tool,
diff --git a/mcp-host/src/core/tools/shell.ts b/mcp-host/src/core/tools/shell.ts
index 320ad63ff..c1010eb7a 100644
--- a/mcp-host/src/core/tools/shell.ts
+++ b/mcp-host/src/core/tools/shell.ts
@@ -6,6 +6,7 @@ import type {
GfsProcessingLeaseProvider,
} from '../../internalTools/gfsProcessingLease'
import { ALL_PROVIDERS, LlmProvider, PROVIDERS } from '../../llm/registryCore'
+import { verifyManagedCallerRootPath } from '../../workspace/callerRootBinding'
import { ToolError, ToolErrorCode } from '../errors'
import { ExecutionContext, Tool } from '../interfaces'
import { ToolOutput } from '../types'
@@ -149,6 +150,11 @@ export class ShellTool implements Tool {
const timeout = Math.min(this.timeout, context?.timeoutMs ?? this.timeout)
const startTime = Date.now()
const command = params.command as string
+ if (this.processingLeases && this.workspacePath) {
+ if (verifyManagedCallerRootPath(this.workspacePath) === undefined) {
+ return this.managedRootUnavailable(startTime)
+ }
+ }
if (!this.workspacePath) {
return {
content:
@@ -453,4 +459,13 @@ export class ShellTool implements Tool {
})
})
}
+
+ private managedRootUnavailable(startTime: number): ToolOutput {
+ return {
+ content:
+ 'Managed shell unavailable: the verified caller workspace root is no longer canonical.',
+ duration_ms: Date.now() - startTime,
+ is_error: true,
+ }
+ }
}
diff --git a/mcp-host/src/workspace/__tests__/gfsCallerRootBinding.test.ts b/mcp-host/src/workspace/__tests__/gfsCallerRootBinding.test.ts
index 34246c072..e22a8612f 100644
--- a/mcp-host/src/workspace/__tests__/gfsCallerRootBinding.test.ts
+++ b/mcp-host/src/workspace/__tests__/gfsCallerRootBinding.test.ts
@@ -1,4 +1,5 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { spawn } from 'node:child_process'
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
@@ -8,6 +9,7 @@ import { GfsDownloadStore } from '../../internalTools/gfsDownloadStore'
import type { IncomingMessage } from '../../server/types'
import { type CallerRootBinding, resolveCallerRootBinding } from '../callerRootBinding'
import { ScopedWorkspaceProvider } from '../scopedWorkspace'
+import { deriveUserKeyFromSource } from '../userKey'
const config: NativeToolConfig = {
workspacePath: '',
@@ -19,12 +21,18 @@ const config: NativeToolConfig = {
memoryMaxSize: 1_048_576,
}
+vi.mock('node:child_process', async importOriginal => {
+ const actual = await importOriginal<typeof import('node:child_process')>()
+ return { ...actual, spawn: vi.fn(actual.spawn) }
+})
+
describe('NativeRegistry GFS caller file-tool binding', () => {
let root: string
let store: GfsDownloadStore
const stores: GfsDownloadStore[] = []
beforeEach(() => {
+ vi.clearAllMocks()
root = fs.mkdtempSync(path.join(os.tmpdir(), 'gfs-caller-binding-'))
})
@@ -133,6 +141,119 @@ describe('NativeRegistry GFS caller file-tool binding', () => {
expect(fs.existsSync(path.join(root, 'degraded.txt'))).toBe(false)
})
+ it('rejects a caller root redirected directly to Host accounting', async () => {
+ store = new GfsDownloadStore(root)
+ stores.push(store)
+ await store.initialize()
+ const provider = new ScopedWorkspaceProvider(root)
+ const lexicalCallerRoot = provider.forSource(source()).userRootPath
+ fs.rmSync(lexicalCallerRoot, { recursive: true, force: true })
+ fs.symlinkSync(path.join(root, '.gfs-download-store'), lexicalCallerRoot)
+
+ const binding = resolveCallerRootBinding(provider, source())
+ expect(binding.root).toBeUndefined()
+
+ const redirected = registry(binding.root, false)
+ expect(redirected.get('file_read')).toBeNull()
+ expect(redirected.get('file_write')).toBeNull()
+ const shell = await redirected.get('shell_exec')!.execute({ command: 'pwd' })
+ expect(shell.is_error).toBe(true)
+ expect(shell.content).toContain('Managed shell unavailable')
+ expect(vi.mocked(spawn)).not.toHaveBeenCalled()
+ })
+
+ it('rejects a redirected users parent without falling back to another namespace', async () => {
+ store = new GfsDownloadStore(root)
+ stores.push(store)
+ await store.initialize()
+ const redirectedUsers = path.join(root, 'redirected-users')
+ fs.mkdirSync(path.join(redirectedUsers), { recursive: true })
+ fs.symlinkSync(redirectedUsers, path.join(root, 'users'))
+ const provider = new ScopedWorkspaceProvider(root)
+
+ const binding = resolveCallerRootBinding(provider, source())
+
+ expect(binding.root).toBeUndefined()
+ expect(fs.readdirSync(redirectedUsers)).toEqual([])
+ const omitted = registry(binding.root, false)
+ expect(omitted.get('file_read')).toBeNull()
+ expect(omitted.get('file_write')).toBeNull()
+ })
+
+ it('does not create a caller child through a redirected users parent', async () => {
+ store = new GfsDownloadStore(root)
+ stores.push(store)
+ await store.initialize()
+ const accountingRoot = path.join(root, '.gfs-download-store')
+ const ledger = path.join(accountingRoot, 'ledger-v1.json')
+ const before = fs.readFileSync(ledger, 'utf-8')
+ fs.symlinkSync(accountingRoot, path.join(root, 'users'))
+ const provider = new ScopedWorkspaceProvider(root)
+ const callerKey = deriveUserKeyFromSource(source())
+
+ const binding = resolveCallerRootBinding(provider, source())
+
+ expect(binding).toEqual({ failureCode: 'EEXIST' })
+ expect(fs.existsSync(path.join(accountingRoot, callerKey))).toBe(false)
+ expect(fs.readdirSync(accountingRoot)).not.toContain(callerKey)
+ expect(fs.readFileSync(ledger, 'utf-8')).toBe(before)
+ })
+
+ it('creates and verifies the first healthy caller beneath a Host-owned users parent', () => {
+ const provider = new ScopedWorkspaceProvider(root)
+ expect(fs.existsSync(path.join(root, 'users'))).toBe(false)
+
+ const binding = resolveCallerRootBinding(provider, source())
+ const callerKey = deriveUserKeyFromSource(source())
+ const expectedRoot = path.join(fs.realpathSync(root), 'users', callerKey)
+
+ expect(binding).toEqual({ root: expectedRoot })
+ expect(fs.statSync(path.join(root, 'users')).isDirectory()).toBe(true)
+ expect(fs.statSync(expectedRoot).isDirectory()).toBe(true)
+ })
+
+ it('rejects a bound caller root replaced by accounting after Registry construction', async () => {
+ store = new GfsDownloadStore(root)
+ stores.push(store)
+ await store.initialize()
+ const provider = new ScopedWorkspaceProvider(root)
+ const binding = resolveCallerRootBinding(provider, source())
+ expect(binding.root).toBeDefined()
+ const bound = registry(binding.root)
+ const ledger = path.join(root, '.gfs-download-store', 'ledger-v1.json')
+ const before = fs.readFileSync(ledger, 'utf-8')
+
+ fs.rmSync(binding.root!, { recursive: true, force: true })
+ fs.symlinkSync(path.join(root, '.gfs-download-store'), binding.root!)
+ const read = await bound.get('file_read')!.execute({ path: 'ledger-v1.json' })
+ const write = await bound.get('file_write')!.execute({
+ path: 'ledger-v1.json',
+ content: 'replacement',
+ })
+ const shell = await bound.get('shell_exec')!.execute({ command: 'pwd' })
+
+ expect(read.is_error).toBe(true)
+ expect(write.is_error).toBe(true)
+ expect(shell.is_error).toBe(true)
+ expect(fs.readFileSync(ledger, 'utf-8')).toBe(before)
+ expect(vi.mocked(spawn)).not.toHaveBeenCalled()
+ })
+
+ it('uses the canonical healthy caller root for managed shell execution', async () => {
+ store = new GfsDownloadStore(root)
+ stores.push(store)
+ await store.initialize()
+ const provider = new ScopedWorkspaceProvider(root)
+ const binding = resolveCallerRootBinding(provider, source())
+ const healthy = registry(binding.root)
+
+ const shell = await healthy.get('shell_exec')!.execute({ command: 'pwd' })
+
+ expect(shell.is_error).toBe(false)
+ expect(vi.mocked(spawn)).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(spawn).mock.calls[0][2]).toMatchObject({ cwd: binding.root })
+ })
+
it('omits managed file tools when no verified caller root exists', () => {
store = new GfsDownloadStore(root)
stores.push(store)
@@ -151,7 +272,7 @@ describe('NativeRegistry GFS caller file-tool binding', () => {
throw new TypeError('unit programming error')
}
const provider = (thrower: () => never) =>
- ({ forSource: thrower }) as unknown as ScopedWorkspaceProvider
+ ({ baseRootPath: root, forSource: thrower }) as unknown as ScopedWorkspaceProvider
const expected: CallerRootBinding = resolveCallerRootBindingForTest(provider(eaccES))
expect(expected).toEqual({ failureCode: 'EACCES' })
expect(() => resolveCallerRootBindingForTest(provider(unexpected))).toThrow(TypeError)
diff --git a/mcp-host/src/workspace/__tests__/protectedWorkspacePaths.test.ts b/mcp-host/src/workspace/__tests__/protectedWorkspacePaths.test.ts
index 569fab0f3..a45e2bcf9 100644
--- a/mcp-host/src/workspace/__tests__/protectedWorkspacePaths.test.ts
+++ b/mcp-host/src/workspace/__tests__/protectedWorkspacePaths.test.ts
@@ -73,6 +73,33 @@ describe('protected workspace paths', () => {
await expect(workspace.search('accounting-sentinel')).resolves.toEqual([])
})
+ it('rejects a workspace root that itself resolves into GFS accounting', async () => {
+ const accountingRoot = path.join(root, '.gfs-download-store')
+ fs.writeFileSync(path.join(accountingRoot, 'MEMORY.md'), 'accounting-sentinel', 'utf-8')
+ const aliasedWorkspace = new WorkspaceService(accountingRoot)
+ const memoryRead = new PersistentMemoryReadTool(aliasedWorkspace)
+ const memoryWrite = new PersistentMemoryWriteTool(aliasedWorkspace)
+
+ await expect(aliasedWorkspace.read('ledger-v1.json')).rejects.toBeInstanceOf(
+ GfsDownloadPathError
+ )
+ await expect(aliasedWorkspace.list()).rejects.toBeInstanceOf(GfsDownloadPathError)
+ await expect(aliasedWorkspace.search('accounting-sentinel')).resolves.toEqual([])
+ await expect(memoryRead.execute({ path: 'MEMORY.md' })).resolves.toMatchObject({
+ is_error: true,
+ content: expect.stringContaining('governed GFS'),
+ })
+ await expect(
+ memoryWrite.execute({ target: 'MEMORY.md', content: 'replacement' })
+ ).resolves.toMatchObject({
+ is_error: true,
+ content: expect.stringContaining('governed GFS'),
+ })
+ expect(fs.readFileSync(path.join(accountingRoot, 'MEMORY.md'), 'utf-8')).toBe(
+ 'accounting-sentinel'
+ )
+ })
+
it('blocks direct and symlinked access through file tools', async () => {
const read = new FileReadTool(root)
const direct = await read.execute({ path: '.gfs-downloads/input-1/source.md' })
diff --git a/mcp-host/src/workspace/callerRootBinding.ts b/mcp-host/src/workspace/callerRootBinding.ts
index 1153be48e..fe39c714d 100644
--- a/mcp-host/src/workspace/callerRootBinding.ts
+++ b/mcp-host/src/workspace/callerRootBinding.ts
@@ -1,11 +1,45 @@
+import * as fs from 'node:fs'
+import * as path from 'node:path'
import type { IncomingMessage } from '../server/types'
+import { isProtectedRealPath } from './protectedPaths'
import type { ScopedWorkspaceProvider } from './scopedWorkspace'
+import { deriveUserKeyFromSource } from './userKey'
export interface CallerRootBinding {
root?: string
failureCode?: 'EACCES' | 'EEXIST' | 'EIO' | 'ENOENT' | 'ENOSPC' | 'ENOTDIR' | 'EPERM' | 'EROFS'
}
+/**
+ * Verify the managed caller shape `<host>/users/<caller>` without prohibiting
+ * a platform alias on the Host base itself. The `users` parent and caller root
+ * must be real directories; a protected resolved root is not a caller root.
+ * Filesystem errors propagate so callers can distinguish degradation from redirects.
+ */
+export function verifyManagedCallerRootPath(lexicalCallerRoot: string): string | undefined {
+ const lexicalCaller = path.resolve(lexicalCallerRoot)
+ const callerName = path.basename(lexicalCaller)
+ const lexicalUsersRoot = path.dirname(lexicalCaller)
+ if (path.basename(lexicalUsersRoot) !== 'users' || !callerName || callerName === '.') {
+ return undefined
+ }
+ const lexicalHostBase = path.dirname(lexicalUsersRoot)
+ const canonicalHostBase = fs.realpathSync(lexicalHostBase)
+ const canonicalUsersRoot = path.join(canonicalHostBase, 'users')
+ const usersInfo = fs.lstatSync(lexicalUsersRoot)
+ if (!usersInfo.isDirectory() || usersInfo.isSymbolicLink()) return undefined
+ const callerInfo = fs.lstatSync(lexicalCaller)
+ if (!callerInfo.isDirectory() || callerInfo.isSymbolicLink()) return undefined
+ const canonicalCallerRoot = path.join(canonicalUsersRoot, callerName)
+ if (
+ fs.realpathSync(lexicalCaller) !== canonicalCallerRoot ||
+ isProtectedRealPath(canonicalCallerRoot, canonicalHostBase)
+ ) {
+ return undefined
+ }
+ return canonicalCallerRoot
+}
+
function bindingFailureCode(error: unknown): CallerRootBinding['failureCode'] {
const code = (error as NodeJS.ErrnoException)?.code
if (
@@ -34,7 +68,43 @@ export function resolveCallerRootBinding(
): CallerRootBinding {
if (!provider) return {}
try {
- return { root: provider.forSource(sourceMessage).userRootPath }
+ const lexicalHostBase = path.resolve(provider.baseRootPath)
+ const canonicalHostBase = fs.realpathSync(lexicalHostBase)
+ const lexicalUsersRoot = path.join(lexicalHostBase, 'users')
+ const canonicalUsersRoot = path.join(canonicalHostBase, 'users')
+
+ // Establish and verify the trusted parent before provider.forSource(),
+ // which get-or-creates the caller child. A redirected parent must never
+ // receive that child creation.
+ let usersInfo: fs.Stats
+ try {
+ usersInfo = fs.lstatSync(lexicalUsersRoot)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ fs.mkdirSync(lexicalUsersRoot, { recursive: false, mode: 0o700 })
+ usersInfo = fs.lstatSync(lexicalUsersRoot)
+ }
+ if (
+ !usersInfo.isDirectory() ||
+ usersInfo.isSymbolicLink() ||
+ fs.realpathSync(lexicalUsersRoot) !== canonicalUsersRoot
+ ) {
+ return { failureCode: 'EEXIST' }
+ }
+
+ const callerKey = deriveUserKeyFromSource(sourceMessage)
+ const expectedLexicalCallerRoot = path.join(lexicalUsersRoot, callerKey)
+ const lexicalCallerRoot = path.resolve(provider.forSource(sourceMessage).userRootPath)
+ if (lexicalCallerRoot !== expectedLexicalCallerRoot) return { failureCode: 'EEXIST' }
+
+ const canonicalCallerRoot = verifyManagedCallerRootPath(lexicalCallerRoot)
+ if (
+ canonicalCallerRoot === undefined ||
+ canonicalCallerRoot !== path.join(canonicalUsersRoot, callerKey)
+ ) {
+ return { failureCode: 'EEXIST' }
+ }
+ return { root: canonicalCallerRoot }
} catch (error) {
const failureCode = bindingFailureCode(error)
if (failureCode === undefined) throw error
diff --git a/mcp-host/src/workspace/protectedPaths.ts b/mcp-host/src/workspace/protectedPaths.ts
index 874967824..4b1c99f28 100644
--- a/mcp-host/src/workspace/protectedPaths.ts
+++ b/mcp-host/src/workspace/protectedPaths.ts
@@ -90,12 +90,33 @@ export function protectedWorkspacePathMessage(relativePath: string): string {
return protectedWorkspacePathError(relativePath).message
}
+/**
+ * Check a resolved absolute path independently of a workspace anchor. This
+ * protects the case where a stale workspace root itself was replaced by a
+ * platform-owned directory; path.relative would otherwise turn its children
+ * into apparently harmless relative paths.
+ */
+function isProtectedAbsoluteRealPath(realPath: string): boolean {
+ if (!path.isAbsolute(realPath)) return false
+ const segments = realPath.split(path.sep).filter(segment => segment.length > 0)
+ if (segments.some(segment => PROTECTED_WORKSPACE_DIRS.has(segment))) return true
+ const base = segments[segments.length - 1]
+ return base !== undefined && PROTECTED_STATE_DB_FILES.has(base)
+}
+
+export function isProtectedGfsRealPath(realPath: string): boolean {
+ if (!path.isAbsolute(realPath)) return false
+ const segments = realPath.split(path.sep).filter(segment => segment.length > 0)
+ return segments.some(segment => segment === '.gfs-download-store' || segment === '.gfs-downloads')
+}
+
/**
* Check a fully resolved path against the real workspace root. This catches
* aliases whose lexical path looks harmless but whose symlink target is a
* protected platform directory or database lateral.
*/
export function isProtectedRealPath(realPath: string, realWorkspaceRoot: string): boolean {
+ if (isProtectedAbsoluteRealPath(realPath)) return true
const relative = path.relative(realWorkspaceRoot, realPath)
if (relative.startsWith('..') || path.isAbsolute(relative) || relative === '') return false
const segments = relative.split(path.sep).filter(segment => segment.length > 0)
diff --git a/mcp-host/src/workspace/scopedWorkspace.ts b/mcp-host/src/workspace/scopedWorkspace.ts
index 00c0cde2e..040cfeb7d 100644
--- a/mcp-host/src/workspace/scopedWorkspace.ts
+++ b/mcp-host/src/workspace/scopedWorkspace.ts
@@ -244,6 +244,11 @@ export class ScopedWorkspaceProvider {
this.collective = new WorkspaceService(baseRoot, { excludeDirs: [USERS_DIR] })
}
+ /** Lexical Host-owned base used to verify the physical caller namespace. */
+ get baseRootPath(): string {
+ return this.baseRoot
+ }
+
/** The collective (Pod-shared) workspace — used for admin identity reconcile. */
get collectiveWorkspace(): WorkspaceService {
return this.collective
diff --git a/mcp-host/src/workspace/service.ts b/mcp-host/src/workspace/service.ts
index 65c119420..8bbadfe9d 100644
--- a/mcp-host/src/workspace/service.ts
+++ b/mcp-host/src/workspace/service.ts
@@ -9,6 +9,8 @@ import * as fs from 'fs/promises'
import * as path from 'path'
import type { PersonalizationConfig } from '../types'
import {
+ GfsDownloadPathError,
+ isProtectedGfsRealPath,
isProtectedRealPath,
isProtectedWorkspacePath,
protectedWorkspacePathError,
@@ -163,7 +165,9 @@ export class WorkspaceService implements Workspace {
throw new Error('Path resolves outside workspace')
}
if (isProtectedRealPath(realPath, realWorkspaceRoot)) {
- throw protectedWorkspacePathError(path.relative(realWorkspaceRoot, realPath))
+ throw isProtectedGfsRealPath(realPath)
+ ? new GfsDownloadPathError(path.relative(realWorkspaceRoot, realPath))
+ : protectedWorkspacePathError(path.relative(realWorkspaceRoot, realPath))
}
break
} catch (err) {
@@ -283,7 +287,18 @@ export class WorkspaceService implements Workspace {
// ── Directory listing ──────────────────────────────────────────────────────
async list(directory: string = ''): Promise<WorkspaceEntry[]> {
- const resolved = directory ? await this.resolveAccessiblePath(directory) : this.workspacePath
+ let resolved: string
+ if (directory) {
+ resolved = await this.resolveAccessiblePath(directory)
+ } else {
+ const realRoot = await fs.realpath(this.workspacePath)
+ if (isProtectedRealPath(realRoot, realRoot)) {
+ throw isProtectedGfsRealPath(realRoot)
+ ? new GfsDownloadPathError(path.basename(realRoot))
+ : protectedWorkspacePathError(path.basename(realRoot))
+ }
+ resolved = this.workspacePath
+ }
let entries: { name: string; isDirectory(): boolean }[]
try {
entries = await fs.readdir(resolved, { withFileTypes: true })