Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(security): authorise reads against the canonical path; prompt on hard links; verify the open (#104)
Salman Qureshif6e33f6aadcf
diff --git a/src/capabilities/filesystem/list-dir.ts b/src/capabilities/filesystem/list-dir.tsindex 62685e4d..d3acc8db 100644--- a/src/capabilities/filesystem/list-dir.ts+++ b/src/capabilities/filesystem/list-dir.ts@@ -3,6 +3,7 @@ import { z } from 'zod';import { existsSync, readdirSync, statSync } from 'node:fs';import { resolve, isAbsolute, join } from 'node:path';import type { PermissionManager } from '../permissions.js';+import { readDenialMessage } from './verified-read.js';export function createListDirTool(permissions: PermissionManager, getCwd: () => string) {return tool({@@ -14,23 +15,28 @@ export function createListDirTool(permissions: PermissionManager, getCwd: () =>const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);const check = await permissions.checkFsAccess(resolved, 'read');if (!check.allowed) {- return `Error: Permission denied for read access to ${resolved}. Use the approve_scope tool with path="${resolved}" and mode="read" to request access from the user.`;+ if (check.code === undefined || check.code === 'denied') {+ return `Error: Permission denied for read access to ${resolved}. Use the approve_scope tool with path="${resolved}" and mode="read" to request access from the user.`;+ }+ return readDenialMessage(resolved, check);}- if (!existsSync(resolved)) {+ // List the canonical directory the check authorised, not the lexical path.+ const target = check.canonical ?? resolved;+ if (!existsSync(target)) {return `Error: Directory not found: ${resolved}`;}try {- const stat = statSync(resolved);+ const stat = statSync(target);if (!stat.isDirectory()) {return `Error: ${resolved} is a file, not a directory. Use read_file instead.`;}- const entries = readdirSync(resolved, { withFileTypes: true });+ const entries = readdirSync(target, { withFileTypes: true });const lines = entries.map(entry => {const isDir = entry.isDirectory();- const fullPath = join(resolved, entry.name);+ const fullPath = join(target, entry.name);let size = '';try {if (!isDir) {diff --git a/src/capabilities/filesystem/read-file.test.ts b/src/capabilities/filesystem/read-file.test.tsnew file mode 100644index 00000000..268f6d4d--- /dev/null+++ b/src/capabilities/filesystem/read-file.test.ts@@ -0,0 +1,137 @@+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync, linkSync, realpathSync, lstatSync, closeSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, dirname } from 'node:path';+import { PermissionManager } from '../permissions.js';+import { createReadFileTool } from './read-file.js';+import { createListDirTool } from './list-dir.js';+import { openVerified } from './verified-read.js';++async function run(toolInstance: any, input: any): Promise<string> {+ return toolInstance.execute(input, { toolCallId: 't', messages: [] });+}++describe('read_file / list_dir read authorisation', () => {+ let root: string;+ let ws: string;+ let outside: string;++ function makePermissions(ask?: (prompt: string) => Promise<string>): PermissionManager {+ const permissions = new PermissionManager();+ const manifest = permissions.getManifest();+ manifest.capabilities.filesystem.enabled = true;+ manifest.capabilities.filesystem.scopes = [{ path: ws, read: true, write: false }];+ permissions.setAutoApproveAll(false);+ permissions.setCurrentContext('web', 'cloud-request-1');+ if (ask) permissions.onAsk(ask);+ return permissions;+ }++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-readtool-'));+ ws = join(root, 'ws');+ outside = join(root, 'outside');+ mkdirSync(ws);+ mkdirSync(outside);+ writeFileSync(join(outside, 'id_rsa'), 'PRIVATE KEY');+ writeFileSync(join(ws, 'plain.txt'), 'hello');+ symlinkSync(join(outside, 'id_rsa'), join(ws, 'alias.txt'));+ symlinkSync(outside, join(ws, 'outside-dir'));+ writeFileSync(join(ws, 'linked.txt'), 'linked');+ linkSync(join(ws, 'linked.txt'), join(outside, 'linked-alias.txt'));+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('reads a plain in-scope file', async () => {+ const tool = createReadFileTool(makePermissions(), () => ws);+ await expect(run(tool, { path: 'plain.txt' })).resolves.toBe('hello');+ });++ it('refuses an in-scope symlink to ~/.ssh-style secrets and teaches the approve_scope lesson for the TARGET', async () => {+ const tool = createReadFileTool(makePermissions(), () => ws);+ const out = await run(tool, { path: join(ws, 'alias.txt') });+ const target = realpathSync(join(outside, 'id_rsa'));+ expect(out).not.toContain('PRIVATE KEY');+ expect(out).toMatch(/^Error: Permission denied for read access to /);+ expect(out).toContain(`(it resolves to ${target})`);+ expect(out).toContain(`Use the approve_scope tool with path="${dirname(target)}" and mode="read"`);+ });++ it('keeps the original denial shape for an ordinary out-of-scope read', async () => {+ const tool = createReadFileTool(makePermissions(), () => ws);+ const out = await run(tool, { path: join(outside, 'id_rsa') });+ expect(out).toBe(`Error: Permission denied for read access to ${join(outside, 'id_rsa')}. Use the approve_scope tool with path="${outside}" and mode="read" to request access from the user.`);+ });++ it('refuses a hard-linked file when no approval handler exists', async () => {+ const tool = createReadFileTool(makePermissions(), () => ws);+ const out = await run(tool, { path: 'linked.txt' });+ expect(out).toMatch(/^Error: Permission denied for read access to .*hard links/);+ expect(out).not.toBe('linked');+ });++ it('reads a hard-linked file once the user approves it', async () => {+ const ask = vi.fn().mockResolvedValue('yes');+ const tool = createReadFileTool(makePermissions(ask), () => ws);+ await expect(run(tool, { path: 'linked.txt' })).resolves.toBe('linked');+ expect(ask).toHaveBeenCalledTimes(1);+ });++ it('list_dir refuses an in-scope symlink to an outside directory', async () => {+ const tool = createListDirTool(makePermissions(), () => ws);+ const out = await run(tool, { path: 'outside-dir' });+ expect(out).toMatch(/^Error: Permission denied for read access to /);+ expect(out).not.toContain('id_rsa');+ });++ it('list_dir lists a plain in-scope directory', async () => {+ const tool = createListDirTool(makePermissions(), () => ws);+ const out = await run(tool, { path: ws });+ expect(out).toContain('plain.txt');+ });++ it('reports a missing file after the check passes', async () => {+ const tool = createReadFileTool(makePermissions(), () => ws);+ await expect(run(tool, { path: 'missing.txt' })).resolves.toMatch(/^Error: File not found: /);+ });+});++describe('openVerified (TOCTOU guard)', () => {+ let root: string;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-openverified-'));+ writeFileSync(join(root, 'a.txt'), 'a');+ writeFileSync(join(root, 'b.txt'), 'b');+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('opens the file when fstat matches the pre-check identity', () => {+ const st = lstatSync(join(root, 'a.txt'));+ const opened = openVerified(join(root, 'a.txt'), { dev: st.dev, ino: st.ino });+ expect(opened.error).toBeUndefined();+ closeSync(opened.fd!);+ });++ it('refuses when the path now points at a different inode (symlink swapped in after the check)', () => {+ const checked = lstatSync(join(root, 'a.txt'));+ rmSync(join(root, 'a.txt'));+ symlinkSync(join(root, 'b.txt'), join(root, 'a.txt'));+ const opened = openVerified(join(root, 'a.txt'), { dev: checked.dev, ino: checked.ino });+ expect(opened.error).toMatch(/changed between the permission check and the read/);+ });++ it('refuses a swapped-in regular file too (replace, not symlink)', () => {+ const checked = lstatSync(join(root, 'a.txt'));+ rmSync(join(root, 'a.txt'));+ writeFileSync(join(root, 'a.txt'), 'replacement');+ const opened = openVerified(join(root, 'a.txt'), { dev: checked.dev, ino: checked.ino });+ expect(opened.error).toMatch(/changed between the permission check and the read/);+ });+});diff --git a/src/capabilities/filesystem/read-file.ts b/src/capabilities/filesystem/read-file.tsindex 12e9b9de..1d4b3a35 100644--- a/src/capabilities/filesystem/read-file.ts+++ b/src/capabilities/filesystem/read-file.ts@@ -1,8 +1,9 @@import { tool, zodSchema } from 'ai';import { z } from 'zod';-import { existsSync, readFileSync } from 'node:fs';+import { readFileSync, closeSync } from 'node:fs';import { resolve, isAbsolute } from 'node:path';import type { PermissionManager } from '../permissions.js';+import { openVerified, readDenialMessage } from './verified-read.js';/** Cap on tool-result size — the full file text is echoed into the LLM* conversation and retained for every subsequent agent step (the AI SDK@@ -20,23 +21,23 @@ export function createReadFileTool(permissions: PermissionManager, getCwd: () =>const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);const check = await permissions.checkFsAccess(resolved, 'read');if (!check.allowed) {- const parentDir = resolve(resolved, '..');- return `Error: Permission denied for read access to ${resolved}. Use the approve_scope tool with path="${parentDir}" and mode="read" to request access from the user.`;+ return readDenialMessage(resolved, check);}- if (!existsSync(resolved)) {- return `Error: File not found: ${resolved}`;- }+ // Read the canonical target the check authorised (never the lexical+ // path), and prove the opened descriptor is that same file.+ const opened = openVerified(check.canonical ?? resolved, check.fileId);+ if (opened.error !== undefined) return opened.error;+ const { fd, stat } = opened;try {- const stat = await import('node:fs').then(m => m.statSync(resolved));if (stat.isDirectory()) {return `Error: ${resolved} is a directory, not a file. Use list_dir instead.`;}if (stat.size > 1024 * 1024) {return `Error: File too large (${Math.round(stat.size / 1024)}KB). Maximum is 1MB. Use run_command with sed/head/tail to read portions.`;}- const content = readFileSync(resolved, 'utf-8');+ const content = readFileSync(fd, 'utf-8');if (content.length > MAX_RESULT_CHARS) {return content.slice(0, MAX_RESULT_CHARS)+ `\n\n[File truncated: showing first ${Math.round(MAX_RESULT_CHARS / 1024)}KB of ${Math.round(content.length / 1024)}KB. Use run_command with sed/head/tail to read specific sections.]`;@@ -44,7 +45,9 @@ export function createReadFileTool(permissions: PermissionManager, getCwd: () =>return content;} catch (err: any) {return `Error reading file: ${err.message}`;+ } finally {+ closeSync(fd);}},});-}\ No newline at end of file+}diff --git a/src/capabilities/filesystem/send-file.ts b/src/capabilities/filesystem/send-file.tsindex f863948a..f63c9afd 100644--- a/src/capabilities/filesystem/send-file.ts+++ b/src/capabilities/filesystem/send-file.ts@@ -3,6 +3,7 @@ import { z } from 'zod';import { existsSync, statSync } from 'node:fs';import { resolve, basename, isAbsolute } from 'node:path';import type { PermissionManager } from '../permissions.js';+import { readDenialMessage } from './verified-read.js';export function createSendFileTool(permissions: PermissionManager,@@ -20,15 +21,16 @@ export function createSendFileTool(const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);const check = await permissions.checkFsAccess(resolved, 'read');if (!check.allowed) {- const parentDir = resolve(resolved, '..');- return `Error: Permission denied for read access to ${resolved}. Use the approve_scope tool with path="${parentDir}" and mode="read" to request access from the user.`;+ return readDenialMessage(resolved, check);}- if (!existsSync(resolved)) {+ // Send the canonical target the check authorised, never the lexical path.+ const target = check.canonical ?? resolved;+ if (!existsSync(target)) {return `Error: File not found: ${resolved}`;}- const stat = statSync(resolved);+ const stat = statSync(target);if (stat.isDirectory()) {return `Error: ${resolved} is a directory, not a file. Use list_dir to show its contents.`;}@@ -38,7 +40,7 @@ export function createSendFileTool(}try {- await sendFile(resolved, channel);+ await sendFile(target, channel);const filename = basename(resolved);const sizeStr =stat.size > 1024 * 1024diff --git a/src/capabilities/filesystem/verified-read.ts b/src/capabilities/filesystem/verified-read.tsnew file mode 100644index 00000000..772dc66e--- /dev/null+++ b/src/capabilities/filesystem/verified-read.ts@@ -0,0 +1,56 @@+import { openSync, fstatSync, closeSync, constants, type Stats } from 'node:fs';+import { dirname } from 'node:path';+import type { FileIdentity, FsAccessResult } from '../permissions.js';++export type VerifiedOpen = { fd: number; stat: Stats; error?: undefined } | { fd?: undefined; stat?: undefined; error: string };++/**+ * Open the canonical path a read was authorised for and prove the descriptor+ * is the same file: `fstat` dev/ino must equal the identity captured by the+ * permission check. A symlink or rename swapped in between the check and the+ * open is refused instead of silently read (TOCTOU). The final component is+ * opened with O_NOFOLLOW where the platform has it, so a symlink planted at+ * the canonical path fails outright.+ *+ * The caller owns the returned descriptor and must `closeSync` it.+ */+export function openVerified(canonical: string, expected?: FileIdentity): VerifiedOpen {+ const flags = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0);+ let fd: number;+ try {+ fd = openSync(canonical, flags);+ } catch (err: any) {+ if (err?.code === 'ENOENT') return { error: `Error: File not found: ${canonical}` };+ if (err?.code === 'ELOOP') return { error: `Error: ${canonical} changed between the permission check and the read (a symlink replaced it). Retry.` };+ return { error: `Error reading file: ${err?.message ?? String(err)}` };+ }+ let stat: Stats;+ try {+ stat = fstatSync(fd);+ } catch (err: any) {+ closeSync(fd);+ return { error: `Error reading file: ${err?.message ?? String(err)}` };+ }+ if (expected && (stat.dev !== expected.dev || stat.ino !== expected.ino)) {+ closeSync(fd);+ return { error: `Error: ${canonical} changed between the permission check and the read (expected inode ${expected.ino}, found ${stat.ino}). Retry.` };+ }+ return { fd, stat };+}++/**+ * The denial text every read tool returns, so the model learns one lesson:+ * call `approve_scope` on the directory that actually needs approving. For a+ * symlink that escapes the scopes that is the target's directory, not the+ * link's; a hard-link refusal cannot be fixed by a scope at all, so the+ * reason is passed through.+ */+export function readDenialMessage(resolved: string, check: FsAccessResult): string {+ if (check.code === 'hardlink') {+ return `Error: ${check.reason ?? `Permission denied for read access to ${resolved}`}`;+ }+ if (check.code === 'symlink-escape' && check.canonical) {+ return `Error: Permission denied for read access to ${resolved} (it resolves to ${check.canonical}). Use the approve_scope tool with path="${dirname(check.canonical)}" and mode="read" to request access from the user.`;+ }+ return `Error: Permission denied for read access to ${resolved}. Use the approve_scope tool with path="${dirname(resolved)}" and mode="read" to request access from the user.`;+}diff --git a/src/capabilities/git/git-path.ts b/src/capabilities/git/git-path.tsindex af949f38..e81abeda 100644--- a/src/capabilities/git/git-path.ts+++ b/src/capabilities/git/git-path.ts@@ -1,5 +1,6 @@import { resolve, isAbsolute } from 'node:path';import type { PermissionManager } from '../permissions.js';+import { readDenialMessage } from '../filesystem/verified-read.js';/*** Resolve a model-chosen path against the tool cwd and run it through the@@ -17,13 +18,10 @@ export async function checkGitReadPath(const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);const check = await permissions.checkFsAccess(resolved, 'read');if (!check.allowed) {- const parentDir = resolve(resolved, '..');- return {- resolved,- error: `Error: Permission denied for read access to ${resolved}. Use the approve_scope tool with path="${parentDir}" and mode="read" to request access from the user.`,- };+ return { resolved, error: readDenialMessage(resolved, check) };}- return { resolved };+ // Hand back the canonical directory so git runs where the check looked.+ return { resolved: check.canonical ?? resolved };}/**diff --git a/src/capabilities/permissions.test.ts b/src/capabilities/permissions.test.tsindex 6f98bb26..ff3e9d8f 100644--- a/src/capabilities/permissions.test.ts+++ b/src/capabilities/permissions.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';-import { mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync } from 'node:fs';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync, linkSync, realpathSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PermissionManager, splitShellSegments } from './permissions.js';@@ -312,3 +312,162 @@ describe('PermissionManager symlink write confinement', () => {await expect(permissions.checkFsAccess(join(ws, 'inner-alias.txt'), 'write')).resolves.toMatchObject({ allowed: true });});});++describe('PermissionManager read-side canonicalisation (symlink reads, #104 hard links)', () => {+ let root: string;+ let ws: string;+ let outside: string;++ function makePermissions(opts: { ask?: (prompt: string) => Promise<string>; context?: [string, string] } = {}): PermissionManager {+ const permissions = new PermissionManager();+ const manifest = permissions.getManifest();+ manifest.capabilities.filesystem.enabled = true;+ manifest.capabilities.filesystem.scopes = [{ path: ws, read: true, write: false }];+ permissions.setAutoApproveAll(false);+ permissions.setCurrentContext(...(opts.context ?? ['web', 'cloud-request-1']));+ if (opts.ask) permissions.onAsk(opts.ask);+ return permissions;+ }++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-read-'));+ ws = join(root, 'ws');+ outside = join(root, 'outside');+ mkdirSync(ws);+ mkdirSync(outside);+ writeFileSync(join(outside, 'id_rsa'), 'PRIVATE');+ writeFileSync(join(ws, 'plain.txt'), 'plain');+ writeFileSync(join(ws, 'inner.txt'), 'inner');+ symlinkSync(join(outside, 'id_rsa'), join(ws, 'alias.txt'));+ symlinkSync(join(ws, 'inner.txt'), join(ws, 'inner-alias.txt'));+ writeFileSync(join(ws, 'linked.txt'), 'linked');+ linkSync(join(ws, 'linked.txt'), join(outside, 'linked-alias.txt'));+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ it('allows a plain in-scope read and reports the canonical path and file identity', async () => {+ const ask = vi.fn().mockResolvedValue('no');+ const permissions = makePermissions({ ask });+ const result = await permissions.checkFsAccess(join(ws, 'plain.txt'), 'read');+ expect(result.allowed).toBe(true);+ expect(result.canonical).toBe(realpathSync(join(ws, 'plain.txt')));+ expect(result.fileId).toMatchObject({ dev: expect.any(Number), ino: expect.any(Number) });+ expect(ask).not.toHaveBeenCalled();+ });++ it('denies an in-scope symlink whose target is outside every readable scope (no handler)', async () => {+ const permissions = makePermissions();+ const result = await permissions.checkFsAccess(join(ws, 'alias.txt'), 'read');+ expect(result).toMatchObject({ allowed: false, code: 'symlink-escape', canonical: realpathSync(join(outside, 'id_rsa')) });+ expect(result.reason).toContain('resolves outside the approved scopes');+ });++ it('asks for the symlink TARGET when a handler exists, and denies on "no"', async () => {+ const ask = vi.fn().mockResolvedValue('no');+ const permissions = makePermissions({ ask });+ const result = await permissions.checkFsAccess(join(ws, 'alias.txt'), 'read');+ expect(result).toMatchObject({ allowed: false, code: 'symlink-escape' });+ expect(ask).toHaveBeenCalledTimes(1);+ expect(ask.mock.calls[0][0]).toContain(realpathSync(join(outside, 'id_rsa')));+ });++ it('allows the symlink read once the user approves the target', async () => {+ const ask = vi.fn().mockResolvedValue('yes');+ const permissions = makePermissions({ ask });+ const result = await permissions.checkFsAccess(join(ws, 'alias.txt'), 'read');+ expect(result).toMatchObject({ allowed: true, canonical: realpathSync(join(outside, 'id_rsa')) });+ expect(result.fileId).toBeDefined();+ });++ it('never prompts for the symlink target in fail-closed mode', async () => {+ const ask = vi.fn().mockResolvedValue('yes');+ const permissions = makePermissions({ ask });+ permissions.setFailClosed(true);+ await expect(permissions.checkFsAccess(join(ws, 'alias.txt'), 'read')).resolves.toMatchObject({ allowed: false, code: 'symlink-escape' });+ expect(ask).not.toHaveBeenCalled();+ });++ it('allows a symlink whose target stays inside the scope', async () => {+ const ask = vi.fn().mockResolvedValue('no');+ const permissions = makePermissions({ ask });+ const result = await permissions.checkFsAccess(join(ws, 'inner-alias.txt'), 'read');+ expect(result).toMatchObject({ allowed: true, canonical: realpathSync(join(ws, 'inner.txt')) });+ expect(ask).not.toHaveBeenCalled();+ });++ it('routes a hard-linked file (nlink > 1) through the approval handler', async () => {+ const ask = vi.fn().mockResolvedValue('no');+ const permissions = makePermissions({ ask });+ const denied = await permissions.checkFsAccess(join(ws, 'linked.txt'), 'read');+ expect(denied).toMatchObject({ allowed: false, code: 'hardlink' });+ expect(ask).toHaveBeenCalledTimes(1);+ expect(ask.mock.calls[0][0]).toMatch(/hard-linked/);++ ask.mockResolvedValue('yes');+ const allowed = await permissions.checkFsAccess(join(ws, 'linked.txt'), 'read');+ expect(allowed).toMatchObject({ allowed: true, canonical: realpathSync(join(ws, 'linked.txt')) });+ });++ it('"always" remembers the hard-linked file for the interaction context', async () => {+ const ask = vi.fn().mockResolvedValue('always');+ const permissions = makePermissions({ ask });+ await expect(permissions.checkFsAccess(join(ws, 'linked.txt'), 'read')).resolves.toMatchObject({ allowed: true });+ await expect(permissions.checkFsAccess(join(ws, 'linked.txt'), 'read')).resolves.toMatchObject({ allowed: true });+ expect(ask).toHaveBeenCalledTimes(1);+ // A different context asks again.+ permissions.setCurrentContext('web', 'cloud-request-2');+ await expect(permissions.checkFsAccess(join(ws, 'linked.txt'), 'read')).resolves.toMatchObject({ allowed: true });+ expect(ask).toHaveBeenCalledTimes(2);+ });++ it('denies a hard-linked file when nothing can ask (no handler, fail-closed, internal)', async () => {+ await expect(makePermissions().checkFsAccess(join(ws, 'linked.txt'), 'read')).resolves.toMatchObject({ allowed: false, code: 'hardlink' });++ const ask = vi.fn().mockResolvedValue('yes');+ const failClosed = makePermissions({ ask });+ failClosed.setFailClosed(true);+ await expect(failClosed.checkFsAccess(join(ws, 'linked.txt'), 'read')).resolves.toMatchObject({ allowed: false, code: 'hardlink' });++ const internal = makePermissions({ ask, context: ['internal', 'internal'] });+ await expect(internal.checkFsAccess(join(ws, 'linked.txt'), 'read')).resolves.toMatchObject({ allowed: false, code: 'hardlink' });+ expect(ask).not.toHaveBeenCalled();+ });++ it('skips the hard-link prompt under Local allow-all', async () => {+ const ask = vi.fn().mockResolvedValue('no');+ const permissions = makePermissions({ ask, context: ['cli', 'cli'] });+ permissions.setAutoApproveAll(true);+ await expect(permissions.checkFsAccess(join(ws, 'linked.txt'), 'read')).resolves.toMatchObject({ allowed: true });+ expect(ask).not.toHaveBeenCalled();+ });++ it('a directory with many links (subdirectories) is not treated as a hard-link alias', async () => {+ mkdirSync(join(ws, 'dir', 'a'), { recursive: true });+ mkdirSync(join(ws, 'dir', 'b'));+ const ask = vi.fn().mockResolvedValue('no');+ const permissions = makePermissions({ ask });+ await expect(permissions.checkFsAccess(join(ws, 'dir'), 'read')).resolves.toMatchObject({ allowed: true });+ expect(ask).not.toHaveBeenCalled();+ });++ it('a temp scope granted on a directory of symlinks does not reach through them', async () => {+ // The user approved the directory (session scope); its entries are+ // symlinks whose targets are still outside every readable scope → denied.+ mkdirSync(join(root, 'links'));+ symlinkSync(join(outside, 'id_rsa'), join(root, 'links', 'key'));+ const permissions = makePermissions();+ permissions.addTempScope(join(root, 'links'), true, false);+ const result = await permissions.checkFsAccess(join(root, 'links', 'key'), 'read');+ expect(result).toMatchObject({ allowed: false, code: 'symlink-escape', canonical: realpathSync(join(outside, 'id_rsa')) });+ });++ it('still returns the plain denial for an out-of-scope read without a handler', async () => {+ const permissions = makePermissions();+ const result = await permissions.checkFsAccess(join(outside, 'id_rsa'), 'read');+ expect(result).toMatchObject({ allowed: false, code: 'denied' });+ expect(result.reason).toBe(`Permission denied for read access to ${join(outside, 'id_rsa')}`);+ });+});diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.tsindex 5ab789a3..69585a0a 100644--- a/src/capabilities/permissions.ts+++ b/src/capabilities/permissions.ts@@ -1,4 +1,4 @@-import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync } from 'node:fs';+import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync, lstatSync } from 'node:fs';import { join, resolve, sep, dirname, basename } from 'node:path';import { homedir } from 'node:os';import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';@@ -45,6 +45,35 @@ export interface PermissionsManifest {};}+/** Device/inode pair identifying the file a read was authorised against. */+export interface FileIdentity {+ dev: number;+ ino: number;+}++export interface FsAccessResult {+ allowed: boolean;+ reason?: string;+ /**+ * Why a read was refused: `symlink-escape` (the canonical target lies+ * outside every readable scope), `hardlink` (nlink > 1 and no approval),+ * or `denied` (ordinary scope/user denial).+ */+ code?: 'symlink-escape' | 'hardlink' | 'denied';+ /**+ * Reads only: the canonical (realpath) target the check was made against.+ * Tools must open THIS path, never the lexical one, so a symlink swapped in+ * after the check cannot redirect the read.+ */+ canonical?: string;+ /**+ * Reads of existing files only: lstat identity of `canonical` at check+ * time. Tools compare it with `fstat` on the opened descriptor to defeat a+ * swap between check and open (TOCTOU).+ */+ fileId?: FileIdentity;+}+const DEFAULT_MANIFEST: PermissionsManifest = {capabilities: {filesystem: {@@ -297,6 +326,8 @@ export class PermissionManager {private currentChannelId: string = 'cli';private approvedCommandsByContext = new Map<string, Set<string>>();private approvedWritesByContext = new Map<string, Set<string>>();+ /** Hard-linked files the user answered "always" for, per interaction context. */+ private approvedHardlinkReadsByContext = new Map<string, Set<string>>();/*** Fail-closed mode (unattended agents, e.g. Mercury Bots): no interactive* approvals exist. Explicitly granted scopes apply without prompting;@@ -461,7 +492,120 @@ export class PermissionManager {}}- async checkFsAccess(path: string, mode: 'read' | 'write'): Promise<{ allowed: boolean; reason?: string }> {+ /**+ * Authorise a filesystem access. Writes: the lexical path must sit in a+ * writable scope and its canonical target must not escape (#105). Reads:+ * the same two conditions against readable scopes (an in-scope symlink to+ * `~/.ssh/id_rsa` is denied), plus a hard-link alias prompt (#104) and a+ * `canonical` + `fileId` the caller must verify at open time.+ *+ * Cost per read: one `realpath` and one `lstat`; nothing is cached across+ * calls, because the file system can change between them.+ */+ async checkFsAccess(path: string, mode: 'read' | 'write'): Promise<FsAccessResult> {+ if (mode === 'write') return this.checkScopedAccess(path, mode);++ const resolved = resolve(path);+ const canonical = this.canonicalizePath(resolved);++ // Skill elevation is an explicit "read anywhere" grant, so neither the+ // scope checks nor the alias prompt apply — but the caller still gets the+ // canonical path and identity so the open is verified like any other.+ if (this.elevatedCommands.has('fs_read')) {+ return this.describeRead(canonical).result;+ }++ const fs = this.manifest.capabilities.filesystem;+ if (!fs.enabled) {+ return { allowed: false, reason: 'Filesystem capability is disabled', code: 'denied' };+ }++ const lexicallyReadable = this.isLexicallyReadable(resolved);+ if (lexicallyReadable && canonical !== resolved && !this.isWithinScope(canonical, 'read')) {+ // The lexical path is approved but it is a symlink (or sits under one)+ // whose target is not. Treat it exactly like a read of the target: ask+ // the user for the target when a prompt is possible, otherwise deny —+ // the model is told the canonical path so it can request that scope.+ const reason = `Permission denied: read of ${path} resolves outside the approved scopes (${canonical})`;+ if (!this.failClosed && !this.isGlobalAutoApproveActive() && this.askHandler && this.currentChannelType !== 'internal') {+ const granted = await this.requestScopeExternal(canonical, 'read');+ if (!granted.allowed) return { allowed: false, reason, code: 'symlink-escape', canonical };+ } else {+ return { allowed: false, reason, code: 'symlink-escape', canonical };+ }+ } else if (!lexicallyReadable) {+ const scoped = await this.checkScopedAccess(path, mode);+ if (!scoped.allowed) return { ...scoped, code: 'denied', canonical };+ // A freshly approved scope covers the lexical path; the canonical+ // target must be covered too (an approval for a directory of symlinks+ // must not reach through them).+ if (canonical !== resolved && !this.isWithinScope(canonical, 'read')) {+ return {+ allowed: false,+ reason: `Permission denied: read of ${path} resolves outside the approved scopes (${canonical})`,+ code: 'symlink-escape',+ canonical,+ };+ }+ }++ return this.finishRead(path, canonical);+ }++ /** Lexical read check against the manifest and temp scopes. */+ private isLexicallyReadable(resolved: string): boolean {+ const scope = this.findScope(resolved);+ if (scope && scope.read) return true;+ const tempScope = this.findTempScope(resolved);+ return tempScope?.read === true;+ }++ /**+ * Post-scope read checks on the canonical target: a regular file with more+ * than one hard link may be an alias of a file outside every scope (the+ * inode carries no path, so the scope check cannot tell), so it goes+ * through the approval handler and is denied when nothing can ask (#104).+ */+ private async finishRead(path: string, canonical: string): Promise<FsAccessResult> {+ const described = this.describeRead(canonical);+ const nlink = described.nlink;+ if (nlink === undefined || nlink <= 1 || this.isGlobalAutoApproveActive()) return described.result;++ const approvedAliases = this.approvedHardlinkReadsByContext.get(this.currentChannelId);+ if (approvedAliases?.has(canonical)) return described.result;++ const reason = `Permission denied for read access to ${path}: the file has ${nlink} hard links and may alias a file outside the approved scopes`;+ if (this.failClosed || !this.askHandler || this.currentChannelType === 'internal') {+ return { allowed: false, reason, code: 'hardlink', canonical };+ }+ const response = await this.askHandler(+ `Read hard-linked file: ${canonical}\n(${nlink} links — it may be an alias of a file outside the approved scopes)`,+ );+ if (response === 'always') {+ const approved = approvedAliases ?? new Set<string>();+ approved.add(canonical);+ this.approvedHardlinkReadsByContext.set(this.currentChannelId, approved);+ return described.result;+ }+ if (response === 'yes') return described.result;+ return { allowed: false, reason: `User denied read of hard-linked file ${path}`, code: 'hardlink', canonical };+ }++ /** One lstat on the canonical target: identity for the open-time check plus the link count. */+ private describeRead(canonical: string): { result: FsAccessResult; nlink?: number } {+ try {+ const st = lstatSync(canonical);+ return {+ result: { allowed: true, canonical, fileId: { dev: st.dev, ino: st.ino } },+ nlink: st.isFile() ? st.nlink : undefined,+ };+ } catch {+ // Missing file: the tool reports "not found" itself.+ return { result: { allowed: true, canonical } };+ }+ }++ private async checkScopedAccess(path: string, mode: 'read' | 'write'): Promise<FsAccessResult> {if (mode === 'read' && this.elevatedCommands.has('fs_read')) {return { allowed: true };}@@ -483,7 +627,7 @@ export class PermissionManager {// whose canonicalised target falls outside every writable scope.if (mode === 'write') {const canonical = this.canonicalizePath(resolved);- if (canonical !== resolved && !this.isWithinWritableScope(canonical)) {+ if (canonical !== resolved && !this.isWithinScope(canonical, 'write')) {return {allowed: false,reason: `Permission denied: write to ${path} resolves outside the approved scopes (${canonical})`,@@ -799,12 +943,16 @@ export class PermissionManager {}}- /** True when a canonical path falls inside one of the writable scopes. */- private isWithinWritableScope(canonicalPath: string): boolean {- const writable = [...this.manifest.capabilities.filesystem.scopes, ...this.tempScopes].filter(- (scope) => scope.write,+ /**+ * True when a canonical path falls inside a scope granting `mode`. Scope+ * bases are canonicalised too so a scope declared through a symlinked+ * directory (macOS `/tmp` → `/private/tmp`) still covers its own files.+ */+ private isWithinScope(canonicalPath: string, mode: 'read' | 'write'): boolean {+ const granting = [...this.manifest.capabilities.filesystem.scopes, ...this.tempScopes].filter(+ (scope) => (mode === 'write' ? scope.write : scope.read),);- for (const scope of writable) {+ for (const scope of granting) {const base = this.canonicalizePath(resolve(scope.path.replace(/^~/, homedir())));if (canonicalPath === base || canonicalPath.startsWith(base + sep)) {return true;