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: fix jiuwenbox bugs

zhaozixuan1d89f84b017d
diff --git a/jiuwenbox/README.md b/jiuwenbox/README.md
index e5ba655888..8c258b46f1 100644
--- a/jiuwenbox/README.md
+++ b/jiuwenbox/README.md
@@ -4,8 +4,9 @@
code snippets with layered isolation.
It exposes a FastAPI server for sandbox lifecycle management, file transfer,
-file listing/search, and command execution. Each sandbox command is launched
-through a small supervisor process that applies the configured isolation policy.
+file listing/search, and command execution. The server applies the configured
+isolation policy in-process by spawning `bubblewrap` directly for each sandbox
+(long-lived per-sandbox daemon plus on-demand background commands).
## Features
@@ -26,14 +27,17 @@ through a small supervisor process that applies the configured isolation policy.
- FastAPI app that manages sandbox lifecycle, policy loading, audit logs, and
API routing.
- `server/runtime`
- - Runtime adapter that starts one supervisor process per sandbox command.
+ - In-process runtime adapter that translates each sandbox policy into a
+ `bubblewrap` command line and spawns it directly from the server (one
+ long-lived daemon per sandbox plus per-call background commands).
- `server/proxy_manager`
- Manages inference privacy proxies for LLM API routing with API key injection.
- `server/policy_reader`
- Shared policy file reader for sandbox and proxy managers.
- `supervisor`
- - Per-command launcher that translates the effective policy into
- `bubblewrap`, Landlock, seccomp, and namespace settings.
+ - Policy-to-isolation translation helpers (`bubblewrap` argv builder,
+ Landlock payload, seccomp filter, cgroup/network setup) consumed by the
+ runtime adapter.
- `proxy`
- HTTP-aware inference privacy proxy with path-based routing and API key
injection (supports OpenAI and Anthropic formats).
@@ -97,13 +101,6 @@ The selected policy path is read from:
JIUWENBOX_POLICY_PATH=/absolute/path/to/policy.yaml
```
-The port can also be set through `JIUWENBOX_PORT` when your process manager
-uses it to render the uvicorn command:
-
-```bash
-JIUWENBOX_PORT=9000
-```
-
### Docker Start
Build the image:
@@ -130,7 +127,7 @@ conflicts.
Listen address is controlled by a single env var:
```bash
-JIUWENBOX_LISTEN=tcp://0.0.0.0:8321 # default, historical behavior
+JIUWENBOX_LISTEN=http://0.0.0.0:8321 # default
JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock # switch to UDS (absolute path required)
```
@@ -172,7 +169,7 @@ jiuwenbox --base-url unix:///tmp/jiuwenbox-sock/jiuwenbox.sock health
JIUWENBOX_URL=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock jiuwenbox sandbox ls
# pytest in dual transport mode (operator launches the matching server first)
-pytest tests/integration --server-endpoint=tcp://127.0.0.1:8321
+pytest tests/integration --server-endpoint=http://127.0.0.1:8321
pytest tests/integration --server-endpoint=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock
```
@@ -180,7 +177,7 @@ UDS-related env vars:
| Variable | Default | Notes |
| --- | --- | --- |
-| `JIUWENBOX_LISTEN` | `tcp://0.0.0.0:8321` | Management API listen URI; accepts `tcp://host:port` or `unix:///abs/socket/path`. Under UDS mode `JIUWENBOX_PORT` is ignored. |
+| `JIUWENBOX_LISTEN` | `http://0.0.0.0:8321` | Management API listen URI; accepts `http://host:port` or `unix:///abs/socket/path`. |
| `JIUWENBOX_UDS_MODE` | `0666` | UDS socket file permissions (octal string). The Docker default is permissive so a non-root host user can connect; for multi-tenant / hardened deployments set `0660` and pass `docker run --user $(id -u):$(id -g)`. |
| `JIUWENBOX_UDS_HOST_DIR` | `/tmp/jiuwenbox-sock` | Host directory bind-mounted by `run_docker.sh` to expose the socket. |
| `JIUWENBOX_UDS_CONTAINER_DIR` | `/run/jiuwenbox` | Container-side mount point; must match the directory in `JIUWENBOX_LISTEN`'s socket path. |
@@ -513,6 +510,19 @@ Routes are differentiated by `path_prefix` (forwarding rules). Each route has **
**Creating routes via API requires valid `listen_host` and `listen_port > 0`**, otherwise returns an error.
+### Proxy-only mode
+
+When the policy YAML file **only configures `inference_privacy_proxies`** (top-level keys limited to `version` / `name` / `inference_privacy_proxies`, and `listen_port > 0`), jiuwenbox automatically enters proxy-only mode on startup:
+
+- The sandbox subsystem is skipped entirely (no `ProcessRuntime`, no zombie reaper, no idle reaper).
+- `GET /health` keeps working and reports `sandboxes_active = 0`.
+- Sandbox-side routes (`/api/v1/sandboxes/*`, `/api/v1/policy/*`) return `503 Service Unavailable` until the policy file adds sandbox configuration.
+- The proxy routes (`/api/v1/proxy/*`) and the inference proxy itself work normally.
+
+The startup log emits `Proxy-only policy detected (no sandbox config); skipping sandbox subsystem startup`, followed by `Inference privacy proxy listening on http://<host>:<port>` so operators can verify the listener address at a glance.
+
+See the reference config at [`configs/inference-policy.yaml`](configs/inference-policy.yaml).
+
### Proxy Configuration
Policy YAML configuration schema:
@@ -598,7 +608,7 @@ flag to maintain in sync:
```
`test.sh` does **not** start the server; launch jiuwenbox first on the
-selected transport (TCP with `JIUWENBOX_LISTEN=tcp://0.0.0.0:8321` or a
+selected transport (TCP with `JIUWENBOX_LISTEN=http://0.0.0.0:8321` or a
custom port, UDS with `JIUWENBOX_LISTEN=unix:///...`).
Run specific test-case:
diff --git a/jiuwenbox/README_CN.md b/jiuwenbox/README_CN.md
index 685464dd05..c8e79c072b 100644
--- a/jiuwenbox/README_CN.md
+++ b/jiuwenbox/README_CN.md
@@ -4,8 +4,9 @@
agent 工具和代码片段。
它提供一个 FastAPI 服务,用于管理沙箱生命周期、文件传输、文件
-列表/搜索以及命令执行。每个沙箱命令都会通过一个小型 supervisor
-进程启动,由 supervisor 根据配置好的隔离策略应用沙箱限制。
+列表/搜索以及命令执行。服务在自身进程内直接调用 `bubblewrap` 启动
+沙箱进程(每个沙箱一个长寿命 daemon,再加上按需的后台命令),由
+预先解析的策略决定隔离细节。
## 功能特性
@@ -25,14 +26,16 @@ agent 工具和代码片段。
- `server`
- FastAPI 应用,负责沙箱生命周期管理、policy 加载、审计日志和 API 路由。
- `server/runtime`
- - 运行时适配层,负责为每个沙箱命令启动一个 supervisor 进程。
+ - 进程内运行时适配层,将沙箱 policy 翻译成 `bubblewrap` 命令行后由
+ server 进程直接 spawn(每个沙箱一个长寿命 daemon,再加上按需的
+ 后台命令)。
- `server/proxy_manager`
- 管理推理隐私代理,用于 LLM API 路由和 API 密钥注入。
- `server/policy_reader`
- 共享 policy 文件读取器,供沙箱和代理管理器使用。
- `supervisor`
- - 每条命令的启动器,负责将生效的 policy 转换为 `bubblewrap`、Landlock、
- seccomp 和命名空间配置。
+ - 策略到隔离的翻译辅助库(`bubblewrap` 命令构造、Landlock payload、
+ seccomp 过滤器、cgroup/网络配置),供运行时适配层调用。
- `proxy`
- HTTP 推理隐私代理,支持路径路由和 API 密钥注入(支持 OpenAI 和 Anthropic 格式)。
- `models`
@@ -92,12 +95,6 @@ sudo env \
JIUWENBOX_POLICY_PATH=/absolute/path/to/policy.yaml
```
-如果进程管理器会使用环境变量渲染 uvicorn 命令,也可以设置:
-
-```bash
-JIUWENBOX_PORT=9000
-```
-
### Docker 启动
构建镜像:
@@ -123,7 +120,7 @@ loopback 端口冲突的场景。上层协议仍是 HTTP/1.1,路由 / 请求
监听地址由统一的环境变量 `JIUWENBOX_LISTEN` 控制,取以下两种形式之一:
```bash
-JIUWENBOX_LISTEN=tcp://0.0.0.0:8321 # 默认, 行为与历史一致
+JIUWENBOX_LISTEN=http://0.0.0.0:8321 # 默认
JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock # 切到 UDS, 路径必须绝对
```
@@ -167,7 +164,7 @@ jiuwenbox --base-url unix:///tmp/jiuwenbox-sock/jiuwenbox.sock health
JIUWENBOX_URL=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock jiuwenbox sandbox ls
# pytest 双通路 (操作者先各自起好对应的 server)
-pytest tests/integration --server-endpoint=tcp://127.0.0.1:8321
+pytest tests/integration --server-endpoint=http://127.0.0.1:8321
pytest tests/integration --server-endpoint=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock
```
@@ -175,7 +172,7 @@ UDS 相关环境变量:
| 变量 | 默认 | 说明 |
| --- | --- | --- |
-| `JIUWENBOX_LISTEN` | `tcp://0.0.0.0:8321` | 管理 API 监听 URI;接受 `tcp://host:port` 或 `unix:///abs/socket/path`。UDS 模式下 `JIUWENBOX_PORT` 被忽略。 |
+| `JIUWENBOX_LISTEN` | `http://0.0.0.0:8321` | 管理 API 监听 URI;接受 `http://host:port` 或 `unix:///abs/socket/path`。 |
| `JIUWENBOX_UDS_MODE` | `0666` | UDS socket 文件权限 (八进制字符串)。Docker 场景下宿主与容器内 uvicorn uid 通常不同,默认放开;多租户 / 强隔离场景建议显式 `JIUWENBOX_UDS_MODE=0660` 并 `docker run --user $(id -u):$(id -g)` 收紧。 |
| `JIUWENBOX_UDS_HOST_DIR` | `/tmp/jiuwenbox-sock` | `run_docker.sh` 把宿主 socket 目录挂载到容器内的位置。 |
| `JIUWENBOX_UDS_CONTAINER_DIR` | `/run/jiuwenbox` | 容器内挂载点,必须与 `JIUWENBOX_LISTEN` 里 socket 路径所在的目录一致。 |
@@ -493,6 +490,19 @@ sandbox:
**通过 API 创建路由需 `listen_host` 有效且 `listen_port > 0`**,否则返回错误。
+### 仅代理模式(proxy-only)
+
+如果 policy YAML 文件**只配置 `inference_privacy_proxies`**(顶层 key 仅允许 `version` / `name` / `inference_privacy_proxies`,且 `listen_port > 0`),jiuwenbox 启动时会自动进入仅代理模式:
+
+- 跳过沙箱子系统的初始化(不创建 `ProcessRuntime`、不注册 zombie reaper、不启动 idle reaper)。
+- `GET /health` 仍可用,`sandboxes_active` 固定为 `0`。
+- 沙箱相关路由(`/api/v1/sandboxes/*`、`/api/v1/policy/*`)返回 `503 Service Unavailable`,提示需要在 policy 里补充沙箱配置才能启用。
+- `/api/v1/proxy/*` 路由及推理代理本身正常工作。
+
+启动日志会打印 `Proxy-only policy detected (no sandbox config); skipping sandbox subsystem startup`,随后再输出 `Inference privacy proxy listening on http://<host>:<port>`,便于运维快速确认监听地址。
+
+参考配置:[`configs/inference-policy.yaml`](configs/inference-policy.yaml)。
+
### 代理配置
配置文件yaml文件说明:
@@ -583,7 +593,7 @@ inference_privacy_proxies:
```
注意 test.sh 本身**不会**起 server,请按选定通路先手工启动对应的 jiuwenbox
-(TCP 走 `JIUWENBOX_LISTEN=tcp://0.0.0.0:8321` 或自定义端口,UDS 走
+(TCP 走 `JIUWENBOX_LISTEN=http://0.0.0.0:8321` 或自定义端口,UDS 走
`JIUWENBOX_LISTEN=unix:///...`)。
运行指定测试用例:
diff --git a/jiuwenbox/cli/jiuwenbox.py b/jiuwenbox/cli/jiuwenbox.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/jiuwenbox/configs/code-agent-policy.yaml b/jiuwenbox/configs/code-agent-policy.yaml
index 9056d35eb4..70a07cec68 100644
--- a/jiuwenbox/configs/code-agent-policy.yaml
+++ b/jiuwenbox/configs/code-agent-policy.yaml
@@ -81,8 +81,6 @@ filesystem_policy:
device:
- host_path: "/dev/null"
sandbox_path: "/dev/null"
- - host_path: "/dev/tty"
- sandbox_path: "/dev/tty"
- host_path: "/dev/random"
sandbox_path: "/dev/random"
- host_path: "/dev/urandom"
diff --git a/jiuwenbox/configs/inference-policy.yaml b/jiuwenbox/configs/inference-policy.yaml
new file mode 100644
index 0000000000..4727b10105
--- /dev/null
+++ b/jiuwenbox/configs/inference-policy.yaml
@@ -0,0 +1,34 @@
+# Yuanrong (Edge/Remote) configuration.
+# This file extends the default policy with inference privacy proxy enabled.
+# The proxy runs on the edge server and routes LLM API requests.
+
+version: 1
+name: "inference-policy"
+
+inference_privacy_proxies:
+ listen_host: "0.0.0.0" # MUST, bind to all interfaces for edge server access
+ listen_port: 8322 # MUST, set to enable proxy. 0 or omit to disable.
+
+ # OPTIONAL: here starts example forwarding rule.
+ # routes can be configured with REST API dynamically instead.
+ routes:
+ # example OpenAI API route
+ - path_prefix: "openai"
+ target_endpoint: "https://api.openai.com"
+ api_key: "sk_sandbox_managed_key" # Set your sandbox-managed API key here
+ # example:
+ # curl -X POST http://127.0.0.1:8322/openai/v1/chat/completions \
+ # -H "Authorization: Bearer sk_fake_key" ...
+ # ==> https://api.openai.com/v1/chat/completions \
+ # -H "Authorization: Bearer sk_sandbox_managed_key" ...
+
+ # example Custom LLM endpoint
+ - path_prefix: "custom"
+ target_endpoint: "http://192.168.1.100:9000"
+ api_key: "sk_sandbox_managed_key"
+ skip_cert_verify: false # for self_signed cert server, debug only
+ # example:
+ # curl -X POST http://127.0.0.1:8322/custom/v1/chat/completions \
+ # -H "Authorization: Bearer sk_fake_key" ...
+ # ==> http://192.168.1.100:9000/v1/chat/completions
+ # -H "Authorization: Bearer sk_sandbox_managed_key" ...
diff --git a/jiuwenbox/configs/yuanrong.yaml b/jiuwenbox/configs/yuanrong.yaml
deleted file mode 100644
index fef82e3cde..0000000000
--- a/jiuwenbox/configs/yuanrong.yaml
+++ /dev/null
@@ -1,332 +0,0 @@
-# Yuanrong (Edge/Remote) configuration.
-# This file extends the default policy with inference privacy proxy enabled.
-# The proxy runs on the edge server and routes LLM API requests.
-
-version: 1
-name: "yuanrong-default"
-
-# Host directory used for server-managed sandbox backing storage.
-sandbox_workspace: "/sandbox"
-
-# Filesystem access rules. Paths are sandbox-visible absolute paths.
-filesystem_policy:
- # Lifecycle directories to create for the sandbox and bind into the sandbox path.
- # Items may be either:
- # - "/path": create a server-managed directory with default permissions
- # - path: "/path"
- # permissions: "0755" # optional octal permissions applied on the backing directory
- # The permissions value may be quoted or numeric, but quoted octal strings are recommended.
- # Paths must be absolute sandbox-visible paths. Directories persist for the sandbox
- # lifecycle and are removed when the sandbox is deleted. Access is still controlled
- # by the directory permissions and Landlock.
- directories:
- - path: "/home"
- permissions: "0777"
- - path: "/tmp"
- permissions: "1777"
-
- # Read-only paths inside the sandbox. These entries grant read permission only;
- # they do not mount host paths by themselves.
- read_only:
- - "/"
- - "/bin"
- - "/sbin"
- - "/usr"
- - "/lib"
- - "/lib64"
- - "/etc"
- - "/opt"
-
- # Read-write paths inside the sandbox. Use directories or bind_mounts to make
- # these paths exist in the sandbox.
- read_write:
- - "/home"
- - "/tmp"
-
- # Extra bind mounts from host into sandbox.
- # Each item uses:
- # host_path: absolute path on the host
- # sandbox_path: absolute path visible inside the sandbox
- # mode: "ro" for read-only or "rw" for read-write
- bind_mounts:
- - host_path: "/bin"
- sandbox_path: "/bin"
- mode: "ro"
- - host_path: "/sbin"
- sandbox_path: "/sbin"
- mode: "ro"
- - host_path: "/usr"
- sandbox_path: "/usr"
- mode: "ro"
- - host_path: "/lib"
- sandbox_path: "/lib"
- mode: "ro"
- - host_path: "/lib64"
- sandbox_path: "/lib64"
- mode: "ro"
- - host_path: "/etc/resolv.conf"
- sandbox_path: "/etc/resolv.conf"
- mode: "ro"
- - host_path: "/etc/hosts"
- sandbox_path: "/etc/hosts"
- mode: "ro"
- - host_path: "/etc/nsswitch.conf"
- sandbox_path: "/etc/nsswitch.conf"
- mode: "ro"
- - host_path: "/etc/host.conf"
- sandbox_path: "/etc/host.conf"
- mode: "ro"
- - host_path: "/etc/ssl/certs"
- sandbox_path: "/etc/ssl/certs"
- mode: "ro"
- - host_path: "/etc/pki"
- sandbox_path: "/etc/pki"
- mode: "ro"
- - host_path: "/opt"
- sandbox_path: "/opt"
- mode: "ro"
-
- # Device nodes to expose inside the sandbox with bwrap --dev-bind.
- # Each item uses:
- # host_path: absolute device path on the host
- # sandbox_path: absolute path visible inside the sandbox
- device:
- - host_path: "/dev/urandom"
- sandbox_path: "/dev/urandom"
- - host_path: "/dev/null"
- sandbox_path: "/dev/null"
-
-# Process identity inside the sandbox.
-process:
- # User name to run as. If the user cannot be resolved, runtime falls back to nobody-style IDs.
- run_as_user: sandbox
-
- # Group name to run as. If the group cannot be resolved, runtime falls back to nobody-style IDs.
- run_as_group: sandbox
-
-# Linux namespace isolation controlled by bubblewrap.
-namespace:
- # user:
- # true: create a new user namespace
- # false: reuse the current user namespace
- user: true
-
- # pid:
- # true: create a new PID namespace
- # false: reuse the current PID namespace
- pid: true
-
- # ipc:
- # true: create a new IPC namespace
- # false: reuse the current IPC namespace
- ipc: true
-
- # cgroup:
- # true: create a new cgroup namespace
- # false: reuse the current cgroup namespace
- cgroup: true
-
- # uts:
- # true: create a new UTS namespace
- # false: reuse the current UTS namespace
- uts: true
-
-# Linux capability rules applied by bubblewrap.
-capabilities:
- # Capabilities to add, for example ["CAP_NET_RAW"] or ["NET_RAW"].
- add: []
-
- # Capabilities to drop. "ALL" drops all capabilities when supported by bubblewrap.
- drop: []
-
-# Landlock filesystem access enforcement.
-landlock:
- # compatibility:
- # disabled: do not apply Landlock
- # best_effort: apply Landlock when supported, otherwise continue
- # hard_requirement: fail sandbox startup if Landlock is unavailable
- compatibility: best_effort
-
-# Seccomp syscall filtering.
-syscall:
- # Syscall names to block on x86_64. Leave empty to disable explicit syscall blocking.
- x86_64:
- blocked:
- - "kexec_load"
- - "kexec_file_load"
- - "reboot"
- - "pivot_root"
- - "swapon"
- - "swapoff"
- - "nfsservctl"
- - "lookup_dcookie"
- - "ptrace"
- - "mount"
- - "umount2"
- - "unshare"
- - "setns"
- - "userfaultfd"
- - "perf_event_open"
- - "bpf"
- - "add_key"
- - "request_key"
- - "keyctl"
- - "io_uring_setup"
- - "io_uring_enter"
- - "io_uring_register"
- - "open_by_handle_at"
- - "name_to_handle_at"
- - "init_module"
- - "finit_module"
- - "delete_module"
- - "acct"
- # Syscall names to block on arm64/aarch64.
- arm64:
- blocked:
- - "kexec_load"
- - "kexec_file_load"
- - "reboot"
- - "pivot_root"
- - "swapon"
- - "swapoff"
- - "nfsservctl"
- - "lookup_dcookie"
- - "ptrace"
- - "mount"
- - "umount2"
- - "unshare"
- - "setns"
- - "userfaultfd"
- - "perf_event_open"
- - "bpf"
- - "add_key"
- - "request_key"
- - "keyctl"
- - "io_uring_setup"
- - "io_uring_enter"
- - "io_uring_register"
- - "open_by_handle_at"
- - "name_to_handle_at"
- - "init_module"
- - "finit_module"
- - "delete_module"
- - "acct"
-
-# Network policy. Egress controls outbound traffic; ingress controls inbound traffic.
-network:
- # mode:
- # isolated: create a dedicated network namespace and apply these rules
- # host: use host networking and skip namespace firewall setup
- mode: host
-
- # Outbound traffic from sandbox to outside destinations.
- egress:
- # default:
- # deny: block traffic unless it matches allowed_domains/allowed_ips and allowed_ports
- # allow: allow traffic unless it matches blocked_domains/blocked_ips/blocked_ports
- default: allow
-
- # Domain names allowed as outbound destinations. Wildcards like "*.example.com" are accepted
- # by resolving the base domain; rules are applied to resolved IPs.
- allowed_domains:
- - "baidu.com"
-
- # Domain names blocked as outbound destinations. Block rules take precedence over allow rules.
- blocked_domains:
- - "ip.me"
-
- # IP/CIDR ranges allowed as outbound destinations, for example "203.0.113.10/32" or
- # "10.0.0.0/8". With default: deny, destinations not listed here are blocked.
- allowed_ips:
- - "127.0.0.1/32"
- - "::1/128"
-
- # IP/CIDR ranges blocked as outbound destinations. Block rules take precedence.
- blocked_ips:
- - "169.254.169.254/32"
-
- # TCP destination ports allowed for outbound traffic when default is deny.
- allowed_ports:
- - 443
- - 80
-
- # TCP destination ports blocked for outbound traffic. Block rules take precedence.
- blocked_ports:
- - 22
-
- # Inbound traffic from outside sources into the sandbox.
- ingress:
- # default:
- # deny: block traffic unless it matches allowed_domains/allowed_ips and allowed_ports
- # allow: allow traffic unless it matches blocked_domains/blocked_ips/blocked_ports
- default: deny
-
- # Domain names allowed as inbound sources. These are resolved to source IP rules.
- allowed_domains:
- - "localhost"
-
- # Domain names blocked as inbound sources. Block rules take precedence over allow rules.
- blocked_domains: []
-
- # IP/CIDR ranges allowed as inbound sources. With default: deny, sources not listed here
- # are blocked unless allowed by allowed_ports-only rules.
- allowed_ips:
- - "127.0.0.1/32"
- - "::1/128"
-
- # IP/CIDR ranges blocked as inbound sources. Block rules take precedence.
- blocked_ips: []
-
- # TCP destination ports allowed for inbound traffic when default is deny.
- allowed_ports:
- - 8322
-
- # TCP destination ports blocked for inbound traffic. Block rules take precedence.
- blocked_ports:
- - 22
-
-# Inference privacy proxy configuration.
-# Single listen_port. Each route defines a path prefix representing a forward rule.
-#
-# The proxy runs on the edge server. Clients connect to:
-# http://<listening_host>:<listening_port>/<path_prefix>/<api_path>
-# ==>
-# <target_endpoint>/<api_path>
-#
-# API key injection:
-# OpenAI format: "Authorization: Bearer <placeholder>"
-# ==> "Authorization: Bearer sk_sandbox_managed_key"
-# Anthropic format: "X-Api-Key: <placeholder>"
-# ==> "X-Api-Key: sk_sandbox_managed_key"
-#
-# Example jiuwenswarm config:
-# api_base: http://192.168.1.100:9000/v1/ ==> http://127.0.0.1:8322/llm_proxy/v1/
-# api_key: sk-real_key ==> sk-fake_key
-
-inference_privacy_proxies:
- listen_host: "0.0.0.0" # MUST, bind to all interfaces for edge server access
- listen_port: 8322 # MUST, set to enable proxy. 0 or omit to disable.
-
- # OPTIONAL: here starts example forwarding rule.
- # routes can be configured with REST API dynamically instead.
- routes:
- # example OpenAI API route
- - path_prefix: "openai"
- target_endpoint: "https://api.openai.com"
- api_key: "sk_sandbox_managed_key" # Set your sandbox-managed API key here
- # example:
- # curl -X POST http://127.0.0.1:8322/openai/v1/chat/completions \
- # -H "Authorization: Bearer sk_fake_key" ...
- # ==> https://api.openai.com/v1/chat/completions \
- # -H "Authorization: Bearer sk_sandbox_managed_key" ...
-
- # example Custom LLM endpoint
- - path_prefix: "custom"
- target_endpoint: "http://192.168.1.100:9000"
- api_key: "sk_sandbox_managed_key"
- skip_cert_verify: false # for self_signed cert server, debug only
- # example:
- # curl -X POST http://127.0.0.1:8322/custom/v1/chat/completions \
- # -H "Authorization: Bearer sk_fake_key" ...
- # ==> http://192.168.1.100:9000/v1/chat/completions
- # -H "Authorization: Bearer sk_sandbox_managed_key" ...
diff --git a/jiuwenbox/docker/Dockerfile b/jiuwenbox/docker/Dockerfile
index 4d31b37953..84d98998e7 100644
--- a/jiuwenbox/docker/Dockerfile
+++ b/jiuwenbox/docker/Dockerfile
@@ -39,8 +39,8 @@ RUN ln -s /usr/bin/python3 /usr/bin/python
EXPOSE 8321
EXPOSE 8322
-# 默认走 TCP, 行为与历史一致; UDS 模式由调用方覆盖 JIUWENBOX_LISTEN, 例如
+# 默认走 HTTP; UDS 模式由调用方覆盖 JIUWENBOX_LISTEN, 例如
# `docker run -e JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \
# -v /tmp/jiuwenbox-sock:/run/jiuwenbox jiuwenbox`。
-ENV JIUWENBOX_LISTEN=tcp://0.0.0.0:8321
+ENV JIUWENBOX_LISTEN=http://0.0.0.0:8321
CMD ["python3", "-m", "jiuwenbox.server.launcher"]
diff --git a/jiuwenbox/docs/jiuwenbox_server_api.md b/jiuwenbox/docs/jiuwenbox_server_api.md
index 1ebb5e02bd..fd2dfc5462 100644
--- a/jiuwenbox/docs/jiuwenbox_server_api.md
+++ b/jiuwenbox/docs/jiuwenbox_server_api.md
@@ -220,7 +220,6 @@ print(resp.json())
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
-| `workdir` | string/null | 否 | 兼容字段 |
| `env` | object | 否 | 沙箱公共环境变量 |
| `policy` | object/null | 否 | 覆盖或追加的 policy 数据 |
| `policy_mode` | string | 否 | `override` 或 `append`,默认 `override` |
@@ -753,6 +752,73 @@ print(resp.json())
}
```
+### 查询 timeout 配置
+
+接口:`GET /api/v1/timeout`
+
+用途:返回服务级别的空闲沙箱回收 (idle reaper) 当前生效的配置,
+对应 `policy.timeout`。`idle_timeout` 为 `null` 表示 reaper 已关闭。
+
+Python 请求示例:
+
+```python
+import requests
+
+resp = requests.get("http://127.0.0.1:8321/api/v1/timeout", timeout=30)
+print(resp.json())
+```
+
+响应示例:
+
+```json
+{
+ "idle_timeout": 1800,
+ "idle_check_interval": 60
+}
+```
+
+### 更新 timeout 配置
+
+接口:`PUT /api/v1/timeout`
+
+用途:原子更新 idle reaper 的一个或两个字段,并立即重启 reaper。
+请求体里**仅显式出现的字段会被应用**,省略的字段保留当前值,
+所以可以单独翻 `idle_timeout` 而不影响 `idle_check_interval`。
+
+请求字段:
+
+| 字段 | 类型 | 说明 |
+| --- | --- | --- |
+| `idle_timeout` | number 或 `null` | 空闲超时秒数。`null` 或 `<= 0` 关闭 reaper。可省略以保留当前值。 |
+| `idle_check_interval` | number | reaper 轮询间隔秒数,必须 `> 0`;**不允许** `null`,省略字段以保留当前值。 |
+
+Python 请求示例:
+
+```python
+import requests
+
+resp = requests.put(
+ "http://127.0.0.1:8321/api/v1/timeout",
+ json={"idle_timeout": 1200},
+ timeout=30,
+)
+print(resp.status_code)
+print(resp.json())
+```
+
+响应示例(成功,返回更新后的完整 `TimeoutPolicy`):
+
+```json
+{
+ "idle_timeout": 1200,
+ "idle_check_interval": 60
+}
+```
+
+校验失败(如 `idle_check_interval <= 0`,或显式传入
+`idle_check_interval: null`)返回 `400 Bad Request`,body 中包含
+具体错误描述。
+
## 代理接口
代理接口用于管理 inference privacy proxy。
diff --git a/jiuwenbox/scripts/run_docker.sh b/jiuwenbox/scripts/run_docker.sh
index 1e5178b74f..6bab2ea560 100755
--- a/jiuwenbox/scripts/run_docker.sh
+++ b/jiuwenbox/scripts/run_docker.sh
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
-set -euox pipefail
+set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
@@ -18,9 +18,9 @@ PROXY_PORT="${JIUWENBOX_PROXY_PORT:-8322}"
# ``JIUWENBOX_LISTEN`` / ``JIUWENBOX_UDS_MODE`` / ``JIUWENBOX_UDS_HOST_DIR`` /
# ``JIUWENBOX_UDS_CONTAINER_DIR``, 这些才是用户在 README 里设的那一份。
-# 管理 API listen URI: 默认与 Dockerfile 一致走 TCP; 设成 unix:///abs/path
+# 管理 API listen URI: 默认与 Dockerfile 一致走 HTTP; 设成 unix:///abs/path
# 即切到 UDS, 容器内 uvicorn 监听 socket 文件, 由下面 ``-v`` 把宿主目录挂进去。
-LISTEN_URI="${JIUWENBOX_LISTEN:-tcp://0.0.0.0:8321}"
+LISTEN_URI="${JIUWENBOX_LISTEN:-http://0.0.0.0:8321}"
# UDS chmod (lifespan 会读); 默认 0666 便于宿主非 root 直接访问, 多租户场景
# 可显式 ``JIUWENBOX_UDS_MODE=0660`` + ``docker run --user`` 收紧。
UDS_MODE="${JIUWENBOX_UDS_MODE:-}"
@@ -57,7 +57,7 @@ Options:
setting JIUWENBOX_SAVE_LOGS_HOST_DIR; the CLI
flag wins when both are present.
-Examples (TCP, default):
+Examples (HTTP, default):
scripts/run_docker.sh
scripts/run_docker.sh configs/default-policy.yaml
JIUWENBOX_HOST_PORT=18321 scripts/run_docker.sh
@@ -136,19 +136,19 @@ if [[ $# -gt 0 ]]; then
esac
fi
-# 解析 listen URI: tcp:// 或 unix:///abs/path; 其它形态拒绝。
+# 解析 listen URI: http:// 或 unix:///abs/path; 其它形态拒绝。
LISTEN_MODE=""
LISTEN_SOCKET_PATH=""
case "$LISTEN_URI" in
- tcp://*)
- LISTEN_MODE="tcp"
+ http://*)
+ LISTEN_MODE="http"
;;
unix:///*)
LISTEN_MODE="uds"
LISTEN_SOCKET_PATH="${LISTEN_URI#unix://}"
;;
*)
- echo "error: JIUWENBOX_LISTEN must start with tcp:// or unix:///, got '$LISTEN_URI'" >&2
+ echo "error: JIUWENBOX_LISTEN must start with http:// or unix:///, got '$LISTEN_URI'" >&2
exit 1
;;
esac
@@ -156,8 +156,8 @@ esac
echo "Starting jiuwenbox container:"
echo " image: $IMAGE_REF"
echo " container: $CONTAINER_NAME"
-if [[ "$LISTEN_MODE" = "tcp" ]]; then
- echo " listen: tcp -> http://127.0.0.1:${HOST_PORT}"
+if [[ "$LISTEN_MODE" = "http" ]]; then
+ echo " listen: http -> http://127.0.0.1:${HOST_PORT}"
DOCKER_PORT_ARGS+=(-p "${HOST_PORT}:8321")
else
echo " listen: uds -> ${UDS_HOST_DIR}/$(basename "$LISTEN_SOCKET_PATH")"
@@ -178,6 +178,7 @@ fi
# 代理端口在两种模式下都映射: Inference Privacy Proxy 是独立 TCP listener,
# 与管理 API 传输方式无关; 即便管理面走 UDS, 代理仍可能需要从宿主转出流量。
DOCKER_PORT_ARGS+=(-p "${PROXY_PORT}:8322")
+echo " proxy: http://127.0.0.1:${PROXY_PORT} (inference privacy proxy)"
# 把 listen / uds-mode 显式 -e 给容器, 让容器 entrypoint 拿到一致的视图。
# 注意: 这里 -e 后面的"键名"必须仍是 JIUWENBOX_LISTEN / JIUWENBOX_UDS_MODE,
diff --git a/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py b/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py
index 9eb7d5f160..fe5fd56f2d 100644
--- a/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py
+++ b/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py
@@ -298,7 +298,6 @@ class _CliClient:
env: dict[str, str] | None = None,
policy: Any = None,
policy_mode: str | None = None,
- workdir: str | None = None,
) -> dict[str, Any]:
body: dict[str, Any] = {}
if env is not None:
@@ -307,8 +306,6 @@ class _CliClient:
body["policy"] = policy
if policy_mode is not None:
body["policy_mode"] = policy_mode
- if workdir is not None:
- body["workdir"] = workdir
return dict(self._post(f"{_API_PREFIX}/sandboxes", json=body).json())
def sandbox_list(self) -> list[dict[str, Any]]:
diff --git a/jiuwenbox/src/jiuwenbox/models/sandbox.py b/jiuwenbox/src/jiuwenbox/models/sandbox.py
index 0cd7c976c8..85e8eeb3c8 100644
--- a/jiuwenbox/src/jiuwenbox/models/sandbox.py
+++ b/jiuwenbox/src/jiuwenbox/models/sandbox.py
@@ -24,7 +24,6 @@ class PolicyMode(str, enum.Enum):
class SandboxSpec(BaseModel):
"""Specification for creating a sandbox."""
- workdir: str | None = None
env: dict[str, str] = Field(default_factory=dict)
diff --git a/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy.py b/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy.py
index 1e052d8811..d800fb089e 100644
--- a/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy.py
+++ b/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy.py
@@ -145,10 +145,6 @@ class InferencePrivacyProxy:
normalized = path_prefix.rstrip("/")
return normalized in self._enabled_routes
- def get_enabled_routes(self) -> list[str]:
- """Get list of enabled route path_prefixes."""
- return list(self._enabled_routes)
-
def _log(self, message: str) -> None:
logger.info(message)
if self._log_callback:
@@ -445,16 +441,3 @@ class InferencePrivacyProxy:
self._serve_task = None
self._log("HTTP proxy stopped")
-
-
-def default_proxy_config() -> InferencePrivacyProxyConfig:
- return InferencePrivacyProxyConfig(
- listen_port=8080,
- routes=[
- ProxyRoute(
- path_prefix="/openai",
- target_endpoint="https://api.openai.com",
- api_key="sk-sandbox-key",
- ),
- ],
- )
diff --git a/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy_manager.py b/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy_manager.py
index d4b9ffa379..4efa265197 100644
--- a/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy_manager.py
+++ b/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy_manager.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import asyncio
import logging
-import subprocess
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
@@ -36,7 +35,6 @@ class ProxyInstance:
config: InferencePrivacyProxyConfig
state: ProxyState = ProxyState.STOPPED
proxy: InferencePrivacyProxy | None = None
- subprocess: subprocess.Popen | None = None
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
started_at: datetime | None = None
error_message: str | None = None
diff --git a/jiuwenbox/src/jiuwenbox/proxy/ipp_launcher.py b/jiuwenbox/src/jiuwenbox/proxy/ipp_launcher.py
deleted file mode 100644
index 1ee2e2fe14..0000000000
--- a/jiuwenbox/src/jiuwenbox/proxy/ipp_launcher.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""Standalone inference privacy proxy launcher.
-
-This script is executed inside a network namespace to start the HTTP proxy.
-The proxy listens on 127.0.0.1 inside that namespace, making it only
-accessible to processes within the same namespace.
-
-Usage:
- python3 -m jiuwenbox.proxy.ipp_launcher --config <json_config>
-"""
-
-from __future__ import annotations
-
-import argparse
-import asyncio
-import json
-import logging
-import signal
-
-from jiuwenbox.logging_config import configure_logging
-from jiuwenbox.proxy.inference_privacy_proxy import InferencePrivacyProxyConfig, ProxyRoute, InferencePrivacyProxy
-
-configure_logging()
-logger = logging.getLogger(__name__)
-
-_proxy: InferencePrivacyProxy | None = None
-
-
-def _signal_handler(sig: int, frame: object) -> None:
- """Handle shutdown signals."""
- logger.info("Received signal %d, shutting down...", sig)
- if _proxy:
- asyncio.create_task(_proxy.stop())
-
-
-def main() -> None:
- parser = argparse.ArgumentParser(description="Launch HTTP inference privacy proxy")
- parser.add_argument("--config", required=True, help="JSON configuration for the proxy")
- parser.add_argument("--namespace", default=None, help="Network namespace name (for logging)")
- args = parser.parse_args()
-
- signal.signal(signal.SIGTERM, _signal_handler)
- signal.signal(signal.SIGINT, _signal_handler)
-
- config_json = json.loads(args.config)
-
- routes = [
- ProxyRoute(
- path_prefix=r["path_prefix"],
- target_endpoint=r["target_endpoint"],
- api_key=r.get("api_key", ""),
- skip_cert_verify=r.get("skip_cert_verify", False),
- )
- for r in config_json.get("routes", [])
- ]
-
- config = InferencePrivacyProxyConfig(
- listen_port=config_json.get("listen_port", 8080),
- routes=routes,
- )
-
- global _proxy
- _proxy = InferencePrivacyProxy(config)
-
- async def run():
- await _proxy.start()
- logger.info(
- "HTTP IPP running in namespace '%s': 127.0.0.1:%d with %d routes",
- args.namespace or "default",
- config.listen_port,
- len(routes),
- )
- while _proxy.is_running:
- await asyncio.sleep(1)
-
- asyncio.run(run())
-
-
-if __name__ == "__main__":
- main()
diff --git a/jiuwenbox/src/jiuwenbox/server/app.py b/jiuwenbox/src/jiuwenbox/server/app.py
index c4bc8c748c..d27376fe57 100644
--- a/jiuwenbox/src/jiuwenbox/server/app.py
+++ b/jiuwenbox/src/jiuwenbox/server/app.py
@@ -10,7 +10,7 @@ from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
from pathlib import Path
-from fastapi import FastAPI, Request
+from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import ValidationError
@@ -23,6 +23,7 @@ from jiuwenbox.server.sandbox_manager import (
SandboxNotFoundError,
SandboxStateError,
)
+from jiuwenbox.server.policy_reader import PolicyReader
from jiuwenbox.server.proxy_manager import ProxyManager
from jiuwenbox.server.policy_engine import PolicyValidationError
from jiuwenbox.server.runtime.process import enable_child_subreaper
@@ -41,6 +42,12 @@ logger = logging.getLogger(__name__)
_sandbox_manager: SandboxManager | None = None
_proxy_manager: ProxyManager | None = None
+# Set during lifespan startup when the policy file only configures
+# ``inference_privacy_proxies``. In that mode we intentionally skip
+# building a ``SandboxManager``; ``get_sandbox_manager`` consults this
+# flag to surface a clean 503 instead of lazily constructing one on
+# the first sandbox-API call.
+_proxy_only_mode: bool = False
# Every sandbox API call that talks to the in-sandbox daemon (exec, write_file,
# read_file, list_dir) is dispatched via ``loop.run_in_executor(None, ...)``
@@ -122,7 +129,7 @@ def _configure_loop_default_executor() -> None:
)
-def _build_sandbox_manager() -> SandboxManager:
+def _build_sandbox_manager(policy_reader: PolicyReader | None = None) -> SandboxManager:
"""Construct the global ``SandboxManager``, honoring ``--save-logs DIR``.
Behaviour matrix:
@@ -156,7 +163,7 @@ def _build_sandbox_manager() -> SandboxManager:
"audit JSONL.",
ENV_SAVE_LOGS_DIR,
)
- return SandboxManager()
+ return SandboxManager(policy_reader=policy_reader)
save_dir = Path(save_dir_raw).expanduser()
try:
save_dir.mkdir(parents=True, exist_ok=True)
@@ -168,27 +175,34 @@ def _build_sandbox_manager() -> SandboxManager:
"Cannot create %s=%s (%s); falling back to disabled log persistence",
ENV_SAVE_LOGS_DIR, save_dir_raw, exc,
)
- return SandboxManager()
+ return SandboxManager(policy_reader=policy_reader)
logger.info("Per-sandbox audit log will be saved under %s", save_dir)
return SandboxManager(
audit_logger=AuditLogger(log_dir=save_dir, filename_strategy="timestamped"),
+ policy_reader=policy_reader,
)
def get_sandbox_manager() -> SandboxManager:
global _sandbox_manager
if _sandbox_manager is None:
+ if _proxy_only_mode:
+ # Refuse to lazily resurrect the sandbox subsystem when the
+ # operator explicitly opted into proxy-only mode. The route
+ # handler will see this as a clean 503 via the exception
+ # handler registered in ``create_app``.
+ raise HTTPException(
+ status_code=503,
+ detail=(
+ "Sandbox subsystem is disabled: policy only configures "
+ "inference_privacy_proxies. Add sandbox configuration "
+ "to the policy file to enable sandbox APIs."
+ ),
+ )
_sandbox_manager = _build_sandbox_manager()
return _sandbox_manager
-def get_proxy_manager() -> ProxyManager:
- global _proxy_manager
- if _proxy_manager is None:
- _proxy_manager = ProxyManager()
- return _proxy_manager
-
-
def _chmod_uds_socket_if_any() -> None:
"""启动后给 UDS socket 文件打权限位.
@@ -224,7 +238,7 @@ def _chmod_uds_socket_if_any() -> None:
@asynccontextmanager
async def lifespan(_application: FastAPI):
- global _sandbox_manager, _proxy_manager
+ global _sandbox_manager, _proxy_manager, _proxy_only_mode
# Both of these have to run after uvicorn has spun up its event loop -
# ``set_default_executor`` requires a running loop, and raising NOFILE is
# only effective within the live process. They are also independent of
@@ -232,38 +246,54 @@ async def lifespan(_application: FastAPI):
# already benefits from the larger executor.
_raise_open_file_limit()
_configure_loop_default_executor()
- # Become the subreaper for our descendant tree *before* any sandbox
- # spawns bwrap. PR_SET_CHILD_SUBREAPER only affects *future* children,
- # so doing it here (after the loop is up but before SandboxManager
- # might create a runtime that spawns bwrap) is the earliest safe point.
- # No-op on non-Linux / when prctl is denied; logs internally.
- enable_child_subreaper()
- _sandbox_manager = _build_sandbox_manager()
- _proxy_manager = ProxyManager()
- # Wire the SIGCHLD-driven zombie reaper onto the running uvicorn loop.
- # This must happen after ``_build_sandbox_manager`` (so a runtime is
- # constructed and can publish its ``register_zombie_reaper`` method)
- # but before ``_proxy_manager.start`` (which may itself fork helper
- # processes whose orphans we now want reaped). Failure is non-fatal:
- # the manager logs and the server keeps running; zombies just won't
- # be cleaned up automatically until the next ``stop()``/``cleanup()``.
- try:
- loop = asyncio.get_running_loop()
- _sandbox_manager.register_zombie_reaper(loop)
- except Exception: # noqa: BLE001
- logger.exception(
- "register_zombie_reaper failed during lifespan startup; bwrap "
- "<defunct> processes may accumulate under the box-server pid",
- )
- # 起 idle sandbox reaper: 只在 root policy 的 ``timeout.idle_timeout`` 显式
- # 配置时生效, 否则是 no-op (默认禁用), 跟未引入本特性前行为完全等价。
- try:
- _sandbox_manager.start_idle_reaper()
- except Exception: # noqa: BLE001
- logger.exception(
- "start_idle_reaper failed during lifespan startup; idle sandboxes "
- "will not be auto-reaped",
+ # Share a single ``PolicyReader`` between the proxy and sandbox subsystems
+ # so the YAML file is parsed once. ``is_proxy_only`` re-reads the file,
+ # but the cost is negligible and the alternative (pre-loading the parsed
+ # SecurityPolicy here) would force every caller through this object too.
+ policy_reader = PolicyReader()
+ _proxy_only_mode = policy_reader.is_proxy_only()
+ if _proxy_only_mode:
+ # Proxy-only deployment: the operator configured only the inference
+ # privacy router, so we skip every sandbox-side moving part (no
+ # ``ProcessRuntime``, no subreaper, no idle/zombie reapers, no
+ # state-dir scrubbing). The ``/health`` endpoint and sandbox routes
+ # still work; they just observe ``_sandbox_manager is None`` and
+ # report "no sandboxes" / 503 respectively.
+ logger.info(
+ "Proxy-only policy detected (no sandbox config); skipping "
+ "sandbox subsystem startup",
)
+ else:
+ # Become the subreaper for our descendant tree *before* any sandbox
+ # spawns bwrap. PR_SET_CHILD_SUBREAPER only affects *future*
+ # children, so doing it here (after the loop is up but before
+ # SandboxManager might create a runtime that spawns bwrap) is the
+ # earliest safe point. No-op on non-Linux / when prctl is denied;
+ # logs internally.
+ enable_child_subreaper()
+ _sandbox_manager = _build_sandbox_manager(policy_reader=policy_reader)
+ # Wire the SIGCHLD-driven zombie reaper onto the running uvicorn
+ # loop. Failure is non-fatal: the manager logs and the server keeps
+ # running; zombies just won't be cleaned up automatically until the
+ # next ``stop()``/``cleanup()``.
+ try:
+ loop = asyncio.get_running_loop()
+ _sandbox_manager.register_zombie_reaper(loop)
+ except Exception: # noqa: BLE001
+ logger.exception(
+ "register_zombie_reaper failed during lifespan startup; bwrap "
+ "<defunct> processes may accumulate under the box-server pid",
+ )
+ # 起 idle sandbox reaper: 只在 root policy 的 ``timeout.idle_timeout``
+ # 显式配置时生效, 否则是 no-op (默认禁用), 跟未引入本特性前行为完全等价。
+ try:
+ _sandbox_manager.start_idle_reaper()
+ except Exception: # noqa: BLE001
+ logger.exception(
+ "start_idle_reaper failed during lifespan startup; idle sandboxes "
+ "will not be auto-reaped",
+ )
+ _proxy_manager = ProxyManager(policy_reader=policy_reader)
logger.info("box-server started (version %s)", __version__)
await _proxy_manager.start()
# 在 proxy 起来之后、yield (接受请求) 之前给 UDS 打权限: 此刻 uvicorn 已
@@ -327,6 +357,12 @@ async def lifespan(_application: FastAPI):
logger.exception(
"sandbox_manager.unregister_zombie_reaper failed during lifespan shutdown",
)
+ # Reset the proxy-only flag so subsequent in-process boots (most
+ # notably the unit-test harness, which spins up create_app() many
+ # times) start from a clean slate; otherwise a previous run with
+ # an inference-only policy would force later sandbox-mode runs
+ # through the 503 short-circuit in ``get_sandbox_manager``.
+ _proxy_only_mode = False
logger.info("box-server shutting down")
@@ -406,9 +442,16 @@ def create_app() -> FastAPI:
from jiuwenbox.models.common import HealthResponse
from jiuwenbox.supervisor.landlock import detect_landlock_abi
- mgr = get_sandbox_manager()
- sandboxes = await mgr.list_sandboxes()
- active = sum(1 for s in sandboxes if s.phase.value == "ready")
+ # Proxy-only deployments never construct a SandboxManager. Reading
+ # the module global directly (instead of going through
+ # ``get_sandbox_manager``) avoids lazily spinning up
+ # ``ProcessRuntime`` from inside ``/health`` and lets us report
+ # zero active sandboxes truthfully.
+ if _sandbox_manager is None:
+ active = 0
+ else:
+ sandboxes = await _sandbox_manager.list_sandboxes()
+ active = sum(1 for s in sandboxes if s.phase.value == "ready")
return HealthResponse(
version=__version__,
diff --git a/jiuwenbox/src/jiuwenbox/server/audit_logger.py b/jiuwenbox/src/jiuwenbox/server/audit_logger.py
index 5bd86c5c5c..7d8bbf87c2 100644
--- a/jiuwenbox/src/jiuwenbox/server/audit_logger.py
+++ b/jiuwenbox/src/jiuwenbox/server/audit_logger.py
@@ -11,8 +11,6 @@ construction time:
developers can wire it into stderr if needed) and ``read_logs*``
returns empty. This keeps a fresh jiuwenbox install from polluting
the user's home dir; opt in via ``--save-logs DIR``.
-- ``"plain"``: ``{sandbox_id}.log`` (legacy layout, useful for embedders
- who manage their own retention; not selected by the bundled server).
- ``"timestamped"``: ``{sandbox_id}-{YYYYMMDDTHHMMSS}.audit.log``. The
timestamp is captured the **first** time a given sandbox is logged and
cached for the rest of the process lifetime, so all events for a single
diff --git a/jiuwenbox/src/jiuwenbox/server/launcher.py b/jiuwenbox/src/jiuwenbox/server/launcher.py
index 2027dfb53c..8829839cf6 100644
--- a/jiuwenbox/src/jiuwenbox/server/launcher.py
+++ b/jiuwenbox/src/jiuwenbox/server/launcher.py
@@ -1,10 +1,10 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""jiuwenbox server 启动器 (TCP / UDS 二选一).
+"""jiuwenbox server 启动器 (HTTP / UDS 二选一).
承担两件事:
1. 把 "怎么 listen" 从 ``Dockerfile`` 命令行硬编码解耦, 改由 ``JIUWENBOX_LISTEN``
- URI 控制 (``tcp://host:port`` 或 ``unix:///abs/socket/path``); 兼容老的
+ URI 控制 (``http://host:port`` 或 ``unix:///abs/socket/path``); 兼容老的
``--host/--port`` 用法只能由用户直接调 ``python -m uvicorn ...``。本入口
不再透出 host/port flag, 仅暴露 ``--listen``。
2. UDS 模式下做必要的 socket 文件预处理 (清理 stale socket、拒绝普通文件残留),
@@ -35,11 +35,11 @@ ENV_UDS_MODE = "JIUWENBOX_UDS_MODE"
# anything imports ``jiuwenbox.server.app`` lazily inside ``uvicorn.run``).
ENV_SAVE_LOGS_DIR = "JIUWENBOX_SAVE_LOGS_DIR"
-DEFAULT_LISTEN = "tcp://0.0.0.0:8321"
+DEFAULT_LISTEN = "http://0.0.0.0:8321"
-TcpSpec = Tuple[str, str, int] # ("tcp", host, port)
-UnixSpec = Tuple[str, str] # ("unix", abs_socket_path)
-ListenSpec = Union[TcpSpec, UnixSpec]
+HttpSpec = Tuple[str, str, int] # ("http", host, port)
+UnixSpec = Tuple[str, str] # ("unix", abs_socket_path)
+ListenSpec = Union[HttpSpec, UnixSpec]
class ListenURIError(ValueError):
@@ -47,19 +47,19 @@ class ListenURIError(ValueError):
def parse_listen(uri: str) -> ListenSpec:
- """把 ``tcp://host:port`` / ``unix:///abs/path`` 解析成结构化形式.
+ """把 ``http://host:port`` / ``unix:///abs/path`` 解析成结构化形式.
Args:
- uri: 监听地址 URI. ``scheme`` 必须是 ``tcp`` 或 ``unix``;
+ uri: 监听地址 URI. ``scheme`` 必须是 ``http`` 或 ``unix``;
``unix`` 路径必须是绝对路径 (以 ``/`` 起头), 否则不同 cwd 下行为
不一致, 且 lifespan / Docker volume 一律按绝对路径处理。
Returns:
- - TCP: ``("tcp", host, port)``;
- - UDS: ``("unix", absolute_socket_path)``.
+ - HTTP: ``("http", host, port)``;
+ - UDS: ``("unix", absolute_socket_path)``.
Raises:
- ListenURIError: scheme 未知 / TCP 缺 host 或 port / UDS 路径相对。
+ ListenURIError: scheme 未知 / HTTP 缺 host 或 port / UDS 路径相对。
"""
if not uri:
raise ListenURIError("listen URI is empty")
@@ -67,18 +67,18 @@ def parse_listen(uri: str) -> ListenSpec:
parsed = urlparse(uri)
scheme = (parsed.scheme or "").lower()
- if scheme == "tcp":
+ if scheme == "http":
host = parsed.hostname
port = parsed.port
if not host or port is None:
raise ListenURIError(
- f"tcp listen URI requires host and port, got {uri!r}"
+ f"http listen URI requires host and port, got {uri!r}"
)
if not (1 <= port <= 65535):
raise ListenURIError(
- f"tcp port out of range in {uri!r}: {port}"
+ f"http port out of range in {uri!r}: {port}"
)
- return ("tcp", host, int(port))
+ return ("http", host, int(port))
if scheme == "unix":
# 三斜杠 ``unix:///tmp/jw.sock`` -> netloc="", path="/tmp/jw.sock";
@@ -105,7 +105,7 @@ def parse_listen(uri: str) -> ListenSpec:
raise ListenURIError(
f"unknown listen URI scheme {scheme!r} in {uri!r}; "
- f"expected 'tcp' or 'unix'"
+ f"expected 'http' or 'unix'"
)
@@ -153,14 +153,14 @@ def _build_parser() -> argparse.ArgumentParser:
description=(
"Launch the jiuwenbox HTTP management server over TCP or UDS. "
"Listen address is controlled by --listen or the JIUWENBOX_LISTEN "
- "environment variable; default is tcp://0.0.0.0:8321."
+ f"environment variable; default is {DEFAULT_LISTEN}."
),
)
parser.add_argument(
"--listen",
default=None,
help=(
- "Listen URI: 'tcp://host:port' or 'unix:///abs/socket/path'. "
+ "Listen URI: 'http://host:port' or 'unix:///abs/socket/path'. "
f"Falls back to ${ENV_LISTEN} env, then {DEFAULT_LISTEN}."
),
)
@@ -253,13 +253,13 @@ def main(argv: list[str] | None = None) -> int:
return 3
uvicorn_kwargs: dict = {"log_level": args.log_level}
- if spec[0] == "tcp":
+ if spec[0] == "http":
_, host, port = spec
# 清掉残留的 UDS_PATH, 避免多次启动时 lifespan 读到陈旧值
os.environ.pop(ENV_UDS_PATH, None)
uvicorn_kwargs["host"] = host
uvicorn_kwargs["port"] = port
- logger.info("[launcher] starting jiuwenbox on tcp://%s:%d", host, port)
+ logger.info("[launcher] starting jiuwenbox on http://%s:%d", host, port)
else:
_, path = spec
try:
diff --git a/jiuwenbox/src/jiuwenbox/server/policy_reader.py b/jiuwenbox/src/jiuwenbox/server/policy_reader.py
index 07711fc9c3..cf604f0771 100644
--- a/jiuwenbox/src/jiuwenbox/server/policy_reader.py
+++ b/jiuwenbox/src/jiuwenbox/server/policy_reader.py
@@ -10,6 +10,8 @@ import logging
import os
from pathlib import Path
+import yaml
+
from jiuwenbox.logging_config import configure_logging
from jiuwenbox.models.policy import SecurityPolicy
from jiuwenbox.server.policy_engine import PolicyEngine
@@ -19,6 +21,13 @@ logger = logging.getLogger(__name__)
JIUWENBOX_POLICY_PATH_ENV = "JIUWENBOX_POLICY_PATH"
+# Top-level YAML keys that don't represent sandbox-related configuration.
+# A policy file whose effective sandbox-config keys are empty (i.e. its
+# top-level key set is a subset of ``_META_KEYS | {"inference_privacy_proxies"}``)
+# is treated as proxy-only and the server skips sandbox initialisation.
+_META_KEYS: frozenset[str] = frozenset({"version", "name"})
+_PROXY_ONLY_ALLOWED_KEYS: frozenset[str] = _META_KEYS | {"inference_privacy_proxies"}
+
class PolicyReader:
"""Reads security policy from YAML files."""
@@ -54,3 +63,34 @@ class PolicyReader:
def load_policy_from_file(self, path: Path) -> SecurityPolicy:
return self.policy_engine.load_policy_from_file(path)
+
+ def is_proxy_only(self) -> bool:
+ """Return True iff the YAML file only configures the inference proxy.
+
+ "Proxy-only" means the operator wants jiuwenbox to act purely as an
+ inference privacy router: the YAML's top-level keys are limited to
+ :data:`_PROXY_ONLY_ALLOWED_KEYS` and the proxy listener is actually
+ enabled (``listen_port > 0``). When this is the case the server skips
+ the sandbox subsystem entirely (no ``ProcessRuntime``, no idle
+ reaper, no zombie reaper) and only runs the proxy lifecycle.
+ """
+ if not self.policy_path.exists():
+ return False
+ try:
+ with open(self.policy_path) as f:
+ data = yaml.safe_load(f)
+ except (OSError, yaml.YAMLError):
+ return False
+ if not isinstance(data, dict):
+ return False
+ top_keys = set(data.keys())
+ if not top_keys.issubset(_PROXY_ONLY_ALLOWED_KEYS):
+ return False
+ proxy_section = data.get("inference_privacy_proxies")
+ if not isinstance(proxy_section, dict):
+ return False
+ try:
+ port = int(proxy_section.get("listen_port", 0) or 0)
+ except (TypeError, ValueError):
+ return False
+ return port > 0
diff --git a/jiuwenbox/src/jiuwenbox/server/proxy_manager.py b/jiuwenbox/src/jiuwenbox/server/proxy_manager.py
index cf1d4f2eed..00649241a8 100644
--- a/jiuwenbox/src/jiuwenbox/server/proxy_manager.py
+++ b/jiuwenbox/src/jiuwenbox/server/proxy_manager.py
@@ -47,8 +47,12 @@ class ProxyManager:
proxy_mgr = get_proxy_manager()
await proxy_mgr.load_from_policy(proxy_config)
+ # 同时打印 host 和 port; 与 launcher 里 ``http://host:port`` 的
+ # 格式对齐, 方便运维 grep 拼接 curl。
+ listen_host = proxy_config.listen_host or "127.0.0.1"
logger.info(
- "Started inference privacy proxies from policy on port %d",
+ "Inference privacy proxy listening on http://%s:%d",
+ listen_host,
proxy_config.listen_port,
)
@@ -61,14 +65,3 @@ class ProxyManager:
except Exception as e:
logger.warning("Failed to stop proxy '%s': %s", proxy_info["name"], e)
logger.info("Stopped all inference privacy proxies")
-
-
-_proxy_manager: ProxyManager | None = None
-
-
-def get_proxy_manager_instance() -> ProxyManager:
- """Get the global ProxyManager instance (wrapper for inference privacy proxy manager)."""
- global _proxy_manager
- if _proxy_manager is None:
- _proxy_manager = ProxyManager()
- return _proxy_manager
diff --git a/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py b/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py
index c084889af0..fd76d747df 100644
--- a/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py
+++ b/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py
@@ -32,7 +32,6 @@ def _mgr():
class CreateSandboxRequest(BaseModel):
command: list[str] = Field(default_factory=list)
- workdir: str | None = None
env: dict[str, str] = Field(default_factory=dict)
policy: dict[str, Any] | None = None
policy_mode: PolicyMode = PolicyMode.OVERRIDE
@@ -56,10 +55,7 @@ class ListFilesQuery(BaseModel):
@router.post("/sandboxes", response_model=SandboxRef, status_code=201)
async def create_sandbox(request: CreateSandboxRequest):
- spec = SandboxSpec(
- workdir=request.workdir,
- env=request.env,
- )
+ spec = SandboxSpec(env=request.env)
return await _mgr().create_sandbox(
spec,
policy_data=request.policy,
diff --git a/jiuwenbox/src/jiuwenbox/server/runtime/base.py b/jiuwenbox/src/jiuwenbox/server/runtime/base.py
index b044a98a36..4122ff472b 100644
--- a/jiuwenbox/src/jiuwenbox/server/runtime/base.py
+++ b/jiuwenbox/src/jiuwenbox/server/runtime/base.py
@@ -47,7 +47,6 @@ class RuntimeAdapter(abc.ABC):
self,
sandbox_id: str,
policy_path: Path,
- workdir: str | None = None,
env: dict[str, str] | None = None,
) -> int:
"""Create and start a sandboxed process. Returns the OS pid."""
diff --git a/jiuwenbox/src/jiuwenbox/server/runtime/process.py b/jiuwenbox/src/jiuwenbox/server/runtime/process.py
index e63aff2cd3..3ae5afee65 100644
--- a/jiuwenbox/src/jiuwenbox/server/runtime/process.py
+++ b/jiuwenbox/src/jiuwenbox/server/runtime/process.py
@@ -2,18 +2,12 @@
"""Process-based runtime adapter (bare-metal mode).
Spawns bubblewrap directly for each sandbox lifecycle process and for each
-``exec`` request. The previous design wrapped every spawn with a Python
-``box-supervisor`` middleman (``python3 -m jiuwenbox.supervisor.main``); for
-hot-path workloads (uploads, exec, listings, downloads) that added ~150 ms of
-Python interpreter cold start plus YAML/Pydantic policy parsing per call.
-
-This adapter performs the equivalent setup in-process and reuses the
-expensive artifacts (seccomp BPF program, encoded Landlock payload, copies of
-the in-sandbox launcher scripts) for the lifetime of the sandbox while
-preserving the same security guarantees: bubblewrap still applies all
-namespace/mount/seccomp/Landlock isolation, the sandbox still runs through
-the dedicated launcher script, and the seccomp memfd still flows through
-``pass_fds`` so it cannot be observed by sandboxed code.
+``exec`` request. Setup runs in-process and reuses the expensive artifacts
+(seccomp BPF program, encoded Landlock payload, copies of the in-sandbox
+launcher scripts) for the lifetime of the sandbox: bubblewrap still applies
+all namespace/mount/seccomp/Landlock isolation, the sandbox still runs
+through the dedicated launcher script, and the seccomp memfd still flows
+through ``pass_fds`` so it cannot be observed by sandboxed code.
"""
from __future__ import annotations
@@ -73,9 +67,6 @@ from jiuwenbox.supervisor.seccomp import build_seccomp_filter
configure_logging()
logger = logging.getLogger(__name__)
-RUNTIME_SANDBOX_ENV = "JIUWENBOX_SANDBOX_ENV"
-RUNTIME_SANDBOX_WORKDIR = "JIUWENBOX_SANDBOX_WORKDIR"
-RUNTIME_POLICY_BINDS = "JIUWENBOX_POLICY_BINDS"
SERVER_PROTECT_PORTS_ENV = "JIUWENBOX_SERVER_PROTECT_PORTS"
# Host-level firewall protection: for ``network.mode: host`` sandboxes we
# attempt to install an iptables OUTPUT block by-sandbox-uid against the
@@ -84,8 +75,8 @@ SERVER_PROTECT_PORTS_ENV = "JIUWENBOX_SERVER_PROTECT_PORTS"
# API. The default tracks the listener configured via ``JIUWENBOX_LISTEN``
# (set by ``launcher.py``); operators who run the server on a non-default
# port no longer have to remember to also bump this list. When
-# ``JIUWENBOX_LISTEN`` is UDS or unparseable we fall back to the historical
-# default of port 8321 so existing setups behave unchanged. The list can
+# ``JIUWENBOX_LISTEN`` is UDS or unparseable we fall back to the
+# historical default of port 8321 so existing setups behave unchanged. The list can
# still be overridden via ``JIUWENBOX_SERVER_PROTECT_PORTS=...``
# (comma-separated integers) or disabled entirely by exporting empty.
#
@@ -103,7 +94,7 @@ def _derive_protect_ports_from_listen() -> tuple[int, ...]:
"""Extract a TCP port from ``$JIUWENBOX_LISTEN`` for self-protection.
Recognized shapes (matching ``launcher.parse_listen``):
- - ``tcp://host:port`` -> ``(port,)``
+ - ``http://host:port`` -> ``(port,)``
- ``unix:///abs/path`` -> ``()`` (no TCP port to protect)
Anything else (env unset, malformed) returns the historical default of
@@ -116,11 +107,11 @@ def _derive_protect_ports_from_listen() -> tuple[int, ...]:
return DEFAULT_SERVER_PROTECT_PORTS
if uri.startswith("unix://"):
return ()
- if uri.startswith("tcp://"):
- # ``tcp://0.0.0.0:8321`` -> ``("0.0.0.0", "8321")``. ``rsplit``
- # guards against IPv6 hosts like ``tcp://[::]:8321`` where ``:``
+ if uri.startswith("http://"):
+ # ``http://0.0.0.0:8321`` -> ``("0.0.0.0", "8321")``. ``rsplit``
+ # guards against IPv6 hosts like ``http://[::]:8321`` where ``:``
# appears multiple times.
- host_port = uri[len("tcp://"):]
+ host_port = uri[len("http://"):]
try:
_, port_str = host_port.rsplit(":", 1)
port = int(port_str)
@@ -156,6 +147,12 @@ DAEMON_CONNECT_TIMEOUT_SECONDS = 2.0
DAEMON_SHUTDOWN_TIMEOUT_SECONDS = 3.0
DAEMON_STARTUP_GRACE_SECONDS = 0.3
DAEMON_MAX_RESPONSE_BYTES = 256 * 1024 * 1024
+# Upper bound on how much of the daemon's spawn-time stdout/stderr we
+# include in the ``RuntimeError`` raised when the supervisor exits before
+# becoming ready. 16 KiB comfortably fits a Python traceback plus a few
+# lines of bwrap/seccomp/landlock diagnostics, while keeping the resulting
+# exception message bounded for callers that surface it over HTTP.
+DAEMON_STARTUP_LOG_MAX_BYTES = 16 * 1024
# File ops (upload/download/list) are CPU-cheap on the daemon side - it
# is just an open/read/write or scandir call. Cap the IPC roundtrip at a
# short upper bound so a wedged daemon does not stall HTTP requests.
@@ -204,11 +201,6 @@ RECOVERABLE_DAEMON_ERRNOS: frozenset[int] = frozenset(
),
)
-# Convenience union for any errno we should *not* let bubble out of an
-# IPC roundtrip as an unhandled OSError (which would otherwise crash the
-# route handler and surface as ``Server disconnected``).
-TRANSIENT_DAEMON_ERRNOS: frozenset[int] = FATAL_DAEMON_ERRNOS | RECOVERABLE_DAEMON_ERRNOS
-
@dataclasses.dataclass(frozen=True)
class _DaemonExecCall:
@@ -707,8 +699,7 @@ class ProcessRuntime(RuntimeAdapter):
def _open_seccomp_fd_from_bytes(bpf: bytes) -> int:
"""Create an anonymous memfd preloaded with ``bpf`` for bwrap.
- Mirrors :func:`jiuwenbox.supervisor.seccomp.open_seccomp_filter` but
- works from cached BPF bytes so the BPF program does not have to be
+ Works from cached BPF bytes so the BPF program does not have to be
re-assembled for every exec.
"""
if not hasattr(os, "memfd_create"):
@@ -739,10 +730,8 @@ class ProcessRuntime(RuntimeAdapter):
) -> list[str]:
"""Build a ready-to-spawn bwrap argv vector for ``command``.
- This collapses the work that used to happen inside the long-lived
- ``box-supervisor`` Python process into the box-server itself. Caches
- populated during :meth:`create` (policy binds, launcher scripts,
- seccomp BPF, landlock payload) keep the per-call cost low.
+ Caches populated during :meth:`create` (policy binds, launcher
+ scripts, seccomp BPF, landlock payload) keep the per-call cost low.
"""
config = BwrapConfig.from_policy(policy, list(command))
if sandbox_env:
@@ -927,7 +916,7 @@ class ProcessRuntime(RuntimeAdapter):
# bound. ``launcher.main`` always writes the resolved listen
# URI back to ``$JIUWENBOX_LISTEN`` (see launcher.py:234) so
# this stays consistent even when the operator passed
- # ``--listen tcp://0.0.0.0:18321``.
+ # ``--listen http://0.0.0.0:18321``.
return list(_derive_protect_ports_from_listen())
if not raw_ports.strip():
return []
@@ -1020,6 +1009,20 @@ class ProcessRuntime(RuntimeAdapter):
if policy.network.mode != NetworkMode.HOST:
return
+ if not network_module.policy_has_network_rules(policy.network):
+ # The operator declared ``mode: host`` and did not list any
+ # egress/ingress entries, so they have explicitly opted out of
+ # all network restrictions. Skip the implicit iptables-based
+ # box-server self-protection in that case: it lets jiuwenbox
+ # run on hosts that do not ship ``iptables`` / ``iptables-nft``
+ # at all, matching the behavior promised by the policy.
+ logger.debug(
+ "Skipping host firewall install for sandbox %s "
+ "(policy declares no egress/ingress rules)",
+ sandbox_id,
+ )
+ return
+
ports = self._server_protect_ports()
if not ports:
# ``JIUWENBOX_SERVER_PROTECT_PORTS=""`` lets operators turn the
@@ -1248,52 +1251,6 @@ class ProcessRuntime(RuntimeAdapter):
return command
return [network_module.IP_BINARY, "netns", "exec", namespace, *command]
- @staticmethod
- def _apply_runtime_env(
- process_env: dict[str, str],
- *,
- netns_name: str | None,
- policy_binds: list[dict[str, str]],
- sandbox_env: dict[str, str] | None = None,
- sandbox_workdir: str | None = None,
- ) -> None:
- if netns_name:
- process_env["JIUWENBOX_NETNS_READY"] = "1"
- if policy_binds:
- process_env[RUNTIME_POLICY_BINDS] = json.dumps(
- policy_binds,
- separators=(",", ":"),
- )
- else:
- process_env.pop(RUNTIME_POLICY_BINDS, None)
- if sandbox_env is not None:
- process_env[RUNTIME_SANDBOX_ENV] = json.dumps(
- sandbox_env,
- separators=(",", ":"),
- )
- if sandbox_workdir:
- process_env[RUNTIME_SANDBOX_WORKDIR] = sandbox_workdir
- else:
- process_env.pop(RUNTIME_SANDBOX_WORKDIR, None)
-
- def _network_mode_for_cleanup(self, sandbox_id: str) -> NetworkMode | None:
- mode = self._network_modes.get(sandbox_id)
- if mode is not None:
- return mode
-
- policy_path = self._policy_paths.get(sandbox_id)
- if policy_path is None or not policy_path.exists():
- return None
-
- try:
- mode = self._load_policy(policy_path).network.mode
- except Exception:
- logger.warning("Failed to reload policy for sandbox %s during cleanup", sandbox_id, exc_info=True)
- return None
-
- self._network_modes[sandbox_id] = mode
- return mode
-
def _policy_for_sandbox(self, sandbox_id: str, policy_path: Path) -> SecurityPolicy:
policy = self._runtime_policies.get(sandbox_id)
if policy is None:
@@ -1625,7 +1582,6 @@ class ProcessRuntime(RuntimeAdapter):
self,
sandbox_id: str,
policy_path: Path,
- workdir: str | None = None,
env: dict[str, str] | None = None,
) -> int:
existing = self._processes.get(sandbox_id)
@@ -1677,7 +1633,7 @@ class ProcessRuntime(RuntimeAdapter):
policy,
list(SANDBOX_DAEMON_COMMAND),
is_daemon=True,
- workdir=workdir,
+ workdir=None,
sandbox_env=env,
netns_attached=netns_name is not None,
seccomp_fd=seccomp_fd,
@@ -1686,10 +1642,9 @@ class ProcessRuntime(RuntimeAdapter):
daemon_cmd = self._wrap_command_in_namespace(bwrap_args, netns_name)
process_env = {**os.environ, **(env or {})}
- # Forward the listener fd number to bwrap (and onward to the
- # daemon) via env so the daemon can recover it without having to
- # parse ``argv``.
- process_env[LISTENER_FD_ENV] = str(listener_fd)
+ # ``LISTENER_FD_ENV`` is injected into the sandboxed process via
+ # ``BwrapConfig.env`` -> ``bwrap --setenv``; bwrap itself never
+ # consumes it, so we no longer set it on the bwrap parent env.
logger.info("Spawning sandbox daemon for %s", sandbox_id)
logger.debug("Sandbox daemon bwrap command for %s: %s", sandbox_id, daemon_cmd)
@@ -1755,23 +1710,32 @@ class ProcessRuntime(RuntimeAdapter):
preexec = _preexec_attach_to_cgroup if cgroup_procs_paths else None
+ # Capture daemon stdout/stderr into an anonymous tempfile so that
+ # if the supervisor dies before becoming ready we can include the
+ # actual error (Python traceback, bwrap/seccomp/landlock message,
+ # missing binary, ...) in the ``RuntimeError`` surfaced upstream.
+ # The previous implementation routed both streams to ``DEVNULL``,
+ # which left operators with only ``exited with code 1`` to go on.
+ # The file is unlinked at create time so it cannot leak onto disk
+ # under any host path; the parent always closes its handle after
+ # startup verification, and the daemon's own fd is reaped by the
+ # kernel when the supervisor exits.
+ startup_log_file = tempfile.TemporaryFile(
+ prefix=f"jiuwenbox-{sandbox_id}-startup-",
+ suffix=".log",
+ )
try:
- # Daemon stdout/stderr is unconditionally dropped at the
- # kernel level: the audit.log already captures per-command
- # stdout/stderr (truncated to 4 KiB) and the historical
- # runtime.log file was removed. Anyone needing the raw
- # stream should run the container with ``-it`` and inspect
- # the bwrap output live; persistence is intentionally gone.
proc = subprocess.Popen(
daemon_cmd,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
+ stdout=startup_log_file,
+ stderr=subprocess.STDOUT,
env=process_env,
pass_fds=pass_fds,
start_new_session=True,
preexec_fn=preexec,
)
except Exception:
+ startup_log_file.close()
if seccomp_fd is not None:
_safe_close_fd(seccomp_fd)
try:
@@ -1805,7 +1769,17 @@ class ProcessRuntime(RuntimeAdapter):
if cgroup_handle is not None:
self._cgroup_handles[sandbox_id] = cgroup_handle
- await self._wait_daemon_ready(sandbox_id, proc, netns_name)
+ try:
+ await self._wait_daemon_ready(
+ sandbox_id, proc, netns_name, startup_log_file,
+ )
+ finally:
+ # Parent no longer needs the fd; the daemon keeps writing into
+ # its own (kernel-anonymous) copy until it exits.
+ try:
+ startup_log_file.close()
+ except OSError:
+ pass
logger.info("Sandbox daemon started for %s (pid=%d)", sandbox_id, proc.pid)
return proc.pid
@@ -1814,6 +1788,7 @@ class ProcessRuntime(RuntimeAdapter):
sandbox_id: str,
proc: subprocess.Popen,
netns_name: str | None,
+ startup_log_file: Any | None = None,
) -> None:
"""Verify the daemon is alive and mark its IPC channel ready.
@@ -1824,9 +1799,16 @@ class ProcessRuntime(RuntimeAdapter):
``accept()`` (so the very first request does not block waiting for
a worker thread to spin up) and confirm the bwrap parent has not
already exited with an error.
+
+ ``startup_log_file`` is the tempfile that captured the daemon's
+ stdout/stderr; on failure :meth:`_verify_daemon_alive` reads from
+ it to enrich the resulting ``RuntimeError`` with the underlying
+ diagnostic (Python traceback, bwrap message, ...). It is optional
+ so existing call sites and tests that build the runtime by hand
+ can still drive the verification step without one.
"""
await asyncio.sleep(DAEMON_STARTUP_GRACE_SECONDS)
- self._verify_daemon_alive(sandbox_id, proc, netns_name)
+ self._verify_daemon_alive(sandbox_id, proc, netns_name, startup_log_file)
self._daemon_socket_ready[sandbox_id] = True
def _verify_daemon_alive(
@@ -1834,21 +1816,56 @@ class ProcessRuntime(RuntimeAdapter):
sandbox_id: str,
proc: subprocess.Popen,
netns_name: str | None,
+ startup_log_file: Any | None = None,
) -> None:
if proc.poll() is None:
return
self._processes.pop(sandbox_id, None)
self._cleanup_sandbox_artifacts(sandbox_id, netns_name)
- # Raw daemon stdout/stderr is no longer persisted (see the
- # ``Popen(DEVNULL)`` call in ``_spawn_supervisor``); we surface
- # only the returncode here. For deeper debugging the operator
- # should re-run with ``docker run -it`` so the bwrap output
- # streams to the terminal.
- raise RuntimeError(
- f"Sandbox daemon exited during startup with code {proc.returncode}; "
- f"runtime stdout/stderr persistence is disabled (only audit.log "
- f"is written)."
+ log_excerpt = self._read_daemon_startup_log(startup_log_file)
+ message = (
+ f"Sandbox daemon exited during startup with code {proc.returncode}."
)
+ if log_excerpt:
+ message = (
+ f"{message} Captured daemon stdout/stderr (truncated to "
+ f"{DAEMON_STARTUP_LOG_MAX_BYTES} bytes):\n{log_excerpt}"
+ )
+ else:
+ # The previous code path advertised "stdout/stderr persistence
+ # is disabled"; we now always try to capture, so an empty log
+ # really does mean the daemon died silently (e.g. via a fast
+ # ``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."
+ )
+ raise RuntimeError(message)
+
+ @staticmethod
+ def _read_daemon_startup_log(startup_log_file: Any | None) -> str:
+ """Return a bounded UTF-8 excerpt of the daemon's startup log.
+
+ The file is the anonymous tempfile installed by ``_spawn_supervisor``
+ as the daemon's stdout/stderr. By the time we get here the daemon
+ has already exited (``_verify_daemon_alive`` only calls in after
+ ``proc.poll()`` returned a non-None code), so ``read`` will not
+ block waiting for additional bytes. All errors are swallowed and
+ turned into a synthetic placeholder line: failing to enrich the
+ diagnostic must never mask the original ``RuntimeError``.
+ """
+ if startup_log_file is None:
+ return ""
+ try:
+ startup_log_file.seek(0)
+ data = startup_log_file.read(DAEMON_STARTUP_LOG_MAX_BYTES)
+ except (OSError, ValueError) as exc:
+ return f"<failed to read daemon startup log: {exc}>"
+ if not data:
+ return ""
+ text = data.decode("utf-8", errors="replace").rstrip()
+ return text
def _cleanup_sandbox_artifacts(
self,
diff --git a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py
index faccc01771..1494085470 100644
--- a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py
+++ b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py
@@ -530,7 +530,6 @@ class SandboxManager:
pid = await self.runtime.create(
sandbox_id=sandbox_id,
policy_path=policy_path,
- workdir=None,
env=ref.env,
)
cleanup_after_create = False
@@ -604,7 +603,6 @@ class SandboxManager:
pid = await self.runtime.create(
sandbox_id=sandbox_id,
policy_path=policy_path,
- workdir=None,
env=ref.env,
)
ref.phase = SandboxPhase.READY
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py
index 41f9888711..09cf19b69b 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py
@@ -1,8 +1,10 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
"""Bubblewrap (bwrap) sandbox wrapper.
-Translates a SecurityPolicy into bwrap command-line arguments and manages
-the lifecycle of the sandboxed process.
+Translates a :class:`SecurityPolicy` into ``bwrap`` command-line arguments.
+The runtime adapter (``server/runtime/process.py``) spawns ``bwrap`` itself
+because it needs ``pass_fds``/``preexec_fn``/``start_new_session`` knobs
+that a generic process wrapper cannot express.
"""
from __future__ import annotations
@@ -10,12 +12,9 @@ from __future__ import annotations
import fnmatch
import logging
import posixpath
-import signal
import stat as stat_module
-import subprocess
from dataclasses import dataclass, field
from pathlib import Path
-from typing import IO
from jiuwenbox.logging_config import configure_logging
from jiuwenbox.models.policy import (
@@ -112,7 +111,6 @@ class BwrapConfig:
die_with_parent: bool = True
# filesystem
- rootfs: str | None = None
ro_binds: list[tuple[str, str]] = field(default_factory=list)
rw_binds: list[tuple[str, str]] = field(default_factory=list)
device_binds: list[tuple[str, str]] = field(default_factory=list)
@@ -290,9 +288,65 @@ class BwrapConfig:
def _apply_environment(cfg: BwrapConfig, environment: dict[str, str]) -> None:
cfg.env.update(environment)
+ @staticmethod
+ def _drop_bwrap_managed_binds(
+ binds: list[tuple[str, str]],
+ bwrap_managed: set[str],
+ kind: str,
+ ) -> list[tuple[str, str]]:
+ """Drop bind entries whose target shadows a bwrap-managed mount.
+
+ bwrap always emits a fresh tmpfs at ``--proc`` and ``--dev`` targets
+ and then needs to be able to ``open(..., O_CREAT)`` the per-device
+ bind targets (e.g. ``/dev/null``) inside that tmpfs. If a policy
+ later puts a read-only bind on top of ``/proc`` or ``/dev`` (the
+ common case is ``bind_root_entries: { host_root: "/" }`` which
+ expands into a ``--ro-bind /dev /dev`` child), bwrap fails with
+ ``Can't create file at /dev/null: Permission denied`` because the
+ ``open`` call lands on a read-only mount.
+
+ Filtering here keeps the failure contained to a single ignored
+ bind: the bwrap-owned tmpfs survives intact, ``--dev-bind`` for
+ per-device entries works as designed, and operators get a debug
+ log line that explains the conflict.
+ """
+ kept: list[tuple[str, str]] = []
+ for src, dst in binds:
+ normalized = dst.rstrip("/") or "/"
+ if normalized in bwrap_managed:
+ logger.debug(
+ "Skipping %s bind %s -> %s; the target shadows the "
+ "bwrap-managed tmpfs and would make --dev-bind fail "
+ "with 'Can't create file at <path>: Permission denied'",
+ kind,
+ src,
+ dst,
+ )
+ continue
+ kept.append((src, dst))
+ return kept
+
def to_args(self) -> list[str]:
- """Convert this config into a bwrap argument list."""
+ """Convert this config into a bwrap argument list.
+
+ ``to_args`` is side-effect free: ``self.ro_binds`` / ``self.rw_binds``
+ are read-only inside this method so the same ``BwrapConfig`` instance
+ can be serialised multiple times without losing or duplicating
+ entries.
+ """
args: list[str] = [BWRAP_BINARY]
+ bwrap_managed_mounts: set[str] = {
+ self.proc_path.rstrip("/") or "/",
+ self.dev_path.rstrip("/") or "/",
+ }
+ # Drop any bind that would overlay /dev or /proc; see
+ # ``_drop_bwrap_managed_binds`` for why this is required.
+ ro_binds_in = self._drop_bwrap_managed_binds(
+ self.ro_binds, bwrap_managed_mounts, "read-only",
+ )
+ rw_binds_in = self._drop_bwrap_managed_binds(
+ self.rw_binds, bwrap_managed_mounts, "read-write",
+ )
if self.unshare_user:
args.append("--unshare-user")
@@ -323,10 +377,10 @@ class BwrapConfig:
for cap in self.cap_drop:
args.extend(["--cap-drop", cap])
- root_ro_binds = [(src, dst) for src, dst in self.ro_binds if dst == "/"]
- root_rw_binds = [(src, dst) for src, dst in self.rw_binds if dst == "/"]
- ro_binds = [(src, dst) for src, dst in self.ro_binds if dst != "/"]
- rw_binds = [(src, dst) for src, dst in self.rw_binds if dst != "/"]
+ root_ro_binds = [(src, dst) for src, dst in ro_binds_in if dst == "/"]
+ root_rw_binds = [(src, dst) for src, dst in rw_binds_in if dst == "/"]
+ ro_binds = [(src, dst) for src, dst in ro_binds_in if dst != "/"]
+ rw_binds = [(src, dst) for src, dst in rw_binds_in if dst != "/"]
if root_rw_binds:
# A read-write root bind already exposes every absolute child path.
# Re-binding private children such as /home/<user>/.jiuwenswarm can
@@ -447,73 +501,3 @@ class BwrapConfig:
return args
-class BwrapProcess:
- """Manages a bubblewrap sandboxed process."""
-
- def __init__(self, config: BwrapConfig) -> None:
- self._config = config
- self._process: subprocess.Popen | None = None
-
- @property
- def pid(self) -> int | None:
- return self._process.pid if self._process else None
-
- @property
- def returncode(self) -> int | None:
- if self._process is None:
- return None
- return self._process.returncode
-
- @property
- def is_running(self) -> bool:
- if self._process is None:
- return False
- return self._process.poll() is None
-
- def start(
- self,
- stdin: int | IO | None = None,
- stdout: int | IO | None = None,
- stderr: int | IO | None = None,
- ) -> None:
- """Spawn the bwrap process."""
- if self._process is not None and self.is_running:
- raise RuntimeError("Process already running")
-
- args = self._config.to_args()
- logger.debug("Starting bwrap with args: %s", args)
- pass_fds = ()
- if self._config.seccomp_fd is not None:
- pass_fds = (self._config.seccomp_fd,)
-
- self._process = subprocess.Popen(
- args,
- stdin=stdin,
- stdout=stdout,
- stderr=stderr,
- pass_fds=pass_fds,
- )
-
- def wait(self, timeout: float | None = None) -> int:
- """Wait for the process to exit and return the exit code."""
- if self._process is None:
- raise RuntimeError("Process not started")
- self._process.wait(timeout=timeout)
- return self._process.returncode
-
- def stop(self, timeout: float = 10.0) -> int | None:
- """Gracefully stop: SIGTERM then SIGKILL after timeout."""
- if self._process is None or not self.is_running:
- return self.returncode
-
- logger.info("Sending SIGTERM to bwrap pid %d", self._process.pid)
- self._process.send_signal(signal.SIGTERM)
-
- try:
- self._process.wait(timeout=timeout)
- except subprocess.TimeoutExpired:
- logger.warning("SIGTERM timeout, sending SIGKILL to pid %d", self._process.pid)
- self._process.kill()
- self._process.wait(timeout=5.0)
-
- return self._process.returncode
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/cgroup.py b/jiuwenbox/src/jiuwenbox/supervisor/cgroup.py
index 281cc2808b..7c25a63e57 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/cgroup.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/cgroup.py
@@ -28,6 +28,7 @@ import os
import shutil
import time
from dataclasses import dataclass, field
+from functools import lru_cache
from pathlib import Path
from jiuwenbox.models.policy import CgroupPolicy
@@ -112,6 +113,7 @@ def _v1_available() -> bool:
return True
+@lru_cache(maxsize=1)
def detect_backend() -> CgroupBackend | None:
"""Probe the host for a usable cgroup backend.
@@ -119,6 +121,11 @@ def detect_backend() -> CgroupBackend | None:
controllers exposed, falling back to ``CgroupBackend.V1`` when each
required controller has its own hierarchy. Returns ``None`` if
neither is present (the caller decides whether that's fatal).
+
+ Cached because the cgroup hierarchy is fixed for the lifetime of the
+ host kernel: every sandbox creation otherwise re-runs ``read_text``
+ on ``/sys/fs/cgroup/cgroup.controllers`` (or ``is_dir`` for v1
+ controllers) which is wasted work on the hot path.
"""
if _v2_available():
return CgroupBackend.V2
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.py b/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.py
index 32e11fa1f5..34f6e0b33e 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.py
@@ -50,7 +50,6 @@ LISTENER_FD_ENV = "JIUWENBOX_CONTROL_LISTENER_FD"
SANDBOX_DAEMON_COMMAND = ["python3", "-S", SANDBOX_DAEMON_SANDBOX_PATH]
# Outgoing request types accepted by the daemon.
-REQUEST_TYPE_PING = "ping"
REQUEST_TYPE_EXEC = "exec"
REQUEST_TYPE_SHUTDOWN = "shutdown"
# File-ops fast paths. Box-server uses these instead of spawning bash/
@@ -121,8 +120,3 @@ def encode_request(
if payload:
body.update(payload)
return json.dumps(body, ensure_ascii=False).encode("utf-8")
-
-
-def decode_request(blob: bytes) -> dict[str, Any]:
- import json
- return json.loads(blob.decode("utf-8"))
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/main.py b/jiuwenbox/src/jiuwenbox/supervisor/main.py
deleted file mode 100644
index 3af2650456..0000000000
--- a/jiuwenbox/src/jiuwenbox/supervisor/main.py
+++ /dev/null
@@ -1,257 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
-"""box-supervisor main entry point."""
-
-from __future__ import annotations
-
-import asyncio
-import json
-import logging
-import os
-import signal
-import sys
-import tempfile
-from pathlib import Path
-
-import yaml
-
-from jiuwenbox.logging_config import configure_logging
-from jiuwenbox.models.policy import NetworkMode, SecurityPolicy
-from jiuwenbox.supervisor.bwrap import BwrapConfig, BwrapProcess
-from jiuwenbox.supervisor.landlock import encode_landlock_payload
-from jiuwenbox.supervisor.daemon_ipc import SANDBOX_RESERVED_DIR
-from jiuwenbox.supervisor.sandbox_daemon import (
- SANDBOX_DAEMON_COMMAND,
- SANDBOX_DAEMON_SANDBOX_PATH,
- SANDBOX_LAUNCHER_PATH,
-)
-from jiuwenbox.supervisor.seccomp import open_seccomp_filter
-
-configure_logging()
-logger = logging.getLogger(__name__)
-RUNTIME_SANDBOX_ENV = "JIUWENBOX_SANDBOX_ENV"
-RUNTIME_SANDBOX_WORKDIR = "JIUWENBOX_SANDBOX_WORKDIR"
-RUNTIME_POLICY_BINDS = "JIUWENBOX_POLICY_BINDS"
-
-
-def _load_runtime_sandbox_env() -> dict[str, str]:
- """Load per-exec sandbox environment passed by the server runtime."""
- raw_env = os.environ.get(RUNTIME_SANDBOX_ENV)
- if not raw_env:
- return {}
-
- try:
- data = json.loads(raw_env)
- except json.JSONDecodeError:
- logger.warning("Ignoring invalid %s", RUNTIME_SANDBOX_ENV, exc_info=True)
- return {}
-
- if not isinstance(data, dict):
- logger.warning("Ignoring non-object %s", RUNTIME_SANDBOX_ENV)
- return {}
-
- return {str(key): str(value) for key, value in data.items()}
-
-
-def _load_runtime_sandbox_workdir() -> str | None:
- """Load per-exec sandbox workdir passed by the server runtime."""
- workdir = os.environ.get(RUNTIME_SANDBOX_WORKDIR)
- if not workdir:
- return None
- return workdir
-
-
-class Supervisor:
- """Manages a single sandboxed process with full isolation."""
-
- def __init__(
- self,
- policy: SecurityPolicy,
- command: list[str],
- workdir: str | None = None,
- env: dict[str, str] | None = None,
- ) -> None:
- self.policy = policy
- self.command = command
- self.workdir = workdir
- self.env = env or {}
- self._bwrap: BwrapProcess | None = None
- self._seccomp_fd: int | None = None
- self._sandbox_daemon_path: Path | None = None
- self._landlock_launcher_path: Path | None = None
- self._shutting_down = False
-
- @classmethod
- def from_policy_file(cls, path: str | Path, command: list[str], **kwargs) -> Supervisor:
- """Create a Supervisor from a policy YAML file."""
- policy_path = Path(path)
- with open(policy_path) as f:
- data = yaml.safe_load(f)
- policy = SecurityPolicy.model_validate(data)
- return cls(policy=policy, command=command, **kwargs)
-
- def _setup_seccomp(self, config: BwrapConfig) -> None:
- """Generate seccomp filter and configure bwrap to use it."""
- fd = open_seccomp_filter(self.policy.syscall)
- self._seccomp_fd = fd
- config.seccomp_fd = fd
-
- def _close_seccomp_fd(self) -> None:
- if self._seccomp_fd is None:
- return
- try:
- os.close(self._seccomp_fd)
- except OSError:
- logger.warning("Failed to close seccomp fd", exc_info=True)
- finally:
- self._seccomp_fd = None
-
- def _setup_network_namespace(self, config: BwrapConfig) -> None:
- """Reuse the pre-configured runtime namespace when one is provided."""
- if self.policy.network.mode != NetworkMode.ISOLATED:
- return
-
- if os.environ.get("JIUWENBOX_NETNS_READY") == "1":
- config.unshare_net = False
-
- @staticmethod
- def _setup_policy_bind_mounts(config: BwrapConfig) -> None:
- """Attach server-created lifecycle paths to their sandbox paths."""
- raw_binds = os.environ.get(RUNTIME_POLICY_BINDS)
- if not raw_binds:
- return
-
- for entry in json.loads(raw_binds):
- config.rw_binds.append((entry["host_path"], entry["sandbox_path"]))
-
- def _setup_sandbox_daemon_mount(self, config: BwrapConfig, temp_dir: Path) -> None:
- """Expose the internal lifecycle daemon when this supervisor is a holder."""
- if config.command != SANDBOX_DAEMON_COMMAND:
- return
-
- daemon_path = Path(__file__).with_name("sandbox_daemon.py")
- temp_daemon_path = temp_dir / "sandbox-daemon.py"
- temp_daemon_path.write_bytes(daemon_path.read_bytes())
- os.chmod(temp_daemon_path, 0o644)
- self._sandbox_daemon_path = temp_daemon_path
- config.ro_binds.append((str(self._sandbox_daemon_path), SANDBOX_DAEMON_SANDBOX_PATH))
-
- def _setup_landlock_launcher(self, config: BwrapConfig, temp_dir: Path) -> None:
- """Run a fixed in-sandbox launcher that applies Landlock before exec."""
- if config.command == SANDBOX_DAEMON_COMMAND:
- return
-
- if self.policy.landlock.compatibility == "disabled":
- return
-
- launcher_path = Path(__file__).with_name("landlock_launcher.py")
- temp_launcher_path = temp_dir / "landlock-launcher.py"
- temp_launcher_path.write_bytes(launcher_path.read_bytes())
- os.chmod(temp_launcher_path, 0o644)
- self._landlock_launcher_path = temp_launcher_path
-
- # ``SANDBOX_RESERVED_DIR`` is locked away by ``PolicyEngine`` so
- # the user cannot collide with this mount via ``bind_mounts`` or
- # smuggle ``/jiuwenbox`` into the Landlock allowlist via
- # ``read_only`` / ``read_write``.
- config.add_dir_mount(SANDBOX_RESERVED_DIR)
- config.ro_binds.append((str(self._landlock_launcher_path), SANDBOX_LAUNCHER_PATH))
- config.command = [
- "python3",
- SANDBOX_LAUNCHER_PATH,
- encode_landlock_payload(self.policy),
- "--",
- *config.command,
- ]
-
- async def start(self) -> int:
- """Start the sandbox and return the exit code of the target process."""
- with tempfile.TemporaryDirectory(prefix="jiuwenbox-landlock-") as temp_dir:
- try:
- # 1. Build bwrap config from policy
- config = BwrapConfig.from_policy(self.policy, self.command)
- config.env.update(self.env)
- if self.workdir:
- config.workdir = self.workdir
- self._setup_network_namespace(config)
- self._setup_policy_bind_mounts(config)
- self._setup_sandbox_daemon_mount(config, Path(temp_dir))
- self._setup_landlock_launcher(config, Path(temp_dir))
-
- # 2. Setup seccomp
- try:
- self._setup_seccomp(config)
- except Exception:
- logger.warning("Failed to setup seccomp, continuing without it", exc_info=True)
-
- # 3. Register signal handlers
- loop = asyncio.get_running_loop()
- for sig in (signal.SIGTERM, signal.SIGINT):
- loop.add_signal_handler(sig, lambda s=sig: asyncio.create_task(self._shutdown(s)))
-
- # 4. Start bwrap process
- self._bwrap = BwrapProcess(config)
- self._bwrap.start()
- self._close_seccomp_fd()
-
- # 5. Wait for process to exit
- return await asyncio.get_running_loop().run_in_executor(
- None, self._bwrap.wait
- )
- finally:
- self._close_seccomp_fd()
- await self._cleanup()
-
- async def _shutdown(self, sig: signal.Signals) -> None:
- """Graceful shutdown on signal."""
- if self._shutting_down:
- return
- self._shutting_down = True
-
- logger.info("Received signal %s, shutting down", sig.name)
- if self._bwrap:
- self._bwrap.stop()
- await self._cleanup()
-
- async def _cleanup(self) -> None:
- """Clean up resources."""
- self._close_seccomp_fd()
- if self._sandbox_daemon_path and self._sandbox_daemon_path.exists():
- self._sandbox_daemon_path.unlink(missing_ok=True)
- if self._landlock_launcher_path and self._landlock_launcher_path.exists():
- self._landlock_launcher_path.unlink(missing_ok=True)
-
-
-async def run_supervisor(
- policy_path: str,
- command: list[str],
- workdir: str | None = None,
- env: dict[str, str] | None = None,
-) -> int:
- """High-level entry point: load policy and run the sandbox."""
- runtime_env = _load_runtime_sandbox_env() if env is None else env
- runtime_workdir = _load_runtime_sandbox_workdir() if workdir is None else workdir
- supervisor = Supervisor.from_policy_file(
- policy_path,
- command,
- workdir=runtime_workdir,
- env=runtime_env,
- )
- return await supervisor.start()
-
-
-def main() -> int:
- """CLI entry point for box-supervisor (used by box-server to spawn)."""
- configure_logging()
-
- if len(sys.argv) < 3:
- logger.error("Usage: %s <policy.yaml> <command> [args...]", sys.argv[0])
- return 1
-
- policy_path = sys.argv[1]
- command = sys.argv[2:]
-
- return asyncio.run(run_supervisor(policy_path, command))
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/network.py b/jiuwenbox/src/jiuwenbox/supervisor/network.py
index d7cdc739a2..b01af1ce71 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/network.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/network.py
@@ -90,6 +90,35 @@ def normalize_ips(values: list[str]) -> list[str]:
return resolved
+def _rule_policy_is_empty(rule: NetworkRulePolicy) -> bool:
+ """Return True when a rule policy defines no allow/block entries.
+
+ Callers use this to decide whether the operator has opted out of all
+ network restrictions. The ``default`` field (``deny``/``allow``) is not
+ treated as a "rule" because it only matters once at least one
+ allow/block entry is configured.
+ """
+ return not (
+ rule.allowed_domains
+ or rule.blocked_domains
+ or rule.allowed_ips
+ or rule.blocked_ips
+ or rule.allowed_ports
+ or rule.blocked_ports
+ )
+
+
+def policy_has_network_rules(policy: NetworkPolicy) -> bool:
+ """Return True when the policy declares any explicit egress/ingress rule.
+
+ A policy that only sets ``mode`` (and leaves both ``egress`` and
+ ``ingress`` empty) is considered to have no rules. In that case the
+ server runtime can skip iptables programming entirely, so hosts that
+ do not ship ``iptables``/``iptables-nft`` still work.
+ """
+ return not (_rule_policy_is_empty(policy.egress) and _rule_policy_is_empty(policy.ingress))
+
+
def build_network_rules(policy: NetworkRulePolicy) -> ResolvedNetworkRules:
"""Resolve domains/IPs and build a direction-agnostic network rule set."""
rules = ResolvedNetworkRules(
@@ -119,7 +148,13 @@ def _existing_binaries(paths: tuple[str, ...]) -> list[str]:
for path in paths:
if path in result:
continue
- if path.startswith("/") and not shutil.which(path):
+ # ``shutil.which`` resolves both absolute paths and bare command
+ # names through ``$PATH``. Filtering both keeps callers from trying
+ # to ``exec`` a binary that simply is not installed on the host
+ # (otherwise ``subprocess.run`` would raise ``FileNotFoundError``
+ # later, which bypasses the ``NetworkSetupError`` handlers wired
+ # up by the server runtime).
+ if not shutil.which(path):
continue
result.append(path)
return result
@@ -150,7 +185,17 @@ def _run_iptables_binary(
if namespace:
cmd = [IP_BINARY, "netns", "exec", namespace, *cmd]
logger.debug("%s: %s", binary, " ".join(cmd))
- result = subprocess.run(cmd, capture_output=True, text=True, check=False)
+ try:
+ result = subprocess.run(cmd, capture_output=True, text=True, check=False)
+ except FileNotFoundError as exc:
+ # ``iptables`` (or ``ip`` when running inside a netns) is not on
+ # ``$PATH``. Surface this as a regular ``NetworkSetupError`` so the
+ # graceful handlers in the server runtime can downgrade it to a
+ # warning instead of crashing sandbox creation.
+ raise NetworkSetupError(
+ f"Required binary '{exc.filename or cmd[0]}' is not installed; "
+ f"cannot run '{' '.join(cmd)}'."
+ ) from exc
if check and result.returncode != 0:
raise NetworkSetupError(_format_command_error(cmd, result))
return result
@@ -187,32 +232,17 @@ def _select_iptables_binary(ip_version: int, namespace: str | None = None) -> st
raise NetworkSetupError(f"No working {family} iptables backend{target}. {detail}")
-def _run_iptables(
+def run_iptables(
args: list[str],
check: bool = True,
namespace: str | None = None,
ip_version: int = 4,
) -> subprocess.CompletedProcess:
- """Run an iptables/ip6tables command."""
+ """Run an iptables/ip6tables command, picking the available backend."""
binary = _select_iptables_binary(ip_version, namespace)
return _run_iptables_binary(binary, args, check=check, namespace=namespace)
-def run_iptables(
- args: list[str],
- check: bool = True,
- namespace: str | None = None,
- ip_version: int = 4,
-) -> subprocess.CompletedProcess:
- """Run an iptables/ip6tables command for callers outside this module."""
- return _run_iptables(
- args,
- check=check,
- namespace=namespace,
- ip_version=ip_version,
- )
-
-
def _ip_version(value: str) -> int:
"""Return 4 or 6 for an IP/CIDR rule value."""
return ipaddress.ip_network(value, strict=False).version
@@ -229,7 +259,7 @@ def _run_iptables_for_ip(
if ip_version == 6 and not _ip6tables_available(namespace):
return subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr="")
- return _run_iptables(
+ return run_iptables(
args,
check=check,
namespace=namespace,
@@ -243,16 +273,16 @@ def _run_iptables_both(
namespace: str | None = None,
) -> None:
"""Run a protocol-agnostic firewall rule for both IPv4 and IPv6."""
- _run_iptables(args, check=check, namespace=namespace, ip_version=4)
+ run_iptables(args, check=check, namespace=namespace, ip_version=4)
if _ip6tables_available(namespace):
- _run_iptables(args, check=check, namespace=namespace, ip_version=6)
+ run_iptables(args, check=check, namespace=namespace, ip_version=6)
@lru_cache(maxsize=128)
def _ip6tables_available(namespace: str | None = None) -> bool:
"""Return whether ip6tables can manage rules in the target namespace."""
try:
- result = _run_iptables(
+ result = run_iptables(
["-L", "OUTPUT", "-n"],
check=False,
namespace=namespace,
@@ -323,16 +353,6 @@ def setup_loopback(namespace: str | None = None) -> None:
_run_ip(["link", "set", "lo", "up"], namespace=namespace)
-def build_egress_rules(egress: NetworkRulePolicy) -> ResolvedNetworkRules:
- """Resolve egress policy into iptables-ready rules."""
- return build_network_rules(egress)
-
-
-def build_ingress_rules(ingress: NetworkRulePolicy) -> ResolvedNetworkRules:
- """Resolve ingress policy into iptables-ready rules."""
- return build_network_rules(ingress)
-
-
def _apply_egress_rules(rules: ResolvedNetworkRules, namespace: str | None = None) -> None:
"""Apply outbound network rules inside the current namespace."""
_run_iptables_both(["-A", "OUTPUT", "-o", "lo", "-j", "ACCEPT"], namespace=namespace)
@@ -445,6 +465,6 @@ def setup_network_isolation(policy: NetworkPolicy, namespace: str | None = None)
logger.info("Network mode is 'host', skipping isolation")
return
- egress_rules = build_egress_rules(policy.egress)
- ingress_rules = build_ingress_rules(policy.ingress)
+ egress_rules = build_network_rules(policy.egress)
+ ingress_rules = build_network_rules(policy.ingress)
apply_iptables_rules(egress_rules, ingress_rules, namespace=namespace)
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py b/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py
index e3214dda67..396643834d 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py
@@ -85,7 +85,6 @@ SANDBOX_LAUNCHER_PATH = f"{SANDBOX_RESERVED_DIR}/landlock-launcher.py"
SANDBOX_DAEMON_COMMAND = ["python3", "-S", SANDBOX_DAEMON_SANDBOX_PATH]
LISTENER_FD_ENV = "JIUWENBOX_CONTROL_LISTENER_FD"
-REQUEST_TYPE_PING = "ping"
REQUEST_TYPE_EXEC = "exec"
REQUEST_TYPE_SHUTDOWN = "shutdown"
REQUEST_TYPE_WRITE_FILE = "write_file"
@@ -692,11 +691,6 @@ def _handle_connection(conn: socket.socket, state: DaemonState) -> None:
request_type = header.get("type")
if request_type == REQUEST_TYPE_EXEC:
_handle_exec(conn, header, state)
- elif request_type == REQUEST_TYPE_PING:
- _send_response(
- conn,
- {"v": PROTOCOL_VERSION, "ok": True, "type": "pong"},
- )
elif request_type == REQUEST_TYPE_SHUTDOWN:
_send_response(
conn,
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py b/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py
index 0d8101efa5..de8dbb9e01 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py
@@ -8,7 +8,6 @@ The BPF program is written to an anonymous memfd whose fd is passed to bwrap.
from __future__ import annotations
import logging
-import os
import platform
import struct
from functools import lru_cache
@@ -33,7 +32,6 @@ BPF_RET = 0x06
SECCOMP_RET_ALLOW = 0x7FFF_0000
SECCOMP_RET_ERRNO = 0x0005_0000
SECCOMP_RET_KILL_PROCESS = 0x8000_0000
-SECCOMP_RET_LOG = 0x7FFC_0000
ERRNO_EPERM = 1
ERRNO_ENOSYS = 38
@@ -277,19 +275,3 @@ def _assemble_bpf(blocked_nrs: list[int]) -> bytes:
return bytes(prog)
-def open_seccomp_filter(policy: SyscallPolicy) -> int:
- """Build the seccomp filter and return an fd positioned at the start."""
- data = build_seccomp_filter(policy)
- if not hasattr(os, "memfd_create"):
- raise RuntimeError("os.memfd_create is required for seccomp filters")
-
- fd = os.memfd_create("jiuwenbox-seccomp", getattr(os, "MFD_CLOEXEC", 0x0001))
- try:
- offset = 0
- while offset < len(data):
- offset += os.write(fd, data[offset:])
- os.lseek(fd, 0, os.SEEK_SET)
- except Exception:
- os.close(fd)
- raise
- return fd
diff --git a/jiuwenbox/tests/conftest.py b/jiuwenbox/tests/conftest.py
index 9da9f6fb5e..cc7e73c447 100644
--- a/jiuwenbox/tests/conftest.py
+++ b/jiuwenbox/tests/conftest.py
@@ -9,8 +9,6 @@ import pytest
pytest_plugins = ["pytest_asyncio"]
-from jiuwenbox.models.policy import SecurityPolicy
-
def pytest_addoption(parser):
parser.addoption(
@@ -135,15 +133,6 @@ def server_host_port_session(pytestconfig):
return host, int(port)
[email protected](scope="session")
-def proxy_port_session(pytestconfig):
- """Session-scoped proxy port."""
- return (
- pytestconfig.getoption("proxy_port")
- or int(os.environ.get("JIUWENBOX_PROXY_PORT", "8322"))
- )
-
-
@pytest.fixture(scope="session")
def test_llm_endpoint(pytestconfig):
"""LLM endpoint URL for testing."""
@@ -176,9 +165,3 @@ def test_llm_model(pytestconfig):
def llm_available(docker_gateway_ip):
"""Extract LLM availability from topology check result."""
return docker_gateway_ip.get("llm_available", False)
-
-
-def policy() -> SecurityPolicy:
- """Return the default policy."""
- return SecurityPolicy()
diff --git a/jiuwenbox/tests/integration/test_inference_privacy_proxy.py b/jiuwenbox/tests/integration/test_inference_privacy_proxy.py
index 1843c53031..73e6311ac4 100644
--- a/jiuwenbox/tests/integration/test_inference_privacy_proxy.py
+++ b/jiuwenbox/tests/integration/test_inference_privacy_proxy.py
@@ -1,7 +1,6 @@
"""Integration tests for HTTP-aware inference privacy proxy with path routing."""
import asyncio
-import copy
import http.client
import json
import logging
@@ -25,44 +24,9 @@ from jiuwenbox.proxy.inference_privacy_proxy_manager import (
)
NUM_THREADS = 5
-
-SYSTEM_BIND_MOUNTS = [
- {"host_path": "/bin", "sandbox_path": "/bin", "mode": "ro"},
- {"host_path": "/sbin", "sandbox_path": "/sbin", "mode": "ro"},
- {"host_path": "/usr", "sandbox_path": "/usr", "mode": "ro"},
- {"host_path": "/lib", "sandbox_path": "/lib", "mode": "ro"},
- {"host_path": "/lib64", "sandbox_path": "/lib64", "mode": "ro"},
- {"host_path": "/etc/resolv.conf", "sandbox_path": "/etc/resolv.conf", "mode": "ro"},
- {"host_path": "/etc/hosts", "sandbox_path": "/etc/hosts", "mode": "ro"},
- {"host_path": "/etc/nsswitch.conf", "sandbox_path": "/etc/nsswitch.conf", "mode": "ro"},
- {"host_path": "/etc/host.conf", "sandbox_path": "/etc/host.conf", "mode": "ro"},
- {"host_path": "/etc/ssl/certs", "sandbox_path": "/etc/ssl/certs", "mode": "ro"},
- {"host_path": "/etc/ssl/openssl.cnf", "sandbox_path": "/etc/ssl/openssl.cnf", "mode": "ro"},
- {"host_path": "/opt", "sandbox_path": "/opt", "mode": "ro"},
-]
-TMP_DIRECTORY = {"path": "/tmp", "permissions": "1777"}
-LONG_RUNNING_COMMAND = ["python3", "-c", "import time; time.sleep(36000)"]
logger = logging.getLogger(__name__)
-def _with_runtime_support(policy: dict) -> dict:
- runtime_policy = copy.deepcopy(policy)
- filesystem_policy = runtime_policy.setdefault("filesystem_policy", {})
- bind_mounts = filesystem_policy.setdefault("bind_mounts", [])
- for mount in SYSTEM_BIND_MOUNTS:
- if mount not in bind_mounts:
- bind_mounts.append(mount.copy())
-
- directories = filesystem_policy.setdefault("directories", [])
- if "/tmp" in filesystem_policy.get("read_write", []) and not any(
- d == "/tmp" or (isinstance(d, dict) and d.get("path") == "/tmp")
- for d in directories
- ):
- directories.append(TMP_DIRECTORY.copy())
-
- return runtime_policy
-
-
@pytest.fixture
def manager():
mgr = InferencePrivacyProxyManager()
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 eafa17057f..f9a279d6be 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts
@@ -84,7 +84,10 @@ function showRuntime(
}
function usageText(): string {
- return [
+ // 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)",
"/sandbox disable leave sandbox mode (recreates agent)",
@@ -95,7 +98,8 @@ function usageText(): string {
"/sandbox files deny <path> deny accessing <path> in sandbox",
"/sandbox files remove <path> remove the path from both allow & deny",
"/sandbox files list list configured files",
- ].join("\n");
+ ];
+ return lines.map((line, i) => (i === 0 ? line : ` ${line}`)).join("\n");
}
export function createSandboxCommand(): SlashCommand {