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: support internet connection on isolated network mode

zhaozixuan283ae94663dd
diff --git a/jiuwenbox/README.md b/jiuwenbox/README.md
index 3fb9d37194..c601573e67 100644
--- a/jiuwenbox/README.md
+++ b/jiuwenbox/README.md
@@ -12,7 +12,7 @@ isolation policy in-process by spawning `bubblewrap` directly for each sandbox
- Process isolation with `bubblewrap`
- Static policy-based filesystem access rules
-- Configurable sandbox backing workspace through `sandbox_workspace`
+- Server-managed sandbox backing storage (`~/.jiuwenbox/workspace`)
- Optional network isolation with Linux network namespaces and firewall rules
- Namespace and Linux capability controls
- Landlock filesystem enforcement when supported by the kernel
@@ -51,6 +51,8 @@ isolation policy in-process by spawning `bubblewrap` directly for each sandbox
- Python 3.11+
- `bubblewrap`
- `iproute2`, `iptables`, and `nftables` when `network.mode: isolated` is used
+- `NET_ADMIN` capability and `net.ipv4.ip_forward=1` on the host when isolated
+ mode uses uplink egress
- Kernel support for Landlock and seccomp when those features are enabled
- `nodejs` if JavaScript execution is needed
@@ -265,34 +267,157 @@ ls /tmp/jiuwenbox-logs
The server loads one static default policy at startup. Policy dynamic update is
not enabled.
-Important fields:
-
-- `sandbox_workspace`
- - Host directory used for server-managed sandbox backing storage.
- - The value must be absolute after `~` and environment variables are expanded.
-- `filesystem_policy.directories`
- - Directories created by the server and bound into each sandbox for its
- lifecycle.
-- `filesystem_policy.read_only`
- - Sandbox-visible paths granted read-only access. These entries do not mount
- host paths by themselves.
-- `filesystem_policy.read_write`
- - Sandbox-visible paths granted read-write access. Use `directories` or
- `bind_mounts` to make the paths exist inside the sandbox.
-- `filesystem_policy.bind_mounts`
- - Explicit host-to-sandbox bind mounts.
-- `filesystem_policy.device`
- - Explicit device nodes exposed inside the sandbox with `bwrap --dev-bind`.
-
-Path fields support shell-style expansion such as `~` and environment
-variables.
-
-Minimal example:
+### Field Reference
+
+#### Top-level fields
+
+| Field | Default | Notes |
+| --- | --- | --- |
+| `version` | `1` | Policy schema version. Only `1` is supported today. |
+| `name` | `"default"` | Human-readable name shown by the policy API. |
+| `environment` | `{}` | Environment variables injected into every process inside the sandbox. |
+
+#### `filesystem_policy`
+
+| Field | Notes |
+| --- | --- |
+| `directories` | Directories created by the server and bound into the sandbox for its lifecycle. Each entry may be a `"/path"` string or a `{ path, permissions }` object (`permissions` is octal, e.g. `"0755"`). |
+| `files` | Empty files created by the server and bound into the sandbox. Same shape as `directories`, with optional `permissions`. |
+| `read_only` | Sandbox-visible paths granted read-only access. These entries do not mount host paths by themselves; pair them with `bind_mounts` / `directories`. |
+| `read_write` | Sandbox-visible paths granted read-write access. Use `directories` or `bind_mounts` to make the paths exist inside the sandbox. |
+| `bind_mounts` | Explicit host-to-sandbox bind mounts with `host_path`, `sandbox_path`, and `mode` (`ro` / `rw`). `host_path` cannot be the literal `"*"`. |
+| `bind_root_entries` | Bind every **first-level** child under `host_root` to `sandbox_path/{name}`. Supports `mode`, `include_hidden` (hidden entries excluded by default), and `exclude` (fnmatch globs). Useful for bulk-mounting immediate children of `/usr` and similar trees. |
+| `device` | Device nodes exposed inside the sandbox with `bwrap --dev-bind`; each item has `host_path` and `sandbox_path`. |
+
+#### `process`
+
+| Field | Default | Notes |
+| --- | --- | --- |
+| `run_as_user` | `sandbox` | User name for sandbox processes. Falls back to nobody-style UIDs when unresolved. |
+| `run_as_group` | `sandbox` | Group name for sandbox processes. Falls back to nobody-style GIDs when unresolved. |
+
+#### `namespace`
+
+Controls Linux namespaces created by `bubblewrap`. Each field is `true` (create new) or `false` (reuse current):
+
+| Field | Default | Notes |
+| --- | --- | --- |
+| `user` | `true` | User namespace. |
+| `pid` | `true` | PID namespace. |
+| `ipc` | `true` | IPC namespace. |
+| `cgroup` | `true` | Cgroup namespace. |
+| `uts` | `true` | UTS (hostname) namespace. |
+
+#### `capabilities`
+
+| Field | Default | Notes |
+| --- | --- | --- |
+| `add` | `[]` | Extra capabilities to grant, e.g. `["CAP_NET_RAW"]` or `["NET_RAW"]`. |
+| `drop` | `[]` | Capabilities to drop. `"ALL"` drops every capability when bubblewrap supports it. |
+
+#### `landlock`
+
+| Field | Default | Notes |
+| --- | --- | --- |
+| `compatibility` | `best_effort` | `disabled`: do not apply Landlock; `best_effort`: apply when supported, otherwise continue; `hard_requirement`: fail sandbox startup if Landlock is unavailable. |
+
+#### `syscall`
+
+Per-architecture seccomp syscall block lists:
+
+| Field | Notes |
+| --- | --- |
+| `x86_64.blocked` | Syscall names blocked on x86_64, e.g. `ptrace`, `mount`, `bpf`. Empty means no extra blocking. |
+| `arm64.blocked` | Syscall names blocked on arm64/aarch64. |
+
+#### `network`
+
+Outbound (`egress`) and inbound (`ingress`) traffic rules. **Only enforced when `mode` is `isolated`**; in `host` mode these rules are not installed inside the sandbox.
+
+**`mode`**
+
+| Mode | Behavior |
+| --- | --- |
+| `isolated` (default) | Creates a dedicated network namespace per sandbox (`jbx-{sandbox_id}`), connects it to the host default route via a veth uplink, and installs `egress` / `ingress` iptables rules inside the sandbox netns. |
+| `host` | Sandbox processes share the host network namespace. **No** egress/ingress firewall rules are installed inside the sandbox, so `blocked_ips`, `blocked_domains`, and similar fields have no effect. In host mode, only the jiuwenbox management port (default 8321) is protected via `uid-owner` iptables rules. |
+
+For intranet deployments that need egress restrictions (for example `blocked_ips` to block RFC1918 addresses), use `isolated` mode with `uplink` configured. Do not rely on `host` mode for egress enforcement.
+
+**`uplink`** (`isolated` mode only)
+
+Each sandbox gets a veth pair (`jwbH{hash}` / `jwbS{hash}`), an address, a default route, and optional NAT through the host.
+
+| Field | Default | Notes |
+| --- | --- | --- |
+| `subnet` | `""` (auto-select) | IPv4 CIDR pool for the uplink. When empty, jiuwenbox scans private pools (`100.64.0.0/10`, focused `10.200.x/16` ranges, `172.30.0.0/16`, `172.31.0.0/16`, `192.168.240.0/20`, then `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`) and allocates a `/30` block that does not overlap any IPv4 route (`ip route show table all`). When set, the value is treated as an address pool and a free `/30` is chosen inside it. |
+| `nat` | `true` | Whether to MASQUERADE uplink traffic on the host side. Usually required in intranet deployments so sandboxes can reach external destinations through the host default route. |
+| `interface` | `""` (auto-detect) | Egress interface name. When empty, jiuwenbox auto-detects the interface used by the host default route. |
+
+**`egress` / `ingress`**
+
+| Field | Notes |
+| --- | --- |
+| `default` | `allow`: permit traffic unless it matches a `blocked_*` rule; `deny`: block traffic unless it matches an `allowed_*` rule. |
+| `blocked_ips` / `allowed_ips` | CIDR-based IP rules applied to the sandbox netns OUTPUT / INPUT chains. `blocked_*` takes precedence over `allowed_*`. |
+| `blocked_domains` / `allowed_domains` | Domain rules resolved via DNS and applied to the resolved IPs. |
+| `blocked_ports` / `allowed_ports` | TCP port rules. |
+
+iptables rules live in the sandbox netns (`jbx-{sandbox_id}`), not in the container or host default netns. When debugging egress blocks, inspect rules inside the corresponding netns:
+
+```bash
+ip netns list
+ip netns exec jbx-<sandbox_id> iptables -L OUTPUT -n
+```
+
+Docker deployments using `isolated` + uplink need `net.ipv4.ip_forward=1` and
+`NET_ADMIN`; `run_docker.sh` already passes both. Grant the same privileges if
+you run `docker run` manually.
+
+#### `cgroup`
+
+Optional per-sandbox cgroup resource limits. All three fields default to `null`
+(no limit). When every field is empty or the `cgroup` block is omitted,
+jiuwenbox skips cgroup setup so the default policy still runs on hosts without
+a writable cgroup tree.
+
+| Field | Format | Notes |
+| --- | --- | --- |
+| `memory_max` | Integer bytes or a unit string (e.g. `"256M"`, `"1G"`) | Memory cap. |
+| `cpu_max` | Fractional cores (e.g. `0.5`) or a `"quota_us period_us"` pair (e.g. `"50000 100000"`) | CPU quota. |
+| `pids_max` | Positive integer | Process/thread cap. |
+
+Cgroup v2 is preferred; v1 is used as a fallback. If at least one field is
+non-null and neither backend is writable, sandbox creation fails.
+
+#### `timeout`
+
+jiuwenbox **server-side** idle sandbox reaping. **Only the root policy loaded
+at server startup takes effect**; the same fields on per-sandbox policies do
+not affect isolation and are returned for display only.
+
+| Field | Default | Notes |
+| --- | --- | --- |
+| `idle_timeout` | `null` (disabled) | Maximum idle duration in seconds. `null` / `0` / negative disables reaping. Idle means time since the last exec / file IO / list-dir API call; `get_sandbox` / `list_sandboxes` / `get_logs` do not refresh the timer. |
+| `idle_check_interval` | `60` | Reaper poll interval in seconds. Must be `> 0`. |
+
+#### `inference_privacy_proxies`
+
+Inference privacy proxy settings. `listen_port: 0` (default) disables the
+proxy; when enabled, set both `listen_host` (IP address) and
+`listen_port > 0`. `routes` defines per-`path_prefix` forwarding targets and
+API key injection. See [Inference Privacy Proxy](#inference-privacy-proxy)
+below.
+
+If the policy contains only `version` / `name` /
+`inference_privacy_proxies` and `listen_port > 0`, jiuwenbox enters
+proxy-only mode (skips the sandbox subsystem). See
+[`src/jiuwenbox/configs/inference-policy.yaml`](src/jiuwenbox/configs/inference-policy.yaml).
+
+### Minimal example
```yaml
version: 1
name: "example"
-sandbox_workspace: "/sandbox"
filesystem_policy:
directories:
@@ -381,6 +506,9 @@ syscall:
network:
mode: isolated
+ uplink:
+ nat: true
+ interface: ""
egress:
default: allow
allowed_domains: []
@@ -604,10 +732,11 @@ flag to maintain in sync:
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:
+Run specific test cases:
```bash
-python3 -m pytest tests/integration/test_server_api_default.py::TestPolicyEnforcement::test_network_mode_isolated_blocks_http_requests -s --server-endpoint 127.0.0.1:8321
+python3 -m pytest tests/integration/test_server_api_default.py::TestPolicyEnforcement::test_network_mode_isolated_allows_external_http_requests -s --server-endpoint 127.0.0.1:8321
+python3 -m pytest tests/integration/test_server_api_default.py::TestPolicyEnforcement::test_network_mode_isolated_blocked_ip_rejects_egress -s --server-endpoint 127.0.0.1:8321
```
### Performance Tests
diff --git a/jiuwenbox/README_CN.md b/jiuwenbox/README_CN.md
index b2e04a27c9..4a59eccf98 100644
--- a/jiuwenbox/README_CN.md
+++ b/jiuwenbox/README_CN.md
@@ -12,7 +12,7 @@ agent 工具和代码片段。
- 基于 `bubblewrap` 的进程隔离
- 基于静态 policy 的文件系统访问控制
-- 通过 `sandbox_workspace` 配置沙箱后端工作目录
+- 服务端管理的沙箱后端存储(`~/.jiuwenbox/workspace`)
- 可选的 Linux 网络命名空间和防火墙网络隔离
- 命名空间和 Linux capability 控制
- 在内核支持时启用 Landlock 文件系统约束
@@ -47,6 +47,7 @@ agent 工具和代码片段。
- Python 3.11+
- `bubblewrap`
- 使用 `network.mode: isolated` 时需要 `iproute2`、`iptables` 和 `nftables`
+- `isolated` 模式启用 uplink 出网时,宿主机需开启 IPv4 转发(`net.ipv4.ip_forward=1`),进程需具备 `NET_ADMIN` capability
- 启用 Landlock 和 seccomp 时需要内核支持对应能力
- 如果需要执行 JavaScript,则需要 `nodejs`
@@ -185,12 +186,6 @@ UDS 相关环境变量:
开启**审计日志**的持久化。文件**销毁沙箱时不再删除**,便于事后离线
分析、滚动归档、外挂到日志收集系统。
-> 注意:历史版本曾把沙箱 daemon / 后台 exec 的原始 stdout/stderr 写到
-> `runtime.log` / `runtime.bg-N.log` 这一组文件里,现在已经**完全移除**。
-> 审计日志里 `exec_command` 事件本身就携带了每条命令截断后的 stdout/stderr
-> (默认 4 KiB),日常排障已经够用;如果确实需要看原始字节流,请用
-> `docker run -it` 直接看 bwrap 的实时输出。
-
审计 JSONL 里**每个操作只落一行**,在调用返回后写出,同时携带"做了什么"
和"结果如何"。只看 JSONL 就能回答"这条指令到底成不成功":
@@ -249,31 +244,142 @@ ls /tmp/jiuwenbox-logs
服务启动时会加载一个静态默认 policy。当前不启用 policy 动态更新功能。
-重要字段:
+### 字段说明
+
+#### 顶层字段
+
+| 字段 | 默认 | 说明 |
+| --- | --- | --- |
+| `version` | `1` | Policy schema 版本,当前仅支持 `1`。 |
+| `name` | `"default"` | 可读名称,供 policy API 展示。 |
+| `environment` | `{}` | 注入到沙箱内每个进程的环境变量键值对。 |
+
+#### `filesystem_policy`
+
+| 字段 | 说明 |
+| --- | --- |
+| `directories` | 沙箱生命周期内由服务端创建并 bind 进沙箱的目录。条目可以是 `"/path"` 字符串,或 `{ path, permissions }` 对象(`permissions` 为八进制,如 `"0755"`)。 |
+| `files` | 沙箱生命周期内由服务端创建并 bind 进沙箱的空文件。格式与 `directories` 类似,支持可选 `permissions`。 |
+| `read_only` | 沙箱内可见路径的只读授权列表;本身不会挂载宿主机路径,需配合 `bind_mounts` / `directories` 让路径存在。 |
+| `read_write` | 沙箱内可见路径的读写授权列表;需通过 `directories` 或 `bind_mounts` 让路径实际存在。 |
+| `bind_mounts` | 显式宿主机到沙箱的 bind mount,每项包含 `host_path`、`sandbox_path`、`mode`(`ro` / `rw`)。`host_path` 不能为字面量 `"*"`。 |
+| `bind_root_entries` | 将 `host_root` 下**第一层**子项逐个 bind 到 `sandbox_path/{name}`。支持 `mode`、`include_hidden`(默认排除 `.` 开头项)、`exclude`(fnmatch glob)。适合批量挂载 `/usr` 等目录的直接子项。 |
+| `device` | 通过 `bwrap --dev-bind` 暴露到沙箱内的设备节点,每项包含 `host_path` 和 `sandbox_path`。 |
+
+#### `process`
+
+| 字段 | 默认 | 说明 |
+| --- | --- | --- |
+| `run_as_user` | `sandbox` | 沙箱内进程运行的用户名;无法解析时回退到 nobody 类 UID。 |
+| `run_as_group` | `sandbox` | 沙箱内进程运行的组名;无法解析时回退到 nobody 类 GID。 |
+
+#### `namespace`
+
+控制 `bubblewrap` 创建的 Linux 命名空间,每项为 `true`(新建)或 `false`(复用当前):
+
+| 字段 | 默认 | 说明 |
+| --- | --- | --- |
+| `user` | `true` | 用户命名空间。 |
+| `pid` | `true` | PID 命名空间。 |
+| `ipc` | `true` | IPC 命名空间。 |
+| `cgroup` | `true` | cgroup 命名空间。 |
+| `uts` | `true` | UTS(主机名)命名空间。 |
+
+#### `capabilities`
+
+| 字段 | 默认 | 说明 |
+| --- | --- | --- |
+| `add` | `[]` | 额外授予的 capability,如 `["CAP_NET_RAW"]` 或 `["NET_RAW"]`。 |
+| `drop` | `[]` | 移除的 capability;`"ALL"` 表示在 bubblewrap 支持时丢弃全部 capability。 |
+
+#### `landlock`
+
+| 字段 | 默认 | 说明 |
+| --- | --- | --- |
+| `compatibility` | `best_effort` | `disabled`:不启用 Landlock;`best_effort`:支持则启用,否则继续;`hard_requirement`:不支持则沙箱启动失败。 |
+
+#### `syscall`
+
+按 CPU 架构配置 seccomp 拦截的系统调用名列表:
+
+| 字段 | 说明 |
+| --- | --- |
+| `x86_64.blocked` | x86_64 上拦截的 syscall 名,如 `ptrace`、`mount`、`bpf` 等。留空表示不额外拦截。 |
+| `arm64.blocked` | arm64/aarch64 上拦截的 syscall 名。 |
+
+#### `network`
+
+出站(`egress`)和入站(`ingress`)流量规则。**仅在 `mode: isolated` 时生效**;`host` 模式下这些规则不会安装到沙箱内。
+
+**`mode`**
+
+| 模式 | 行为 |
+| --- | --- |
+| `isolated`(默认) | 为每个沙箱创建独立网络命名空间(`jbx-{sandbox_id}`),通过 veth uplink 连接宿主机默认路由,并在沙箱 netns 内安装 `egress` / `ingress` iptables 规则。 |
+| `host` | 沙箱进程共享宿主机网络命名空间。**不会**在沙箱内安装 egress/ingress 防火墙规则,`blocked_ips`、`blocked_domains` 等字段不生效。host 模式仅通过 `uid-owner` iptables 保护 jiuwenbox 管理端口(默认 8321),防止沙箱进程访问管理 API。 |
+
+内网部署若需要 egress 封禁(例如 `blocked_ips` 封禁 RFC1918 地址),应使用 `isolated` 模式并配置 `uplink`,不要依赖 `host` 模式。
+
+**`uplink`**(仅 `isolated` 模式)
+
+每个沙箱创建一个 veth 对(`jwbH{hash}` / `jwbS{hash}`),配置地址与默认路由,并可选通过宿主机 NAT 出网。
+
+| 字段 | 默认 | 说明 |
+| --- | --- | --- |
+| `subnet` | `""`(自动选择) | uplink 使用的 IPv4 地址池。留空时 jiuwenbox 依次扫描私有网段(`100.64.0.0/10`、聚焦的 `10.200.x/16` 段、`172.30.0.0/16`、`172.31.0.0/16`、`192.168.240.0/20`,以及 `10.0.0.0/8`、`172.16.0.0/12`、`192.168.0.0/16`),在池内分配不与现有 IPv4 路由(`ip route show table all`)冲突的 `/30` 网段。显式配置时将该 CIDR 视为地址池,并在其中选取空闲 `/30`。 |
+| `nat` | `true` | 是否在宿主机侧对 uplink 流量做 MASQUERADE。内网部署通常需要开启,沙箱才能通过宿主机默认路由访问外网。 |
+| `interface` | `""`(自动探测) | 出网网卡名称。留空时自动探测宿主机默认路由对应的网卡。 |
+
+**`egress` / `ingress`**
+
+| 字段 | 说明 |
+| --- | --- |
+| `default` | `allow`:默认放行,仅 `blocked_*` 匹配项被拒绝;`deny`:默认拒绝,仅 `allowed_*` 匹配项被放行。 |
+| `blocked_ips` / `allowed_ips` | CIDR 格式 IP 规则,作用于沙箱 netns 的 OUTPUT / INPUT 链。`blocked_*` 优先于 `allowed_*`。 |
+| `blocked_domains` / `allowed_domains` | 域名规则,通过 DNS 解析后应用到解析出的 IP。 |
+| `blocked_ports` / `allowed_ports` | TCP 端口规则。 |
+
+iptables 规则写在沙箱 netns(`jbx-{sandbox_id}`)内,不在容器或宿主机的默认 netns。排查 egress 封禁时请进入对应 netns 查看:
+
+```bash
+ip netns list
+ip netns exec jbx-<sandbox_id> iptables -L OUTPUT -n
+```
+
+`isolated` + uplink 的 Docker 部署需要 `net.ipv4.ip_forward=1` 和 `NET_ADMIN`;`run_docker.sh` 已默认配置。自行 `docker run` 时需授予同等权限。
+
+#### `cgroup`
+
+可选的每沙箱 cgroup 资源限制。三个字段默认均为 `null`(不限);全部为空或省略 `cgroup` 块时,jiuwenbox 跳过 cgroup 设置,便于在无可用 cgroup 树的宿主机上运行。
+
+| 字段 | 格式 | 说明 |
+| --- | --- | --- |
+| `memory_max` | 字节整数或带单位字符串(如 `"256M"`、`"1G"`) | 内存上限。 |
+| `cpu_max` | 小数核数(如 `0.5`)或 `"quota_us period_us"` 对(如 `"50000 100000"`) | CPU 配额。 |
+| `pids_max` | 正整数 | 进程/线程数上限。 |
+
+优先使用 cgroup v2;v2 不可写时回退 v1。至少一个字段非空且两种后端均不可写时,沙箱创建失败。
+
+#### `timeout`
+
+jiuwenbox **服务端**的空闲沙箱淘汰配置,**仅在 server 启动时加载的根 policy 上生效**;per-sandbox policy 上的同名字段不影响沙箱隔离,仅用于配置回显。
+
+| 字段 | 默认 | 说明 |
+| --- | --- | --- |
+| `idle_timeout` | `null`(禁用) | 沙箱最大空闲时长(秒)。`null` / `0` / 负值表示禁用。空闲 = 自最后一次 exec / 文件 IO / 列目录等 API 调用以来的时长;`get_sandbox` / `list_sandboxes` / `get_logs` 不会刷新计时器。 |
+| `idle_check_interval` | `60` | reaper 轮询间隔(秒),必须 `> 0`。 |
+
+#### `inference_privacy_proxies`
-- `sandbox_workspace`
- - 用于服务端管理沙箱后端存储的宿主机目录。
- - 该值在展开 `~` 和环境变量之后必须是绝对路径。
-- `filesystem_policy.directories`
- - 由服务端创建并在沙箱生命周期内绑定到沙箱中的目录。
-- `filesystem_policy.read_only`
- - 沙箱内授予只读访问权限的路径;这些条目本身不会挂载 host 路径。
-- `filesystem_policy.read_write`
- - 沙箱内授予读写访问权限的路径;需要通过 `directories` 或 `bind_mounts`
- 让这些路径实际存在于沙箱内。
-- `filesystem_policy.bind_mounts`
- - 显式的宿主机到沙箱路径的 bind mount 配置。
-- `filesystem_policy.device`
- - 使用 `bwrap --dev-bind` 暴露到沙箱内的显式设备节点。
+推理隐私代理配置。`listen_port: 0`(默认)表示禁用;启用时需同时设置 `listen_host`(IP 地址)和 `listen_port > 0`。`routes` 定义按 `path_prefix` 转发的目标端点和 API 密钥注入规则。详见下文 [推理隐私代理](#推理隐私代理) 章节。
-路径字段支持 shell 风格的展开,例如 `~` 和环境变量。
+若 policy 仅包含 `version` / `name` / `inference_privacy_proxies` 且 `listen_port > 0`,jiuwenbox 会进入仅代理模式(跳过沙箱子系统)。参考 [`src/jiuwenbox/configs/inference-policy.yaml`](src/jiuwenbox/configs/inference-policy.yaml)。
-最小示例:
+### 最小示例
```yaml
version: 1
name: "example"
-sandbox_workspace: "/sandbox"
filesystem_policy:
directories:
@@ -362,6 +468,9 @@ syscall:
network:
mode: isolated
+ uplink:
+ nat: true
+ interface: ""
egress:
default: allow
allowed_domains: []
@@ -573,7 +682,8 @@ inference_privacy_proxies:
`--server-endpoint=URI` 切换连接方式,**传输协议自动从 URI 形式推断**:
```bash
-# TCP (默认通路,等价于 --server-endpoint=http://127.0.0.1:8321)
+# TCP(默认通路,等价于 --server-endpoint=http://127.0.0.1:8321;
+# server 应以 default-policy.yaml 作为安全策略启动)
./tests/test.sh default
# 自定义 TCP 监听 (host:port 会自动补 http:// 前缀)
@@ -592,7 +702,8 @@ inference_privacy_proxies:
运行指定测试用例:
```bash
-python3 -m pytest tests/integration/test_server_api_default.py::TestPolicyEnforcement::test_network_mode_isolated_blocks_http_requests -s --server-endpoint 127.0.0.1:8321
+python3 -m pytest tests/integration/test_server_api_default.py::TestPolicyEnforcement::test_network_mode_isolated_allows_external_http_requests -s --server-endpoint 127.0.0.1:8321
+python3 -m pytest tests/integration/test_server_api_default.py::TestPolicyEnforcement::test_network_mode_isolated_blocked_ip_rejects_egress -s --server-endpoint 127.0.0.1:8321
```
### 性能测试
diff --git a/jiuwenbox/docs/jiuwenbox_server_api.md b/jiuwenbox/docs/jiuwenbox_server_api.md
index fd2dfc5462..ac8b5df920 100644
--- a/jiuwenbox/docs/jiuwenbox_server_api.md
+++ b/jiuwenbox/docs/jiuwenbox_server_api.md
@@ -223,6 +223,7 @@ print(resp.json())
| `env` | object | 否 | 沙箱公共环境变量 |
| `policy` | object/null | 否 | 覆盖或追加的 policy 数据 |
| `policy_mode` | string | 否 | `override` 或 `append`,默认 `override` |
+| `sandbox_id` | string/null | 否 | 可选,指定沙箱 ID。长度 4~16,仅允许小写字母、数字、减号(`-`)和下划线(`_`)。省略或空字符串时服务端自动生成(形如 `6011f5ca-76a`)。格式非法返回 400;与已有 ID 冲突返回 409 |
Python 请求示例:
@@ -232,6 +233,7 @@ import requests
resp = requests.post(
"http://127.0.0.1:8321/api/v1/sandboxes",
json={
+ "sandbox_id": "my-sb_01",
"env": {
"DEMO_KEY": "demo-value"
},
@@ -243,11 +245,11 @@ print(resp.status_code)
print(resp.json())
```
-响应示例:
+响应示例(指定 `sandbox_id` 时返回该值;省略时自动生成,形如 `6011f5ca-76a`):
```json
{
- "id": "abc123def456",
+ "id": "my-sb_01",
"phase": "ready",
"runtime": "process",
"pid": 12345,
diff --git a/jiuwenbox/scripts/run_docker.sh b/jiuwenbox/scripts/run_docker.sh
index 7cb1e57cf8..96e32819bb 100755
--- a/jiuwenbox/scripts/run_docker.sh
+++ b/jiuwenbox/scripts/run_docker.sh
@@ -226,6 +226,7 @@ echo
docker run -itd \
--name "$CONTAINER_NAME" \
--restart=unless-stopped \
+ --sysctl net.ipv4.ip_forward=1 \
--cap-add=SYS_ADMIN \
--cap-add=NET_ADMIN \
--security-opt seccomp=unconfined \
diff --git a/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py b/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py
index fe5fd56f2d..a2be180c7c 100644
--- a/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py
+++ b/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py
@@ -298,6 +298,7 @@ class _CliClient:
env: dict[str, str] | None = None,
policy: Any = None,
policy_mode: str | None = None,
+ sandbox_id: str | None = None,
) -> dict[str, Any]:
body: dict[str, Any] = {}
if env is not None:
@@ -306,6 +307,8 @@ class _CliClient:
body["policy"] = policy
if policy_mode is not None:
body["policy_mode"] = policy_mode
+ if sandbox_id is not None:
+ body["sandbox_id"] = sandbox_id
return dict(self._post(f"{_API_PREFIX}/sandboxes", json=body).json())
def sandbox_list(self) -> list[dict[str, Any]]:
@@ -675,6 +678,7 @@ def cmd_sandbox_create(args: argparse.Namespace, client: _CliClient) -> Any:
env=env,
policy=policy,
policy_mode=args.policy_mode,
+ sandbox_id=args.sandbox_id,
)
@@ -1046,6 +1050,10 @@ def build_parser() -> argparse.ArgumentParser:
"--policy-mode", choices=["override", "append"], default=None,
help="policy merge mode (default server-side 'override')",
)
+ p.add_argument(
+ "--sandbox-id",
+ help="optional sandbox id (4-16 chars: lowercase letters, digits, -, _)",
+ )
p.set_defaults(_handler=cmd_sandbox_create)
p = sandbox_subs.add_parser("ls", help="list sandboxes")
diff --git a/jiuwenbox/src/jiuwenbox/configs/default-policy.yaml b/jiuwenbox/src/jiuwenbox/configs/default-policy.yaml
index 017903d9a7..c8c6e668ef 100644
--- a/jiuwenbox/src/jiuwenbox/configs/default-policy.yaml
+++ b/jiuwenbox/src/jiuwenbox/configs/default-policy.yaml
@@ -225,7 +225,15 @@ network:
# mode:
# isolated: create a dedicated network namespace and apply these rules
# host: use host networking and skip namespace firewall setup
- mode: host
+ mode: isolated
+
+ # Uplink for isolated network namespaces. Each sandbox gets a veth pair,
+ # a default route, and optional NAT through the host/container default route.
+ # When subnet is omitted, jiuwenbox selects a private IPv4 range that does
+ # not overlap with current routes.
+ uplink:
+ nat: true
+ interface: ""
# Outbound traffic from sandbox to outside destinations.
egress:
diff --git a/jiuwenbox/src/jiuwenbox/configs/enterprise-policy.yaml b/jiuwenbox/src/jiuwenbox/configs/enterprise-policy.yaml
index 356ae1dd12..f67523e6de 100644
--- a/jiuwenbox/src/jiuwenbox/configs/enterprise-policy.yaml
+++ b/jiuwenbox/src/jiuwenbox/configs/enterprise-policy.yaml
@@ -222,7 +222,15 @@ network:
# mode:
# isolated: create a dedicated network namespace and apply these rules
# host: use host networking and skip namespace firewall setup
- mode: host
+ mode: isolated
+
+ # Uplink for isolated network namespaces. Each sandbox gets a veth pair,
+ # a default route, and optional NAT through the host/container default route.
+ # When subnet is omitted, jiuwenbox selects a private IPv4 range that does
+ # not overlap with current routes.
+ uplink:
+ nat: true
+ interface: ""
# Outbound traffic from sandbox to outside destinations.
egress:
diff --git a/jiuwenbox/src/jiuwenbox/models/__init__.py b/jiuwenbox/src/jiuwenbox/models/__init__.py
index 340e021d8a..3f02b228f0 100644
--- a/jiuwenbox/src/jiuwenbox/models/__init__.py
+++ b/jiuwenbox/src/jiuwenbox/models/__init__.py
@@ -3,6 +3,7 @@
from jiuwenbox.models.sandbox import (
BackgroundExecResult,
ExecResult,
+ InvalidSandboxIdError,
SandboxPhase,
SandboxRef,
SandboxSpec,
@@ -31,6 +32,7 @@ from jiuwenbox.models.common import (
__all__ = [
"BackgroundExecResult",
"ExecResult",
+ "InvalidSandboxIdError",
"SandboxPhase",
"SandboxRef",
"SandboxSpec",
diff --git a/jiuwenbox/src/jiuwenbox/models/policy.py b/jiuwenbox/src/jiuwenbox/models/policy.py
index eeff7dd931..e7d5f9347d 100644
--- a/jiuwenbox/src/jiuwenbox/models/policy.py
+++ b/jiuwenbox/src/jiuwenbox/models/policy.py
@@ -584,8 +584,32 @@ class InferencePrivacyProxyPolicy(BaseModel):
return value.strip()
+class NetworkUplinkPolicy(BaseModel):
+ subnet: str = ""
+ nat: bool = True
+ interface: str = ""
+
+ @field_validator("subnet", mode="after")
+ @classmethod
+ def validate_subnet(cls, value: str) -> str:
+ import ipaddress
+
+ if not value.strip():
+ return ""
+ try:
+ network = ipaddress.ip_network(value, strict=False)
+ except ValueError as exc:
+ raise ValueError(f"uplink.subnet must be a valid CIDR: {value}") from exc
+ if network.version != 4:
+ raise ValueError("uplink.subnet must be an IPv4 CIDR")
+ if network.prefixlen > 24:
+ raise ValueError("uplink.subnet prefix must be /24 or shorter")
+ return str(network)
+
+
class NetworkPolicy(BaseModel):
mode: NetworkMode = NetworkMode.ISOLATED
+ uplink: NetworkUplinkPolicy = Field(default_factory=NetworkUplinkPolicy)
egress: NetworkRulePolicy = Field(default_factory=NetworkRulePolicy)
ingress: NetworkRulePolicy = Field(default_factory=NetworkRulePolicy)
diff --git a/jiuwenbox/src/jiuwenbox/models/sandbox.py b/jiuwenbox/src/jiuwenbox/models/sandbox.py
index 85e8eeb3c8..0ce81f3c8d 100644
--- a/jiuwenbox/src/jiuwenbox/models/sandbox.py
+++ b/jiuwenbox/src/jiuwenbox/models/sandbox.py
@@ -4,9 +4,37 @@
from __future__ import annotations
import enum
+import re
+import uuid
from datetime import datetime
+
from pydantic import BaseModel, Field
+SANDBOX_ID_MIN_LEN = 4
+SANDBOX_ID_MAX_LEN = 16
+CUSTOM_SANDBOX_ID_RE = re.compile(r"^[0-9a-z_-]{4,16}$")
+
+SANDBOX_ID_FORMAT_MESSAGE = (
+ "sandbox_id must be 4-16 characters and contain only lowercase letters, "
+ "digits, hyphens, and underscores (e.g. my-sb_01)"
+)
+
+
+class InvalidSandboxIdError(Exception):
+ """Raised when a user-supplied sandbox_id fails format validation."""
+
+
+def generate_sandbox_id() -> str:
+ """Generate a sandbox id using the existing uuid4[:12] scheme."""
+ return str(uuid.uuid4())[:12]
+
+
+def validate_custom_sandbox_id(value: str) -> str:
+ """Validate a user-supplied sandbox_id; return it unchanged on success."""
+ if not CUSTOM_SANDBOX_ID_RE.fullmatch(value):
+ raise InvalidSandboxIdError(SANDBOX_ID_FORMAT_MESSAGE)
+ return value
+
class SandboxPhase(str, enum.Enum):
PROVISIONING = "provisioning"
@@ -25,6 +53,7 @@ class SandboxSpec(BaseModel):
"""Specification for creating a sandbox."""
env: dict[str, str] = Field(default_factory=dict)
+ sandbox_id: str | None = None
class SandboxRef(BaseModel):
diff --git a/jiuwenbox/src/jiuwenbox/server/app.py b/jiuwenbox/src/jiuwenbox/server/app.py
index d27376fe57..958be301e2 100644
--- a/jiuwenbox/src/jiuwenbox/server/app.py
+++ b/jiuwenbox/src/jiuwenbox/server/app.py
@@ -18,7 +18,9 @@ from pydantic import ValidationError
from jiuwenbox.logging_config import configure_logging
from jiuwenbox import __version__
from jiuwenbox.server.audit_logger import AuditLogger
+from jiuwenbox.models.sandbox import InvalidSandboxIdError
from jiuwenbox.server.sandbox_manager import (
+ SandboxConflictError,
SandboxManager,
SandboxNotFoundError,
SandboxStateError,
@@ -390,6 +392,14 @@ def create_app() -> FastAPI:
async def state_error_handler(request: Request, exc: SandboxStateError):
return JSONResponse(status_code=409, content={"error": str(exc)})
+ @application.exception_handler(SandboxConflictError)
+ async def conflict_error_handler(request: Request, exc: SandboxConflictError):
+ return JSONResponse(status_code=409, content={"error": str(exc)})
+
+ @application.exception_handler(InvalidSandboxIdError)
+ async def invalid_sandbox_id_handler(request: Request, exc: InvalidSandboxIdError):
+ return JSONResponse(status_code=400, content={"error": str(exc)})
+
@application.exception_handler(PolicyValidationError)
async def policy_validation_error_handler(request: Request, exc: PolicyValidationError):
return JSONResponse(status_code=400, content={"error": str(exc)})
diff --git a/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py b/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py
index fd76d747df..f1a7d42ffb 100644
--- a/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py
+++ b/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py
@@ -35,6 +35,7 @@ class CreateSandboxRequest(BaseModel):
env: dict[str, str] = Field(default_factory=dict)
policy: dict[str, Any] | None = None
policy_mode: PolicyMode = PolicyMode.OVERRIDE
+ sandbox_id: str | None = None
class ExecRequest(BaseModel):
@@ -55,7 +56,11 @@ class ListFilesQuery(BaseModel):
@router.post("/sandboxes", response_model=SandboxRef, status_code=201)
async def create_sandbox(request: CreateSandboxRequest):
- spec = SandboxSpec(env=request.env)
+ if request.sandbox_id is None or request.sandbox_id.strip() == "":
+ sandbox_id = None
+ else:
+ sandbox_id = request.sandbox_id
+ spec = SandboxSpec(env=request.env, sandbox_id=sandbox_id)
return await _mgr().create_sandbox(
spec,
policy_data=request.policy,
diff --git a/jiuwenbox/src/jiuwenbox/server/runtime/process.py b/jiuwenbox/src/jiuwenbox/server/runtime/process.py
index 3ae5afee65..6618a3f146 100644
--- a/jiuwenbox/src/jiuwenbox/server/runtime/process.py
+++ b/jiuwenbox/src/jiuwenbox/server/runtime/process.py
@@ -510,6 +510,7 @@ class ProcessRuntime(RuntimeAdapter):
self._policy_binds: dict[str, list[dict[str, str]]] = {}
self._network_modes: dict[str, NetworkMode] = {}
self._netns_names: dict[str, str] = {}
+ self._uplink_handles: dict[str, network_module.UplinkHandle] = {}
self._directory_roots: dict[str, Path] = {}
self._file_roots: dict[str, Path] = {}
self._launcher_dirs: dict[str, Path] = {}
@@ -833,12 +834,22 @@ class ProcessRuntime(RuntimeAdapter):
namespace = self._get_netns_name(sandbox_id)
if network_module.namespace_exists(namespace):
- return namespace
+ network_module.delete_named_namespace(namespace)
network_module.create_named_namespace(namespace)
+ uplink_handle: network_module.UplinkHandle | None = None
try:
+ uplink_handle = network_module.setup_network_uplink(
+ namespace,
+ sandbox_id,
+ policy.network.uplink,
+ management_ports=self._server_protect_ports(),
+ )
network_module.setup_network_isolation(policy.network, namespace=namespace)
+ self._uplink_handles[sandbox_id] = uplink_handle
except Exception:
+ if uplink_handle is not None:
+ network_module.teardown_network_uplink(uplink_handle)
try:
network_module.delete_named_namespace(namespace)
except Exception:
@@ -1886,6 +1897,9 @@ class ProcessRuntime(RuntimeAdapter):
if control_dir is not None:
shutil.rmtree(control_dir, ignore_errors=True)
self._daemon_socket_ready.pop(sandbox_id, None)
+ uplink_handle = self._uplink_handles.pop(sandbox_id, None)
+ if uplink_handle is not None:
+ network_module.teardown_network_uplink(uplink_handle)
if netns_name and network_module.namespace_exists(netns_name):
network_module.delete_named_namespace(netns_name)
self._network_modes.pop(sandbox_id, None)
@@ -2709,10 +2723,14 @@ class ProcessRuntime(RuntimeAdapter):
sandbox_id,
network_module.netns_name_for_sandbox(sandbox_id),
)
+ uplink_handle = self._uplink_handles.pop(sandbox_id, None)
+ if uplink_handle is not None:
+ network_module.teardown_network_uplink(uplink_handle)
if network_module.namespace_exists(namespace):
network_module.delete_named_namespace(namespace)
else:
self._netns_names.pop(sandbox_id, None)
+ self._uplink_handles.pop(sandbox_id, None)
self._remove_sandbox_host_firewall_rules(sandbox_id)
directory_root = self._directory_roots.pop(sandbox_id, None)
diff --git a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py
index 1494085470..5d6774bcdf 100644
--- a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py
+++ b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py
@@ -16,7 +16,6 @@ import logging
import os
import textwrap
import time
-import uuid
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime, timezone
@@ -53,6 +52,8 @@ from jiuwenbox.models.sandbox import (
SandboxPhase,
SandboxRef,
SandboxSpec,
+ generate_sandbox_id,
+ validate_custom_sandbox_id,
)
from jiuwenbox.server.audit_logger import AuditLogger
from jiuwenbox.server.policy_engine import PolicyEngine
@@ -95,6 +96,10 @@ class SandboxStateError(Exception):
logger.error("%s: %s", self.__class__.__name__, str(self))
+class SandboxConflictError(Exception):
+ """Raised for expected request conflicts such as duplicate sandbox IDs."""
+
+
class SandboxManager:
"""Manages sandbox lifecycle and state."""
@@ -504,7 +509,17 @@ class SandboxManager:
) -> SandboxRef:
"""Create a new sandbox."""
async with self._lock:
- sandbox_id = str(uuid.uuid4())[:12]
+ if spec.sandbox_id is None:
+ sandbox_id = generate_sandbox_id()
+ while sandbox_id in self._sandboxes:
+ sandbox_id = generate_sandbox_id()
+ else:
+ validate_custom_sandbox_id(spec.sandbox_id)
+ if spec.sandbox_id in self._sandboxes:
+ raise SandboxConflictError(
+ f"Sandbox '{spec.sandbox_id}' already exists"
+ )
+ sandbox_id = spec.sandbox_id
policy = self._resolve_effective_policy(policy_data, policy_mode)
logger.debug("Creating sandbox %s with policy %s", sandbox_id, str(policy))
self.policy_engine.validate_policy(policy)
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/network.py b/jiuwenbox/src/jiuwenbox/supervisor/network.py
index b01af1ce71..ad0abc514a 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/network.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/network.py
@@ -6,6 +6,7 @@ This module configures iptables rules within a sandbox network namespace.
from __future__ import annotations
+import hashlib
import ipaddress
import logging
import shutil
@@ -15,7 +16,12 @@ from dataclasses import dataclass, field
from functools import lru_cache
from jiuwenbox.logging_config import configure_logging
-from jiuwenbox.models.policy import NetworkPolicy, NetworkMode, NetworkRulePolicy
+from jiuwenbox.models.policy import (
+ NetworkMode,
+ NetworkPolicy,
+ NetworkRulePolicy,
+ NetworkUplinkPolicy,
+)
configure_logging()
logger = logging.getLogger(__name__)
@@ -202,7 +208,11 @@ def _run_iptables_binary(
@lru_cache(maxsize=128)
-def _select_iptables_binary(ip_version: int, namespace: str | None = None) -> str:
+def _select_iptables_binary(
+ ip_version: int,
+ namespace: str | None = None,
+ table: str = "filter",
+) -> str:
"""Return a working iptables backend for the target namespace.
Some distributions default iptables to the nf_tables backend,
@@ -210,26 +220,31 @@ def _select_iptables_binary(ip_version: int, namespace: str | None = None) -> st
and keep the sandbox creation failure explicit if neither backend works.
"""
failures: list[str] = []
+ probe_args = (
+ ["-t", "nat", "-L", "POSTROUTING", "-n"]
+ if table == "nat"
+ else ["-L", "OUTPUT", "-n"]
+ )
for binary in _iptables_candidates(ip_version):
result = _run_iptables_binary(
binary,
- ["-L", "OUTPUT", "-n"],
+ probe_args,
check=False,
namespace=namespace,
)
if result.returncode == 0:
return binary
failures.append(_format_command_error(
- [IP_BINARY, "netns", "exec", namespace, binary, "-L", "OUTPUT", "-n"]
+ [IP_BINARY, "netns", "exec", namespace, binary, *probe_args]
if namespace
- else [binary, "-L", "OUTPUT", "-n"],
+ else [binary, *probe_args],
result,
))
family = "IPv6" if ip_version == 6 else "IPv4"
target = f" in netns {namespace}" if namespace else ""
detail = " ".join(failures) if failures else "No iptables binary found."
- raise NetworkSetupError(f"No working {family} iptables backend{target}. {detail}")
+ raise NetworkSetupError(f"No working {family} iptables {table} backend{target}. {detail}")
def run_iptables(
@@ -314,9 +329,12 @@ def _run_ip(
return subprocess.run(cmd, capture_output=True, text=True, check=check)
+NETNS_NAME_PREFIX = "jbx-"
+
+
def netns_name_for_sandbox(sandbox_id: str) -> str:
"""Return the deterministic network namespace name for a sandbox."""
- return f"jiuwenbox-{sandbox_id}"
+ return f"{NETNS_NAME_PREFIX}{sandbox_id}"
def namespace_exists(namespace: str) -> bool:
@@ -353,6 +371,394 @@ def setup_loopback(namespace: str | None = None) -> None:
_run_ip(["link", "set", "lo", "up"], namespace=namespace)
+@dataclass
+class UplinkHandle:
+ host_if: str
+ sandbox_if: str
+ subnet: str
+ uplink_if: str
+ nat: bool
+ management_ports: list[int] = field(default_factory=list)
+ forward_rules: list[list[str]] = field(default_factory=list)
+
+
+_nat_refcounts: dict[tuple[str, str], int] = {}
+_mgmt_refcounts: dict[tuple[str, int], int] = {}
+# Preferred pools for auto-selection; each sandbox receives a /30 inside the first pool
+# that yields a block not overlapping existing routes.
+_UPLINK_DEFAULT_POOLS: tuple[str, ...] = (
+ "100.64.0.0/10",
+ "10.200.0.0/16",
+ "10.201.0.0/16",
+ "10.202.0.0/16",
+ "10.203.0.0/16",
+ "172.30.0.0/16",
+ "172.31.0.0/16",
+ "192.168.240.0/20",
+ "10.0.0.0/8",
+ "172.16.0.0/12",
+ "192.168.0.0/16",
+)
+_LINK_LOCAL_NETWORK = ipaddress.ip_network("169.254.0.0/16")
+_MAX_UPLINK_BLOCK_SCAN = 4096
+_UPLINK_BLOCK_PREFIX = 30
+_SKIP_ROUTE_PREFIXES = frozenset({
+ "default",
+ "unreachable",
+ "blackhole",
+ "prohibit",
+ "throw",
+ "local",
+ "broadcast",
+ "multicast",
+ "anycast",
+ "nexthop",
+})
+
+
+def _interface_names(sandbox_id: str) -> tuple[str, str]:
+ digest = hashlib.sha256(sandbox_id.encode()).hexdigest()[:8]
+ return f"jwbH{digest}", f"jwbS{digest}"
+
+
+def _route_networks() -> list[ipaddress.IPv4Network]:
+ result = subprocess.run(
+ [IP_BINARY, "-4", "route", "show", "table", "all"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if result.returncode != 0:
+ raise NetworkSetupError("Failed to inspect IPv4 routes for uplink subnet selection")
+
+ networks: list[ipaddress.IPv4Network] = []
+ for line in result.stdout.splitlines():
+ parts = line.split()
+ if not parts or parts[0] in _SKIP_ROUTE_PREFIXES:
+ continue
+ try:
+ networks.append(ipaddress.ip_network(parts[0], strict=False))
+ except ValueError:
+ continue
+ return networks
+
+
+def _resolve_uplink_pools(subnet: str) -> list[ipaddress.IPv4Network]:
+ if subnet.strip():
+ pool = ipaddress.ip_network(subnet.strip(), strict=False)
+ if pool.prefixlen > _UPLINK_BLOCK_PREFIX:
+ raise NetworkSetupError(
+ f"Uplink subnet {subnet} is too small; need prefix length /{_UPLINK_BLOCK_PREFIX} or shorter"
+ )
+ return [pool]
+
+ return [ipaddress.ip_network(candidate, strict=False) for candidate in _UPLINK_DEFAULT_POOLS]
+
+
+def _uplink_search_region(
+ pool: ipaddress.IPv4Network,
+ sandbox_id: str,
+ slot: int,
+) -> ipaddress.IPv4Network:
+ """Narrow large pools to a /16-sized window before scanning /30 blocks."""
+ if pool.prefixlen >= 16:
+ return pool
+
+ hash_val = int(hashlib.sha256(f"{sandbox_id}:{slot}".encode()).hexdigest(), 16)
+ slash16_subnets = list(pool.subnets(new_prefix=16))
+ return slash16_subnets[hash_val % len(slash16_subnets)]
+
+
+def _is_usable_uplink_block(
+ block: ipaddress.IPv4Network,
+ pool: ipaddress.IPv4Network,
+ routes: list[ipaddress.IPv4Network],
+) -> bool:
+ if block.prefixlen != _UPLINK_BLOCK_PREFIX:
+ return False
+ if not block.subnet_of(pool):
+ return False
+ if block.overlaps(_LINK_LOCAL_NETWORK):
+ return False
+ return not any(block.overlaps(route) for route in routes)
+
+
+def _allocate_uplink_block(
+ sandbox_id: str,
+ subnet: str,
+ slot: int = 0,
+) -> tuple[ipaddress.IPv4Address, ipaddress.IPv4Address, int, str]:
+ """Pick a /30 block and return gateway, sandbox IP, prefix length, and block CIDR."""
+ pools = _resolve_uplink_pools(subnet)
+ routes = _route_networks()
+
+ for pool in pools:
+ region = _uplink_search_region(pool, sandbox_id, slot)
+ blocks = list(region.subnets(new_prefix=_UPLINK_BLOCK_PREFIX))
+ if not blocks:
+ continue
+
+ hash_val = int(hashlib.sha256(f"{sandbox_id}:{slot}".encode()).hexdigest(), 16)
+ start_idx = hash_val % len(blocks)
+ scan_limit = min(len(blocks), _MAX_UPLINK_BLOCK_SCAN)
+ for offset in range(scan_limit):
+ block = blocks[(start_idx + offset) % len(blocks)]
+ if not _is_usable_uplink_block(block, pool, routes):
+ continue
+ gateway = block.network_address + 1
+ sandbox_ip = block.network_address + 2
+ return gateway, sandbox_ip, _UPLINK_BLOCK_PREFIX, str(block)
+
+ raise NetworkSetupError(
+ f"No available /{_UPLINK_BLOCK_PREFIX} IPv4 block for sandbox uplink "
+ f"(sandbox_id={sandbox_id!r})"
+ )
+
+
+def resolve_uplink_subnet(subnet: str) -> str:
+ """Return the configured uplink pool, or the first default pool when auto-selecting."""
+ return str(_resolve_uplink_pools(subnet)[0])
+
+
+def resolve_uplink_interface(interface: str) -> str:
+ if interface.strip():
+ return interface.strip()
+ result = subprocess.run(
+ [IP_BINARY, "route", "show", "default"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if result.returncode != 0:
+ raise NetworkSetupError("Failed to inspect default route for uplink interface")
+ for line in result.stdout.splitlines():
+ parts = line.split()
+ if "dev" in parts:
+ return parts[parts.index("dev") + 1]
+ raise NetworkSetupError("No default route interface found for uplink")
+
+
+def ensure_ip_forward() -> None:
+ path = "/proc/sys/net/ipv4/ip_forward"
+ try:
+ with open(path, "w", encoding="ascii") as handle:
+ handle.write("1\n")
+ except OSError as exc:
+ raise NetworkSetupError(f"Failed to enable IPv4 forwarding at {path}") from exc
+
+
+def run_iptables_nat(
+ args: list[str],
+ *,
+ check: bool = True,
+ namespace: str | None = None,
+ ip_version: int = 4,
+) -> subprocess.CompletedProcess:
+ binary = _select_iptables_binary(ip_version, namespace, table="nat")
+ return _run_iptables_binary(
+ binary,
+ ["-t", "nat", *args],
+ check=check,
+ namespace=namespace,
+ )
+
+
+def _iptables_rule_exists(
+ args: list[str],
+ *,
+ namespace: str | None = None,
+ ip_version: int = 4,
+ table: str | None = None,
+) -> bool:
+ check_args = ["-C", *args]
+ if table == "nat":
+ result = run_iptables_nat(check_args, check=False, namespace=namespace, ip_version=ip_version)
+ else:
+ result = run_iptables(check_args, check=False, namespace=namespace, ip_version=ip_version)
+ return result.returncode == 0
+
+
+def _ensure_iptables_rule(
+ args: list[str],
+ *,
+ namespace: str | None = None,
+ ip_version: int = 4,
+ table: str | None = None,
+) -> None:
+ if _iptables_rule_exists(args, namespace=namespace, ip_version=ip_version, table=table):
+ return
+ insert_args = ["-I", *args]
+ if table == "nat":
+ run_iptables_nat(insert_args, namespace=namespace, ip_version=ip_version)
+ else:
+ run_iptables(insert_args, namespace=namespace, ip_version=ip_version)
+
+
+def _remove_iptables_rule(
+ args: list[str],
+ *,
+ namespace: str | None = None,
+ ip_version: int = 4,
+ table: str | None = None,
+) -> None:
+ delete_args = ["-D", *args]
+ if table == "nat":
+ run_iptables_nat(delete_args, check=False, namespace=namespace, ip_version=ip_version)
+ else:
+ run_iptables(delete_args, check=False, namespace=namespace, ip_version=ip_version)
+
+
+def _acquire_nat(subnet: str, uplink_if: str) -> None:
+ key = (subnet, uplink_if)
+ if _nat_refcounts.get(key, 0) == 0:
+ _ensure_iptables_rule(
+ ["POSTROUTING", "-s", subnet, "-o", uplink_if, "-j", "MASQUERADE"],
+ table="nat",
+ )
+ _nat_refcounts[key] = _nat_refcounts.get(key, 0) + 1
+
+
+def _release_nat(subnet: str, uplink_if: str) -> None:
+ key = (subnet, uplink_if)
+ count = _nat_refcounts.get(key, 0)
+ if count <= 1:
+ _nat_refcounts.pop(key, None)
+ _remove_iptables_rule(
+ ["POSTROUTING", "-s", subnet, "-o", uplink_if, "-j", "MASQUERADE"],
+ table="nat",
+ )
+ return
+ _nat_refcounts[key] = count - 1
+
+
+def _acquire_management_port_block(subnet: str, port: int) -> None:
+ key = (subnet, port)
+ if _mgmt_refcounts.get(key, 0) == 0:
+ _ensure_iptables_rule(
+ ["INPUT", "-s", subnet, "-p", "tcp", "--dport", str(port), "-j", "REJECT"],
+ )
+ _mgmt_refcounts[key] = _mgmt_refcounts.get(key, 0) + 1
+
+
+def _release_management_port_block(subnet: str, port: int) -> None:
+ key = (subnet, port)
+ count = _mgmt_refcounts.get(key, 0)
+ if count <= 1:
+ _mgmt_refcounts.pop(key, None)
+ _remove_iptables_rule(
+ ["INPUT", "-s", subnet, "-p", "tcp", "--dport", str(port), "-j", "REJECT"],
+ )
+ return
+ _mgmt_refcounts[key] = count - 1
+
+
+def setup_network_uplink(
+ namespace: str,
+ sandbox_id: str,
+ uplink: NetworkUplinkPolicy,
+ *,
+ management_ports: list[int] | None = None,
+) -> UplinkHandle:
+ """Attach a veth uplink and optional NAT for an isolated sandbox netns."""
+ ensure_ip_forward()
+ uplink_if = resolve_uplink_interface(uplink.interface)
+ host_if, sandbox_if = _interface_names(sandbox_id)
+ last_error: Exception | None = None
+ subnet = ""
+
+ for slot in range(64):
+ gateway, sandbox_ip, prefix_len, subnet = _allocate_uplink_block(
+ sandbox_id,
+ uplink.subnet,
+ slot,
+ )
+ host_addr = f"{gateway}/{prefix_len}"
+ sandbox_addr = f"{sandbox_ip}/{prefix_len}"
+ try:
+ _run_ip(["link", "del", host_if], check=False)
+ _run_ip([
+ "link", "add", host_if, "type", "veth",
+ "peer", "name", sandbox_if, "netns", namespace,
+ ])
+ _run_ip(["addr", "add", host_addr, "dev", host_if])
+ _run_ip(["link", "set", host_if, "up"])
+ _run_ip(["addr", "add", sandbox_addr, "dev", sandbox_if], namespace=namespace)
+ _run_ip(["link", "set", sandbox_if, "up"], namespace=namespace)
+ _run_ip([
+ "route", "add", "default", "via", str(gateway), "dev", sandbox_if,
+ ], namespace=namespace)
+ break
+ except (subprocess.CalledProcessError, NetworkSetupError) as exc:
+ last_error = exc
+ _run_ip(["link", "del", host_if], check=False)
+ continue
+ else:
+ raise NetworkSetupError(
+ f"Failed to allocate uplink addresses for sandbox {sandbox_id}: {last_error}"
+ ) from last_error
+
+ forward_rules = [
+ ["FORWARD", "-i", host_if, "-j", "ACCEPT"],
+ [
+ "FORWARD", "-o", host_if,
+ "-m", "state", "--state", "RELATED,ESTABLISHED", "-j", "ACCEPT",
+ ],
+ ]
+ applied_forward_rules: list[list[str]] = []
+ nat_acquired = False
+ protected_ports: list[int] = []
+ try:
+ for rule in forward_rules:
+ _ensure_iptables_rule(rule)
+ applied_forward_rules.append(rule)
+
+ if uplink.nat:
+ _acquire_nat(subnet, uplink_if)
+ nat_acquired = True
+
+ for port in management_ports or []:
+ _acquire_management_port_block(subnet, port)
+ protected_ports.append(port)
+ except Exception:
+ for port in reversed(protected_ports):
+ _release_management_port_block(subnet, port)
+ if nat_acquired:
+ _release_nat(subnet, uplink_if)
+ for rule in reversed(applied_forward_rules):
+ _remove_iptables_rule(rule)
+ _run_ip(["link", "del", host_if], check=False)
+ raise
+
+ logger.info(
+ "Network uplink applied for sandbox %s: host_if=%s sandbox_if=%s subnet=%s uplink_if=%s nat=%s",
+ sandbox_id,
+ host_if,
+ sandbox_if,
+ subnet,
+ uplink_if,
+ uplink.nat,
+ )
+ return UplinkHandle(
+ host_if=host_if,
+ sandbox_if=sandbox_if,
+ subnet=subnet,
+ uplink_if=uplink_if,
+ nat=uplink.nat,
+ management_ports=protected_ports,
+ forward_rules=applied_forward_rules,
+ )
+
+
+def teardown_network_uplink(handle: UplinkHandle) -> None:
+ for rule in reversed(handle.forward_rules):
+ _remove_iptables_rule(rule)
+ if handle.nat:
+ _release_nat(handle.subnet, handle.uplink_if)
+ for port in handle.management_ports:
+ _release_management_port_block(handle.subnet, port)
+ _run_ip(["link", "del", handle.host_if], check=False)
+
+
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)
diff --git a/jiuwenbox/tests/integration/test_cli_default.py b/jiuwenbox/tests/integration/test_cli_default.py
index a258053e30..3d8a8d9d49 100644
--- a/jiuwenbox/tests/integration/test_cli_default.py
+++ b/jiuwenbox/tests/integration/test_cli_default.py
@@ -181,6 +181,16 @@ def test_cli_sandbox_create_and_get(server_url, tracking_sandboxes):
assert data.get("phase") in ("ready", "provisioning", "stopped")
+def test_cli_sandbox_create_with_custom_id(server_url, tracking_sandboxes):
+ custom_id = "my-sb_cli01"
+ proc, data = _run_cli_json(
+ ["sandbox", "create", "--sandbox-id", custom_id],
+ base_url=server_url,
+ )
+ assert data.get("id") == custom_id
+ tracking_sandboxes.append(custom_id)
+
+
def test_cli_sandbox_ls(server_url, tracking_sandboxes):
_create_sandbox_via_cli(server_url, tracking_sandboxes)
diff --git a/jiuwenbox/tests/integration/test_server_api_default.py b/jiuwenbox/tests/integration/test_server_api_default.py
index e0610669c6..5746f65175 100644
--- a/jiuwenbox/tests/integration/test_server_api_default.py
+++ b/jiuwenbox/tests/integration/test_server_api_default.py
@@ -2,12 +2,16 @@
"""Integration tests for box-server API endpoints."""
import copy
+import ipaddress
+import json
import logging
import posixpath
+import re
import socket
import textwrap
import time
import uuid
+from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import httpx
@@ -16,6 +20,7 @@ import yaml
from jiuwenbox.bundled_configs import default_policy_path
from jiuwenbox.models.policy import SecurityPolicy
+from jiuwenbox.models.sandbox import SANDBOX_ID_FORMAT_MESSAGE
from jiuwenbox.supervisor import network as network_module
from jiuwenbox.supervisor.bwrap import BwrapConfig
@@ -195,6 +200,91 @@ def _unused_host_network_tcp_port_from_sandbox(client, sandbox_id: str) -> int:
return int(data["stdout"].strip())
+def _isolated_network_policy(*, uplink_subnet: str = "") -> dict:
+ network = {
+ "mode": "isolated",
+ "egress": {"default": "allow"},
+ }
+ if uplink_subnet:
+ network["uplink"] = {"subnet": uplink_subnet}
+ return {
+ "name": "uplink-test-policy",
+ "filesystem_policy": {
+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],
+ "read_write": ["/tmp"],
+ },
+ "network": network,
+ }
+
+
+_UPLINK_INFO_SCRIPT = textwrap.dedent(
+ """
+ import ipaddress
+ import json
+ import re
+ import subprocess
+ import sys
+
+ def run_ip(args):
+ try:
+ return subprocess.check_output(
+ ["ip", *args],
+ stderr=subprocess.DEVNULL,
+ text=True,
+ )
+ except (FileNotFoundError, subprocess.CalledProcessError):
+ return ""
+
+ default_route = run_ip(["-4", "route", "show", "default"])
+ dev_match = re.search(r"dev\\s+(\\S+)", default_route)
+ if not dev_match:
+ sys.exit(1)
+ device = dev_match.group(1)
+
+ addr_output = run_ip(["-4", "-o", "addr", "show", "dev", device])
+ inet_match = re.search(r"inet\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)/(\\d+)", addr_output)
+ if not inet_match:
+ sys.exit(2)
+ sandbox_ip = ipaddress.IPv4Address(inet_match.group(1))
+ prefix_len = int(inet_match.group(2))
+
+ gateway_match = re.search(r"via\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)", default_route)
+ if not gateway_match:
+ sys.exit(3)
+ gateway = ipaddress.IPv4Address(gateway_match.group(1))
+
+ block = ipaddress.ip_network(f"{sandbox_ip}/{prefix_len}", strict=False)
+ print(json.dumps({
+ "block": str(block),
+ "sandbox_ip": str(sandbox_ip),
+ "gateway": str(gateway),
+ }))
+ """
+).strip()
+
+
+def _uplink_info_from_sandbox(
+ client,
+ sandbox_id: str,
+) -> tuple[ipaddress.IPv4Network, ipaddress.IPv4Address, ipaddress.IPv4Address]:
+ """Read uplink /30 details from inside the sandbox (works when server runs in a container)."""
+ response = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={
+ "command": ["python3", "-c", _UPLINK_INFO_SCRIPT],
+ "timeout_seconds": 5,
+ })
+ assert response.status_code == 200, response.text
+ data = response.json()
+ assert data["exit_code"] == 0, data
+ payload = json.loads(data["stdout"])
+ block = ipaddress.ip_network(payload["block"], strict=False)
+ sandbox_ip = ipaddress.IPv4Address(payload["sandbox_ip"])
+ gateway = ipaddress.IPv4Address(payload["gateway"])
+ assert block.prefixlen == 30, block
+ assert sandbox_ip == block.network_address + 2, (sandbox_ip, block)
+ assert gateway == block.network_address + 1, (gateway, block)
+ return block, sandbox_ip, gateway
+
+
def _capability_check_script(cap_bit: int) -> str:
return textwrap.dedent(
f"""
@@ -310,7 +400,6 @@ def client(server_endpoint):
def create_sandbox_with_policy(client):
def factory(
*,
- name_prefix: str,
policy: dict,
policy_mode: str = "override",
) -> dict:
@@ -393,6 +482,82 @@ class TestSandboxCRUD:
resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")
assert resp.status_code == 404
+ @staticmethod
+ def test_create_sandbox_auto_generated_id_format(client):
+ resp = client.post("/api/v1/sandboxes", json={})
+ assert resp.status_code == 201, resp.text
+ sandbox_id = resp.json()["id"]
+ assert re.fullmatch(r"^[0-9a-f]{8}-[0-9a-f]{3}$", sandbox_id), sandbox_id
+
+ @staticmethod
+ def test_create_sandbox_with_custom_id(client):
+ custom_id = f"my-sb_{uuid.uuid4().hex[:6]}"
+ resp = client.post("/api/v1/sandboxes", json={"sandbox_id": custom_id})
+ assert resp.status_code == 201, resp.text
+ assert resp.json()["id"] == custom_id
+
+ @staticmethod
+ def test_create_sandbox_with_custom_id_abcd(client):
+ custom_id = f"abcd-{uuid.uuid4().hex[:4]}"
+ resp = client.post("/api/v1/sandboxes", json={"sandbox_id": custom_id})
+ assert resp.status_code == 201, resp.text
+ assert resp.json()["id"] == custom_id
+
+ @staticmethod
+ def test_create_sandbox_empty_sandbox_id_generates(client):
+ resp = client.post("/api/v1/sandboxes", json={"sandbox_id": ""})
+ assert resp.status_code == 201, resp.text
+ sandbox_id = resp.json()["id"]
+ assert re.fullmatch(r"^[0-9a-f]{8}-[0-9a-f]{3}$", sandbox_id), sandbox_id
+
+ @staticmethod
+ @pytest.mark.parametrize(
+ "invalid_id",
+ [
+ "abc",
+ "ABC123",
+ "my sb",
+ " abcd ",
+ "a" * 17,
+ "id!",
+ ],
+ )
+ def test_create_sandbox_rejects_invalid_custom_id(client, invalid_id):
+ resp = client.post("/api/v1/sandboxes", json={"sandbox_id": invalid_id})
+ assert resp.status_code == 400, resp.text
+ assert SANDBOX_ID_FORMAT_MESSAGE in resp.json()["error"]
+
+ @staticmethod
+ def test_create_sandbox_rejects_duplicate_id(client):
+ custom_id = f"dup-{uuid.uuid4().hex[:4]}"
+ first = client.post("/api/v1/sandboxes", json={"sandbox_id": custom_id})
+ assert first.status_code == 201, first.text
+
+ second = client.post("/api/v1/sandboxes", json={"sandbox_id": custom_id})
+ assert second.status_code == 409, second.text
+ assert custom_id in second.json()["error"]
+
+ @staticmethod
+ def test_create_sandbox_concurrent_duplicate_id(server_endpoint):
+ custom_id = f"race-{uuid.uuid4().hex[:4]}"
+
+ def _create() -> httpx.Response:
+ with _build_httpx_client(server_endpoint, timeout=30.0) as thread_client:
+ return thread_client.post(
+ "/api/v1/sandboxes",
+ json={"sandbox_id": custom_id},
+ )
+
+ try:
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ futures = [pool.submit(_create) for _ in range(2)]
+ statuses = sorted(f.result().status_code for f in as_completed(futures))
+
+ assert statuses == [201, 409], statuses
+ finally:
+ with _build_httpx_client(server_endpoint, timeout=30.0) as cleanup_client:
+ cleanup_client.delete(f"/api/v1/sandboxes/{custom_id}")
+
class TestSandboxLifecycle:
@staticmethod
@@ -612,7 +777,7 @@ class TestPolicyAPI:
}
assert data["capabilities"] == {"add": [], "drop": []}
assert data["landlock"]["compatibility"] == "best_effort"
- assert data["network"]["mode"] == "host"
+ assert data["network"]["mode"] == "isolated"
assert data["network"]["egress"]["allowed_domains"] == ["baidu.com"]
assert data["network"]["egress"]["allowed_ips"] == ["127.0.0.1/32", "::1/128"]
assert data["network"]["egress"]["blocked_ips"] == ["169.254.169.254/32"]
@@ -1149,7 +1314,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="fs-rw",
policy={
"name": "fs-rw-policy",
"filesystem_policy": {
@@ -1183,7 +1347,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="fs-ro",
policy={
"name": "fs-ro-policy",
"filesystem_policy": {
@@ -1210,7 +1373,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="fs-dir",
policy={
"name": "fs-dir-policy",
"filesystem_policy": {
@@ -1255,7 +1417,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="fs-nested-dir",
policy={
"name": "fs-nested-dir-policy",
"filesystem_policy": {
@@ -1303,7 +1464,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="fs-file",
policy={
"name": "fs-file-policy",
"filesystem_policy": {
@@ -1354,7 +1514,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="fs-home-dir",
policy={
"name": "fs-home-dir-policy",
"filesystem_policy": {
@@ -1418,7 +1577,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="exec-options",
policy={
"name": "exec-options-policy",
"filesystem_policy": {
@@ -1455,7 +1613,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="policy-env",
policy={
"name": "policy-env-policy",
"environment": {
@@ -1502,7 +1659,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="exec-js",
policy={
"name": "exec-js-policy",
"filesystem_policy": {
@@ -1538,7 +1694,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="download-missing",
policy={
"name": "download-missing-policy",
"filesystem_policy": {
@@ -1563,7 +1718,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="download-dir",
policy={
"name": "download-dir-policy",
"filesystem_policy": {
@@ -1588,7 +1742,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="list-files",
policy={
"name": "list-files-policy",
"filesystem_policy": {
@@ -1646,7 +1799,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="search-files",
policy={
"name": "search-files-policy",
"filesystem_policy": {
@@ -1694,7 +1846,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="process-root",
policy={
"name": "process-root-policy",
"filesystem_policy": {
@@ -1735,7 +1886,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="syscall-block",
policy={
"name": "syscall-block-policy",
"filesystem_policy": {
@@ -1800,7 +1950,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="pid-ns",
policy={
"name": "pid-ns-policy",
"filesystem_policy": {
@@ -1834,7 +1983,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="cap-drop",
policy={
"name": "cap-drop-policy",
"filesystem_policy": {
@@ -1873,7 +2021,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="cap-add",
policy={
"name": "cap-add-policy",
"filesystem_policy": {
@@ -1989,15 +2136,13 @@ class TestPolicyEnforcement:
assert "unexpected-success" not in data["stdout"]
@staticmethod
- def test_network_mode_isolated_blocks_http_requests(
+ def test_network_mode_isolated_allows_external_http_requests(
client,
create_sandbox_with_policy,
- server_endpoint,
):
sandbox = create_sandbox_with_policy(
- name_prefix="net-isolated",
policy={
- "name": "net-isolated-policy",
+ "name": "net-isolated-uplink-policy",
"filesystem_policy": {
"read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],
"read_write": ["/tmp"],
@@ -2009,18 +2154,70 @@ class TestPolicyEnforcement:
},
)
- script = (
- "import sys, urllib.request; "
- "urllib.request.urlopen(sys.argv[1], timeout=2).read(); "
- "print('unexpected-success')"
+ script = textwrap.dedent(
+ """
+ import sys
+ import urllib.request
+
+ request = urllib.request.Request(
+ sys.argv[1],
+ headers={"User-Agent": "jiuwenbox-integration-test"},
+ )
+ with urllib.request.urlopen(request, timeout=10) as response:
+ print(response.status)
+ print(response.geturl())
+ """
+ ).strip()
+ response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={
+ "command": ["python3", "-c", script, "https://www.baidu.com/"],
+ "timeout_seconds": 15,
+ })
+ assert response.status_code == 200
+ data = response.json()
+ assert data["exit_code"] == 0, data
+ assert "baidu.com" in data["stdout"].lower()
+
+ @staticmethod
+ def test_network_mode_isolated_blocked_ip_rejects_egress(
+ client,
+ create_sandbox_with_policy,
+ ):
+ blocked_ip = socket.gethostbyname("www.baidu.com")
+ sandbox = create_sandbox_with_policy(
+ policy={
+ "name": "net-isolated-block-policy",
+ "filesystem_policy": {
+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],
+ "read_write": ["/tmp"],
+ },
+ "network": {
+ "mode": "isolated",
+ "egress": {
+ "default": "allow",
+ "blocked_ips": [f"{blocked_ip}/32"],
+ },
+ },
+ },
)
+
+ script = textwrap.dedent(
+ """
+ import sys
+ import socket
+
+ ip = sys.argv[1]
+ with socket.create_connection((ip, 443), timeout=10):
+ pass
+ print("unexpected-success")
+ """
+ ).strip()
response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={
- "command": ["python", "-c", script, _sandbox_health_url(server_endpoint)],
- "timeout_seconds": 5,
+ "command": ["python3", "-c", script, blocked_ip],
+ "timeout_seconds": 15,
})
assert response.status_code == 200
data = response.json()
- assert data["exit_code"] != 0
+ assert data["exit_code"] != 0, data
assert "unexpected-success" not in data["stdout"]
@staticmethod
@@ -2029,7 +2226,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="net-host",
policy={
"name": "net-host-policy",
"filesystem_policy": {
@@ -2072,7 +2268,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="net-host-listener",
policy={
"name": "net-host-listener-policy",
"filesystem_policy": {
@@ -2254,7 +2449,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="ingress-allow",
policy={
"name": "ingress-allow-policy",
"filesystem_policy": {
@@ -2288,7 +2482,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="ingress-block",
policy={
"name": "ingress-block-policy",
"filesystem_policy": {
@@ -2323,7 +2516,6 @@ class TestPolicyEnforcement:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="netns-persist",
policy={
"name": "netns-persist-policy",
"filesystem_policy": {
@@ -2429,7 +2621,6 @@ class TestPolicyEnforcement:
the happy path here is the locked-down path.
"""
sandbox = create_sandbox_with_policy(
- name_prefix="reserved-script-integrity",
policy=TestPolicyEnforcement._RESERVED_INTEGRITY_POLICY,
)
@@ -2582,7 +2773,6 @@ class TestPolicyEnforcement:
download) still produce the expected results.
"""
sandbox = create_sandbox_with_policy(
- name_prefix="reserved-script-survival",
policy=TestPolicyEnforcement._RESERVED_INTEGRITY_POLICY,
)
sandbox_id = sandbox["id"]
@@ -2891,7 +3081,6 @@ class TestReservedSandboxPaths:
},
}
sandbox = create_sandbox_with_policy(
- name_prefix="non-reserved",
policy=policy,
)
assert sandbox["phase"] == "ready", sandbox
@@ -3005,6 +3194,102 @@ class TestBwrapFilesystem:
assert _has_arg_pair(args, "--remount-ro", "/etc")
+class TestNetworkUplink:
+ @staticmethod
+ def test_isolated_uplink_auto_allocates_cgnat_pool_block(
+ client,
+ create_sandbox_with_policy,
+ ):
+ sandbox = create_sandbox_with_policy(policy=_isolated_network_policy())
+ block, sandbox_ip, _gateway = _uplink_info_from_sandbox(client, sandbox["id"])
+ assert block.subnet_of(ipaddress.ip_network("100.64.0.0/10"))
+ assert sandbox_ip == block.network_address + 2
+
+ @staticmethod
+ def test_isolated_uplink_user_pool_allocates_within_subnet(
+ client,
+ create_sandbox_with_policy,
+ ):
+ pool = "10.55.0.0/24"
+ sandbox = create_sandbox_with_policy(
+ policy=_isolated_network_policy(uplink_subnet=pool),
+ )
+ block, _sandbox_ip, _gateway = _uplink_info_from_sandbox(client, sandbox["id"])
+ assert block.subnet_of(ipaddress.ip_network(pool, strict=False))
+
+ @staticmethod
+ def test_isolated_uplink_skips_route_occupied_block(client):
+ pool = "10.55.0.0/24"
+ policy = _with_runtime_support(_isolated_network_policy(uplink_subnet=pool))
+
+ first_response = client.post("/api/v1/sandboxes", json={
+ "policy_mode": "override",
+ "policy": policy,
+ "sandbox_id": f"uplk1_{uuid.uuid4().hex[:6]}",
+ })
+ assert first_response.status_code == 201, first_response.text
+ first = first_response.json()
+ assert first["phase"] == "ready", first
+ first_block, _, _ = _uplink_info_from_sandbox(client, first["id"])
+
+ second_response = client.post("/api/v1/sandboxes", json={
+ "policy_mode": "override",
+ "policy": policy,
+ "sandbox_id": f"uplk2_{uuid.uuid4().hex[:6]}",
+ })
+ assert second_response.status_code == 201, second_response.text
+ second = second_response.json()
+ assert second["phase"] == "ready", second
+ second_block, _, _ = _uplink_info_from_sandbox(client, second["id"])
+ assert first_block != second_block
+
+ @staticmethod
+ def test_isolated_uplink_concurrent_sandboxes_use_distinct_blocks(client):
+ policy = _with_runtime_support(
+ _isolated_network_policy(uplink_subnet="10.55.0.0/24"),
+ )
+
+ def create_one(index: int):
+ return client.post("/api/v1/sandboxes", json={
+ "policy_mode": "override",
+ "policy": policy,
+ "sandbox_id": f"uplk{index:02d}_{uuid.uuid4().hex[:6]}",
+ })
+
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ responses = list(executor.map(create_one, range(4)))
+
+ sandbox_ids: list[str] = []
+ for response in responses:
+ assert response.status_code == 201, response.text
+ sandbox = response.json()
+ assert sandbox["phase"] == "ready", sandbox
+ sandbox_ids.append(sandbox["id"])
+
+ blocks = [
+ _uplink_info_from_sandbox(client, sandbox_id)[0]
+ for sandbox_id in sandbox_ids
+ ]
+ assert len({str(block) for block in blocks}) == len(blocks)
+
+ @staticmethod
+ def test_isolated_uplink_reports_error_when_pool_has_no_free_block(client):
+ # Policy allows pools up to /24; /30 is rejected at validation time.
+ # 169.254.0.0/24 is a valid pool, but every /30 overlaps the reserved
+ # link-local range and is filtered out by the allocator.
+ pool = "169.254.0.0/24"
+ response = client.post("/api/v1/sandboxes", json={
+ "policy_mode": "override",
+ "policy": _with_runtime_support(
+ _isolated_network_policy(uplink_subnet=pool),
+ ),
+ "sandbox_id": f"uplkex_{uuid.uuid4().hex[:6]}",
+ })
+ assert response.status_code == 201, response.text
+ sandbox = response.json()
+ assert sandbox["phase"] == "error", sandbox
+
+
class TestNetworkIptables:
@staticmethod
def test_iptables_backend_falls_back_to_legacy(monkeypatch):
@@ -3297,7 +3582,6 @@ class TestBindRootEntries:
):
host_root = bind_root_entries_host_tree
sandbox = create_sandbox_with_policy(
- name_prefix="bind-root-entries-ro",
policy={
"name": "bind-root-entries-ro-policy",
"filesystem_policy": {
@@ -3356,7 +3640,6 @@ class TestBindRootEntries:
):
host_root = bind_root_entries_host_tree
sandbox = create_sandbox_with_policy(
- name_prefix="bind-root-entries-rw",
policy={
"name": "bind-root-entries-rw-policy",
"filesystem_policy": {
@@ -3402,7 +3685,6 @@ class TestBindRootEntries:
# confirm the bind actually shares the host inode rather than landing
# on a tmpfs unique to this sandbox.
verify_sandbox = create_sandbox_with_policy(
- name_prefix="bind-root-entries-rw-verify",
policy={
"name": "bind-root-entries-rw-verify-policy",
"filesystem_policy": {
@@ -3441,7 +3723,6 @@ class TestBindRootEntries:
):
host_root = bind_root_entries_host_tree
sandbox = create_sandbox_with_policy(
- name_prefix="bind-root-entries-filter",
policy={
"name": "bind-root-entries-filter-policy",
"filesystem_policy": {
@@ -3485,7 +3766,6 @@ class TestBindRootEntries:
# to be independent of that topology.
missing = f"/tmp/jiuwenbox-bind-root-entries-missing-{uuid.uuid4().hex}"
sandbox = create_sandbox_with_policy(
- name_prefix="bind-root-entries-missing",
policy={
"name": "bind-root-entries-missing-policy",
"filesystem_policy": {
@@ -3530,7 +3810,6 @@ class TestBindRootEntries:
host_root = bind_root_entries_host_tree
nested_host_root = f"{host_root}/nested_dir"
sandbox = create_sandbox_with_policy(
- name_prefix="bind-root-entries-roundtrip",
policy={
"name": "bind-root-entries-roundtrip-policy",
"filesystem_policy": {
@@ -3678,7 +3957,6 @@ class TestBindRootEntries:
try:
sandbox = create_sandbox_with_policy(
- name_prefix="bind-root-entries-app-build-rw-overlay",
policy={
"name": "bind-root-entries-app-build-rw-overlay-policy",
"filesystem_policy": {
@@ -3774,7 +4052,6 @@ class TestBindRootEntries:
# wrote, proving the rw bind shares the host inode rather than a
# per-sandbox tmpfs.
verify_sandbox = create_sandbox_with_policy(
- name_prefix="bind-root-entries-app-build-verify",
policy={
"name": "bind-root-entries-app-build-verify-policy",
"filesystem_policy": {
@@ -3941,7 +4218,6 @@ class TestCgroupPolicy:
@staticmethod
def test_no_cgroup_field_skips_setup_entirely(client, create_sandbox_with_policy):
sandbox = create_sandbox_with_policy(
- name_prefix="cgroup-skip-noField",
policy=TestCgroupPolicy._expect_no_limit_policy(None),
)
TestCgroupPolicy._assert_skip_path_runs_cleanly(client, sandbox["id"])
@@ -3949,7 +4225,6 @@ class TestCgroupPolicy:
@staticmethod
def test_empty_cgroup_field_skips_setup(client, create_sandbox_with_policy):
sandbox = create_sandbox_with_policy(
- name_prefix="cgroup-skip-empty",
policy=TestCgroupPolicy._expect_no_limit_policy({}),
)
TestCgroupPolicy._assert_skip_path_runs_cleanly(client, sandbox["id"])
@@ -3957,7 +4232,6 @@ class TestCgroupPolicy:
@staticmethod
def test_all_null_cgroup_field_skips_setup(client, create_sandbox_with_policy):
sandbox = create_sandbox_with_policy(
- name_prefix="cgroup-skip-allNull",
policy=TestCgroupPolicy._expect_no_limit_policy({
"memory_max": None,
"cpu_max": None,
@@ -4087,7 +4361,6 @@ class TestCgroupPolicy:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="cgroup-roundtrip",
policy={
"name": "cgroup-roundtrip-policy",
"filesystem_policy": {
@@ -4121,7 +4394,6 @@ class TestCgroupPolicy:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="cgroup-memory-limit",
policy={
"name": "cgroup-memory-policy",
"filesystem_policy": {
@@ -4169,7 +4441,6 @@ class TestCgroupPolicy:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="cgroup-pids-limit",
policy={
"name": "cgroup-pids-policy",
"filesystem_policy": {
@@ -4233,7 +4504,6 @@ class TestCgroupPolicy:
create_sandbox_with_policy,
):
sandbox = create_sandbox_with_policy(
- name_prefix="cgroup-cpu-throttle",
policy={
"name": "cgroup-cpu-policy",
"filesystem_policy": {