Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
26 changes: 26 additions & 0 deletions packages/code/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,32 @@ container/NsJail profile. The worker connects outbound to Code API,
long-polls for assignments, sends them to the local runtime, and returns fenced
results. The VM does not need an inbound public port.

## Internal host file root admission

Trusted in-process callers may pass `admitRoot` to `LocalWorkspaceTools.create`.
Every registered root then needs a supplied identity (canonical path, device,
and inode) that matches the directory and can be opened by the host file tools.
The policy receives a frozen copy of that verified identity. Registration
awaits an explicit `true` and rechecks the path and identity after the policy
returns. Missing or invalid identity, denial, or a policy error fails creation
with `REGISTRATION_INVALID` (`Invalid workspace registration`); policy details
are not forwarded. Omitting the policy preserves existing registration behavior.

The linked-worktree and conversation-instance factories accept the same check as
`admitFileRoot` on a source. It runs on the resolved worktree when its host file
executor is constructed. Cached registrations (including failures) are reused
until rebuilt; this is not a live policy or revocation check. Checkout delegates
keep their own registration, including source instruction reads. Worktree
provisioning, setup, and credential routing are not gated by this hook. Native
commands require their own admission: linked-worktree commands use a separate
factory. Conversation commands await file registration, but their setup can run
before it.

This hook does not change CLI options, configuration, or capabilities. The root
identity check does not verify mount topology. Callers whose policy depends on
mount topology must keep it stable or pin it independently for the lifetime of
the registration; this hook is not an isolation boundary for changing mounts.

## Inspect local projects

Before registering a directory containing several checkouts, inspect its Git
Expand Down
27 changes: 27 additions & 0 deletions packages/code/src/linked-worktrees.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
import { NativeWorkspaceCommandPool as CommandPool } from './native-pool.js';
import { LocalWorkspaceTools, WorkspaceToolError } from './workspace.js';

import type { WorkspaceRootAdmissionPolicy } from './workspace.js';
import type { NativeWorkspaceCommandPool } from './native-pool.js';
import type { NativeProcessSandboxOptions } from './native-process.js';
import type { WorkspaceExecuteCommandRequest, WorkspaceToolRequest } from './protocol.js';
Expand Down Expand Up @@ -165,6 +166,7 @@ async function laneTools(
root: string,
pool?: NativeWorkspaceCommandPool,
onRelease?: (root: string) => void,
admitFileRoot?: WorkspaceRootAdmissionPolicy,
) {
const delegate = await LocalWorkspaceTools.create({
repositoryInstructions: false,
Expand All @@ -181,6 +183,7 @@ async function laneTools(
root,
command: { workspaceRoot: root } as NativeProcessSandboxOptions,
repositoryInstructions: false,
admitFileRoot,
writable: true,
},
],
Expand Down Expand Up @@ -226,6 +229,30 @@ test('lane file tools are confined to the worktree and report the public workspa
);
});

test('linked lane file registration enforces the source root policy', async (t) => {
const { parent, root } = await checkout();
t.after(() => rm(parent, { recursive: true, force: true }));
const lane = await verifyLinkedWorktree(root, 'task-a');
const seen: string[] = [];
const tools = await laneTools(root, undefined, undefined, (identity) => {
seen.push(identity.path);
return false;
});
const request = {
protocolVersion: 1, operation: 'write_file', workspaceId: 'repo',
path: 'denied.txt', content: 'denied',
} as const;
for (let i = 0; i < 2; i++) {
await assert.rejects(tools.execute({ ...request, worktree: 'task-a' }), {
code: 'REGISTRATION_INVALID', message: 'Invalid workspace registration',
});
}
assert.deepEqual(seen, [lane.root]);
await assert.rejects(stat(join(lane.root, request.path)), { code: 'ENOENT' });
await tools.execute(request);
assert.equal(await readFile(join(root, request.path), 'utf8'), 'denied');
});

test('lane writes create missing parents inside the worktree and report missing files', async (t) => {
const { parent, root } = await checkout();
t.after(() => rm(parent, { recursive: true, force: true }));
Expand Down
9 changes: 8 additions & 1 deletion packages/code/src/linked-worktrees.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ import type {
WorkspaceToolRequest,
WorkspaceToolResult,
} from './protocol.js';
import type { WorkspaceFileImporter, WorkspaceToolExecutor } from './workspace.js';
import type {
WorkspaceFileImporter,
WorkspaceRootAdmissionPolicy,
WorkspaceToolExecutor,
} from './workspace.js';

/** Linked worktrees are only admitted from this directory beneath a checkout. */
export const LINKED_WORKTREE_DIRECTORY = '.worktrees';
Expand Down Expand Up @@ -64,6 +68,8 @@ export interface LinkedWorktreeSource {
lifecycleEligible?: boolean;
writable: boolean;
importer?: WorkspaceFileImporter;
/** Applied when constructing this source's dynamic host file executor. */
admitFileRoot?: WorkspaceRootAdmissionPolicy;
}

export interface VerifiedLinkedWorktree {
Expand Down Expand Up @@ -395,6 +401,7 @@ export class LinkedWorktreeWorkspaceTools implements WorkspaceToolExecutor, Link
value: LocalWorkspaceTools.create({
repositoryInstructions: source.repositoryInstructions,
importer: source.importer,
admitRoot: source.admitFileRoot,
workspaces: [
{ id: internalId, identity: lane.identity, root: lane.root, writable: source.writable },
],
Expand Down
41 changes: 41 additions & 0 deletions packages/code/src/workspace-instances.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,47 @@ test('routes each conversation to its own writable Git worktree', async (t) => {
assert.equal(instructionResult.content, 'local repository rules\n');
});

test('conversation instance file registration enforces the source root policy', async (t) => {
const { parent, root } = await repository();
t.after(() => rm(parent, { recursive: true, force: true }));
const delegate = await LocalWorkspaceTools.create({
workspaces: [{ id: 'primary', root, writable: true }],
});
const manager = new GitWorktreeManager({
maxCount: 1,
root: join(parent, 'instances'),
sources: new Map([['primary', await source(root)]]),
});
const workspaceInstanceId = 'a'.repeat(64);
const instance = await manager.resolve('primary', workspaceInstanceId);
const seen: string[] = [];
const tools = new GitWorktreeWorkspaceTools({
delegate,
manager,
sources: new Map([['primary', {
repositoryInstructions: false,
writable: true,
async admitFileRoot(identity) {
seen.push(identity.path);
throw new Error(instance.root);
},
}]]),
});
const request = {
protocolVersion: 1, operation: 'write_file', workspaceId: 'primary',
path: 'denied.txt', content: 'denied',
} as const;
for (let i = 0; i < 2; i++) {
await assert.rejects(tools.execute({ ...request, workspaceInstanceId }), {
code: 'REGISTRATION_INVALID', message: 'Invalid workspace registration',
});
}
assert.deepEqual(seen, [instance.root]);
await assert.rejects(readFile(join(instance.root, request.path)), { code: 'ENOENT' });
await tools.execute(request);
assert.equal(await readFile(join(root, request.path), 'utf8'), 'denied');
});

test('reports provisioning rejection as an atomic workspace error', async (t) => {
const fixture = await repository();
t.after(() => rm(fixture.parent, { recursive: true, force: true }));
Expand Down
9 changes: 8 additions & 1 deletion packages/code/src/workspace-instances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,19 @@ import type {
WorkspaceToolRequest,
WorkspaceToolResult,
} from './protocol.js';
import type { WorkspaceFileImporter, WorkspaceToolExecutor } from './workspace.js';
import type {
WorkspaceFileImporter,
WorkspaceRootAdmissionPolicy,
WorkspaceToolExecutor,
} from './workspace.js';

interface WorkspaceInstanceSource {
command?: NativeProcessSandboxOptions;
repositoryInstructions: boolean;
writable: boolean;
importer?: WorkspaceFileImporter;
/** Applied when constructing this source's dynamic host file executor. */
admitFileRoot?: WorkspaceRootAdmissionPolicy;
}

export interface GitWorktreeWorkspaceToolsOptions {
Expand Down Expand Up @@ -121,6 +127,7 @@ export class GitWorktreeWorkspaceTools implements WorkspaceToolExecutor {
value: LocalWorkspaceTools.create({
repositoryInstructions: source.repositoryInstructions,
importer: source.importer,
admitRoot: source.admitFileRoot,
workspaces: [
{
id: internalId,
Expand Down
99 changes: 99 additions & 0 deletions packages/code/src/workspace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
readFile,
readdir,
realpath,
rename,
rm,
stat,
symlink,
Expand Down Expand Up @@ -76,6 +77,104 @@ test('reads a bounded range from a registered local workspace', async (t) => {
);
});

test('awaits root admission on the verified canonical identity before exposing file tools', async (t) => {
const parent = await realpath(await mkdtemp(join(tmpdir(), 'workspace-admission-')));
t.after(() => rm(parent, { recursive: true, force: true }));
const root = join(parent, 'root');
const alias = join(parent, 'alias');
await mkdir(root);
await symlink(root, alias);
await writeFile(join(root, 'notes.txt'), 'allowed');
const identity = await captureWorkspaceRootIdentity(root);
const expected = { ...identity };
let entered!: () => void;
let approve!: () => void;
const started = new Promise<void>((resolve) => { entered = resolve; });
const decision = new Promise<void>((resolve) => { approve = resolve; });
let calls = 0;
let settled = false;
const registration = LocalWorkspaceTools.create({
workspaces: [{ id: 'primary', root: alias, identity }],
async admitRoot(candidate) {
calls++;
entered();
assert.deepEqual(candidate, expected);
assert.ok(Object.isFrozen(candidate));
await decision;
return true;
},
}).finally(() => { settled = true; });

await Promise.race([registration, started]);
assert.equal(settled, false);
identity.ino = '0';
approve();
const tools = await registration;
assert.deepEqual(tools.capabilities.workspaces, [{ id: 'primary' }]);
const result = await tools.execute({
protocolVersion: 1, operation: 'read_file', workspaceId: 'primary', path: 'notes.txt',
});
assert.equal(result.operation === 'read_file' && result.content, 'allowed');
assert.equal(calls, 1);
});

test('a root denial rejects the entire registration, including previously admitted roots', async (t) => {
const parent = await realpath(await mkdtemp(join(tmpdir(), 'workspace-admission-')));
t.after(() => rm(parent, { recursive: true, force: true }));
const allowed = join(parent, 'allowed');
const denied = join(parent, 'denied');
await Promise.all([mkdir(allowed), mkdir(denied)]);
const seen: string[] = [];
await assert.rejects(LocalWorkspaceTools.create({
workspaces: [
{ id: 'allowed', root: allowed, identity: await captureWorkspaceRootIdentity(allowed) },
{ id: 'denied', root: denied, identity: await captureWorkspaceRootIdentity(denied) },
],
admitRoot(identity) {
seen.push(identity.path);
return identity.path === allowed;
},
}), { code: 'REGISTRATION_INVALID', message: 'Invalid workspace registration' });
assert.deepEqual(seen, [allowed, denied]);
});

test('requires a matching supplied identity before running a root policy', async (t) => {
const root = await realpath(await mkdtemp(join(tmpdir(), 'workspace-admission-')));
t.after(() => rm(root, { recursive: true, force: true }));
const identity = await captureWorkspaceRootIdentity(root);
let calls = 0;
for (const supplied of [undefined, { ...identity, ino: '0' }]) {
await assert.rejects(LocalWorkspaceTools.create({
workspaces: [{ id: 'primary', root, identity: supplied }],
admitRoot() { calls++; return true; },
}), { name: 'WorkspaceToolError', code: 'REGISTRATION_INVALID', message: 'Invalid workspace registration' });
}
assert.equal(calls, 0);
});

test('sanitizes policy denial, policy failure, and a root change during admission', async (t) => {
const parent = await realpath(await mkdtemp(join(tmpdir(), 'workspace-admission-')));
t.after(() => rm(parent, { recursive: true, force: true }));
const root = join(parent, 'root');
await mkdir(root);
const identity = await captureWorkspaceRootIdentity(root);
const error = { name: 'WorkspaceToolError', code: 'REGISTRATION_INVALID', message: 'Invalid workspace registration' };
const workspaces = [{ id: 'primary', root, identity, writable: true }];
await assert.rejects(LocalWorkspaceTools.create({ workspaces, admitRoot: () => false }), error);
await assert.rejects(LocalWorkspaceTools.create({
workspaces,
async admitRoot() { throw new WorkspaceToolError(root, 'INVALID_PATH'); },
}), error);
await assert.rejects(LocalWorkspaceTools.create({
workspaces,
async admitRoot() {
await rename(root, join(parent, 'moved'));
await mkdir(root);
return true;
},
}), error);
});

test('rejects traversal outside a registered workspace without leaking its host path', async (t) => {
const parent = await mkdtemp(
join(tmpdir(), 'librechat-code-workspace-parent-'),
Expand Down
31 changes: 27 additions & 4 deletions packages/code/src/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,19 @@ export interface WorkspaceFileImporter {
availableBytes(directory: string): Promise<number>;
}

/**
* Trusted, registration-time check of a verified canonical root. Only `true`
* admits it. This does not pin mount topology or recheck it during requests.
*/
export type WorkspaceRootAdmissionPolicy = (
identity: Readonly<WorkspaceRootIdentity>,
) => boolean | Promise<boolean>;

export interface LocalWorkspaceToolsOptions {
workspaces: LocalWorkspaceConfig[];
repositoryInstructions?: boolean;
/** Requires a supplied identity on every root; not a protocol or CLI option. */
admitRoot?: WorkspaceRootAdmissionPolicy;
/** Enables `import_file` on writable workspaces. */
importer?: WorkspaceFileImporter;
}
Expand Down Expand Up @@ -2383,13 +2393,26 @@ export class LocalWorkspaceTools implements WorkspaceToolExecutor {
options: LocalWorkspaceToolsOptions,
): Promise<LocalWorkspaceTools> {
const roots = new Map<string, WorkspaceRoot>();
const admit = options.admitRoot;
for (const workspace of options.workspaces) {
let canonicalRoot: string;
let identity = workspace.identity;
try {
if (admit !== undefined) {
if (identity == null) throw new Error();
const { path, dev, ino } = identity;
identity = Object.freeze({ path, dev, ino });
}
canonicalRoot = await realpath(workspace.root);
if (workspace.identity && !await matchesWorkspaceRoot(canonicalRoot, workspace.identity)) throw new Error();
await withWorkspaceRoot(canonicalRoot, workspace.identity, async () => undefined);
if (identity && !(await matchesWorkspaceRoot(canonicalRoot, identity))) throw new Error();
await withWorkspaceRoot(canonicalRoot, identity, async () => undefined);
if (!(await stat(canonicalRoot)).isDirectory()) throw new Error();
if (
admit !== undefined &&
(identity == null ||
(await admit(identity)) !== true ||
!(await matchesWorkspaceRoot(canonicalRoot, identity)))
) throw new Error();
} catch {
throw new WorkspaceToolError(
'Invalid workspace registration',
Expand All @@ -2398,14 +2421,14 @@ export class LocalWorkspaceTools implements WorkspaceToolExecutor {
}
const writable = workspace.writable === true;
roots.set(workspace.id, {
identity: workspace.identity,
identity,
root: canonicalRoot,
writable,
/** Imports land in folders that may not exist yet, so only where parents can be created. */
imports:
writable &&
options.importer != null &&
(await canAnchorWorkspaceRoot(canonicalRoot, workspace.identity)),
(await canAnchorWorkspaceRoot(canonicalRoot, identity)),
});
}
const anyWritable = options.workspaces.some(
Expand Down
Loading