Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix: /sandbox delete permission parameter

zhaozixuan287ca1cc888e
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.md
index e0da477190..4ab1ee09e0 100644
--- a/docs/en/SlashCommands.md
+++ b/docs/en/SlashCommands.md
@@ -480,14 +480,14 @@ Enter / leave jiuwenbox sandbox mode and tune its runtime policy. Calls `command
| Command | Description |
|---|---|
-| `/sandbox` or `/sandbox status` | Show current runtime (`enabled`, `excluded_commands`, `files.allow_write`, `files.deny_write`) |
+| `/sandbox` or `/sandbox status` | Show current runtime (`enabled`, `landlock`, `excluded_commands`, `files.allow_write`, `files.deny_write`) |
| `/sandbox enable` | Enter sandbox mode (spawns jiuwenbox if needed, rebuilds agent) |
| `/sandbox disable` | Leave sandbox mode (rebuilds agent; stops jiuwenbox only if jiuwenswarm started it) |
| `/sandbox exclude add <pattern>` | Add a shell glob whose matches run locally instead of in the sandbox |
| `/sandbox exclude remove <pattern>` | Remove a pattern |
| `/sandbox exclude list` | List current `excluded_commands` |
-| `/sandbox files allow <path> [perm]` | Allow writing `<path>` inside the sandbox |
-| `/sandbox files deny <path>` | Deny writing `<path>` inside the sandbox |
+| `/sandbox files allow <path>` | Allow write access to `<path>` inside the sandbox (shown as rw) |
+| `/sandbox files deny <path>` | Deny write access to `<path>` inside the sandbox (read still allowed, shown as ro) |
| `/sandbox files remove <path>` | Remove `<path>` from the user-configured allow & deny sets |
| `/sandbox files list` | List effective `allow_write` / `deny_write` |
| `/sandbox help` | Print usage |
@@ -495,7 +495,9 @@ Enter / leave jiuwenbox sandbox mode and tune its runtime policy. Calls `command
#### Concepts
- **Platform support**: `/sandbox` is Linux-only (jiuwenbox depends on Linux kernel features such as bwrap, Landlock, and Linux namespaces). On a Windows or macOS agent-server, every `/sandbox` sub-command returns a `SANDBOX_BAD_REQUEST` error. If the TUI runs on Windows/macOS but the agent-server is on a Linux host, the command works — what matters is the agent-server's platform.
-- **Effective write policy**: `files.allow_write` / `files.deny_write` in the status panel show the merged view of auto-managed and user-configured entries. Auto-managed entries are server-injected (intrinsic files such as `AGENT.md`, `HEARTBEAT.md`, `IDENTITY.md`, `SOUL.md`, `USER.md`, the `memory/daily_memory/` directory, and depending on the mode, `project_dir` and `config/config.yaml`) and cannot be removed via `/sandbox files remove`.
+- **Write policy semantics**: `allow` / `deny` control **write access** (rw/ro) inside the sandbox, not Unix octal modes. Enforcement uses bwrap bind mounts + `--remount-ro`; Landlock is defense-in-depth (when `landlock.compatibility=disabled`, bwrap is primary).
+- **Nested paths**: Supported: parent allow + child deny (e.g. allow `/tmp`, deny `/tmp/secret`). Not supported: child allow + parent deny (parent deny wins); the server rejects such configs.
+- **Effective write policy**: `files.allow_write` / `files.deny_write` in the status panel show the merged view of auto-managed and user-configured entries, each labeled `(rw)` or `(ro)`. Auto-managed entries are server-injected (intrinsic files such as `AGENT.md`, `HEARTBEAT.md`, `IDENTITY.md`, `SOUL.md`, `USER.md`, the `memory/daily_memory/` directory, and depending on the mode, `project_dir` and `config/config.yaml`) and cannot be removed via `/sandbox files remove`.
- **preserve_file_sharing_mode**: Controlled by jiuwenswarm config, not by `/sandbox`. Only `mount` is supported: intrinsic files and `project_dir` are bind-mounted into the sandbox and `project_dir/config/config.yaml` is explicitly added to `deny_write`. Writing any other value into config.yaml is rejected by the server.
- **excluded_commands**: Match the full command string (not just `argv[0]`); a match makes that tool call run on the host, effectively granting the command's side effects to the local environment.
- **Add / remove are strict**: `exclude add` rejects a pattern that is already in the list; `exclude remove` rejects a pattern that is not in the list. `files allow|deny` rejects a path that is already in the same bucket, and rejects a path that exists in the opposite bucket (allow vs deny conflict) — run `files remove` first if you want to flip it. `files remove` rejects paths that have no matching user-configured entry.
@@ -505,7 +507,8 @@ Enter / leave jiuwenbox sandbox mode and tune its runtime policy. Calls `command
- `/sandbox enable` — turn on sandbox mode
- `/sandbox status` — see runtime + effective files
-- `/sandbox files allow ./tmp/ 0777` — let the sandbox write into `./tmp/` with mode 0777
+- `/sandbox files allow ./tmp/` — allow sandbox write access to `./tmp/` (rw)
+- `/sandbox files deny ./tmp/secret/` — deny write under an allowed parent (ro)
- `/sandbox exclude add "git *"` — let `git` run on the host instead of inside the sandbox
### `/hooks` (Browse Hooks Configuration)
diff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
index 0aa2d09b9b..6e7505fd27 100644
--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
@@ -497,14 +497,14 @@
| 命令 | 说明 |
|---|---|
-| `/sandbox` 或 `/sandbox status` | 显示当前 runtime(`enabled`、`excluded_commands`、`files.allow_write`、`files.deny_write`) |
+| `/sandbox` 或 `/sandbox status` | 显示当前 runtime(`enabled`、`landlock`、`excluded_commands`、`files.allow_write`、`files.deny_write`) |
| `/sandbox enable` | 进入沙箱模式(需要时启动 jiuwenbox,并重建 agent) |
| `/sandbox disable` | 离开沙箱模式(重建 agent;jiuwenbox 只在 jiuwenswarm 启动时才停掉) |
| `/sandbox exclude add <pattern>` | 加入一条 shell glob,命中后在本地而非沙箱内执行 |
| `/sandbox exclude remove <pattern>` | 移除一条 pattern |
| `/sandbox exclude list` | 列出当前 `excluded_commands` |
-| `/sandbox files allow <path> [perm]` | 允许沙箱内写 `<path>` |
-| `/sandbox files deny <path>` | 拒绝沙箱内写 `<path>` |
+| `/sandbox files allow <path>` | 允许沙箱内写 `<path>`(显示为 rw) |
+| `/sandbox files deny <path>` | 拒绝沙箱内写 `<path>`(仍可读,显示为 ro) |
| `/sandbox files remove <path>` | 从 user-configured allow & deny 中移除该 path |
| `/sandbox files list` | 列出生效的 `allow_write` / `deny_write` |
| `/sandbox help` | 打印用法 |
@@ -512,7 +512,9 @@
#### 概念说明
- **平台限制**:`/sandbox` 仅支持 Linux 平台(jiuwenbox 依赖 bwrap / Landlock / Linux namespace 等内核能力)。 在 Windows / macOS 上运行的 agent-server 收到任何 `/sandbox` 子命令都会返回 `SANDBOX_BAD_REQUEST` 错误;如果 TUI 在 Mac/Windows 上、agent-server 在 Linux 主机上,是支持的(看 agent-server 所在主机的平台)。
-- **生效写入策略**:状态面板里的 `files.allow_write` / `files.deny_write` 是 auto-managed 与 user-configured 合并后的视图。auto-managed 条目由服务端自动注入(intrinsic 文件 `AGENT.md`、`HEARTBEAT.md`、`IDENTITY.md`、`SOUL.md`、`USER.md`,`memory/daily_memory/` 目录,以及按 mode 决定的 `project_dir` 与 `config/config.yaml`),不能通过 `/sandbox files remove` 移除。
+- **写入策略语义**:`allow` / `deny` 控制的是沙箱内的**写访问**(rw/ro),不是 Unix 八进制权限;enforcement 由 bwrap bind mount + `--remount-ro` 实现,Landlock 为纵深防御(`landlock.compatibility=disabled` 时主要依赖 bwrap)。
+- **嵌套路径**:支持「父 allow + 子 deny」(例如 allow `/tmp`、deny `/tmp/secret`);不支持「子 allow + 父 deny」(父 deny 会覆盖子 allow),服务端会拒绝此类配置。
+- **生效写入策略**:状态面板里的 `files.allow_write` / `files.deny_write` 是 auto-managed 与 user-configured 合并后的视图,每条路径显示 `(rw)` 或 `(ro)`。auto-managed 条目由服务端自动注入(intrinsic 文件 `AGENT.md`、`HEARTBEAT.md`、`IDENTITY.md`、`SOUL.md`、`USER.md`,`memory/daily_memory/` 目录,以及按 mode 决定的 `project_dir` 与 `config/config.yaml`),不能通过 `/sandbox files remove` 移除。
- **preserve_file_sharing_mode**:由 jiuwenswarm 配置决定,不通过 `/sandbox` 切换。仅支持 `mount`:intrinsic 文件与 `project_dir` 通过 bind mount 注入沙箱,`project_dir/config/config.yaml` 会显式加进 `deny_write`;yaml 里写入其它值会被服务端拒绝。
- **excluded_commands**:按完整命令字符串匹配(不是只看 `argv[0]`),命中后该次调用穿透到本地,相当于把对应命令的副作用授权给本地环境。
- **add / remove 的去重与冲突**:`exclude add` 在已存在同名 pattern 时报错;`exclude remove` 在不存在该 pattern 时报错。`files allow|deny` 在同一 bucket 已有同 path 时报错,在对侧 bucket(allow vs deny)已登记同 path 时也报错,需要先 `files remove` 再 add;`files remove` 在用户配置里找不到该 path 时报错。
@@ -522,7 +524,8 @@
- `/sandbox enable` — 打开沙箱模式
- `/sandbox status` — 查看 runtime 与生效路径
-- `/sandbox files allow ./tmp/ 0777` — 允许沙箱以 0777 写入 `./tmp/`
+- `/sandbox files allow ./tmp/` — 允许沙箱写入 `./tmp/`(rw)
+- `/sandbox files deny ./tmp/secret/` — 在已 allow 的父目录下禁止写入子目录(ro)
- `/sandbox exclude add "git *"` — 让 `git` 命令穿透到本地执行,不进沙箱
### `/hooks`(浏览 Hooks 配置)
diff --git "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
index 52d3f71ae8..9c478ac46e 100644
--- "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
+++ "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
@@ -316,11 +316,13 @@
- 状态面板字段:
- `enabled` — 当前开关。
- `excluded_commands` — 命中后穿透到本地执行的 shell glob 列表。
- - `files.allow_write` / `files.deny_write` — 生效(auto-managed ∪ user-configured,去重)的写入策略。
+ - `landlock` — jiuwenbox Landlock 支持情况(`supported` + `compatibility`)。
+ - `files.allow_write` / `files.deny_write` — 生效(auto-managed ∪ user-configured,去重)的写入策略,显示 `(rw)` / `(ro)`。
- 自动配置路径:文件 `AGENT.md`、`HEARTBEAT.md`、`IDENTITY.md`、`SOUL.md`、`USER.md`,目录 `memory/daily_memory/`,以及 `project_dir`(allow_write)与 `project_dir/config/config.yaml`(deny_write)。`preserve_file_sharing_mode` 仅支持 `mount`。
- `excluded_commands` 的匹配:按完整命令字符串匹配,不仅看 `argv[0]`;写 glob 时要把参数也覆盖进去(例如 `"git *"` 而不是 `git`)。本质等同于沙箱穿透口,不要对 `rm -rf` / `curl` 这类高风险命令使用。
- add / remove 严格校验:`exclude add` 已存在 pattern、`exclude remove` 不存在 pattern 都会报错;`files allow|deny` 在同 bucket 已有 path 或对侧 bucket 已有 path(allow/deny 冲突)会报错,先 `files remove` 再 add;`files remove` 没匹配到也会报错。避免"看起来执行了实际什么也没改"。
-- 示例:`/sandbox enable`、`/sandbox status`、`/sandbox files allow ./tmp/ 0777`、`/sandbox exclude add "git *"`。
+- 写入策略:`allow` / `deny` 控制写访问(rw/ro),不是 Unix 八进制权限;支持「父 allow + 子 deny」,不支持「子 allow + 父 deny」。
+- 示例:`/sandbox enable`、`/sandbox status`、`/sandbox files allow ./tmp/`、`/sandbox exclude add "git *"`。
#### `/hooks`(浏览 Hooks 配置)
diff --git a/jiuwenbox/docker/Dockerfile b/jiuwenbox/docker/Dockerfile
index bf29938182..e7c8753faa 100644
--- a/jiuwenbox/docker/Dockerfile
+++ b/jiuwenbox/docker/Dockerfile
@@ -8,8 +8,8 @@ RUN echo "sslverify=false" >> /etc/yum.conf
RUN echo "insecure" >> ~/.curlrc
RUN sed -i 's/gpgcheck=1/gpgcheck=0/g' /etc/yum.conf /etc/yum.repos.d/openEuler.repo
-RUN yum makecache \
- && yum install -y \
+RUN yum makecache
+RUN yum install -y \
bubblewrap \
iproute \
iptables \
@@ -27,6 +27,7 @@ WORKDIR /app
COPY pyproject.toml README.md ./
COPY docker/requirements.txt ./docker/requirements.txt
COPY src ./src
+COPY src/jiuwenbox/configs /app/configs
RUN pip install --break-system-packages --upgrade -i https://pypi.tuna.tsinghua.edu.cn/simple build setuptools wheel \
&& pip install --break-system-packages -i https://pypi.tuna.tsinghua.edu.cn/simple -r ./docker/requirements.txt \
diff --git a/jiuwenbox/scripts/build_docker.sh b/jiuwenbox/scripts/build_docker.sh
index 3d28c98713..f745549b7d 100755
--- a/jiuwenbox/scripts/build_docker.sh
+++ b/jiuwenbox/scripts/build_docker.sh
@@ -23,4 +23,4 @@ if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
exit 0
fi
-docker build -f "$PROJECT_DIR/docker/Dockerfile" --no-cache -t "$IMAGE_REF" "$PROJECT_DIR" "$@"
+docker build -f "$PROJECT_DIR/docker/Dockerfile" -t "$IMAGE_REF" "$PROJECT_DIR" "$@"
diff --git a/jiuwenbox/src/jiuwenbox/server/runtime/process.py b/jiuwenbox/src/jiuwenbox/server/runtime/process.py
index 6618a3f146..5d40ff9ae5 100644
--- a/jiuwenbox/src/jiuwenbox/server/runtime/process.py
+++ b/jiuwenbox/src/jiuwenbox/server/runtime/process.py
@@ -1849,8 +1849,7 @@ class ProcessRuntime(RuntimeAdapter):
# ``exit(1)`` before printing anything).
message = (
f"{message} No stdout/stderr was captured before the "
- f"daemon exited; re-run with the container attached "
- f"(``docker run -it``) to see live bwrap output."
+ f"daemon exited."
)
raise RuntimeError(message)
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py
index 731db06a4e..09cf19b69b 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py
@@ -164,7 +164,7 @@ class BwrapConfig:
# bind_root_entries is the "wildcard / generic" parent mount (e.g.
# ``host_root="/"`` expanded into every immediate child of the host
# rootfs), while ``bind_mounts`` are user-explicit per-path overrides
- # (``/sandbox files allow|deny <path>`` lowered by jiuwenswarm's
+ # (``/sandbox files allow|deny <path>`` lowered by jiuwenclaw's
# ``sysop_builder``). bwrap's later-overrides-earlier mount semantics
# means whichever entry we ``append`` last wins on conflicting paths;
# putting bind_root_entries first guarantees the explicit
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py b/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py
index 396643834d..7f7590f801 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py
@@ -38,12 +38,14 @@ cannot reach (or delete) the listener.
Important security notes:
-* The daemon does **not** install signal handlers. Inside the sandbox's
- PID namespace the daemon runs as PID 1; the kernel drops signals from
- other namespace members targeting an init that has not registered a
- handler, so a sandboxed payload cannot kill the daemon. Box-server
- shuts the daemon down via the ``shutdown`` IPC command (graceful) or
- ``SIGKILL`` from outside the namespace (forced).
+* Sandboxed payloads share the daemon's UID (typically ``nobody``). The
+ kernel's PID-1 signal protections are not sufficient on every platform,
+ so seccomp additionally blocks ``kill``/``tkill``/``tgkill`` targeting
+ infrastructure PIDs (1/2, process group, or broadcast). Each user exec
+ also runs in its own session so ``kill(0)`` cannot reach the daemon.
+
+* Box-server shuts the daemon down via the ``shutdown`` IPC command
+ (graceful) or ``SIGKILL`` from outside the namespace (forced).
* Children are spawned via :func:`subprocess.Popen` so the kernel does
the standard ``fork``/``execve`` pair. The seccomp BPF filter and
@@ -246,6 +248,9 @@ def _handle_exec(conn: socket.socket, header: dict[str, Any], state: DaemonState
"stderr": subprocess.PIPE,
"env": merged_env,
"close_fds": True,
+ # Isolate each exec in its own session so kill(0) from user
+ # code cannot reach the long-running daemon process group.
+ "start_new_session": True,
}
if workdir:
proc_kwargs["cwd"] = workdir
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py b/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py
index de8dbb9e01..2d2dda45b1 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py
@@ -57,6 +57,19 @@ ARCH_ALIASES = {
SECCOMP_DATA_NR_OFFSET = 0
# offsetof(struct seccomp_data, arch)
SECCOMP_DATA_ARCH_OFFSET = 4
+# offsetof(struct seccomp_data, args[0]) / args[1]
+SECCOMP_DATA_ARG0_OFFSET = 16
+SECCOMP_DATA_ARG1_OFFSET = 24
+
+# kill(2) pid arguments compared via BPF_W (lower 32 bits of seccomp args[0]).
+_DAEMON_PROTECTED_KILL_TARGETS = (
+ 0,
+ 1,
+ 2,
+ 0xFFFFFFFE, # -2, kill process group 2
+ 0xFFFFFFFF, # -1, broadcast to same-UID processes
+)
+_DAEMON_PROTECTED_TGKILL_TARGETS = (1, 2)
def _machine() -> str:
@@ -95,6 +108,9 @@ def _fallback_syscall_numbers() -> dict[str, int]:
"delete_module": 106,
"ptrace": 117,
"reboot": 142,
+ "kill": 129,
+ "tkill": 130,
+ "tgkill": 131,
"getpid": 172,
"getppid": 173,
"add_key": 217,
@@ -206,6 +222,55 @@ def _bpf_jump(code: int, k: int, jt: int, jf: int) -> bytes:
return struct.pack("<HBBI", code, jt, jf, k)
+def _append_daemon_signal_guard(prog: bytearray, syscall_table: dict[str, int]) -> None:
+ """Deny kill-family syscalls that target sandbox infrastructure PIDs.
+
+ Appended after policy-driven syscall blocks and before the default
+ ALLOW. Each guarded syscall uses an inline EPERM return so this
+ section does not share tail-jump offsets with the policy blocklist.
+ """
+ guarded = (
+ ("kill", _DAEMON_PROTECTED_KILL_TARGETS, ()),
+ ("tkill", _DAEMON_PROTECTED_KILL_TARGETS, ()),
+ ("tgkill", _DAEMON_PROTECTED_KILL_TARGETS, _DAEMON_PROTECTED_TGKILL_TARGETS),
+ )
+ for name, arg0_targets, arg1_targets in guarded:
+ nr = syscall_table.get(name)
+ if nr is None:
+ continue
+
+ body = bytearray()
+ body += _bpf_stmt(BPF_LD | BPF_W | BPF_ABS, SECCOMP_DATA_ARG0_OFFSET)
+ eperm_index = (
+ 1
+ + len(arg0_targets)
+ + (1 if arg1_targets else 0)
+ + len(arg1_targets)
+ + 1
+ )
+ for index, value in enumerate(arg0_targets):
+ remaining = eperm_index - (1 + index + 1)
+ body += _bpf_jump(BPF_JMP | BPF_JEQ | BPF_K, value, remaining, 0)
+ if arg1_targets:
+ body += _bpf_stmt(BPF_LD | BPF_W | BPF_ABS, SECCOMP_DATA_ARG1_OFFSET)
+ arg1_start = 1 + len(arg0_targets) + 1
+ for index, value in enumerate(arg1_targets):
+ remaining = eperm_index - (arg1_start + index + 1)
+ body += _bpf_jump(BPF_JMP | BPF_JEQ | BPF_K, value, remaining, 0)
+ # ``BPF_JMP|BPF_K`` uses the immediate ``k`` field as the jump
+ # offset. When no protected PID matched above, skip the EPERM RET
+ # below (``k=1``). ``k=0`` incorrectly falls through to EPERM and
+ # blocks every other kill/tkill/tgkill target (e.g. user pid 18).
+ body += _bpf_jump(BPF_JMP | BPF_K, 1, 0, 0)
+ body += _bpf_stmt(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | ERRNO_EPERM)
+
+ skip_body = len(body) // 8
+ # Re-load nr before each guard: prior LD arg0/arg1 clobbers the accumulator.
+ prog += _bpf_stmt(BPF_LD | BPF_W | BPF_ABS, SECCOMP_DATA_NR_OFFSET)
+ prog += _bpf_jump(BPF_JMP | BPF_JEQ | BPF_K, nr, 0, skip_body)
+ prog.extend(body)
+
+
def build_seccomp_filter(policy: SyscallPolicy) -> bytes:
"""Build a seccomp-bpf binary filter from a SyscallPolicy.
@@ -232,19 +297,15 @@ def _assemble_bpf(blocked_nrs: list[int]) -> bytes:
Structure:
1. Validate arch == current process architecture
2. Load syscall number
- 3. For each blocked nr: if match -> return configured errno
- 4. Default: ALLOW
+ 3. For each blocked nr: if match -> inline return errno
+ 4. Deny kill/tkill/tgkill that target sandbox infrastructure PIDs
+ 5. Default: ALLOW
+
+ Policy blocks use inline RET actions instead of tail jumps so adding
+ the daemon signal guard cannot perturb blocked-syscall offsets.
"""
syscall_table = _get_syscall_numbers()
clone3_nr = syscall_table.get("clone3")
- errno_actions: dict[int, int] = {}
- for nr in blocked_nrs:
- # pthread_create in recent glibc probes clone3 first and only falls back
- # to clone when clone3 looks unavailable. Return ENOSYS instead of EPERM
- # so runtimes like Node.js can still create threads via clone.
- errno_actions[nr] = ERRNO_ENOSYS if nr == clone3_nr else ERRNO_EPERM
-
- action_values = list(dict.fromkeys(errno_actions.values()))
prog = bytearray()
# Load arch
@@ -256,22 +317,20 @@ def _assemble_bpf(blocked_nrs: list[int]) -> bytes:
# Load syscall number
prog += _bpf_stmt(BPF_LD | BPF_W | BPF_ABS, SECCOMP_DATA_NR_OFFSET)
- # For each blocked syscall: jump to deny if match
- n = len(blocked_nrs)
- for i, nr in enumerate(blocked_nrs):
- action_index = action_values.index(errno_actions[nr])
- jump_offset = (n - i) + action_index
- # If match -> jump to the errno block.
- # If no match -> fall through to next check
- prog += _bpf_jump(BPF_JMP | BPF_JEQ | BPF_K, nr, jump_offset, 0)
+ # For each blocked syscall: inline deny on match.
+ # On miss, skip only the inline RET (``jf=1``). A larger skip would
+ # jump over the next syscall's JEQ as well and leave the filter in an
+ # invalid state that makes bwrap crash with SIGSEGV during startup.
+ for nr in blocked_nrs:
+ prog += _bpf_jump(BPF_JMP | BPF_JEQ | BPF_K, nr, 0, 1)
+ errno = ERRNO_ENOSYS if nr == clone3_nr else ERRNO_EPERM
+ prog += _bpf_stmt(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | errno)
+
+ _append_daemon_signal_guard(prog, syscall_table)
# Default: allow
prog += _bpf_stmt(BPF_RET | BPF_K, SECCOMP_RET_ALLOW)
- # Deny blocks.
- for errno in action_values:
- prog += _bpf_stmt(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | errno)
-
return bytes(prog)
diff --git a/jiuwenbox/tests/integration/test_server_api_default.py b/jiuwenbox/tests/integration/test_server_api_default.py
index 5746f65175..5a08573b82 100644
--- a/jiuwenbox/tests/integration/test_server_api_default.py
+++ b/jiuwenbox/tests/integration/test_server_api_default.py
@@ -594,12 +594,10 @@ class TestSandboxLifecycle:
@staticmethod
def test_sandbox_process_cannot_target_sandbox_daemon(client):
# The long-running daemon shares the sandbox PID namespace with
- # user-spawned children (the daemon is PID 1 in that namespace).
- # The kernel protects PID 1 of a namespace from in-namespace senders
- # for any signal that PID 1 has not registered a handler for; the
- # daemon registers no handlers, so SIGTERM/SIGINT/SIGKILL from user
- # code must all be silently dropped and the daemon must continue to
- # service requests.
+ # user-spawned children. bwrap's monitor is typically PID 1 and
+ # the daemon is PID 2; seccomp blocks kill-family syscalls that
+ # target those PIDs (plus broadcast/process-group forms), and each
+ # exec runs in its own session so kill(0) cannot reach the daemon.
create_resp = client.post("/api/v1/sandboxes", json={})
assert create_resp.status_code == 201
sandbox = create_resp.json()
@@ -620,24 +618,35 @@ class TestSandboxLifecycle:
targets = [signal.SIGTERM, signal.SIGINT, signal.SIGKILL,
signal.SIGHUP, signal.SIGUSR1, signal.SIGUSR2]
delivered = []
- for sig in targets:
+ for pid in (1, 2):
+ for sig in targets:
+ try:
+ os.kill(pid, sig)
+ except ProcessLookupError:
+ delivered.append(f"missing:{pid}:{sig}")
+ except PermissionError:
+ continue
+ except OSError as exc:
+ delivered.append(f"error:{pid}:{sig}:{exc.errno}")
+ for pid in (0, -1, -2):
try:
- os.kill(1, sig)
+ os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
- delivered.append(f"missing:{sig}")
+ delivered.append(f"missing:{pid}")
except PermissionError:
continue
except OSError as exc:
- delivered.append(f"error:{sig}:{exc.errno}")
+ delivered.append(f"error:{pid}:{exc.errno}")
time.sleep(0.5)
- try:
- os.kill(1, 0)
- except ProcessLookupError:
- print("daemon-killed")
- sys.exit(1)
- except PermissionError:
- pass
+ for pid in (1, 2):
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ print(f"daemon-killed:{pid}")
+ sys.exit(1)
+ except PermissionError:
+ pass
if delivered:
print(f"unexpected:{','.join(delivered)}")
@@ -653,6 +662,21 @@ class TestSandboxLifecycle:
assert kill_data["exit_code"] == 0, kill_data
assert kill_data["stdout"].strip() == "daemon-survived"
+ shell_kill_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={
+ "command": [
+ "sh",
+ "-c",
+ "kill -9 1 2>/dev/null; kill -9 2 2>/dev/null; "
+ "kill -9 0 2>/dev/null; kill -9 -1 2>/dev/null; "
+ "kill -9 -2 2>/dev/null; echo daemon-survived",
+ ],
+ "timeout_seconds": 10,
+ })
+ assert shell_kill_resp.status_code == 200
+ shell_kill_data = shell_kill_resp.json()
+ assert shell_kill_data["exit_code"] == 0, shell_kill_data
+ assert shell_kill_data["stdout"].strip() == "daemon-survived"
+
status_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")
assert status_resp.status_code == 200
assert status_resp.json()["phase"] == "ready", status_resp.json()
@@ -668,12 +692,11 @@ class TestSandboxLifecycle:
@staticmethod
def test_sandbox_process_cannot_inspect_sandbox_daemon_memory(client):
- # PID 1 of the sandbox PID namespace is the long-running daemon.
- # Reading the daemon's address space (``/proc/1/mem``) requires
- # CAP_SYS_PTRACE (stripped by the default policy) and
- # ``ptrace(PTRACE_ATTACH, 1)`` is blocked by seccomp. Together
- # these prevent a sandboxed process from extracting secrets from
- # or hijacking the long-running daemon.
+ # The sandbox infrastructure occupies PID 1/2 (bwrap monitor and
+ # daemon). Reading either process' address space requires
+ # CAP_SYS_PTRACE (stripped by the default policy), and ptrace attach is
+ # blocked by seccomp. Together these prevent a sandboxed process from
+ # extracting secrets from or hijacking the long-running daemon.
create_resp = client.post("/api/v1/sandboxes", json={})
assert create_resp.status_code == 201
sandbox = create_resp.json()
@@ -686,34 +709,36 @@ class TestSandboxLifecycle:
import os
import sys
- try:
- fd = os.open('/proc/1/mem', os.O_RDONLY)
- except PermissionError:
- pass
- except FileNotFoundError:
- pass
- else:
+ for pid in (1, 2):
try:
- os.read(fd, 16)
+ fd = os.open(f'/proc/{pid}/mem', os.O_RDONLY)
except PermissionError:
- pass
- except OSError:
- pass
+ continue
+ except FileNotFoundError:
+ continue
else:
+ try:
+ os.read(fd, 16)
+ except PermissionError:
+ pass
+ except OSError:
+ pass
+ else:
+ os.close(fd)
+ print(f'infrastructure-memory-readable:{pid}')
+ sys.exit(2)
os.close(fd)
- print('daemon-memory-readable')
- sys.exit(2)
- os.close(fd)
- try:
- libc = ctypes.CDLL('libc.so.6', use_errno=True)
- PTRACE_ATTACH = 16
- rc = libc.ptrace(PTRACE_ATTACH, 1, 0, 0)
- if rc == 0:
- print('daemon-ptraceable')
- sys.exit(3)
- except OSError:
- pass
+ libc = ctypes.CDLL('libc.so.6', use_errno=True)
+ PTRACE_ATTACH = 16
+ for pid in (1, 2):
+ try:
+ rc = libc.ptrace(PTRACE_ATTACH, pid, 0, 0)
+ if rc == 0:
+ print(f'infrastructure-ptraceable:{pid}')
+ sys.exit(3)
+ except OSError:
+ pass
print('daemon-protected')
"""
@@ -727,6 +752,111 @@ class TestSandboxLifecycle:
assert data["exit_code"] == 0, data
assert data["stdout"].strip() == "daemon-protected"
+ @staticmethod
+ def test_default_policy_seccomp_allows_sandbox_startup(client):
+ # End-to-end regression for the seccomp BPF chain: the default policy
+ # blocks many syscalls and uses isolated networking. A malformed filter
+ # used to make bwrap exit with SIGSEGV (code 139) before the daemon
+ # printed anything, leaving the sandbox stuck in ``error``.
+ create_resp = client.post("/api/v1/sandboxes", json={})
+ assert create_resp.status_code == 201
+ sandbox = create_resp.json()
+ assert sandbox["phase"] == "ready", sandbox
+ assert sandbox.get("error_message") in (None, ""), sandbox
+
+ exec_resp = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={
+ "command": ["echo", "seccomp-ok"],
+ "timeout_seconds": 5,
+ })
+ assert exec_resp.status_code == 200
+ exec_data = exec_resp.json()
+ assert exec_data["exit_code"] == 0, exec_data
+ assert exec_data["stdout"].strip() == "seccomp-ok"
+
+ @staticmethod
+ def test_default_policy_blocked_syscall_is_enforced(client):
+ # Prove the installed default-policy seccomp filter still denies blocked
+ # syscalls at exec time (not only at sandbox startup).
+ create_resp = client.post("/api/v1/sandboxes", json={})
+ assert create_resp.status_code == 201
+ sandbox = create_resp.json()
+ assert sandbox["phase"] == "ready", sandbox
+ sandbox_id = sandbox["id"]
+
+ response = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={
+ "command": [
+ "python3",
+ "-c",
+ textwrap.dedent(
+ """
+ import ctypes
+ import errno
+ import platform
+ import sys
+
+ syscall_numbers = {
+ "x86_64": 165,
+ "AMD64": 165,
+ "aarch64": 40,
+ }
+ nr = syscall_numbers.get(platform.machine())
+ if nr is None:
+ print(f"unsupported-arch:{platform.machine()}")
+ sys.exit(2)
+
+ libc = ctypes.CDLL("libc.so.6", use_errno=True)
+ libc.syscall.restype = ctypes.c_long
+ ctypes.set_errno(0)
+ result = libc.syscall(nr)
+ err = ctypes.get_errno()
+ if result == -1 and err == errno.EPERM:
+ print("syscall-blocked")
+ sys.exit(7)
+
+ print(f"unexpected-success:{result}:{err}")
+ """
+ ).strip(),
+ ],
+ "timeout_seconds": 5,
+ })
+ assert response.status_code == 200
+ data = response.json()
+ assert data["exit_code"] == 7, data
+ assert "syscall-blocked" in data["stdout"]
+ assert "unexpected-success" not in data["stdout"]
+
+ @staticmethod
+ def test_sandbox_process_can_kill_unprotected_child(client):
+ # Seccomp only guards infrastructure PIDs (0/1/2 and broadcast forms).
+ # User payloads must still be able to signal their own children.
+ create_resp = client.post("/api/v1/sandboxes", json={})
+ assert create_resp.status_code == 201
+ sandbox = create_resp.json()
+ assert sandbox["phase"] == "ready", sandbox
+ sandbox_id = sandbox["id"]
+
+ kill_child_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={
+ "command": [
+ "sh",
+ "-c",
+ "sleep 30 & pid=$!; "
+ "kill -0 $pid || exit 11; "
+ "kill -9 $pid || exit 12; "
+ "wait $pid; "
+ "echo killed:$pid",
+ ],
+ "timeout_seconds": 10,
+ })
+ assert kill_child_resp.status_code == 200
+ kill_child_data = kill_child_resp.json()
+ assert kill_child_data["exit_code"] == 0, kill_child_data
+ assert kill_child_data["stdout"].strip().startswith("killed:")
+ assert "Operation not permitted" not in kill_child_data["stderr"]
+
+ status_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")
+ assert status_resp.status_code == 200
+ assert status_resp.json()["phase"] == "ready", status_resp.json()
+
@staticmethod
def test_get_logs(client):
create_resp = client.post("/api/v1/sandboxes", json={})
@@ -1885,6 +2015,10 @@ class TestPolicyEnforcement:
client,
create_sandbox_with_policy,
):
+ # Use ``mount`` rather than ``getpid``: seccomp is installed once for the
+ # whole sandbox lifecycle (daemon + user exec children), so blocking a
+ # syscall the daemon needs during startup would prevent the sandbox from
+ # reaching ``ready``.
sandbox = create_sandbox_with_policy(
policy={
"name": "syscall-block-policy",
@@ -1893,8 +2027,8 @@ class TestPolicyEnforcement:
"read_write": ["/tmp"],
},
"syscall": {
- "x86_64": {"blocked": ["getpid"]},
- "arm64": {"blocked": ["getpid"]},
+ "x86_64": {"blocked": ["mount"]},
+ "arm64": {"blocked": ["mount"]},
},
"network": {
"mode": "host",
@@ -1914,9 +2048,9 @@ class TestPolicyEnforcement:
import sys
syscall_numbers = {
- "x86_64": 39,
- "AMD64": 39,
- "aarch64": 172,
+ "x86_64": 165,
+ "AMD64": 165,
+ "aarch64": 40,
}
nr = syscall_numbers.get(platform.machine())
if nr is None:
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts
index a485bf6883..64e603d605 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts
@@ -3,7 +3,7 @@ import { CommandKind, type SlashCommand } from "../types.js";
type SandboxFileEntry =
| string
- | { path: string; permissions?: string; kind?: "file" | "directory" };
+ | { path: string; access?: string; kind?: "file" | "directory" };
type SandboxRuntime = {
enabled?: boolean;
@@ -40,12 +40,12 @@ function formatBool(value: unknown): string {
return value === true ? "on" : "off";
}
-function formatFileEntry(entry: SandboxFileEntry): string {
+function formatFileEntry(entry: SandboxFileEntry, defaultAccess?: string): string {
if (typeof entry === "string") return entry;
if (entry && typeof entry === "object") {
const path = String(entry.path ?? "");
- const perm = entry.permissions ? ` (${entry.permissions})` : "";
- return `${path}${perm}`;
+ const access = entry.access ?? defaultAccess;
+ return access ? `${path} (${access})` : path;
}
return String(entry);
}
@@ -59,33 +59,35 @@ function showRuntime(
const excludes = rt.excluded_commands ?? [];
const allowWrite = effective?.allow_write ?? rt.files?.allow ?? [];
const denyWrite = effective?.deny_write ?? rt.files?.deny ?? [];
+ const items = [
+ { label: "enabled", value: formatBool(rt.enabled) },
+ {
+ label: "excluded_commands",
+ value: excludes.length ? excludes.join(", ") : "(empty)",
+ },
+ {
+ label: "files.allow_write",
+ value: allowWrite.length
+ ? allowWrite.map((e) => formatFileEntry(e, "rw")).join(", ")
+ : "(empty)",
+ },
+ {
+ label: "files.deny_write",
+ value: denyWrite.length
+ ? denyWrite.map((e) => formatFileEntry(e, "ro")).join(", ")
+ : "(empty)",
+ },
+ ];
ctx.addItem(
addInfo(ctx.sessionId, "Sandbox status", "s", {
view: "kv",
title: "Sandbox Runtime",
- items: [
- { label: "enabled", value: formatBool(rt.enabled) },
- {
- label: "excluded_commands",
- value: excludes.length ? excludes.join(", ") : "(empty)",
- },
- {
- label: "files.allow_write",
- value: allowWrite.length ? allowWrite.map(formatFileEntry).join(", ") : "(empty)",
- },
- {
- label: "files.deny_write",
- value: denyWrite.length ? denyWrite.map(formatFileEntry).join(", ") : "(empty)",
- },
- ],
+ items,
}),
);
}
function usageText(): string {
- // The InfoMessageComponent renderer only prepends the "· " bullet to the
- // first physical line of the content, so we indent every subsequent line
- // with two spaces to keep "/sandbox …" left-aligned with line 1.
const lines = [
"/sandbox show current runtime status",
"/sandbox enable enter sandbox mode (spawns jiuwenbox + recreates agent)",
@@ -93,8 +95,8 @@ function usageText(): string {
"/sandbox exclude add <pattern> add a glob whose match runs locally instead of sandbox",
"/sandbox exclude remove <pattern> remove a previously added pattern",
"/sandbox exclude list list current excluded_commands",
- "/sandbox files allow <path> [perm] allow accessing <path> in sandbox (trailing / => directory)",
- "/sandbox files deny <path> deny accessing <path> in sandbox",
+ "/sandbox files allow <path> allow write access to <path> in sandbox",
+ "/sandbox files deny <path> deny write access to <path> in sandbox (read still allowed)",
"/sandbox files remove <path> remove the path from both allow & deny",
"/sandbox files list list configured files",
];
@@ -220,11 +222,15 @@ export function createSandboxCommand(): SlashCommand {
items: [
{
label: "allow_write",
- value: allowWrite.length ? allowWrite.map(formatFileEntry).join(", ") : "(empty)",
+ value: allowWrite.length
+ ? allowWrite.map((e) => formatFileEntry(e, "rw")).join(", ")
+ : "(empty)",
},
{
label: "deny_write",
- value: denyWrite.length ? denyWrite.map(formatFileEntry).join(", ") : "(empty)",
+ value: denyWrite.length
+ ? denyWrite.map((e) => formatFileEntry(e, "ro")).join(", ")
+ : "(empty)",
},
],
}),
@@ -232,16 +238,23 @@ export function createSandboxCommand(): SlashCommand {
return;
}
if (op === "allow" || op === "deny" || op === "remove") {
+ if (tokens.length > 3) {
+ ctx.addItem(
+ addError(
+ ctx.sessionId,
+ `Too many arguments. Usage: /sandbox files ${op} <path>`,
+ ),
+ );
+ return;
+ }
const path = tokens[2];
- const perm = tokens[3];
if (!path) {
- ctx.addItem(addError(ctx.sessionId, `Missing path. Usage: /sandbox files ${op} <path> [permissions]`));
+ ctx.addItem(addError(ctx.sessionId, `Missing path. Usage: /sandbox files ${op} <path>`));
return;
}
const subAction =
op === "allow" ? "files.allow" : op === "deny" ? "files.deny" : "files.remove";
const params: Record<string, unknown> = { sub: subAction, path };
- if (perm) params.permissions = perm;
const payload = await ctx.request<SandboxResponse>("command.sandbox", params);
ctx.addItem(
addInfo(
@@ -253,6 +266,15 @@ export function createSandboxCommand(): SlashCommand {
showRuntime(ctx, payload.runtime, payload.effective_files);
return;
}
+ if (op === "add") {
+ ctx.addItem(
+ addError(
+ ctx.sessionId,
+ "Unknown files sub-command 'add'; use 'allow' or 'deny'",
+ ),
+ );
+ return;
+ }
ctx.addItem(addError(ctx.sessionId, "Usage: /sandbox files <allow|deny|remove|list> [path]"));
return;
}
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 4044fa37ad..bd2db3d962 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -43,7 +43,9 @@ from jiuwenswarm.server.runtime.session.session_history import append_compact_hi
from jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (
build_filesystem_policy,
find_auto_managed_match,
+ find_nested_files_conflict,
list_effective_sandbox_files,
+ validate_sandbox_files_runtime,
)
from jiuwenswarm.server.utils.utils import is_team_params
from jiuwenswarm.agents.harness.common.rails.permissions.permissions_config_rpc import (
@@ -366,6 +368,28 @@ def _canonicalize_sandbox_files_path(path: str) -> str:
return path
+_SANDBOX_FILES_PARAMS = frozenset(
+ {
+ "sub",
+ "path",
+ "session_id",
+ "trusted_dirs",
+ "project_dir",
+ "cwd",
+ "mode", # injected by gateway for agent routing
+ }
+)
+
+
+def _reject_extra_sandbox_files_params(params: dict[str, Any]) -> None:
+ extra = set(params.keys()) - _SANDBOX_FILES_PARAMS
+ if extra:
+ raise ValueError(
+ f"unexpected parameter(s): {', '.join(sorted(extra))}; "
+ "/sandbox files allow|deny|remove accepts a single path only"
+ )
+
+
def _inject_plan_mode_activation_reminder(request: AgentRequest) -> None:
"""在用户消息中注入 <system-reminder> 告知 LLM 调用 enter_plan_mode.
@@ -3412,6 +3436,7 @@ class AgentWebSocketServer:
# 故意的, 让 ValueError 命中下方 ``except ValueError`` 分支转成
# ``SANDBOX_BAD_REQUEST`` 回执, 跟其它入参校验失败的处理一致。
_require_sandbox_supported()
+ validate_sandbox_files_runtime(get_sandbox_runtime().get("files"))
if sub == "status":
payload = {"runtime": get_sandbox_runtime()}
elif sub == "enable":
@@ -3435,6 +3460,7 @@ class AgentWebSocketServer:
else:
raise ValueError(f"unknown sub: {sub!r}")
self._attach_effective_sandbox_files(payload, channel_id, params)
+ await self._attach_landlock_status(payload)
resp = AgentResponse(
request_id=request.request_id,
channel_id=request.channel_id,
@@ -3647,19 +3673,6 @@ class AgentWebSocketServer:
params: dict[str, Any],
files: dict[str, Any],
) -> None:
- """在 ``update_sandbox_runtime`` 之前用候选 ``files`` 跑一次
- :func:`build_filesystem_policy` 试压, 失败立刻抛 ``ValueError`` 给 TUI.
-
- 没有这层 dry-run 时, ``/sandbox files allow|deny|remove`` 的处理顺序是
- "先 ``update_sandbox_runtime`` 写盘 → 再 ``_apply_sandbox_runtime_patch``
- 调 adapter 触发 ``build_filesystem_policy``"; 一旦 build 抛
- ``FileNotFoundError`` (典型场景: ``allow /no/such/path``——files.allow /
- files.deny 都要求 path 在 host 上真实存在),
- :meth:`_apply_sandbox_runtime_patch` 的 ``except Exception`` 会把异常
- 吞成 warning, 但 yaml 已经写了 ——用户视角是"runtime 看着更新, 沙箱却
- 没重建, 而且 TUI 上没任何报错". 本函数就是消除这个不可见的中间态:
- 校验失败时直接拒绝命令, 不让 yaml 进入"build 不出 policy"的死局。
- """
project_dir = self._resolve_active_project_dir(channel_id, params)
is_code_agent = self._resolve_active_is_code_agent(channel_id)
try:
@@ -3674,6 +3687,7 @@ class AgentWebSocketServer:
async def _handle_sandbox_files_set(
self, channel_id: str, params: dict[str, Any], *, bucket: str
) -> dict[str, Any]:
+ _reject_extra_sandbox_files_params(params)
path = str(params.get("path") or "").strip()
if not path:
raise ValueError("path is required")
@@ -3709,14 +3723,11 @@ class AgentWebSocketServer:
f"path is auto-managed (always in {matched_bucket}): {canonical}; "
f"cannot add via /sandbox files {bucket}"
)
- permissions = params.get("permissions")
current = get_sandbox_runtime()
files = dict(current.get("files") or {})
files.setdefault("allow", [])
files.setdefault("deny", [])
# 1) 同 bucket 内已经存在等价条目 → 直接报错, 不做 "先删后加" 的隐式覆盖。
- # permissions 的差异也算冲突: 让用户先 ``files remove`` 再重新 add,
- # 确保 yaml 落盘前后 TUI 看到的差异与他实际打的命令一一对应。
target_list: list[Any] = list(files.get(bucket) or [])
for existing in target_list:
if _file_entry_matches_path(existing, path):
@@ -3735,9 +3746,10 @@ class AgentWebSocketServer:
f"cannot add the same path to {bucket}. "
f"`/sandbox files remove {path}` first if you want to flip it"
)
+ nested_error = find_nested_files_conflict(path, bucket, files)
+ if nested_error is not None:
+ raise ValueError(nested_error)
entry: dict[str, Any] = {"path": path}
- if isinstance(permissions, str) and permissions.strip():
- entry["permissions"] = permissions.strip()
target_list.append(entry)
files[bucket] = target_list
# 在写盘前做一次 dry-run, 防止后续 build_filesystem_policy 抛错时,
@@ -3751,6 +3763,7 @@ class AgentWebSocketServer:
async def _handle_sandbox_files_remove(
self, channel_id: str, params: dict[str, Any]
) -> dict[str, Any]:
+ _reject_extra_sandbox_files_params(params)
path = str(params.get("path") or "").strip()
if not path:
raise ValueError("path is required")
@@ -3935,6 +3948,50 @@ class AgentWebSocketServer:
except Exception as exc: # noqa: BLE001
logger.warning("[command.sandbox] attach effective_files failed: %s", exc)
+ @staticmethod
+ def _read_landlock_compatibility(policy_path: Path | None) -> str:
+ if policy_path is None or not policy_path.is_file():
+ return "best_effort"
+ try:
+ import yaml
+
+ data = yaml.safe_load(policy_path.read_text(encoding="utf-8"))
+ if isinstance(data, dict):
+ landlock = data.get("landlock")
+ if isinstance(landlock, dict):
+ compat = landlock.get("compatibility")
+ if isinstance(compat, str) and compat.strip():
+ return compat.strip()
+ except Exception as exc:
+ logger.debug("[command.sandbox] read landlock compatibility failed: %s", exc)
+ return "best_effort"
+
+ async def _attach_landlock_status(self, payload: dict[str, Any]) -> None:
+ """Attach jiuwenbox Landlock capability summary to sandbox responses."""
+ try:
+ endpoint = get_sandbox_endpoint()
+ jb = payload.get("jiuwenbox")
+ if isinstance(jb, dict) and jb.get("host") and jb.get("port"):
+ host = str(jb["host"])
+ port = int(jb["port"])
+ else:
+ url = endpoint.get("url") or "http://127.0.0.1:8321"
+ host, port = self._parse_sandbox_host_port(url)
+
+ health = await self._jiuwenbox_runner.fetch_health(host, port)
+ landlock_supported = bool(health.get("landlock_supported")) if health else False
+
+ policy_file = endpoint.get("policy_file") or DEFAULT_SANDBOX_POLICY_FILE
+ policy_path = resolve_sandbox_policy_path(policy_file)
+ compatibility = self._read_landlock_compatibility(policy_path)
+
+ payload["landlock"] = {
+ "supported": landlock_supported,
+ "compatibility": compatibility,
+ }
+ except Exception as exc:
+ logger.warning("[command.sandbox] attach landlock status failed: %s", exc)
+
async def _apply_sandbox_runtime_patch(
self, channel_id: str, runtime: dict[str, Any], *, files_changed: bool
) -> None:
@@ -3945,13 +4002,8 @@ class AgentWebSocketServer:
try:
await adapter.apply_sandbox_runtime_patch(runtime, files_changed=files_changed)
except (FileNotFoundError, ValueError) as exc:
- # User-facing 配置冲突 (典型: ``/sandbox files allow|deny`` path 在
- # host 上不存在) 必须直接抛到 TUI——上层 _handle_command_sandbox 的
- # 大 try/except 会把 ValueError 路由成 ``SANDBOX_BAD_REQUEST`` 回执,
- # 用户能立刻看到错误原因; 而不是被 ``except Exception`` 吞成一行
- # 后台 warning, runtime config 已经写盘但沙箱悄悄没重建。
raise ValueError(str(exc)) from exc
- except Exception as exc: # noqa: BLE001
+ except Exception as exc:
logger.warning("[command.sandbox] apply_sandbox_runtime_patch failed: %s", exc)
@staticmethod
diff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
index 2418e89c19..ca20096274 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
@@ -113,21 +113,90 @@ _INTRINSIC_RO_FILE_PATH_FUNCS = (
)
-def _normalize_fs_entry(entry: Any, default_permissions: str) -> dict[str, Any] | None:
- """归一化 {path, permissions} 项;接受 str/dict,过滤空值。"""
+def _normalize_fs_entry(entry: Any) -> dict[str, str] | None:
if entry is None:
return None
if isinstance(entry, str):
path = entry.strip()
if not path:
return None
- return {"path": path, "permissions": default_permissions}
+ return {"path": path}
if isinstance(entry, dict):
path = str(entry.get("path") or "").strip()
if not path:
return None
- permissions = str(entry.get("permissions") or default_permissions)
- return {"path": path, "permissions": permissions}
+ return {"path": path}
+ return None
+
+
+def _sandbox_files_entry_path(entry: Any) -> str | None:
+ """Extract the path string from a sandbox.files allow/deny entry."""
+ normalized = _normalize_fs_entry(entry)
+ if normalized is None:
+ return None
+ return normalized["path"]
+
+
+def _is_strict_path_prefix(parent: str, child: str) -> bool:
+ """Return True when ``parent`` is a strict directory ancestor of ``child``."""
+ parent_norm = parent.rstrip("/") or "/"
+ child_norm = child.rstrip("/") or "/"
+ if parent_norm == child_norm:
+ return False
+ if parent_norm == "/":
+ return child_norm != "/"
+ return child_norm.startswith(parent_norm + "/")
+
+
+def validate_sandbox_files_runtime(files: dict[str, Any] | None) -> None:
+ """Reject invalid ``sandbox.files`` shapes."""
+ if not isinstance(files, dict):
+ return
+ for bucket in ("allow", "deny"):
+ entries = files.get(bucket)
+ if not isinstance(entries, list):
+ continue
+ for entry in entries:
+ _normalize_fs_entry(entry)
+
+
+def find_nested_files_conflict(
+ path: str,
+ bucket: str,
+ files: dict[str, Any],
+) -> str | None:
+ """Return an error message when ``path`` would create unsupported nesting.
+
+ Supported: allow parent + deny child (parent rw, child ro).
+ Rejected: allow child while deny ancestor exists, or deny parent while allow
+ descendant exists (parent deny overrides child allow at mount time).
+ """
+ target = _resolve_display_path(path)
+ if target is None:
+ return None
+
+ if bucket == "allow":
+ for entry in files.get("deny") or []:
+ deny_path = _sandbox_files_entry_path(entry)
+ if deny_path is None:
+ continue
+ deny_resolved = _resolve_display_path(deny_path)
+ if deny_resolved is not None and _is_strict_path_prefix(deny_resolved, target):
+ return (
+ f"cannot allow {path!r}: ancestor {deny_path!r} is deny_write; "
+ f"remove `/sandbox files remove {deny_path}` first"
+ )
+ elif bucket == "deny":
+ for entry in files.get("allow") or []:
+ allow_path = _sandbox_files_entry_path(entry)
+ if allow_path is None:
+ continue
+ allow_resolved = _resolve_display_path(allow_path)
+ if allow_resolved is not None and _is_strict_path_prefix(target, allow_resolved):
+ return (
+ f"cannot deny {path!r}: descendant {allow_path!r} is allow_write; "
+ f"remove `/sandbox files remove {allow_path}` first"
+ )
return None
@@ -392,6 +461,7 @@ def build_filesystem_policy(
的 dry-run 会把它捕获成 ``ValueError`` 回 TUI 让用户看到。
"""
files_runtime = files_runtime or {}
+ validate_sandbox_files_runtime(files_runtime)
allow_files: list[dict[str, Any]] = []
allow_dirs: list[dict[str, Any]] = []
@@ -591,7 +661,7 @@ def build_filesystem_policy(
# - 用户语义是 "把 host 已有 path 带进沙箱", 不存在的 path 操作
# 本身就是 no-op, 报错让用户立刻知道 path 拼错或文件还没建。
for entry in files_runtime.get("allow") or []:
- normalized = _normalize_fs_entry(entry, default_permissions="0666")
+ normalized = _normalize_fs_entry(entry)
if normalized is None:
continue
path = normalized["path"].rstrip("/") or "/"
@@ -605,7 +675,7 @@ def build_filesystem_policy(
path,
path,
is_dir=host.is_dir(),
- permissions=str(normalized.get("permissions") or "0666"),
+ permissions="0666",
)
if path not in read_write_promote:
read_write_promote.append(path)
@@ -614,7 +684,7 @@ def build_filesystem_policy(
# 跟 agent_skills 一起在上面统一注册; 这里不再单独处理。 (见
# ``_collect_intrinsic_targets`` 与 ``_record_ro_resource_bind`` 的注释.)
for entry in files_runtime.get("deny") or []:
- normalized = _normalize_fs_entry(entry, default_permissions="0000")
+ normalized = _normalize_fs_entry(entry)
if normalized is None:
continue
path = normalized["path"].rstrip("/") or "/"
@@ -866,7 +936,7 @@ def list_auto_managed_sandbox_paths(
Returns:
``{"allow_write": [...], "deny_write": [...]}`` where each entry is
- ``{"path": str, "permissions": str, "kind": "file" | "directory"}``.
+ ``{"path": str, "access": "rw"|"ro", "kind": "file" | "directory"}``.
Directory paths carry a trailing ``/``.
"""
allow: list[dict[str, str]] = []
@@ -885,7 +955,7 @@ def list_auto_managed_sandbox_paths(
continue
_append_unique(
allow,
- {"path": str(Path(raw)), "permissions": "0666", "kind": "file"},
+ {"path": str(Path(raw)), "access": "rw", "kind": "file"},
)
try:
@@ -904,7 +974,7 @@ def list_auto_managed_sandbox_paths(
allow,
{
"path": str(daily_memory_path) + "/",
- "permissions": "0777",
+ "access": "rw",
"kind": "directory",
},
)
@@ -935,7 +1005,7 @@ def list_auto_managed_sandbox_paths(
allow,
{
"path": str(resolved_project) + "/",
- "permissions": "0777",
+ "access": "rw",
"kind": "directory",
},
)
@@ -965,7 +1035,7 @@ def list_auto_managed_sandbox_paths(
continue
_append_unique(
deny,
- {"path": str(resolved), "permissions": "0444", "kind": "file"},
+ {"path": str(resolved), "access": "ro", "kind": "file"},
)
# Built-in skills directory mirrors what :func:`build_filesystem_policy`
@@ -981,7 +1051,7 @@ def list_auto_managed_sandbox_paths(
allow,
{
"path": str(agent_skills) + "/",
- "permissions": "0777",
+ "access": "rw",
"kind": "directory",
},
)
@@ -1016,7 +1086,7 @@ def list_effective_sandbox_files(
Returns:
``{"allow_write": [...], "deny_write": [...]}`` where every entry is
- ``{"path": str, "permissions": str, "kind": "file" | "directory"}``.
+ ``{"path": str, "access": "rw"|"ro", "kind": "file" | "directory"}``.
"""
auto = list_auto_managed_sandbox_paths(
project_dir=project_dir,
@@ -1026,9 +1096,10 @@ def list_effective_sandbox_files(
deny = list(auto["deny_write"])
files_runtime = files_runtime or {}
+ validate_sandbox_files_runtime(files_runtime)
- def _emit(bucket: list[dict[str, str]], entry: Any, default_permissions: str) -> None:
- normalized = _normalize_fs_entry(entry, default_permissions=default_permissions)
+ def _emit(bucket: list[dict[str, str]], entry: Any, *, access: str) -> None:
+ normalized = _normalize_fs_entry(entry)
if normalized is None:
return
stripped = str(normalized["path"]).rstrip("/") or "/"
@@ -1038,15 +1109,15 @@ def list_effective_sandbox_files(
bucket,
{
"path": display,
- "permissions": str(normalized["permissions"]),
+ "access": access,
"kind": kind,
},
)
for entry in files_runtime.get("allow") or []:
- _emit(allow, entry, "0666")
+ _emit(allow, entry, access="rw")
for entry in files_runtime.get("deny") or []:
- _emit(deny, entry, "0000")
+ _emit(deny, entry, access="ro")
return {"allow_write": allow, "deny_write": deny}
@@ -1096,6 +1167,8 @@ __all__ = [
"create_sandbox_sysop_card",
"create_local_sysop_card",
"find_auto_managed_match",
+ "find_nested_files_conflict",
"list_auto_managed_sandbox_paths",
"list_effective_sandbox_files",
+ "validate_sandbox_files_runtime",
]
diff --git a/jiuwenswarm/server/sandbox/jiuwenbox_runner.py b/jiuwenswarm/server/sandbox/jiuwenbox_runner.py
index 460ab203e0..8a8238dc5c 100644
--- a/jiuwenswarm/server/sandbox/jiuwenbox_runner.py
+++ b/jiuwenswarm/server/sandbox/jiuwenbox_runner.py
@@ -143,6 +143,21 @@ class JiuwenBoxRunner:
except Exception:
return False
+ async def fetch_health(self, host: str | None = None, port: int | None = None) -> dict[str, Any] | None:
+ """Return parsed jiuwenbox ``/health`` JSON, or ``None`` on failure."""
+ target_host = host or self._host
+ target_port = port or self._port
+ url = f"http://{target_host}:{target_port}/health"
+ try:
+ async with httpx.AsyncClient(timeout=2.0) as client:
+ resp = await client.get(url)
+ if resp.status_code != 200:
+ return None
+ data = resp.json()
+ return data if isinstance(data, dict) else None
+ except Exception:
+ return None
+
async def ensure_running(
self,
host: str = "127.0.0.1",