From a87ff53a1e9c6c77efaa1d3beed3a2b0905b2c77 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:20:47 +0000 Subject: [PATCH 1/3] feat(team): confine member Bot commands on Linux Hosts (#4183) Member Bot commands run in a bwrap profile that hides DSH_HOME, homes, /run and other Bots' Memory and Workspaces, binds back only the Session roots, removes secret environment variables, and joins a private network namespace that denies the Host loopback, link-local, private and tailnet ranges. Team mode reports enforced isolation only when both work. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lpx6qkvJqKRjdg67NfFT7X --- changes/4183-team-mode-linux-confinement.md | 11 + docs/architecture/team-mode.md | 2 +- docs/architecture/team-mode.zh.md | 2 +- docs/bot-cli.md | 2 +- docs/bot-cli.zh.md | 2 +- packages/core/package.json | 1 + .../core/src/execution/linux-confinement.ts | 236 +++++++++++ .../core/src/execution/member-confinement.ts | 218 ++++++++++ packages/core/src/plugin.ts | 6 + packages/core/src/team/http.ts | 2 +- packages/core/src/team/service.ts | 21 +- .../core/src/workspaces/grant-native-tools.ts | 13 +- packages/core/test/member-confinement.test.ts | 384 ++++++++++++++++++ packages/core/test/team-approvals.test.ts | 26 ++ pnpm-lock.yaml | 3 + 15 files changed, 920 insertions(+), 9 deletions(-) create mode 100644 changes/4183-team-mode-linux-confinement.md create mode 100644 packages/core/src/execution/linux-confinement.ts create mode 100644 packages/core/src/execution/member-confinement.ts create mode 100644 packages/core/test/member-confinement.test.ts diff --git a/changes/4183-team-mode-linux-confinement.md b/changes/4183-team-mode-linux-confinement.md new file mode 100644 index 0000000000..842f1eea37 --- /dev/null +++ b/changes/4183-team-mode-linux-confinement.md @@ -0,0 +1,11 @@ +--- +section: Added +--- + +## en + +- On Linux Hosts, Team mode now confines member Bots' commands. A member Bot's Shell sees only its own Memory and the folders its Session may use, cannot reach the Host's local services or private network addresses, and runs without secret environment variables. When bubblewrap, slirp4netns and nftables all work, the trial notice changes to "members are isolated"; otherwise the trial notice stays and `deepseekbot team-mode status` lists what is missing ([#4183](https://github.com/BotHarness/DeepSeekBot/issues/4183)). + +## zh + +- 在 Linux Host 上,团队模式现在会隔离成员 Bot 的命令:成员 Bot 的 Shell 只能看到自己的 Memory 和当前 Session 有权使用的文件夹,无法访问 Host 本机服务和私有网络地址,运行时也不带密钥类环境变量。bubblewrap、slirp4netns 和 nftables 都可用时,试用告知会变成“成员之间已隔离”;否则继续显示试用告知,`deepseekbot team-mode status` 会列出缺少的组件([#4183](https://github.com/BotHarness/DeepSeekBot/issues/4183))。 diff --git a/docs/architecture/team-mode.md b/docs/architecture/team-mode.md index 17a552ed64..b76eb18b5a 100644 --- a/docs/architecture/team-mode.md +++ b/docs/architecture/team-mode.md @@ -45,7 +45,7 @@ A Tobs Host — an office computer or a VPS — can be used remotely by colleagu Settled scope: - Until M12, Team mode is a light **trial**. One plain notice says that member Bots can technically read other Bots' data on this Host. There is no per-call Shell approval. Member Bots never escalate or use `danger-full-access` (M5). -- **M12** adds Linux execution confinement. A `runnerCommand` wrapper around DSH's bwrap hides `DSH_HOME`, the space roots and `/home`, and binds back only the Session's allowed roots (mirroring `currentRoots(session, kind)`). A network namespace denies loopback, link-local, private ranges and the tailnet. It fails closed without a resolvable Session. M12 is required before Team mode leaves the trial, because secrets stay on the Host. +- **M12** adds Linux execution confinement. BotHarness wraps `ctx.sandbox.confine` rather than setting `runnerCommand`, because only `confine` receives the calling `sessionId`. For a member Bot, the command runs in a bwrap profile that hides `DSH_HOME`, the Host user's home, `/home`, `/root`, `/run`, `/mnt`, `/media`, `/srv`, every other Bot's Memory and every Workspace outside the Session, then binds back only the Session's roots (`sessionRoots`, the same computation as `currentRoots(session, kind)`), a private `HOME` beside the Bot's Memory, and the Host's tool directories from `PATH`. Secret-looking environment variables are removed inside the sandbox. A user and network namespace with slirp4netns and an nftables table allows the public internet and DNS, and denies the Host's loopback, link-local, RFC1918, `100.64.0.0/10` and multicast. A command without a calling Session is refused while Team mode is on, and an owned Session whose Bot or roots cannot be resolved is refused, never widened. `isolation` becomes `enforced` only when the probe finds both bwrap and the network namespace working; otherwise the trial notice stays and the Owner's `team-mode status` shows `confinement.missing`. M12 is required before Team mode leaves the trial, because secrets stay on the Host. - Account spaces (`spaces/`) and audience-scoped shared spaces (for example `shared/team`, `shared/finance`). Each space keeps Bot Memory (`bots//memory`) apart from its grantable `files/` folder. - Not in scope: per-account quotas, macOS and Windows confinement (macOS Team Hosts keep the trial notice), deployment check scripts, microVMs, per-member OS users or containers. Highly sensitive data is best kept on a separate Host. diff --git a/docs/architecture/team-mode.zh.md b/docs/architecture/team-mode.zh.md index e7c4a2953e..1f2239b79b 100644 --- a/docs/architecture/team-mode.zh.md +++ b/docs/architecture/team-mode.zh.md @@ -25,7 +25,7 @@ Human 在 2026-11-13 完成 Q1–Q35 并确认的目标设计,不代表已实 敲定的范围: - M12 之前,Team mode 以轻量**试用**形态开放:只显示一句告知"成员的 Bot 技术上能读到这台 Host 上其他 Bot 的数据",不对 Shell 做逐次审批;成员 Bot 不能升级,也不能用 `danger-full-access`(M5)。 -- **M12**:Linux 执行隔离。给 DSH 的 bwrap 包一层 `runnerCommand` 脚本,隐藏 `DSH_HOME`、各空间目录和 `/home`,只挂回这个 Session 有权访问的目录;网络命名空间拒绝本机、链路本地地址、私有网段和 tailnet;解析不到 Session 时拒绝执行。机密放在 Host 上,所以结束试用之前必须完成 M12。 +- **M12**:Linux 执行隔离。BotHarness 包装 `ctx.sandbox.confine`,而不是设置 `runnerCommand`,因为只有 `confine` 能拿到调用方的 `sessionId`。成员 Bot 的命令运行在 bwrap 里:隐藏 `DSH_HOME`、Host 用户主目录、`/home`、`/root`、`/run`、`/mnt`、`/media`、`/srv`、其他 Bot 的 Memory 和这个 Session 之外的所有 Workspace,再只挂回 Session 有权访问的目录(`sessionRoots`,与 `currentRoots(session, kind)` 同一套计算)、Bot Memory 旁边的私有 `HOME`,以及 `PATH` 里的 Host 工具目录。看起来像密钥的环境变量在沙箱内被移除。用户和网络命名空间配合 slirp4netns 与 nftables:允许公网和 DNS,拒绝 Host 本机、链路本地、RFC1918、`100.64.0.0/10` 和组播地址。Team mode 开启时,没有调用方 Session 的命令一律拒绝;归属已知但 Bot 或目录解析不到的 Session 也拒绝,绝不放宽。只有探测到 bwrap 和网络命名空间都可用时 `isolation` 才变为 `enforced`;否则继续显示试用告知,Owner 的 `team-mode status` 会在 `confinement.missing` 里列出缺少的组件。机密放在 Host 上,所以结束试用之前必须完成 M12。 - 账号空间(`spaces/`)和按受众划分的共享空间(如 `shared/team`、`shared/finance`);每个空间里,Bot 的 Memory(`bots//memory`)和可以授权的 `files/` 目录分开存放。 - 不在范围内:账号配额,macOS 和 Windows 的隔离(macOS 上的 Team Host 一直显示试用告知),部署检查脚本,microVM,每个成员一个 OS 用户或容器。高敏感数据建议放在单独的 Host 上。 diff --git a/docs/bot-cli.md b/docs/bot-cli.md index 6071605d61..855e51e408 100644 --- a/docs/bot-cli.md +++ b/docs/bot-cli.md @@ -2110,7 +2110,7 @@ deepseekbot members purge bob --preview deepseekbot members purge bob --token-stdin --confirm < purge-token.txt ``` -Password changes default to signing out every other browser and paired device; `false` keeps them except during the forced first change. Lifecycle operations require `members.manage` with the target-role ceiling; Owner and self targets are protected, and only the Owner can manage Admin targets. Deactivation preserves data and revokes every grant. Reactivation requires fresh sign-in. Transfer moves group Channel ownership and the member's private Bots, with their Memory and DM history, to an active member or the Owner; preview lists both before anything moves. The member's Tob stays with them until purge. Purge requires deactivation and completed transfer, then a single-use, five-minute token from the preview. The username argument supplies the exact username confirmation; stdin supplies only the token. Shared messages retain `author.humanId` with `author.deleted: true` and no display name. `team-mode status` includes `activeMembers`; `team-mode off` also returns `suspendedMembers`. Previously deactivated accounts remain deactivated after off/on. Purge also removes the member's Tob and any private Bots still owned by them, with their Memory; DMs that another Human took part in are kept. +Password changes default to signing out every other browser and paired device; `false` keeps them except during the forced first change. Lifecycle operations require `members.manage` with the target-role ceiling; Owner and self targets are protected, and only the Owner can manage Admin targets. Deactivation preserves data and revokes every grant. Reactivation requires fresh sign-in. Transfer moves group Channel ownership and the member's private Bots, with their Memory and DM history, to an active member or the Owner; preview lists both before anything moves. The member's Tob stays with them until purge. Purge requires deactivation and completed transfer, then a single-use, five-minute token from the preview. The username argument supplies the exact username confirmation; stdin supplies only the token. Shared messages retain `author.humanId` with `author.deleted: true` and no display name. `team-mode status` includes `activeMembers` and `isolation` (`enforced` only while Linux file and network confinement are both active). For the Owner it also includes `confinement` with `enforcement`, `filesystem`, `network` and the `missing` tools; `team-mode off` also returns `suspendedMembers`. Previously deactivated accounts remain deactivated after off/on. Purge also removes the member's Tob and any private Bots still owned by them, with their Memory; DMs that another Human took part in are kept. ```sh deepseekbot usage members --period week [--as ] diff --git a/docs/bot-cli.zh.md b/docs/bot-cli.zh.md index 6fbb6ec47c..7427a1b210 100644 --- a/docs/bot-cli.zh.md +++ b/docs/bot-cli.zh.md @@ -2030,7 +2030,7 @@ deepseekbot members purge bob --preview deepseekbot members purge bob --token-stdin --confirm < purge-token.txt ``` -改密默认注销其他所有浏览器和配对设备;`false` 保留其他设备,首次强制改密除外。生命周期操作需要 `members.manage` 并遵循目标角色的权限上限;不能操作 Owner 或自己,Admin 目标仅限 Owner。停用保留数据并撤销全部授权,重新激活后需要重新登录。移交会把群 Channel 所有权以及该成员的私有 Bot(连同其 Memory 和私信记录)交给活跃成员或 Owner;预览会先列出两者。成员的 Tob 在永久删除前仍归其本人。永久删除要求先停用并完成移交,再使用预览返回的五分钟内有效、一次性令牌。用户名参数提供精确的用户名确认,stdin 仅提供令牌。共享消息保留 `author.humanId`,增加 `author.deleted: true` 并移除显示名。`team-mode status` 返回 `activeMembers`,`team-mode off` 另返回 `suspendedMembers`;关闭再开启不会激活原本已停用的账户。永久删除还会移除该成员的 Tob 以及仍归其所有的私有 Bot 和对应 Memory;有其他人参与过的私信会保留。 +改密默认注销其他所有浏览器和配对设备;`false` 保留其他设备,首次强制改密除外。生命周期操作需要 `members.manage` 并遵循目标角色的权限上限;不能操作 Owner 或自己,Admin 目标仅限 Owner。停用保留数据并撤销全部授权,重新激活后需要重新登录。移交会把群 Channel 所有权以及该成员的私有 Bot(连同其 Memory 和私信记录)交给活跃成员或 Owner;预览会先列出两者。成员的 Tob 在永久删除前仍归其本人。永久删除要求先停用并完成移交,再使用预览返回的五分钟内有效、一次性令牌。用户名参数提供精确的用户名确认,stdin 仅提供令牌。共享消息保留 `author.humanId`,增加 `author.deleted: true` 并移除显示名。`team-mode status` 返回 `activeMembers` 和 `isolation`(只有 Linux 文件与网络隔离都生效时才是 `enforced`);Owner 还会看到 `confinement`,包含 `enforcement`、`filesystem`、`network` 和缺少的工具 `missing`。`team-mode off` 另返回 `suspendedMembers`;关闭再开启不会激活原本已停用的账户。永久删除还会移除该成员的 Tob 以及仍归其所有的私有 Bot 和对应 Memory;有其他人参与过的私信会保留。 ```sh deepseekbot usage members --period week [--as ] diff --git a/packages/core/package.json b/packages/core/package.json index 30a1597ee0..547d45200c 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -53,6 +53,7 @@ "@deepseek-ai/dsh-jobs": "0.2.2-rc.1", "@deepseek-ai/dsh-llm": "0.2.2-rc.1", "@deepseek-ai/dsh-mcp-client": "0.2.2-rc.1", + "@deepseek-ai/dsh-sandbox": "0.2.2-rc.1", "@deepseek-ai/dsh-sandbox-policy": "0.2.2-rc.1", "@deepseek-ai/dsh-schedule": "0.2.2-rc.1", "@deepseek-ai/dsh-scope": "0.2.2-rc.1", diff --git a/packages/core/src/execution/linux-confinement.ts b/packages/core/src/execution/linux-confinement.ts new file mode 100644 index 0000000000..73aa2ea227 --- /dev/null +++ b/packages/core/src/execution/linux-confinement.ts @@ -0,0 +1,236 @@ +import { spawnSync } from 'node:child_process'; + +export type ConfinementEnforcement = 'full' | 'partial' | 'unavailable'; +export interface ConfinementStatus { + enforcement: ConfinementEnforcement; + filesystem: boolean; + network: boolean; + missing: string[]; +} + +export interface ExecutionPlan { + readable: string[]; + writable: string[]; + hidden: string[]; + tools?: string[] | undefined; + home: string; + resolvConf?: string | undefined; +} + +export const RUNNER_FAILURE_SIGNATURE = 'bh-confine: '; +export const DENIAL_SIGNATURES = ['read-only file system', 'permission denied'] as const; + +export const NETWORK_RULES = `table inet botharness { + chain output { + type filter hook output priority 0; policy accept; + ip daddr 10.0.2.3 meta l4proto { tcp, udp } th dport 53 accept + oifname "lo" accept + ip daddr { 0.0.0.0/8, 10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16, 224.0.0.0/3 } goto deny + ip6 daddr { ::/127, ::ffff:0:0/96, fc00::/7, fe80::/10, ff00::/8 } goto deny + } + chain deny { + meta l4proto tcp reject with tcp reset + reject + } +} +`; + +export const NETWORK_RUNNER = String.raw`set -u +fail() { echo "bh-confine: $1" >&2; exit 125; } +dir=$(mktemp -d) || fail "cannot create a private runtime directory" +cleanup() { [ -n "\${slirp:-}" ] && kill "$slirp" 2>/dev/null; rm -rf "$dir"; } +trap cleanup EXIT +trap 'kill -TERM "\${child:-0}" 2>/dev/null' TERM INT HUP +rules=$1 +shift +printf 'nameserver 10.0.2.3\n' > "$dir/resolv.conf" || fail "cannot create a private resolver file" +mkfifo "$dir/go" || fail "cannot create a synchronisation pipe" +unshare --user --map-root-user --net --kill-child -- /bin/sh -c ' + read -r ready < "$1/go" + [ "$ready" = go ] || { echo "bh-confine: network setup was not confirmed" >&2; exit 125; } + ip link set lo up 2>/dev/null + n=0 + until grep -q tap0 /proc/net/route; do + n=$((n + 1)) + [ "$n" -gt 250 ] && { echo "bh-confine: the private network has no route" >&2; exit 125; } + sleep 0.02 + done + printf "%s" "$2" | nft -f - || { echo "bh-confine: network rules were refused" >&2; exit 125; } + nft list table inet botharness >/dev/null 2>&1 || { echo "bh-confine: network rules are not active" >&2; exit 125; } + exec 9< "$1/resolv.conf" || { echo "bh-confine: the private resolver file is missing" >&2; exit 125; } + shift 2 + exec "$@" +' bh-confine "$dir" "$rules" "$@" & +child=$! +host=$(readlink /proc/self/ns/net) +i=0 +while [ "$(readlink "/proc/$child/ns/net" 2>/dev/null)" = "$host" ]; do + i=$((i + 1)) + if [ "$i" -gt 250 ] || ! kill -0 "$child" 2>/dev/null; then + kill -KILL "$child" 2>/dev/null + fail "the private network namespace did not start" + fi + sleep 0.02 +done +slirp4netns --configure --mtu=65520 --disable-host-loopback --ready-fd=3 "$child" tap0 3>"$dir/ready" >"$dir/slirp.log" 2>&1 & +slirp=$! +i=0 +while [ ! -s "$dir/ready" ]; do + i=$((i + 1)) + if [ "$i" -gt 250 ] || ! kill -0 "$slirp" 2>/dev/null; then + kill -KILL "$child" 2>/dev/null + fail "the private network did not start" + fi + sleep 0.02 +done +printf 'go\n' > "$dir/go" +wait "$child" +`; + +export const SECRET_ENV_PATTERN = + '(^|_)(API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|COOKIE|AUTH)(_|$)|^DSH_|^DEEPSEEKBOT_HOST$'; + +export const ENV_SCRUB = String.raw`for name in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' | grep -Ei "$1"); do unset "$name" 2>/dev/null; done +shift +exec "$@" +`; + +export function secretEnvNames(env: NodeJS.ProcessEnv): string[] { + const pattern = new RegExp(SECRET_ENV_PATTERN, 'iu'); + return Object.keys(env).filter((name) => pattern.test(name)); +} + +export function bwrapArgs( + plan: ExecutionPlan, + mode: 'read-only' | 'workspace-write', + network = false, +): string[] { + const args = [ + '--ro-bind', + '/', + '/', + '--dev', + '/dev', + '--unshare-user', + '--unshare-pid', + '--unshare-ipc', + '--unshare-uts', + '--unshare-cgroup-try', + '--proc', + '/proc', + '--die-with-parent', + '--new-session', + ]; + for (const path of plan.hidden) args.push('--tmpfs', path); + args.push('--tmpfs', '/tmp'); + if (plan.resolvConf !== undefined) + args.push( + ...(network + ? ['--ro-bind-data', '9', plan.resolvConf] + : ['--ro-bind-try', plan.resolvConf, plan.resolvConf]), + ); + for (const path of plan.tools ?? []) args.push('--ro-bind-try', path, path); + const writable = new Set(mode === 'workspace-write' ? plan.writable : []); + for (const path of plan.readable) if (!writable.has(path)) args.push('--ro-bind', path, path); + for (const path of writable) args.push('--bind', path, path); + if (mode === 'workspace-write' && !writable.has(plan.home)) + args.push('--bind', plan.home, plan.home); + else if (!writable.has(plan.home)) args.push('--ro-bind', plan.home, plan.home); + args.push( + '--setenv', + 'HOME', + plan.home, + '--setenv', + 'XDG_CACHE_HOME', + `${plan.home}/.cache`, + '--setenv', + 'XDG_CONFIG_HOME', + `${plan.home}/.config`, + '--setenv', + 'XDG_DATA_HOME', + `${plan.home}/.local/share`, + '--setenv', + 'XDG_STATE_HOME', + `${plan.home}/.local/state`, + '--setenv', + 'TMPDIR', + '/tmp', + ); + return args; +} + +export function confinedArgv( + plan: ExecutionPlan, + mode: 'read-only' | 'workspace-write', + argv: readonly string[], + network: boolean, +): string[] { + const inner = [ + 'bwrap', + ...bwrapArgs(plan, mode, network), + '--', + '/bin/sh', + '-c', + ENV_SCRUB, + 'bh-scrub', + SECRET_ENV_PATTERN, + ...argv, + ]; + return network ? ['/bin/sh', '-c', NETWORK_RUNNER, 'bh-confine', NETWORK_RULES, ...inner] : inner; +} + +type Spawn = typeof spawnSync; + +function runs(spawn: Spawn, argv: string[]): { ok: boolean; output: string } { + const result = spawn(argv[0]!, argv.slice(1), { + encoding: 'utf8', + timeout: 10_000, + stdio: ['ignore', 'pipe', 'pipe'], + }); + return { + ok: result.status === 0 && result.error === undefined, + output: `${result.stdout ?? ''}`, + }; +} + +export function probeConfinement( + spawn: Spawn = spawnSync, + platform: NodeJS.Platform = process.platform, +): ConfinementStatus { + if (platform !== 'linux') + return { enforcement: 'unavailable', filesystem: false, network: false, missing: ['linux'] }; + const plan: ExecutionPlan = { + readable: [], + writable: [], + hidden: [], + home: '/tmp', + }; + const filesystem = runs(spawn, confinedArgv(plan, 'read-only', ['/bin/true'], false)).ok; + if (!filesystem) + return { + enforcement: 'unavailable', + filesystem: false, + network: false, + missing: ['bwrap'], + }; + const tools = ['unshare', 'slirp4netns', 'nft'].filter( + (tool) => !runs(spawn, ['/bin/sh', '-c', `command -v ${tool}`]).ok, + ); + const network = + tools.length === 0 && + runs( + spawn, + confinedArgv( + plan, + 'read-only', + ['/bin/sh', '-c', 'cat /proc/net/route | tail -n +2 | grep -q . && echo routed'], + true, + ), + ).output.includes('routed'); + return { + enforcement: network ? 'full' : 'partial', + filesystem: true, + network, + missing: network ? [] : tools.length ? tools : ['network-namespace'], + }; +} diff --git a/packages/core/src/execution/member-confinement.ts b/packages/core/src/execution/member-confinement.ts new file mode 100644 index 0000000000..746c104e39 --- /dev/null +++ b/packages/core/src/execution/member-confinement.ts @@ -0,0 +1,218 @@ +import { existsSync, lstatSync, mkdirSync, realpathSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { dirname, join } from 'node:path'; + +import type { Context } from '@deepseek-ai/cordis'; +import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'; + +import type { BotHarnessCore } from '../plugin.js'; +import { within } from '../workspaces/space-paths.js'; +import { isMemberBot } from '../workspaces/grant-execution.js'; +import { sessionRoots } from '../workspaces/grant-native-tools.js'; +import { + confinedArgv, + DENIAL_SIGNATURES, + probeConfinement, + RUNNER_FAILURE_SIGNATURE, + type ConfinementStatus, + type ExecutionPlan, +} from './linux-confinement.js'; + +export type ConfinementCore = Pick< + BotHarnessCore, + 'ownership' | 'runtime' | 'grants' | 'registry' +> & { + team?: Pick; +}; + +type Mode = 'read-only' | 'workspace-write'; + +interface Policy { + mode: string; + workspaceRoot: string; + additionalWritableRoots?: readonly string[]; + sessionId?: string; +} + +interface Confined { + argv: string[]; + enforcement: 'full' | 'partial'; + denialSignatures: readonly string[]; + runnerFailureRules: readonly { fatalSignatures: readonly string[] }[]; +} + +export type PlanResult = + | { kind: 'unconfined' } + | { kind: 'refused'; reason: string } + | { kind: 'plan'; plan: ExecutionPlan; botSlug: string }; + +const SYSTEM_HIDDEN = ['/home', '/root', '/run', '/mnt', '/media', '/srv']; + +function real(path: string): string { + try { + return realpathSync(path); + } catch { + return path; + } +} + +function rootOwner(core: ConfinementCore, sessionId: string) { + let owner = core.ownership.resolve(sessionId); + const seen = new Set(); + while (owner?.parentSessionId !== undefined) { + if (seen.has(owner.sessionId)) return undefined; + seen.add(owner.sessionId); + const parent = core.ownership.resolve(owner.parentSessionId); + if (parent === undefined || parent.botSlug !== owner.botSlug) return undefined; + owner = parent; + } + return owner; +} + +function outermost(paths: readonly string[]): string[] { + const unique = [...new Set(paths)].sort((a, b) => a.length - b.length); + return unique.filter((path, index) => !unique.slice(0, index).some((root) => within(root, path))); +} + +function resolverTarget(): string | undefined { + try { + return lstatSync('/etc/resolv.conf').isSymbolicLink() + ? realpathSync('/etc/resolv.conf') + : '/etc/resolv.conf'; + } catch { + return undefined; + } +} + +export function memberExecutionPlan( + core: ConfinementCore, + dshHome: string, + sessionId: string | undefined, +): PlanResult { + if (sessionId === undefined) + return core.team?.enabled() === true + ? { kind: 'refused', reason: 'the command has no calling Session' } + : { kind: 'unconfined' }; + const owner = core.ownership.resolve(sessionId); + if (owner === undefined) return { kind: 'unconfined' }; + const root = rootOwner(core, sessionId); + if (root === undefined) return { kind: 'refused', reason: 'the Session owner is unresolved' }; + if (core.registry.get(root.botSlug) === undefined) + return { kind: 'refused', reason: 'the PersonaBot is unavailable' }; + if (!isMemberBot(core, root.botSlug)) return { kind: 'unconfined' }; + const memory = core.registry.memoryDirFor(root.botSlug); + if (memory === undefined) return { kind: 'refused', reason: 'the PersonaBot Memory is missing' }; + const readable = sessionRoots(core, sessionId, 'read', undefined).map(real); + const writable = sessionRoots(core, sessionId, 'write', undefined).map(real); + if (readable.length === 0) + return { kind: 'refused', reason: 'the Session has no authorized folder' }; + const home = join(dirname(memory), 'home'); + mkdirSync(home, { recursive: true, mode: 0o700 }); + const allowed = [...readable, home]; + const others = [ + ...core.registry.list().flatMap((record) => { + const dir = core.registry.memoryDirFor(record.slug); + return dir === undefined ? [] : [real(dir)]; + }), + ...core.grants.availableWorkspaces().map((workspace) => real(workspace.path)), + ].filter((path) => !allowed.some((root) => within(root, path))); + const hidden = outermost( + [real(dshHome), real(homedir()), ...SYSTEM_HIDDEN, ...others] + .filter((path) => existsSync(path)) + .filter((path) => !allowed.includes(path)), + ); + const sensitive = [real(dshHome), real(homedir()), ...others]; + const tools = [...(process.env['PATH'] ?? '').split(':'), dirname(dirname(process.execPath))] + .filter((path) => path.startsWith('/') && existsSync(path)) + .map(real) + .filter( + (path) => + hidden.some((root) => within(root, path)) && + !sensitive.some((secret) => within(path, secret)) && + ![real(dshHome), ...others].some((secret) => within(secret, path)), + ); + return { + kind: 'plan', + botSlug: root.botSlug, + plan: { + readable, + writable, + hidden, + tools: [...new Set(tools)], + home: real(home), + resolvConf: resolverTarget(), + }, + }; +} + +export function confineMemberCommand( + plan: ExecutionPlan, + argv: readonly string[], + policy: Policy, + status: ConfinementStatus, +): Confined { + const mode: Mode = policy.mode === 'workspace-write' ? 'workspace-write' : 'read-only'; + const root = real(policy.workspaceRoot); + if (!plan.readable.some((allowed) => within(allowed, root))) + throw new SandboxUnavailableError(mode, 'the working folder is outside this Session'); + return { + argv: confinedArgv(plan, mode, argv, status.network), + enforcement: status.network ? 'full' : 'partial', + denialSignatures: DENIAL_SIGNATURES, + runnerFailureRules: [{ fatalSignatures: ['bwrap: ', RUNNER_FAILURE_SIGNATURE] }], + }; +} + +export class MemberConfinement { + #status: ConfinementStatus | undefined; + + constructor( + private readonly core: ConfinementCore, + private readonly dshHome: string, + private readonly probe: () => ConfinementStatus = probeConfinement, + ) {} + + status(): ConfinementStatus { + this.#status ??= this.probe(); + return this.#status; + } + + async confine( + original: (argv: readonly string[], policy: Policy, signal?: AbortSignal) => Promise, + argv: readonly string[], + policy: Policy, + signal?: AbortSignal, + ): Promise { + const result = memberExecutionPlan(this.core, this.dshHome, policy.sessionId); + const mode: Mode = policy.mode === 'workspace-write' ? 'workspace-write' : 'read-only'; + if (result.kind === 'refused') throw new SandboxUnavailableError(mode, result.reason); + const confined = await original(argv, policy, signal); + if (result.kind === 'unconfined') return confined; + const status = this.status(); + if (!status.filesystem) return { ...confined, enforcement: 'partial' }; + return confineMemberCommand(result.plan, argv, policy, status); + } +} + +export function installMemberConfinement( + ctx: Context, + confinement: MemberConfinement, + platform: NodeJS.Platform = process.platform, +): void { + if (platform !== 'linux') return; + ctx.inject(['sandbox'], (child) => { + const sandbox = child.get('sandbox') as unknown as { + confine(argv: readonly string[], policy: Policy, signal?: AbortSignal): Promise; + }; + const original = sandbox.confine; + sandbox.confine = function (this: unknown, argv, policy, signal) { + return confinement.confine((...args) => original.apply(this, args), argv, policy, signal); + }; + child.effect( + () => () => { + sandbox.confine = original; + }, + 'botharness: member Bot execution confinement', + ); + }); +} diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index c837e9da75..276a270038 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -349,6 +349,7 @@ import { import { createIdleCompactionSettings } from './runtime/idle-compaction-settings.js'; import { ChannelUserQuestions, registerChannelUserQuestions } from './channels/user-questions.js'; import { mountPrivateInputs } from './credentials/mount.js'; +import { installMemberConfinement, MemberConfinement } from './execution/member-confinement.js'; import type { PrivateInputs } from './credentials/private-inputs.js'; import { createAssignmentAccessStore, @@ -2215,6 +2216,11 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { secretMcpStore, diagnosticEvents, ); + const memberConfinement = new MemberConfinement(core, dshHome); + installMemberConfinement(ctx, memberConfinement); + core.team.bindConfinement(() => + process.platform === 'linux' ? memberConfinement.status() : undefined, + ); const takeovers = createCoreTakeoverHandoffs(ctx, core, diagnosticEvents); mountTakeoverTools(ctx, core, takeovers); ctx.effect(() => () => core.externalMessaging.close(), 'botharness: external messaging'); diff --git a/packages/core/src/team/http.ts b/packages/core/src/team/http.ts index 719add692b..6871f7ac59 100644 --- a/packages/core/src/team/http.ts +++ b/packages/core/src/team/http.ts @@ -298,7 +298,7 @@ export function createTeamHttp(options: TeamHttpOptions): TeamHttp { `${MEMBER_COOKIE}=${result.token}; Path=${TEAM_PATH}/; HttpOnly; SameSite=Strict${secure ? '; Secure' : ''}`, ); return json(response, 200, { - isolation: 'trial', + isolation: options.team.isolation(), humanId: result.member.humanId, displayName: result.member.displayName, mustChangePassword: result.member.mustChangePassword, diff --git a/packages/core/src/team/service.ts b/packages/core/src/team/service.ts index 97983e6a87..2af7db8455 100644 --- a/packages/core/src/team/service.ts +++ b/packages/core/src/team/service.ts @@ -1,4 +1,5 @@ import { TeamPrivateContent } from './private-content.js'; +import type { ConfinementStatus } from '../execution/linux-confinement.js'; import { accountSpaceFiles, prepareSpaceTransfer } from '../workspaces/space-lifecycle.js'; import type { WorkspaceSpaces } from '../workspaces/spaces.js'; import { TeamApprovals } from './approvals.js'; @@ -54,6 +55,7 @@ const memberSchema = z.object({ export type TeamMember = z.infer; export interface TeamModeView { isolation: 'trial' | 'enforced'; + confinement?: ConfinementStatus; enabled: boolean; privateAccessNotice?: true; activeMembers: number; @@ -204,6 +206,7 @@ export class TeamService { private peerFactory: ((principal: MemberPrincipal) => PeerScope) | undefined; private invalidate: () => void = () => {}; private urls: () => string[] = () => []; + private confinement: () => ConfinementStatus | undefined = () => undefined; private readonly ensureTob: ((human: HumanContext) => Promise) | undefined; private readonly now: () => number; private readonly log: (phase: string, facts: Record) => void; @@ -285,6 +288,18 @@ export class TeamService { }; } + bindConfinement(status: () => ConfinementStatus | undefined): void { + this.confinement = status; + } + + enabled(): boolean { + return this.settings().enabled; + } + + isolation(): 'trial' | 'enforced' { + return this.confinement()?.enforcement === 'full' ? 'enforced' : 'trial'; + } + private settings() { return z .object({ enabled: z.coerce.boolean(), insecure_http_allowed: z.coerce.boolean() }) @@ -374,8 +389,10 @@ export class TeamService { const settings = this.settings(); const member = this.member(human.humanId); if (!member) throw new TeamError('credentials-invalid'); + const confinement = this.confinement(); return { - isolation: 'trial', + isolation: confinement?.enforcement === 'full' ? 'enforced' : 'trial', + ...(confinement === undefined || !this.isOwner(human) ? {} : { confinement }), enabled: settings.enabled, ...(settings.enabled ? { privateAccessNotice: true as const } : {}), activeMembers: this.db.read((db) => @@ -539,7 +556,7 @@ export class TeamService { ); this.spaceProvider?.().ensureAccount(humanId); this.invalidate(); - return { member: this.member(humanId)!, initialPassword, isolation: 'trial' }; + return { member: this.member(humanId)!, initialPassword, isolation: this.isolation() }; } private byUsername(username: string): TeamMember | undefined { diff --git a/packages/core/src/workspaces/grant-native-tools.ts b/packages/core/src/workspaces/grant-native-tools.ts index 7a0bb48546..dd5d323a8b 100644 --- a/packages/core/src/workspaces/grant-native-tools.ts +++ b/packages/core/src/workspaces/grant-native-tools.ts @@ -74,7 +74,16 @@ function canonicalRoot(root: string): string | undefined { } export function currentRoots(core: GrantCore, session: Session, kind: AccessKind): string[] { - let owner = core.ownership.resolve(session.id); + return sessionRoots(core, session.id, kind, session.header.cwd); +} + +export function sessionRoots( + core: GrantCore, + sessionId: string, + kind: AccessKind, + cwd: string | undefined, +): string[] { + let owner = core.ownership.resolve(sessionId); if (owner === undefined) return []; const seen = new Set(); while (owner.parentSessionId !== undefined) { @@ -104,7 +113,7 @@ export function currentRoots(core: GrantCore, session: Session, kind: AccessKind } if (owner.rootRole !== 'assignment') return []; const permission = core.runtime.getAssignment(owner.botSlug, owner.sessionId)?.permission; - if (permission === undefined || permission.primaryCwd !== session.header.cwd) return []; + if (permission === undefined || (cwd !== undefined && permission.primaryCwd !== cwd)) return []; try { const grant = core.grants.requireActive(owner.botSlug, permission.grantId); return (kind === 'read' || grant.orchestratorWrite === true) && diff --git a/packages/core/test/member-confinement.test.ts b/packages/core/test/member-confinement.test.ts new file mode 100644 index 0000000000..de6408099a --- /dev/null +++ b/packages/core/test/member-confinement.test.ts @@ -0,0 +1,384 @@ +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:net'; +import { join } from 'node:path'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { + bwrapArgs, + probeConfinement, + secretEnvNames, + type ConfinementStatus, +} from '../src/execution/linux-confinement.js'; +import { + confineMemberCommand, + MemberConfinement, + memberExecutionPlan, + type ConfinementCore, +} from '../src/execution/member-confinement.js'; + +interface Owner { + sessionId: string; + botSlug: string; + rootRole: 'orchestrator' | 'assignment'; + parentSessionId?: string; +} + +function fixture(root: string, teamEnabled = true) { + const dsh = join(root, 'dsh'); + const write = (path: string, text: string) => { + mkdirSync(join(path, '..'), { recursive: true }); + writeFileSync(path, text); + }; + const memory = { + ada: join(dsh, 'spaces', 'alice', 'bots', 'ada', 'memory'), + ben: join(dsh, 'spaces', 'bob', 'bots', 'ben', 'memory'), + owl: join(dsh, 'spaces', 'owner', 'bots', 'owl', 'memory'), + }; + write(join(memory.ada, 'note.md'), 'ada memory'); + write(join(memory.ben, 'secret.md'), 'ben memory'); + write(join(memory.owl, 'note.md'), 'owner memory'); + write(join(dsh, 'spaces', 'bob', 'private.md'), 'bob account'); + write(join(dsh, 'shared', 'finance', 'ledger.md'), 'finance'); + write(join(dsh, '.credentials.yaml'), 'token: secret'); + write(join(dsh, 'botharness', 'botharness.db'), 'database'); + const work = { + alpha: join(root, 'work', 'alpha'), + beta: join(root, 'work', 'beta'), + gamma: join(root, 'work', 'gamma'), + }; + write(join(work.alpha, 'readme.md'), 'alpha'); + write(join(work.beta, 'readme.md'), 'beta'); + write(join(work.gamma, 'readme.md'), 'gamma'); + const bots = [ + { slug: 'ada', ownerHumanId: 'alice' }, + { slug: 'ben', ownerHumanId: 'bob' }, + { slug: 'owl', ownerHumanId: 'owner' }, + ]; + const grants: Record< + string, + { id: string; workspaceId: string; workspacePath: string; orchestratorWrite: boolean }[] + > = { + ada: [ + { id: 'g-alpha', workspaceId: 'w-alpha', workspacePath: work.alpha, orchestratorWrite: true }, + { id: 'g-beta', workspaceId: 'w-beta', workspacePath: work.beta, orchestratorWrite: false }, + ], + ben: [ + { id: 'g-gamma', workspaceId: 'w-gamma', workspacePath: work.gamma, orchestratorWrite: true }, + ], + owl: [], + }; + const owners = new Map([ + ['ada-chat', { sessionId: 'ada-chat', botSlug: 'ada', rootRole: 'orchestrator' }], + [ + 'ada-sub', + { + sessionId: 'ada-sub', + botSlug: 'ada', + rootRole: 'orchestrator', + parentSessionId: 'ada-chat', + }, + ], + ['ada-task', { sessionId: 'ada-task', botSlug: 'ada', rootRole: 'assignment' }], + ['owl-chat', { sessionId: 'owl-chat', botSlug: 'owl', rootRole: 'orchestrator' }], + ['ghost-chat', { sessionId: 'ghost-chat', botSlug: 'ghost', rootRole: 'orchestrator' }], + ]); + const core = { + ownership: { resolve: (id: string) => owners.get(id) }, + registry: { + get: (slug: string) => bots.find((bot) => bot.slug === slug), + list: () => bots, + memoryDirFor: (slug: string) => memory[slug as keyof typeof memory], + }, + grants: { + list: (slug: string) => grants[slug] ?? [], + requireActive: (slug: string, id: string) => { + const grant = (grants[slug] ?? []).find((entry) => entry.id === id); + if (grant === undefined) throw new Error('grant missing'); + return grant; + }, + availableWorkspaces: () => + Object.values(grants) + .flat() + .map((grant) => ({ id: grant.workspaceId, path: grant.workspacePath, title: grant.id })), + }, + runtime: { + getAssignment: (slug: string, sessionId: string) => + slug === 'ada' && sessionId === 'ada-task' + ? { + permission: { + grantId: 'g-alpha', + workspaceId: 'w-alpha', + primaryCwd: work.alpha, + mode: 'workspace-write', + }, + } + : undefined, + }, + team: { ownerContext: () => ({ humanId: 'owner' }), enabled: () => teamEnabled }, + } as unknown as ConfinementCore; + return { core, dsh, memory, work }; +} + +const original = (argv: readonly string[]) => + Promise.resolve({ + argv: ['bwrap', '--ro-bind', '/', '/', '--', ...argv], + enforcement: 'full' as const, + denialSignatures: ['read-only file system'], + runnerFailureRules: [{ fatalSignatures: ['bwrap: '] }], + }); + +describe('member Bot execution plan', () => { + let root: string; + beforeAll(() => { + root = mkdtempSync('/var/tmp/bh-plan-'); + }); + afterAll(() => rmSync(root, { recursive: true, force: true })); + + it('refuses a command without a calling Session while Team mode is on', () => { + expect(memberExecutionPlan(fixture(root).core, join(root, 'dsh'), undefined)).toEqual({ + kind: 'refused', + reason: 'the command has no calling Session', + }); + expect(memberExecutionPlan(fixture(root, false).core, join(root, 'dsh'), undefined)).toEqual({ + kind: 'unconfined', + }); + }); + + it('refuses an owned Session whose Bot is gone instead of widening access', () => { + const f = fixture(root); + expect(memberExecutionPlan(f.core, f.dsh, 'ghost-chat').kind).toBe('refused'); + }); + + it('leaves the Owner Bot and non-Bot Sessions on the DSH profile', async () => { + const f = fixture(root); + expect(memberExecutionPlan(f.core, f.dsh, 'owl-chat')).toEqual({ kind: 'unconfined' }); + expect(memberExecutionPlan(f.core, f.dsh, 'native-session')).toEqual({ kind: 'unconfined' }); + const confinement = new MemberConfinement(f.core, f.dsh, () => { + throw new Error('probe must not run for an unconfined Session'); + }); + const result = await confinement.confine(original, ['true'], { + mode: 'workspace-write', + workspaceRoot: f.memory.owl, + sessionId: 'owl-chat', + }); + expect(result.argv).toEqual(['bwrap', '--ro-bind', '/', '/', '--', 'true']); + }); + + it('binds an Orchestrator Memory and Grants and hides the rest of the Host', () => { + const f = fixture(root); + const result = memberExecutionPlan(f.core, f.dsh, 'ada-sub'); + if (result.kind !== 'plan') throw new Error(result.kind); + expect(result.plan.readable).toEqual([f.memory.ada, f.work.alpha, f.work.beta]); + expect(result.plan.writable).toEqual([f.memory.ada, f.work.alpha]); + expect(result.plan.hidden).toEqual(expect.arrayContaining([f.dsh, f.work.gamma])); + expect(result.plan.hidden).not.toContain(f.memory.ben); + expect(result.plan.home).toBe(join(f.dsh, 'spaces', 'alice', 'bots', 'ada', 'home')); + }); + + it('limits an Assignment to its primary Grant', () => { + const f = fixture(root); + const result = memberExecutionPlan(f.core, f.dsh, 'ada-task'); + if (result.kind !== 'plan') throw new Error(result.kind); + expect(result.plan.readable).toEqual([f.work.alpha]); + expect(result.plan.hidden).toEqual(expect.arrayContaining([f.work.beta, f.work.gamma])); + }); + + it('refuses a working folder outside the Session roots', () => { + const f = fixture(root); + const result = memberExecutionPlan(f.core, f.dsh, 'ada-task'); + if (result.kind !== 'plan') throw new Error(result.kind); + expect(() => + confineMemberCommand( + result.plan, + ['true'], + { mode: 'workspace-write', workspaceRoot: f.work.beta }, + { enforcement: 'full', filesystem: true, network: true, missing: [] }, + ), + ).toThrow(/outside this Session/u); + }); + + it('refuses through the sandbox seam when the Session is missing', async () => { + const f = fixture(root); + const confinement = new MemberConfinement(f.core, f.dsh, () => ({ + enforcement: 'full', + filesystem: true, + network: true, + missing: [], + })); + await expect( + confinement.confine(original, ['true'], { mode: 'workspace-write', workspaceRoot: f.dsh }), + ).rejects.toMatchObject({ code: 'SANDBOX_UNAVAILABLE' }); + }); + + it('hides paths before binding allowed roots and binds a private resolver with the network', () => { + const args = bwrapArgs( + { + readable: ['/srv/a'], + writable: ['/srv/a'], + hidden: ['/srv'], + home: '/srv/a/home', + resolvConf: '/etc/resolv.conf', + }, + 'workspace-write', + true, + ); + expect(args.indexOf('/srv')).toBeLessThan(args.indexOf('/srv/a')); + expect(args.join(' ')).toContain('--ro-bind-data 9 /etc/resolv.conf'); + }); + + it('names secret environment variables for removal', () => { + expect( + secretEnvNames({ + OPENCODE_GO_API_KEY: '1', + GITHUB_TOKEN: '1', + DSH_HOME: '1', + DEEPSEEKBOT_HOST: '1', + PATH: '1', + KEYBOARD: '1', + GIT_CONFIG_KEY_0: '1', + AWS_ACCESS_KEY_ID: '1', + }).sort(), + ).toEqual([ + 'AWS_ACCESS_KEY_ID', + 'DEEPSEEKBOT_HOST', + 'DSH_HOME', + 'GITHUB_TOKEN', + 'OPENCODE_GO_API_KEY', + ]); + }); +}); + +const status: ConfinementStatus = + process.platform === 'linux' + ? probeConfinement() + : { enforcement: 'unavailable', filesystem: false, network: false, missing: ['linux'] }; + +describe.skipIf(!status.filesystem)('member Bot Shell under bwrap', () => { + let root: string; + let server: Server; + let port = 0; + beforeAll(async () => { + root = mkdtempSync('/var/tmp/bh-confine-'); + server = createServer((socket) => socket.end('host api\n')); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + port = (server.address() as { port: number }).port; + }); + afterAll(async () => { + await new Promise((resolve) => server.close(resolve)); + rmSync(root, { recursive: true, force: true }); + }); + + const run = (sessionId: string, workspaceRoot: string, script: string) => { + const f = fixture(root); + const plan = memberExecutionPlan(f.core, f.dsh, sessionId); + if (plan.kind !== 'plan') throw new Error(plan.kind); + const confined = confineMemberCommand( + plan.plan, + ['/bin/sh', '-c', script], + { mode: 'workspace-write', workspaceRoot, sessionId }, + status, + ); + const result = spawnSync(confined.argv[0]!, confined.argv.slice(1), { + encoding: 'utf8', + timeout: 30_000, + env: { ...process.env, OPENCODE_GO_API_KEY: 'sk-test', DSH_HOME: f.dsh }, + }); + return { ...result, f, enforcement: confined.enforcement }; + }; + + it("keeps Alice's Bot out of Bob's spaces, shared roles and the Host data", () => { + const f = fixture(root); + const targets = [ + join(f.memory.ben, 'secret.md'), + join(f.dsh, 'spaces', 'bob', 'private.md'), + join(f.dsh, 'shared', 'finance', 'ledger.md'), + join(f.dsh, '.credentials.yaml'), + join(f.dsh, 'botharness', 'botharness.db'), + join(f.work.gamma, 'readme.md'), + ]; + const result = run( + 'ada-chat', + f.memory.ada, + targets.map((path) => `cat '${path}' 2>/dev/null && echo LEAK`).join('; ') + + `; cat '${join(f.memory.ada, 'note.md')}'; cat '${join(f.work.beta, 'readme.md')}'`, + ); + expect(result.stdout).not.toContain('LEAK'); + expect(result.stdout).toContain('ada memory'); + expect(result.stdout).toContain('beta'); + }); + + it('lets the Bot write its Memory and writable Grant but not a read-only Grant', () => { + const f = fixture(root); + const result = run( + 'ada-chat', + f.memory.ada, + `echo ok > '${join(f.memory.ada, 'new.md')}' && echo memory-ok; echo ok > '${join(f.work.alpha, 'new.md')}' && echo grant-ok; echo no > '${join(f.work.beta, 'new.md')}' || echo beta-denied; echo $HOME; touch "$HOME/x" && echo home-ok`, + ); + expect(result.stdout).toContain('memory-ok'); + expect(result.stdout).toContain('grant-ok'); + expect(result.stdout).toContain('beta-denied'); + expect(result.stdout).toContain('home-ok'); + expect(result.stdout).toContain(join('bots', 'ada', 'home')); + }); + + it('still runs ordinary Git work inside the Bot roots', () => { + const f = fixture(root); + const result = run( + 'ada-chat', + f.work.alpha, + `cd '${f.work.alpha}' && git init -q && git add readme.md && git -c user.name=ada -c user.email=ada@example.invalid commit -qm init && git log --format=%s`, + ); + expect(result.stderr).toBe(''); + expect(result.stdout.trim()).toBe('init'); + }); + + it("keeps an Assignment out of the same Bot's other Grants", () => { + const f = fixture(root); + const result = run( + 'ada-task', + f.work.alpha, + `cat '${join(f.work.alpha, 'readme.md')}'; cat '${join(f.work.beta, 'readme.md')}' 2>/dev/null && echo LEAK; cat '${join(f.memory.ada, 'note.md')}' 2>/dev/null && echo LEAK`, + ); + expect(result.stdout).toContain('alpha'); + expect(result.stdout).not.toContain('LEAK'); + }); + + it('removes secrets from the command environment', () => { + const f = fixture(root); + const result = run('ada-chat', f.memory.ada, 'env'); + expect(result.stdout).toContain('PATH='); + expect(result.stdout).not.toContain('OPENCODE_GO_API_KEY'); + expect(result.stdout).not.toContain('DSH_HOME'); + }); + + it.skipIf(!status.network)('refuses loopback ports such as the Host API', () => { + const f = fixture(root); + const result = run( + 'ada-chat', + f.memory.ada, + `'${process.execPath}' -e "const s=require('net').connect(${port},'127.0.0.1');s.on('data',d=>{process.stdout.write('LEAK '+d);process.exit(0)});s.on('error',e=>{console.log('refused',e.code);process.exit(0)});setTimeout(()=>{console.log('timeout');process.exit(0)},5000)"`, + ); + expect(result.enforcement).toBe('full'); + expect(result.stdout).toContain('refused'); + expect(result.stdout).not.toContain('LEAK'); + }); + + it.skipIf(!status.network)('refuses the Host gateway, link-local and tailnet addresses', () => { + const f = fixture(root); + const probe = (host: string, target: number) => + `'${process.execPath}' -e "const s=require('net').connect(${target},'${host}');s.on('connect',()=>{console.log('LEAK ${host}');process.exit(0)});s.on('error',e=>{console.log('refused ${host}');process.exit(0)});setTimeout(()=>{console.log('timeout ${host}');process.exit(0)},5000)"`; + const result = run( + 'ada-chat', + f.memory.ada, + [ + probe('10.0.2.2', port), + probe('169.254.169.254', 80), + probe('100.100.100.100', 80), + probe('192.168.1.1', 80), + ].join('; '), + ); + expect(result.stdout).not.toContain('LEAK'); + expect(result.stdout.match(/refused/gu)).toHaveLength(4); + }); +}); diff --git a/packages/core/test/team-approvals.test.ts b/packages/core/test/team-approvals.test.ts index b4de6cda5e..4313e18d4e 100644 --- a/packages/core/test/team-approvals.test.ts +++ b/packages/core/test/team-approvals.test.ts @@ -1,4 +1,5 @@ import { questionAnswerReceipts } from '../src/channels/question-answer-receipts.js'; +import type { ConfinementStatus } from '../src/execution/linux-confinement.js'; import { createServer } from 'node:http'; import { createRequire } from 'node:module'; import { pathToFileURL } from 'node:url'; @@ -1681,6 +1682,31 @@ describe('M5 approval projections and decisions', () => { viewer: { kind: 'owner' }, }); }); + + it('reports enforced isolation only while both file and network confinement are active', async () => { + const f = fixture(); + let status: ConfinementStatus | undefined = { + enforcement: 'full', + filesystem: true, + network: true, + missing: [], + }; + f.team.bindConfinement(() => status); + expect(await f.invoke(owner, 'teamMode', {})).toMatchObject({ + isolation: 'enforced', + confinement: { enforcement: 'full' }, + }); + const member = (await f.invoke(bob, 'teamMode', {})) as Record; + expect(member).toMatchObject({ isolation: 'enforced' }); + expect(member).not.toHaveProperty('confinement'); + status = { enforcement: 'partial', filesystem: true, network: false, missing: ['slirp4netns'] }; + expect(await f.invoke(owner, 'teamMode', {})).toMatchObject({ + isolation: 'trial', + confinement: { missing: ['slirp4netns'] }, + }); + status = undefined; + expect(await f.invoke(bob, 'teamMode', {})).toMatchObject({ isolation: 'trial' }); + }); }); describe('M5 configuration and execution fences', () => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e33f848b3b..fda391450c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -973,6 +973,9 @@ importers: '@deepseek-ai/dsh-mcp-client': specifier: 0.2.2-rc.1 version: 0.2.2-rc.1(f493aa6df3539275aa669c2bcea3e03a) + '@deepseek-ai/dsh-sandbox': + specifier: 0.2.2-rc.1 + version: 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) '@deepseek-ai/dsh-sandbox-policy': specifier: 0.2.2-rc.1 version: 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-agent@0.2.2-rc.1(d9740b81bf2b48fd86b0c38a41e906a0))(@deepseek-ai/dsh-sandbox@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session-projection@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) From 393082979cce63e7fa4b33ce2bf340e0e1a1515f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:56:48 +0000 Subject: [PATCH 2/3] fix(team): give each public Bot's hidden Memory space a distinct name The hidden space name started with a NUL byte. SQLite NOCASE comparison stops at NUL, so every public Bot's space name compared equal and the second publication on a Host failed the shared-name unique index. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lpx6qkvJqKRjdg67NfFT7X --- changes/public-bot-memory-space-names.md | 11 +++++++++++ .../core/src/workspaces/bot-memory-placement.ts | 2 +- .../core/test/team-public-bot-memory.test.ts | 17 +++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 changes/public-bot-memory-space-names.md diff --git a/changes/public-bot-memory-space-names.md b/changes/public-bot-memory-space-names.md new file mode 100644 index 0000000000..b5cf408907 --- /dev/null +++ b/changes/public-bot-memory-space-names.md @@ -0,0 +1,11 @@ +--- +section: Fixed +--- + +## en + +- A Host can make more than one Bot public. Publishing a second Bot used to fail with an internal error because the hidden Memory folders of public Bots shared one name ([#4150](https://github.com/BotHarness/DeepSeekBot/issues/4150)). + +## zh + +- 同一个 Host 现在可以公开多个 Bot。之前公开第二个 Bot 会报内部错误,原因是公开 Bot 的隐藏 Memory 文件夹用了同一个名字([#4150](https://github.com/BotHarness/DeepSeekBot/issues/4150))。 diff --git a/packages/core/src/workspaces/bot-memory-placement.ts b/packages/core/src/workspaces/bot-memory-placement.ts index a106bd711f..3f754cf1e9 100644 --- a/packages/core/src/workspaces/bot-memory-placement.ts +++ b/packages/core/src/workspaces/bot-memory-placement.ts @@ -79,7 +79,7 @@ export class BotMemoryPlacement { db.prepare(`INSERT INTO workspace_spaces VALUES (?,'shared',?,NULL,?) ON CONFLICT(space_id) DO UPDATE SET audience_json=excluded.audience_json`).run( spaceId, - '\u0000' + spaceId, + '\u0001' + spaceId, JSON.stringify(visibility.audience), ); else { diff --git a/packages/core/test/team-public-bot-memory.test.ts b/packages/core/test/team-public-bot-memory.test.ts index 7eed79fc4e..403a5285a1 100644 --- a/packages/core/test/team-public-bot-memory.test.ts +++ b/packages/core/test/team-public-bot-memory.test.ts @@ -221,6 +221,23 @@ describe('M7 public Bot Memory placement', () => { if (turn.admitted) await turn.settled; } }); + it('publishes more than one Bot without colliding hidden backing-space names', () => { + const f = fixture(); + f.core.team.bots.setVisibility(owner, 'helper', everyone); + expect(f.core.team.bots.setVisibility(owner, 'other', everyone).applied).toBe(true); + const names = f.db.read((sql) => + sql + .prepare( + "SELECT space_id, name FROM workspace_spaces WHERE kind = 'shared' ORDER BY space_id", + ) + .all(), + ); + expect(names.map((row) => row['space_id'])).toEqual([ + botMemorySpaceId('helper'), + botMemorySpaceId('other'), + ]); + expect(new Set(names.map((row) => row['name'])).size).toBe(2); + }); it('does no repository or metadata writes for an already-correct startup placement', () => { const f = fixture(); f.core.team.bots.setVisibility(owner, 'helper', everyone); From ed3c34b32d24cf733373f24f26392d595d4e19aa Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:06:10 +0000 Subject: [PATCH 3/3] test(team): add the M15 real-model Team mode security suite scripts/e2e-team-security.mjs sets up roles with Role Policy, members, public and private Bots, folders and Channels on an isolated Host and drives real model turns that try to leak restricted figures, reach other members' folders, the Host data directory and the Host API through file tools, Shell and grants, and cross private Bots, Channels, DMs, offboarding and model allowlists. Hard boundaries are asserted on Host state and tool results. AGENTS.md requires its report for every PR that changes Team mode permissions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lpx6qkvJqKRjdg67NfFT7X --- .agents/skills/verify-deepseekbot/SKILL.md | 12 + .../verify-deepseekbot/features/README.md | 2 +- .../verify-deepseekbot/features/team-mode.md | 2 + AGENTS.md | 2 + changes/4197-team-security-suite.md | 11 + docs/agents/development-scripts.md | 13 + scripts/e2e-team-security.mjs | 905 ++++++++++++++++++ scripts/verification-inventory.json | 20 +- 8 files changed, 964 insertions(+), 3 deletions(-) create mode 100644 changes/4197-team-security-suite.md create mode 100644 scripts/e2e-team-security.mjs diff --git a/.agents/skills/verify-deepseekbot/SKILL.md b/.agents/skills/verify-deepseekbot/SKILL.md index c131538096..c5b00f9eec 100644 --- a/.agents/skills/verify-deepseekbot/SKILL.md +++ b/.agents/skills/verify-deepseekbot/SKILL.md @@ -81,6 +81,18 @@ The Windows runner uses [Android device QA](../../../docs/agents/android-device- Web-export checks qualify their named web paths; native-only behavior remains untested until its device result is recorded. +## Team mode security suite + +For a change that affects Team mode permissions, run the real-model security suite on an isolated Host and attach its report to the PR: + +```bash +pnpm build +node scripts/e2e-team-security.mjs --launch # every scenario +node scripts/e2e-team-security.mjs --name --scenario B # only file and Shell boundaries +``` + +It sets up roles with Role Policy, members, public and private Bots, folders and Channels, then drives real model turns that try to leak finance figures (A), reach other members' folders, the Host data directory or the Host API through file tools, Shell and grants (B), and cross private Bots, Channels, Human DMs, offboarding and model allowlists (C). Hard boundaries are asserted on Host state and tool results; Role Policy scenarios pass only when no restricted value appears in any reply. Shell checks are enforced only when `team-mode status` reports `isolation: enforced` (Linux with bwrap, slirp4netns and nft); elsewhere B2 reports the known gap. The report lands in `.humanlayer/team-security/