diff --git a/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.md b/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.md index ece39654ea..425c1618eb 100644 --- a/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.md +++ b/.agents/notes/implemented/architecture/2026-07-02-fs-per-session-cwd.md @@ -8,13 +8,15 @@ The ACP bridge gives every session its own workspace: `session/new` records the Filesystem resolution used one plugin-load cwd while bash used the session project directory. Relative paths therefore disagreed whenever the editor project differed from the server launch directory; snapshots hid the bug by making those paths identical. +A valid absolute cwd can itself have two apparent parents: when it contains `symlink/..`, filesystem lookup follows the symlink before applying `..`, while `path.resolve()` erases both components lexically. Resolving sandbox policy lexically while launching bash from the raw cwd granted the unrelated lexical parent, denied writes in the real workspace, and let filesystem tools resolve relative paths into the wrong directory. + ## Decision -Thread the caller's session cwd into path resolution, exactly as `dsh-tool-bash` already does for `workdir`. The **caller** (the tool) supplies the cwd; the provider does not read a session or agent. +Thread the caller's session cwd into path resolution, exactly as `dsh-tool-bash` already does for `workdir`. Resolve that cwd to its native filesystem identity before any lexical join, and reuse the resolved sandbox-policy root for mutations and sandboxed bash calls so one call has one workspace identity. The **caller** (the tool) supplies the cwd; the provider does not read a session or agent. - `FileSystem.resolve` accepts `resolve(path: string, opts?: { cwd?: string; signal?: AbortSignal }): Promise`. `opts.cwd` is the base a RELATIVE `path` resolves against; an absolute `path` ignores it; omitting `opts.cwd` uses the backend's own default. `opts.signal` cancels resolution when the backend performs I/O. The options object keeps both caller-owned resolution controls together without positional growth. - `dsh-fs-local.resolve` uses `resolveLocalTarget(opts?.cwd ?? this.config.cwd, path)`. `config.cwd` stays the default for a caller that supplies none (non-ACP / no-session use, and the single-session stdio demo where `process.cwd()` IS the workspace). -- `dsh-tool-fs`'s `read`/`write`/`edit` derive the session cwd through a shared `sessionCwd(exec)` helper (`exec.agent?.session.header.cwd`, mirroring bash's `resolveWorkdir`) and pass it to `resolve`. A non-agent / headerless caller yields `undefined`, so the backend applies its default. +- `dsh-tool-fs`'s `read`/`write`/`edit` derive the session cwd through a shared `sessionCwd(exec)` helper (`exec.agent?.session.header.cwd`, mirroring bash's `resolveWorkdir`), canonicalize it with native realpath semantics, and pass it to `resolve`. A sandboxed mutation reuses the complete policy's `workspaceRoot`; a non-agent / headerless caller yields `undefined`, so the backend applies its default. ## Alternatives considered @@ -27,6 +29,7 @@ The default lives in ONE place — the provider's `config.cwd`. `sessionCwd` ret ## Consequences - In the ACP demo the fs tools and bash now agree on each session's workspace; an editor can open any project folder and both tool families act on it. +- A session cwd containing `symlink/..` resolves to the same physical workspace for bash launch, relative filesystem paths, and the sandbox grant; the lexical parent receives no grant. - No change to `FsTarget` identity: `targetKey` is still the realpath of the resolved absolute path, so observed-state keying and symlink identity are unaffected — a correct per-session cwd produces the same key bash targets. - Backward compatible: every existing `resolve(path)` call (all in tests) keeps working; the new argument is optional. - The single-session stdio demo is unaffected: it supplies no session cwd (its agent's session has no `cwd`), so resolution falls back to `config.cwd = process.cwd()`, which is the workspace. diff --git a/docs/core-data-structures/sandbox.md b/docs/core-data-structures/sandbox.md index c6f1fbae3f..bdc86287fb 100644 --- a/docs/core-data-structures/sandbox.md +++ b/docs/core-data-structures/sandbox.md @@ -38,7 +38,7 @@ type SandboxEnforcement = 'full' | 'partial' ## Per-call policy -The complete execution policy is resolved and carried per capability call. It includes `danger-full-access` so a consumer can resolve policy once before deciding whether to bypass confinement. Normal tool calls derive `workspaceRoot` from the calling session's immutable cwd; deployment configuration is the agentless fallback. +The complete execution policy is resolved and carried per capability call. It includes `danger-full-access` so a consumer can resolve policy once before deciding whether to bypass confinement. Normal tool calls derive `workspaceRoot` from the calling session's immutable cwd; deployment configuration is the agentless fallback. The root is canonicalized with filesystem semantics before lexical normalization, so a cwd containing `symlink/..` identifies the directory where a spawned process actually runs. ```ts type-equiv /** diff --git a/packages/bash/tool-bash/README.md b/packages/bash/tool-bash/README.md index 258967fad9..9e5fbcc4ad 100644 --- a/packages/bash/tool-bash/README.md +++ b/packages/bash/tool-bash/README.md @@ -17,12 +17,12 @@ The plugin also contributes the `tool:bash` prompt section (order 105): check th | `command` | string (required) | Run via `bash -c`. No state persists between calls — use `workdir`, not `cd`. | | `description` | string (required) | One-line, active-voice summary of the command (5-10 words), for UI/log display only — no effect on execution. | | `timeoutMs` | number | Timeout override in milliseconds. The executor applies its configured default and cap. | -| `workdir` | string | Working directory for this call. Defaults to the calling agent's session cwd (`session.header.cwd`) so each session runs in its own workspace; a relative `workdir` is resolved against that session cwd. | +| `workdir` | string | Working directory for this call. Defaults to the filesystem identity of the calling agent's session cwd (`session.header.cwd`) so each session runs in its own workspace; a relative `workdir` is resolved against that same identity. | | `run_in_background` | boolean | Return a task id immediately; no timeout applies. | | `sandbox_permissions` | string enum | ADVERTISED ONLY when the mounted executor sandboxes (`ctx.bash.sandboxMode` reports a confining default): the wider mode a denied command needs, from the closed target vocabulary `workspace-write`/`danger-full-access` (never cut down to the executor's default — the effective mode is per-session; strict widening is checked at execution against it, and a non-widening request fails without prompting anyone). | | `justification` | string | Required together with `sandbox_permissions` (each without the other is a validation error): one sentence for the user explaining why this exact command needs the wider access. | -`command`, `workdir`, and `timeoutMs` are resolved against the executor's config defaults via `ctx.bash.resolve()` before execution, so the executor seam (`BashExecSpec`) receives explicit `workdir`/`timeoutMs` values. The workdir default is applied in the tool layer (from the calling agent's `session.header.cwd`) BEFORE `resolve()` — the per-session cwd must come from `exec.agent`, since N sessions share one executor; only when no session cwd is available does the executor fall back to its own config / `process.cwd()`. +`command`, `workdir`, and `timeoutMs` are resolved against the executor's config defaults via `ctx.bash.resolve()` before execution, so the executor seam (`BashExecSpec`) receives explicit `workdir`/`timeoutMs` values. The workdir default is applied in the tool layer from the calling agent's `session.header.cwd` BEFORE `resolve()` — the per-session cwd must come from `exec.agent`, since N sessions share one executor; only when no session cwd is available does the executor fall back to its own config / `process.cwd()`. When sandbox policy is present, the tool reuses its already-canonical `workspaceRoot` as the workdir base so confinement and process launch cannot resolve the same session spelling differently. ### Managed shell environment diff --git a/packages/bash/tool-bash/src/index.ts b/packages/bash/tool-bash/src/index.ts index 5b552a224c..0b1c7a78c9 100644 --- a/packages/bash/tool-bash/src/index.ts +++ b/packages/bash/tool-bash/src/index.ts @@ -19,7 +19,7 @@ import type {} from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-tasks' import type {} from '@deepseek-ai/dsh-user-approval' import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' -import { ESCALATION_TARGETS, approveEscalation, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' +import { ESCALATION_TARGETS, approveEscalation, canonicalPath, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy' import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-bash' import type { DshEnvironment, DshEnvironmentKey } from '@deepseek-ai/dsh-bash' @@ -299,11 +299,18 @@ function presentBashResult(args: unknown, result: ToolResult): ToolResultView | } /** - * Resolve an explicit workdir first, making a relative one session-cwd-relative; - * otherwise use the session cwd and leave executor defaulting as the fallback. + * Resolve an explicit workdir first, making a relative one session-workspace-relative; + * otherwise use the filesystem identity of the session cwd and leave executor + * defaulting as the fallback. A resolved sandbox-policy root wins so workdir + * and confinement use the exact same per-call identity. */ -function resolveWorkdir(modelWorkdir: string | undefined, exec: { agent?: Agent }): string | undefined { - const sessionCwd = exec.agent?.session.header.cwd +function resolveWorkdir( + modelWorkdir: string | undefined, + exec: { agent?: Agent }, + policyWorkspaceRoot?: string, +): string | undefined { + const headerCwd = exec.agent?.session.header.cwd + const sessionCwd = policyWorkspaceRoot ?? (headerCwd === undefined ? undefined : canonicalPath(headerCwd)) if (modelWorkdir === undefined) return sessionCwd if (sessionCwd !== undefined && !isAbsolute(modelWorkdir)) { return resolvePath(sessionCwd, modelWorkdir) @@ -418,7 +425,7 @@ export function apply(ctx: Context, config: Config = {}): void { const policy = approvedMode === undefined ? standingPolicy : { ...(standingPolicy as SandboxExecutionPolicy), mode: approvedMode } - const workdir = resolveWorkdir(args.workdir, exec) + const workdir = resolveWorkdir(args.workdir, exec, standingPolicy?.workspaceRoot) const dshEnv = bashEnv.collect(exec) const request = { command: args.command, diff --git a/packages/examples/agent-spine-demo/tests/multi-project-sandbox.e2e.ts b/packages/examples/agent-spine-demo/tests/multi-project-sandbox.e2e.ts index 6ef409f7e3..a1726943a4 100644 --- a/packages/examples/agent-spine-demo/tests/multi-project-sandbox.e2e.ts +++ b/packages/examples/agent-spine-demo/tests/multi-project-sandbox.e2e.ts @@ -1,5 +1,5 @@ import { spawnSync } from 'node:child_process' -import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, rm, symlink } from 'node:fs/promises' import { homedir } from 'node:os' import { basename, join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' @@ -146,4 +146,50 @@ describe('one-context multi-project sandbox', () => { await expectMissing(join(projectB, 'from-a.txt')) await expectMissing(join(projectA, 'from-b.txt')) }) + + it.skipIf(!processSandboxUsable)('keeps symlink-sensitive session cwd semantics aligned across bash, fs, and policy', async () => { + const active = ctx as Context + const lexicalRoot = await projectDir('lexical-workspace') + const physicalRoot = await projectDir('physical-workspace') + const physicalChild = join(physicalRoot, 'child') + await mkdir(physicalChild) + const link = join(lexicalRoot, 'link') + await symlink(physicalChild, link, process.platform === 'win32' ? 'junction' : 'dir') + const sessionCwd = `${link}/..` + const handle = await active.agents.create({ + sessionId: SessionId('symlink-parent-session'), + meta: { cwd: sessionCwd }, + }) + + const [bashOwn, bashLexical, fsOwn, fsLexical] = await Promise.all([ + active.tools.execute({ + callId: CallId('bash-symlink-own'), name: 'bash', agent: handle.agent, + arguments: { command: 'printf bash > bash-owned.txt', description: 'Write physical workspace marker' }, + }), + active.tools.execute({ + callId: CallId('bash-symlink-lexical'), name: 'bash', agent: handle.agent, + arguments: { command: `printf escaped > ${join(lexicalRoot, 'bash-escaped.txt')}`, description: 'Attempt lexical workspace write' }, + }), + active.tools.execute({ + callId: CallId('fs-symlink-own'), name: 'write', agent: handle.agent, + arguments: { file_path: 'fs-owned.txt', content: 'fs' }, + }), + active.tools.execute({ + callId: CallId('fs-symlink-lexical'), name: 'write', agent: handle.agent, + arguments: { file_path: join(lexicalRoot, 'fs-escaped.txt'), content: 'escaped' }, + }), + ]) + + expect(bashOwn.isError).toBe(false) + expect(resultText(bashOwn)).not.toContain('[sandbox:') + expect(bashLexical.isError).toBe(false) + expect(resultText(bashLexical)).toContain('[sandbox: file access denied under workspace-write mode]') + expect(fsOwn.isError).toBe(false) + expect(fsLexical.isError).toBe(true) + expect(resultText(fsLexical)).toContain('[sandbox: file access denied under workspace-write mode]') + expect(await readFile(join(physicalRoot, 'bash-owned.txt'), 'utf8')).toBe('bash') + expect(await readFile(join(physicalRoot, 'fs-owned.txt'), 'utf8')).toBe('fs') + await expectMissing(join(lexicalRoot, 'bash-escaped.txt')) + await expectMissing(join(lexicalRoot, 'fs-escaped.txt')) + }) }) diff --git a/packages/fs/README.md b/packages/fs/README.md index 98737f380d..7b5561ca4d 100644 --- a/packages/fs/README.md +++ b/packages/fs/README.md @@ -8,7 +8,7 @@ The filesystem stack: a provider seam (text IO + atomic mutation with an optiona | `fs-local/` | Local-filesystem `FileSystem` implementation | (registers `ctx.fs`) | | `fs-sandbox/` | Sandbox-enforcing `FileSystem`: extends `fs-local` and fences write/edit by the per-call mode + workspace root policy (read-only denies, workspace-write contains to the session workspace + temp roots), reads pass through | (registers `ctx.fs`) | | `fs-policy/` | Policy gate plugin: observed-state + read-before-edit + version-guarded write/edit, via the `fs/*` event gate | (no service — `fs/*` listeners) | -| `tool-fs/` | Model-facing `read`/`write`/`edit` tools AND the executor (reads via `ctx.fs`, owns read windowing, dispatches `fs/*`); advertises the sandbox escalation fields when the mounted `ctx.fs` confines | (registers on `ctx.tools`) | +| `tool-fs/` | Model-facing `read`/`write`/`edit` tools AND the executor (reads via `ctx.fs`, owns read windowing, dispatches `fs/*`); resolves relative paths from the filesystem identity of the session cwd and advertises sandbox escalation fields when the mounted `ctx.fs` confines | (registers on `ctx.tools`) | | `tool-fs-search/` | Model-facing `glob`/`grep` discovery tools when `rg` is available on the bash executor `PATH`, backed by fixed ripgrep commands through `ctx.bash`, NOT by `ctx.fs` provider methods | (registers on `ctx.tools`) | The interface lives at `fs/fs/`. A sandboxed, remote, or project-scoped filesystem backend can replace `fs-local` without touching the seam, the policy gate, or the model-facing tool schemas — `fs-sandbox` is the first such replacement (an in-process path fence over the shared sandbox mode; see [the cross-family fs sandbox Agent Note](../../.agents/notes/implemented/feature/2026-07-14-cross-family-fs-sandbox.md)). The policy (`fs-policy/`) is a plugin that participates only through the `fs/*` event gate, not a service the tool injects — so dropping it gracefully loses the policy and leaves the unconstrained bare provider rather than breaking the tool. A deployment that loads `tool-fs/` is expected to also load it. The mode fence and the read-before-edit gate are orthogonal and compose. Discovery (`tool-fs-search/`) deliberately does NOT extend the provider seam: search is a process-backed `rg` workflow on the bash executor, so filesystem backends stay free of a universal search contract; its tools register only when that executor can find `rg`, and its results are follow-up-readable when the bash workdir and the `read` root are the same workspace (the co-located deployment its README documents). diff --git a/packages/fs/tool-fs/src/edit.ts b/packages/fs/tool-fs/src/edit.ts index a0742c730d..ec7c44902b 100644 --- a/packages/fs/tool-fs/src/edit.ts +++ b/packages/fs/tool-fs/src/edit.ts @@ -95,7 +95,7 @@ export function applyEditTool(ctx: Context, sandbox: FsSandboxSurface): void { // Resolve the per-call sandbox policy (approved mode > session override // > backend default, plus the session cwd root) BEFORE anything executes. const sandboxPolicy = await sandbox.resolvePolicy('edit', args, exec) - const target = await ctx.fs.resolve(input.filePath, sessionResolveOptions(exec)) + const target = await ctx.fs.resolve(input.filePath, sessionResolveOptions(exec, sandboxPolicy?.workspaceRoot)) // Single-slot decision: the policy plugin returns { version: vObserved } or // throws FS_NOT_OBSERVED; the bare default is undefined (unconditional edit). // No stat — the bare default never manufactures a version basis. diff --git a/packages/fs/tool-fs/src/session-cwd.ts b/packages/fs/tool-fs/src/session-cwd.ts index 4f98a41a94..c9f86ed196 100644 --- a/packages/fs/tool-fs/src/session-cwd.ts +++ b/packages/fs/tool-fs/src/session-cwd.ts @@ -9,6 +9,7 @@ */ import type { ToolExecution } from '@deepseek-ai/dsh-tools' +import { canonicalPath } from '@deepseek-ai/dsh-sandbox' /** * The session workspace cwd for this call, or `undefined` when none applies. @@ -16,16 +17,18 @@ import type { ToolExecution } from '@deepseek-ai/dsh-tools' * @returns the calling agent's session cwd, or undefined for a non-agent caller (the backend then applies its own default). */ export function sessionCwd(exec: ToolExecution): string | undefined { - return exec.agent?.session.header.cwd + const cwd = exec.agent?.session.header.cwd + return cwd === undefined ? undefined : canonicalPath(cwd) } /** * Resolution options shared by all model-facing filesystem tools. * @param exec - the tool-execution context supplying session cwd and cancellation. + * @param policyWorkspaceRoot - resolved per-call root, when a mutation carries sandbox policy. * @returns provider resolution options for the current tool call. */ -export function sessionResolveOptions(exec: ToolExecution): { cwd?: string; signal?: AbortSignal } { - const cwd = sessionCwd(exec) +export function sessionResolveOptions(exec: ToolExecution, policyWorkspaceRoot?: string): { cwd?: string; signal?: AbortSignal } { + const cwd = policyWorkspaceRoot ?? sessionCwd(exec) return { ...cwd !== undefined ? { cwd } : {}, ...exec.signal !== undefined ? { signal: exec.signal } : {}, diff --git a/packages/fs/tool-fs/src/write.ts b/packages/fs/tool-fs/src/write.ts index 4e7bf48816..38a01faa83 100644 --- a/packages/fs/tool-fs/src/write.ts +++ b/packages/fs/tool-fs/src/write.ts @@ -80,7 +80,7 @@ export function applyWriteTool(ctx: Context, sandbox: FsSandboxSurface): void { // > backend default, plus the session cwd root) BEFORE anything executes; // an escalating call throws its distinct text on any non-grant. const sandboxPolicy = await sandbox.resolvePolicy('write', args, exec) - const target = await ctx.fs.resolve(input.filePath, sessionResolveOptions(exec)) + const target = await ctx.fs.resolve(input.filePath, sessionResolveOptions(exec, sandboxPolicy?.workspaceRoot)) // Single-slot decision: the policy plugin produces createIfAbsent/ // replaceIfVersion; the bare default is undefined (unconditional). No stat. const intent = await ctx.waterfall('fs/write-intent', target, exec, () => undefined) diff --git a/packages/sandbox/sandbox-policy/README.md b/packages/sandbox/sandbox-policy/README.md index 0dbab99e52..fac9f5730b 100644 --- a/packages/sandbox/sandbox-policy/README.md +++ b/packages/sandbox/sandbox-policy/README.md @@ -9,11 +9,11 @@ Two families enforce the same mode vocabulary: the sandboxed bash executor (`@de ## Config - `mode` — the deployment default `SandboxMode` (`read-only` / `workspace-write` / `danger-full-access`), validated at load. Default `read-only` (fail-safe). -- `workspaceRoot` — the fallback directory `workspace-write` may write under for agentless calls or sessions without a cwd. Default `process.cwd()`, resolved absolute either way. A normal agent call uses its session header's immutable `cwd` instead. +- `workspaceRoot` — the fallback directory `workspace-write` may write under for agentless calls or sessions without a cwd. Default `process.cwd()`, resolved to its absolute filesystem identity either way. A normal agent call uses its session header's immutable `cwd` instead. ## Surface -- `ctx.sandboxPolicy.resolve({ session?, mode? })` — resolves one complete per-call policy. An explicit approved mode outranks the session's last `sandbox/mode` event, which outranks `defaultMode`; the session's immutable `cwd` becomes `workspaceRoot`, otherwise the configured fallback applies. +- `ctx.sandboxPolicy.resolve({ session?, mode? })` — resolves one complete per-call policy. An explicit approved mode outranks the session's last `sandbox/mode` event, which outranks `defaultMode`; the session's immutable `cwd` is canonicalized with filesystem semantics before becoming `workspaceRoot`, otherwise the configured fallback applies. Canonicalization precedes lexical normalization so `symlink/..` agrees with process working-directory resolution. - `ctx.sandboxPolicy.defaultMode` / `ctx.sandboxPolicy.workspaceRoot` — the deployment default and fallback root used by `resolve()`. - `effectiveSandboxMode(events)` — the pure fold of a session's `sandbox/mode` events (the last switch wins, or `undefined`), used inside `resolve()`. - `setSandboxMode(session, mode)` — THE write path for a per-session override: appends exactly one `sandbox/mode` event. The switch IS its event; nothing mutates the mode out of band. diff --git a/packages/sandbox/sandbox-policy/src/index.ts b/packages/sandbox/sandbox-policy/src/index.ts index cd768c1db8..23a205e60c 100644 --- a/packages/sandbox/sandbox-policy/src/index.ts +++ b/packages/sandbox/sandbox-policy/src/index.ts @@ -17,12 +17,17 @@ import { resolve as resolvePath } from 'node:path' import { Context, Service } from 'cordis' import z from 'schemastery' -import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' +import { canonicalPath, type SandboxExecutionPolicy, type SandboxMode } from '@deepseek-ai/dsh-sandbox' import type { Session } from '@deepseek-ai/dsh-session' import { effectiveSandboxMode } from './session-mode.ts' export { SANDBOX_MODES, effectiveSandboxMode, setSandboxMode } from './session-mode.ts' +/** Resolve filesystem identity before lexical normalization can erase symlink-sensitive components. */ +function resolveWorkspaceRoot(path: string): string { + return resolvePath(canonicalPath(path)) +} + declare module 'cordis' { interface Context { sandboxPolicy: SandboxPolicyService @@ -80,7 +85,7 @@ export class SandboxPolicyService extends Service { // runtime fact. `workspaceRoot` has NO schema default, so its fallback to // the process cwd is real branching, resolved absolute either way. this.defaultMode = config.mode as SandboxMode - this.workspaceRoot = resolvePath(config.workspaceRoot ?? process.cwd()) + this.workspaceRoot = resolveWorkspaceRoot(config.workspaceRoot ?? process.cwd()) } /** @@ -96,7 +101,7 @@ export class SandboxPolicyService extends Service { const { session } = request return { mode: request.mode ?? (session === undefined ? undefined : effectiveSandboxMode(session.events)) ?? this.defaultMode, - workspaceRoot: resolvePath(session?.header.cwd ?? this.workspaceRoot), + workspaceRoot: resolveWorkspaceRoot(session?.header.cwd ?? this.workspaceRoot), } } } diff --git a/packages/sandbox/sandbox-policy/tests/policy.spec.ts b/packages/sandbox/sandbox-policy/tests/policy.spec.ts index 77d6b6dae0..cd81caa6b4 100644 --- a/packages/sandbox/sandbox-policy/tests/policy.spec.ts +++ b/packages/sandbox/sandbox-policy/tests/policy.spec.ts @@ -4,7 +4,9 @@ * override kit (fold + write path) both enforcing families read. */ -import { resolve } from 'node:path' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve, sep } from 'node:path' import { describe, expect, it } from 'vitest' import { Context } from 'cordis' import { Session, SessionId } from '@deepseek-ai/dsh-session' @@ -67,6 +69,28 @@ describe('SandboxPolicyService', () => { }) }) + it('resolves a symlink-sensitive session cwd with filesystem semantics', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-policy-cwd-')) + try { + const lexical = join(root, 'lexical') + const physical = join(root, 'physical') + const child = join(physical, 'child') + mkdirSync(lexical) + mkdirSync(child, { recursive: true }) + const link = join(lexical, 'link') + symlinkSync(child, link, process.platform === 'win32' ? 'junction' : 'dir') + const cwd = `${link}${sep}..` + const ctx = await mounted({ mode: 'workspace-write', workspaceRoot: '/fallback' }) + + expect(ctx.sandboxPolicy.resolve({ session: session('sess-symlink-parent', cwd) })).toEqual({ + mode: 'workspace-write', + workspaceRoot: realpathSync.native(physical), + }) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + it('lets an approved mode outrank the session mode while retaining its root', async () => { const ctx = await mounted({ workspaceRoot: '/fallback' }) const active = session('sess-approved', '/projects/approved') diff --git a/packages/sandbox/sandbox/README.md b/packages/sandbox/sandbox/README.md index 8c49c01a62..2b2d6e8df7 100644 --- a/packages/sandbox/sandbox/README.md +++ b/packages/sandbox/sandbox/README.md @@ -6,7 +6,7 @@ The contract in one line: `ctx.sandbox.confine(argv, policy)` returns the argv t Policy rides the call, not the provider: two consumers may confine under different policies at the same instant (bash under `read-only` while a confined child agent keeps its state directory writable), and an approved escalated retry is just a new call with a wider policy. -**Same-world confinement only.** A backend shares the host's filesystem and kernel (`bwrap`, Landlock, Seatbelt); `workspaceRoot` names a real host path. Containers, microVMs, and remote executors are NOT backends of this seam — they replace whole capability implementations (`ctx.bash`, `ctx.fs`) as environment-coherent groups. The boundary and its rationale: [the sandbox Agent Note](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md). +**Same-world confinement only.** A backend shares the host's filesystem and kernel (`bwrap`, Landlock, Seatbelt); `workspaceRoot` names the filesystem-canonical real host directory. Workspace identity is resolved before lexical normalization, so a valid cwd containing `symlink/..` grants the directory where `chdir` actually lands rather than an unrelated lexical parent. Containers, microVMs, and remote executors are NOT backends of this seam — they replace whole capability implementations (`ctx.bash`, `ctx.fs`) as environment-coherent groups. The boundary and its rationale: [the sandbox Agent Note](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md). Implementations: [`@deepseek-ai/dsh-sandbox-local`](../sandbox-local/) (Linux: `bwrap`, else the per-platform Landlock launcher; macOS: `sandbox-exec`/Seatbelt). Consumers: [`@deepseek-ai/dsh-bash-sandbox`](../../bash/bash-sandbox/) (wraps `['bash', '-c', command]`). diff --git a/packages/sandbox/sandbox/src/roots.ts b/packages/sandbox/sandbox/src/roots.ts index 06e8cd7c09..1215f3dac1 100644 --- a/packages/sandbox/sandbox/src/roots.ts +++ b/packages/sandbox/sandbox/src/roots.ts @@ -29,9 +29,13 @@ import type { SandboxExecutionPolicy } from './index.ts' */ export function canonicalPath(path: string): string { try { - return realpathSync(path) + // Node's JavaScript realpath implementation lexically collapses `..` + // before resolving a preceding symlink on some platforms. The native + // implementation follows the filesystem's component-by-component lookup, + // matching chdir/spawn and the enforcement layers this identity feeds. + return realpathSync.native(path) } catch { - // realpathSync failed: the path (or a prefix) is missing or unreadable. + // realpathSync.native failed: the path (or a prefix) is missing or unreadable. return path } }