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: jiuwenbox适配jiuwenclaw调用方式
zhaozixuan85f408fe16a0
diff --git a/jiuwenbox/README.md b/jiuwenbox/README.mdindex df86ec24a6..61f8fbe80f 100644--- a/jiuwenbox/README.md+++ b/jiuwenbox/README.md@@ -18,6 +18,7 @@ through a small supervisor process that applies the configured isolation policy.- Seccomp syscall filtering- Python and JavaScript execution support when the corresponding runtimes exist- Audit logging and persisted sandbox lifecycle state+- Inference Privacy Proxy for LLM API request routing with automatic API key injection## Architecture@@ -26,31 +27,20 @@ through a small supervisor process that applies the configured isolation policy.API routing.- `server/runtime`- Runtime adapter that starts one supervisor process per sandbox command.+- `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.+- `proxy`+ - HTTP-aware inference privacy proxy with path-based routing and API key+ injection (supports OpenAI and Anthropic formats).- `models`- Pydantic models for policies, sandboxes, API responses, and common statusstructures.-## Layout--```text-configs/- default-policy.yaml- jiuwenclaw-policy.yaml-docker/-scripts/- server.sh- test.sh-src/jiuwenbox/- models/- server/- supervisor/-tests/- integration/-```-## Requirements- Linux@@ -64,45 +54,50 @@ On Ubuntu:```bashsudo apt-get update-sudo apt-get install -y bubblewrap iproute2 iptables nftables python3-pip nodejs+sudo apt-get install -y bubblewrap iproute2 iptables nftables python3-pip python3-venv nodejs```## Install```bashcd jiuwenclaw/jiuwenbox-uv venv+python3 -m venv .venvsource .venv/bin/activate-uv sync+python3 -m pip install --upgrade pip build+python3 -m build --wheel+python3 -m pip install dist/jiuwenbox-*.whl```## Start The Server### Local Start-`scripts/server.sh` accepts a policy file as the first positional argument.-The path is resolved relative to the caller's current directory and then passed-to the server as an absolute path.+Set the default policy path and start the installed service with `python -m`:```bash-sudo ./scripts/server.sh-sudo ./scripts/server.sh configs/default-policy.yaml-sudo ./scripts/server.sh configs/jiuwenclaw-policy.yaml 9000+export JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml"+sudo -E .venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 8321 --log-level debug```-The default port is `8321`. A numeric second positional argument overrides the-port. Additional arguments are forwarded to `uvicorn`.+Use another policy or port by changing the environment variable or uvicorn+arguments:++```bash+export JIUWENBOX_POLICY_PATH="$(pwd)/configs/jiuwenclaw-policy.yaml"+sudo -E .venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 9000 --log-level debug+```-The selected policy path is exported as:+The selected policy path is read from:```bash-JIUWENBOX_DEFAULT_POLICY_PATH=/absolute/path/to/policy.yaml+JIUWENBOX_POLICY_PATH=/absolute/path/to/policy.yaml```-The port can also be set through:+The port can also be set through `JIUWENBOX_PORT` when your process manager+uses it to render the uvicorn command:```bash-JIUWENBOX_PORT=9000 sudo ./scripts/server.sh configs/default-policy.yaml+JIUWENBOX_PORT=9000```### Docker Start@@ -110,7 +105,7 @@ JIUWENBOX_PORT=9000 sudo ./scripts/server.sh configs/default-policy.yamlBuild the image:```bash-cd jiuwenclaw/jiuwenbox/docker+cd jiuwenclaw/jiuwenbox/scriptssudo ./build_docker.sh```@@ -120,8 +115,6 @@ Run with the default policy:sudo ./run_docker.sh```-The Docker image starts `./scripts/server.sh` by default.-## Policy FilesThe server loads one static default policy at startup. Policy dynamic update is@@ -269,52 +262,94 @@ network:- 22```-## API Examples+## Inference Privacy Proxy-Create a sandbox:+The inference privacy proxy enables secure LLM API access from edge servers:-```bash-curl -sS -X POST http://127.0.0.1:8321/api/v1/sandboxes \- -H 'Content-Type: application/json' \- -d '{"command":["/usr/bin/python3","-c","import time; time.sleep(3600)"]}'-```+- Path-based routing to different LLM providers (OpenAI, Anthropic, custom)+- Automatic API key injection (OpenAI `Authorization: Bearer`, Anthropic `X-Api-Key`)+- Hot-pluggable via REST API (create/start/stop/update/delete)+- Configured via policy YAML or dynamically through API-Run a command:+**Architecture**:-```bash-curl -sS -X POST http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>/exec \- -H 'Content-Type: application/json' \- -d '{"command":["/usr/bin/python3","-c","print(\"hello\")"],"workdir":"/tmp"}'-```+One global proxy process listens on a single host:port.-Upload a file:+**Privacy routes default to `listen_port=0` (disabled)**. When enabled, both `listen_host` (IP address) and `listen_port` must be configured.-```bash-curl -sS -X POST \- 'http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>/upload?sandbox_path=/tmp/input.txt' \- -F '[email protected]'+Routes are differentiated by `path_prefix` (forwarding rules). Each route has **independent state** (`running` = enabled forwarding; `stopped` = disabled).++**Creating routes via API requires valid `listen_host` and `listen_port > 0`**, otherwise returns an error.++### Proxy Configuration++Policy YAML configuration schema:++```yaml+inference_privacy_proxies:+ listen_host: ipaddress, IP address to bind # MUST+ listen_port: number, listen port # MUST, non-zero enables proxy++ # OPTIONAL, can be managed via REST API after startup+ routes:+ - path_prefix: str, path name for forwarding rule+ target_endpoint: URL, target endpoint+ api_key: str, api key to inject when forwarding+ skip_cert_verify: boolean, skip cert verify for self-signed https targets, debug only```-Download a file:+### API Key Injection-```bash-curl -sS \- 'http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>/download?sandbox_path=/tmp/input.txt'+- OpenAI: Replace `Authorization: Bearer <placeholder>` with actual key+- Anthropic: Replace `X-Api-Key: <placeholder>` with actual key++### Configuration Example++`Note: The network endpoints https://api.openai.com and http://192.168.1.100:9000 are examples only`++#### Policy YAML Example++```yaml+inference_privacy_proxies:++ listen_host: "127.0.0.1"+ listen_port: 8080++ routes:+ - path_prefix: "openai"+ target_endpoint: "https://api.openai.com"+ api_key: "sk_sandbox_managed_openai_key"+ - path_prefix: "custom"+ target_endpoint: "http://192.168.1.100:9000"+ api_key: "sk_sandbox_managed_custom_key"```-Delete a sandbox:+For edge servers, use `listen_host: "0.0.0.0"` to accept connections from all interfaces.-```bash-curl -sS -X DELETE http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>+#### Forwarding Example++```text+Client request: POST http://127.0.0.1:8322/openai/v1/chat/completions -H "Authorization: Bearer sk_fake_key"+Proxy forwards: POST https://api.openai.com/v1/chat/completions -H "Authorization: Bearer sk_sandbox_managed_openai_key"++Client request: POST http://127.0.0.1:8322/custom/v1/chat/completions -H "Authorization: Bearer sk_fake_key"+Proxy forwards: POST http://192.168.1.100:9000/v1/chat/completions -H "Authorization: Bearer sk_sandbox_managed_custom_key"```+#### jiuwenclaw Configuration Example++| Config | Old Value | New Value |+| --------- | ----------------------------- | ---------------------------------- |+| api_base | http://192.168.1.100:9000/v1/ | http://127.0.0.1:8322/custom/v1/ |+| api_key | sk_sandbox_managed_custom_key | sk_fake_key |+## Run Integration TestsRun one policy-specific integration suite:```bash-./scripts/test.sh default # jiuwenbox runs the service using default-policy.yaml as the security policy.-./scripts/test.sh jiuwenclaw-tool # jiuwenbox runs the service using jiuwenclaw-tool-policy.yaml as the security policy.+./tests/test.sh default # jiuwenbox runs the service using default-policy.yaml as the security policy.+./tests/test.sh yuanrong # jiuwenbox runs the service using yuanrong.yaml with proxy enabled on port 8322.```Run specific test-case:@@ -323,6 +358,43 @@ Run specific test-case: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```+### Performance Tests++Run the office-workload performance suite:++```bash+./tests/test.sh performance --server-endpoint 127.0.0.1:8321+```++Tune sandbox count, per-sandbox concurrency, and per-task loop count:++```bash+./tests/test.sh performance \+ --sandbox-count 2 \+ --concurrency 16 \+ --loop 8 \+ --server-endpoint 127.0.0.1:8321+```++The script maps these arguments to environment variables used by the performance+fixtures:++| Script argument | Environment variable | Default |+| --------------- | -------------------- | ------- |+| `--sandbox-count` | `JIUWENBOX_PERF_SANDBOX_COUNT` | `1` |+| `--concurrency` | `JIUWENBOX_PERF_CONCURRENCY` | `4` |+| `--loop` | `JIUWENBOX_PERF_LOOP` | `8` |++### Real LLM Integration Tests++To run real LLM integration tests, set the following environment variables. These tests are skipped by default if the environment variables are not set.:++```bash+export JIUWENBOX_TEST_LLM_ENDPOINT="https://api.openai.com"+export JIUWENBOX_TEST_LLM_API_KEY="sk_sandbox_managed_key"+export JIUWENBOX_TEST_LLM_MODEL="YOUR_MODEL"+```+## Notes- Restart the server after changing the startup policy file.diff --git a/jiuwenbox/README_CN.md b/jiuwenbox/README_CN.mdindex d8e706c8b4..58715614f2 100644--- a/jiuwenbox/README_CN.md+++ b/jiuwenbox/README_CN.md@@ -18,6 +18,7 @@ agent 工具和代码片段。- Seccomp 系统调用过滤- 在运行时存在时支持 Python 和 JavaScript 代码执行- 审计日志和持久化的沙箱生命周期状态+- 推理隐私代理,用于 LLM API 请求路由和自动 API 密钥注入## 架构@@ -25,30 +26,18 @@ agent 工具和代码片段。- FastAPI 应用,负责沙箱生命周期管理、policy 加载、审计日志和 API 路由。- `server/runtime`- 运行时适配层,负责为每个沙箱命令启动一个 supervisor 进程。+- `server/proxy_manager`+ - 管理推理隐私代理,用于 LLM API 路由和 API 密钥注入。+- `server/policy_reader`+ - 共享 policy 文件读取器,供沙箱和代理管理器使用。- `supervisor`- 每条命令的启动器,负责将生效的 policy 转换为 `bubblewrap`、Landlock、seccomp 和命名空间配置。+- `proxy`+ - HTTP 推理隐私代理,支持路径路由和 API 密钥注入(支持 OpenAI 和 Anthropic 格式)。- `models`- 基于 Pydantic 的 policy、沙箱、API 响应和通用状态结构模型。-## 目录结构--```text-configs/- default-policy.yaml- jiuwenclaw-policy.yaml-docker/-scripts/- server.sh- test.sh-src/jiuwenbox/- models/- server/- supervisor/-tests/- integration/-```-## 环境要求- Linux@@ -62,44 +51,48 @@ Ubuntu 安装示例:```bashsudo apt-get update-sudo apt-get install -y bubblewrap iproute2 iptables nftables python3-pip nodejs+sudo apt-get install -y bubblewrap iproute2 iptables nftables python3-pip python3-venv nodejs```## 安装```bashcd jiuwenclaw/jiuwenbox-uv venv+python3 -m venv .venvsource .venv/bin/activate-uv sync+python3 -m pip install --upgrade pip build+python3 -m build --wheel+python3 -m pip install dist/jiuwenbox-*.whl```## 启动服务### 本地启动-`scripts/server.sh` 将第一个位置参数作为 policy 文件路径。该路径会按照-调用脚本时所在的当前目录进行解析,然后转换为绝对路径传给服务。+设置默认 policy 路径,并通过 `python -m` 启动已安装的服务:```bash-sudo ./scripts/server.sh-sudo ./scripts/server.sh configs/default-policy.yaml-sudo ./scripts/server.sh configs/jiuwenclaw-policy.yaml 9000+export JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml"+sudo -E .venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 8321 --log-level debug```-默认端口是 `8321`。第二个位置参数如果是数字,则会作为端口号使用。-其余参数会继续透传给 `uvicorn`。+如需使用其他 policy 或端口,可修改环境变量或 uvicorn 参数:++```bash+export JIUWENBOX_POLICY_PATH="$(pwd)/configs/jiuwenclaw-policy.yaml"+sudo -E .venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 9000 --log-level debug+```-选中的 policy 路径会导出为:+服务会从以下环境变量读取默认 policy 路径:```bash-JIUWENBOX_DEFAULT_POLICY_PATH=/absolute/path/to/policy.yaml+JIUWENBOX_POLICY_PATH=/absolute/path/to/policy.yaml```-端口也可以通过环境变量设置:+如果进程管理器会使用环境变量渲染 uvicorn 命令,也可以设置:```bash-JIUWENBOX_PORT=9000 sudo ./scripts/server.sh configs/default-policy.yaml+JIUWENBOX_PORT=9000```### Docker 启动@@ -107,7 +100,7 @@ JIUWENBOX_PORT=9000 sudo ./scripts/server.sh configs/default-policy.yaml构建镜像:```bash-cd jiuwenclaw/jiuwenbox/docker+cd jiuwenclaw/jiuwenbox/scriptssudo ./build_docker.sh```@@ -117,8 +110,6 @@ sudo ./build_docker.shsudo ./run_docker.sh```-Docker 镜像默认会启动 `./scripts/server.sh`。-## Policy 文件服务启动时会加载一个静态默认 policy。当前不启用 policy 动态更新功能。@@ -262,52 +253,102 @@ network:- 22```-## API 示例+## 推理隐私代理-创建沙箱:+推理隐私代理用于在边缘服务器上安全访问 LLM API:-```bash-curl -sS -X POST http://127.0.0.1:8321/api/v1/sandboxes \- -H 'Content-Type: application/json' \- -d '{"command":["/usr/bin/python3","-c","import time; time.sleep(3600)"]}'-```+- 路径路由到不同 LLM 提供商(OpenAI、Anthropic、自定义)+- 自动 API 密钥注入(OpenAI `Authorization: Bearer`、Anthropic `X-Api-Key`)+- 通过 REST API 热插拔(创建/启动/停止/重启/更新/删除)+- 通过 policy YAML 配置或REST API 管理-执行命令:+**架构说明**:-```bash-curl -sS -X POST http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>/exec \- -H 'Content-Type: application/json' \- -d '{"command":["/usr/bin/python3","-c","print(\"hello\")"],"workdir":"/tmp"}'-```+服务端运行一个全局代理进程,监听单一 host:port。-上传文件:+**隐私路由默认 `listen_port=0`(禁用)**,启用时需同时配置 `listen_host`(IP 地址)和 `listen_port`。-```bash-curl -sS -X POST \- 'http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>/upload?sandbox_path=/tmp/input.txt' \- -F '[email protected]'+通过 `path_prefix`区分路由(转发规则)。**每条路由有独立状态**(`running` = 启用转发流量;`stopped` = 禁用)。++**通过 API 创建路由需 `listen_host` 有效且 `listen_port > 0`**,否则返回错误。++### 代理配置++配置文件yaml文件说明:++```yaml+inference_privacy_proxies:+ listen_host: ipaddress,绑定的 IP 地址 # 必须+ listen_port: number:监听端口号 # 必须,非 0 值启用代理++ # 选填,可在启动后通过RESTAPI管理+ routes:+ - path_prefix: str,转发规则的路径名称+ target_endpoint: URL,目标端点+ api_key: str,转发时用于替换的api key+ skip_cert_verify: boolean,仅当target_endpoint为https且证书为自签名时跳过证书校验,调试用```-下载文件:+### URL 路由-```bash-curl -sS \- 'http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>/download?sandbox_path=/tmp/input.txt'+将+http://\<listening_host\>:\<listening_port\>/\<path_prefix\>/\<api_path\>+转发至+\<target_endpoint\>/\<api_path\>++### API 密钥注入++- OpenAI: 将 `Authorization: Bearer <placeholder>` 替换为实际密钥+- Anthropic: 将 `X-Api-Key: <placeholder>` 替换为实际密钥++### 配置示例++`注意:以下网络端点地址 https://api.openai.com、http://192.168.1.100:9000 均为示例`++#### 配置文件yaml示例++```yaml+inference_privacy_proxies:++ listen_host: "127.0.0.1"+ listen_port: 8080++ routes:+ - path_prefix: "openai"+ target_endpoint: "https://api.openai.com"+ api_key: "sk_sandbox_managed_openai_key"+ - path_prefix: "custom"+ target_endpoint: "http://192.168.1.100:9000"+ api_key: "sk_sandbox_managed_custom_key"```-删除沙箱:+边缘服务器可使用 `listen_host: "0.0.0.0"` 接收所有网络接口的连接。-```bash-curl -sS -X DELETE http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>+#### 转发示例++```text+客户端请求: POST http://127.0.0.1:8322/openai/v1/chat/completions -H "Authorization: Bearer sk_fake_key"+代理转发: POST https://api.openai.com/v1/chat/completions -H "Authorization: Bearer sk_sandbox_managed_openai_key"++客户端请求: POST http://127.0.0.1:8322/custom/v1/chat/completions -H "Authorization: Bearer sk_fake_key"+代理转发: POST http://192.168.1.100:9000/v1/chat/completions -H "Authorization: Bearer sk_sandbox_managed_custom_key"```+#### jiuwenclaw配置示例+++| 配置项 | 旧值 | 新值 |+| --------- | ----------------------------- | -------------------------------- |+| api\_base | http://192.168.1.100:9000/v1/ | http://127.0.0.1:8322/custom/v1/ |+| api\_key | sk_sandbox_managed_custom_key | sk_fake_key |+## 运行集成测试运行指定 policy 对应的集成测试:```bash-./scripts/test.sh default # jiuwenbox 使用 default-policy.yaml 作为安全策略运行服务。-./scripts/test.sh jiuwenclaw-tool # jiuwenbox 使用 jiuwenclaw-tool-policy.yaml 作为安全策略运行服务。+./tests/test.sh default # jiuwenbox 使用 default-policy.yaml 作为安全策略运行服务。+./tests/test.sh yuanrong # jiuwenbox 使用 yuanrong.yaml 运行服务,代理监听端口 8322。```运行指定测试用例:@@ -316,6 +357,42 @@ curl -sS -X DELETE http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>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```+### 性能测试++运行日常办公 workload 性能测试:++```bash+./tests/test.sh performance --server-endpoint 127.0.0.1:8321+```++可通过脚本参数设置沙箱数量、每个沙箱内的并发数,以及每个任务的循环次数:++```bash+./tests/test.sh performance \+ --sandbox-count 2 \+ --concurrency 16 \+ --loop 8 \+ --server-endpoint 127.0.0.1:8321+```++脚本会把这些参数映射为性能测试 fixture 使用的环境变量:++| 脚本参数 | 环境变量 | 默认值 |+| -------- | -------- | ------ |+| `--sandbox-count` | `JIUWENBOX_PERF_SANDBOX_COUNT` | `1` |+| `--concurrency` | `JIUWENBOX_PERF_CONCURRENCY` | `4` |+| `--loop` | `JIUWENBOX_PERF_LOOP` | `8` |++### 真实 LLM 集成测试++运行真实 LLM 集成测试需设置以下环境变量,若未设置环境变量,这些测试默认跳过:++```bash+export JIUWENBOX_TEST_LLM_ENDPOINT="https://api.openai.com"+export JIUWENBOX_TEST_LLM_API_KEY="sk_sandbox_managed_key"+export JIUWENBOX_TEST_LLM_MODEL="YOUR_MODEL"+```+## 注意事项- 修改启动 policy 文件后,需要重启服务。diff --git a/jiuwenbox/configs/default-policy.yaml b/jiuwenbox/configs/default-policy.yamlindex 2a94894fa4..41e1ffe0d2 100644--- a/jiuwenbox/configs/default-policy.yaml+++ b/jiuwenbox/configs/default-policy.yaml@@ -4,8 +4,8 @@ version: 1# Human-readable policy name shown by the server policy API.name: "server-default"-# Host directory used for server-managed sandbox backing storage.-sandbox_workspace: "/sandbox"+# Environment variables injected into every process running inside the sandbox.+environment: {}# Filesystem access rules. Paths are sandbox-visible absolute paths.filesystem_policy:@@ -20,10 +20,19 @@ filesystem_policy:# by the directory permissions and Landlock.directories:- path: "/home"- permissions: "0755"+ permissions: "0777"- path: "/tmp"permissions: "1777"+ # Lifecycle files to create for the sandbox and bind into the sandbox path.+ # Items may be either:+ # - "/path/to/file": create a server-managed empty file with default permissions+ # - path: "/path/to/file"+ # permissions: "0644" # optional octal permissions applied on the backing file+ # Paths must be absolute sandbox-visible paths. Files persist for the sandbox+ # lifecycle and are removed when the sandbox is deleted.+ files: []+# Read-only paths inside the sandbox. These entries grant read permission only;# they do not mount host paths by themselves.read_only:@@ -258,7 +267,7 @@ network:# 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+ default: allow# Domain names allowed as inbound sources. These are resolved to source IP rules.allowed_domains:@@ -281,5 +290,4 @@ network:- 8080# TCP destination ports blocked for inbound traffic. Block rules take precedence.- blocked_ports:- - 22+ blocked_ports: []diff --git a/jiuwenbox/configs/jiuwenclaw-tool-policy.yaml b/jiuwenbox/configs/yuanrong.yamlsimilarity index 71%rename from jiuwenbox/configs/jiuwenclaw-tool-policy.yamlrename to jiuwenbox/configs/yuanrong.yamlindex fa62976029..fb618f9cb2 100644--- a/jiuwenbox/configs/jiuwenclaw-tool-policy.yaml+++ b/jiuwenbox/configs/yuanrong.yaml@@ -1,21 +1,34 @@-# Policy schema version. Currently only version 1 is supported.-version: 1+# 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.-# Human-readable policy name shown by the server policy API.-name: "server-default"+version: 1+name: "yuanrong-default"# Host directory used for server-managed sandbox backing storage.-sandbox_workspace: "/tmp/sandbox"+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"@@ -27,8 +40,8 @@ filesystem_policy:# Read-write paths inside the sandbox. Use directories or bind_mounts to make# these paths exist in the sandbox.read_write:+ - "/home"- "/tmp"- - "/home/USER/.jiuwenclaw"# Extra bind mounts from host into sandbox.# Each item uses:@@ -66,15 +79,12 @@ filesystem_policy:- host_path: "/etc/ssl/certs"sandbox_path: "/etc/ssl/certs"mode: "ro"- - host_path: "/etc/ssl/openssl.cnf"- sandbox_path: "/etc/ssl/openssl.cnf"+ - host_path: "/etc/pki"+ sandbox_path: "/etc/pki"mode: "ro"- host_path: "/opt"sandbox_path: "/opt"mode: "ro"- - host_path: "/home/USER/.jiuwenclaw"- sandbox_path: "/home/USER/.jiuwenclaw"- mode: "rw"# Device nodes to expose inside the sandbox with bwrap --dev-bind.# Each item uses:@@ -99,7 +109,7 @@ namespace:# user:# true: create a new user namespace# false: reuse the current user namespace- user: false+ user: true# pid:# true: create a new PID namespace@@ -269,8 +279,54 @@ network:# TCP destination ports allowed for inbound traffic when default is deny.allowed_ports:- - 8080+ - 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 jiuwenclaw 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/Dockerfileindex 19720104ef..f923f8a1a7 100644--- a/jiuwenbox/docker/Dockerfile+++ b/jiuwenbox/docker/Dockerfile@@ -25,36 +25,18 @@ RUN yum makecache \WORKDIR /appCOPY pyproject.toml README.md ./+COPY docker/requirements.txt ./docker/requirements.txtCOPY src ./srcCOPY configs ./configs-COPY scripts ./scripts--RUN chmod +x ./scripts/server.sh--RUN pip install --break-system-packages -e . -i https://pypi.tuna.tsinghua.edu.cn/simple \- && pip install --break-system-packages -i https://pypi.tuna.tsinghua.edu.cn/simple \- "fastapi>=0.104.0" \- "uvicorn>=0.24.0" \- "pydantic>=2.5.0" \- "pydantic-settings>=2.1.0" \- "sqlalchemy>=2.0.0" \- "async-gaussdb>=0.30.4" \- "aiomysql>=0.2.0" \- "aiosqlite>=0.19.0" \- "python-dotenv>=1.0.0" \- "apscheduler>=3.10.0" \- "loguru>=0.7.0" \- "httpx>=0.25.0" \- "pyyaml>=6.0.0" \- "greenlet>=3.3.0" \- "openjiuwen==0.1.7" \- "jinja2>=3.0.0" \- "mcp>=1.0.0" \- "sse-starlette>=1.6.0" \- numexpr \- "redis~=7.3.0" \- "opencv-python>=4.10.0"++RUN pip install --break-system-packages --upgrade -i https://pypi.tuna.tsinghua.edu.cn/simple build setuptools wheel \+ && pip install --break-system-packages -i https://pypi.tuna.tsinghua.edu.cn/simple -r ./docker/requirements.txt \+ && python3 -m build --wheel --no-isolation \+ && pip install --break-system-packages -i https://pypi.tuna.tsinghua.edu.cn/simple dist/jiuwenbox-*.whl++RUN ln -s /usr/bin/python3 /usr/bin/pythonEXPOSE 8321+EXPOSE 8322-CMD ["./scripts/server.sh"]+CMD ["python3", "-m", "uvicorn", "jiuwenbox.server.app:app", "--host", "0.0.0.0", "--port", "8321"]diff --git a/jiuwenbox/docker/requirements.txt b/jiuwenbox/docker/requirements.txtnew file mode 100644index 0000000000..26e04f2383--- /dev/null+++ b/jiuwenbox/docker/requirements.txt@@ -0,0 +1,6 @@+python-dotenv>=1.0.0+pyyaml>=6.0.0+greenlet>=3.3.0+jinja2>=3.0.0+mcp>=1.0.0+numexprdiff --git a/jiuwenbox/docs/jiuwenbox_server_api.md b/jiuwenbox/docs/jiuwenbox_server_api.mdnew file mode 100644index 0000000000..06a6dfb59c--- /dev/null+++ b/jiuwenbox/docs/jiuwenbox_server_api.md@@ -0,0 +1,977 @@+# jiuwenbox 服务接口说明++本文档基于当前 jiuwenbox 服务端源码整理,描述 HTTP 接口的用途、参数和响应格式。++## 基础信息++### 默认地址++```text+http://127.0.0.1:8321+```++业务接口统一使用 `/api/v1` 前缀,健康检查接口为 `/health`。++### 请求与响应约定++- JSON 请求使用 `Content-Type: application/json`+- 文件上传使用 `multipart/form-data`+- 文件下载返回 `application/octet-stream`+- 日志接口通常返回 `text/plain`++成功响应通常直接返回 JSON 对象或数组,例如:++```json+{+ "id": "abc123",+ "phase": "ready"+}+```++删除、上传等无响应体接口成功时返回 `204 No Content`。++错误响应通常为:++```json+{+ "error": "Sandbox 'abc123' not found"+}+```++部分代理接口使用 FastAPI 默认错误格式:++```json+{+ "detail": "Proxy 'openai' not found"+}+```++### 常见状态码++| 状态码 | 含义 |+| --- | --- |+| `200` | 请求成功 |+| `201` | 资源创建成功 |+| `204` | 请求成功,无响应体 |+| `400` | 请求参数错误或 policy 校验失败 |+| `404` | 沙箱、策略、文件、目录或代理不存在 |+| `409` | 当前状态不允许执行该操作 |+| `500` | 服务端内部错误 |++## 通用数据结构++### 沙箱引用信息++| 字段 | 类型 | 说明 |+| --- | --- | --- |+| `id` | string | 沙箱 ID |+| `phase` | string | 沙箱状态,取值为 `provisioning`、`ready`、`stopped`、`error`、`deleting` |+| `runtime` | string | 当前固定为 `process` |+| `pid` | integer/null | 沙箱生命周期进程 PID |+| `created_at` | string | 创建时间 |+| `started_at` | string/null | 启动时间 |+| `error_message` | string/null | 错误信息 |+| `env` | object | 创建沙箱时注入的环境变量 |++示例:++```json+{+ "id": "abc123def456",+ "phase": "ready",+ "runtime": "process",+ "pid": 12345,+ "created_at": "2026-04-25T11:30:00.000000",+ "started_at": "2026-04-25T11:30:01.000000+00:00",+ "error_message": null,+ "env": {+ "DEMO_KEY": "demo-value"+ }+}+```++### 命令执行结果++| 字段 | 类型 | 说明 |+| --- | --- | --- |+| `exit_code` | integer | 命令退出码 |+| `stdout` | string | 标准输出 |+| `stderr` | string | 标准错误 |++### 后台执行结果++| 字段 | 类型 | 说明 |+| --- | --- | --- |+| `started` | boolean | 后台进程是否创建成功 |+| `pid` | integer/null | supervisor 进程 PID |+| `command` | string[] | 实际执行的命令 |+| `error_message` | string/null | 创建失败原因 |++### 健康检查结果++| 字段 | 类型 | 说明 |+| --- | --- | --- |+| `status` | string | 固定为 `ok` |+| `version` | string | 服务版本 |+| `runtime` | string | 当前固定为 `process` |+| `landlock_supported` | boolean | 当前主机是否支持 Landlock |+| `sandboxes_active` | integer | 当前处于 `ready` 状态的沙箱数量 |++## 健康检查++### 健康检查接口++接口:`GET /health`++用途:检查服务是否存活,并返回运行时信息。++Python 请求示例:++```python+import requests++resp = requests.get("http://127.0.0.1:8321/health", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "status": "ok",+ "version": "0.1.0",+ "runtime": "process",+ "landlock_supported": true,+ "sandboxes_active": 1+}+```++## 沙箱接口++### 创建沙箱++接口:`POST /api/v1/sandboxes`++用途:创建沙箱。++请求字段:++| 字段 | 类型 | 必填 | 说明 |+| --- | --- | --- | --- |+| `command` | string[] | 否 | 兼容字段,当前生命周期进程不会使用该命令 |+| `workdir` | string/null | 否 | 兼容字段 |+| `env` | object | 否 | 沙箱公共环境变量 |+| `policy` | object/null | 否 | 覆盖或追加的 policy 数据 |+| `policy_mode` | string | 否 | `override` 或 `append`,默认 `override` |++Python 请求示例:++```python+import requests++resp = requests.post(+ "http://127.0.0.1:8321/api/v1/sandboxes",+ json={+ "env": {+ "DEMO_KEY": "demo-value"+ },+ "policy_mode": "override"+ },+ timeout=30,+)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "id": "abc123def456",+ "phase": "ready",+ "runtime": "process",+ "pid": 12345,+ "created_at": "2026-04-25T11:30:00.000000",+ "started_at": "2026-04-25T11:30:01.000000+00:00",+ "error_message": null,+ "env": {+ "DEMO_KEY": "demo-value"+ }+}+```++### 查询沙箱列表++接口:`GET /api/v1/sandboxes`++用途:列出全部沙箱。++Python 请求示例:++```python+import requests++resp = requests.get("http://127.0.0.1:8321/api/v1/sandboxes", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+[+ {+ "id": "abc123def456",+ "phase": "ready",+ "runtime": "process",+ "pid": 12345,+ "created_at": "2026-04-25T11:30:00.000000",+ "started_at": "2026-04-25T11:30:01.000000+00:00",+ "error_message": null,+ "env": {}+ }+]+```++### 查询沙箱状态++接口:`GET /api/v1/sandboxes/{sandbox_id}`++用途:查询单个沙箱状态。++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.get(f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "id": "abc123def456",+ "phase": "ready",+ "runtime": "process",+ "pid": 12345,+ "created_at": "2026-04-25T11:30:00.000000",+ "started_at": "2026-04-25T11:30:01.000000+00:00",+ "error_message": null,+ "env": {}+}+```++### 删除沙箱++接口:`DELETE /api/v1/sandboxes/{sandbox_id}`++用途:删除沙箱。++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.delete(f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}", timeout=30)+print(resp.status_code)+```++响应示例:++```text+204 No Content+```++### 启动沙箱++接口:`POST /api/v1/sandboxes/{sandbox_id}/start`++用途:启动已停止的沙箱。++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.post(f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}/start", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "id": "abc123def456",+ "phase": "ready",+ "runtime": "process",+ "pid": 12345,+ "created_at": "2026-04-25T11:30:00.000000",+ "started_at": "2026-04-25T11:31:00.000000+00:00",+ "error_message": null,+ "env": {}+}+```++### 停止沙箱++接口:`POST /api/v1/sandboxes/{sandbox_id}/stop`++用途:停止沙箱。++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.post(f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}/stop", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "id": "abc123def456",+ "phase": "stopped",+ "runtime": "process",+ "pid": null,+ "created_at": "2026-04-25T11:30:00.000000",+ "started_at": "2026-04-25T11:31:00.000000+00:00",+ "error_message": null,+ "env": {}+}+```++### 重启沙箱++接口:`POST /api/v1/sandboxes/{sandbox_id}/restart`++用途:重启沙箱。++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.post(f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}/restart", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "id": "abc123def456",+ "phase": "ready",+ "runtime": "process",+ "pid": 22345,+ "created_at": "2026-04-25T11:30:00.000000",+ "started_at": "2026-04-25T11:32:00.000000+00:00",+ "error_message": null,+ "env": {}+}+```++### 同步执行命令++接口:`POST /api/v1/sandboxes/{sandbox_id}/exec`++用途:在沙箱内同步执行命令,等待命令结束后返回结果。++请求字段:++| 字段 | 类型 | 必填 | 说明 |+| --- | --- | --- | --- |+| `command` | string[] | 是 | 待执行命令 |+| `workdir` | string/null | 否 | 命令工作目录 |+| `env` | object/null | 否 | 本次执行追加环境变量 |+| `stdin` | string/null | 否 | 标准输入文本 |+| `timeout_seconds` | integer/null | 否 | 超时时间,单位秒 |++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.post(+ f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}/exec",+ json={+ "command": ["python3", "-c", "print('hello')"],+ "timeout_seconds": 10+ },+ timeout=30,+)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "exit_code": 0,+ "stdout": "hello\n",+ "stderr": ""+}+```++### 启动后台命令++接口:`POST /api/v1/sandboxes/{sandbox_id}/exec_background`++用途:在沙箱内启动后台进程,进程创建后立即返回。++请求字段与 `/exec` 相同。++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.post(+ f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}/exec_background",+ json={+ "command": ["python3", "-m", "http.server", "18080"]+ },+ timeout=30,+)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "started": true,+ "pid": 23456,+ "command": ["python3", "-m", "http.server", "18080"],+ "error_message": null+}+```++### 查看沙箱日志++接口:`GET /api/v1/sandboxes/{sandbox_id}/logs`++用途:读取沙箱审计日志。++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.get(f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}/logs", timeout=30)+print(resp.status_code)+print(resp.text)+```++响应示例:++```text+[2026-04-25T11:30:00.000000] sandbox_created+[2026-04-25T11:30:01.000000] sandbox_started+```++### 上传文件++接口:`POST /api/v1/sandboxes/{sandbox_id}/upload`++用途:向沙箱内上传文件。++查询参数:++| 参数 | 类型 | 必填 | 说明 |+| --- | --- | --- | --- |+| `sandbox_path` | string | 是 | 沙箱内目标路径 |++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+with open("local.txt", "rb") as f:+ resp = requests.post(+ f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}/upload",+ params={"sandbox_path": "/tmp/remote.txt"},+ files={"file": ("local.txt", f)},+ timeout=30,+ )+print(resp.status_code)+```++响应示例:++```text+204 No Content+```++### 下载文件++接口:`GET /api/v1/sandboxes/{sandbox_id}/download`++用途:从沙箱内下载文件。++查询参数:++| 参数 | 类型 | 必填 | 说明 |+| --- | --- | --- | --- |+| `sandbox_path` | string | 是 | 沙箱内源文件路径 |++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.get(+ f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}/download",+ params={"sandbox_path": "/tmp/remote.txt"},+ timeout=30,+)+print(resp.status_code)+print(resp.content)+```++响应示例:++```text+二进制文件内容+```++### 列出文件++接口:`GET /api/v1/sandboxes/{sandbox_id}/files`++用途:列出沙箱目录下的文件和目录。++查询参数:++| 参数 | 类型 | 必填 | 说明 |+| --- | --- | --- | --- |+| `sandbox_path` | string | 是 | 待列举目录 |+| `recursive` | boolean | 否 | 是否递归 |+| `max_depth` | integer/null | 否 | 递归深度限制 |+| `include_files` | boolean | 否 | 是否包含文件,默认 `true` |+| `include_dirs` | boolean | 否 | 是否包含目录,默认 `true` |++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.get(+ f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}/files",+ params={+ "sandbox_path": "/tmp",+ "recursive": "true",+ "max_depth": 2,+ "include_files": "true",+ "include_dirs": "true",+ },+ timeout=30,+)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "items": [+ {+ "name": "remote.txt",+ "path": "/tmp/remote.txt",+ "size": 12,+ "is_directory": false,+ "modified_time": "2026-04-25T11:35:00.000000",+ "type": ".txt"+ }+ ]+}+```++### 搜索文件++接口:`GET /api/v1/sandboxes/{sandbox_id}/search`++用途:按 glob 模式搜索文件。++查询参数:++| 参数 | 类型 | 必填 | 说明 |+| --- | --- | --- | --- |+| `sandbox_path` | string | 是 | 搜索根目录 |+| `pattern` | string | 是 | 匹配模式 |+| `exclude_patterns` | string[] | 否 | 排除模式,可重复传入 |++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.get(+ f"http://127.0.0.1:8321/api/v1/sandboxes/{sandbox_id}/search",+ params={+ "sandbox_path": "/tmp",+ "pattern": "*.txt",+ "exclude_patterns": "*.bak",+ },+ timeout=30,+)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "items": [+ {+ "name": "remote.txt",+ "path": "/tmp/remote.txt",+ "size": 12,+ "is_directory": false,+ "modified_time": "2026-04-25T11:35:00.000000",+ "type": ".txt"+ }+ ]+}+```++## Policy 接口++### 查询沙箱策略++接口:`GET /api/v1/policies/{sandbox_id}`++用途:获取某个沙箱当前生效的 policy。++Python 请求示例:++```python+import requests++sandbox_id = "abc123def456"+resp = requests.get(f"http://127.0.0.1:8321/api/v1/policies/{sandbox_id}", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "name": "default-policy",+ "process": {+ "run_as_user": "nobody",+ "run_as_group": "nobody"+ },+ "network": {+ "mode": "host"+ }+}+```++## 代理接口++代理接口用于管理 inference privacy proxy。++### 创建代理++接口:`POST /api/v1/proxies`++用途:创建一个代理路由。++请求字段:++| 字段 | 类型 | 必填 | 说明 |+| --- | --- | --- | --- |+| `path_prefix` | string | 是 | 路由前缀,如 `/openai` |+| `target_endpoint` | string | 是 | 目标服务地址 |+| `api_key` | string | 否 | 注入到上游的 API Key |+| `skip_cert_verify` | boolean | 否 | 是否跳过证书校验 |++Python 请求示例:++```python+import requests++resp = requests.post(+ "http://127.0.0.1:8321/api/v1/proxies",+ json={+ "path_prefix": "/openai",+ "target_endpoint": "https://api.openai.com",+ "api_key": "sk-demo",+ "skip_cert_verify": False+ },+ timeout=30,+)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "name": "openai",+ "state": "stopped",+ "created_at": "2026-04-25T11:40:00.000000"+}+```++### 查询代理列表++接口:`GET /api/v1/proxies`++用途:列出全部代理路由。++Python 请求示例:++```python+import requests++resp = requests.get("http://127.0.0.1:8321/api/v1/proxies", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+[+ {+ "name": "openai",+ "state": "running",+ "listen_port": 18080,+ "route": {+ "path_prefix": "/openai",+ "target_endpoint": "https://api.openai.com",+ "api_key": "sk-demo..."+ },+ "created_at": "2026-04-25T11:40:00.000000",+ "started_at": "2026-04-25T11:41:00.000000",+ "error_message": null+ }+]+```++### 查询代理详情++接口:`GET /api/v1/proxies/{proxy_name}`++用途:查询单个代理路由详情。++Python 请求示例:++```python+import requests++proxy_name = "openai"+resp = requests.get(f"http://127.0.0.1:8321/api/v1/proxies/{proxy_name}", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "name": "openai",+ "state": "running",+ "listen_port": 18080,+ "route": {+ "path_prefix": "/openai",+ "target_endpoint": "https://api.openai.com",+ "api_key": "sk-demo",+ "skip_cert_verify": false,+ "target_host": "api.openai.com",+ "target_port": 443,+ "use_tls": true+ },+ "created_at": "2026-04-25T11:40:00.000000",+ "started_at": "2026-04-25T11:41:00.000000",+ "error_message": null+}+```++### 删除代理++接口:`DELETE /api/v1/proxies/{proxy_name}`++用途:删除代理路由。++Python 请求示例:++```python+import requests++proxy_name = "openai"+resp = requests.delete(f"http://127.0.0.1:8321/api/v1/proxies/{proxy_name}", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "name": "openai",+ "deleted": true+}+```++### 启动代理++接口:`POST /api/v1/proxies/{proxy_name}/start`++用途:启动代理路由。++Python 请求示例:++```python+import requests++proxy_name = "openai"+resp = requests.post(f"http://127.0.0.1:8321/api/v1/proxies/{proxy_name}/start", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "name": "openai",+ "state": "running",+ "started_at": "2026-04-25T11:41:00.000000",+ "error_message": null+}+```++### 停止代理++接口:`POST /api/v1/proxies/{proxy_name}/stop`++用途:停止代理路由。++Python 请求示例:++```python+import requests++proxy_name = "openai"+resp = requests.post(f"http://127.0.0.1:8321/api/v1/proxies/{proxy_name}/stop", timeout=30)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "name": "openai",+ "state": "stopped",+ "error_message": null+}+```++### 更新代理++接口:`PUT /api/v1/proxies/{proxy_name}`++用途:更新代理路由目标。++请求字段与创建代理相同,但 `path_prefix` 仅用于构造请求体,服务端会保留原有路由名对应的前缀。++Python 请求示例:++```python+import requests++proxy_name = "openai"+resp = requests.put(+ f"http://127.0.0.1:8321/api/v1/proxies/{proxy_name}",+ json={+ "path_prefix": "/openai",+ "target_endpoint": "https://api.openai.com/v1",+ "api_key": "sk-demo-new",+ "skip_cert_verify": False+ },+ timeout=30,+)+print(resp.status_code)+print(resp.json())+```++响应示例:++```json+{+ "name": "openai",+ "state": "running",+ "started_at": "2026-04-25T11:42:30.000000",+ "error_message": null+}+```++### 查看代理日志++接口:`GET /api/v1/proxies/{proxy_name}/logs`++用途:查看代理日志。++查询参数:++| 参数 | 类型 | 必填 | 说明 |+| --- | --- | --- | --- |+| `lines` | integer/null | 否 | 只返回最后 N 行 |++Python 请求示例:++```python+import requests++proxy_name = "openai"+resp = requests.get(+ f"http://127.0.0.1:8321/api/v1/proxies/{proxy_name}/logs",+ params={"lines": 50},+ timeout=30,+)+print(resp.status_code)+print(resp.text)+```++响应示例:++```text+[2026-04-25T11:41:00.000000] Global proxy started on port 18080+[2026-04-25T11:41:00.100000] Route 'openai' enabled for routing+```++## 说明++- `sandbox.create` 仍接受 `command` 和 `workdir` 字段,但当前生命周期持有进程为服务内部 daemon,这两个字段不会出现在 `SandboxRef` 返回体中。+- `sandbox.exec` 和 `sandbox.exec_background` 中的 `workdir`、`env`、`timeout_seconds` 仍然有效。+- 文档示例中的时间、PID、ID 仅为示意。diff --git a/jiuwenbox/pyproject.toml b/jiuwenbox/pyproject.tomlindex f3928a0847..4a20e35818 100644--- a/jiuwenbox/pyproject.toml+++ b/jiuwenbox/pyproject.toml@@ -8,7 +8,7 @@ version = "0.1.0"description = "Jiuwen sandbox system"readme = "README.md"requires-python = ">=3.11"-license = "Apache-2.0"+license = {text = "Apache-2.0"}dependencies = ["pydantic>=2.0","pyyaml>=6.0",@@ -32,6 +32,14 @@ include = ["jiuwenbox*"][tool.pytest.ini_options]testpaths = ["tests"]+markers = [+ "unit: Unit tests",+ "integration: Integration tests",+ "performance: Performance tests",+ "system: System tests",+ "slow: Slow running tests",+ "async: Async tests",+][tool.ruff]src = ["src"]diff --git a/jiuwenbox/scripts/build_docker.sh b/jiuwenbox/scripts/build_docker.shindex db29b3a8bd..3d28c98713 100755--- a/jiuwenbox/scripts/build_docker.sh+++ b/jiuwenbox/scripts/build_docker.sh@@ -9,4 +9,18 @@ IMAGE_NAME="${JIUWENBOX_IMAGE_NAME:-jiuwenbox}"IMAGE_TAG="${JIUWENBOX_IMAGE_TAG:-latest}"IMAGE_REF="${IMAGE_NAME}:${IMAGE_TAG}"+usage() {+ cat <<'EOF'+Usage: scripts/build_docker.sh [docker build args...]++Build the jiuwenbox image only. The policy file is selected later when+running the container via scripts/run_docker.sh.+EOF+}++if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then+ usage+ exit 0+fi+docker build -f "$PROJECT_DIR/docker/Dockerfile" --no-cache -t "$IMAGE_REF" "$PROJECT_DIR" "$@"diff --git a/jiuwenbox/scripts/run_docker.sh b/jiuwenbox/scripts/run_docker.shindex 697161312e..06e0e74fad 100755--- a/jiuwenbox/scripts/run_docker.sh+++ b/jiuwenbox/scripts/run_docker.sh@@ -3,22 +3,84 @@set -euo pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"+CALLER_CWD="$(pwd)"IMAGE_NAME="${JIUWENBOX_IMAGE_NAME:-jiuwenbox}"IMAGE_TAG="${JIUWENBOX_IMAGE_TAG:-latest}"IMAGE_REF="${IMAGE_NAME}:${IMAGE_TAG}"CONTAINER_NAME="${JIUWENBOX_CONTAINER_NAME:-jiuwenbox}"HOST_PORT="${JIUWENBOX_HOST_PORT:-8321}"+PROXY_PORT="${JIUWENBOX_PROXY_PORT:-8322}"+POLICY_CONFIG=""+CONTAINER_POLICY_PATH="/app/runtime-config/policy.yaml"+CONTAINER_DEFAULT_POLICY_PATH="/app/configs/default-policy.yaml"+DOCKER_ENV_ARGS=()+DOCKER_VOLUME_ARGS=()++usage() {+ cat <<'EOF'+Usage: scripts/run_docker.sh [policy-config.yaml] [docker run args...]++Examples:+ scripts/run_docker.sh+ scripts/run_docker.sh configs/default-policy.yaml+EOF+}++if [[ $# -gt 0 ]]; then+ case "$1" in+ -h|--help)+ usage+ exit 0+ ;;+ -*)+ ;;+ *)+ POLICY_CONFIG="$1"+ shift+ ;;+ esac+fiecho "Starting jiuwenbox container:"echo " image: $IMAGE_REF"echo " container: $CONTAINER_NAME"echo " url: http://127.0.0.1:${HOST_PORT}"++if [[ -n "$POLICY_CONFIG" ]]; then+ POLICY_CONFIG_ABS=""++ if [[ "$POLICY_CONFIG" = /* && -f "$POLICY_CONFIG" ]]; then+ POLICY_CONFIG_ABS="$(realpath "$POLICY_CONFIG")"+ elif [[ -f "$CALLER_CWD/$POLICY_CONFIG" ]]; then+ POLICY_CONFIG_ABS="$(realpath "$CALLER_CWD/$POLICY_CONFIG")"+ elif [[ -f "$PROJECT_DIR/$POLICY_CONFIG" ]]; then+ POLICY_CONFIG_ABS="$(realpath "$PROJECT_DIR/$POLICY_CONFIG")"+ else+ echo "error: policy config not found: $POLICY_CONFIG" >&2+ exit 1+ fi++ DOCKER_ENV_ARGS+=(-e "JIUWENBOX_POLICY_PATH=${CONTAINER_POLICY_PATH}")+ DOCKER_VOLUME_ARGS+=(-v "${POLICY_CONFIG_ABS}:${CONTAINER_POLICY_PATH}:ro")+ echo " policy: $POLICY_CONFIG_ABS"+else+ DOCKER_ENV_ARGS+=(-e "JIUWENBOX_POLICY_PATH=${CONTAINER_DEFAULT_POLICY_PATH}")+ echo " policy: ${CONTAINER_DEFAULT_POLICY_PATH} (container default)"+fi+echo-docker run -it \+docker run -itd \--name "$CONTAINER_NAME" \- --privileged \+ --cap-add=SYS_ADMIN \+ --cap-add=NET_ADMIN \+ --security-opt seccomp=unconfined \+ --security-opt apparmor=unconfined \-p "${HOST_PORT}:8321" \- "$IMAGE_REF" \- "$@"\ No newline at end of file+ -p "${PROXY_PORT}:8322" \+ "${DOCKER_ENV_ARGS[@]}" \+ "${DOCKER_VOLUME_ARGS[@]}" \+ "$@" \+ "$IMAGE_REF"diff --git a/jiuwenbox/scripts/server.sh b/jiuwenbox/scripts/server.shdeleted file mode 100755index a11ed23ae1..0000000000--- a/jiuwenbox/scripts/server.sh+++ /dev/null@@ -1,58 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--CALLER_CWD="$(pwd)"-PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"-cd "$PROJECT_DIR"--usage() {- cat <<'EOF'-Usage: scripts/server.sh [policy-config.yaml] [uvicorn args...]- scripts/server.sh [policy-config.yaml] [port] [uvicorn args...]--Examples:- scripts/server.sh configs/jiuwenclaw-policy.yaml- scripts/server.sh configs/default-policy.yaml 9000 --reload-EOF-}--POLICY_CONFIG="${JIUWENBOX_DEFAULT_POLICY_PATH:-}"-PORT="${JIUWENBOX_PORT:-8321}"--if [[ $# -gt 0 ]]; then- case "$1" in- -h|--help)- usage- exit 0- ;;- -*)- ;;- *)- POLICY_CONFIG="$1"- shift- ;;- esac-fi--if [[ $# -gt 0 && "$1" =~ ^[0-9]+$ ]]; then- PORT="$1"- shift-fi--POLICY_CONFIG="${POLICY_CONFIG:-configs/default-policy.yaml}"-POLICY_CONFIG_ABS=""--if [[ "$POLICY_CONFIG" = /* && -f "$POLICY_CONFIG" ]]; then- POLICY_CONFIG_ABS="$(realpath "$POLICY_CONFIG")"-elif [[ -f "$CALLER_CWD/$POLICY_CONFIG" ]]; then- POLICY_CONFIG_ABS="$(realpath "$CALLER_CWD/$POLICY_CONFIG")"-else- echo "error: policy config not found: $POLICY_CONFIG" >&2- exit 1-fi--export JIUWENBOX_DEFAULT_POLICY_PATH="$POLICY_CONFIG_ABS"--echo "Starting jiuwenbox with policy config: $JIUWENBOX_DEFAULT_POLICY_PATH"-echo "Listening on port: $PORT"-python3 -m uvicorn jiuwenbox.server.app:app --app-dir src --host 0.0.0.0 --port "$PORT" --log-level debug "$@"diff --git a/jiuwenbox/src/jiuwenbox/logging_config.py b/jiuwenbox/src/jiuwenbox/logging_config.pynew file mode 100644index 0000000000..a9ed69562a--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/logging_config.py@@ -0,0 +1,28 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Shared logging configuration for jiuwenbox."""++from __future__ import annotations++import logging++LOG_FORMAT = "[%(asctime)s] %(levelname)s %(name)s: %(message)s"+LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"+UVICORN_LOGGER_NAMES = ("uvicorn", "uvicorn.error", "uvicorn.access")+++def _timestamp_formatter() -> logging.Formatter:+ return logging.Formatter(LOG_FORMAT, datefmt=LOG_DATE_FORMAT)+++def _set_handler_formatters(logger: logging.Logger, formatter: logging.Formatter) -> None:+ for handler in logger.handlers:+ handler.setFormatter(formatter)+++def configure_logging(level: int = logging.INFO) -> None:+ """Configure process logging with jiuwenbox's default timestamped format."""+ logging.basicConfig(level=level, format=LOG_FORMAT, datefmt=LOG_DATE_FORMAT)+ formatter = _timestamp_formatter()+ _set_handler_formatters(logging.getLogger(), formatter)+ for logger_name in UVICORN_LOGGER_NAMES:+ _set_handler_formatters(logging.getLogger(logger_name), formatter)diff --git a/jiuwenbox/src/jiuwenbox/models/__init__.py b/jiuwenbox/src/jiuwenbox/models/__init__.pyindex 358ef2005a..340e021d8a 100644--- a/jiuwenbox/src/jiuwenbox/models/__init__.py+++ b/jiuwenbox/src/jiuwenbox/models/__init__.py@@ -1,6 +1,7 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.from jiuwenbox.models.sandbox import (+ BackgroundExecResult,ExecResult,SandboxPhase,SandboxRef,@@ -10,6 +11,7 @@ from jiuwenbox.models.policy import (ArchitectureSyscallPolicy,BindMount,DirectoryMount,+ FileMount,FilesystemPolicy,CapabilityPolicy,LandlockPolicy,@@ -27,6 +29,7 @@ from jiuwenbox.models.common import ()__all__ = [+ "BackgroundExecResult","ExecResult","SandboxPhase","SandboxRef",@@ -34,6 +37,7 @@ __all__ = ["BindMount","ArchitectureSyscallPolicy","DirectoryMount",+ "FileMount","FilesystemPolicy","CapabilityPolicy","LandlockPolicy",diff --git a/jiuwenbox/src/jiuwenbox/models/policy.py b/jiuwenbox/src/jiuwenbox/models/policy.pyindex d8033c9e48..20691e4da7 100644--- a/jiuwenbox/src/jiuwenbox/models/policy.py+++ b/jiuwenbox/src/jiuwenbox/models/policy.py@@ -8,6 +8,7 @@ import osfrom pathlib import Pathfrom typing import Literal+import yamlfrom pydantic import BaseModel, ConfigDict, Field, field_validator@@ -16,6 +17,45 @@ def _expand_path(value: str) -> str:return str(Path(os.path.expandvars(value)).expanduser())+def _contains_crlf_or_null(value: str) -> bool:+ """Check if string contains CRLF or null byte."""+ return "\r" in value or "\n" in value or "\x00" in value+++def _contains_control_chars(value: str) -> bool:+ """Check if string contains control characters (excluding tab)."""+ for c in value:+ if ord(c) < 32 and c != "\t":+ return True+ return False+++def _contains_path_traversal(value: str) -> bool:+ """Check if string contains path traversal sequence."""+ from urllib.parse import unquote+ decoded = unquote(value)+ return ".." in decoded or "/../" in decoded or decoded.endswith("/..")+++def _normalize_octal_permissions(value: object, *, label: str) -> str | None:+ if value is None:+ return None+ if isinstance(value, int):+ if 0 <= value <= 0o777:+ text = format(value, "o")+ else:+ text = str(value)+ else:+ text = str(value)+ if not text:+ raise ValueError(f"{label} cannot be empty")+ if not all(char in "01234567" for char in text):+ raise ValueError(f"{label} must be an octal value")+ if len(text) > 4:+ raise ValueError(f"{label} must be at most four octal digits")+ return text.zfill(4)++class BindMount(BaseModel):host_path: strsandbox_path: str@@ -55,26 +95,29 @@ class DirectoryMount(BaseModel):@field_validator("permissions", mode="before")@classmethoddef permissions_must_be_octal(cls, value: object) -> str | None:- if value is None:- return None- if isinstance(value, int):- if 0 <= value <= 0o777:- text = format(value, "o")- else:- text = str(value)- else:- text = str(value)- if not text:- raise ValueError("directory permissions cannot be empty")- if not all(char in "01234567" for char in text):- raise ValueError("directory permissions must be an octal value")- if len(text) > 4:- raise ValueError("directory permissions must be at most four octal digits")- return text.zfill(4)+ return _normalize_octal_permissions(value, label="directory permissions")+++class FileMount(BaseModel):+ path: str+ permissions: str | int | None = None++ @field_validator("path", mode="before")+ @classmethod+ def expand_path(cls, value: object) -> object:+ if isinstance(value, str):+ return _expand_path(value)+ return value++ @field_validator("permissions", mode="before")+ @classmethod+ def permissions_must_be_octal(cls, value: object) -> str | None:+ return _normalize_octal_permissions(value, label="file permissions")class FilesystemPolicy(BaseModel):directories: list[str | DirectoryMount] = Field(default_factory=list)+ files: list[str | FileMount] = Field(default_factory=list)read_only: list[str] = Field(default_factory=list)read_write: list[str] = Field(default_factory=list)bind_mounts: list[BindMount] = Field(default_factory=list)@@ -87,6 +130,13 @@ class FilesystemPolicy(BaseModel):return [_expand_path(item) if isinstance(item, str) else item for item in value]return value+ @field_validator("files", mode="before")+ @classmethod+ def expand_file_paths(cls, value: object) -> object:+ if isinstance(value, list):+ return [_expand_path(item) if isinstance(item, str) else item for item in value]+ return value+@field_validator("read_only", "read_write", mode="before")@classmethoddef expand_path_lists(cls, value: object) -> object:@@ -143,6 +193,133 @@ class NetworkRulePolicy(BaseModel):blocked_ports: list[int] = Field(default_factory=list)+class ProxyRouteEntry(BaseModel):+ path_prefix: str # Required - no default (must be single-level, non-root)+ target_endpoint: str = "https://api.openai.com"+ api_key: str = ""+ skip_cert_verify: bool = False++ @field_validator("path_prefix", mode="after")+ @classmethod+ def validate_path_prefix(cls, value: str) -> str:+ from urllib.parse import unquote++ if not value or not value.strip():+ raise ValueError("path_prefix cannot be empty")++ normalized = value.strip()++ if _contains_crlf_or_null(normalized):+ raise ValueError("path_prefix contains invalid characters")++ decoded = unquote(normalized)+ if _contains_crlf_or_null(decoded):+ raise ValueError("path_prefix contains invalid characters")++ if _contains_control_chars(normalized) or _contains_control_chars(decoded):+ raise ValueError("path_prefix contains invalid characters")++ if _contains_path_traversal(normalized):+ raise ValueError("path_prefix cannot contain path traversal")++ if not normalized.startswith("/"):+ normalized = "/" + normalized++ # Check for root path BEFORE stripping trailing slash+ # "/" normalized becomes "" after rstrip, so check original normalized+ if normalized.rstrip("/") == "":+ raise ValueError(+ "path_prefix cannot be root path '/'. "+ "Root path would match all requests and make other routes unreachable. "+ "Use a specific prefix like '/api' or '/llm-proxy'."+ )++ normalized = normalized.rstrip("/")++ # Ban internal slashes (single-level only)+ stripped = normalized.lstrip("/")+ if "/" in stripped:+ raise ValueError(+ f"path_prefix must be single-level (no internal slashes). "+ f"Got '{value}' -> '{normalized}'. "+ f"Use '/api' not '/api/v1'. Each route handles one path level only."+ )++ return normalized++ @field_validator("api_key", mode="after")+ @classmethod+ def validate_api_key(cls, value: str) -> str:+ from urllib.parse import unquote++ if not value:+ return value++ if _contains_crlf_or_null(value):+ raise ValueError("api_key contains invalid characters")++ decoded = unquote(value)+ if _contains_crlf_or_null(decoded):+ raise ValueError("api_key contains invalid characters")++ if _contains_control_chars(value) or _contains_control_chars(decoded):+ raise ValueError("api_key contains invalid characters")++ return value++ @field_validator("target_endpoint", mode="after")+ @classmethod+ def validate_target_endpoint(cls, value: str) -> str:+ from urllib.parse import urlparse++ if not value or not value.strip():+ raise ValueError("target_endpoint cannot be empty")++ normalized = value.strip()++ if _contains_crlf_or_null(normalized):+ raise ValueError("target_endpoint contains invalid characters")++ try:+ parsed = urlparse(normalized)+ if not parsed.scheme or not parsed.netloc:+ raise ValueError("target_endpoint must be a valid URL")+ if parsed.scheme not in ("http", "https"):+ raise ValueError("target_endpoint must use http or https scheme")+ except Exception as e:+ raise ValueError(f"target_endpoint must be a valid URL: {e}") from e++ return normalized+++class InferencePrivacyProxyPolicy(BaseModel):+ listen_port: int = 0+ listen_host: str | None = None+ routes: list[ProxyRouteEntry] = Field(default_factory=list)++ @field_validator("listen_port", mode="after")+ @classmethod+ def validate_listen_port(cls, value: int) -> int:+ if value < 0 or value > 65535:+ raise ValueError("listen_port must be between 0 and 65535")+ return value++ @field_validator("listen_host", mode="after")+ @classmethod+ def validate_listen_host(cls, value: str | None, info) -> str | None:+ import ipaddress+ listen_port = info.data.get("listen_port", 0)+ if listen_port <= 0:+ return value+ if not value or not value.strip():+ raise ValueError("listen_host required when listen_port > 0")+ try:+ ipaddress.ip_address(value.strip())+ except ValueError as e:+ raise ValueError(f"listen_host must be valid IP address: {value}") from e+ return value.strip()++class NetworkPolicy(BaseModel):mode: NetworkMode = NetworkMode.ISOLATEDegress: NetworkRulePolicy = Field(default_factory=NetworkRulePolicy)@@ -154,7 +331,7 @@ class SecurityPolicy(BaseModel):version: int = 1name: str = "default"- sandbox_workspace: str = "/sandbox"+ environment: dict[str, str] = Field(default_factory=dict)filesystem_policy: FilesystemPolicy = Field(default_factory=FilesystemPolicy)process: ProcessPolicy = Field(default_factory=ProcessPolicy)namespace: NamespacePolicy = Field(default_factory=NamespacePolicy)@@ -162,11 +339,15 @@ class SecurityPolicy(BaseModel):landlock: LandlockPolicy = Field(default_factory=LandlockPolicy)syscall: SyscallPolicy = Field(default_factory=SyscallPolicy)network: NetworkPolicy = Field(default_factory=NetworkPolicy)-- @field_validator("sandbox_workspace")- @classmethod- def sandbox_workspace_must_be_absolute(cls, value: str) -> str:- workspace = Path(_expand_path(value))- if not workspace.is_absolute():- raise ValueError("sandbox_workspace must be an absolute host path")- return str(workspace)+ inference_privacy_proxies: InferencePrivacyProxyPolicy = Field(default_factory=InferencePrivacyProxyPolicy)++ def tostring(self) -> str:+ """Serialize the policy to a YAML string."""+ return yaml.safe_dump(+ self.model_dump(mode="json"),+ sort_keys=False,+ allow_unicode=True,+ )++ def __str__(self) -> str:+ return self.tostring()diff --git a/jiuwenbox/src/jiuwenbox/models/sandbox.py b/jiuwenbox/src/jiuwenbox/models/sandbox.pyindex e164de6cd3..74a9582174 100644--- a/jiuwenbox/src/jiuwenbox/models/sandbox.py+++ b/jiuwenbox/src/jiuwenbox/models/sandbox.py@@ -38,8 +38,6 @@ class SandboxRef(BaseModel):created_at: datetime = Field(default_factory=datetime.now)started_at: datetime | None = Noneerror_message: str | None = None- command: list[str] = Field(default_factory=list)- workdir: str | None = Noneenv: dict[str, str] = Field(default_factory=dict)@@ -49,3 +47,12 @@ class ExecResult(BaseModel):exit_code: intstdout: str = ""stderr: str = ""+++class BackgroundExecResult(BaseModel):+ """Result of starting a background command in a sandbox."""++ started: bool+ pid: int | None = None+ command: list[str] = Field(default_factory=list)+ error_message: str | None = Nonediff --git a/jiuwenbox/src/jiuwenbox/proxy/__init__.py b/jiuwenbox/src/jiuwenbox/proxy/__init__.pynew file mode 100644index 0000000000..d4086adfb8--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/proxy/__init__.py@@ -0,0 +1,24 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Inference privacy proxy package."""++from jiuwenbox.proxy.inference_privacy_proxy import (+ InferencePrivacyProxy,+ InferencePrivacyProxyConfig,+ ProxyRoute,+ PLACEHOLDER,+)+from jiuwenbox.proxy.inference_privacy_proxy_manager import (+ InferencePrivacyProxyManager,+ ProxyState,+ get_proxy_manager,+)++__all__ = [+ "InferencePrivacyProxy",+ "InferencePrivacyProxyConfig",+ "ProxyRoute",+ "PLACEHOLDER",+ "InferencePrivacyProxyManager",+ "ProxyState",+ "get_proxy_manager",+]\ No newline at end of filediff --git a/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy.py b/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy.pynew file mode 100644index 0000000000..1e052d8811--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy.py@@ -0,0 +1,460 @@+"""HTTP-aware inference privacy proxy with path-based routing.++Supports multiple target endpoints through path prefix routing:+- POST http://127.0.0.1:8080/openai/v1/chat/completions+ -> forwards to https://api.openai.com/v1/chat/completions+ -> injects API key for openai route++Features:+- Path-based routing to multiple targets+- API key injection via Authorization header+- Request/response logging+- HTTPS target support+"""++from __future__ import annotations++import asyncio+import logging+import re+import ssl+from dataclasses import dataclass, field+from typing import Callable+from urllib.parse import urlparse++from jiuwenbox.logging_config import configure_logging++configure_logging()+logger = logging.getLogger(__name__)+++PLACEHOLDER = "<placeholder>"+++@dataclass+class ProxyRoute:+ path_prefix: str+ target_endpoint: str+ api_key: str = ""+ skip_cert_verify: bool = False+ _target_host: str = ""+ _target_port: int = 0+ _use_tls: bool = False+ _target_base_path: str = ""++ def __post_init__(self):+ (+ self._target_host,+ self._target_port,+ self._use_tls,+ self._target_base_path,+ ) = self._parse_endpoint(self.target_endpoint)+ if not self.path_prefix.startswith("/"):+ self.path_prefix = "/" + self.path_prefix+ self.path_prefix = self.path_prefix.rstrip("/")++ @staticmethod+ def _parse_endpoint(endpoint: str) -> tuple[str, int, bool, str]:+ """Parse endpoint URL to extract host, port, TLS, and base path."""+ endpoint = endpoint.strip()++ if endpoint.startswith("http://") or endpoint.startswith("https://"):+ parsed = urlparse(endpoint)+ host = parsed.hostname or "localhost"+ port = parsed.port or (443 if parsed.scheme == "https" else 80)+ use_tls = parsed.scheme == "https"+ base_path = parsed.path.rstrip("/") or ""+ return host, port, use_tls, base_path++ if ":" in endpoint:+ parts = endpoint.rsplit(":", 1)+ host = parts[0]+ try:+ port = int(parts[1])+ use_tls = port == 443+ except ValueError:+ host = endpoint+ port = 443+ use_tls = True+ return host, port, use_tls, ""++ return endpoint, 443, True, ""++ @property+ def target_host(self) -> str:+ return self._target_host++ @property+ def target_port(self) -> int:+ return self._target_port++ @property+ def use_tls(self) -> bool:+ return self._use_tls++ @property+ def target_base_path(self) -> str:+ return self._target_base_path+++@dataclass+class InferencePrivacyProxyConfig:+ listen_port: int = 0+ listen_host: str = "127.0.0.1"+ routes: list[ProxyRoute] = field(default_factory=list)+++class InferencePrivacyProxy:+ def __init__(+ self,+ config: InferencePrivacyProxyConfig,+ log_callback: Callable[[str], None] | None = None,+ ) -> None:+ self.config = config+ self._server: asyncio.Server | None = None+ self._serve_task: asyncio.Task[None] | None = None+ self._running = False+ self._log_callback = log_callback+ self._ssl_contexts: dict[str, ssl.SSLContext] = {}+ self._enabled_routes: set[str] = set()++ @property+ def is_running(self) -> bool:+ """Return whether the proxy accept loop is active."""+ return self._running++ @property+ def server(self) -> asyncio.Server | None:+ """Expose the listener for tests and management code."""+ return self._server++ def enable_route(self, path_prefix: str) -> None:+ """Enable a route for routing."""+ normalized = path_prefix.rstrip("/")+ self._enabled_routes.add(normalized)+ self._log(f"Route '{normalized}' enabled")++ def disable_route(self, path_prefix: str) -> None:+ """Disable a route (requests will return 404)."""+ normalized = path_prefix.rstrip("/")+ self._enabled_routes.discard(normalized)+ self._log(f"Route '{normalized}' disabled")++ def is_route_enabled(self, path_prefix: str) -> bool:+ """Check if a route is enabled."""+ 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:+ self._log_callback(message)++ def _get_ssl_context(self, route: ProxyRoute) -> ssl.SSLContext:+ """Get or create SSL context for a route."""+ if route.path_prefix not in self._ssl_contexts:+ ctx = ssl.create_default_context()+ if route.skip_cert_verify:+ ctx.check_hostname = False+ ctx.verify_mode = ssl.CERT_NONE+ self._ssl_contexts[route.path_prefix] = ctx+ return self._ssl_contexts[route.path_prefix]++ def _match_route(self, path: str) -> ProxyRoute | None:+ """Match request path to the longest matching enabled route.++ Longest-prefix matching ensures specific routes take precedence+ over generic routes that could incorrectly match due to string+ prefix collision (e.g., '/api' matching '/api-v2/chat').++ With single-level path_prefix requirement:+ - '/api' matches '/api/chat' and '/api-v2/chat' (string prefix)+ - '/api-v2' matches '/api-v2/chat' (longer, more specific)+ - Request '/api-v2/chat' -> matches '/api-v2' (len=6) not '/api' (len=4)++ Args:+ path: Request path to match++ Returns:+ ProxyRoute with longest matching prefix, or None if no match+ """+ path = path.rstrip("/")+ best_match = None+ best_length = 0++ for route in self.config.routes:+ if path.startswith(route.path_prefix) and self.is_route_enabled(route.path_prefix):+ prefix_len = len(route.path_prefix)+ if prefix_len > best_length:+ best_match = route+ best_length = prefix_len++ return best_match++ def match_route(self, path: str) -> ProxyRoute | None:+ """Public wrapper for route matching."""+ return self._match_route(path)++ @staticmethod+ def _rewrite_path(path: str, route: ProxyRoute) -> str:+ """Rewrite request path by stripping prefix and adding target base path."""+ path = path.rstrip("/")+ stripped = path[len(route.path_prefix):]++ if not stripped:+ return route.target_base_path or "/"++ if route.target_base_path:+ return route.target_base_path + stripped+ return stripped++ def rewrite_path(self, path: str, route: ProxyRoute) -> str:+ """Public wrapper for request path rewriting."""+ return self._rewrite_path(path, route)++ def _inject_api_key(self, headers: bytes, route: ProxyRoute) -> bytes:+ """Inject API key into headers (wildcard replacement).++ Replaces ANY existing key with configured key:+ - Authorization: Bearer <any-key> -> Authorization: Bearer {route.api_key}+ - X-Api-Key: <any-key> -> X-Api-Key: {route.api_key}+ """+ if not route.api_key:+ return headers++ headers_str = headers.decode(errors="replace")++ patterns = [+ (r'Authorization:\s*Bearer\s+\S+', f'Authorization: Bearer {route.api_key}'),+ (r'X-Api-Key:\s*\S+', f'X-Api-Key: {route.api_key}'),+ ]++ result = headers_str+ injected = False++ for pattern, replacement in patterns:+ new_result = re.sub(pattern, replacement, result)+ if new_result != result:+ injected = True+ result = new_result++ if injected:+ self._log(f"Injected API key for route '{route.path_prefix}'")++ return result.encode()++ def inject_api_key(self, headers: bytes, route: ProxyRoute) -> bytes:+ """Public wrapper for API key header injection."""+ return self._inject_api_key(headers, route)++ async def _handle_connection(+ self,+ client_reader: asyncio.StreamReader,+ client_writer: asyncio.StreamWriter,+ ) -> None:+ conn_id = id(client_writer)+ peer_addr = client_writer.get_extra_info('peername')+ self._log(f"[{conn_id}] New HTTP connection from {peer_addr or 'unknown'}")++ try:+ request_data = await client_reader.read(65536)+ if not request_data:+ self._log(f"[{conn_id}] No data received")+ return++ request_text = request_data.decode(errors="replace")+ headers_end = request_text.find("\r\n\r\n")+ if headers_end == -1:+ self._log(f"[{conn_id}] Invalid HTTP request: no headers end")+ error_response = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n"+ client_writer.write(error_response.encode())+ await client_writer.drain()+ return++ headers_raw = request_text[:headers_end]+ body = request_text[headers_end + 4:]+ header_lines = headers_raw.split("\r\n")++ request_line = header_lines[0]+ parts = request_line.split(" ")+ if len(parts) < 3:+ self._log(f"[{conn_id}] Invalid HTTP request line")+ error_response = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n"+ client_writer.write(error_response.encode())+ await client_writer.drain()+ return++ method = parts[0]+ original_path = parts[1]+ version = parts[2]++ route = self._match_route(original_path)+ if route is None:+ self._log(f"[{conn_id}] No route matched for path: {original_path}")+ error_response = (+ "HTTP/1.1 404 Not Found\r\n"+ "Content-Type: text/plain\r\n"+ "Content-Length: 20\r\n"+ "\r\n"+ f"No route matched: {original_path}"+ )+ client_writer.write(error_response.encode())+ await client_writer.drain()+ return++ self._log(f"[{conn_id}] Route '{route.path_prefix}' matched for {method} {original_path}")++ new_path = self._rewrite_path(original_path, route)+ new_request_line = f"{method} {new_path} {version}"++ new_headers = []+ for i, line in enumerate(header_lines):+ if i == 0:+ new_headers.append(new_request_line)+ elif line.lower().startswith("host:"):+ new_headers.append(f"Host: {route.target_host}")+ else:+ new_headers.append(line)++ new_headers_raw = "\r\n".join(new_headers)+ new_headers_bytes = self._inject_api_key(new_headers_raw.encode(), route)++ new_request = new_headers_bytes + "\r\n\r\n".encode() + body.encode(errors="replace")++ ssl_ctx = self._get_ssl_context(route) if route.use_tls else None++ target_reader, target_writer = await asyncio.open_connection(+ route.target_host,+ route.target_port,+ ssl=ssl_ctx,+ )+ self._log(f"[{conn_id}] Connected to {route.target_host}:{route.target_port}")++ target_writer.write(new_request)+ await target_writer.drain()++ request_bytes = len(new_request)+ response_bytes = 0++ async def forward_remaining_request():+ nonlocal request_bytes+ try:+ while True:+ data = await client_reader.read(8192)+ if not data:+ break+ target_writer.write(data)+ await target_writer.drain()+ request_bytes += len(data)+ except Exception as exc:+ logger.debug("[%s] Request forwarding stopped: %s", conn_id, exc)++ async def forward_response():+ nonlocal response_bytes+ try:+ while True:+ data = await target_reader.read(8192)+ if not data:+ break+ client_writer.write(data)+ await client_writer.drain()+ response_bytes += len(data)+ except Exception as exc:+ logger.debug("[%s] Response forwarding stopped: %s", conn_id, exc)++ request_task = asyncio.create_task(forward_remaining_request())+ response_task = asyncio.create_task(forward_response())++ _, pending = await asyncio.wait(+ [request_task, response_task],+ return_when=asyncio.ALL_COMPLETED,+ )++ for task in pending:+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ logger.debug("[%s] Cancelled pending proxy task", conn_id)+ self._log(f"[{conn_id}] Complete: {request_bytes} bytes sent, {response_bytes} bytes received")++ except Exception as e:+ self._log(f"[{conn_id}] Error: {e}")+ try:+ error_response = (+ "HTTP/1.1 502 Bad Gateway\r\n"+ "Content-Type: text/plain\r\n"+ f"Content-Length: {len(str(e))}\r\n"+ "\r\n"+ f"{e}"+ )+ client_writer.write(error_response.encode())+ await client_writer.drain()+ except Exception as exc:+ logger.debug("[%s] Failed to send error response: %s", conn_id, exc)+ finally:+ self._log(f"[{conn_id}] Connection closed")+ try:+ client_writer.close()+ await client_writer.wait_closed()+ except Exception as exc:+ logger.debug("[%s] Failed to close client writer: %s", conn_id, exc)++ async def start(self) -> None:+ if self._running:+ return++ self._running = True++ self._server = await asyncio.start_server(+ self._handle_connection,+ self.config.listen_host,+ self.config.listen_port,+ )++ addr = self._server.sockets[0].getsockname()+ routes_info = ", ".join(f"{r.path_prefix}->{r.target_endpoint}" for r in self.config.routes)+ self._log(f"HTTP proxy listening on {addr[0]}:{addr[1]} with routes: {routes_info}")++ async def serve():+ while self._running:+ await asyncio.sleep(1)++ self._serve_task = asyncio.create_task(serve())++ async def stop(self) -> None:+ if not self._running:+ return++ self._running = False++ if self._server:+ self._server.close()+ await self._server.wait_closed()++ if self._serve_task:+ self._serve_task.cancel()+ try:+ await self._serve_task+ except asyncio.CancelledError:+ logger.debug("Proxy serve task cancelled")+ 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.pynew file mode 100644index 0000000000..d4b9ffa379--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/proxy/inference_privacy_proxy_manager.py@@ -0,0 +1,500 @@+"""Manager for hot-pluggable inference privacy proxies.++Provides CRUD operations for proxy configurations and runtime management:+- create/start/stop/update/delete proxies+- list proxies and their status+- get logs for debugging+"""++from __future__ import annotations++import asyncio+import logging+import subprocess+from dataclasses import dataclass, field+from datetime import datetime, timezone+from enum import Enum+from typing import Any++from jiuwenbox.logging_config import configure_logging+from jiuwenbox.proxy.inference_privacy_proxy import InferencePrivacyProxyConfig, ProxyRoute, InferencePrivacyProxy++configure_logging()+logger = logging.getLogger(__name__)+++class ProxyState(str, Enum):+ STOPPED = "stopped"+ STARTING = "starting"+ RUNNING = "running"+ STOPPING = "stopping"+ ERROR = "error"+++@dataclass+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+ log_lines: list[str] = field(default_factory=list)+ route_states: dict[str, ProxyState] = field(default_factory=dict)+ _log_max_lines: int = 1000++ def add_log(self, line: str) -> None:+ timestamp = datetime.now(timezone.utc).isoformat()+ self.log_lines.append(f"[{timestamp}] {line}")+ if len(self.log_lines) > self._log_max_lines:+ self.log_lines = self.log_lines[-self._log_max_lines:]++ def get_logs(self) -> str:+ return "\n".join(self.log_lines)++ def get_route_state(self, route_name: str) -> ProxyState:+ return self.route_states.get(route_name, ProxyState.STOPPED)++ def set_route_state(self, route_name: str, state: ProxyState) -> None:+ self.route_states[route_name] = state++ def get_enabled_route_count(self) -> int:+ return sum(1 for s in self.route_states.values() if s == ProxyState.RUNNING)+++class InferencePrivacyProxyManager:+ def __init__(self) -> None:+ self._proxies: dict[str, ProxyInstance] = {}+ self._lock = asyncio.Lock()++ @staticmethod+ def _route_name(route: ProxyRoute) -> str:+ return route.path_prefix.lstrip("/").replace("/", "-") or "default"++ def reset(self) -> None:+ """Clear all tracked proxies. Intended for isolated tests."""+ self._proxies.clear()++ def get_global_instance(self) -> ProxyInstance | None:+ """Return the shared proxy instance for test inspection."""+ return self._proxies.get("default")++ async def list_proxies(self) -> list[dict[str, Any]]:+ """List all proxy configurations and their state.++ Returns one entry per route with independent state.+ """+ async with self._lock:+ global_instance = self._proxies.get("default")+ if global_instance is None:+ return []++ result = []+ for route in global_instance.config.routes:+ proxy_name = self._route_name(route)+ route_state = global_instance.get_route_state(proxy_name)+ result.append({+ "name": proxy_name,+ "state": route_state.value,+ "listen_host": global_instance.config.listen_host,+ "listen_port": global_instance.config.listen_port,+ "route": {+ "path_prefix": route.path_prefix,+ "target_endpoint": route.target_endpoint,+ "api_key": route.api_key[:10] + "..." if len(route.api_key) > 10 else route.api_key,+ },+ "created_at": global_instance.created_at.isoformat() if global_instance.created_at else None,+ "started_at": global_instance.started_at.isoformat() if global_instance.started_at else None,+ "error_message": global_instance.error_message,+ })+ return result++ async def get_proxy(self, name: str) -> dict[str, Any] | None:+ """Get a specific proxy's details (route info with its own state)."""+ async with self._lock:+ global_instance = self._proxies.get("default")+ if global_instance is None:+ return None++ for route in global_instance.config.routes:+ proxy_name = self._route_name(route)+ if proxy_name == name:+ route_state = global_instance.get_route_state(proxy_name)+ return {+ "name": name,+ "state": route_state.value,+ "listen_host": global_instance.config.listen_host,+ "listen_port": global_instance.config.listen_port,+ "route": {+ "path_prefix": route.path_prefix,+ "target_endpoint": route.target_endpoint,+ "api_key": route.api_key,+ "skip_cert_verify": route.skip_cert_verify,+ "target_host": route.target_host,+ "target_port": route.target_port,+ "use_tls": route.use_tls,+ },+ "created_at": global_instance.created_at.isoformat() if global_instance.created_at else None,+ "started_at": global_instance.started_at.isoformat() if global_instance.started_at else None,+ "error_message": global_instance.error_message,+ }+ return None++ async def create_proxy(self, name: str, config: InferencePrivacyProxyConfig) -> dict[str, Any]:+ """Create or add a route to the global proxy."""+ async with self._lock:+ global_instance = self._proxies.get("default")++ if global_instance is not None and global_instance.config.listen_port == 0:+ raise ValueError(+ "Cannot create route: proxy disabled (listen_port=0). "+ "Set listen_port > 0 in policy YAML first."+ )++ if global_instance is None and config.listen_port == 0:+ raise ValueError(+ "Cannot create route: listen_port=0 (disabled). "+ "Set listen_port > 0 in policy YAML first."+ )++ if global_instance is None:+ global_instance = ProxyInstance(config=config)+ global_instance.state = ProxyState.STOPPED+ for route in config.routes:+ route_name = self._route_name(route)+ global_instance.set_route_state(route_name, ProxyState.STOPPED)+ global_instance.add_log(f"Global proxy created with {len(config.routes)} routes")+ self._proxies["default"] = global_instance+ logger.info("Created global proxy: listen_port=%d, routes=%d", config.listen_port, len(config.routes))+ else:+ for route in config.routes:+ route_name = self._route_name(route)+ existing_names = [+ self._route_name(existing_route)+ for existing_route in global_instance.config.routes+ ]+ if route_name in existing_names:+ raise ValueError(f"Proxy '{name}' already exists")+ global_instance.config.routes.append(route)+ global_instance.set_route_state(route_name, ProxyState.STOPPED)+ global_instance.add_log(f"Added route: {route.path_prefix} -> {route.target_endpoint}")+ logger.info("Added route '%s' to global proxy", route_name)++ route = config.routes[0] if config.routes else None+ proxy_name = self._route_name(route) if route else name+ route_state = global_instance.get_route_state(proxy_name)++ return {+ "name": proxy_name,+ "state": route_state.value,+ "created_at": global_instance.created_at.isoformat(),+ }++ async def start_proxy(self, name: str) -> dict[str, Any]:+ """Start a specific route (enable it for routing)."""+ async with self._lock:+ global_instance = self._proxies.get("default")+ if global_instance is None:+ raise ValueError(f"Proxy '{name}' not found")++ route = None+ for r in global_instance.config.routes:+ if self._route_name(r) == name:+ route = r+ break++ if route is None:+ raise ValueError(f"Proxy '{name}' not found")++ if global_instance.config.listen_port == 0:+ warning_msg = (+ "Cannot start proxy: listen_port=0 (disabled). "+ "Proxy is disabled by default. "+ "Set listen_port > 0 in policy YAML to enable."+ )+ global_instance.add_log(warning_msg)+ logger.warning(warning_msg)+ return {+ "name": name,+ "state": global_instance.get_route_state(name).value,+ "started_at": global_instance.started_at.isoformat() if global_instance.started_at else None,+ "error_message": None,+ }++ current_state = global_instance.get_route_state(name)+ if current_state == ProxyState.RUNNING:+ global_instance.add_log(f"Route '{name}' already running")+ return {+ "name": name,+ "state": current_state.value,+ "started_at": global_instance.started_at.isoformat() if global_instance.started_at else None,+ }++ global_instance.set_route_state(name, ProxyState.STARTING)+ global_instance.add_log(f"Starting route '{name}'...")++ try:+ if global_instance.proxy is None or not global_instance.proxy.is_running:+ proxy = InferencePrivacyProxy(global_instance.config, log_callback=global_instance.add_log)+ await proxy.start()+ global_instance.proxy = proxy+ global_instance.state = ProxyState.RUNNING+ global_instance.started_at = datetime.now(timezone.utc)+ global_instance.add_log(f"Global proxy started on port {global_instance.config.listen_port}")+ logger.info("Global proxy started on port %d", global_instance.config.listen_port)++ global_instance.proxy.enable_route(route.path_prefix)+ global_instance.set_route_state(name, ProxyState.RUNNING)+ global_instance.add_log(f"Route '{name}' enabled for routing")+ logger.info("Route '%s' enabled", name)+ except Exception as e:+ global_instance.set_route_state(name, ProxyState.ERROR)+ global_instance.error_message = str(e)+ global_instance.add_log(f"Failed to start route '{name}': {e}")+ logger.error("Failed to start route '%s': %s", name, e)+ raise++ return {+ "name": name,+ "state": global_instance.get_route_state(name).value,+ "started_at": global_instance.started_at.isoformat() if global_instance.started_at else None,+ "error_message": global_instance.error_message,+ }++ async def stop_proxy(self, name: str) -> dict[str, Any]:+ """Stop a specific route (disable it, stop global proxy if all routes disabled)."""+ async with self._lock:+ global_instance = self._proxies.get("default")+ if global_instance is None:+ raise ValueError(f"Proxy '{name}' not found")++ route = None+ for r in global_instance.config.routes:+ if self._route_name(r) == name:+ route = r+ break++ if route is None:+ raise ValueError(f"Proxy '{name}' not found")++ current_state = global_instance.get_route_state(name)+ if current_state == ProxyState.STOPPED:+ global_instance.add_log(f"Route '{name}' already stopped")+ return {+ "name": name,+ "state": current_state.value,+ }++ global_instance.set_route_state(name, ProxyState.STOPPING)+ global_instance.add_log(f"Stopping route '{name}'...")++ try:+ if global_instance.proxy:+ global_instance.proxy.disable_route(route.path_prefix)+ global_instance.add_log(f"Route '{name}' disabled")++ global_instance.set_route_state(name, ProxyState.STOPPED)++ enabled_count = global_instance.get_enabled_route_count()+ if enabled_count == 0 and global_instance.proxy:+ global_instance.add_log("All routes disabled, stopping global proxy...")+ await global_instance.proxy.stop()+ global_instance.proxy = None+ global_instance.state = ProxyState.STOPPED+ global_instance.started_at = None+ global_instance.add_log("Global proxy stopped")+ logger.info("Global proxy stopped (no enabled routes)")++ logger.info("Route '%s' stopped", name)+ except Exception as e:+ global_instance.set_route_state(name, ProxyState.ERROR)+ global_instance.error_message = str(e)+ global_instance.add_log(f"Failed to stop route '{name}': {e}")+ logger.error("Failed to stop route '%s': %s", name, e)+ raise++ return {+ "name": name,+ "state": global_instance.get_route_state(name).value,+ "error_message": global_instance.error_message,+ }++ async def update_proxy(self, name: str, config: InferencePrivacyProxyConfig) -> dict[str, Any]:+ """Update a route in the global proxy (keeps path_prefix, updates target/api_key)."""+ async with self._lock:+ global_instance = self._proxies.get("default")+ if global_instance is None:+ raise ValueError(f"Proxy '{name}' not found")++ route_idx = None+ old_path_prefix = None+ for i, r in enumerate(global_instance.config.routes):+ derived_name = r.path_prefix.lstrip("/").replace("/", "-") or "default"+ if derived_name == name:+ route_idx = i+ old_path_prefix = r.path_prefix+ break++ if route_idx is None:+ raise ValueError(f"Proxy '{name}' not found")++ was_running = global_instance.state == ProxyState.RUNNING++ if was_running:+ global_instance.state = ProxyState.STOPPING+ global_instance.add_log("Stopping proxy for route update...")+ try:+ if global_instance.proxy:+ await global_instance.proxy.stop()+ global_instance.proxy = None+ except Exception as e:+ global_instance.add_log(f"Failed to stop for update: {e}")++ if config.routes:+ new_route = config.routes[0]+ updated_route = ProxyRoute(+ path_prefix=old_path_prefix,+ target_endpoint=new_route.target_endpoint,+ api_key=new_route.api_key,+ skip_cert_verify=new_route.skip_cert_verify,+ )+ global_instance.config.routes[route_idx] = updated_route+ global_instance.add_log(f"Route updated: {old_path_prefix} -> {updated_route.target_endpoint}")++ if was_running:+ global_instance.state = ProxyState.STARTING+ global_instance.add_log("Restarting proxy with updated route...")+ try:+ proxy = InferencePrivacyProxy(global_instance.config, log_callback=global_instance.add_log)+ await proxy.start()+ global_instance.proxy = proxy+ global_instance.state = ProxyState.RUNNING+ global_instance.started_at = datetime.now(timezone.utc)+ global_instance.add_log("Proxy restarted successfully")+ except Exception as e:+ global_instance.state = ProxyState.ERROR+ global_instance.error_message = str(e)+ global_instance.add_log(f"Failed to restart: {e}")++ logger.info("Updated route '%s'", name)++ return {+ "name": name,+ "state": global_instance.state.value,+ "started_at": global_instance.started_at.isoformat() if global_instance.started_at else None,+ "error_message": global_instance.error_message,+ }++ async def delete_proxy(self, name: str) -> dict[str, Any]:+ """Delete a route from the global proxy."""+ async with self._lock:+ global_instance = self._proxies.get("default")+ if global_instance is None:+ raise ValueError(f"Proxy '{name}' not found")++ route_idx = None+ for i, r in enumerate(global_instance.config.routes):+ if self._route_name(r) == name:+ route_idx = i+ break++ if route_idx is None:+ raise ValueError(f"Proxy '{name}' not found")++ global_instance.config.routes.pop(route_idx)+ global_instance.add_log(f"Deleted route: {name}")+ logger.info("Deleted route '%s'", name)++ if len(global_instance.config.routes) == 0:+ if global_instance.state == ProxyState.RUNNING:+ try:+ if global_instance.proxy:+ await global_instance.proxy.stop()+ except Exception as e:+ logger.warning("Error stopping proxy during delete: %s", e)+ del self._proxies["default"]+ logger.info("Deleted global proxy (no routes remaining)")++ return {"name": name, "deleted": True}++ async def get_proxy_logs(self, name: str, lines: int | None = None) -> dict[str, Any]:+ """Get logs for the global proxy."""+ async with self._lock:+ global_instance = self._proxies.get("default")+ if global_instance is None:+ raise ValueError(f"Proxy '{name}' not found")++ route_exists = any(+ self._route_name(r) == name+ for r in global_instance.config.routes+ )+ if not route_exists:+ raise ValueError(f"Proxy '{name}' not found")++ logs = global_instance.get_logs()+ if lines:+ log_list = logs.split("\n")+ logs = "\n".join(log_list[-lines:])++ return {+ "name": name,+ "logs": logs,+ }++ async def load_from_policy(self, proxies_config: Any) -> None:+ """Load global proxy from policy configuration at startup.++ Creates ONE global proxy with ALL routes sharing the same listen_port.+ All routes are started (enabled) by default.+ """+ if not proxies_config or proxies_config.listen_port <= 0:+ return++ routes = [+ ProxyRoute(+ path_prefix=route_data.path_prefix,+ target_endpoint=route_data.target_endpoint,+ api_key=route_data.api_key,+ skip_cert_verify=route_data.skip_cert_verify,+ )+ for route_data in proxies_config.routes+ ]++ if not routes:+ logger.info("No routes configured")+ return++ config = InferencePrivacyProxyConfig(+ listen_port=proxies_config.listen_port,+ listen_host=proxies_config.listen_host or "127.0.0.1",+ routes=routes,+ )++ try:+ await self.create_proxy("default", config)++ route_names = [r.path_prefix.lstrip("/").replace("/", "-") or "default" for r in routes]+ for route_name in route_names:+ await self.start_proxy(route_name)++ logger.info(+ "Started global proxy on %s:%d with %d routes: %s",+ config.listen_host,+ proxies_config.listen_port,+ len(routes),+ ", ".join(f"{r.path_prefix}->{r.target_endpoint}" for r in routes),+ )+ except Exception as e:+ logger.error("Failed to load global proxy: %s", e)+++_proxy_manager: InferencePrivacyProxyManager | None = None+++def get_proxy_manager() -> InferencePrivacyProxyManager:+ """Get the global proxy manager instance."""+ global _proxy_manager+ if _proxy_manager is None:+ _proxy_manager = InferencePrivacyProxyManager()+ return _proxy_managerdiff --git a/jiuwenbox/src/jiuwenbox/proxy/ipp_launcher.py b/jiuwenbox/src/jiuwenbox/proxy/ipp_launcher.pynew file mode 100644index 0000000000..1ee2e2fe14--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/proxy/ipp_launcher.py@@ -0,0 +1,79 @@+"""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.pyindex 2071a35a77..4deeef8a27 100644--- a/jiuwenbox/src/jiuwenbox/server/app.py+++ b/jiuwenbox/src/jiuwenbox/server/app.py@@ -3,47 +3,146 @@from __future__ import annotations+import asyncioimport logging+import os+from concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse+from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox import __version__from jiuwenbox.server.sandbox_manager import (SandboxManager,SandboxNotFoundError,SandboxStateError,)+from jiuwenbox.server.proxy_manager import ProxyManagerfrom jiuwenbox.server.policy_engine import PolicyValidationError-logging.basicConfig(level=logging.INFO)+configure_logging()logger = logging.getLogger(__name__)-_manager: SandboxManager | None = None+_sandbox_manager: SandboxManager | None = None+_proxy_manager: ProxyManager | None = None++# 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, ...)``+# and therefore consumes one slot in the asyncio default ThreadPoolExecutor.+# Python's default size is ``min(32, os.cpu_count() + 4)`` which is *eight*+# threads on a 4-CPU box; running 100 concurrent sandboxes blows past that+# cap immediately, leaving 90+ requests sitting in the executor queue while+# the event loop sees the same coroutines as "still awaiting". That extra+# queueing time eventually trips upstream HTTP read timeouts and can be+# misread by clients as the server hanging up. Raise the pool to something+# proportional to the sandbox fan-out, with an env override for operators.+_IO_THREADS_ENV = "JIUWENBOX_IO_THREADS"+_DEFAULT_IO_THREADS_FLOOR = 64++# 100 sandboxes × (1 listener + 3 stdio + several transient client/daemon+# sockets) easily exceeds the typical Docker default of ``RLIMIT_NOFILE=1024``.+# Hitting it surfaces as a mix of ``EMFILE`` errors during ``accept``,+# ``connect``, or ``open`` - none of which fail loudly but all of which+# manifest to the test client as random "Server disconnected" responses.+# Raise the soft limit to the hard limit at startup.+++def _resolve_io_thread_count() -> int:+ raw = os.environ.get(_IO_THREADS_ENV)+ if raw:+ try:+ value = int(raw)+ except ValueError:+ logger.warning(+ "Ignoring non-integer %s=%r; falling back to default",+ _IO_THREADS_ENV,+ raw,+ )+ else:+ if value >= 1:+ return value+ logger.warning(+ "Ignoring %s=%r (must be >= 1); falling back to default",+ _IO_THREADS_ENV,+ raw,+ )+ cpu_count = os.cpu_count() or 1+ return max(_DEFAULT_IO_THREADS_FLOOR, cpu_count * 16)+++def _raise_open_file_limit() -> None:+ try:+ import resource+ except ImportError:+ return+ try:+ soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)+ except (OSError, ValueError) as exc:+ logger.warning("Could not query RLIMIT_NOFILE: %s", exc)+ return+ if soft >= hard:+ logger.info("RLIMIT_NOFILE already at %s (hard=%s)", soft, hard)+ return+ try:+ resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard))+ except (OSError, ValueError) as exc:+ logger.warning("Could not raise RLIMIT_NOFILE from %s to %s: %s", soft, hard, exc)+ return+ logger.info("Raised RLIMIT_NOFILE soft limit from %s to %s", soft, hard)+++def _configure_loop_default_executor() -> None:+ workers = _resolve_io_thread_count()+ loop = asyncio.get_running_loop()+ executor = ThreadPoolExecutor(+ max_workers=workers,+ thread_name_prefix="jiuwenbox-io",+ )+ loop.set_default_executor(executor)+ logger.info(+ "asyncio default executor configured with %d threads (override via %s)",+ workers,+ _IO_THREADS_ENV,+ )+++def get_sandbox_manager() -> SandboxManager:+ global _sandbox_manager+ if _sandbox_manager is None:+ _sandbox_manager = SandboxManager()+ return _sandbox_manager-def get_manager() -> SandboxManager:- """Get the global SandboxManager instance."""- global _manager- if _manager is None:- _manager = SandboxManager()- return _manager+def get_proxy_manager() -> ProxyManager:+ global _proxy_manager+ if _proxy_manager is None:+ _proxy_manager = ProxyManager()+ return _proxy_manager@asynccontextmanagerasync def lifespan(_application: FastAPI):- """Application lifespan: initialize manager on startup."""- global _manager- _manager = SandboxManager()+ global _sandbox_manager, _proxy_manager+ # 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+ # any other sandbox state, so doing them first means later startup work+ # already benefits from the larger executor.+ _raise_open_file_limit()+ _configure_loop_default_executor()+ _sandbox_manager = SandboxManager()+ _proxy_manager = ProxyManager()logger.info("box-server started (version %s)", __version__)+ await _proxy_manager.start()yield+ await _proxy_manager.stop()logger.info("box-server shutting down")def create_app() -> FastAPI:- """Create and configure the FastAPI application."""application = FastAPI(title="jiuwenbox",description="Agent sandbox management API",@@ -59,7 +158,6 @@ def create_app() -> FastAPI:allow_headers=["*"],)- # Exception handlers@application.exception_handler(SandboxNotFoundError)async def not_found_handler(request: Request, exc: SandboxNotFoundError):return JSONResponse(status_code=404, content={"error": str(exc)})@@ -72,19 +170,45 @@ def create_app() -> FastAPI:async def policy_validation_error_handler(request: Request, exc: PolicyValidationError):return JSONResponse(status_code=400, content={"error": str(exc)})- # Register routes+ @application.exception_handler(Exception)+ async def unhandled_exception_handler(request: Request, exc: Exception):+ # Without this catch-all, an unexpected error inside a route handler+ # (e.g. ``OSError`` with EMFILE/ENOMEM under heavy fan-out, or any+ # other unanticipated exception) escapes uvicorn's ASGI cycle and+ # the connection is dropped without a response. Clients then see+ # ``RemoteProtocolError: Server disconnected without sending a+ # response`` and have no way to distinguish a real crash from a+ # transient overload. Returning a structured 500 lets the test+ # harness's retry logic kick in and surfaces a debuggable trace+ # in the server log.+ logger.exception(+ "Unhandled exception in %s %s: %s",+ request.method,+ request.url.path,+ exc,+ )+ return JSONResponse(+ status_code=500,+ content={+ "error": "internal_server_error",+ "detail": str(exc) or exc.__class__.__name__,+ },+ )+from jiuwenbox.server.routes.sandbox import router as sandbox_routerfrom jiuwenbox.server.routes.policy import router as policy_router+ from jiuwenbox.server.routes.proxy import router as proxy_routerapplication.include_router(sandbox_router, prefix="/api/v1")application.include_router(policy_router, prefix="/api/v1")+ application.include_router(proxy_router, prefix="/api/v1")@application.get("/health")async def health():from jiuwenbox.models.common import HealthResponsefrom jiuwenbox.supervisor.landlock import detect_landlock_abi- mgr = get_manager()+ mgr = get_sandbox_manager()sandboxes = await mgr.list_sandboxes()active = sum(1 for s in sandboxes if s.phase.value == "ready")@@ -98,3 +222,4 @@ def create_app() -> FastAPI:app = create_app()+get_manager = get_sandbox_managerdiff --git a/jiuwenbox/src/jiuwenbox/server/audit_logger.py b/jiuwenbox/src/jiuwenbox/server/audit_logger.pyindex d164c4ee8a..d9f3fa36cb 100644--- a/jiuwenbox/src/jiuwenbox/server/audit_logger.py+++ b/jiuwenbox/src/jiuwenbox/server/audit_logger.py@@ -1,35 +1,76 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Structured audit logging in JSONL format.-Each sandbox gets its own log file under ~/.jiuwenbox/logs/.+Each sandbox gets its own log file under ~/.jiuwenbox/logs/. Writes are routed+through a dedicated single-thread executor so disk I/O does not stall the+asyncio event loop on hot paths such as ``exec_in_sandbox``."""from __future__ import annotationsimport jsonimport logging+import threading+from concurrent.futures import ThreadPoolExecutorfrom pathlib import Path+from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.common import AuditEvent, AuditEventType+from jiuwenbox.server.workspace import JIUWENBOX_HOME-logging.basicConfig(level=logging.INFO)+configure_logging()logger = logging.getLogger(__name__)+def _write_jsonl_line(log_file: Path, line: str) -> None:+ """Append ``line`` (already serialized JSON) to ``log_file``.++ POSIX guarantees writes <= ``PIPE_BUF`` (typically 4 KiB) to ``O_APPEND``+ files are atomic, so we can interleave appends from multiple threads+ without corrupting individual JSONL records.+ """+ with open(log_file, "a", encoding="utf-8") as f:+ f.write(line + "\n")++class AuditLogger:"""Append-only JSONL audit logger, one file per sandbox."""def __init__(self, log_dir: Path | None = None) -> None:- self.log_dir = log_dir or Path.home() / ".jiuwenbox" / "logs"+ self.log_dir = log_dir or JIUWENBOX_HOME / "logs"self.log_dir.mkdir(parents=True, exist_ok=True)+ # A single worker keeps writes ordered without forcing the event loop+ # to wait on disk I/O. ``thread_name_prefix`` aids in debugging.+ self._executor = ThreadPoolExecutor(+ max_workers=1,+ thread_name_prefix="jiuwenbox-audit",+ )+ self._lock = threading.Lock()- def log_event(self, event: AuditEvent) -> None:+ def _serialize_event(self, event: AuditEvent) -> tuple[Path, str]:log_file = self.log_dir / f"{event.sandbox_id}.log"line = json.dumps(event.model_dump(mode="json"), ensure_ascii=False)- with open(log_file, "a") as f:- f.write(line + "\n")+ return log_file, line++ def log_event(self, event: AuditEvent) -> None:+ """Schedule a non-blocking append of ``event`` to its sandbox log.++ The serialization happens synchronously on the caller's thread (it is+ cheap for the small audit payloads jiuwenbox produces) but the file+ write is dispatched to a dedicated background thread so callers in+ the asyncio event loop are not blocked on disk I/O.+ """+ log_file, line = self._serialize_event(event)+ with self._lock:+ self._executor.submit(_write_jsonl_line, log_file, line)logger.debug("Audit: %s %s", event.event_type.value, event.sandbox_id)+ def log_event_sync(self, event: AuditEvent) -> None:+ """Synchronous append used by tests and shutdown paths."""+ log_file, line = self._serialize_event(event)+ _write_jsonl_line(log_file, line)+ logger.debug("Audit (sync): %s %s", event.event_type.value, event.sandbox_id)+def log(self,event_type: AuditEventType,@@ -44,8 +85,17 @@ class AuditLogger:)self.log_event(event)+ def flush(self, timeout: float | None = None) -> None:+ """Wait for queued audit writes to drain, primarily for tests."""+ with self._lock:+ executor = self._executor+ # Use an empty submit() and wait so any prior writes complete.+ future = executor.submit(lambda: None)+ future.result(timeout=timeout)+def read_logs(self, sandbox_id: str) -> list[AuditEvent]:"""Read all audit events for a sandbox."""+ self.flush()log_file = self.log_dir / f"{sandbox_id}.log"if not log_file.exists():return []@@ -57,6 +107,7 @@ class AuditLogger:def read_logs_raw(self, sandbox_id: str) -> str:"""Read raw log text for a sandbox."""+ self.flush()log_file = self.log_dir / f"{sandbox_id}.log"if not log_file.exists():return ""@@ -64,5 +115,6 @@ class AuditLogger:def delete_logs(self, sandbox_id: str) -> None:"""Delete logs for a sandbox."""+ self.flush()log_file = self.log_dir / f"{sandbox_id}.log"log_file.unlink(missing_ok=True)diff --git a/jiuwenbox/src/jiuwenbox/server/policy_engine.py b/jiuwenbox/src/jiuwenbox/server/policy_engine.pyindex 5072b3e81a..2fb49b0262 100644--- a/jiuwenbox/src/jiuwenbox/server/policy_engine.py+++ b/jiuwenbox/src/jiuwenbox/server/policy_engine.py@@ -9,9 +9,11 @@ from pathlib import Path, PurePosixPathimport yaml+from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.policy import NetworkRulePolicy, SecurityPolicy+from jiuwenbox.server.workspace import SANDBOX_WORKSPACE, JIUWENBOX_HOME-logging.basicConfig(level=logging.INFO)+configure_logging()logger = logging.getLogger(__name__)@@ -26,16 +28,78 @@ class PolicyValidationError(Exception):class PolicyEngine:"""Validates, resolves, and persists static security policies."""+ # In-sandbox paths reserved by jiuwenbox itself. These are mounted by+ # the runtime under bubblewrap to host the trusted launcher and daemon+ # scripts (see ``jiuwenbox/supervisor/daemon_ipc.py``). Allowing user+ # policy to reference any path under these subtrees would either+ # collide with the runtime's own bind mounts (e.g. a user+ # ``bind_mount`` whose ``sandbox_path`` is ``/jiuwenbox`` would+ # shadow the launcher script and prevent the sandbox from starting)+ # or punch them into the Landlock allowlist (``landlock.py`` adds+ # every read_only / read_write / bind_mount / device target to the+ # Landlock ruleset), which would let user code read the launcher and+ # daemon scripts the runtime is supposed to keep opaque. The set is+ # tiny on purpose - a single dedicated namespace - so users have no+ # legitimate reason to ever name it.+ _RESERVED_SANDBOX_PATHS: tuple[str, ...] = ("/jiuwenbox",)+def __init__(self, policies_dir: Path | None = None) -> None:- self.policies_dir = policies_dir or Path.home() / ".jiuwenbox" / "policies"+ self.policies_dir = policies_dir or JIUWENBOX_HOME / "policies"self.policies_dir.mkdir(parents=True, exist_ok=True)@staticmethod- def _is_sandbox_internal_path(path: str, sandbox_workspace: str) -> bool:+ def _is_sandbox_internal_path(path: str, workspace_root: str) -> bool:normalized = PurePosixPath(path)- workspace = PurePosixPath(sandbox_workspace)+ workspace = PurePosixPath(workspace_root)return normalized == workspace or normalized.is_relative_to(workspace)+ @staticmethod+ def _is_jiuwenbox_path(path: str) -> bool:+ normalized = PurePosixPath(path)+ jiuwenbox_root = PurePosixPath(str(JIUWENBOX_HOME))+ return normalized == jiuwenbox_root or normalized.is_relative_to(jiuwenbox_root)++ @classmethod+ def _is_reserved_workspace_path(cls, path: str, workspace_root: str) -> bool:+ return (+ cls._is_sandbox_internal_path(path, workspace_root)+ or cls._is_jiuwenbox_path(path)+ )++ @classmethod+ def _is_reserved_sandbox_path(cls, path: str) -> bool:+ """Return True iff ``path`` falls inside any reserved sandbox subtree.++ Used for paths that are interpreted *inside* the sandbox - i.e.+ ``read_only`` / ``read_write`` entries, ``directories`` /+ ``files`` paths, and the ``sandbox_path`` half of ``bind_mounts``+ / ``device`` entries. Host-side paths (``host_path``) are+ unaffected, since they live in the operator's filesystem and+ cannot collide with the in-sandbox launcher/daemon mounts.+ """+ if not path:+ return False+ normalized = PurePosixPath(path)+ for reserved in cls._RESERVED_SANDBOX_PATHS:+ reserved_path = PurePosixPath(reserved)+ if normalized == reserved_path or normalized.is_relative_to(reserved_path):+ return True+ return False++ @staticmethod+ def _reserved_workspace_error(path: str) -> PolicyValidationError:+ return PolicyValidationError(+ f"Policy cannot directly reference '{path}'; this path is reserved "+ "for server-managed backing storage"+ )++ @staticmethod+ def _reserved_sandbox_error(path: str) -> PolicyValidationError:+ return PolicyValidationError(+ f"Policy cannot reference '{path}'; this path is reserved by "+ "jiuwenbox for the in-sandbox launcher and daemon scripts"+ )+@staticmethoddef _is_absolute_sandbox_path(path: str) -> bool:return PurePosixPath(path).is_absolute()@@ -46,6 +110,12 @@ class PolicyEngine:return directoryreturn getattr(directory, "path")+ @staticmethod+ def _file_path(file: object) -> str:+ if isinstance(file, str):+ return file+ return getattr(file, "path")+@staticmethoddef _denies_without_allow_rules(rule: NetworkRulePolicy) -> bool:return rule.default == "deny" and not any([@@ -61,12 +131,18 @@ class PolicyEngine:if not policy.name:raise PolicyValidationError("Policy name is required")+ workspace_root = str(SANDBOX_WORKSPACE)directory_paths = [self._directory_path(directory)for directory in policy.filesystem_policy.directories]+ file_paths = [+ self._file_path(file)+ for file in policy.filesystem_policy.files+ ]for path in [*directory_paths,+ *file_paths,*policy.filesystem_policy.read_only,*policy.filesystem_policy.read_write,]:@@ -74,11 +150,15 @@ class PolicyEngine:raise PolicyValidationError("Filesystem policy paths must be absolute sandbox paths")- if self._is_sandbox_internal_path(path, policy.sandbox_workspace):+ if self._is_reserved_workspace_path(path, workspace_root):+ raise self._reserved_workspace_error(path)+ if self._is_reserved_sandbox_path(path):+ raise self._reserved_sandbox_error(path)++ for path in file_paths:+ if path in directory_paths:raise PolicyValidationError(- f"Policy cannot directly reference '{policy.sandbox_workspace}' "- "or its child paths; this path is reserved for server-managed "- "backing storage"+ f"Filesystem file path '{path}' conflicts with a declared directory path")for mount in policy.filesystem_policy.bind_mounts:@@ -90,16 +170,23 @@ class PolicyEngine:"Filesystem bind mount paths must be absolute paths")if (- self._is_sandbox_internal_path(mount.host_path, policy.sandbox_workspace)- or self._is_sandbox_internal_path(+ self._is_reserved_workspace_path(mount.host_path, workspace_root)+ or self._is_reserved_workspace_path(mount.sandbox_path,- policy.sandbox_workspace,+ workspace_root,)):+ reserved_path = (+ mount.host_path+ if self._is_reserved_workspace_path(mount.host_path, workspace_root)+ else mount.sandbox_path+ )+ raise self._reserved_workspace_error(reserved_path)+ if self._is_reserved_sandbox_path(mount.sandbox_path):+ raise self._reserved_sandbox_error(mount.sandbox_path)+ if mount.sandbox_path in file_paths:raise PolicyValidationError(- f"Policy cannot directly reference '{policy.sandbox_workspace}' "- "or its child paths; this path is reserved for server-managed "- "backing storage"+ f"Filesystem file path '{mount.sandbox_path}' conflicts with a bind mount")for device in policy.filesystem_policy.device:@@ -111,16 +198,23 @@ class PolicyEngine:"Filesystem device mount paths must be absolute paths")if (- self._is_sandbox_internal_path(device.host_path, policy.sandbox_workspace)- or self._is_sandbox_internal_path(+ self._is_reserved_workspace_path(device.host_path, workspace_root)+ or self._is_reserved_workspace_path(device.sandbox_path,- policy.sandbox_workspace,+ workspace_root,)):+ reserved_path = (+ device.host_path+ if self._is_reserved_workspace_path(device.host_path, workspace_root)+ else device.sandbox_path+ )+ raise self._reserved_workspace_error(reserved_path)+ if self._is_reserved_sandbox_path(device.sandbox_path):+ raise self._reserved_sandbox_error(device.sandbox_path)+ if device.sandbox_path in file_paths:raise PolicyValidationError(- f"Policy cannot directly reference '{policy.sandbox_workspace}' "- "or its child paths; this path is reserved for server-managed "- "backing storage"+ f"Filesystem file path '{device.sandbox_path}' conflicts with a device mount")if policy.network.mode.value == "isolated":diff --git a/jiuwenbox/src/jiuwenbox/server/policy_reader.py b/jiuwenbox/src/jiuwenbox/server/policy_reader.pynew file mode 100644index 0000000000..07711fc9c3--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/server/policy_reader.py@@ -0,0 +1,56 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Policy file reader for loading security policies from YAML files.++Shared by SandboxManager and ProxyManager to avoid duplicate policy loading logic.+"""++from __future__ import annotations++import logging+import os+from pathlib import Path++from jiuwenbox.logging_config import configure_logging+from jiuwenbox.models.policy import SecurityPolicy+from jiuwenbox.server.policy_engine import PolicyEngine++configure_logging()+logger = logging.getLogger(__name__)++JIUWENBOX_POLICY_PATH_ENV = "JIUWENBOX_POLICY_PATH"+++class PolicyReader:+ """Reads security policy from YAML files."""++ def __init__(+ self,+ policy_engine: PolicyEngine | None = None,+ policy_path: Path | None = None,+ ) -> None:+ self.policy_engine = policy_engine or PolicyEngine()+ self.policy_path = (+ Path(policy_path)+ if policy_path is not None+ else self._resolve_policy_path()+ )++ @staticmethod+ def _resolve_policy_path() -> Path:+ env_path = os.environ.get(JIUWENBOX_POLICY_PATH_ENV)+ if env_path:+ return Path(env_path).expanduser()+ return Path(__file__).resolve().parents[3] / "configs" / "default-policy.yaml"++ def load_policy(self) -> SecurityPolicy:+ if self.policy_path.exists():+ return self.policy_engine.load_policy_from_file(self.policy_path)++ logger.warning(+ "Default policy file not found at %s, falling back to SecurityPolicy defaults",+ self.policy_path,+ )+ return SecurityPolicy()++ def load_policy_from_file(self, path: Path) -> SecurityPolicy:+ return self.policy_engine.load_policy_from_file(path)diff --git a/jiuwenbox/src/jiuwenbox/server/proxy_manager.py b/jiuwenbox/src/jiuwenbox/server/proxy_manager.pynew file mode 100644index 0000000000..cf1d4f2eed--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/server/proxy_manager.py@@ -0,0 +1,74 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Proxy lifecycle manager.++Manages inference privacy proxies based on policy configuration.+Similar to SandboxManager but focused on proxy management.+"""++from __future__ import annotations++import logging+from pathlib import Path++from jiuwenbox.logging_config import configure_logging+from jiuwenbox.models.policy import SecurityPolicy+from jiuwenbox.proxy.inference_privacy_proxy_manager import get_proxy_manager+from jiuwenbox.server.policy_reader import PolicyReader++configure_logging()+logger = logging.getLogger(__name__)+++class ProxyManager:+ """Manages inference privacy proxies lifecycle."""++ def __init__(+ self,+ policy_reader: PolicyReader | None = None,+ policy_path: Path | None = None,+ ) -> None:+ self.policy_reader = policy_reader or PolicyReader(+ policy_path=policy_path+ )+ self.policy: SecurityPolicy | None = None++ def load_policy(self) -> SecurityPolicy:+ self.policy = self.policy_reader.load_policy()+ return self.policy++ async def start(self) -> None:+ if not self.policy:+ self.load_policy()++ proxy_config = self.policy.inference_privacy_proxies+ if not proxy_config or proxy_config.listen_port <= 0:+ logger.info("Proxy disabled (listen_port=0 or not configured)")+ return++ proxy_mgr = get_proxy_manager()+ await proxy_mgr.load_from_policy(proxy_config)+ logger.info(+ "Started inference privacy proxies from policy on port %d",+ proxy_config.listen_port,+ )++ async def stop(self) -> None:+ proxy_mgr = get_proxy_manager()+ proxies = await proxy_mgr.list_proxies()+ for proxy_info in proxies:+ try:+ await proxy_mgr.stop_proxy(proxy_info["name"])+ 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_managerdiff --git a/jiuwenbox/src/jiuwenbox/server/routes/policy.py b/jiuwenbox/src/jiuwenbox/server/routes/policy.pyindex 4d71da6a9f..9b5008c9ea 100644--- a/jiuwenbox/src/jiuwenbox/server/routes/policy.py+++ b/jiuwenbox/src/jiuwenbox/server/routes/policy.py@@ -8,9 +8,11 @@ import loggingfrom fastapi import APIRouterfrom fastapi.responses import JSONResponse+from jiuwenbox.logging_config import configure_logging+router = APIRouter(tags=["policies"])-logging.basicConfig(level=logging.INFO)+configure_logging()logger = logging.getLogger(__name__)diff --git a/jiuwenbox/src/jiuwenbox/server/routes/proxy.py b/jiuwenbox/src/jiuwenbox/server/routes/proxy.pynew file mode 100644index 0000000000..3915f591ca--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/server/routes/proxy.py@@ -0,0 +1,207 @@+"""Inference privacy proxy API routes.++Provides hot-pluggable proxy management:+- Create/start/stop/update/delete proxies+- Each proxy has a single route (path_prefix -> target_endpoint)+- List proxies and get logs++Validation is handled by Pydantic models in models/policy.py.+Connectivity is not checked at config time - proxy returns 502 if target unreachable at request time.+"""++from __future__ import annotations++import logging+from fastapi import APIRouter, HTTPException, Query+from fastapi.responses import PlainTextResponse+from pydantic import BaseModel, Field, ValidationError++from jiuwenbox.logging_config import configure_logging+from jiuwenbox.models.policy import ProxyRouteEntry+from jiuwenbox.proxy.inference_privacy_proxy import InferencePrivacyProxyConfig, ProxyRoute+from jiuwenbox.proxy.inference_privacy_proxy_manager import get_proxy_manager++router = APIRouter(tags=["proxies"])+configure_logging()+logger = logging.getLogger(__name__)+++def _contains_crlf_or_null(value: str) -> bool:+ """Check if string contains CRLF or null byte."""+ return "\r" in value or "\n" in value or "\x00" in value+++def _validate_proxy_name(name: str) -> str:+ """Validate proxy_name URL parameter.++ Only allows: alphanumeric, dash (-), underscore (_)+ Prevents log injection and error message injection.+ """+ if not name or not name.strip():+ raise HTTPException(status_code=400, detail="proxy_name cannot be empty")++ if _contains_crlf_or_null(name):+ raise HTTPException(status_code=400, detail="proxy_name contains invalid characters")++ stripped = name.strip()+ for c in stripped:+ if not (c.isalnum() or c in ("-", "_")):+ raise HTTPException(+ status_code=400,+ detail="proxy_name must contain only alphanumeric, dash, or underscore"+ )++ return stripped+++class RouteRequest(BaseModel):+ path_prefix: str = Field(..., description="Path prefix to match (e.g., /openai)")+ target_endpoint: str = Field(..., description="Target endpoint URL (e.g., https://api.openai.com)")+ api_key: str = Field(default="", description="API key to inject")+ skip_cert_verify: bool = Field(default=False, description="Skip TLS cert verification")+++def _mgr():+ return get_proxy_manager()++[email protected]("/proxies", status_code=201)+async def create_proxy(route: RouteRequest):+ """Create inference privacy proxy with a single route."""++ try:+ validated_entry = ProxyRouteEntry(+ path_prefix=route.path_prefix,+ target_endpoint=route.target_endpoint,+ api_key=route.api_key,+ skip_cert_verify=route.skip_cert_verify,+ )+ except ValidationError as e:+ raise HTTPException(status_code=400, detail=str(e)) from e++ proxy_name = validated_entry.path_prefix.lstrip("/").replace("/", "-") or "default"++ existing = await _mgr().get_proxy(proxy_name)+ if existing is not None:+ raise HTTPException(status_code=400, detail=f"Route '{validated_entry.path_prefix}' already exists")++ proxy_route = ProxyRoute(+ path_prefix=validated_entry.path_prefix,+ target_endpoint=validated_entry.target_endpoint,+ api_key=validated_entry.api_key,+ skip_cert_verify=validated_entry.skip_cert_verify,+ )+ config = InferencePrivacyProxyConfig(routes=[proxy_route])++ try:+ result = await _mgr().create_proxy(proxy_name, config)+ return result+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e)) from e++[email protected]("/proxies")+async def list_proxies():+ """List all inference privacy proxies."""+ return await _mgr().list_proxies()++[email protected]("/proxies/{proxy_name}")+async def get_proxy(proxy_name: str):+ """Get a specific proxy's details."""+ validated_name = _validate_proxy_name(proxy_name)+ result = await _mgr().get_proxy(validated_name)+ if result is None:+ raise HTTPException(status_code=404, detail=f"Proxy '{validated_name}' not found")+ return result++[email protected]("/proxies/{proxy_name}")+async def delete_proxy(proxy_name: str):+ """Delete a proxy."""+ validated_name = _validate_proxy_name(proxy_name)+ try:+ result = await _mgr().delete_proxy(validated_name)+ return result+ except ValueError as e:+ raise HTTPException(status_code=404, detail=str(e)) from e++[email protected]("/proxies/{proxy_name}/start")+async def start_proxy(proxy_name: str):+ """Start a proxy."""+ validated_name = _validate_proxy_name(proxy_name)+ try:+ result = await _mgr().start_proxy(validated_name)+ return result+ except ValueError as e:+ raise HTTPException(status_code=404, detail=str(e)) from e+ except Exception as e:+ raise HTTPException(status_code=500, detail=str(e)) from e++[email protected]("/proxies/{proxy_name}/stop")+async def stop_proxy(proxy_name: str):+ """Stop a proxy."""+ validated_name = _validate_proxy_name(proxy_name)+ try:+ result = await _mgr().stop_proxy(validated_name)+ return result+ except ValueError as e:+ raise HTTPException(status_code=404, detail=str(e)) from e+ except Exception as e:+ raise HTTPException(status_code=500, detail=str(e)) from e++[email protected]("/proxies/{proxy_name}")+async def update_proxy(proxy_name: str, route: RouteRequest):+ """Update proxy route."""+ validated_name = _validate_proxy_name(proxy_name)++ try:+ validated_entry = ProxyRouteEntry(+ path_prefix=route.path_prefix,+ target_endpoint=route.target_endpoint,+ api_key=route.api_key,+ skip_cert_verify=route.skip_cert_verify,+ )+ except ValidationError as e:+ raise HTTPException(status_code=400, detail=str(e)) from e++ existing = await _mgr().get_proxy(validated_name)+ if existing is None:+ raise HTTPException(status_code=404, detail=f"Proxy '{validated_name}' not found")++ proxy_route = ProxyRoute(+ path_prefix=validated_entry.path_prefix,+ target_endpoint=validated_entry.target_endpoint,+ api_key=validated_entry.api_key,+ skip_cert_verify=validated_entry.skip_cert_verify,+ )+ config = InferencePrivacyProxyConfig(+ listen_port=existing["listen_port"],+ listen_host=existing.get("listen_host", "127.0.0.1"),+ routes=[proxy_route],+ )++ try:+ result = await _mgr().update_proxy(validated_name, config)+ return result+ except ValueError as e:+ raise HTTPException(status_code=404, detail=str(e)) from e++[email protected]("/proxies/{proxy_name}/logs")+async def get_proxy_logs(+ proxy_name: str,+ lines: int | None = Query(None, description="Number of log lines to return")+):+ """Get logs for a proxy."""+ validated_name = _validate_proxy_name(proxy_name)+ if lines is not None and (lines < 0 or lines > 10000):+ raise HTTPException(status_code=400, detail="lines must be between 0 and 10000")+ try:+ result = await _mgr().get_proxy_logs(validated_name, lines)+ return PlainTextResponse(result["logs"])+ except ValueError as e:+ raise HTTPException(status_code=404, detail=str(e)) from ediff --git a/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py b/jiuwenbox/src/jiuwenbox/server/routes/sandbox.pyindex 2f1d6571fd..c084889af0 100644--- a/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py+++ b/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py@@ -10,11 +10,18 @@ from fastapi import APIRouter, File, Query, UploadFilefrom fastapi.responses import JSONResponse, PlainTextResponse, Responsefrom pydantic import BaseModel, Field-from jiuwenbox.models.sandbox import ExecResult, PolicyMode, SandboxRef, SandboxSpec+from jiuwenbox.logging_config import configure_logging+from jiuwenbox.models.sandbox import (+ BackgroundExecResult,+ ExecResult,+ PolicyMode,+ SandboxRef,+ SandboxSpec,+)from jiuwenbox.server.sandbox_manager import SandboxExecRequest, SandboxListRequestrouter = APIRouter(tags=["sandboxes"])-logging.basicConfig(level=logging.INFO)+configure_logging()logger = logging.getLogger(__name__)@@ -55,7 +62,6 @@ async def create_sandbox(request: CreateSandboxRequest):)return await _mgr().create_sandbox(spec,- command=request.command,policy_data=request.policy,policy_mode=request.policy_mode,)@@ -106,6 +112,21 @@ async def exec_in_sandbox(sandbox_id: str, request: ExecRequest):)[email protected]("/sandboxes/{sandbox_id}/exec_background", response_model=BackgroundExecResult)+async def exec_background_in_sandbox(sandbox_id: str, request: ExecRequest):+ stdin_data = request.stdin.encode() if request.stdin else None+ return await _mgr().exec_background_in_sandbox(+ sandbox_id=sandbox_id,+ request=SandboxExecRequest(+ command=list(request.command),+ workdir=request.workdir,+ env=request.env,+ stdin_data=stdin_data,+ timeout=request.timeout_seconds,+ ),+ )++@router.get("/sandboxes/{sandbox_id}/logs")async def get_logs(sandbox_id: str):logs = await _mgr().get_logs(sandbox_id)diff --git a/jiuwenbox/src/jiuwenbox/server/runtime/base.py b/jiuwenbox/src/jiuwenbox/server/runtime/base.pyindex 36dc335b8f..b044a98a36 100644--- a/jiuwenbox/src/jiuwenbox/server/runtime/base.py+++ b/jiuwenbox/src/jiuwenbox/server/runtime/base.py@@ -6,8 +6,9 @@ from __future__ import annotationsimport abcfrom dataclasses import dataclassfrom pathlib import Path+from typing import Any-from jiuwenbox.models.sandbox import ExecResult+from jiuwenbox.models.sandbox import BackgroundExecResult, ExecResult@dataclass(frozen=True)@@ -19,6 +20,25 @@ class RuntimeExecRequest:timeout: float | None = None+@dataclass(frozen=True)+class RuntimeFileOpResult:+ """Result of an in-sandbox file op routed via the daemon fast path.++ ``ok`` indicates whether the op completed successfully. When ``ok`` is+ ``False`` callers can branch on ``error`` (a stable string code such+ as ``"not_found"``, ``"is_directory"``, ``"is_symlink"``, etc.) and+ optionally on ``errno`` to translate into HTTP semantics. ``content``+ and ``items`` are populated by the read/list paths respectively.+ """++ ok: bool+ error: str | None = None+ errno: int | None = None+ detail: str | None = None+ content: bytes | None = None+ items: list[dict[str, Any]] | None = None++class RuntimeAdapter(abc.ABC):"""Interface for sandbox runtime backends (process, docker, etc.)."""@@ -27,7 +47,6 @@ class RuntimeAdapter(abc.ABC):self,sandbox_id: str,policy_path: Path,- command: list[str],workdir: str | None = None,env: dict[str, str] | None = None,) -> int:@@ -53,7 +72,67 @@ class RuntimeAdapter(abc.ABC):"""Execute a one-shot command inside a running sandbox."""...+ @abc.abstractmethod+ async def exec_background(+ self,+ sandbox_id: str,+ request: RuntimeExecRequest,+ ) -> BackgroundExecResult:+ """Start a background command inside a running sandbox."""+ ...+@abc.abstractmethodasync def cleanup(self, sandbox_id: str) -> None:"""Release all resources for a sandbox."""...++ async def write_file(+ self,+ sandbox_id: str,+ sandbox_path: str,+ content: bytes,+ *,+ mkdir_parents: bool = True,+ mode: int | None = None,+ ) -> RuntimeFileOpResult:+ """Write ``content`` to ``sandbox_path`` inside the sandbox.++ Default implementation indicates the runtime does not provide a+ fast path and the caller should fall back to ``exec``. Subclasses+ with a daemon IPC channel (``ProcessRuntime``) override this to+ avoid the fork+exec roundtrip.+ """+ return RuntimeFileOpResult(+ ok=False,+ error="unsupported",+ detail="runtime adapter does not implement write_file fast path",+ )++ async def read_file(+ self,+ sandbox_id: str,+ sandbox_path: str,+ ) -> RuntimeFileOpResult:+ """Read ``sandbox_path`` from the sandbox via the daemon fast path."""+ return RuntimeFileOpResult(+ ok=False,+ error="unsupported",+ detail="runtime adapter does not implement read_file fast path",+ )++ async def list_dir(+ self,+ sandbox_id: str,+ sandbox_path: str,+ *,+ recursive: bool = False,+ max_depth: int | None = None,+ include_files: bool = True,+ include_dirs: bool = True,+ ) -> RuntimeFileOpResult:+ """List directory entries under ``sandbox_path``."""+ return RuntimeFileOpResult(+ ok=False,+ error="unsupported",+ detail="runtime adapter does not implement list_dir fast path",+ )diff --git a/jiuwenbox/src/jiuwenbox/server/runtime/process.py b/jiuwenbox/src/jiuwenbox/server/runtime/process.pyindex 9c52ad562c..655b4f1c3c 100644--- a/jiuwenbox/src/jiuwenbox/server/runtime/process.py+++ b/jiuwenbox/src/jiuwenbox/server/runtime/process.py@@ -1,13 +1,27 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Process-based runtime adapter (bare-metal mode).-Spawns box-supervisor as a subprocess for each sandbox.+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."""from __future__ import annotationsimport asyncioimport base64+import dataclasses+import errnoimport grpimport jsonimport logging@@ -15,21 +29,300 @@ import osimport pwdimport shutilimport signal+import socketimport subprocess-import sysimport tempfilefrom pathlib import Path+from typing import Anyimport yaml+from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.policy import NetworkMode, SecurityPolicy-from jiuwenbox.models.sandbox import ExecResult-from jiuwenbox.server.runtime.base import RuntimeAdapter, RuntimeExecRequest+from jiuwenbox.models.sandbox import BackgroundExecResult, ExecResult+from jiuwenbox.server.runtime.base import (+ RuntimeAdapter,+ RuntimeExecRequest,+ RuntimeFileOpResult,+)+from jiuwenbox.server.workspace import SANDBOX_WORKSPACE, JIUWENBOX_HOMEfrom jiuwenbox.supervisor import network as network_module-from jiuwenbox.supervisor.sandbox_daemon import SANDBOX_DAEMON_COMMAND+from jiuwenbox.supervisor.bwrap import BwrapConfig+from jiuwenbox.supervisor.daemon_ipc import (+ LISTENER_FD_ENV,+ MAX_FILE_BYTES,+ MAX_HEADER_BYTES,+ REQUEST_TYPE_EXEC,+ REQUEST_TYPE_LIST_DIR,+ REQUEST_TYPE_READ_FILE,+ REQUEST_TYPE_SHUTDOWN,+ REQUEST_TYPE_WRITE_FILE,+ SANDBOX_CONTROL_SOCKET_NAME,+ SANDBOX_DAEMON_COMMAND,+ SANDBOX_DAEMON_SANDBOX_PATH,+ SANDBOX_LAUNCHER_PATH,+ SANDBOX_RESERVED_DIR,+ encode_request,+ recv_frame,+ send_frame,+)+from jiuwenbox.supervisor.landlock import encode_landlock_payload+from jiuwenbox.supervisor.seccomp import build_seccomp_filter-logging.basicConfig(level=logging.INFO)+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"+DEFAULT_SERVER_PROTECT_PORTS = (8321,)++_SUPERVISOR_DIR = Path(__file__).resolve().parents[2] / "supervisor"+LANDLOCK_LAUNCHER_SOURCE = _SUPERVISOR_DIR / "landlock_launcher.py"+SANDBOX_DAEMON_SOURCE = _SUPERVISOR_DIR / "sandbox_daemon.py"+# Read the launcher and daemon source once at module load so we do not pay+# the I/O cost on every sandbox creation; bytes are immutable so sharing is+# safe across sandboxes.+_LANDLOCK_LAUNCHER_BYTES = LANDLOCK_LAUNCHER_SOURCE.read_bytes()+_SANDBOX_DAEMON_BYTES = SANDBOX_DAEMON_SOURCE.read_bytes()+PYTHON_EXECUTABLE = "python3"++# Per-sandbox control socket: box-server ``bind()``s a Unix socket on its+# own host filesystem inside a per-sandbox control directory, then passes+# the listener fd into bubblewrap via ``subprocess.Popen(pass_fds=...)``.+# Bubblewrap forks twice (monitor → intermediate → user command) but the+# user command path never closes arbitrary inherited fds, and Python's+# ``pass_fds`` clears CLOEXEC, so the listener fd survives all the way to+# the daemon. The daemon recovers the fd number from ``LISTENER_FD_ENV``+# and ``accept()``s on it. Because the socket file never appears under any+# sandbox-visible path, user code spawned by the daemon cannot reach the+# listener (and the daemon's ``subprocess.Popen`` calls run with+# ``close_fds=True`` so the inherited listener fd is not exposed to+# children either).+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+# 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.+DAEMON_FILE_OP_TIMEOUT_SECONDS = 30.0++# OS-level errors that mean the daemon is actually gone or its control+# socket is permanently broken. When we see one of these, ``_daemon_socket_ready``+# is flipped to ``False`` so subsequent calls take the slow legacy+# ``bash`` / ``python3`` fallback path instead of repeatedly re-trying a+# dead socket.+FATAL_DAEMON_ERRNOS: frozenset[int] = frozenset(+ (+ errno.ECONNREFUSED, # nothing listening → daemon crashed+ errno.ECONNRESET, # peer (daemon) closed mid-stream+ errno.ENOENT, # listener path vanished+ errno.EPIPE, # writing to a closed pipe/socket+ errno.ETIMEDOUT, # daemon never responded → hung+ errno.EBADF, # our fd was already closed → dead session+ ),+)++# OS-level errors that are *recoverable* - they describe a transient+# resource shortage on this specific call (host out of fds, fork queue+# full, signal interrupt, ...) but say nothing about whether the daemon+# itself is healthy. Reporting them to the caller as ``transport_failure``+# without flipping ``_daemon_socket_ready`` lets the next request try the+# fast path again. The earlier version of this fix lumped them into the+# fatal set, which caused a single ``EAGAIN`` / ``EBUSY`` / ``EINTR`` to+# permanently demote a sandbox to the bash+base64 path - sandbox-count=8+# regressed from ~217 ms back to ~919 ms because every later call paid the+# python cold-start tax.+RECOVERABLE_DAEMON_ERRNOS: frozenset[int] = frozenset(+ (+ errno.EAGAIN,+ errno.EMFILE,+ errno.ENFILE,+ errno.ENOMEM,+ errno.ENOBUFS,+ errno.EHOSTUNREACH,+ errno.ENETUNREACH,+ errno.EBUSY,+ errno.EINTR,+ # Some platforms expose ``EWOULDBLOCK`` as a distinct value from+ # ``EAGAIN``; on Linux they are equal so the frozenset deduplicates.+ errno.EWOULDBLOCK,+ ),+)++# 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++[email protected](frozen=True)+class _DaemonExecCall:+ """Inputs to one IPC ``exec`` request.++ Bundled into a single value object so the per-call worker thread+ only takes one positional argument (G.FNM.03 keeps the signature at+ or below five arguments).+ """++ socket_path: Path+ command: list[str]+ env: dict[str, str] | None+ workdir: str | None+ stdin_bytes: bytes | None+ timeout: float | None++[email protected](frozen=True)+class _DaemonListDirCall:+ """Inputs to one IPC ``list_dir`` request (see ``_DaemonExecCall``)."""++ socket_path: Path+ sandbox_path: str+ recursive: bool+ max_depth: int | None+ include_files: bool+ include_dirs: bool+++# Admission control for ``exec``. ``exec`` is the one operation that+# spawns a fresh ``python3`` (or other) child inside the sandbox, which+# is overwhelmingly CPU-bound (interpreter cold start + imports + user+# script). Allowing more concurrent ``exec`` calls than the box has+# usable CPUs causes classic throughput collapse: TLB churn, L3-cache+# eviction across competing python interpreters, and per-fork mmap_sem+# contention in the kernel. Empirically each unit of oversubscription+# beyond 1.0 multiplies per-call latency by roughly 2-3x because of+# this collapse, *not* by the linear factor a fully scheduler-friendly+# workload would predict.+#+# The ``JIUWENBOX_EXEC_CONCURRENCY`` env var lets operators tune the+# limit (e.g. set it lower than CPU count to leave headroom for the+# server, or set it to a very large number to disable throttling). When+# unset we use the cgroup-aware ``os.process_cpu_count()`` if available+# (Python 3.13+) and fall back to ``os.cpu_count()`` so containers with+# CPU quotas get the right value automatically.+EXEC_CONCURRENCY_ENV = "JIUWENBOX_EXEC_CONCURRENCY"+++def _read_cgroup_cpu_quota() -> int | None:+ """Return the cgroup-imposed CPU count, or ``None`` if uncapped.++ On Python 3.11 (which the box-server image ships with) ``os.cpu_count()``+ on Linux returns the *host* CPU count, NOT the container's+ ``--cpus``/cgroup quota. That means a 4-CPU container running on a+ 16-core host saw ``os.cpu_count() == 16``, which silently undid the+ exec admission semaphore: the limit became 16, all 8 sandboxes ran+ concurrently, throughput collapsed under 4x oversubscription, and+ sandbox-count=8 latency stayed pinned at ~900 ms instead of ~200 ms.+ Reading cgroup directly gives the actual scheduling budget.+ """+ # cgroup v2: ``/sys/fs/cgroup/cpu.max`` -> ``"<quota> <period>"`` or+ # ``"max <period>"`` if uncapped.+ try:+ with open("/sys/fs/cgroup/cpu.max", "r") as fh:+ raw = fh.read().strip()+ except OSError:+ raw = ""+ if raw:+ parts = raw.split()+ if len(parts) == 2 and parts[0] != "max":+ try:+ quota = int(parts[0])+ period = int(parts[1])+ except ValueError:+ quota = period = 0+ if quota > 0 and period > 0:+ cpus = max(1, round(quota / period))+ return cpus+ if parts and parts[0] == "max":+ return None+ # cgroup v1 fallback.+ try:+ with open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us", "r") as fh:+ quota = int(fh.read().strip())+ with open("/sys/fs/cgroup/cpu/cpu.cfs_period_us", "r") as fh:+ period = int(fh.read().strip())+ except (OSError, ValueError):+ return None+ if quota <= 0 or period <= 0:+ return None+ return max(1, round(quota / period))+++def _detect_default_exec_concurrency() -> int:+ """Detect how many parallel CPU-bound execs the host can actually run.++ Preference order (most to least authoritative for our purposes):+ 1. cgroup CPU quota - exactly matches Docker's ``--cpus``.+ 2. ``os.process_cpu_count()`` - Python 3.13+ cgroup-aware helper.+ 3. ``os.sched_getaffinity(0)`` - Linux affinity mask, useful when+ the user pinned us via ``taskset``.+ 4. ``os.cpu_count()`` - finally, the host's reported CPU count.+ """+ cgroup_cpus = _read_cgroup_cpu_quota()+ if cgroup_cpus is not None and cgroup_cpus >= 1:+ return cgroup_cpus++ process_cpu_count = getattr(os, "process_cpu_count", None)+ if callable(process_cpu_count):+ try:+ value = process_cpu_count()+ except (OSError, ValueError):+ value = None+ if value and value >= 1:+ return value++ sched_getaffinity = getattr(os, "sched_getaffinity", None)+ if callable(sched_getaffinity):+ try:+ mask = sched_getaffinity(0)+ except OSError:+ mask = None+ if mask:+ return len(mask)++ cpu_count = os.cpu_count()+ if cpu_count and cpu_count >= 1:+ return cpu_count+ return 1+++def _resolve_exec_concurrency() -> int:+ raw = os.environ.get(EXEC_CONCURRENCY_ENV)+ if raw:+ try:+ value = int(raw)+ except ValueError:+ logger.warning(+ "Ignoring non-integer %s=%r; falling back to detected CPU count",+ EXEC_CONCURRENCY_ENV,+ raw,+ )+ else:+ if value >= 1:+ return value+ logger.warning(+ "Ignoring %s=%r (must be >= 1); falling back to detected CPU count",+ EXEC_CONCURRENCY_ENV,+ raw,+ )+ return _detect_default_exec_concurrency()+++def _safe_close_fd(fd: int) -> None:+ try:+ os.close(fd)+ except OSError:+ logger.debug("Failed to close fd %d", fd, exc_info=True)+++def _summarize_command(command: list[str], max_length: int = 180) -> str:+ text = json.dumps(command, ensure_ascii=False)+ if len(text) <= max_length:+ return text+ return f"{text[:max_length]}... ({len(text)} chars)"class ProcessRuntime(RuntimeAdapter):@@ -38,11 +331,38 @@ class ProcessRuntime(RuntimeAdapter):def __init__(self) -> None:self._processes: dict[str, subprocess.Popen] = {}self._policy_paths: dict[str, Path] = {}+ self._runtime_policies: dict[str, SecurityPolicy] = {}+ self._policy_binds: dict[str, list[dict[str, str]]] = {}self._network_modes: dict[str, NetworkMode] = {}self._netns_names: dict[str, str] = {}self._directory_roots: dict[str, Path] = {}- self._log_dir = Path.home() / ".jiuwenbox" / "sandbox_logs"+ self._file_roots: dict[str, Path] = {}+ self._launcher_dirs: dict[str, Path] = {}+ self._control_dirs: dict[str, Path] = {}+ self._daemon_socket_ready: dict[str, bool] = {}+ self._seccomp_bpf: dict[str, bytes] = {}+ self._landlock_payloads: dict[str, str] = {}+ self._background_processes: dict[str, list[subprocess.Popen]] = {}+ self._host_firewall_refcounts: dict[tuple[int, int], int] = {}+ self._sandbox_host_firewall_rules: dict[str, list[tuple[int, int]]] = {}+ self._log_dir = JIUWENBOX_HOME / "sandbox_logs"self._log_dir.mkdir(parents=True, exist_ok=True)+ # Admission-control semaphore for ``exec``. Lazy-initialized in+ # ``_ensure_exec_semaphore`` because ``asyncio.Semaphore`` binds to+ # the running loop on first use, and ``ProcessRuntime`` is built+ # outside the asyncio loop in some startup paths (CLI, tests).+ self._exec_concurrency_limit: int = _resolve_exec_concurrency()+ self._exec_semaphore: asyncio.Semaphore | None = None+ logger.info(+ "ProcessRuntime exec concurrency limit = %d "+ "(override via %s; cgroup_cpus=%s, os.cpu_count=%s, "+ "sched_affinity=%s)",+ self._exec_concurrency_limit,+ EXEC_CONCURRENCY_ENV,+ _read_cgroup_cpu_quota(),+ os.cpu_count(),+ len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else None,+ )@staticmethoddef _load_policy(policy_path: Path) -> SecurityPolicy:@@ -50,13 +370,271 @@ class ProcessRuntime(RuntimeAdapter):data = yaml.safe_load(f)return SecurityPolicy.model_validate(data)+ def _ensure_launcher_dir(self, sandbox_id: str) -> Path:+ """Create a per-sandbox host directory holding the launcher scripts.++ The directory is reused across all ``exec`` calls for the sandbox so we+ do not pay the ``tempfile.TemporaryDirectory`` + file-write cost on the+ hot path. The directory is removed in :meth:`cleanup`.+ """+ existing = self._launcher_dirs.get(sandbox_id)+ if existing is not None and existing.exists():+ return existing++ sandbox_root = self._sandbox_root()+ sandbox_root.mkdir(parents=True, exist_ok=True)+ launcher_dir = Path(tempfile.mkdtemp(+ prefix=f"{sandbox_id}-launcher-",+ dir=sandbox_root,+ ))+ launcher_dst = launcher_dir / "landlock-launcher.py"+ daemon_dst = launcher_dir / "sandbox-daemon.py"+ launcher_dst.write_bytes(_LANDLOCK_LAUNCHER_BYTES)+ daemon_dst.write_bytes(_SANDBOX_DAEMON_BYTES)+ os.chmod(launcher_dst, 0o644)+ os.chmod(daemon_dst, 0o644)+ self._launcher_dirs[sandbox_id] = launcher_dir+ return launcher_dir++ def _ensure_control_dir(self, sandbox_id: str) -> Path:+ """Return the per-sandbox host directory holding the control socket.++ The directory is restricted to mode 0700 owned by the box-server+ process; the listener socket is created here, but the directory is+ **never** bind-mounted into the sandbox - box-server keeps exclusive+ filesystem access to the IPC endpoint.+ """+ existing = self._control_dirs.get(sandbox_id)+ if existing is not None and existing.exists():+ return existing++ sandbox_root = self._sandbox_root()+ sandbox_root.mkdir(parents=True, exist_ok=True)+ control_dir = Path(tempfile.mkdtemp(+ prefix=f"{sandbox_id}-control-",+ dir=sandbox_root,+ ))+ try:+ os.chmod(control_dir, 0o700)+ except OSError:+ logger.debug(+ "Failed to chmod control dir %s; relying on default mode",+ control_dir,+ exc_info=True,+ )+ self._control_dirs[sandbox_id] = control_dir+ return control_dir++ def _control_socket_host_path(self, sandbox_id: str) -> Path | None:+ control_dir = self._control_dirs.get(sandbox_id)+ if control_dir is None:+ return None+ return control_dir / SANDBOX_CONTROL_SOCKET_NAME++ def _create_daemon_listener(+ self,+ sandbox_id: str,+ policy: SecurityPolicy,+ ) -> socket.socket:+ """Create the per-sandbox host listener socket the daemon will adopt.++ The fd is later handed to bubblewrap via+ ``subprocess.Popen(pass_fds=[fd])``. Bubblewrap's user command+ path (PID 2 inside the new pid namespace) never closes arbitrary+ inherited fds, so the listener flows naturally through bwrap →+ launcher → daemon. We mark the fd non-CLOEXEC so it survives every+ ``execve`` along that chain.+ """+ control_dir = self._ensure_control_dir(sandbox_id)+ socket_path = control_dir / SANDBOX_CONTROL_SOCKET_NAME+ try:+ socket_path.unlink()+ except FileNotFoundError:+ pass++ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ try:+ listener.bind(str(socket_path))+ try:+ # ``0o600`` keeps the listener reachable only by the+ # box-server uid (and root); daemon connects come from+ # outside the sandbox so the sandbox uid does not need+ # access to this path.+ os.chmod(socket_path, 0o600)+ except OSError:+ logger.debug(+ "Failed to chmod listener socket %s; relying on umask",+ socket_path,+ exc_info=True,+ )+ # Restrict ownership tightly: the listener fd is what the daemon+ # uses, so file ownership only protects against in-host meddling.+ try:+ os.chown(socket_path, os.geteuid(), os.getegid())+ except OSError:+ pass+ listener.listen(64)+ # ``pass_fds`` already clears CLOEXEC on the listed fd before+ # exec'ing bwrap; calling ``set_inheritable`` makes the intent+ # explicit and survives even if the caller forgets to thread+ # the fd through ``pass_fds``.+ os.set_inheritable(listener.fileno(), True)+ except Exception:+ try:+ listener.close()+ except OSError:+ pass+ raise+ # Track per-sandbox so the policy-aware uid (used for chown of+ # other policy-managed paths) is consistent with what created the+ # socket; we do not actually need ``policy`` further here.+ _ = policy+ return listener++ def _ensure_seccomp_bpf(self, sandbox_id: str, policy: SecurityPolicy) -> bytes:+ bpf = self._seccomp_bpf.get(sandbox_id)+ if bpf is not None:+ return bpf+ bpf = build_seccomp_filter(policy.syscall)+ self._seccomp_bpf[sandbox_id] = bpf+ return bpf++ def _ensure_landlock_payload(self, sandbox_id: str, policy: SecurityPolicy) -> str:+ payload = self._landlock_payloads.get(sandbox_id)+ if payload is not None:+ return payload+ payload = encode_landlock_payload(policy)+ self._landlock_payloads[sandbox_id] = payload+ return payload+@staticmethod- def _build_supervisor_command(policy_path: Path, command: list[str]) -> list[str]:- return [- sys.executable, "-m", "jiuwenbox.supervisor.main",- str(policy_path),- *command,- ]+ 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+ re-assembled for every exec.+ """+ 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(bpf):+ offset += os.write(fd, bpf[offset:])+ os.lseek(fd, 0, os.SEEK_SET)+ except Exception:+ os.close(fd)+ raise+ return fd++ def _build_sandbox_bwrap_args(+ self,+ sandbox_id: str,+ policy: SecurityPolicy,+ command: list[str],+ *,+ is_daemon: bool,+ workdir: str | None,+ sandbox_env: dict[str, str] | None,+ netns_attached: bool,+ seccomp_fd: int | None,+ listener_fd: int | None = None,+ ) -> 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.+ """+ config = BwrapConfig.from_policy(policy, list(command))+ if sandbox_env:+ config.env.update(sandbox_env)+ if workdir:+ config.workdir = workdir++ # When the runtime has joined the bwrap process to a pre-configured+ # named netns via ``ip netns exec``, bwrap must not unshare it again+ # otherwise the carefully prepared firewall rules become invisible.+ if policy.network.mode == NetworkMode.ISOLATED and netns_attached:+ config.unshare_net = False++ for entry in self._policy_binds.get(sandbox_id, []):+ config.rw_binds.append((entry["host_path"], entry["sandbox_path"]))++ launcher_dir = self._launcher_dirs.get(sandbox_id)+ landlock_enabled = policy.landlock.compatibility != "disabled"++ if is_daemon and launcher_dir is not None:+ daemon_path = launcher_dir / "sandbox-daemon.py"+ config.ro_binds.append(+ (str(daemon_path), SANDBOX_DAEMON_SANDBOX_PATH),+ )++ if listener_fd is not None:+ # The listener fd is delivered into the sandbox purely through+ # natural fd inheritance: box-server creates the listener with+ # CLOEXEC cleared, hands the fd to bubblewrap via+ # ``subprocess.Popen(pass_fds=[fd])``, and bubblewrap's user+ # command path (PID 2 of the new pid namespace) never calls+ # ``fdwalk`` to close arbitrary inherited descriptors, so the fd+ # survives the bwrap → launcher → daemon ``execve`` chain. The+ # daemon adopts it via ``LISTENER_FD_ENV`` and never reaches+ # into the filesystem for the IPC endpoint, which means+ # Landlock can stay locked down.+ config.env[LISTENER_FD_ENV] = str(listener_fd)++ if launcher_dir is not None and landlock_enabled:+ launcher_path = launcher_dir / "landlock-launcher.py"+ # ``SANDBOX_RESERVED_DIR`` is created as a fresh tmpfs by bwrap+ # so we can ``--ro-bind`` the trusted scripts on top of it.+ # ``PolicyEngine`` rejects any user policy that references this+ # subtree, which prevents the launcher / daemon mount from+ # colliding with a user-supplied ``bind_mount`` or being+ # accidentally exposed to user code via the Landlock allowlist.+ config.add_dir_mount(SANDBOX_RESERVED_DIR)+ config.ro_binds.append((str(launcher_path), SANDBOX_LAUNCHER_PATH))+ payload = self._ensure_landlock_payload(sandbox_id, policy)+ # ``-S`` skips ``import site`` so the launcher does not pay for+ # building the global ``sys.path`` table; the launcher is+ # stdlib-only.+ #+ # For the per-sandbox daemon we use the launcher's+ # ``--daemon`` mode: the launcher pre-reads the daemon+ # script, applies Landlock, and then runs the daemon code in+ # the same Python process via ``compile``/``exec``. There is+ # no second ``execve`` after Landlock is locked in, which+ # means the daemon (and every ``fork+exec`` it does for IPC+ # requests) inherits Landlock without the daemon script's+ # on-disk path needing to remain reachable. That lets us+ # keep ``/run`` outside the Landlock allowlist so user code+ # cannot read the launcher / daemon scripts at runtime.+ #+ # For the generic (legacy) path used by ``exec_background``,+ # the launcher still runs in ``--`` mode: apply Landlock and+ # then ``execvp`` the requested user command.+ if is_daemon:+ config.command = [+ PYTHON_EXECUTABLE,+ "-S",+ SANDBOX_LAUNCHER_PATH,+ payload,+ "--daemon",+ SANDBOX_DAEMON_SANDBOX_PATH,+ ]+ else:+ config.command = [+ PYTHON_EXECUTABLE,+ "-S",+ SANDBOX_LAUNCHER_PATH,+ payload,+ "--",+ *config.command,+ ]++ config.seccomp_fd = seccomp_fd+ return config.to_args()def _get_netns_name(self, sandbox_id: str) -> str:return self._netns_names.setdefault(@@ -95,13 +673,19 @@ class ProcessRuntime(RuntimeAdapter):return getattr(directory, "path"), getattr(directory, "permissions", None)@staticmethod- def _host_directory_name(sandbox_path: str) -> str:+ def _file_spec(file: object) -> tuple[str, str | None]:+ if isinstance(file, str):+ return file, None+ return getattr(file, "path"), getattr(file, "permissions", None)++ @staticmethod+ def _host_entry_name(sandbox_path: str) -> str:encoded = base64.urlsafe_b64encode(sandbox_path.encode()).decode()return encoded.rstrip("=")@staticmethod- def _sandbox_root_for_policy(policy: SecurityPolicy) -> Path:- return Path(policy.sandbox_workspace).expanduser()+ def _sandbox_root() -> Path:+ return SANDBOX_WORKSPACE@staticmethoddef _resolve_backing_identity(policy: SecurityPolicy) -> tuple[int, int]:@@ -125,13 +709,143 @@ class ProcessRuntime(RuntimeAdapter):return uid, gid@staticmethod- def _apply_directory_ownership(path: Path, uid: int, gid: int) -> bool:+ def _resolve_process_uid(policy: SecurityPolicy) -> int:+ try:+ return pwd.getpwnam(policy.process.run_as_user).pw_uid+ except KeyError:+ return 65534++ @classmethod+ def _host_firewall_uids(cls, policy: SecurityPolicy) -> list[int]:+ uids = [cls._resolve_process_uid(policy)]+ current_uid = os.geteuid()+ if policy.namespace.user and current_uid == 0 and current_uid not in uids:+ uids.append(current_uid)+ return uids++ @staticmethod+ def _server_protect_ports() -> list[int]:+ raw_ports = os.environ.get(SERVER_PROTECT_PORTS_ENV)+ if raw_ports is None:+ return list(DEFAULT_SERVER_PROTECT_PORTS)+ if not raw_ports.strip():+ return []++ ports: list[int] = []+ for raw_port in raw_ports.split(","):+ raw_port = raw_port.strip()+ if not raw_port:+ continue+ try:+ port = int(raw_port)+ except ValueError:+ logger.warning(+ "Ignoring invalid %s entry: %s",+ SERVER_PROTECT_PORTS_ENV,+ raw_port,+ )+ continue+ if 1 <= port <= 65535 and port not in ports:+ ports.append(port)+ else:+ logger.warning(+ "Ignoring out-of-range %s entry: %s",+ SERVER_PROTECT_PORTS_ENV,+ raw_port,+ )+ return ports++ @staticmethod+ def _host_firewall_insert_args(uid: int, port: int) -> list[str]:+ return [+ "-I", "OUTPUT", "1",+ "-p", "tcp",+ "-m", "owner", "--uid-owner", str(uid),+ "--dport", str(port),+ "-j", "REJECT",+ ]++ @staticmethod+ def _host_firewall_delete_args(uid: int, port: int) -> list[str]:+ return [+ "-D", "OUTPUT",+ "-p", "tcp",+ "-m", "owner", "--uid-owner", str(uid),+ "--dport", str(port),+ "-j", "REJECT",+ ]++ def _install_host_firewall_rule(self, uid: int, port: int) -> tuple[int, int]:+ key = (uid, port)+ current_count = self._host_firewall_refcounts.get(key, 0)+ if current_count == 0:+ network_module.run_iptables(+ self._host_firewall_insert_args(uid, port),+ ip_version=4,+ )+ logger.info(+ "Blocked sandbox uid %d from connecting to box-server port %d",+ uid,+ port,+ )+ self._host_firewall_refcounts[key] = current_count + 1+ return key++ def _remove_host_firewall_rule(self, uid: int, port: int) -> None:+ key = (uid, port)+ current_count = self._host_firewall_refcounts.get(key, 0)+ if current_count <= 1:+ self._host_firewall_refcounts.pop(key, None)+ try:+ network_module.run_iptables(+ self._host_firewall_delete_args(uid, port),+ ip_version=4,+ )+ except Exception:+ logger.warning(+ "Failed to remove sandbox uid %d box-server port %d block rule",+ uid,+ port,+ exc_info=True,+ )+ return+ self._host_firewall_refcounts[key] = current_count - 1++ def _install_sandbox_host_firewall_rules(+ self,+ sandbox_id: str,+ policy: SecurityPolicy,+ ) -> None:+ if policy.network.mode != NetworkMode.HOST:+ return++ ports = self._server_protect_ports()+ if not ports:+ return++ installed: list[tuple[int, int]] = []+ try:+ for uid in self._host_firewall_uids(policy):+ for port in ports:+ installed.append(self._install_host_firewall_rule(uid, port))+ except Exception:+ for installed_uid, installed_port in reversed(installed):+ self._remove_host_firewall_rule(installed_uid, installed_port)+ raise+ self._sandbox_host_firewall_rules[sandbox_id] = installed++ def _remove_sandbox_host_firewall_rules(self, sandbox_id: str) -> None:+ for uid, port in reversed(self._sandbox_host_firewall_rules.pop(sandbox_id, [])):+ self._remove_host_firewall_rule(uid, port)++ @staticmethod+ def _apply_path_ownership(path: Path, uid: int, gid: int) -> bool:try:os.chown(path, uid, gid)return Trueexcept PermissionError:logger.warning(- "Failed to chown policy directory %s to %d:%d; keeping current owner",+ "Failed to chown policy path %s to %d:%d; keeping current owner",path,uid,gid,@@ -139,7 +853,7 @@ class ProcessRuntime(RuntimeAdapter):return False@staticmethod- def _apply_directory_permissions(path: Path, permissions: str | None) -> None:+ def _apply_path_permissions(path: Path, permissions: str | None) -> None:if permissions is None:returnos.chmod(path, int(permissions, 8))@@ -161,6 +875,13 @@ class ProcessRuntime(RuntimeAdapter):and not bool(mode & 0o002))+ @staticmethod+ def _needs_userns_owner_access_fallback(+ policy: SecurityPolicy,+ uid: int,+ ) -> bool:+ return os.geteuid() == 0 and policy.namespace.user and uid != 0+@staticmethoddef _apply_userns_write_fallback(path: Path) -> None:mode = path.stat().st_mode & 0o777@@ -168,9 +889,25 @@ class ProcessRuntime(RuntimeAdapter):if fallback_mode == mode:returnlogger.warning(- "Relaxing policy directory %s permissions from %s to %s because "+ "Relaxing policy path %s permissions from %s to %s because ""root-run user namespaces cannot map the sandbox uid onto the "- "bind-mounted backing directory owner",+ "bind-mounted backing path owner",+ path,+ oct(mode),+ oct(fallback_mode),+ )+ os.chmod(path, fallback_mode)++ @staticmethod+ def _apply_userns_file_access_fallback(path: Path) -> None:+ mode = path.stat().st_mode & 0o777+ owner_bits = (mode & 0o700) >> 6+ fallback_mode = mode | owner_bits+ if fallback_mode == mode:+ return+ logger.warning(+ "Relaxing policy file %s permissions from %s to %s because "+ "root-run user namespaces cannot preserve owner-only file access",path,oct(mode),oct(fallback_mode),@@ -189,7 +926,7 @@ class ProcessRuntime(RuntimeAdapter):if mode & 0o005 and not mode & 0o002:fallback_mode = mode | 0o002logger.warning(- "Relaxing policy directory %s permissions from %s to %s because chown failed",+ "Relaxing policy path %s permissions from %s to %s because chown failed",path,oct(mode),oct(fallback_mode),@@ -205,7 +942,7 @@ class ProcessRuntime(RuntimeAdapter):if not directories:return []- sandbox_root = self._sandbox_root_for_policy(policy)+ sandbox_root = self._sandbox_root()sandbox_root.mkdir(parents=True, exist_ok=True)directory_root = self._directory_roots.get(sandbox_id)if directory_root is None:@@ -221,10 +958,51 @@ class ProcessRuntime(RuntimeAdapter):binds: list[dict[str, str]] = []for directory in directories:sandbox_path, permissions = self._directory_spec(directory)- host_path = directory_root / self._host_directory_name(sandbox_path)+ host_path = directory_root / self._host_entry_name(sandbox_path)host_path.mkdir(parents=True, exist_ok=True)- owner_applied = self._apply_directory_ownership(host_path, uid, gid)- self._apply_directory_permissions(host_path, permissions)+ owner_applied = self._apply_path_ownership(host_path, uid, gid)+ self._apply_path_permissions(host_path, permissions)+ if self._needs_userns_write_fallback(policy, uid, permissions):+ self._apply_userns_write_fallback(host_path)+ self._ensure_writable_when_chown_unavailable(host_path, owner_applied)+ binds.append({+ "host_path": str(host_path),+ "sandbox_path": sandbox_path,+ })+ return binds++ def _ensure_policy_files(+ self,+ sandbox_id: str,+ policy: SecurityPolicy,+ ) -> list[dict[str, str]]:+ files = policy.filesystem_policy.files+ if not files:+ return []++ sandbox_root = self._sandbox_root()+ sandbox_root.mkdir(parents=True, exist_ok=True)+ file_root = self._file_roots.get(sandbox_id)+ if file_root is None:+ file_root = Path(tempfile.mkdtemp(+ prefix=f"{sandbox_id}-files-",+ dir=sandbox_root,+ ))+ self._file_roots[sandbox_id] = file_root+ else:+ file_root.mkdir(parents=True, exist_ok=True)++ uid, gid = self._resolve_backing_identity(policy)+ binds: list[dict[str, str]] = []+ for file in files:+ sandbox_path, permissions = self._file_spec(file)+ host_path = file_root / self._host_entry_name(sandbox_path)+ host_path.parent.mkdir(parents=True, exist_ok=True)+ host_path.touch(exist_ok=True)+ owner_applied = self._apply_path_ownership(host_path, uid, gid)+ self._apply_path_permissions(host_path, permissions)+ if self._needs_userns_owner_access_fallback(policy, uid):+ self._apply_userns_file_access_fallback(host_path)if self._needs_userns_write_fallback(policy, uid, permissions):self._apply_userns_write_fallback(host_path)self._ensure_writable_when_chown_unavailable(host_path, owner_applied)@@ -245,15 +1023,28 @@ class ProcessRuntime(RuntimeAdapter):process_env: dict[str, str],*,netns_name: str | None,- directory_binds: list[dict[str, str]],+ 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 directory_binds:- process_env["JIUWENBOX_DIRECTORY_BINDS"] = json.dumps(- directory_binds,+ 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)@@ -273,11 +1064,64 @@ class ProcessRuntime(RuntimeAdapter):self._network_modes[sandbox_id] = modereturn mode+ def _policy_for_sandbox(self, sandbox_id: str, policy_path: Path) -> SecurityPolicy:+ policy = self._runtime_policies.get(sandbox_id)+ if policy is None:+ policy = self._load_policy(policy_path)+ self._runtime_policies[sandbox_id] = policy+ self._network_modes[sandbox_id] = policy.network.mode+ return policy++ def _policy_binds_for_sandbox(+ self,+ sandbox_id: str,+ policy: SecurityPolicy,+ ) -> list[dict[str, str]]:+ policy_binds = self._policy_binds.get(sandbox_id)+ if policy_binds is None:+ directory_binds = self._ensure_policy_directories(sandbox_id, policy)+ file_binds = self._ensure_policy_files(sandbox_id, policy)+ policy_binds = [*directory_binds, *file_binds]+ self._policy_binds[sandbox_id] = policy_binds+ return policy_binds++ def _reap_background_processes(self, sandbox_id: str) -> None:+ processes = self._background_processes.get(sandbox_id)+ if not processes:+ return+ running = [proc for proc in processes if proc.poll() is None]+ if running:+ self._background_processes[sandbox_id] = running+ else:+ self._background_processes.pop(sandbox_id, None)++ async def _stop_background_processes(self, sandbox_id: str, timeout: float = 5.0) -> None:+ processes = self._background_processes.pop(sandbox_id, [])+ if not processes:+ return++ running = [proc for proc in processes if proc.poll() is None]+ for proc in running:+ try:+ os.killpg(proc.pid, signal.SIGTERM)+ except ProcessLookupError:+ continue++ loop = asyncio.get_running_loop()+ for proc in running:+ try:+ await loop.run_in_executor(None, proc.wait, timeout)+ except subprocess.TimeoutExpired:+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except ProcessLookupError:+ continue+ await loop.run_in_executor(None, proc.wait, 5.0)+async def create(self,sandbox_id: str,policy_path: Path,- command: list[str],workdir: str | None = None,env: dict[str, str] | None = None,) -> int:@@ -288,101 +1132,231 @@ class ProcessRuntime(RuntimeAdapter):self._processes.pop(sandbox_id, None)policy = self._load_policy(policy_path)+ self._runtime_policies[sandbox_id] = policyself._network_modes[sandbox_id] = policy.network.mode+ self._policy_paths[sandbox_id] = Path(policy_path)+netns_name = self._ensure_named_netns(sandbox_id, policy)- directory_binds = self._ensure_policy_directories(sandbox_id, policy)+ self._policy_binds_for_sandbox(sandbox_id, policy)+ self._install_sandbox_host_firewall_rules(sandbox_id, policy)- supervisor_cmd = self._wrap_command_in_namespace(- self._build_supervisor_command(policy_path, SANDBOX_DAEMON_COMMAND),- netns_name,- )+ # Pre-build expensive per-sandbox artifacts so subsequent ``exec``+ # calls only have to allocate a fresh seccomp memfd and assemble the+ # bwrap argv list.+ self._ensure_launcher_dir(sandbox_id)+ self._ensure_landlock_payload(sandbox_id, policy)+ self._daemon_socket_ready[sandbox_id] = False- process_env = {**os.environ, **(env or {})}- self._apply_runtime_env(- process_env,- netns_name=netns_name,- directory_binds=directory_binds,- )+ try:+ listener = self._create_daemon_listener(sandbox_id, policy)+ except OSError as exc:+ self._cleanup_sandbox_artifacts(sandbox_id, netns_name)+ raise RuntimeError(+ f"Failed to bind daemon control listener for sandbox "+ f"{sandbox_id}: {exc}",+ ) from exc+ listener_fd = listener.fileno()- log_file = self._log_dir / f"{sandbox_id}.log"+ seccomp_fd: int | None = None+ try:+ seccomp_fd = self._open_seccomp_fd_from_bytes(+ self._ensure_seccomp_bpf(sandbox_id, policy),+ )+ except Exception:+ logger.warning(+ "Failed to build seccomp filter for sandbox %s; continuing without seccomp",+ sandbox_id,+ exc_info=True,+ )- logger.info(- "Spawning sandbox daemon for %s; ignoring requested command: %s",+ bwrap_args = self._build_sandbox_bwrap_args(sandbox_id,- command,+ policy,+ list(SANDBOX_DAEMON_COMMAND),+ is_daemon=True,+ workdir=workdir,+ sandbox_env=env,+ netns_attached=netns_name is not None,+ seccomp_fd=seccomp_fd,+ listener_fd=listener_fd,)- logger.info("Sandbox daemon supervisor command for %s: %s", sandbox_id, supervisor_cmd)+ 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)+ log_file = self._log_dir / f"{sandbox_id}.log"+ logger.info("Spawning sandbox daemon for %s", sandbox_id)+ logger.debug("Sandbox daemon bwrap command for %s: %s", sandbox_id, daemon_cmd)++ pass_fd_list: list[int] = [listener_fd]+ if seccomp_fd is not None:+ pass_fd_list.append(seccomp_fd)+ pass_fds = tuple(pass_fd_list)try:- with open(log_file, "w", encoding="utf-8") as log_fd:+ log_fd = open(log_file, "w", encoding="utf-8")+ try:proc = subprocess.Popen(- supervisor_cmd,+ daemon_cmd,stdout=log_fd,stderr=subprocess.STDOUT,env=process_env,- cwd=workdir,+ pass_fds=pass_fds,start_new_session=True,)+ finally:+ log_fd.close()except Exception:- directory_root = self._directory_roots.pop(sandbox_id, None)- if directory_root is not None:- shutil.rmtree(directory_root, ignore_errors=True)- if netns_name and network_module.namespace_exists(netns_name):- network_module.delete_named_namespace(netns_name)- self._network_modes.pop(sandbox_id, None)+ if seccomp_fd is not None:+ _safe_close_fd(seccomp_fd)+ try:+ listener.close()+ except OSError:+ pass+ self._cleanup_sandbox_artifacts(sandbox_id, netns_name)raise+ if seccomp_fd is not None:+ _safe_close_fd(seccomp_fd)+ # The daemon now owns the listener fd in its process; box-server's+ # copy is no longer useful and must not block accept-loop teardown.+ try:+ listener.close()+ except OSError:+ pass+self._processes[sandbox_id] = proc- self._policy_paths[sandbox_id] = Path(policy_path)- await asyncio.sleep(0.3)- if proc.poll() is not None:- self._processes.pop(sandbox_id, None)- self._policy_paths.pop(sandbox_id, None)- directory_root = self._directory_roots.pop(sandbox_id, None)- if directory_root is not None:- shutil.rmtree(directory_root, ignore_errors=True)- if netns_name and network_module.namespace_exists(netns_name):- network_module.delete_named_namespace(netns_name)- self._network_modes.pop(sandbox_id, None)- log_tail = ""- if log_file.exists():- log_tail = log_file.read_text(encoding="utf-8", errors="replace")[-4000:]- raise RuntimeError(- f"Sandbox daemon exited during startup with code {proc.returncode}; "- f"see log {log_file}. Log tail: {log_tail}"- )- logger.info("Supervisor started for %s (pid=%d)", sandbox_id, proc.pid)+ await self._wait_daemon_ready(+ sandbox_id,+ proc,+ log_file,+ netns_name,+ )+ logger.info("Sandbox daemon started for %s (pid=%d)", sandbox_id, proc.pid)return proc.pid+ async def _wait_daemon_ready(+ self,+ sandbox_id: str,+ proc: subprocess.Popen,+ log_file: Path,+ netns_name: str | None,+ ) -> None:+ """Verify the daemon is alive and mark its IPC channel ready.++ Box-server already created the listener and ``listen()``ed before+ spawning bubblewrap, so the kernel will queue connection attempts+ immediately - there is no socket file we still have to wait for. We+ sleep briefly to ensure the daemon process has had a chance to+ ``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.+ """+ await asyncio.sleep(DAEMON_STARTUP_GRACE_SECONDS)+ self._verify_daemon_alive(sandbox_id, proc, log_file, netns_name)+ self._daemon_socket_ready[sandbox_id] = True++ def _verify_daemon_alive(+ self,+ sandbox_id: str,+ proc: subprocess.Popen,+ log_file: Path,+ netns_name: str | None,+ ) -> None:+ if proc.poll() is None:+ return+ self._processes.pop(sandbox_id, None)+ self._cleanup_sandbox_artifacts(sandbox_id, netns_name)+ log_tail = ""+ if log_file.exists():+ log_tail = log_file.read_text(encoding="utf-8", errors="replace")[-4000:]+ raise RuntimeError(+ f"Sandbox daemon exited during startup with code {proc.returncode}; "+ f"see log {log_file}. Log tail: {log_tail}"+ )++ def _cleanup_sandbox_artifacts(+ self,+ sandbox_id: str,+ netns_name: str | None,+ ) -> None:+ """Drop every cache that was populated during a failed ``create``."""+ directory_root = self._directory_roots.pop(sandbox_id, None)+ if directory_root is not None:+ shutil.rmtree(directory_root, ignore_errors=True)+ file_root = self._file_roots.pop(sandbox_id, None)+ if file_root is not None:+ shutil.rmtree(file_root, ignore_errors=True)+ launcher_dir = self._launcher_dirs.pop(sandbox_id, None)+ if launcher_dir is not None:+ shutil.rmtree(launcher_dir, ignore_errors=True)+ control_dir = self._control_dirs.pop(sandbox_id, None)+ if control_dir is not None:+ shutil.rmtree(control_dir, ignore_errors=True)+ self._daemon_socket_ready.pop(sandbox_id, None)+ if netns_name and network_module.namespace_exists(netns_name):+ network_module.delete_named_namespace(netns_name)+ self._network_modes.pop(sandbox_id, None)+ self._runtime_policies.pop(sandbox_id, None)+ self._policy_binds.pop(sandbox_id, None)+ self._seccomp_bpf.pop(sandbox_id, None)+ self._landlock_payloads.pop(sandbox_id, None)+ self._policy_paths.pop(sandbox_id, None)+ self._remove_sandbox_host_firewall_rules(sandbox_id)+async def stop(self, sandbox_id: str, timeout: float = 10.0) -> None:+ await self._stop_background_processes(sandbox_id)proc = self._processes.get(sandbox_id)if proc is None:+ self._remove_sandbox_host_firewall_rules(sandbox_id)returnif proc.poll() is not None:self._processes.pop(sandbox_id, None)+ self._remove_sandbox_host_firewall_rules(sandbox_id)returnlogger.info("Stopping sandbox %s (pid=%d)", sandbox_id, proc.pid)+ # Politely ask the daemon to drain in-flight IPC requests first;+ # ``SIGTERM`` from the host then trips the kernel's normal default+ # action (the daemon installs no signal handlers, so PID-1 namespace+ # init protection prevents inside-sandbox processes from hijacking+ # this path).+ await self._send_daemon_shutdown(sandbox_id)+ # Briefly give the daemon a chance to exit on its own; if it does we+ # avoid the SIGTERM/SIGKILL escalation entirely.+ loop = asyncio.get_running_loop()try:- os.killpg(proc.pid, signal.SIGTERM)- except ProcessLookupError:- self._processes.pop(sandbox_id, None)- return-- try:- await asyncio.get_running_loop().run_in_executor(- None, proc.wait, timeout,+ await loop.run_in_executor(+ None, proc.wait, DAEMON_SHUTDOWN_TIMEOUT_SECONDS,)except subprocess.TimeoutExpired:- logger.warning("SIGTERM timeout for %s, killing", sandbox_id)try:- os.killpg(proc.pid, signal.SIGKILL)+ os.killpg(proc.pid, signal.SIGTERM)except ProcessLookupError:self._processes.pop(sandbox_id, None)+ self._daemon_socket_ready.pop(sandbox_id, None)+ self._remove_sandbox_host_firewall_rules(sandbox_id)return- await asyncio.get_running_loop().run_in_executor(None, proc.wait, 5.0)++ try:+ await loop.run_in_executor(None, proc.wait, timeout)+ except subprocess.TimeoutExpired:+ logger.warning("SIGTERM timeout for %s, killing", sandbox_id)+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except ProcessLookupError:+ self._processes.pop(sandbox_id, None)+ self._daemon_socket_ready.pop(sandbox_id, None)+ self._remove_sandbox_host_firewall_rules(sandbox_id)+ return+ await loop.run_in_executor(None, proc.wait, 5.0)self._processes.pop(sandbox_id, None)+ self._daemon_socket_ready.pop(sandbox_id, None)+ self._remove_sandbox_host_firewall_rules(sandbox_id)async def is_running(self, sandbox_id: str) -> bool:proc = self._processes.get(sandbox_id)@@ -403,62 +1377,703 @@ class ProcessRuntime(RuntimeAdapter):f"returncode={returncode}; log={log_file}; log_tail={log_tail}")- async def exec(+ def _prepare_exec_invocation(self,sandbox_id: str,request: RuntimeExecRequest,- ) -> ExecResult:- """Execute a command by spawning a new supervisor inside the sandbox netns."""+ ) -> tuple[list[str], int | None] | None:+ """Build the bwrap argv + a fresh seccomp memfd for one ``exec``.++ Returns ``None`` when the sandbox has no recorded policy (the caller+ decides what failure to surface).+ """policy_path = self._policy_paths.get(sandbox_id)if policy_path is None:- return ExecResult(exit_code=1, stderr="No policy found for sandbox")+ return None- netns_name = None- if self._network_mode_for_cleanup(sandbox_id) == NetworkMode.ISOLATED:- policy = self._load_policy(policy_path)+ policy = self._policy_for_sandbox(sandbox_id, policy_path)+ if policy.network.mode == NetworkMode.ISOLATED:netns_name = self._ensure_named_netns(sandbox_id, policy)else:- policy = self._load_policy(policy_path)- directory_binds = self._ensure_policy_directories(sandbox_id, policy)+ netns_name = None+ self._policy_binds_for_sandbox(sandbox_id, policy)+ self._ensure_launcher_dir(sandbox_id)- supervisor_cmd = self._wrap_command_in_namespace(- self._build_supervisor_command(policy_path, list(request.command)),- netns_name,+ seccomp_fd: int | None = None+ try:+ seccomp_fd = self._open_seccomp_fd_from_bytes(+ self._ensure_seccomp_bpf(sandbox_id, policy),+ )+ except Exception:+ logger.warning(+ "Failed to build seccomp filter for sandbox %s exec; continuing without seccomp",+ sandbox_id,+ exc_info=True,+ )++ bwrap_args = self._build_sandbox_bwrap_args(+ sandbox_id,+ policy,+ list(request.command),+ is_daemon=False,+ workdir=request.workdir,+ sandbox_env=request.env,+ netns_attached=netns_name is not None,+ seccomp_fd=seccomp_fd,)+ return self._wrap_command_in_namespace(bwrap_args, netns_name), seccomp_fd- process_env = {**os.environ, **(request.env or {})}- self._apply_runtime_env(- process_env,- netns_name=netns_name,- directory_binds=directory_binds,+ def _daemon_ipc_available(self, sandbox_id: str) -> bool:+ if not self._daemon_socket_ready.get(sandbox_id, False):+ return False+ proc = self._processes.get(sandbox_id)+ if proc is None or proc.poll() is not None:+ return False+ socket_path = self._control_socket_host_path(sandbox_id)+ if socket_path is None:+ return False+ try:+ return socket_path.exists()+ except OSError:+ return False++ @staticmethod+ def _connect_daemon_socket(socket_path: Path) -> socket.socket:+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ sock.settimeout(DAEMON_CONNECT_TIMEOUT_SECONDS)+ try:+ sock.connect(str(socket_path))+ except OSError:+ sock.close()+ raise+ return sock++ @staticmethod+ def _send_request_blob(+ sock: socket.socket,+ header_blob: bytes,+ stdin_bytes: bytes | None,+ ) -> None:+ send_frame(sock, header_blob)+ if stdin_bytes:+ sock.sendall(stdin_bytes)++ @staticmethod+ def _read_response_blob(sock: socket.socket) -> dict[str, Any]:+ blob = recv_frame(sock, DAEMON_MAX_RESPONSE_BYTES)+ return json.loads(blob.decode("utf-8"))++ def _exec_via_daemon_blocking(self, call: _DaemonExecCall) -> ExecResult:+ """Run one ``exec`` over the IPC channel and return an ``ExecResult``.++ Executed via a worker thread so the asyncio event loop does not block+ on the synchronous Unix-socket IO. The daemon ``communicate()``s the+ child entirely before responding, so we only have to handle the+ request/response pair here.+ """+ request_payload: dict[str, Any] = {+ "command": list(call.command),+ "stdin_size": len(call.stdin_bytes or b""),+ }+ if call.env:+ request_payload["env"] = dict(call.env)+ if call.workdir:+ request_payload["workdir"] = call.workdir+ if call.timeout is not None:+ request_payload["timeout"] = call.timeout+ header_blob = encode_request(+ request_type=REQUEST_TYPE_EXEC,+ payload=request_payload,)+ if len(header_blob) > MAX_HEADER_BYTES:+ return ExecResult(+ exit_code=1,+ stderr=(+ f"daemon request header too large "+ f"({len(header_blob)} > {MAX_HEADER_BYTES})"+ ),+ )+ sock = self._connect_daemon_socket(call.socket_path)try:- logger.info("Executing command in sandbox %s: %s", sandbox_id, supervisor_cmd)- result = await asyncio.get_running_loop().run_in_executor(+ # The daemon waits for the user command to finish before+ # responding, so the receive timeout has to outlive the request+ # timeout. ``None`` means "wait forever" which matches the+ # legacy bwrap path when no timeout is configured.+ if call.timeout is not None:+ sock.settimeout(call.timeout + 5.0)+ else:+ sock.settimeout(None)+ self._send_request_blob(sock, header_blob, call.stdin_bytes)+ try:+ sock.shutdown(socket.SHUT_WR)+ except OSError:+ pass+ response = self._read_response_blob(sock)+ finally:+ try:+ sock.close()+ except OSError:+ pass++ return ExecResult(+ exit_code=int(response.get("exit_code", 1)),+ stdout=str(response.get("stdout", "")),+ stderr=str(response.get("stderr", "")),+ )++ async def _exec_via_daemon(+ self,+ sandbox_id: str,+ request: RuntimeExecRequest,+ ) -> ExecResult:+ """Run an ``exec`` over the daemon IPC channel.++ Transport-level failures (connection refused, daemon crashed,+ timeout, framing/JSON corruption) surface as a synthetic+ ``ExecResult`` with a non-zero exit code so callers see the same+ value-shape regardless of whether the IPC roundtrip succeeded.+ Whenever transport fails the daemon is also flagged unhealthy so+ the next call short-circuits without attempting another connect.+ """+ socket_path = self._control_socket_host_path(sandbox_id)+ if socket_path is None or not self._daemon_ipc_available(sandbox_id):+ return ExecResult(+ exit_code=1,+ stdout="",+ stderr=(+ f"sandbox {sandbox_id!r} daemon IPC channel unavailable; "+ "the daemon is not running or its control socket is gone"+ ),+ )++ loop = asyncio.get_running_loop()+ try:+ return await loop.run_in_executor(None,- lambda: subprocess.run(- supervisor_cmd,- input=request.stdin_data,- capture_output=True,+ self._exec_via_daemon_blocking,+ _DaemonExecCall(+ socket_path=socket_path,+ command=list(request.command),+ env=dict(request.env) if request.env else None,+ workdir=request.workdir,+ stdin_bytes=request.stdin_data,timeout=request.timeout,- env=process_env,- cwd=request.workdir,),)+ except (ConnectionError, ValueError) as exc:+ # ``ValueError`` already covers ``json.JSONDecodeError`` (G.ERR.09).+ self._daemon_socket_ready[sandbox_id] = False+ logger.warning(+ "Daemon IPC transport failure for sandbox %s: %s",+ sandbox_id,+ exc,+ )return ExecResult(- exit_code=result.returncode,- stdout=result.stdout.decode(errors="replace"),- stderr=result.stderr.decode(errors="replace"),+ exit_code=1,+ stdout="",+ stderr=f"daemon IPC transport failure: {exc}",)- except subprocess.TimeoutExpired:- return ExecResult(exit_code=124, stderr="Command timed out")+ except socket.timeout as exc:+ self._daemon_socket_ready[sandbox_id] = False+ logger.warning(+ "Daemon IPC timeout for sandbox %s: %s",+ sandbox_id,+ exc,+ )+ return ExecResult(+ exit_code=124,+ stdout="",+ stderr=f"daemon IPC timeout: {exc}",+ )+ except OSError as exc:+ if exc.errno in FATAL_DAEMON_ERRNOS:+ # Daemon is genuinely gone - flip the flag so future+ # callers stop trying this socket and fall back.+ self._daemon_socket_ready[sandbox_id] = False+ logger.warning(+ "Daemon IPC unavailable for sandbox %s (fatal errno=%s): %s",+ sandbox_id,+ exc.errno,+ exc,+ )+ return ExecResult(+ exit_code=1,+ stdout="",+ stderr=f"daemon IPC unavailable: {exc}",+ )+ if exc.errno in RECOVERABLE_DAEMON_ERRNOS:+ # This is just transient host-side pressure (EMFILE,+ # EAGAIN, ENOMEM, ...). Don't poison the daemon - the+ # next request should be able to use the fast path.+ logger.warning(+ "Daemon IPC transient failure for sandbox %s (errno=%s): %s",+ sandbox_id,+ exc.errno,+ exc,+ )+ return ExecResult(+ exit_code=1,+ stdout="",+ stderr=f"daemon IPC transient failure: {exc}",+ )+ raise++ def _file_op_unavailable(self, sandbox_id: str) -> RuntimeFileOpResult:+ return RuntimeFileOpResult(+ ok=False,+ error="daemon_unavailable",+ detail=(+ f"sandbox {sandbox_id!r} daemon IPC channel unavailable; "+ "the daemon is not running or its control socket is gone"+ ),+ )++ def _file_op_transport_failure(+ self,+ sandbox_id: str,+ exc: BaseException,+ *,+ fatal: bool = True,+ ) -> RuntimeFileOpResult:+ """Build a transport-failure result.++ If ``fatal`` is true the sandbox's daemon is flagged unhealthy so+ subsequent callers fall back to the legacy ``bash`` / ``python3``+ path. Recoverable resource-pressure errors (EMFILE, EAGAIN, ...)+ should pass ``fatal=False`` so the next request can still take+ the IPC fast path - otherwise a single transient blip permanently+ demotes the sandbox to the slow exec fallback and turns subsequent+ calls into ~hundreds of ms each.+ """+ if fatal:+ self._daemon_socket_ready[sandbox_id] = False+ logger.warning(+ "Daemon IPC %s failure during file-op for sandbox %s: %s",+ "transport" if fatal else "transient",+ sandbox_id,+ exc,+ )+ return RuntimeFileOpResult(+ ok=False,+ error="transport_failure",+ detail=str(exc),+ )++ def _write_file_via_daemon_blocking(+ self,+ socket_path: Path,+ sandbox_path: str,+ content: bytes,+ mkdir_parents: bool,+ mode: int | None,+ ) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "path": sandbox_path,+ "content_size": len(content),+ "mkdir_parents": mkdir_parents,+ }+ if mode is not None:+ payload["mode"] = mode+ header_blob = encode_request(+ request_type=REQUEST_TYPE_WRITE_FILE,+ payload=payload,+ )+ sock = self._connect_daemon_socket(socket_path)+ try:+ sock.settimeout(DAEMON_FILE_OP_TIMEOUT_SECONDS)+ self._send_request_blob(sock, header_blob, content)+ try:+ sock.shutdown(socket.SHUT_WR)+ except OSError:+ pass+ return self._read_response_blob(sock)+ finally:+ try:+ sock.close()+ except OSError:+ pass++ def _read_file_via_daemon_blocking(+ self,+ socket_path: Path,+ sandbox_path: str,+ ) -> tuple[dict[str, Any], bytes]:+ header_blob = encode_request(+ request_type=REQUEST_TYPE_READ_FILE,+ payload={"path": sandbox_path},+ )+ sock = self._connect_daemon_socket(socket_path)+ try:+ sock.settimeout(DAEMON_FILE_OP_TIMEOUT_SECONDS)+ self._send_request_blob(sock, header_blob, None)+ try:+ sock.shutdown(socket.SHUT_WR)+ except OSError:+ pass+ response = self._read_response_blob(sock)+ content = b""+ if response.get("ok"):+ size = int(response.get("content_size") or 0)+ if size > 0:+ content = recv_frame(sock, MAX_FILE_BYTES)+ if len(content) != size:+ raise ConnectionError(+ f"daemon returned {len(content)} bytes but advertised {size}",+ )+ return response, content+ finally:+ try:+ sock.close()+ except OSError:+ pass++ def _list_dir_via_daemon_blocking(+ self, call: _DaemonListDirCall,+ ) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "path": call.sandbox_path,+ "recursive": call.recursive,+ "include_files": call.include_files,+ "include_dirs": call.include_dirs,+ }+ if call.max_depth is not None:+ payload["max_depth"] = call.max_depth+ header_blob = encode_request(+ request_type=REQUEST_TYPE_LIST_DIR,+ payload=payload,+ )+ sock = self._connect_daemon_socket(call.socket_path)+ try:+ sock.settimeout(DAEMON_FILE_OP_TIMEOUT_SECONDS)+ self._send_request_blob(sock, header_blob, None)+ try:+ sock.shutdown(socket.SHUT_WR)+ except OSError:+ pass+ return self._read_response_blob(sock)+ finally:+ try:+ sock.close()+ except OSError:+ pass++ @staticmethod+ def _file_op_result_from_response(response: dict[str, Any]) -> RuntimeFileOpResult:+ if response.get("ok"):+ return RuntimeFileOpResult(ok=True)+ return RuntimeFileOpResult(+ ok=False,+ error=str(response.get("error") or "io_error"),+ errno=int(response["errno"]) if isinstance(response.get("errno"), int) else None,+ detail=str(response.get("stderr") or response.get("detail") or ""),+ )++ async def write_file(+ self,+ sandbox_id: str,+ sandbox_path: str,+ content: bytes,+ *,+ mkdir_parents: bool = True,+ mode: int | None = None,+ ) -> RuntimeFileOpResult:+ socket_path = self._control_socket_host_path(sandbox_id)+ if socket_path is None or not self._daemon_ipc_available(sandbox_id):+ return self._file_op_unavailable(sandbox_id)+ if len(content) > MAX_FILE_BYTES:+ return RuntimeFileOpResult(+ ok=False,+ error="too_large",+ detail=(+ f"content size {len(content)} exceeds limit {MAX_FILE_BYTES}"+ ),+ )++ loop = asyncio.get_running_loop()+ try:+ response = await loop.run_in_executor(+ None,+ self._write_file_via_daemon_blocking,+ socket_path,+ sandbox_path,+ content,+ mkdir_parents,+ mode,+ )+ except (ConnectionError, ValueError) as exc:+ # ``ValueError`` already covers ``json.JSONDecodeError`` (G.ERR.09).+ return self._file_op_transport_failure(sandbox_id, exc)+ except socket.timeout as exc:+ return self._file_op_transport_failure(sandbox_id, exc)+ except OSError as exc:+ if exc.errno in FATAL_DAEMON_ERRNOS:+ return self._file_op_transport_failure(sandbox_id, exc)+ if exc.errno in RECOVERABLE_DAEMON_ERRNOS:+ return self._file_op_transport_failure(sandbox_id, exc, fatal=False)+ raise+ return self._file_op_result_from_response(response)++ async def read_file(+ self,+ sandbox_id: str,+ sandbox_path: str,+ ) -> RuntimeFileOpResult:+ socket_path = self._control_socket_host_path(sandbox_id)+ if socket_path is None or not self._daemon_ipc_available(sandbox_id):+ return self._file_op_unavailable(sandbox_id)++ loop = asyncio.get_running_loop()+ try:+ response, content = await loop.run_in_executor(+ None,+ self._read_file_via_daemon_blocking,+ socket_path,+ sandbox_path,+ )+ except (ConnectionError, ValueError) as exc:+ # ``ValueError`` already covers ``json.JSONDecodeError`` (G.ERR.09).+ return self._file_op_transport_failure(sandbox_id, exc)+ except socket.timeout as exc:+ return self._file_op_transport_failure(sandbox_id, exc)+ except OSError as exc:+ if exc.errno in FATAL_DAEMON_ERRNOS:+ return self._file_op_transport_failure(sandbox_id, exc)+ if exc.errno in RECOVERABLE_DAEMON_ERRNOS:+ return self._file_op_transport_failure(sandbox_id, exc, fatal=False)+ raise++ if response.get("ok"):+ return RuntimeFileOpResult(ok=True, content=content)+ return self._file_op_result_from_response(response)++ async def list_dir(+ self,+ sandbox_id: str,+ sandbox_path: str,+ *,+ recursive: bool = False,+ max_depth: int | None = None,+ include_files: bool = True,+ include_dirs: bool = True,+ ) -> RuntimeFileOpResult:+ socket_path = self._control_socket_host_path(sandbox_id)+ if socket_path is None or not self._daemon_ipc_available(sandbox_id):+ return self._file_op_unavailable(sandbox_id)++ loop = asyncio.get_running_loop()+ try:+ response = await loop.run_in_executor(+ None,+ self._list_dir_via_daemon_blocking,+ _DaemonListDirCall(+ socket_path=socket_path,+ sandbox_path=sandbox_path,+ recursive=recursive,+ max_depth=max_depth,+ include_files=include_files,+ include_dirs=include_dirs,+ ),+ )+ except (ConnectionError, ValueError) as exc:+ # ``ValueError`` already covers ``json.JSONDecodeError`` (G.ERR.09).+ return self._file_op_transport_failure(sandbox_id, exc)+ except socket.timeout as exc:+ return self._file_op_transport_failure(sandbox_id, exc)+ except OSError as exc:+ if exc.errno in FATAL_DAEMON_ERRNOS:+ return self._file_op_transport_failure(sandbox_id, exc)+ if exc.errno in RECOVERABLE_DAEMON_ERRNOS:+ return self._file_op_transport_failure(sandbox_id, exc, fatal=False)+ raise++ if response.get("ok"):+ items = response.get("items")+ if not isinstance(items, list):+ items = []+ return RuntimeFileOpResult(ok=True, items=items)+ return self._file_op_result_from_response(response)++ async def _send_daemon_shutdown(self, sandbox_id: str) -> None:+ """Politely ask the daemon to drain and exit before sending SIGTERM."""+ socket_path = self._control_socket_host_path(sandbox_id)+ if socket_path is None or not self._daemon_socket_ready.get(sandbox_id, False):+ return+ if not socket_path.exists():+ return++ def _ask_shutdown(path: Path) -> None:+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ sock.settimeout(DAEMON_SHUTDOWN_TIMEOUT_SECONDS)+ try:+ sock.connect(str(path))+ send_frame(+ sock,+ encode_request(request_type=REQUEST_TYPE_SHUTDOWN),+ )+ try:+ recv_frame(sock, MAX_HEADER_BYTES)+ except OSError:+ # ``OSError`` already covers ``ConnectionError`` (G.ERR.09).+ pass+ finally:+ try:+ sock.close()+ except OSError:+ pass++ loop = asyncio.get_running_loop()+ try:+ await asyncio.wait_for(+ loop.run_in_executor(None, _ask_shutdown, socket_path),+ timeout=DAEMON_SHUTDOWN_TIMEOUT_SECONDS,+ )+ except (asyncio.TimeoutError, OSError) as exc:+ logger.debug(+ "Failed to send daemon shutdown for %s: %s",+ sandbox_id,+ exc,+ )++ def _ensure_exec_semaphore(self) -> asyncio.Semaphore:+ """Lazily build the per-runtime ``exec`` admission semaphore.++ Cannot be created in ``__init__`` because ``ProcessRuntime`` may+ be instantiated before any event loop is running (e.g. CLI tools+ or pytest fixtures), and ``asyncio.Semaphore`` will then bind to+ the wrong loop. By creating it the first time ``exec`` actually+ awaits inside the server's loop, we guarantee it is bound to the+ loop that will end up signalling it.+ """+ sem = self._exec_semaphore+ if sem is None:+ sem = asyncio.Semaphore(self._exec_concurrency_limit)+ self._exec_semaphore = sem+ return sem++ async def exec(+ self,+ sandbox_id: str,+ request: RuntimeExecRequest,+ ) -> ExecResult:+ """Execute a command in the sandbox via the daemon IPC channel.++ Each sandbox owns a long-running in-sandbox daemon (PID 1 of its+ own PID namespace) that bubblewrap set up once at sandbox creation+ with the full namespace/mount/seccomp/Landlock envelope. ``exec``+ therefore boils down to a single Unix-socket roundtrip; bubblewrap+ is **not** spawned per call. The same security envelope is+ inherited by every command the daemon ``fork+exec``s.++ Concurrency is gated by ``_exec_semaphore`` to keep the number of+ in-flight CPU-heavy commands below ``JIUWENBOX_EXEC_CONCURRENCY``+ (defaulted to the box's usable CPU count). Without this cap,+ running more concurrent ``exec`` calls than there are CPUs causes+ super-linear latency growth - the typical "throughput collapse"+ pattern of oversubscribed CPU-bound workloads. File-ops fast+ paths (``write_file``/``read_file``/``list_dir``) are *not*+ throttled because they are I/O-bound and barely consume CPU.+ """+ logger.info(+ "Executing command in sandbox %s via daemon IPC: %s",+ sandbox_id,+ _summarize_command(list(request.command)),+ )+ semaphore = self._ensure_exec_semaphore()+ async with semaphore:+ return await self._exec_via_daemon(sandbox_id, request)++ async def exec_background(+ self,+ sandbox_id: str,+ request: RuntimeExecRequest,+ ) -> BackgroundExecResult:+ """Start a command and return after the process is created."""+ prepared = self._prepare_exec_invocation(sandbox_id, request)+ if prepared is None:+ return BackgroundExecResult(+ started=False,+ command=list(request.command),+ error_message="No policy found for sandbox",+ )+ bwrap_cmd, seccomp_fd = prepared++ process_env = {**os.environ, **(request.env or {})}++ self._reap_background_processes(sandbox_id)+ log_index = len(self._background_processes.get(sandbox_id, []))+ log_file = self._log_dir / f"{sandbox_id}-background-{log_index}.log"+ stdin_target = subprocess.PIPE if request.stdin_data is not None else subprocess.DEVNULL+ pass_fds = (seccomp_fd,) if seccomp_fd is not None else ()+ try:+ log_fd = open(log_file, "ab")+ try:+ proc = subprocess.Popen(+ bwrap_cmd,+ stdin=stdin_target,+ stdout=log_fd,+ stderr=subprocess.STDOUT,+ env=process_env,+ pass_fds=pass_fds,+ start_new_session=True,+ )+ if request.stdin_data is not None and proc.stdin is not None:+ proc.stdin.write(request.stdin_data)+ proc.stdin.close()+ finally:+ log_fd.close()+ except Exception as exc:+ return BackgroundExecResult(+ started=False,+ command=list(request.command),+ error_message=str(exc),+ )+ finally:+ if seccomp_fd is not None:+ _safe_close_fd(seccomp_fd)++ await asyncio.sleep(0.2)+ if proc.poll() is not None:+ log_tail = ""+ if log_file.exists():+ log_tail = log_file.read_text(encoding="utf-8", errors="replace")[-4000:]+ return BackgroundExecResult(+ started=False,+ pid=proc.pid,+ command=list(request.command),+ error_message=(+ f"Background command exited during startup with code "+ f"{proc.returncode}; log={log_file}; log_tail={log_tail}"+ ),+ )++ self._background_processes.setdefault(sandbox_id, []).append(proc)+ logger.info(+ "Started background command in sandbox %s (pid=%d): %s",+ sandbox_id,+ proc.pid,+ _summarize_command(list(request.command)),+ )+ logger.debug(+ "Background bwrap command for sandbox %s: %s",+ sandbox_id,+ bwrap_cmd,+ )+ return BackgroundExecResult(+ started=True,+ pid=proc.pid,+ command=list(request.command),+ )async def cleanup(self, sandbox_id: str) -> None:await self.stop(sandbox_id)self._processes.pop(sandbox_id, None)policy_path = self._policy_paths.pop(sandbox_id, None)network_mode = self._network_modes.pop(sandbox_id, None)+ self._runtime_policies.pop(sandbox_id, None)+ self._policy_binds.pop(sandbox_id, None)+ self._seccomp_bpf.pop(sandbox_id, None)+ self._landlock_payloads.pop(sandbox_id, None)if network_mode is None and policy_path is not None and policy_path.exists():try:network_mode = self._load_policy(policy_path).network.mode@@ -478,10 +2093,23 @@ class ProcessRuntime(RuntimeAdapter):network_module.delete_named_namespace(namespace)else:self._netns_names.pop(sandbox_id, None)+ self._remove_sandbox_host_firewall_rules(sandbox_id)directory_root = self._directory_roots.pop(sandbox_id, None)if directory_root is not None and directory_root.exists():shutil.rmtree(directory_root, ignore_errors=True)+ file_root = self._file_roots.pop(sandbox_id, None)+ if file_root is not None and file_root.exists():+ shutil.rmtree(file_root, ignore_errors=True)+ launcher_dir = self._launcher_dirs.pop(sandbox_id, None)+ if launcher_dir is not None and launcher_dir.exists():+ shutil.rmtree(launcher_dir, ignore_errors=True)+ control_dir = self._control_dirs.pop(sandbox_id, None)+ if control_dir is not None and control_dir.exists():+ shutil.rmtree(control_dir, ignore_errors=True)+ self._daemon_socket_ready.pop(sandbox_id, None)log_file = self._log_dir / f"{sandbox_id}.log"log_file.unlink(missing_ok=True)+ for background_log in self._log_dir.glob(f"{sandbox_id}-background-*.log"):+ background_log.unlink(missing_ok=True)diff --git a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.pyindex 2f1ad636d1..b13f9e388c 100644--- a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py+++ b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py@@ -21,9 +21,11 @@ from dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Path+from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.common import AuditEventTypefrom jiuwenbox.models.policy import SecurityPolicyfrom jiuwenbox.models.sandbox import (+ BackgroundExecResult,ExecResult,PolicyMode,SandboxPhase,@@ -32,14 +34,14 @@ from jiuwenbox.models.sandbox import ()from jiuwenbox.server.audit_logger import AuditLoggerfrom jiuwenbox.server.policy_engine import PolicyEngine+from jiuwenbox.server.policy_reader import PolicyReaderfrom jiuwenbox.server.runtime.base import RuntimeAdapter, RuntimeExecRequestfrom jiuwenbox.server.runtime.process import ProcessRuntime+from jiuwenbox.server.workspace import JIUWENBOX_HOME-logging.basicConfig(level=logging.INFO)+configure_logging()logger = logging.getLogger(__name__)-DEFAULT_POLICY_PATH_ENV = "JIUWENBOX_DEFAULT_POLICY_PATH"-@dataclass(frozen=True)class SandboxExecRequest:@@ -80,48 +82,31 @@ class SandboxManager:policy_engine: PolicyEngine | None = None,audit_logger: AuditLogger | None = None,state_dir: Path | None = None,- default_policy_path: Path | None = None,+ policy_reader: PolicyReader | None = None,+ policy_path: Path | None = None,) -> None:self.runtime = runtime or ProcessRuntime()self.policy_engine = policy_engine or PolicyEngine()self.audit = audit_logger or AuditLogger()- self.state_dir = state_dir or Path.home() / ".jiuwenbox" / "sandboxes"+ self.state_dir = state_dir or JIUWENBOX_HOME / "sandboxes"self.state_dir.mkdir(parents=True, exist_ok=True)- self.default_policy_path = (- Path(default_policy_path)- if default_policy_path is not None- else self._resolve_default_policy_path()+ self.policy_reader = policy_reader or PolicyReader(+ policy_engine=self.policy_engine,+ policy_path=policy_path,)- self.default_policy = self._load_default_policy()+ self.policy = self.policy_reader.load_policy()self._lock = asyncio.Lock()self._sandboxes: dict[str, SandboxRef] = {}self._policies: dict[str, SecurityPolicy] = {}self._load_state()- @staticmethod- def _resolve_default_policy_path() -> Path:- env_path = os.environ.get(DEFAULT_POLICY_PATH_ENV)- if env_path:- return Path(env_path).expanduser()- return Path(__file__).resolve().parents[3] / "configs" / "default-policy.yaml"-- def _load_default_policy(self) -> SecurityPolicy:- if self.default_policy_path.exists():- return self.policy_engine.load_policy_from_file(self.default_policy_path)-- logger.warning(- "Default policy file not found at %s, falling back to SecurityPolicy defaults",- self.default_policy_path,- )- return SecurityPolicy()-def _resolve_effective_policy(self,policy_data: SecurityPolicy | Mapping[str, object] | None,policy_mode: PolicyMode,) -> SecurityPolicy:- base_policy = self.default_policy.model_copy(deep=True)+ base_policy = self.policy.model_copy(deep=True)if policy_data is None:return base_policy@@ -136,7 +121,6 @@ class SandboxManager:if isinstance(policy_payload, SecurityPolicy):return policy_payload.model_copy(deep=True)- policy_payload.setdefault("sandbox_workspace", base_policy.sandbox_workspace)return SecurityPolicy.model_validate(policy_payload)def _load_state(self) -> None:@@ -168,7 +152,6 @@ class SandboxManager:async def create_sandbox(self,spec: SandboxSpec,- command: list[str] | None = None,policy_data: SecurityPolicy | Mapping[str, object] | None = None,policy_mode: PolicyMode = PolicyMode.OVERRIDE,) -> SandboxRef:@@ -176,13 +159,12 @@ class SandboxManager:async with self._lock:sandbox_id = str(uuid.uuid4())[:12]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)# Create sandbox refref = SandboxRef(id=sandbox_id,phase=SandboxPhase.PROVISIONING,- command=[],- workdir=spec.workdir,env=dict(spec.env),)self._sandboxes[sandbox_id] = ref@@ -195,25 +177,38 @@ class SandboxManager:policy_path = self.policy_engine.write_sandbox_policy(sandbox_id, policy)self.audit.log(AuditEventType.POLICY_APPLIED, sandbox_id, policy_name=policy.name)- # Start via runtime- try:- pid = await self.runtime.create(- sandbox_id=sandbox_id,- policy_path=policy_path,- command=ref.command,- workdir=ref.workdir,- env=ref.env,- )- ref.phase = SandboxPhase.READY- ref.pid = pid- ref.started_at = datetime.now(timezone.utc)- except Exception as e:+ # Runtime startup can be expensive. Do it outside the manager-wide lock+ # so independent sandboxes can start in parallel.+ try:+ pid = await self.runtime.create(+ sandbox_id=sandbox_id,+ policy_path=policy_path,+ workdir=None,+ env=ref.env,+ )+ cleanup_after_create = False+ async with self._lock:+ current_ref = self._sandboxes.get(sandbox_id)+ if current_ref is not ref or ref.phase == SandboxPhase.DELETING:+ cleanup_after_create = True+ else:+ ref.phase = SandboxPhase.READY+ ref.pid = pid+ ref.started_at = datetime.now(timezone.utc)+ self._save_state(ref)+ if cleanup_after_create:+ await self.runtime.cleanup(sandbox_id)+ except Exception as e:+ async with self._lock:+ current_ref = self._sandboxes.get(sandbox_id)+ if current_ref is not ref or ref.phase == SandboxPhase.DELETING:+ return refref.phase = SandboxPhase.ERRORref.error_message = str(e)logger.error("Failed to create sandbox %s: %s", sandbox_id, e)+ self._save_state(ref)- self._save_state(ref)- return ref+ return refasync def get_sandbox(self, sandbox_id: str) -> SandboxRef:async with self._lock:@@ -258,8 +253,7 @@ class SandboxManager:pid = await self.runtime.create(sandbox_id=sandbox_id,policy_path=policy_path,- command=ref.command,- workdir=ref.workdir,+ workdir=None,env=ref.env,)ref.phase = SandboxPhase.READY@@ -299,10 +293,14 @@ class SandboxManager:ref.phase = SandboxPhase.DELETINGself._save_state(ref)- await self.runtime.cleanup(sandbox_id)- self.policy_engine.delete_sandbox_policy(sandbox_id)- self.audit.log(AuditEventType.SANDBOX_DELETED, sandbox_id)+ # Cleanup can wait on processes and namespace teardown. Keep it outside+ # the global state lock so deleting one sandbox does not block unrelated+ # sandbox operations.+ await self.runtime.cleanup(sandbox_id)+ self.policy_engine.delete_sandbox_policy(sandbox_id)+ self.audit.log(AuditEventType.SANDBOX_DELETED, sandbox_id)+ async with self._lock:self._sandboxes.pop(sandbox_id, None)self._policies.pop(sandbox_id, None)self._delete_state(sandbox_id)@@ -319,10 +317,12 @@ class SandboxManager:f"Cannot exec in sandbox '{sandbox_id}': state is {ref.phase.value}")- self.audit.log(- AuditEventType.EXEC_COMMAND, sandbox_id,- command=request.command, workdir=request.workdir,- )+ self.audit.log(+ AuditEventType.EXEC_COMMAND,+ sandbox_id,+ command=request.command,+ workdir=request.workdir,+ )return await self.runtime.exec(sandbox_id,@@ -335,12 +335,50 @@ class SandboxManager:),)+ async def exec_background_in_sandbox(+ self,+ sandbox_id: str,+ request: SandboxExecRequest,+ ) -> BackgroundExecResult:+ async with self._lock:+ ref = self._get_sandbox(sandbox_id)+ if ref.phase != SandboxPhase.READY:+ raise SandboxStateError(+ f"Cannot exec in sandbox '{sandbox_id}': state is {ref.phase.value}"+ )++ self.audit.log(+ AuditEventType.EXEC_COMMAND,+ sandbox_id,+ command=request.command,+ workdir=request.workdir,+ background=True,+ )++ return await self.runtime.exec_background(+ sandbox_id,+ RuntimeExecRequest(+ command=request.command,+ workdir=request.workdir,+ env=request.env,+ stdin_data=request.stdin_data,+ timeout=request.timeout,+ ),+ )+async def upload_file_to_sandbox(self,sandbox_id: str,sandbox_path: str,content: bytes,) -> None:+ async with self._lock:+ ref = self._get_sandbox(sandbox_id)+ if ref.phase != SandboxPhase.READY:+ raise SandboxStateError(+ f"Cannot upload to sandbox '{sandbox_id}': state is {ref.phase.value}"+ )+self.audit.log(AuditEventType.FILE_TRANSFER,sandbox_id,@@ -348,31 +386,63 @@ class SandboxManager:sandbox_path=sandbox_path,)- encoded_content = base64.b64encode(content)+ # Fast path: tell the in-sandbox daemon to write the file in its+ # own process. The daemon already runs with the sandbox uid/gid,+ # mount layout, seccomp filter, and Landlock ruleset, so doing+ # the write in-process is exactly equivalent (security-wise) to+ # spawning ``bash -c 'cat > "$target"'`` but skips the bash+ # cold-start and an extra fork/exec roundtrip per upload.+ result = await self.runtime.write_file(+ sandbox_id,+ sandbox_path,+ content,+ mkdir_parents=True,+ )+ if result.ok:+ return++ if result.error in ("daemon_unavailable", "transport_failure", "unsupported"):+ await self._upload_via_exec_fallback(sandbox_id, sandbox_path, content)+ return++ detail = result.detail or result.error or "unknown failure"+ raise SandboxStateError(+ f"Failed to upload file to '{sandbox_path}': {detail}"+ )++ async def _upload_via_exec_fallback(+ self,+ sandbox_id: str,+ sandbox_path: str,+ content: bytes,+ ) -> None:+ """Legacy ``bash + cat`` upload path used only when the IPC fast+ path is unavailable (e.g. an older runtime adapter, or a sandbox+ whose daemon flagged itself unhealthy mid-request)."""upload_script = textwrap.dedent("""set -euo pipefailtarget="$1"- parent=$(/usr/bin/dirname -- "$target") || {+ parent=$(dirname -- "$target") || {status=$?printf "dirname failed for upload target '%s' (exit %s)\\n" "$target" "$status" >&2exit "$status"}- /usr/bin/mkdir -p -- "$parent" || {+ mkdir -p -- "$parent" || {status=$?- uid=$(/usr/bin/id -u 2>/dev/null || true)- gid=$(/usr/bin/id -g 2>/dev/null || true)- parent_parent=$(/usr/bin/dirname -- "$parent" 2>/dev/null || true)+ uid=$(id -u 2>/dev/null || true)+ gid=$(id -g 2>/dev/null || true)+ parent_parent=$(dirname -- "$parent" 2>/dev/null || true)printf "mkdir failed: parent='%s' target='%s'\\n" "$parent" "$target" >&2printf "sandbox identity: uid=%s gid=%s exit=%s\\n" "$uid" "$gid" "$status" >&2if [ -n "$parent_parent" ]; then- /usr/bin/ls -ld -- "$parent_parent" "$parent" >&2 || true+ ls -ld -- "$parent_parent" "$parent" >&2 || truefiexit "$status"}- /usr/bin/base64 -d > "$target" || {+ cat > "$target" || {status=$?- printf "base64 decode/write failed: target='%s' exit=%s\\n" "$target" "$status" >&2+ printf "write failed: target='%s' exit=%s\\n" "$target" "$status" >&2exit "$status"}"""@@ -381,13 +451,13 @@ class SandboxManager:sandbox_id,SandboxExecRequest(command=[- "/usr/bin/bash",+ "bash","-c",upload_script,"jiuwenbox-upload",sandbox_path,],- stdin_data=encoded_content,+ stdin_data=content,),)if result.exit_code != 0:@@ -403,6 +473,13 @@ class SandboxManager:sandbox_id: str,sandbox_path: str,) -> bytes:+ async with self._lock:+ ref = self._get_sandbox(sandbox_id)+ if ref.phase != SandboxPhase.READY:+ raise SandboxStateError(+ f"Cannot download from sandbox '{sandbox_id}': state is {ref.phase.value}"+ )+self.audit.log(AuditEventType.FILE_TRANSFER,sandbox_id,@@ -410,18 +487,49 @@ class SandboxManager:sandbox_path=sandbox_path,)+ # Fast path: ask the daemon to read the file directly. The daemon+ # carries the sandbox's full security envelope so it cannot read+ # any path that user code couldn't read. Binary content survives+ # the IPC unchanged - no base64 round-trip.+ result = await self.runtime.read_file(sandbox_id, sandbox_path)+ if result.ok:+ return result.content or b""++ if result.error == "not_found":+ raise FileNotFoundError(sandbox_path)+ if result.error in ("is_directory", "is_a_directory"):+ raise SandboxStateError(f"Sandbox path '{sandbox_path}' is a directory")+ if result.error == "is_symlink":+ raise SandboxStateError(+ f"Refusing to follow symlink at '{sandbox_path}'"+ )+ if result.error in ("daemon_unavailable", "transport_failure", "unsupported"):+ return await self._download_via_exec_fallback(sandbox_id, sandbox_path)++ detail = result.detail or result.error or "unknown failure"+ raise SandboxStateError(+ f"Failed to download file from '{sandbox_path}': {detail}"+ )++ async def _download_via_exec_fallback(+ self,+ sandbox_id: str,+ sandbox_path: str,+ ) -> bytes:+ """Legacy bash+base64 download path used only when the IPC fast+ path is unavailable."""result = await self.exec_in_sandbox(sandbox_id,SandboxExecRequest(command=[- "/usr/bin/bash",+ "bash","-c",("set -euo pipefail; "'target="$1"; ''if [ ! -e "$target" ]; then exit 44; fi; ''if [ -d "$target" ]; then exit 45; fi; '- '/usr/bin/base64 -w 0 -- "$target"'+ 'base64 -w 0 -- "$target"'),"jiuwenbox-download",sandbox_path,@@ -449,6 +557,48 @@ class SandboxManager:sandbox_id: str,request: SandboxListRequest,) -> list[dict[str, object]]:+ async with self._lock:+ ref = self._get_sandbox(sandbox_id)+ if ref.phase != SandboxPhase.READY:+ raise SandboxStateError(+ f"Cannot list files in sandbox '{sandbox_id}': state is {ref.phase.value}"+ )++ # Fast path: ask the daemon to walk the directory in-process.+ # Saves the python3 cold start and the fork+exec that the legacy+ # helper paid on every call.+ result = await self.runtime.list_dir(+ sandbox_id,+ request.sandbox_path,+ recursive=request.recursive,+ max_depth=request.max_depth,+ include_files=request.include_files,+ include_dirs=request.include_dirs,+ )+ if result.ok:+ return list(result.items or [])++ if result.error == "not_found":+ raise FileNotFoundError(request.sandbox_path)+ if result.error in ("not_a_directory", "is_not_a_directory"):+ raise SandboxStateError(+ f"Sandbox path '{request.sandbox_path}' is not a directory"+ )+ if result.error in ("daemon_unavailable", "transport_failure", "unsupported"):+ return await self._list_via_exec_fallback(sandbox_id, request)++ detail = result.detail or result.error or "unknown failure"+ raise SandboxStateError(+ f"Failed to list files in '{request.sandbox_path}': {detail}"+ )++ async def _list_via_exec_fallback(+ self,+ sandbox_id: str,+ request: SandboxListRequest,+ ) -> list[dict[str, object]]:+ """Legacy ``python3`` helper kept for runtimes without a daemon+ IPC channel."""script = textwrap.dedent("""import datetime@@ -508,7 +658,8 @@ class SandboxManager:sandbox_id,SandboxExecRequest(command=[- "/usr/bin/python3",+ "python3",+ "-S","-c",script,request.sandbox_path,@@ -522,7 +673,9 @@ class SandboxManager:if result.exit_code == 44:raise FileNotFoundError(request.sandbox_path)if result.exit_code == 45:- raise SandboxStateError(f"Sandbox path '{request.sandbox_path}' is not a directory")+ raise SandboxStateError(+ f"Sandbox path '{request.sandbox_path}' is not a directory"+ )if result.exit_code != 0:raise SandboxStateError(f"Failed to list files in '{request.sandbox_path}': {result.stderr or result.stdout}"@@ -586,8 +739,11 @@ class SandboxManager:result = await self.exec_in_sandbox(sandbox_id,SandboxExecRequest(+ # ``-S`` skips ``import site`` for the in-sandbox python3 cold+ # start; the helper script only needs the standard library.command=[- "/usr/bin/python3",+ "python3",+ "-S","-c",script,sandbox_path,diff --git a/jiuwenbox/src/jiuwenbox/server/workspace.py b/jiuwenbox/src/jiuwenbox/server/workspace.pynew file mode 100644index 0000000000..06e10650db--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/server/workspace.py@@ -0,0 +1,20 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Server-managed workspace paths."""++from __future__ import annotations++import os+import pwd+from pathlib import Path+++def _effective_user_home() -> Path:+ """Return the effective user's home directory without trusting $HOME."""+ try:+ return Path(pwd.getpwuid(os.geteuid()).pw_dir)+ except KeyError:+ return Path.home()+++JIUWENBOX_HOME = _effective_user_home() / ".jiuwenbox"+SANDBOX_WORKSPACE = JIUWENBOX_HOME / "workspace"diff --git a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.pyindex 105750f56c..b02785a981 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py@@ -14,6 +14,7 @@ import subprocessfrom dataclasses import dataclass, fieldfrom typing import IO+from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.policy import (CapabilityPolicy,FilesystemPolicy,@@ -24,10 +25,10 @@ from jiuwenbox.models.policy import (SecurityPolicy,)-logging.basicConfig(level=logging.INFO)+configure_logging()logger = logging.getLogger(__name__)-BWRAP_BINARY = "/usr/bin/bwrap"+BWRAP_BINARY = "bwrap"def _normalize_capability(capability: str) -> str:@@ -118,6 +119,7 @@ class BwrapConfig:cls._apply_namespace(cfg, policy.namespace)cls._apply_capabilities(cfg, policy.capabilities)cls._apply_network(cfg, policy.network)+ cls._apply_environment(cfg, policy.environment)return cfgdef add_dir_mount(self, path: str, permissions: str | None = None) -> None:@@ -177,6 +179,10 @@ class BwrapConfig:def _apply_network(cfg: BwrapConfig, net: NetworkPolicy) -> None:cfg.unshare_net = net.mode == NetworkMode.ISOLATED+ @staticmethod+ def _apply_environment(cfg: BwrapConfig, environment: dict[str, str]) -> None:+ cfg.env.update(environment)+def to_args(self) -> list[str]:"""Convert this config into a bwrap argument list."""args: list[str] = [BWRAP_BINARY]diff --git a/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.py b/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.pynew file mode 100644index 0000000000..32e11fa1f5--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.py@@ -0,0 +1,128 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""IPC protocol shared between box-server and the in-sandbox daemon.++The protocol is intentionally tiny: every message is a single 4-byte+big-endian length prefix followed by exactly that many bytes of payload.+JSON objects describe the request/response semantics, while raw bytes+(stdin contents, captured stdout/stderr) ride alongside as additional+length-prefixed frames so we can carry binary payloads safely.++Stays standard-library only so the daemon (loaded with ``python3 -S``+inside the sandbox) does not have to drag in the rest of jiuwenbox to+participate in IPC.+"""++from __future__ import annotations++import socket+import struct+from typing import Any++# Names match between server and daemon; do not rename without bumping the+# protocol version below. Both the daemon script and the Landlock launcher+# live under ``/jiuwenbox`` (a fresh tmpfs created per sandbox by the+# runtime). The directory is reserved by ``PolicyEngine`` - user policies+# cannot reference any path under it - so collisions with+# ``read_only`` / ``read_write`` / ``bind_mounts`` / ``device`` entries+# are rejected at policy-validation time, and ``/jiuwenbox`` is also kept+# *outside* the Landlock allowlist so user code spawned by the daemon+# cannot read either script after Landlock applies.+SANDBOX_RESERVED_DIR = "/jiuwenbox"+SANDBOX_DAEMON_SANDBOX_PATH = f"{SANDBOX_RESERVED_DIR}/sandbox-daemon.py"+SANDBOX_CONTROL_SOCKET_NAME = "control.sock"+SANDBOX_LAUNCHER_PATH = f"{SANDBOX_RESERVED_DIR}/landlock-launcher.py"++# Box-server binds the listener Unix socket on the host filesystem and+# passes the listener fd into the sandbox via+# ``subprocess.Popen(pass_fds=...)``. Bubblewrap's user command path never+# closes arbitrary inherited fds, so the listener flows untouched through+# bwrap → launcher → daemon. The daemon recovers the fd number from this+# environment variable and runs ``accept`` against it directly. This+# keeps the IPC channel entirely outside the sandbox view: there is no+# path inside the sandbox that points at the control socket, so user+# code spawned by the daemon cannot reach it (and the daemon spawns user+# children with ``close_fds=True`` so the inherited fd is not exposed+# either).+LISTENER_FD_ENV = "JIUWENBOX_CONTROL_LISTENER_FD"++# Daemon argv vector. ``-S`` shaves the ``import site`` cost so the daemon+# starts faster; the daemon is stdlib-only so ``site`` is unnecessary.+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/+# python helpers via ``REQUEST_TYPE_EXEC`` so upload/download/list pay no+# python cold-start or fork+exec cost. The daemon performs the operation+# directly in its own process, so namespaces, mount layout, the policy+# uid/gid, seccomp and Landlock all apply identically to what a child+# would see.+REQUEST_TYPE_WRITE_FILE = "write_file"+REQUEST_TYPE_READ_FILE = "read_file"+REQUEST_TYPE_LIST_DIR = "list_dir"++PROTOCOL_VERSION = 1+MAX_HEADER_BYTES = 1 * 1024 * 1024 # 1 MiB JSON header upper bound+MAX_STDIN_BYTES = 64 * 1024 * 1024 # 64 MiB stdin upper bound+MAX_STDOUT_BYTES = 64 * 1024 * 1024 # 64 MiB stdout upper bound+MAX_STDERR_BYTES = 64 * 1024 * 1024 # 64 MiB stderr upper bound+MAX_FILE_BYTES = 256 * 1024 * 1024 # 256 MiB read/write upper bound++ACCEPT_BACKLOG = 128+++def recv_exact(sock: socket.socket, n: int) -> bytes:+ """Read exactly ``n`` bytes from ``sock`` or raise ``ConnectionError``."""+ if n == 0:+ return b""+ buf = bytearray()+ while len(buf) < n:+ chunk = sock.recv(n - len(buf))+ if not chunk:+ raise ConnectionError(+ f"socket closed after {len(buf)}/{n} bytes",+ )+ buf.extend(chunk)+ return bytes(buf)+++def send_frame(sock: socket.socket, payload: bytes) -> None:+ """Send a single length-prefixed frame on ``sock``."""+ if len(payload) > 0xFFFFFFFF:+ raise ValueError(f"frame size {len(payload)} exceeds 4 GiB")+ sock.sendall(struct.pack(">I", len(payload)))+ if payload:+ sock.sendall(payload)+++def recv_frame(sock: socket.socket, max_size: int) -> bytes:+ """Receive a single length-prefixed frame, enforcing ``max_size``."""+ header = recv_exact(sock, 4)+ (size,) = struct.unpack(">I", header)+ if size > max_size:+ raise ValueError(+ f"incoming frame size {size} exceeds limit {max_size}",+ )+ return recv_exact(sock, size)+++def encode_request(+ *,+ request_type: str,+ payload: dict[str, Any] | None = None,+) -> bytes:+ import json+ body: dict[str, Any] = {+ "v": PROTOCOL_VERSION,+ "type": request_type,+ }+ 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/landlock.py b/jiuwenbox/src/jiuwenbox/supervisor/landlock.pyindex 433acd92d2..fdebdb3480 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/landlock.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/landlock.py@@ -40,6 +40,11 @@ def encode_landlock_payload(policy: SecurityPolicy) -> str:read_write.append(directory)else:read_write.append(directory.path)+ for file in policy.filesystem_policy.files:+ if isinstance(file, str):+ read_write.append(file)+ else:+ read_write.append(file.path)for mount in policy.filesystem_policy.bind_mounts:if mount.mode == "ro":read_only.append(mount.sandbox_path)@@ -50,6 +55,27 @@ def encode_landlock_payload(policy: SecurityPolicy) -> str:# These pseudo-filesystems are created by bwrap and are needed by common runtimes.read_only.append("/proc")read_write.append("/dev")+ # ``/jiuwenbox`` is intentionally NOT added here. The runtime mounts+ # the Landlock launcher and the in-sandbox daemon script under that+ # reserved subtree, and the Python interpreter only needs to read+ # them *before* Landlock is active:+ # * the launcher script is loaded by ``python3`` before any user+ # code in this process runs, so ``/jiuwenbox`` is still openable+ # at that point;+ # * the daemon script is read into memory by the launcher in the+ # same window and then ``compile``/``exec``ed in-process - no+ # further on-disk access is required after Landlock applies.+ # Keeping ``/jiuwenbox`` outside the allowlist guarantees that user+ # code spawned by the daemon cannot read the launcher or daemon+ # scripts (and therefore cannot inspect or replace them), which is+ # what ``test_landlock_rules_allow_policy_paths_and_deny_other_mounted_paths``+ # and the ``/jiuwenbox`` runtime-script integrity tests pin.+ # ``PolicyEngine._RESERVED_SANDBOX_PATHS`` is the policy-validation+ # mirror of this invariant: any user policy that tries to add+ # ``/jiuwenbox`` (or anything under it) to ``read_only`` /+ # ``read_write`` / ``directories`` / ``files`` / ``bind_mounts`` /+ # ``device`` is rejected at sandbox creation time so the allowlist+ # below cannot be widened from the outside.payload = {"compatibility": policy.landlock.compatibility,diff --git a/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py b/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.pyindex 48472cccaa..98ebefecf2 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py@@ -2,8 +2,26 @@"""In-sandbox Landlock launcher.This module is executed inside bubblewrap after mounts/namespaces are in place.-It applies Landlock to itself, then execs the target command so restrictions are-inherited by the sandboxed program.+It pre-reads the in-sandbox daemon script, applies Landlock to itself, and+then runs the daemon code in the same Python process via ``compile`` + ``exec``.+No further ``execve`` happens between Landlock setup and the daemon, so the+daemon (and every child it spawns) inherits the Landlock ruleset directly+without ever needing the daemon script's on-disk path to remain readable.++This is what lets us keep ``/jiuwenbox`` *outside* the Landlock allowlist:+only the launcher (loaded before Landlock) and the daemon source (read+into memory before Landlock) need access to that subtree. After Landlock+applies, user code spawned by the daemon cannot read ``/jiuwenbox`` at+all, which is the property+``test_landlock_rules_allow_policy_paths_and_deny_other_mounted_paths``+and the runtime-script integrity tests rely on. The mirror invariant -+that user policies cannot punch ``/jiuwenbox`` back into the Landlock+allowlist via ``read_only`` / ``read_write`` / ``bind_mounts`` etc. -+is enforced by ``PolicyEngine._RESERVED_SANDBOX_PATHS``.++This module deliberately depends on the standard library only so the in-sandbox+Python interpreter does not have to load the rest of jiuwenbox before launching+the daemon. That keeps per-sandbox cold-start overhead low."""from __future__ import annotations@@ -21,8 +39,7 @@ LANDLOCK_RESTRICT_SELF = 446LANDLOCK_RULE_PATH_BENEATH = 1PR_SET_NO_NEW_PRIVS = 38-logging.basicConfig(level=logging.INFO)-logger = logging.getLogger(__name__)+logger = logging.getLogger("jiuwenbox.landlock_launcher")READ_FILE = 1 << 2READ_DIR = 1 << 3@@ -191,25 +208,119 @@ def apply_landlock(payload: dict) -> None:os.close(ruleset_fd)-def main() -> int:- if len(sys.argv) < 4 or sys.argv[2] != "--":+def _run_daemon_in_process(daemon_path: str, payload: dict) -> int:+ """Apply Landlock and run the daemon script in this Python process.++ The daemon source is read **before** ``apply_landlock`` so the+ ``/jiuwenbox`` directory containing the daemon script can be locked+ away by Landlock immediately afterward. Running the daemon in-process+ (no second ``execve``) is what lets the daemon - and every user+ child it spawns - inherit Landlock without ever needing the on-disk+ daemon script to remain reachable. That keeps ``/jiuwenbox`` outside+ the Landlock allowlist, which matters for the policy-enforcement+ tests.++ ``__name__`` is deliberately **not** set to ``"__main__"`` so the+ ``if __name__ == "__main__": raise SystemExit(main())`` guard at the+ bottom of the daemon script does not fire. We call ``main()`` directly+ instead and use its int return value, which avoids ``except SystemExit``+ in this function (G.ERR.11).+ """+ try:+ with open(daemon_path, "rb") as fh:+ daemon_source = fh.read()+ except OSError as exc:+ logger.error("Failed to read daemon script %s: %s", daemon_path, exc)+ return 2++ try:+ apply_landlock(payload)+ except LandlockHardRequirementError:+ return 126++ daemon_globals: dict = {+ "__name__": "jiuwenbox.supervisor.sandbox_daemon_inproc",+ "__file__": daemon_path,+ }+ try:+ compiled = compile(daemon_source, daemon_path, "exec")+ except SyntaxError as exc:+ logger.error("Failed to compile daemon script %s: %s", daemon_path, exc)+ return 2+ exec(compiled, daemon_globals)++ daemon_main = daemon_globals.get("main")+ if not callable(daemon_main):logger.error(- "Usage: landlock_launcher.py <payload> -- <command> [args...]",+ "Daemon script %s does not expose a callable ``main`` symbol",+ daemon_path,)return 2+ result = daemon_main()+ try:+ return int(result) if result is not None else 0+ except (TypeError, ValueError):+ return 1+- payload = _decode_payload(sys.argv[1])- command = sys.argv[3:]+def _run_command(command: list[str], payload: dict) -> int:+ """Apply Landlock and ``execvp`` the user command (legacy path).++ Used by ``exec_background``-style callers that still spawn a fresh+ bubblewrap per command and need Landlock to be inherited by the+ user binary they exec into.+ """try:apply_landlock(payload)- os.execvp(command[0], command)except LandlockHardRequirementError:return 126+ try:+ os.execvp(command[0], command)except OSError as exc:logger.error("Failed to exec command %s: %s", command[0], exc)return 127return 0+def main() -> int:+ """Dispatch between the daemon and generic-exec launcher modes.++ Layouts:+ ``landlock_launcher.py PAYLOAD --daemon DAEMON_SCRIPT_PATH``+ Apply Landlock and run the daemon script via ``compile``/``exec``.+ ``landlock_launcher.py PAYLOAD -- COMMAND [ARGS...]``+ Apply Landlock and ``execvp`` the user command (legacy path,+ used by ``exec_background`` for one-shot bwrap invocations).+ """+ if len(sys.argv) < 4:+ logger.error(+ "Usage: landlock_launcher.py <payload> --daemon <daemon_script>"+ " | landlock_launcher.py <payload> -- <command> [args...]",+ )+ return 2++ payload_b64 = sys.argv[1]+ mode_token = sys.argv[2]++ try:+ payload = _decode_payload(payload_b64)+ except ValueError as exc:+ # ``ValueError`` already covers ``json.JSONDecodeError`` (G.ERR.09).+ logger.error("Failed to decode landlock payload: %s", exc)+ return 2++ if mode_token == "--daemon":+ return _run_daemon_in_process(sys.argv[3], payload)+ if mode_token == "--":+ command = sys.argv[3:]+ if not command:+ logger.error("Generic launcher mode requires a command after '--'")+ return 2+ return _run_command(command, payload)++ logger.error("Unknown launcher mode token %r", mode_token)+ return 2++if __name__ == "__main__":raise SystemExit(main())diff --git a/jiuwenbox/src/jiuwenbox/supervisor/main.py b/jiuwenbox/src/jiuwenbox/supervisor/main.pyindex 165979f711..3af2650456 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/main.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/main.py@@ -14,17 +14,50 @@ from pathlib import Pathimport yaml+from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.policy import NetworkMode, SecurityPolicyfrom jiuwenbox.supervisor.bwrap import BwrapConfig, BwrapProcessfrom jiuwenbox.supervisor.landlock import encode_landlock_payload+from jiuwenbox.supervisor.daemon_ipc import SANDBOX_RESERVED_DIRfrom jiuwenbox.supervisor.sandbox_daemon import (SANDBOX_DAEMON_COMMAND,SANDBOX_DAEMON_SANDBOX_PATH,+ SANDBOX_LAUNCHER_PATH,)from jiuwenbox.supervisor.seccomp import open_seccomp_filter-logging.basicConfig(level=logging.INFO)+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 workdirclass Supervisor:@@ -81,9 +114,9 @@ class Supervisor:config.unshare_net = False@staticmethod- def _setup_policy_directory_mounts(config: BwrapConfig) -> None:- """Attach server-created lifecycle directories to their sandbox paths."""- raw_binds = os.environ.get("JIUWENBOX_DIRECTORY_BINDS")+ 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@@ -96,7 +129,7 @@ class Supervisor:returndaemon_path = Path(__file__).with_name("sandbox_daemon.py")- temp_daemon_path = temp_dir / "jiuwenbox-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@@ -111,17 +144,20 @@ class Supervisor:returnlauncher_path = Path(__file__).with_name("landlock_launcher.py")- temp_launcher_path = temp_dir / "jiuwenbox-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_launcher_path = "/run/jiuwenbox-landlock-launcher.py"- config.add_dir_mount("/run")- config.ro_binds.append((str(self._landlock_launcher_path), sandbox_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 = [- "/usr/bin/python3",- sandbox_launcher_path,+ "python3",+ SANDBOX_LAUNCHER_PATH,encode_landlock_payload(self.policy),"--",*config.command,@@ -137,7 +173,7 @@ class Supervisor:if self.workdir:config.workdir = self.workdirself._setup_network_namespace(config)- self._setup_policy_directory_mounts(config)+ self._setup_policy_bind_mounts(config)self._setup_sandbox_daemon_mount(config, Path(temp_dir))self._setup_landlock_launcher(config, Path(temp_dir))@@ -192,16 +228,20 @@ async def run_supervisor(env: dict[str, str] | None = None,) -> int:"""High-level entry point: load policy and run the sandbox."""- supervisor = Supervisor.from_policy_file(policy_path, command, workdir=workdir, env=env)+ 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)."""- logging.basicConfig(- level=logging.INFO,- format="[%(asctime)s] %(name)s %(levelname)s: %(message)s",- )+ configure_logging()if len(sys.argv) < 3:logger.error("Usage: %s <policy.yaml> <command> [args...]", sys.argv[0])diff --git a/jiuwenbox/src/jiuwenbox/supervisor/network.py b/jiuwenbox/src/jiuwenbox/supervisor/network.pyindex 282535f8ff..d7cdc739a2 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/network.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/network.py@@ -14,18 +14,19 @@ import subprocessfrom dataclasses import dataclass, fieldfrom functools import lru_cache+from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.policy import NetworkPolicy, NetworkMode, NetworkRulePolicy-logging.basicConfig(level=logging.INFO)+configure_logging()logger = logging.getLogger(__name__)-IP_BINARY = "/usr/sbin/ip"-IPTABLES_BINARY = "/usr/sbin/iptables"-IP6TABLES_BINARY = "/usr/sbin/ip6tables"-IPTABLES_LEGACY_BINARY = "/usr/sbin/iptables-legacy"-IP6TABLES_LEGACY_BINARY = "/usr/sbin/ip6tables-legacy"-IPTABLES_NFT_BINARY = "/usr/sbin/iptables-nft"-IP6TABLES_NFT_BINARY = "/usr/sbin/ip6tables-nft"+IP_BINARY = "ip"+IPTABLES_BINARY = "iptables"+IP6TABLES_BINARY = "ip6tables"+IPTABLES_LEGACY_BINARY = "iptables-legacy"+IP6TABLES_LEGACY_BINARY = "ip6tables-legacy"+IPTABLES_NFT_BINARY = "iptables-nft"+IP6TABLES_NFT_BINARY = "ip6tables-nft"class NetworkSetupError(RuntimeError):@@ -159,7 +160,7 @@ def _run_iptables_binary(def _select_iptables_binary(ip_version: int, namespace: str | None = None) -> str:"""Return a working iptables backend for the target namespace.- Some distributions default /usr/sbin/iptables to the nf_tables backend,+ Some distributions default iptables to the nf_tables backend,while older or constrained kernels only support legacy xtables. Probe bothand keep the sandbox creation failure explicit if neither backend works."""@@ -197,6 +198,21 @@ def _run_iptables(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).versiondiff --git a/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py b/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.pyindex 26d49a7433..e3214dda67 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py@@ -1,27 +1,825 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-"""Long-running in-sandbox daemon used to hold a sandbox lifecycle open."""+"""Long-running in-sandbox daemon that handles ``exec`` requests.++The previous implementation was a placeholder that just blocked on+``signal.pause`` so the sandbox lifecycle stayed alive. To make exec+calls cheap, the daemon now hosts a Unix-socket IPC server inside the+sandbox: box-server connects to the socket and sends ``exec`` requests+that the daemon services by ``fork+exec``-ing the user command. Because+the daemon already has bubblewrap's namespaces, mounts, seccomp, and+Landlock applied, every spawned child inherits the same isolation - the+expensive ``bwrap`` setup happens once per sandbox lifecycle instead of+once per exec.++How the daemon is started+-------------------------+Inside the sandbox the Landlock launcher (see ``landlock_launcher.py``)+reads this script's source from ``/jiuwenbox`` *before* applying+Landlock and then runs the daemon code with ``compile``/``exec`` in the+launcher's own Python process. There is **no** second ``execve`` after+Landlock is locked in, which is what allows the ``/jiuwenbox`` directory+to be omitted from the Landlock allowlist: nothing in the sandbox needs+to read the daemon script from disk after Landlock applies. From the+kernel's point of view the daemon and the launcher are the same Linux+process (PID 1 of the sandbox PID namespace). The directory is reserved+by ``PolicyEngine`` so user policies cannot reference it; see+``_RESERVED_SANDBOX_PATHS`` in ``jiuwenbox/server/policy_engine.py``.++The control socket itself lives on the **host** filesystem; box-server+``bind()``s and ``listen()``s before spawning bubblewrap, then passes+the listener file descriptor into the sandbox via+``subprocess.Popen(pass_fds=...)``. Bubblewrap's user command path+never closes arbitrary inherited fds (only its own monitor/PID-1 paths+do), so the listener fd flows naturally through the bwrap → launcher+chain. The daemon recovers the fd from ``JIUWENBOX_CONTROL_LISTENER_FD``+and ``accept()``s against it. This keeps the IPC channel entirely+outside any sandbox-visible path, so user code spawned by the daemon+cannot reach (or delete) the listener.++Important security notes:++* The daemon does **not** install signal handlers. Inside the sandbox's+ PID namespace the daemon runs as PID 1; the kernel drops signals from+ other namespace members targeting an init that has not registered a+ handler, so a sandboxed payload cannot kill the daemon. Box-server+ shuts the daemon down via the ``shutdown`` IPC command (graceful) or+ ``SIGKILL`` from outside the namespace (forced).++* Children are spawned via :func:`subprocess.Popen` so the kernel does+ the standard ``fork``/``execve`` pair. The seccomp BPF filter and+ Landlock ruleset that bwrap and the launcher installed before running+ the daemon are inherited by every child - they cannot be relaxed or+ stripped from inside the sandbox. ``close_fds=True`` (the Python+ default) ensures the listener fd is **not** inherited by user code.++The module deliberately stays standard-library-only so it can be+launched with ``python3 -S`` (no ``import site``) for fastest cold+start, and so the launcher's ``compile``/``exec`` step does not need to+reach outside the standard library to load the daemon.+"""from __future__ import annotations-import signal+import contextlib+import datetime+import errno+import json+import logging+import os+import socket+import struct+import subprocess+import sysimport threading+import time+from collections.abc import Iterator+from typing import Any++# These constants are duplicated from ``daemon_ipc`` so the in-sandbox+# daemon does not need to import the package; the script is mounted at+# ``/jiuwenbox/sandbox-daemon.py`` and executed directly. Any change must+# be mirrored in ``daemon_ipc.py``.+SANDBOX_RESERVED_DIR = "/jiuwenbox"+SANDBOX_DAEMON_SANDBOX_PATH = f"{SANDBOX_RESERVED_DIR}/sandbox-daemon.py"+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"+REQUEST_TYPE_READ_FILE = "read_file"+REQUEST_TYPE_LIST_DIR = "list_dir"++PROTOCOL_VERSION = 1+MAX_HEADER_BYTES = 1 * 1024 * 1024+MAX_STDIN_BYTES = 64 * 1024 * 1024+MAX_FILE_BYTES = 256 * 1024 * 1024++ACCEPT_TIMEOUT_SECONDS = 1.0+SHUTDOWN_DRAIN_TIMEOUT_SECONDS = 30.0++logger = logging.getLogger("jiuwenbox.sandbox_daemon")+++def _recv_exact(sock: socket.socket, n: int) -> bytes:+ if n == 0:+ return b""+ buf = bytearray()+ while len(buf) < n:+ chunk = sock.recv(n - len(buf))+ if not chunk:+ raise ConnectionError(+ f"socket closed after {len(buf)}/{n} bytes",+ )+ buf.extend(chunk)+ return bytes(buf)+++def _send_frame(sock: socket.socket, payload: bytes) -> None:+ if len(payload) > 0xFFFFFFFF:+ raise ValueError(f"frame size {len(payload)} exceeds 4 GiB")+ sock.sendall(struct.pack(">I", len(payload)))+ if payload:+ sock.sendall(payload)+++def _recv_frame(sock: socket.socket, max_size: int) -> bytes:+ header = _recv_exact(sock, 4)+ (size,) = struct.unpack(">I", header)+ if size > max_size:+ raise ValueError(+ f"incoming frame size {size} exceeds limit {max_size}",+ )+ return _recv_exact(sock, size)+++def _send_response(sock: socket.socket, response: dict[str, Any]) -> None:+ body = json.dumps(response, ensure_ascii=False).encode("utf-8")+ _send_frame(sock, body)+++def _exec_response(+ *,+ exit_code: int,+ stdout: str = "",+ stderr: str = "",+ started: bool = True,+ error: str | None = None,+) -> dict[str, Any]:+ response: dict[str, Any] = {+ "v": PROTOCOL_VERSION,+ "ok": started,+ "exit_code": exit_code,+ "stdout": stdout,+ "stderr": stderr,+ }+ if error:+ response["error"] = error+ return response+++def _stringify_command(command: list[Any]) -> list[str]:+ return [str(item) for item in command]+++def _normalize_env(env: Any) -> dict[str, str] | None:+ if env is None:+ return None+ if not isinstance(env, dict):+ raise ValueError("env must be a JSON object")+ return {str(key): str(value) for key, value in env.items()}+++class DaemonState:+ """Shared mutable state guarded by ``lock``."""++ def __init__(self) -> None:+ self.shutdown_event = threading.Event()+ self.in_flight = 0+ self.lock = threading.Lock()+ self.completion = threading.Condition(self.lock)++ def begin_request(self) -> None:+ with self.lock:+ self.in_flight += 1++ def end_request(self) -> None:+ with self.lock:+ self.in_flight -= 1+ if self.in_flight <= 0:+ self.completion.notify_all()++ def wait_drain(self, timeout: float) -> bool:+ deadline = time.monotonic() + max(0.0, timeout)+ with self.lock:+ while self.in_flight > 0:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return False+ self.completion.wait(timeout=remaining)+ return True+++def _handle_exec(conn: socket.socket, header: dict[str, Any], state: DaemonState) -> None:+ """Run a single user command and stream the result back to ``conn``."""+ try:+ command = header.get("command")+ if not isinstance(command, list) or not command:+ _send_response(+ conn,+ _exec_response(+ exit_code=2,+ stderr="exec request missing 'command'",+ started=False,+ error="bad_request",+ ),+ )+ return+ command = _stringify_command(command)++ env_override = _normalize_env(header.get("env"))+ workdir = header.get("workdir")+ if workdir is not None and not isinstance(workdir, str):+ raise ValueError("workdir must be a string")+ timeout = header.get("timeout")+ if timeout is not None and not isinstance(timeout, (int, float)):+ raise ValueError("timeout must be a number")+ stdin_size = int(header.get("stdin_size") or 0)+ if stdin_size < 0 or stdin_size > MAX_STDIN_BYTES:+ raise ValueError(f"invalid stdin_size {stdin_size}")++ stdin_bytes = _recv_exact(conn, stdin_size) if stdin_size else b""++ merged_env = dict(os.environ)+ # Children must not see the listener fd or the env var pointing at+ # it; ``close_fds=True`` (Python default) closes the fd, but we also+ # strip the env var so user code cannot trivially fingerprint the+ # daemon.+ merged_env.pop(LISTENER_FD_ENV, None)+ if env_override is not None:+ merged_env.update(env_override)++ proc_kwargs: dict[str, Any] = {+ "stdin": subprocess.PIPE if stdin_size else subprocess.DEVNULL,+ "stdout": subprocess.PIPE,+ "stderr": subprocess.PIPE,+ "env": merged_env,+ "close_fds": True,+ }+ if workdir:+ proc_kwargs["cwd"] = workdir++ try:+ proc = subprocess.Popen(command, **proc_kwargs)+ except OSError as exc:+ # ``OSError`` already covers ``FileNotFoundError`` and+ # ``PermissionError``; keep one branch (G.ERR.09).+ _send_response(+ conn,+ _exec_response(+ exit_code=127,+ stderr=f"failed to spawn command: {exc}",+ started=False,+ error="spawn_failed",+ ),+ )+ return++ try:+ stdout_bytes, stderr_bytes = proc.communicate(+ input=stdin_bytes if stdin_size else None,+ timeout=timeout,+ )+ response = _exec_response(+ exit_code=proc.returncode if proc.returncode is not None else 0,+ stdout=stdout_bytes.decode("utf-8", errors="replace"),+ stderr=stderr_bytes.decode("utf-8", errors="replace"),+ )+ except subprocess.TimeoutExpired:+ try:+ proc.kill()+ except ProcessLookupError:+ pass+ try:+ stdout_bytes, stderr_bytes = proc.communicate(timeout=5.0)+ except subprocess.TimeoutExpired:+ stdout_bytes, stderr_bytes = b"", b""+ stderr_text = stderr_bytes.decode("utf-8", errors="replace")+ stderr_text = (+ f"{stderr_text}\nCommand timed out"+ if stderr_text+ else "Command timed out"+ )+ response = _exec_response(+ exit_code=124,+ stdout=stdout_bytes.decode("utf-8", errors="replace"),+ stderr=stderr_text,+ error="timeout",+ )++ _send_response(conn, response)+ except (ValueError, ConnectionError) as exc:+ try:+ _send_response(+ conn,+ _exec_response(+ exit_code=2,+ stderr=str(exc),+ started=False,+ error="bad_request",+ ),+ )+ except OSError:+ pass+ except Exception as exc: # pragma: no cover - defensive guard+ logger.exception("Unhandled error while handling exec request")+ try:+ _send_response(+ conn,+ _exec_response(+ exit_code=1,+ stderr=f"daemon internal error: {exc}",+ started=False,+ error="internal",+ ),+ )+ except OSError:+ pass+++def _os_error_response(exc: OSError, fallback: str = "io_error") -> dict[str, Any]:+ """Build a JSON-friendly description of an ``OSError`` from a file op."""+ return {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": fallback,+ "errno": exc.errno or 0,+ "stderr": exc.strerror or str(exc),+ }+++def _handle_write_file(conn: socket.socket, header: dict[str, Any]) -> None:+ """Write a file on behalf of box-server, no child process involved.++ The daemon already runs inside the sandbox PID/mount/user namespaces+ with the policy uid/gid, Landlock ruleset, and seccomp filter applied,+ so doing this in-process is exactly equivalent to a sandboxed+ ``cat > path``: the same paths are reachable, the same uid owns the+ resulting file, and the same syscall filter is enforced. The win is+ that we avoid forking ``bash`` for every upload.+ """+ try:+ path = header.get("path")+ if not isinstance(path, str) or not path:+ raise ValueError("write_file request missing 'path'")+ content_size = int(header.get("content_size") or 0)+ if content_size < 0 or content_size > MAX_FILE_BYTES:+ raise ValueError(f"invalid content_size {content_size}")+ mkdir_parents = bool(header.get("mkdir_parents", True))+ mode = header.get("mode")+ if mode is not None and not isinstance(mode, int):+ raise ValueError("mode must be an integer")+ except ValueError as exc:+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "bad_request",+ "stderr": str(exc),+ },+ )+ return++ try:+ content = _recv_exact(conn, content_size) if content_size else b""+ except ConnectionError as exc:+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "bad_request",+ "stderr": f"truncated write_file payload: {exc}",+ },+ )+ return++ parent = os.path.dirname(path) or "/"+ if mkdir_parents and parent not in ("", "/"):+ try:+ os.makedirs(parent, exist_ok=True)+ except OSError as exc:+ _send_response(conn, _os_error_response(exc, "mkdir_failed"))+ return++ # Open with O_NOFOLLOW so a pre-existing symlink at ``path`` (which a+ # malicious user payload could have planted before the upload arrived)+ # cannot redirect the write to an attacker-chosen location. The link+ # would still be subject to Landlock, but refusing it outright keeps+ # the IPC fast path's behaviour aligned with what the previous+ # ``cat > $target`` pipeline produced.+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW+ try:+ fd = os.open(path, flags, mode if mode is not None else 0o644)+ except OSError as exc:+ _send_response(conn, _os_error_response(exc, "open_failed"))+ return+ try:+ try:+ if content:+ view = memoryview(content)+ offset = 0+ while offset < len(view):+ written = os.write(fd, view[offset:])+ if written <= 0:+ raise OSError(errno.EIO, "short write")+ offset += written+ except OSError as exc:+ _send_response(conn, _os_error_response(exc, "write_failed"))+ return+ finally:+ try:+ os.close(fd)+ except OSError:+ pass++ _send_response(conn, {"v": PROTOCOL_VERSION, "ok": True})+++def _handle_read_file(conn: socket.socket, header: dict[str, Any]) -> None:+ """Read a file in-process and stream it back as a single frame.++ Matches the safety properties of the previous ``base64 -w 0 -- $path``+ helper but without a ``bash`` cold start. The header is sent first+ with ``content_size``; the body frame follows so binary content+ survives intact (no base64 round-trip, no ``replace`` decoding).+ """+ path = header.get("path")+ if not isinstance(path, str) or not path:+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "bad_request",+ "stderr": "read_file request missing 'path'",+ },+ )+ return++ try:+ if os.path.islink(path):+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "is_symlink",+ "errno": errno.ELOOP,+ "stderr": f"refusing to read symlink {path!r}",+ },+ )+ return+ try:+ stat = os.stat(path, follow_symlinks=False)+ except FileNotFoundError as exc:+ _send_response(conn, _os_error_response(exc, "not_found"))+ return+ except IsADirectoryError as exc:+ _send_response(conn, _os_error_response(exc, "is_directory"))+ return+ if os.path.isdir(path):+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "is_directory",+ "errno": errno.EISDIR,+ "stderr": f"{path!r} is a directory",+ },+ )+ return+ if stat.st_size > MAX_FILE_BYTES:+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "too_large",+ "stderr": (+ f"file size {stat.st_size} exceeds limit "+ f"{MAX_FILE_BYTES}"+ ),+ },+ )+ return+ try:+ # ``mode`` is required by G.FIO.01 even though the kernel+ # ignores it without ``O_CREAT``; a placeholder of ``0o600``+ # documents the (would-be) least-privilege permission.+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW, 0o600)+ except OSError as exc:+ _send_response(conn, _os_error_response(exc, "open_failed"))+ return+ try:+ chunks: list[bytes] = []+ remaining = stat.st_size+ while remaining > 0:+ chunk = os.read(fd, min(remaining, 1 << 20))+ if not chunk:+ break+ chunks.append(chunk)+ remaining -= len(chunk)+ content = b"".join(chunks)+ finally:+ try:+ os.close(fd)+ except OSError:+ pass+ except OSError as exc:+ _send_response(conn, _os_error_response(exc, "read_failed"))+ return++ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": True,+ "content_size": len(content),+ },+ )+ _send_frame(conn, content)+++def _list_dir_entries(+ root: str,+ *,+ recursive: bool,+ max_depth: int | None,+ include_files: bool,+ include_dirs: bool,+) -> list[dict[str, Any]]:+ """Build the ``items`` payload for a list_dir response."""+ items: list[dict[str, Any]] = []+ pending: list[tuple[str, int]] = [(root, 0)]+ while pending:+ current, depth = pending.pop()+ try:+ iterator = os.scandir(current)+ except OSError:+ continue+ with iterator:+ for entry in iterator:+ try:+ stat = entry.stat(follow_symlinks=False)+ except OSError:+ continue+ rel_depth = depth + 1+ if max_depth is not None and rel_depth > max_depth:+ continue+ is_dir = entry.is_dir(follow_symlinks=False)+ if is_dir and recursive:+ pending.append((entry.path, rel_depth))+ if is_dir and not include_dirs:+ continue+ if not is_dir and not include_files:+ continue+ items.append({+ "name": entry.name,+ "path": entry.path,+ "size": 0 if is_dir else stat.st_size,+ "is_directory": is_dir,+ "modified_time": datetime.datetime.fromtimestamp(+ stat.st_mtime,+ ).isoformat(),+ "type": (+ None+ if is_dir+ else (os.path.splitext(entry.name)[1] or None)+ ),+ })+ items.sort(key=lambda item: item["path"])+ return items+++def _handle_list_dir(conn: socket.socket, header: dict[str, Any]) -> None:+ """List a directory tree from the daemon process."""+ path = header.get("path")+ if not isinstance(path, str) or not path:+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "bad_request",+ "stderr": "list_dir request missing 'path'",+ },+ )+ return+ recursive = bool(header.get("recursive", False))+ raw_max_depth = header.get("max_depth")+ if raw_max_depth is None:+ max_depth: int | None = None+ elif isinstance(raw_max_depth, int) and raw_max_depth >= 0:+ max_depth = raw_max_depth+ else:+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "bad_request",+ "stderr": "max_depth must be a non-negative integer",+ },+ )+ return+ include_files = bool(header.get("include_files", True))+ include_dirs = bool(header.get("include_dirs", True))++ if not os.path.exists(path):+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "not_found",+ "errno": errno.ENOENT,+ "stderr": f"path {path!r} does not exist",+ },+ )+ return+ if not os.path.isdir(path):+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "not_a_directory",+ "errno": errno.ENOTDIR,+ "stderr": f"path {path!r} is not a directory",+ },+ )+ return++ try:+ items = _list_dir_entries(+ path,+ recursive=recursive,+ max_depth=max_depth,+ include_files=include_files,+ include_dirs=include_dirs,+ )+ except OSError as exc:+ _send_response(conn, _os_error_response(exc, "list_failed"))+ return++ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": True,+ "items": items,+ },+ )+++def _handle_connection(conn: socket.socket, state: DaemonState) -> None:+ state.begin_request()+ try:+ try:+ header_bytes = _recv_frame(conn, MAX_HEADER_BYTES)+ except OSError:+ # ``OSError`` already covers ``ConnectionError`` (G.ERR.09).+ return+ try:+ header = json.loads(header_bytes.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "bad_request",+ "stderr": f"invalid request header: {exc}",+ },+ )+ return++ 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,+ {"v": PROTOCOL_VERSION, "ok": True, "type": "shutdown_ack"},+ )+ state.shutdown_event.set()+ elif request_type == REQUEST_TYPE_WRITE_FILE:+ _handle_write_file(conn, header)+ elif request_type == REQUEST_TYPE_READ_FILE:+ _handle_read_file(conn, header)+ elif request_type == REQUEST_TYPE_LIST_DIR:+ _handle_list_dir(conn, header)+ else:+ _send_response(+ conn,+ {+ "v": PROTOCOL_VERSION,+ "ok": False,+ "error": "unknown_request_type",+ "stderr": f"unknown request type: {request_type!r}",+ },+ )+ finally:+ try:+ conn.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ try:+ conn.close()+ except OSError:+ pass+ state.end_request()+++def _adopted_listener() -> Iterator[socket.socket]:+ """Recover the host-bound listener fd that box-server passed in.++ Box-server creates the Unix listening socket on its own filesystem and+ passes the resulting fd to bubblewrap via ``subprocess.Popen(pass_fds=...)``.+ Bubblewrap's user command path never closes arbitrary inherited fds, so+ by the time the daemon runs, the fd is already in our process and+ ready to ``accept()``. We wrap it in a Python socket object so the+ standard library accept loop works without re-binding (which Landlock+ would forbid, since the launcher applies the policy filesystem ruleset+ before exec'ing the daemon).-SANDBOX_DAEMON_SANDBOX_PATH = "/jiuwenbox-sandbox-daemon.py"-SANDBOX_DAEMON_COMMAND = ["/usr/bin/python3", SANDBOX_DAEMON_SANDBOX_PATH]+ Exposed as a context manager so resource acquisition (wrapping the+ pre-bound fd in a Python socket object) and release (closing that+ socket) live in the same lexical scope, satisfying the resource-pair+ requirement (G.PRM.03).+ """+ raw = os.environ.get(LISTENER_FD_ENV)+ if raw is None:+ raise RuntimeError(+ f"{LISTENER_FD_ENV} is not set; box-server must hand the daemon "+ "a pre-bound control listener fd",+ )+ try:+ fd = int(raw)+ except ValueError as exc:+ raise RuntimeError(+ f"{LISTENER_FD_ENV}={raw!r} is not an integer",+ ) from exc-_SHUTDOWN_EVENT = threading.Event()+ listener = socket.socket(+ family=socket.AF_UNIX,+ type=socket.SOCK_STREAM,+ fileno=fd,+ )+ try:+ listener.settimeout(ACCEPT_TIMEOUT_SECONDS)+ yield listener+ finally:+ try:+ listener.close()+ except OSError:+ pass-def _handle_shutdown(_signum: int, _frame: object) -> None:- _SHUTDOWN_EVENT.set()+def _accept_loop(listener: socket.socket, state: DaemonState) -> None:+ while not state.shutdown_event.is_set():+ try:+ conn, _ = listener.accept()+ except socket.timeout:+ continue+ except OSError as exc:+ if exc.errno == errno.EBADF:+ return+ logger.warning("accept() failed: %s", exc)+ continue+ thread = threading.Thread(+ target=_handle_connection,+ args=(conn, state),+ name="jiuwenbox-daemon-worker",+ daemon=True,+ )+ thread.start()def main() -> int:- """Stay alive until the runtime asks the sandbox to stop."""- signal.signal(signal.SIGTERM, _handle_shutdown)- signal.signal(signal.SIGINT, _handle_shutdown)+ logging.basicConfig(+ level=logging.INFO,+ format="[%(asctime)s] %(levelname)s %(name)s: %(message)s",+ stream=sys.stderr,+ )+ state = DaemonState()+ try:+ with _adopted_listener() as listener:+ logger.info(+ "sandbox daemon adopted listener fd; entering accept loop",+ )+ try:+ _accept_loop(listener, state)+ finally:+ # Give in-flight requests a brief window to complete cleanly+ # before the context manager closes the listener.+ state.wait_drain(SHUTDOWN_DRAIN_TIMEOUT_SECONDS)+ except RuntimeError as exc:+ logger.error("%s", exc)+ return 1- _SHUTDOWN_EVENT.wait()+ logger.info("sandbox daemon exited cleanly")return 0diff --git a/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py b/jiuwenbox/src/jiuwenbox/supervisor/seccomp.pyindex b788cd4cbe..0d8101efa5 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py@@ -11,11 +11,13 @@ import loggingimport osimport platformimport struct+from functools import lru_cachefrom pathlib import Path+from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.policy import SyscallPolicy-logging.basicConfig(level=logging.INFO)+configure_logging()logger = logging.getLogger(__name__)# ── BPF constants (linux/bpf_common.h, linux/seccomp.h) ──@@ -143,6 +145,7 @@ def _fallback_syscall_numbers() -> dict[str, int]:}+@lru_cache(maxsize=1)def _get_syscall_numbers() -> dict[str, int]:"""Load the syscall number table for the current architecture.diff --git a/jiuwenbox/tests/conftest.py b/jiuwenbox/tests/conftest.pyindex 315fd1d78d..6701cba450 100644--- a/jiuwenbox/tests/conftest.py+++ b/jiuwenbox/tests/conftest.py@@ -7,6 +7,8 @@ import osimport pytest+pytest_plugins = ["pytest_asyncio"]+from jiuwenbox.models.policy import SecurityPolicy@@ -15,20 +17,139 @@ def pytest_addoption(parser):"--server-endpoint",action="store",default=None,- help="Run server API tests against an external server endpoint. Defaults to 127.0.0.1:8321.",+ help="Server endpoint (host:port or URL). Default: 127.0.0.1:8321",+ )+ parser.addoption(+ "--proxy-port",+ action="store",+ default=None,+ type=int,+ help="Proxy listen port. Default: 8322",+ )+ parser.addoption(+ "--test-llm-endpoint",+ action="store",+ default=None,+ help="LLM endpoint URL for testing (e.g., https://api.openai.com/v1)",+ )+ parser.addoption(+ "--test-llm-api-key",+ action="store",+ default=None,+ help="LLM API key for testing",+ )+ parser.addoption(+ "--test-llm-model",+ action="store",+ default=None,+ help="LLM model name. Default: gpt-4o-mini",)@pytest.fixturedef server_endpoint(pytestconfig) -> str:+ """Server endpoint as host:port or URL string."""+ return (+ pytestconfig.getoption("server_endpoint")+ or os.environ.get("JIUWENBOX_TEST_SERVER")+ or "127.0.0.1:8321"+ )+++def proxy_port(pytestconfig) -> int:+ """Proxy listen port."""return (+ pytestconfig.getoption("proxy_port")+ or int(os.environ.get("JIUWENBOX_PROXY_PORT", "8322"))+ )+++def server_host_port(server_endpoint):+ """Parse server_endpoint into (host, port) tuple."""+ endpoint = server_endpoint+ if "://" in endpoint:+ endpoint = endpoint.split("://", 1)[1]+ host, port = endpoint.rsplit(":", 1)+ return host, int(port)+++def server_url(server_endpoint):+ """Server endpoint as full URL."""+ return server_endpoint if "://" in server_endpoint else f"http://{server_endpoint}"++[email protected](scope="session")+def server_url_session(pytestconfig):+ """Session-scoped server URL."""+ endpoint = (pytestconfig.getoption("server_endpoint")or os.environ.get("JIUWENBOX_TEST_SERVER")or "127.0.0.1:8321")+ return endpoint if "://" in endpoint else f"http://{endpoint}"++[email protected](scope="session")+def server_host_port_session(pytestconfig):+ """Session-scoped parsed host and port."""+ endpoint = (+ pytestconfig.getoption("server_endpoint")+ or os.environ.get("JIUWENBOX_TEST_SERVER")+ or "127.0.0.1:8321"+ )+ if "://" in endpoint:+ endpoint = endpoint.split("://", 1)[1]+ host, port = endpoint.rsplit(":", 1)+ 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"))+ )++[email protected](scope="session")+def test_llm_endpoint(pytestconfig):+ """LLM endpoint URL for testing."""+ return (+ pytestconfig.getoption("test_llm_endpoint")+ or os.environ.get("JIUWENBOX_TEST_LLM_ENDPOINT")+ )++[email protected](scope="session")+def test_llm_api_key(pytestconfig):+ """LLM API key for testing."""+ return (+ pytestconfig.getoption("test_llm_api_key")+ or os.environ.get("JIUWENBOX_TEST_LLM_API_KEY")+ )++[email protected](scope="session")+def test_llm_model(pytestconfig):+ """LLM model name for testing."""+ return (+ pytestconfig.getoption("test_llm_model")+ or os.environ.get("JIUWENBOX_TEST_LLM_MODEL")+ or "gpt-4o-mini"+ )++[email protected](scope="session")+def llm_available(docker_gateway_ip):+ """Extract LLM availability from topology check result."""+ return docker_gateway_ip.get("llm_available", False)@pytest.fixture-def default_policy() -> SecurityPolicy:+def policy() -> SecurityPolicy:"""Return the default policy."""return SecurityPolicy()diff --git a/jiuwenbox/tests/integration/conftest.py b/jiuwenbox/tests/integration/conftest.pynew file mode 100644index 0000000000..22b455aa4b--- /dev/null+++ b/jiuwenbox/tests/integration/conftest.py@@ -0,0 +1,447 @@+"""Shared fixtures for integration tests."""++from __future__ import annotations++import asyncio+import logging+import socket+import subprocess+import time+from socketserver import ThreadingMixIn+from wsgiref.simple_server import WSGIRequestHandler, WSGIServer, make_server++import httpx+import pytest+import pytest_asyncio++LONG_RUNNING_COMMAND = ["python3", "-c", "import time; time.sleep(36000)"]+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"}+logger = logging.getLogger(__name__)++DOCKER_ACCESSIBLE_IP = "172.17.0.1"+++def _allocate_tcp_port() -> int:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as tcp_socket:+ tcp_socket.bind(("0.0.0.0", 0))+ return tcp_socket.getsockname()[1]+++class SandboxTrackingClient:+ """Track sandboxes created during a test and clean them up afterwards."""++ def __init__(self, client):+ self._client = client+ self._created_ids: list[str] = []++ def __getattr__(self, name: str):+ return getattr(self._client, name)++ def post(self, url, *args, **kwargs):+ response = self._client.post(url, *args, **kwargs)+ if str(url).rstrip("/") == "/api/v1/sandboxes" and response.status_code == 201:+ try:+ sandbox_id = response.json().get("id")+ except Exception as exc:+ logger.debug("Failed to parse sandbox create response: %s", exc)+ sandbox_id = None+ if sandbox_id:+ self._created_ids.append(sandbox_id)+ return response++ def delete(self, url, *args, **kwargs):+ response = self._client.delete(url, *args, **kwargs)+ sandbox_id = self._sandbox_id_from_delete_url(url)+ if sandbox_id and response.status_code in (200, 202, 204, 404):+ self._created_ids = [item for item in self._created_ids if item != sandbox_id]+ return response++ def cleanup_sandboxes(self) -> None:+ for sandbox_id in reversed(self._created_ids):+ try:+ self._client.delete(f"/api/v1/sandboxes/{sandbox_id}")+ except Exception as exc:+ logger.warning("Failed to cleanup sandbox %s: %s", sandbox_id, exc)+ self._created_ids.clear()++ @staticmethod+ def _sandbox_id_from_delete_url(url) -> str | None:+ path = str(url).split("?", 1)[0].rstrip("/")+ prefix = "/api/v1/sandboxes/"+ if not path.startswith(prefix):+ return None+ suffix = path[len(prefix):]+ if "/" in suffix:+ return None+ return suffix or None+++def _normalize_endpoint(endpoint: str) -> str:+ return endpoint if "://" in endpoint else f"http://{endpoint}"+++def client(server_endpoint):+ with httpx.Client(base_url=_normalize_endpoint(server_endpoint), timeout=30.0) as external:+ tracking = SandboxTrackingClient(external)+ try:+ yield tracking+ finally:+ tracking.cleanup_sandboxes()++[email protected](scope="session")+def mock_llm_server_http_port():+ """Find an available port for mock LLM HTTP server (session-scoped)."""+ return _allocate_tcp_port()++[email protected](scope="session")+def mock_llm_server_https_port():+ """Find an available port for mock LLM HTTPS server (session-scoped)."""+ return _allocate_tcp_port()++[email protected](scope="session")+def mock_llm_server(mock_llm_server_http_port, mock_llm_server_https_port):+ """Start mock LLM server for testing (session-scoped).++ Runs once per test session. All tests share the same server instance.+ Server is thread-safe and handles concurrent requests.+ Binds on 0.0.0.0 so it's accessible from Docker containers.++ Returns:+ dict: {"http_port": int, "https_port": int, "process": subprocess.Popen}+ """+ import sys+ from pathlib import Path++ mock_server_path = Path(__file__).parent / "mock_llm_server.py"+ proc = subprocess.Popen(+ [+ sys.executable,+ str(mock_server_path),+ "--http-port", str(mock_llm_server_http_port),+ "--https-port", str(mock_llm_server_https_port),+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )++ time.sleep(0.5)++ try:+ yield {+ "http_port": mock_llm_server_http_port,+ "https_port": mock_llm_server_https_port,+ "process": proc,+ }+ finally:+ proc.terminate()+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait()++[email protected](scope="session")+def http_target_port():+ """Allocate a dynamic port once per test session."""+ return _allocate_tcp_port()+++def proxy_listen_port():+ """Allocate a dynamic port for proxy listen address (per test function)."""+ return _allocate_tcp_port()++[email protected](scope="session")+def simple_http_target(http_target_port):+ """Session-scoped HTTP target server that returns 200 OK.++ Starts once at session beginning, runs for all tests, stops at session end.+ Uses threading to avoid pytest-asyncio event loop scope issues.++ Returns the port number for tests to use in target_endpoint URLs.+ """+ connection_count = [0]++ class ThreadedWSGIServer(ThreadingMixIn, WSGIServer):+ daemon_threads = True++ class LoggingWSGIRequestHandler(WSGIRequestHandler):+ def log_message(self, fmt: str, *args) -> None: # noqa: A003+ logger.info("[simple_http_target] " + fmt, *args)++ def simple_wsgi_app(environ, start_response):+ content_length = int(environ.get("CONTENT_LENGTH") or "0")+ if content_length:+ _ = environ["wsgi.input"].read(content_length)+ connection_count[0] += 1+ logger.info(+ "[simple_http_target] Connection #%s from %s",+ connection_count[0],+ environ.get("REMOTE_ADDR"),+ )+ start_response("200 OK", [("Content-Length", "2")])+ return [b"OK"]++ server = make_server(+ "0.0.0.0",+ http_target_port,+ simple_wsgi_app,+ server_class=ThreadedWSGIServer,+ handler_class=LoggingWSGIRequestHandler,+ )++ def threaded_server() -> None:+ logger.info(+ "[simple_http_target] Session server started on 0.0.0.0:%s",+ http_target_port,+ )+ server.serve_forever(poll_interval=0.5)+ logger.info(+ "[simple_http_target] Session server stopped, total connections: %s",+ connection_count[0],+ )++ import threading++ server_thread = threading.Thread(target=threaded_server, daemon=True)+ server_thread.start()+ time.sleep(0.2)++ try:+ yield http_target_port+ finally:+ server.shutdown()+ server.server_close()+ server_thread.join(timeout=5.0)+ logger.info("[simple_http_target] Session fixture teardown complete")++[email protected](scope="session")+def docker_gateway_ip(+ http_target_port,+ simple_http_target,+ server_url_session,+ test_llm_endpoint,+ test_llm_api_key,+):+ """+ Detect topology AND check LLM availability (reuses same sandbox).++ Uses sandbox exec curl to test connectivity from sandbox environment.++ Returns dict:+ - "gateway_ip": "127.0.0.1" or "172.17.0.1" (Docker gateway IP for target endpoints)+ - "llm_available": True/False++ Raises:+ RuntimeError: If API server unreachable or topology detection fails+ """+ port = http_target_port++ logger.info("[docker_gateway_ip] Starting checks")+ logger.info("[docker_gateway_ip] API server: %s", server_url_session)++ try:+ with httpx.Client(base_url=server_url_session, timeout=5.0) as client:+ health = client.get("/health")+ if health.status_code != 200:+ raise RuntimeError(+ f"API server at {server_url_session} unhealthy (status {health.status_code})"+ )+ except Exception as e:+ raise RuntimeError(+ f"API server at {server_url_session} unreachable. "+ f"Please ensure the server is running. Error: {e}"+ ) from e++ sandbox_id = None+ detected = None+ llm_ok = False++ try:+ with httpx.Client(base_url=server_url_session, timeout=30.0) as client:+ create = client.post("/api/v1/sandboxes", json={})+ if create.status_code != 201:+ raise RuntimeError(+ f"Failed to create sandbox via {server_url_session} (status {create.status_code})"+ )+ sandbox_id = create.json()["id"]+ logger.info("[docker_gateway_ip] Created sandbox %s", sandbox_id)++ for _ in range(10):+ status = client.get(f"/api/v1/sandboxes/{sandbox_id}")+ if status.json().get("phase") == "ready":+ break+ time.sleep(0.5)++ # ========== Topology detection ==========+ logger.info("[docker_gateway_ip] Testing 127.0.0.1:%s", port)+ exec_127 = client.post(+ f"/api/v1/sandboxes/{sandbox_id}/exec",+ json={+ "command": ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",+ "--connect-timeout", "3", f"http://127.0.0.1:{port}/test"],+ "timeout_seconds": 10,+ }+ )++ if exec_127.status_code == 200:+ result = exec_127.json()+ if result.get("exit_code") == 0 and result.get("stdout", "").strip() == "200":+ detected = "127.0.0.1"+ logger.info("[docker_gateway_ip] 127.0.0.1 reachable -> sandbox in WSL")+ else:+ logger.info(+ "[docker_gateway_ip] 127.0.0.1 failed (exit=%s, stdout=%s)",+ result.get("exit_code"),+ result.get("stdout"),+ )++ logger.info("[docker_gateway_ip] Testing 172.17.0.1:%s", port)+ exec_gw = client.post(+ f"/api/v1/sandboxes/{sandbox_id}/exec",+ json={+ "command": ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",+ "--connect-timeout", "3", f"http://172.17.0.1:{port}/test"],+ "timeout_seconds": 10,+ }+ )+ if exec_gw.status_code == 200:+ result = exec_gw.json()+ if result.get("exit_code") == 0 and result.get("stdout", "").strip() == "200":+ detected = "172.17.0.1"+ logger.info(+ "[docker_gateway_ip] 172.17.0.1 reachable -> sandbox in Docker"+ )+ else:+ raise RuntimeError(+ f"Both IPs unreachable for target server at port {port}. "+ f"127.0.0.1: exit={exec_127.json().get('exit_code')}, "+ f"172.17.0.1: exit={result.get('exit_code')}"+ )+ else:+ raise RuntimeError(+ f"Gateway exec failed via {server_url_session} (status {exec_gw.status_code})"+ )+ else:+ raise RuntimeError(+ f"127.0.0.1 exec failed via {server_url_session} (status {exec_127.status_code})"+ )++ # ========== LLM check (conditional) ==========+ if test_llm_endpoint and test_llm_api_key:+ logger.info("[docker_gateway_ip] Testing LLM: %s", test_llm_endpoint)+ exec_llm = client.post(+ f"/api/v1/sandboxes/{sandbox_id}/exec",+ json={+ "command": [+ "curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",+ "--connect-timeout", "10",+ "-H", f"Authorization: Bearer {test_llm_api_key}",+ f"{test_llm_endpoint}/models"+ ],+ "timeout_seconds": 15,+ }+ )++ if exec_llm.status_code == 200:+ result = exec_llm.json()+ http_code = result.get("stdout", "").strip()+ if result.get("exit_code") == 0 and http_code == "200":+ llm_ok = True+ logger.info("[docker_gateway_ip] LLM reachable (HTTP %s)", http_code)+ else:+ logger.info(+ "[docker_gateway_ip] LLM returned HTTP %s (exit=%s)",+ http_code,+ result.get("exit_code"),+ )+ else:+ logger.info("[docker_gateway_ip] LLM not configured, skipping check")++ # Cleanup sandbox+ client.delete(f"/api/v1/sandboxes/{sandbox_id}")+ logger.info("[docker_gateway_ip] Deleted sandbox %s", sandbox_id)+ logger.info(+ "[docker_gateway_ip] Complete: gateway_ip=%s, llm_available=%s",+ detected,+ llm_ok,+ )++ return {+ "gateway_ip": detected,+ "llm_available": llm_ok,+ }++ except RuntimeError:+ raise+ except Exception as e:+ if sandbox_id:+ try:+ with httpx.Client(base_url=server_url_session, timeout=5.0) as client:+ client.delete(f"/api/v1/sandboxes/{sandbox_id}")+ except Exception as cleanup_exc:+ logger.debug(+ "[docker_gateway_ip] Failed to cleanup sandbox %s after error: %s",+ sandbox_id,+ cleanup_exc,+ )+ raise RuntimeError(f"Checks failed: {e}") from e++[email protected](scope="session")+def proxy_host_from_test(server_host_port_session):+ """+ IP address to connect FROM test process TO proxy.++ When proxy runs in API server (possibly Docker), this returns+ the host where proxy is accessible from test environment.++ For local API server: returns 127.0.0.1+ For Docker API server: returns the mapped host (usually 127.0.0.1 if port mapped)++ Returns:+ str: Host IP for connecting to proxy from test process+ """+ if server_host_port_session:+ return server_host_port_session[0]+ return "127.0.0.1"++[email protected](scope="session")+def mock_server_host_for_docker(docker_gateway_ip):+ """+ IP address for mock server TARGET endpoints.++ When proxy runs in Docker and needs to connect to mock server+ running in test process, use Docker gateway IP.++ For local tests: returns 127.0.0.1+ For Docker tests: returns Docker gateway IP (172.17.0.1 or similar)++ Returns:+ str: Host IP for mock server target_endpoint URLs+ """+ if docker_gateway_ip:+ return docker_gateway_ip["gateway_ip"]+ return "127.0.0.1"diff --git a/jiuwenbox/tests/integration/mock_llm_server.py b/jiuwenbox/tests/integration/mock_llm_server.pynew file mode 100644index 0000000000..fffb09262a--- /dev/null+++ b/jiuwenbox/tests/integration/mock_llm_server.py@@ -0,0 +1,239 @@+"""Mock LLM server for testing inference privacy proxy.++Simulates an OpenAI-like API endpoint that accepts chat completion requests.+Supports both HTTP and HTTPS simultaneously on different ports.+"""++from __future__ import annotations++import argparse+import asyncio+import datetime+import ipaddress+import json+import logging+import ssl+import tempfile+from pathlib import Path++logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)+++async def handle_request(reader: asyncio.StreamReader, writer: asyncio.StreamWriter, protocol: str = "HTTP") -> None:+ """Handle incoming HTTP request and return mock LLM response."""+ try:+ request_data = await reader.read(8192)+ if not request_data:+ return++ request_text = request_data.decode(errors="replace")+ logger.info("[%s] Received request:\n%s", protocol, request_text[:500])++ request_json = {}+ extracted_api_key = None+ auth_header = None++ try:+ if request_text.startswith("POST") or request_text.startswith("GET"):+ headers_end = request_text.find("\r\n\r\n")+ if headers_end > 0:+ headers_section = request_text[:headers_end]+ body = request_text[headers_end + 4:]++ for line in headers_section.split("\r\n"):+ if line.lower().startswith("authorization:"):+ auth_header = line+ if "bearer " in line.lower():+ extracted_api_key = line.split("Bearer ")[-1].strip()+ elif line.lower().startswith("x-api-key:"):+ extracted_api_key = line.split(":")[-1].strip()++ if body:+ request_json = json.loads(body)+ logger.info("[%s] Parsed JSON body: %s", protocol, request_json)+ else:+ request_json = json.loads(request_text)+ logger.info("[%s] Parsed raw JSON: %s", protocol, request_json)+ except json.JSONDecodeError:+ pass++ model = request_json.get("model", "no model")++ if extracted_api_key and len(extracted_api_key) > 15:+ key_display = extracted_api_key[:15] + "..."+ else:+ key_display = extracted_api_key or "no-key"++ response = {+ "id": "mock-chatcmpl-123",+ "object": "chat.completion",+ "created": 1234567890,+ "model": model,+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": f"Mock response from '{model}'. Injected API key: {key_display}",+ },+ "finish_reason": "stop",+ }+ ],+ "usage": {+ "prompt_tokens": 10,+ "completion_tokens": 5,+ "total_tokens": 15,+ },+ "system_fingerprint": "fp_mock_test",+ "endpoint": f"{protocol.lower()}://api.mock-llm.local/v1/chat/completions",+ "injected_api_key": extracted_api_key,+ "auth_header": auth_header,+ }++ response_json = json.dumps(response)+ response_http = (+ "HTTP/1.1 200 OK\r\n"+ "Content-Type: application/json\r\n"+ f"Content-Length: {len(response_json)}\r\n"+ "Connection: close\r\n"+ "\r\n"+ f"{response_json}"+ )++ writer.write(response_http.encode())+ await writer.drain()+ logger.info("[%s] Sent response for model: '%s'", protocol, model)++ except Exception as e:+ logger.exception("[%s] Error handling request: %s", protocol, e)+ error_response = json.dumps({"error": str(e)})+ writer.write(+ (+ "HTTP/1.1 500 Internal Server Error\r\n"+ "Content-Type: application/json\r\n"+ "\r\n"+ f"{error_response}"+ ).encode()+ )+ await writer.drain()+ finally:+ writer.close()+ await writer.wait_closed()+++def generate_self_signed_cert() -> tuple[Path, Path]:+ """Generate a self-signed certificate for HTTPS testing."""+ try:+ from cryptography import x509+ from cryptography.x509.oid import NameOID+ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import rsa+ except ImportError as exc:+ raise ImportError("cryptography library required for HTTPS mode") from exc++ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)++ subject = x509.Name([+ x509.NameAttribute(NameOID.COMMON_NAME, "mock-llm.local"),+ x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Mock LLM Test"),+ ])++ now = datetime.datetime.now(datetime.timezone.utc)+ cert = (+ x509.CertificateBuilder()+ .subject_name(subject)+ .issuer_name(subject)+ .public_key(key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(now)+ .not_valid_after(now + datetime.timedelta(days=365))+ .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)+ .add_extension(+ x509.SubjectAlternativeName([+ x509.DNSName("mock-llm.local"),+ x509.DNSName("localhost"),+ x509.IPAddress(ipaddress.IPv4Address("127.0.0.1")),+ ]),+ critical=False,+ )+ .sign(key, hashes.SHA256())+ )++ cert_dir = Path(tempfile.mkdtemp(prefix="mock_llm_cert_"))+ cert_path = cert_dir / "mock_llm.crt"+ key_path = cert_dir / "mock_llm.key"++ cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))+ key_path.write_bytes(key.private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.TraditionalOpenSSL,+ encryption_algorithm=serialization.NoEncryption(),+ ))++ logger.info("Generated self-signed cert: %s", cert_path)+ logger.info("Generated self-signed key: %s", key_path)++ return cert_path, key_path+++async def start_http_server(port: int) -> asyncio.Server:+ """Start HTTP server."""+ server = await asyncio.start_server(+ lambda r, w: handle_request(r, w, "HTTP"),+ "0.0.0.0",+ port,+ )+ addr = server.sockets[0].getsockname()+ logger.info("HTTP server listening on http://%s:%d", addr[0], addr[1])+ return server+++async def start_https_server(port: int) -> asyncio.Server:+ """Start HTTPS server with self-signed certificate."""+ cert_path, key_path = generate_self_signed_cert()+ ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ ssl_ctx.load_cert_chain(str(cert_path), str(key_path))++ server = await asyncio.start_server(+ lambda r, w: handle_request(r, w, "HTTPS"),+ "0.0.0.0",+ port,+ ssl=ssl_ctx,+ )+ addr = server.sockets[0].getsockname()+ logger.info("HTTPS server listening on https://%s:%d", addr[0], addr[1])+ return server+++async def main(http_port: int, https_port: int | None) -> None:+ """Start mock LLM servers."""+ servers = []++ http_server = await start_http_server(http_port)+ servers.append(http_server)++ if https_port:+ https_server = await start_https_server(https_port)+ servers.append(https_server)++ logger.info("Mock LLM server ready. Connect via inference_privacy_proxy.")+ logger.info("HTTP endpoint: http://127.0.0.1:%d", http_port)+ if https_port:+ logger.info("HTTPS endpoint: https://127.0.0.1:%d", https_port)++ async def serve_forever(server: asyncio.Server) -> None:+ async with server:+ await server.serve_forever()++ tasks = [asyncio.create_task(serve_forever(s)) for s in servers]+ await asyncio.gather(*tasks)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description="Mock LLM server for testing inference_privacy_proxy")+ parser.add_argument("--http-port", type=int, default=9999, help="HTTP port (default: 9999)")+ parser.add_argument("--https-port", type=int, default=None, help="HTTPS port (default: None, set to enable HTTPS)")+ args = parser.parse_args()++ asyncio.run(main(args.http_port, args.https_port))diff --git a/jiuwenbox/tests/integration/test_inference_privacy_proxy.py b/jiuwenbox/tests/integration/test_inference_privacy_proxy.pynew file mode 100644index 0000000000..1843c53031--- /dev/null+++ b/jiuwenbox/tests/integration/test_inference_privacy_proxy.py@@ -0,0 +1,2266 @@+"""Integration tests for HTTP-aware inference privacy proxy with path routing."""++import asyncio+import copy+import http.client+import json+import logging+import os+import socket+import threading++import httpx+import pytest+import pytest_asyncio++from jiuwenbox.proxy.inference_privacy_proxy import (+ InferencePrivacyProxyConfig,+ ProxyRoute,+ InferencePrivacyProxy,+ PLACEHOLDER,+)+from jiuwenbox.proxy.inference_privacy_proxy_manager import (+ InferencePrivacyProxyManager,+ ProxyState,+)++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+++def manager():+ mgr = InferencePrivacyProxyManager()+ mgr.reset()+ return mgr+++def proxy_route_factory(http_target_port, mock_server_host_for_docker):+ """Factory to create ProxyRoute objects with custom parameters.++ Args:+ path_prefix: Route path prefix (e.g., "/test", "/route1")+ api_key: API key for the route (default: "sk-test-key")++ Returns:+ ProxyRoute instance configured with dynamic host+ """+ def create_route(path_prefix: str, api_key: str = "sk-test-key"):+ return ProxyRoute(+ path_prefix=path_prefix,+ target_endpoint=f"http://{mock_server_host_for_docker}:{http_target_port}",+ api_key=api_key,+ )+ return create_route+++def integration_target_endpoint(simple_http_target, docker_gateway_ip):+ """Target endpoint for integration tests (API server perspective)."""+ gateway_ip = docker_gateway_ip["gateway_ip"]+ return f"http://{gateway_ip}:{simple_http_target}"+++def _proxy_http_get(proxy_host: str, proxy_port: int, path: str, timeout: float = 5.0) -> str:+ connection = http.client.HTTPConnection(proxy_host, proxy_port, timeout=timeout)+ try:+ connection.request("GET", path, headers={"Host": "localhost"})+ response = connection.getresponse()+ body = response.read().decode(errors="replace")+ return f"{response.status} {response.reason}\n{body}"+ finally:+ connection.close()+++async def validate_proxy_http(+ proxy_port: int,+ path: str,+ expect_forward: bool,+ proxy_host: str = "127.0.0.1",+ timeout: float = 2.0,+):+ """Validate proxy state by making real HTTP call (unit test helper).++ Args:+ proxy_port: Port the proxy listens on+ path: Path to request (e.g., "/test/v1/chat")+ expect_forward: True if proxy should forward (200), False if route disabled (404) or proxy stopped+ proxy_host: Host IP for proxy connection (default: 127.0.0.1)+ timeout: Timeout for connection attempt+ """+ try:+ reader, writer = await asyncio.wait_for(+ asyncio.open_connection(proxy_host, proxy_port),+ timeout=timeout+ )++ request = f"GET {path} HTTP/1.1\r\nHost: localhost\r\n\r\n"+ writer.write(request.encode())+ await writer.drain()++ response = await asyncio.wait_for(reader.read(1024), timeout=timeout)+ response_text = response.decode()++ writer.close()+ await writer.wait_closed()++ if expect_forward:+ assert "200 OK" in response_text, f"Expected 200 OK, got: {response_text}"+ else:+ assert "404" in response_text or "No route matched" in response_text, \+ f"Expected 404 for disabled route, got: {response_text}"++ except asyncio.TimeoutError as e:+ if expect_forward:+ raise AssertionError(+ f"Expected proxy at {proxy_host}:{proxy_port} to be listening, "+ f"but connection failed: {e}"+ ) from e+ return+ except OSError as e:+ if expect_forward:+ raise AssertionError(+ f"Expected proxy at {proxy_host}:{proxy_port} to be listening, "+ f"but connection failed: {e}"+ ) from e+ return+++async def validate_proxy_not_listening(+ proxy_port: int,+ proxy_host: str = "127.0.0.1",+ timeout: float = 1.0,+):+ """Validate that proxy is NOT listening (unit test helper).++ Args:+ proxy_port: Port to check+ proxy_host: Host IP for proxy connection (default: 127.0.0.1)+ timeout: Timeout for connection attempt+ """+ try:+ reader, writer = await asyncio.wait_for(+ asyncio.open_connection(proxy_host, proxy_port),+ timeout=timeout+ )+ writer.close()+ await writer.wait_closed()+ raise AssertionError(+ f"Expected connection to fail at {proxy_host}:{proxy_port}, "+ f"but proxy is listening"+ )+ except asyncio.TimeoutError:+ return+ except OSError:+ return+++class TestProxyManagerCRUD:+ """Test create, read, update, delete operations."""++ @pytest.mark.asyncio+ async def test_create_proxy_with_zero_port_raises(self, manager, proxy_route_factory):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=0, routes=[route])++ with pytest.raises(ValueError, match="listen_port=0"):+ await manager.create_proxy("test", config)++ @pytest.mark.asyncio+ async def test_create_proxy_on_disabled_proxy_raises(self, manager, proxy_route_factory, proxy_listen_port):+ route = proxy_route_factory("/test")+ config1 = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ await manager.create_proxy("test", config1)++ global_instance = manager.get_global_instance()+ global_instance.config.listen_port = 0++ route2 = proxy_route_factory("/route2", api_key="key2")+ config2 = InferencePrivacyProxyConfig(routes=[route2])++ with pytest.raises(ValueError, match="listen_port=0"):+ await manager.create_proxy("route2", config2)++ @pytest.mark.asyncio+ async def test_create_proxy(self, manager, proxy_route_factory, proxy_listen_port):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ result = await manager.create_proxy("test", config)++ assert result["name"] == "test"+ assert result["state"] == "stopped"++ @pytest.mark.asyncio+ async def test_create_duplicate_proxy_raises(self, manager, proxy_route_factory, proxy_listen_port):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ await manager.create_proxy("test", config)++ with pytest.raises(ValueError, match="already exists"):+ await manager.create_proxy("test", config)++ @pytest.mark.asyncio+ async def test_list_proxies(self, manager, proxy_route_factory, proxy_listen_port):+ route1 = proxy_route_factory("/route1", api_key="key1")+ config1 = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route1])+ await manager.create_proxy("route1", config1)++ route2 = proxy_route_factory("/route2", api_key="key2")+ config2 = InferencePrivacyProxyConfig(routes=[route2])+ await manager.create_proxy("route2", config2)++ proxies = await manager.list_proxies()+ assert len(proxies) == 2+ names = [p["name"] for p in proxies]+ assert "route1" in names+ assert "route2" in names++ @pytest.mark.asyncio+ async def test_get_proxy(self, manager, proxy_route_factory, proxy_listen_port):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ await manager.create_proxy("test", config)++ result = await manager.get_proxy("test")+ assert result is not None+ assert result["name"] == "test"+ assert result["state"] == "stopped"+ assert result["route"]["path_prefix"] == "/test"++ @pytest.mark.asyncio+ async def test_get_nonexistent_proxy_returns_none(self, manager):+ result = await manager.get_proxy("nonexistent")+ assert result is None++ @pytest.mark.asyncio+ async def test_delete_proxy(self, manager, proxy_route_factory, proxy_listen_port):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ await manager.create_proxy("test", config)++ result = await manager.delete_proxy("test")+ assert result["deleted"] == True++ proxies = await manager.list_proxies()+ assert len(proxies) == 0++ @pytest.mark.asyncio+ async def test_delete_nonexistent_proxy_raises(self, manager):+ with pytest.raises(ValueError, match="not found"):+ await manager.delete_proxy("nonexistent")++ @pytest.mark.asyncio+ async def test_update_proxy(+ self,+ manager,+ proxy_route_factory,+ proxy_listen_port,+ http_target_port,+ mock_server_host_for_docker,+ ):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ await manager.create_proxy("test", config)++ new_route = ProxyRoute(+ path_prefix="/test",+ target_endpoint=f"http://{mock_server_host_for_docker}:{http_target_port}",+ api_key="sk-new-key",+ )+ new_config = InferencePrivacyProxyConfig(routes=[new_route])++ result = await manager.update_proxy("test", new_config)+ assert result["name"] == "test"++ proxy = await manager.get_proxy("test")+ assert proxy["route"]["target_endpoint"] == f"http://{mock_server_host_for_docker}:{http_target_port}"+++class TestProxyManagerLifecycle:+ """Test start, stop operations."""++ @pytest.mark.asyncio+ async def test_start_proxy_with_zero_port_returns_stopped(+ self,+ manager,+ proxy_route_factory,+ simple_http_target,+ proxy_listen_port,+ ):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ await manager.create_proxy("test", config)++ global_instance = manager.get_global_instance()+ global_instance.config.listen_port = 0++ result = await manager.start_proxy("test")+ assert result["state"] == "stopped"++ proxy = await manager.get_proxy("test")+ assert proxy["state"] == "stopped"++ logs = await manager.get_proxy_logs("test")+ assert "listen_port=0" in logs["logs"]+ assert "disabled" in logs["logs"].lower()++ await validate_proxy_not_listening(proxy_listen_port)++ @pytest.mark.asyncio+ async def test_start_proxy(self, manager, proxy_route_factory, simple_http_target, proxy_listen_port):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ await manager.create_proxy("test", config)++ result = await manager.start_proxy("test")+ assert result["state"] == "running"++ proxy = await manager.get_proxy("test")+ assert proxy["state"] == "running"++ await validate_proxy_http(proxy_listen_port, "/test/v1/chat", expect_forward=True)++ await manager.stop_proxy("test")++ @pytest.mark.asyncio+ async def test_start_nonexistent_proxy_raises(self, manager):+ with pytest.raises(ValueError, match="not found"):+ await manager.start_proxy("nonexistent")++ @pytest.mark.asyncio+ async def test_stop_proxy(self, manager, proxy_route_factory, simple_http_target, proxy_listen_port):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ await manager.create_proxy("test", config)+ await manager.start_proxy("test")++ await validate_proxy_http(proxy_listen_port, "/test/v1/chat", expect_forward=True)++ result = await manager.stop_proxy("test")+ assert result["state"] == "stopped"++ proxy = await manager.get_proxy("test")+ assert proxy["state"] == "stopped"++ await validate_proxy_not_listening(proxy_listen_port)++ @pytest.mark.asyncio+ async def test_independent_route_states(self, manager, proxy_route_factory, simple_http_target, proxy_listen_port):+ route1 = proxy_route_factory("/route1", api_key="key1")+ route2 = proxy_route_factory("/route2", api_key="key2")+ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[route1, route2],+ )+ await manager.create_proxy("route1", config)++ await manager.start_proxy("route1")++ proxy1 = await manager.get_proxy("route1")+ proxy2 = await manager.get_proxy("route2")++ assert proxy1["state"] == "running"+ assert proxy2["state"] == "stopped"++ await validate_proxy_http(proxy_listen_port, "/route1/v1/chat", expect_forward=True)+ await validate_proxy_http(proxy_listen_port, "/route2/v1/chat", expect_forward=False)++ await manager.start_proxy("route2")++ proxy1 = await manager.get_proxy("route1")+ proxy2 = await manager.get_proxy("route2")++ assert proxy1["state"] == "running"+ assert proxy2["state"] == "running"++ await validate_proxy_http(proxy_listen_port, "/route1/v1/chat", expect_forward=True)+ await validate_proxy_http(proxy_listen_port, "/route2/v1/chat", expect_forward=True)++ await manager.stop_proxy("route1")+ await manager.stop_proxy("route2")++ @pytest.mark.asyncio+ async def test_stop_one_route_keeps_proxy_running(+ self,+ manager,+ proxy_route_factory,+ simple_http_target,+ proxy_listen_port,+ ):+ route1 = proxy_route_factory("/route1", api_key="key1")+ route2 = proxy_route_factory("/route2", api_key="key2")+ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[route1, route2],+ )+ await manager.create_proxy("route1", config)++ await manager.start_proxy("route1")+ await manager.start_proxy("route2")++ await validate_proxy_http(proxy_listen_port, "/route1/v1/chat", expect_forward=True)+ await validate_proxy_http(proxy_listen_port, "/route2/v1/chat", expect_forward=True)++ await manager.stop_proxy("route1")++ proxy1 = await manager.get_proxy("route1")+ proxy2 = await manager.get_proxy("route2")++ assert proxy1["state"] == "stopped"+ assert proxy2["state"] == "running"++ await validate_proxy_http(proxy_listen_port, "/route1/v1/chat", expect_forward=False)+ await validate_proxy_http(proxy_listen_port, "/route2/v1/chat", expect_forward=True)++ await manager.stop_proxy("route2")+++class TestProxyManagerLogs:+ """Test log operations."""++ @pytest.mark.asyncio+ async def test_get_proxy_logs(self, manager, proxy_route_factory, proxy_listen_port):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ await manager.create_proxy("test", config)++ result = await manager.get_proxy_logs("test")+ assert "logs" in result+ assert "created" in result["logs"].lower() or "route" in result["logs"].lower()++ @pytest.mark.asyncio+ async def test_get_proxy_logs_with_lines_limit(self, manager, proxy_route_factory, proxy_listen_port):+ route = proxy_route_factory("/test")+ config = InferencePrivacyProxyConfig(listen_port=proxy_listen_port, routes=[route])+ await manager.create_proxy("test", config)++ result = await manager.get_proxy_logs("test", lines=5)+ assert "logs" in result++ @pytest.mark.asyncio+ async def test_get_logs_nonexistent_proxy_raises(self, manager):+ with pytest.raises(ValueError, match="not found"):+ await manager.get_proxy_logs("nonexistent")+++class TestInferencePrivacyProxyUnit:+ """Unit tests for HTTP-aware proxy."""++ @pytest.mark.asyncio+ async def test_proxy_starts_and_stops(self):+ config = InferencePrivacyProxyConfig(+ listen_port=18080,+ routes=[+ ProxyRoute(+ path_prefix="/test",+ target_endpoint="http://127.0.0.1:9999",+ api_key="sk-test-key",+ ),+ ],+ )+ proxy = InferencePrivacyProxy(config)+ proxy.enable_route("/test")+ await proxy.start()++ assert proxy.is_running+ assert proxy.server is not None++ await proxy.stop()+ assert not proxy.is_running++ @pytest.mark.asyncio+ async def test_route_matching(self):+ route1 = ProxyRoute(path_prefix="/openai", target_endpoint="https://api.openai.com")+ route2 = ProxyRoute(path_prefix="/anthropic", target_endpoint="https://api.anthropic.com")++ config = InferencePrivacyProxyConfig(routes=[route1, route2])+ proxy = InferencePrivacyProxy(config)++ proxy.enable_route("/openai")+ proxy.enable_route("/anthropic")++ assert proxy.match_route("/openai/v1/chat") == route1+ assert proxy.match_route("/anthropic/v1/messages") == route2+ assert proxy.match_route("/other/path") is None++ @pytest.mark.asyncio+ async def test_route_enable_disable(self):+ route1 = ProxyRoute(path_prefix="/openai", target_endpoint="https://api.openai.com")+ route2 = ProxyRoute(path_prefix="/anthropic", target_endpoint="https://api.anthropic.com")++ config = InferencePrivacyProxyConfig(routes=[route1, route2])+ proxy = InferencePrivacyProxy(config)++ proxy.enable_route("/openai")+ assert proxy.match_route("/openai/v1/chat") == route1+ assert proxy.match_route("/anthropic/v1/messages") is None++ proxy.enable_route("/anthropic")+ assert proxy.match_route("/anthropic/v1/messages") == route2++ proxy.disable_route("/openai")+ assert proxy.match_route("/openai/v1/chat") is None+ assert proxy.match_route("/anthropic/v1/messages") == route2++ @pytest.mark.asyncio+ async def test_path_rewrite(self):+ route = ProxyRoute(+ path_prefix="/llm-proxy",+ target_endpoint="https://api.example.com/v1",+ )++ config = InferencePrivacyProxyConfig(routes=[route])+ proxy = InferencePrivacyProxy(config)++ assert proxy.rewrite_path("/llm-proxy/chat/completions", route) == "/v1/chat/completions"+ assert proxy.rewrite_path("/llm-proxy/", route) == "/v1"+ assert proxy.rewrite_path("/llm-proxy", route) == "/v1"++ @pytest.mark.asyncio+ async def test_api_key_injection_openai_format(self):+ route = ProxyRoute(+ path_prefix="/test",+ target_endpoint="http://127.0.0.1:9999",+ api_key="sk-sandbox-key",+ )++ config = InferencePrivacyProxyConfig(routes=[route])+ proxy = InferencePrivacyProxy(config)++ headers = f"Authorization: Bearer {PLACEHOLDER}\r\nHost: example.com\r\n".encode()+ modified = proxy.inject_api_key(headers, route)++ assert "sk-sandbox-key" in modified.decode()+ assert PLACEHOLDER not in modified.decode()++ @pytest.mark.asyncio+ async def test_api_key_injection_anthropic_format(self):+ route = ProxyRoute(+ path_prefix="/test",+ target_endpoint="http://127.0.0.1:9999",+ api_key="sk-ant-api03-test-key",+ )++ config = InferencePrivacyProxyConfig(routes=[route])+ proxy = InferencePrivacyProxy(config)++ headers = f"X-Api-Key: {PLACEHOLDER}\r\nHost: example.com\r\n".encode()+ modified = proxy.inject_api_key(headers, route)++ assert "sk-ant-api03-test-key" in modified.decode()+ assert PLACEHOLDER not in modified.decode()+++class TestInferencePrivacyProxyHTTPRouting:+ """Tests for actual HTTP request routing."""++ @pytest.mark.asyncio+ async def test_http_request_routing(self, proxy_listen_port, mock_server_host_for_docker):+ """Test HTTP request routing with mock target server."""+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.bind(("0.0.0.0", 0))+ target_port = s.getsockname()[1]++ async def target_server(reader, writer):+ data = await reader.read(8192)+ response = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK"+ writer.write(response.encode())+ await writer.drain()+ writer.close()+ await writer.wait_closed()++ server = await asyncio.start_server(target_server, "0.0.0.0", target_port)+ server_task = asyncio.create_task(server.serve_forever())++ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[+ ProxyRoute(+ path_prefix="/test",+ target_endpoint=f"http://{mock_server_host_for_docker}:{target_port}",+ api_key="sk-test-key",+ ),+ ],+ )++ proxy = InferencePrivacyProxy(config)+ proxy.enable_route("/test")+ await proxy.start()++ try:+ request = (+ "POST /test/v1/chat HTTP/1.1\r\n"+ f"Authorization: Bearer {PLACEHOLDER}\r\n"+ "Content-Length: 13\r\n"+ "\r\n"+ '{"test": true}'+ )++ reader, writer = await asyncio.open_connection("127.0.0.1", proxy_listen_port)+ writer.write(request.encode())+ await writer.drain()++ response = await reader.read(8192)+ assert "200 OK" in response.decode()++ writer.close()+ await writer.wait_closed()+ finally:+ await proxy.stop()+ server.close()+ await server.wait_closed()+ server_task.cancel()++ @pytest.mark.asyncio+ async def test_no_route_matched_returns_404(self, proxy_listen_port):+ """Test that unmatched paths return 404."""+ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[+ ProxyRoute(+ path_prefix="/openai",+ target_endpoint="https://api.openai.com",+ ),+ ],+ )++ proxy = InferencePrivacyProxy(config)+ proxy.enable_route("/openai")+ await proxy.start()++ try:+ request = "GET /other/path HTTP/1.1\r\nHost: localhost\r\n\r\n"++ reader, writer = await asyncio.open_connection("127.0.0.1", proxy_listen_port)+ writer.write(request.encode())+ await writer.drain()++ response = await reader.read(8192)+ assert "404 Not Found" in response.decode()+ assert "No route matched" in response.decode()++ writer.close()+ await writer.wait_closed()+ finally:+ await proxy.stop()++ @pytest.mark.asyncio+ async def test_disabled_route_returns_404(self, proxy_listen_port):+ """Test that disabled routes return 404."""+ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[+ ProxyRoute(+ path_prefix="/openai",+ target_endpoint="https://api.openai.com",+ ),+ ],+ )++ proxy = InferencePrivacyProxy(config)+ await proxy.start()++ try:+ request = "GET /openai/v1/chat HTTP/1.1\r\nHost: localhost\r\n\r\n"++ reader, writer = await asyncio.open_connection("127.0.0.1", proxy_listen_port)+ writer.write(request.encode())+ await writer.drain()++ response = await reader.read(8192)+ assert "404 Not Found" in response.decode()+ assert "No route matched" in response.decode()++ writer.close()+ await writer.wait_closed()+ finally:+ await proxy.stop()+++class TestInferencePrivacyProxyWithMockServer:+ """Tests using the mock_llm_server fixture."""++ @pytest.mark.asyncio+ async def test_http_proxy_with_mock_server(self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker):+ """Test HTTP proxy forwarding to mock LLM server."""+ http_port = mock_llm_server["http_port"]++ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[+ ProxyRoute(+ path_prefix="/mock",+ target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",+ api_key="sk-sandbox-key",+ ),+ ],+ )++ proxy = InferencePrivacyProxy(config)+ proxy.enable_route("/mock")+ await proxy.start()++ try:+ request = (+ "POST /mock/v1/chat/completions HTTP/1.1\r\n"+ f"Authorization: Bearer {PLACEHOLDER}\r\n"+ "Content-Type: application/json\r\n"+ "Content-Length: 43\r\n"+ "\r\n"+ '{"model": "gpt-3.5-turbo", "messages": []}'+ )++ reader, writer = await asyncio.open_connection("127.0.0.1", proxy_listen_port)+ writer.write(request.encode())+ await writer.drain()++ response = await reader.read(4096)+ response_text = response.decode()++ assert "200 OK" in response_text+ assert "sk-sandbox-key" in response_text++ writer.close()+ await writer.wait_closed()+ finally:+ await proxy.stop()++ @pytest.mark.asyncio+ async def test_https_proxy_with_mock_server(self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker):+ """Test HTTPS proxy forwarding to mock LLM server."""+ https_port = mock_llm_server["https_port"]++ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[+ ProxyRoute(+ path_prefix="/mock",+ target_endpoint=f"https://{mock_server_host_for_docker}:{https_port}",+ api_key="sk-sandbox-key",+ skip_cert_verify=True,+ ),+ ],+ )++ proxy = InferencePrivacyProxy(config)+ proxy.enable_route("/mock")+ await proxy.start()++ try:+ request = (+ "POST /mock/v1/chat/completions HTTP/1.1\r\n"+ f"Authorization: Bearer {PLACEHOLDER}\r\n"+ "Content-Type: application/json\r\n"+ "Content-Length: 43\r\n"+ "\r\n"+ '{"model": "gpt-3.5-turbo", "messages": []}'+ )++ reader, writer = await asyncio.open_connection("127.0.0.1", proxy_listen_port)+ writer.write(request.encode())+ await writer.drain()++ response = await reader.read(4096)+ response_text = response.decode()++ assert "HTTP/1.1" in response_text+ assert "sk-sandbox-key" in response_text++ writer.close()+ await writer.wait_closed()+ finally:+ await proxy.stop()++ @pytest.mark.asyncio+ async def test_anthropic_api_key_injection(self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker):+ """Test Anthropic-style X-Api-Key header injection."""+ http_port = mock_llm_server["http_port"]++ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[+ ProxyRoute(+ path_prefix="/anthropic",+ target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",+ api_key="sk-ant-api03-test-key",+ ),+ ],+ )++ proxy = InferencePrivacyProxy(config)+ proxy.enable_route("/anthropic")+ await proxy.start()++ try:+ request = (+ "POST /anthropic/v1/messages HTTP/1.1\r\n"+ f"X-Api-Key: {PLACEHOLDER}\r\n"+ "anthropic-version: 2023-06-01\r\n"+ "Content-Type: application/json\r\n"+ "Content-Length: 52\r\n"+ "\r\n"+ '{"model": "claude-3-opus", "max_tokens": 100, "messages": []}'+ )++ reader, writer = await asyncio.open_connection("127.0.0.1", proxy_listen_port)+ writer.write(request.encode())+ await writer.drain()++ response = await reader.read(4096)+ response_text = response.decode()++ assert "HTTP/1.1" in response_text+ assert "sk-ant-api03-test-key" in response_text++ writer.close()+ await writer.wait_closed()+ finally:+ await proxy.stop()+++# =============================================================================+# HTTP API Integration Tests+# =============================================================================+# Tests below use real HTTP calls to the API server and proxy.+# These validate behavior from end-to-end perspective.+++@pytest_asyncio.fixture(name="api_client")+async def _api_client_fixture(server_url):+ """Async HTTP client for API server."""+ async with httpx.AsyncClient(base_url=server_url, timeout=30.0) as client:+ yield client+++@pytest_asyncio.fixture(name="test_route_cleanup")+async def _test_route_cleanup_fixture(api_client):+ """Track and cleanup test routes after each integration test."""+ created_routes = []+ yield created_routes+ for name in reversed(created_routes):+ try:+ await api_client.delete(f"/api/v1/proxies/{name}")+ except Exception as exc:+ logger.debug("Failed to cleanup route %s: %s", name, exc)+++def llm_test_settings(+ llm_available,+ test_llm_endpoint,+ test_llm_api_key,+ test_llm_model,+):+ return {+ "available": llm_available,+ "endpoint": test_llm_endpoint,+ "api_key": test_llm_api_key,+ "model": test_llm_model,+ }+++def llm_proxy_runtime(server_host_port, proxy_port, api_client, test_route_cleanup):+ return {+ "proxy_host": server_host_port[0],+ "proxy_port": proxy_port,+ "api_client": api_client,+ "route_cleanup": test_route_cleanup,+ }+++async def _validate_proxy_forward(path: str, proxy_host: str, proxy_port: int, timeout: float = 2.0):+ """Validate route forwards request through proxy."""+ try:+ reader, writer = await asyncio.wait_for(+ asyncio.open_connection(proxy_host, proxy_port),+ timeout=timeout+ )++ request = f"GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"+ writer.write(request.encode())+ await writer.drain()++ response = await asyncio.wait_for(reader.read(1024), timeout=timeout)+ response_text = response.decode()++ writer.close()+ await writer.wait_closed()++ assert "200 OK" in response_text, f"Expected 200 OK, got: {response_text[:200]}"++ except asyncio.TimeoutError:+ raise AssertionError(+ f"Timeout connecting to proxy at {proxy_host}:{proxy_port}. "+ f"Ensure proxy server is running and accessible."+ ) from None+ except ConnectionRefusedError:+ raise AssertionError(+ f"Proxy at {proxy_host}:{proxy_port} not listening. "+ f"Ensure proxy server is running."+ ) from None+ except OSError as e:+ raise AssertionError(+ f"Connection error to proxy at {proxy_host}:{proxy_port}: {e}"+ ) from e+++async def _validate_route_disabled(path: str, proxy_host: str, proxy_port: int, timeout: float = 2.0):+ """Validate route is disabled (returns 404 or connection fails)."""+ try:+ reader, writer = await asyncio.wait_for(+ asyncio.open_connection(proxy_host, proxy_port),+ timeout=timeout+ )++ request = f"GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"+ writer.write(request.encode())+ await writer.drain()++ response = await asyncio.wait_for(reader.read(1024), timeout=timeout)+ response_text = response.decode()++ writer.close()+ await writer.wait_closed()++ assert "404" in response_text or "No route matched" in response_text, \+ f"Expected 404 for disabled route, got: {response_text[:200]}"++ except asyncio.TimeoutError:+ return+ except OSError:+ return+++class TestIntegrationProxyCRUD:+ """Test CRUD operations via HTTP API."""++ @pytest.mark.asyncio+ async def test_int_create_route(self, api_client, integration_target_endpoint, test_route_cleanup):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-create",+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 201+ data = response.json()+ assert data["name"] == "int-create"+ assert data["state"] == "stopped"++ test_route_cleanup.append("int-create")++ response = await api_client.get("/api/v1/proxies/int-create")+ assert response.status_code == 200+ assert response.json()["name"] == "int-create"++ @pytest.mark.asyncio+ async def test_int_list_routes(self, api_client, integration_target_endpoint, test_route_cleanup):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-list1",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-list1")++ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-list2",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-list2")++ response = await api_client.get("/api/v1/proxies")+ assert response.status_code == 200+ routes = response.json()+ names = [r["name"] for r in routes]+ assert "int-list1" in names+ assert "int-list2" in names++ @pytest.mark.asyncio+ async def test_int_get_route(self, api_client, integration_target_endpoint, test_route_cleanup):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-get",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-get")++ response = await api_client.get("/api/v1/proxies/int-get")+ assert response.status_code == 200+ data = response.json()+ assert data["name"] == "int-get"+ assert data["route"]["path_prefix"] == "/int-get"+ assert data["route"]["target_endpoint"] == integration_target_endpoint++ @pytest.mark.asyncio+ async def test_int_delete_route(self, api_client, integration_target_endpoint):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-delete",+ "target_endpoint": integration_target_endpoint,+ }+ )++ response = await api_client.delete("/api/v1/proxies/int-delete")+ assert response.status_code == 200+ assert response.json()["deleted"] == True++ response = await api_client.get("/api/v1/proxies/int-delete")+ assert response.status_code == 404++ @pytest.mark.asyncio+ async def test_int_update_route(self, api_client, integration_target_endpoint, test_route_cleanup):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-update",+ "target_endpoint": integration_target_endpoint,+ "api_key": "old-key",+ }+ )+ test_route_cleanup.append("int-update")++ response = await api_client.put(+ "/api/v1/proxies/int-update",+ json={+ "path_prefix": "/int-update",+ "target_endpoint": integration_target_endpoint,+ "api_key": "new-key",+ }+ )+ assert response.status_code == 200++ response = await api_client.get("/api/v1/proxies/int-update")+ assert response.json()["route"]["api_key"] == "new-key"+++class TestIntegrationProxyLifecycle:+ """Test lifecycle operations via HTTP API with real HTTP validation."""++ @pytest.mark.asyncio+ async def test_int_start_route_http_validation(+ self, api_client, integration_target_endpoint, proxy_host_from_test, proxy_port, test_route_cleanup+ ):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-life-start",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-life-start")++ response = await api_client.post("/api/v1/proxies/int-life-start/start")+ assert response.status_code == 200+ assert response.json()["state"] == "running"++ await _validate_proxy_forward("/int-life-start/v1/chat", proxy_host_from_test, proxy_port)++ @pytest.mark.asyncio+ async def test_int_stop_route_http_validation(+ self, api_client, integration_target_endpoint, proxy_host_from_test, proxy_port, test_route_cleanup+ ):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-life-stop",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-life-stop")++ await api_client.post("/api/v1/proxies/int-life-stop/start")++ await _validate_proxy_forward("/int-life-stop/v1/chat", proxy_host_from_test, proxy_port)++ response = await api_client.post("/api/v1/proxies/int-life-stop/stop")+ assert response.status_code == 200+ assert response.json()["state"] == "stopped"++ await _validate_route_disabled("/int-life-stop/v1/chat", proxy_host_from_test, proxy_port)++ @pytest.mark.asyncio+ async def test_int_start_already_running(+ self, api_client, integration_target_endpoint, test_route_cleanup+ ):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-life-dup",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-life-dup")++ await api_client.post("/api/v1/proxies/int-life-dup/start")++ response = await api_client.post("/api/v1/proxies/int-life-dup/start")+ assert response.status_code == 200+ assert response.json()["state"] == "running"++ @pytest.mark.asyncio+ async def test_int_operations_on_nonexistent(self, api_client):+ response = await api_client.get("/api/v1/proxies/nonexistent-route")+ assert response.status_code == 404++ response = await api_client.delete("/api/v1/proxies/nonexistent-route")+ assert response.status_code == 404++ response = await api_client.post("/api/v1/proxies/nonexistent-route/start")+ assert response.status_code == 404++ response = await api_client.post("/api/v1/proxies/nonexistent-route/stop")+ assert response.status_code == 404+++class TestIntegrationProxyIndependentRoutes:+ """Test independent route states with HTTP validation."""++ @pytest.mark.asyncio+ async def test_int_independent_start_stop(+ self, api_client, integration_target_endpoint, proxy_host_from_test, proxy_port, test_route_cleanup+ ):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-ind1",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-ind1")++ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-ind2",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-ind2")++ await api_client.post("/api/v1/proxies/int-ind1/start")++ await _validate_proxy_forward("/int-ind1/v1/chat", proxy_host_from_test, proxy_port)+ await _validate_route_disabled("/int-ind2/v1/chat", proxy_host_from_test, proxy_port)++ await api_client.post("/api/v1/proxies/int-ind2/start")++ await _validate_proxy_forward("/int-ind1/v1/chat", proxy_host_from_test, proxy_port)+ await _validate_proxy_forward("/int-ind2/v1/chat", proxy_host_from_test, proxy_port)++ @pytest.mark.asyncio+ async def test_int_stop_one_keeps_other_running(+ self, api_client, integration_target_endpoint, proxy_host_from_test, proxy_port, test_route_cleanup+ ):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-ind3",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-ind3")++ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-ind4",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-ind4")++ await api_client.post("/api/v1/proxies/int-ind3/start")+ await api_client.post("/api/v1/proxies/int-ind4/start")++ await _validate_proxy_forward("/int-ind3/v1/chat", proxy_host_from_test, proxy_port)+ await _validate_proxy_forward("/int-ind4/v1/chat", proxy_host_from_test, proxy_port)++ await api_client.post("/api/v1/proxies/int-ind3/stop")++ await _validate_route_disabled("/int-ind3/v1/chat", proxy_host_from_test, proxy_port)+ await _validate_proxy_forward("/int-ind4/v1/chat", proxy_host_from_test, proxy_port)++ @pytest.mark.asyncio+ async def test_int_shared_port_validation(+ self, api_client, integration_target_endpoint, proxy_host_from_test, proxy_port, test_route_cleanup+ ):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-share1",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-share1")++ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-share2",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-share2")++ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-share3",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-share3")++ await api_client.post("/api/v1/proxies/int-share1/start")+ await api_client.post("/api/v1/proxies/int-share2/start")+ await api_client.post("/api/v1/proxies/int-share3/start")++ await _validate_proxy_forward("/int-share1/v1/chat", proxy_host_from_test, proxy_port)+ await _validate_proxy_forward("/int-share2/v1/chat", proxy_host_from_test, proxy_port)+ await _validate_proxy_forward("/int-share3/v1/chat", proxy_host_from_test, proxy_port)+++class TestIntegrationProxyErrorHandling:+ """Test error handling via HTTP API."""++ @pytest.mark.asyncio+ async def test_int_create_duplicate_route(self, api_client, integration_target_endpoint, test_route_cleanup):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-dup",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("int-dup")++ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-dup",+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 400+ detail = response.json().get("detail", "")+ error = response.json().get("error", "")+ assert "already exists" in detail or "already exists" in error++ @pytest.mark.asyncio+ async def test_int_create_invalid_target_endpoint(self, api_client):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/int-invalid",+ "target_endpoint": "not-a-valid-url",+ }+ )+ assert response.status_code == 400++ @pytest.mark.asyncio+ async def test_int_create_empty_path_prefix(self, api_client, integration_target_endpoint):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "",+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 400+++class TestThreadingProxyConnection:+ """Test concurrent proxy connections using threading."""++ @staticmethod+ def test_01_concurrent_forward_strict(+ integration_target_endpoint, server_url, proxy_host_from_test, proxy_port+ ):+ """5 threads with unique routes - all must succeed."""+ results = []++ def worker(thread_id):+ with httpx.Client(base_url=server_url, timeout=30.0) as client:+ try:+ resp = client.post("/api/v1/proxies", json={+ "path_prefix": f"/thread-strict-{thread_id}",+ "target_endpoint": integration_target_endpoint,+ })+ if resp.status_code != 201:+ results.append((thread_id, "create_failed", resp.status_code))+ return++ resp = client.post(f"/api/v1/proxies/thread-strict-{thread_id}/start")+ if resp.status_code != 200:+ results.append((thread_id, "start_failed", resp.status_code))+ return++ response = _proxy_http_get(+ proxy_host_from_test,+ proxy_port,+ f"/thread-strict-{thread_id}/v1/chat",+ )++ if "200 OK" not in response:+ results.append((thread_id, "forward_failed", response[:100]))+ return++ client.delete(f"/api/v1/proxies/thread-strict-{thread_id}")+ results.append((thread_id, "success", None))+ except Exception as e:+ results.append((thread_id, "exception", str(e)))++ threads = [threading.Thread(target=worker, args=(i,)) for i in range(NUM_THREADS)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ successes = [r for r in results if r[1] == "success"]+ assert len(successes) == NUM_THREADS, f"Expected {NUM_THREADS} successes, got {len(successes)}: {results}"++ @staticmethod+ def test_02_concurrent_forward_relaxed(+ integration_target_endpoint, server_url, proxy_host_from_test, proxy_port+ ):+ """5 threads competing for same route - validate error handling."""+ results = []+ create_winner_found = [False]+ route_started = threading.Event()++ def worker(thread_id):+ with httpx.Client(base_url=server_url, timeout=30.0) as client:+ try:+ resp = client.post("/api/v1/proxies", json={+ "path_prefix": "/thread-relaxed",+ "target_endpoint": integration_target_endpoint,+ })++ if resp.status_code == 201:+ if not create_winner_found[0]:+ create_winner_found[0] = True+ results.append((thread_id, "create_success", 201))++ resp = client.post("/api/v1/proxies/thread-relaxed/start")+ if resp.status_code != 200:+ results.append((thread_id, "start_failed", resp.status_code))+ return+ route_started.set()+ else:+ results.append((thread_id, "create_duplicate_success", 201))+ elif resp.status_code == 400:+ detail = resp.json().get("detail", "")+ if "already exists" in detail:+ results.append((thread_id, "create_failed_expected", detail))+ route_started.wait(timeout=5.0)+ else:+ results.append((thread_id, "create_failed_unexpected", detail))+ return+ else:+ results.append((thread_id, "create_unexpected", resp.status_code))+ return++ for attempt in range(10):+ response = _proxy_http_get(+ proxy_host_from_test,+ proxy_port,+ "/thread-relaxed/v1/chat",+ )+ if "200 OK" in response:+ results.append((thread_id, "connect_success", None))+ break+ if "404 Not Found" in response:+ time.sleep(0.1)+ continue+ results.append((thread_id, "connect_failed", response[:100]))+ break+ else:+ results.append(+ (thread_id, "connect_failed", "route did not become ready in time")+ )+ except Exception as e:+ results.append((thread_id, "exception", str(e)))++ threads = [threading.Thread(target=worker, args=(i,)) for i in range(NUM_THREADS)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ with httpx.Client(base_url=server_url, timeout=30.0) as client:+ try:+ client.delete("/api/v1/proxies/thread-relaxed")+ except Exception as exc:+ logger.debug("Cleanup for thread-relaxed failed: %s", exc)++ create_successes = [r for r in results if r[1] == "create_success"]+ assert len(create_successes) >= 1, f"Expected at least 1 create success, got: {results}"++ create_failures = [r for r in results if r[1] == "create_failed_expected"]+ assert len(create_failures) >= 1, f"Expected at least 1 'already exists' failure, got: {results}"++ connect_successes = [r for r in results if r[1] == "connect_success"]+ assert len(connect_successes) == NUM_THREADS, f"Expected {NUM_THREADS} connect successes, got: {results}"+++class TestThreadingCRUD:+ """Test concurrent CRUD operations using threading."""++ @staticmethod+ def test_03_concurrent_crud_strict(+ integration_target_endpoint, server_url, proxy_host_from_test, proxy_port+ ):+ """5 threads with unique routes - all must succeed."""+ results = []++ def worker(thread_id):+ with httpx.Client(base_url=server_url, timeout=30.0) as client:+ try:+ resp = client.post("/api/v1/proxies", json={+ "path_prefix": f"/crud-strict-{thread_id}",+ "target_endpoint": integration_target_endpoint,+ })+ if resp.status_code != 201:+ results.append((thread_id, "create_failed", resp.status_code))+ return++ resp = client.post(f"/api/v1/proxies/crud-strict-{thread_id}/start")+ if resp.status_code != 200:+ results.append((thread_id, "start_failed", resp.status_code))+ return++ resp = client.get(f"/api/v1/proxies/crud-strict-{thread_id}")+ if resp.status_code != 200:+ results.append((thread_id, "get_failed", resp.status_code))+ return++ data = resp.json()+ if data.get("state") != "running":+ results.append((thread_id, "state_wrong", data.get("state")))+ return++ resp = client.post(f"/api/v1/proxies/crud-strict-{thread_id}/stop")+ if resp.status_code != 200:+ results.append((thread_id, "stop_failed", resp.status_code))+ return++ resp = client.delete(f"/api/v1/proxies/crud-strict-{thread_id}")+ if resp.status_code != 200:+ results.append((thread_id, "delete_failed", resp.status_code))+ return++ results.append((thread_id, "success", None))+ except Exception as e:+ results.append((thread_id, "exception", str(e)))++ threads = [threading.Thread(target=worker, args=(i,)) for i in range(NUM_THREADS)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ successes = [r for r in results if r[1] == "success"]+ assert len(successes) == NUM_THREADS, f"Expected {NUM_THREADS} successes, got {len(successes)}: {results}"++ @staticmethod+ def test_04_concurrent_crud_relaxed(+ integration_target_endpoint, server_url, proxy_host_from_test, proxy_port+ ):+ """5 threads competing for same route - validate error handling."""+ results = []+ create_winner_found = [False]++ def worker(thread_id):+ with httpx.Client(base_url=server_url, timeout=30.0) as client:+ try:+ resp = client.post("/api/v1/proxies", json={+ "path_prefix": "/crud-relaxed",+ "target_endpoint": integration_target_endpoint,+ })++ if resp.status_code == 201:+ if not create_winner_found[0]:+ create_winner_found[0] = True+ results.append((thread_id, "create_success", 201))++ resp = client.post("/api/v1/proxies/crud-relaxed/start")+ if resp.status_code != 200:+ results.append((thread_id, "start_failed", resp.status_code))+ return+ else:+ results.append((thread_id, "create_duplicate_success", 201))+ elif resp.status_code == 400:+ detail = resp.json().get("detail", "")+ if "already exists" in detail:+ results.append((thread_id, "create_failed_expected", detail))+ else:+ results.append((thread_id, "create_failed_unexpected", detail))+ return+ else:+ results.append((thread_id, "create_unexpected", resp.status_code))+ return++ resp = client.get("/api/v1/proxies/crud-relaxed")+ if resp.status_code == 200:+ data = resp.json()+ results.append((thread_id, "get_success", data.get("state")))+ elif resp.status_code == 404:+ results.append((thread_id, "get_notfound", 404))+ else:+ results.append((thread_id, "get_failed", resp.status_code))+ except Exception as e:+ results.append((thread_id, "exception", str(e)))++ threads = [threading.Thread(target=worker, args=(i,)) for i in range(NUM_THREADS)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ with httpx.Client(base_url=server_url, timeout=30.0) as client:+ try:+ client.post("/api/v1/proxies/crud-relaxed/stop")+ client.delete("/api/v1/proxies/crud-relaxed")+ except Exception as exc:+ logger.debug("Cleanup for crud-relaxed failed: %s", exc)++ create_successes = [r for r in results if r[1] == "create_success"]+ assert len(create_successes) >= 1, f"Expected at least 1 create success, got: {results}"++ create_failures = [r for r in results if r[1] == "create_failed_expected"]+ assert len(create_failures) >= 1, f"Expected at least 1 'already exists' failure, got: {results}"++ get_successes = [r for r in results if r[1] == "get_success"]+ assert len(get_successes) == NUM_THREADS, f"Expected {NUM_THREADS} GET successes, got: {results}"+++class TestInputValidation:+ """Test input validation for path_prefix, api_key, and target_endpoint."""++ @pytest.mark.asyncio+ async def test_path_prefix_with_crlf_rejected(self, api_client, integration_target_endpoint):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test\r\nInjected: header",+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 400+ assert "invalid characters" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_path_prefix_with_null_byte_rejected(self, api_client, integration_target_endpoint):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test\x00hidden",+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 400+ assert "invalid characters" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_path_prefix_with_path_traversal_rejected(self, api_client, integration_target_endpoint):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test/../escape",+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 400+ assert "path traversal" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_path_prefix_with_url_encoded_crlf_rejected(self, api_client, integration_target_endpoint):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test%0d%0aInjected: header",+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 400+ assert "invalid characters" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_path_prefix_with_url_encoded_path_traversal_rejected(self, api_client, integration_target_endpoint):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test%2e%2e/escape",+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 400+ assert "path traversal" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_path_prefix_normalization(self, api_client, integration_target_endpoint, test_route_cleanup):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "test/", # missing / prefix, has trailing /+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 201++ data = response.json()+ assert data["name"] == "test"++ test_route_cleanup.append("test")++ get_response = await api_client.get("/api/v1/proxies/test")+ assert get_response.json()["route"]["path_prefix"] == "/test"++ @pytest.mark.asyncio+ async def test_api_key_with_crlf_rejected(self, api_client, integration_target_endpoint):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test-crlf-key",+ "target_endpoint": integration_target_endpoint,+ "api_key": "key\r\nX-Injected: malicious",+ }+ )+ assert response.status_code == 400+ assert "invalid characters" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_api_key_with_null_byte_rejected(self, api_client, integration_target_endpoint):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test-null-key",+ "target_endpoint": integration_target_endpoint,+ "api_key": "key\x00hidden",+ }+ )+ assert response.status_code == 400+ assert "invalid characters" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_api_key_with_url_encoded_crlf_rejected(self, api_client, integration_target_endpoint):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test-url-key",+ "target_endpoint": integration_target_endpoint,+ "api_key": "key%0d%0aInjected",+ }+ )+ assert response.status_code == 400+ assert "invalid characters" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_valid_target_endpoint_accepted(self, api_client, integration_target_endpoint, test_route_cleanup):+ response = await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/valid-target",+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 201++ test_route_cleanup.append("valid-target")++ @pytest.mark.asyncio+ async def test_update_validates_path_prefix(self, api_client, integration_target_endpoint, test_route_cleanup):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/update-test",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("update-test")++ response = await api_client.put(+ "/api/v1/proxies/update-test",+ json={+ "path_prefix": "/update-test\r\nbad",+ "target_endpoint": integration_target_endpoint,+ }+ )+ assert response.status_code == 400+ assert "invalid characters" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_update_validates_api_key(self, api_client, integration_target_endpoint, test_route_cleanup):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/update-key",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("update-key")++ response = await api_client.put(+ "/api/v1/proxies/update-key",+ json={+ "path_prefix": "/update-key",+ "target_endpoint": integration_target_endpoint,+ "api_key": "key\r\nbad",+ }+ )+ assert response.status_code == 400+ assert "invalid characters" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_proxy_name_with_crlf_rejected(self, api_client, integration_target_endpoint, test_route_cleanup):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test-proxy-name",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("test-proxy-name")++ response = await api_client.get("/api/v1/proxies/test-proxy%0d%0aname")+ assert response.status_code == 400+ assert "invalid characters" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_proxy_name_with_special_chars_rejected(+ self,+ api_client,+ integration_target_endpoint,+ test_route_cleanup,+ ):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test-proxy-special",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("test-proxy-special")++ response = await api_client.get("/api/v1/proxies/test-proxy!@#$")+ assert response.status_code == 400+ assert "alphanumeric" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_proxy_name_with_space_rejected(self, api_client):+ response = await api_client.get("/api/v1/proxies/test proxy")+ assert response.status_code == 400+ assert "alphanumeric" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_proxy_name_with_dot_rejected(self, api_client):+ response = await api_client.get("/api/v1/proxies/test.proxy")+ assert response.status_code == 400+ assert "alphanumeric" in response.json().get("detail", "").lower()++ @pytest.mark.asyncio+ async def test_proxy_name_valid_accepted(self, api_client, integration_target_endpoint, test_route_cleanup):+ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/test-valid-name_123",+ "target_endpoint": integration_target_endpoint,+ }+ )+ test_route_cleanup.append("test-valid-name_123")++ response = await api_client.get("/api/v1/proxies/test-valid-name_123")+ assert response.status_code == 200+ assert response.json()["name"] == "test-valid-name_123"+++class TestModelValidation:+ """Test Pydantic model validation (YAML + API both validated)."""++ @staticmethod+ def test_listen_port_out_of_range_rejected():+ from jiuwenbox.models.policy import InferencePrivacyProxyPolicy++ with pytest.raises(ValueError, match="listen_port must be between"):+ InferencePrivacyProxyPolicy(listen_port=70000, listen_host="0.0.0.0")++ @staticmethod+ def test_listen_port_negative_rejected():+ from jiuwenbox.models.policy import InferencePrivacyProxyPolicy++ with pytest.raises(ValueError, match="listen_port must be between"):+ InferencePrivacyProxyPolicy(listen_port=-1, listen_host="0.0.0.0")++ @staticmethod+ def test_listen_port_valid_accepted():+ from jiuwenbox.models.policy import InferencePrivacyProxyPolicy++ policy = InferencePrivacyProxyPolicy(listen_port=8080, listen_host="127.0.0.1")+ assert policy.listen_port == 8080++ @staticmethod+ def test_path_prefix_empty_rejected():+ from jiuwenbox.models.policy import ProxyRouteEntry++ with pytest.raises(ValueError, match="path_prefix cannot be empty"):+ ProxyRouteEntry(path_prefix="", target_endpoint="https://api.openai.com")++ @staticmethod+ def test_path_prefix_with_crlf_rejected():+ from jiuwenbox.models.policy import ProxyRouteEntry++ with pytest.raises(ValueError, match="invalid characters"):+ ProxyRouteEntry(path_prefix="/test\r\nbad", target_endpoint="https://api.openai.com")++ @staticmethod+ def test_path_prefix_with_control_chars_rejected():+ from jiuwenbox.models.policy import ProxyRouteEntry++ with pytest.raises(ValueError, match="invalid characters"):+ ProxyRouteEntry(path_prefix="/test\x01bad", target_endpoint="https://api.openai.com")++ @staticmethod+ def test_api_key_with_crlf_rejected():+ from jiuwenbox.models.policy import ProxyRouteEntry++ with pytest.raises(ValueError, match="invalid characters"):+ ProxyRouteEntry(+ path_prefix="/test",+ target_endpoint="https://api.openai.com",+ api_key="key\r\nInjected: bad"+ )++ @staticmethod+ def test_api_key_with_control_chars_rejected():+ from jiuwenbox.models.policy import ProxyRouteEntry++ with pytest.raises(ValueError, match="invalid characters"):+ ProxyRouteEntry(+ path_prefix="/test",+ target_endpoint="https://api.openai.com",+ api_key="key\x01hidden"+ )++ @staticmethod+ def test_target_endpoint_invalid_scheme_rejected():+ from jiuwenbox.models.policy import ProxyRouteEntry++ with pytest.raises(ValueError, match="http or https"):+ ProxyRouteEntry(path_prefix="/test", target_endpoint="ftp://example.com")++ @staticmethod+ def test_target_endpoint_empty_rejected():+ from jiuwenbox.models.policy import ProxyRouteEntry++ with pytest.raises(ValueError, match="target_endpoint cannot be empty"):+ ProxyRouteEntry(path_prefix="/test", target_endpoint="")++ @staticmethod+ def test_target_endpoint_with_crlf_rejected():+ from jiuwenbox.models.policy import ProxyRouteEntry++ with pytest.raises(ValueError, match="invalid characters"):+ ProxyRouteEntry(path_prefix="/test", target_endpoint="https://api.openai.com\r\nbad")++ @staticmethod+ def test_listen_host_invalid_ip_rejected():+ from jiuwenbox.models.policy import InferencePrivacyProxyPolicy++ with pytest.raises(ValueError, match="valid IP address"):+ InferencePrivacyProxyPolicy(listen_port=8080, listen_host="invalid-host")++ @staticmethod+ def test_listen_host_ipv6_accepted():+ from jiuwenbox.models.policy import InferencePrivacyProxyPolicy++ policy = InferencePrivacyProxyPolicy(listen_port=8080, listen_host="::1")+ assert policy.listen_host == "::1"++ @staticmethod+ def test_path_prefix_root_rejected():+ """Root path '/' should be rejected to prevent catch-all blocking other routes."""+ from jiuwenbox.models.policy import ProxyRouteEntry++ with pytest.raises(ValueError, match="root path"):+ ProxyRouteEntry(path_prefix="/", target_endpoint="http://example.com")++ @staticmethod+ def test_path_prefix_multi_level_rejected():+ """Path prefix with internal slashes should be rejected (single-level only)."""+ from jiuwenbox.models.policy import ProxyRouteEntry++ invalid_prefixes = [+ "/api/v1",+ "/openai/chat",+ "/v1/models",+ "api/v1",+ ]++ for prefix in invalid_prefixes:+ with pytest.raises(ValueError, match="single-level"):+ ProxyRouteEntry(path_prefix=prefix, target_endpoint="http://example.com")++ @staticmethod+ def test_path_prefix_single_level_accepted():+ """Single-level path prefix should be accepted."""+ from jiuwenbox.models.policy import ProxyRouteEntry++ valid_prefixes = [+ "/api",+ "/api-v2",+ "/v1",+ "/llm-proxy",+ "api",+ ]++ for prefix in valid_prefixes:+ route = ProxyRouteEntry(path_prefix=prefix, target_endpoint="http://example.com")+ expected = prefix if prefix.startswith("/") else "/" + prefix+ assert route.path_prefix == expected+++class TestRouteLongestPrefixMatching:+ """Test that longest-prefix matching prevents route collision."""++ @pytest.mark.asyncio+ async def test_longer_prefix_wins_over_string_prefix_collision(+ self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker+ ):+ """Test '/api-v2' wins over '/api' for request '/api-v2/chat'."""+ http_port = mock_llm_server["http_port"]++ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[+ ProxyRoute(+ path_prefix="/api",+ target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",+ api_key="generic-key",+ ),+ ProxyRoute(+ path_prefix="/api-v2",+ target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",+ api_key="specific-key",+ ),+ ],+ )++ proxy = InferencePrivacyProxy(config)+ proxy.enable_route("/api")+ proxy.enable_route("/api-v2")+ await proxy.start()++ try:+ request = (+ "POST /api-v2/chat HTTP/1.1\r\n"+ f"Authorization: Bearer {PLACEHOLDER}\r\n"+ "Content-Length: 13\r\n"+ "\r\n"+ '{"test": true}'+ )++ reader, writer = await asyncio.open_connection("127.0.0.1", proxy_listen_port)+ writer.write(request.encode())+ await writer.drain()++ response = await reader.read(4096)+ response_text = response.decode()++ assert "specific-key" in response_text+ assert "generic-key" not in response_text++ writer.close()+ await writer.wait_closed()+ finally:+ await proxy.stop()++ @pytest.mark.asyncio+ async def test_shorter_prefix_matches_when_no_longer_match(+ self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker+ ):+ """Test '/api' matches '/api/chat' when '/api-v2' doesn't match."""+ http_port = mock_llm_server["http_port"]++ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[+ ProxyRoute(+ path_prefix="/api",+ target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",+ api_key="generic-key",+ ),+ ProxyRoute(+ path_prefix="/api-v2",+ target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",+ api_key="specific-key",+ ),+ ],+ )++ proxy = InferencePrivacyProxy(config)+ proxy.enable_route("/api")+ proxy.enable_route("/api-v2")+ await proxy.start()++ try:+ request = (+ "POST /api/chat HTTP/1.1\r\n"+ f"Authorization: Bearer {PLACEHOLDER}\r\n"+ "Content-Length: 13\r\n"+ "\r\n"+ '{"test": true}'+ )++ reader, writer = await asyncio.open_connection("127.0.0.1", proxy_listen_port)+ writer.write(request.encode())+ await writer.drain()++ response = await reader.read(4096)+ response_text = response.decode()++ assert "generic-key" in response_text+ assert "specific-key" not in response_text++ writer.close()+ await writer.wait_closed()+ finally:+ await proxy.stop()++ @pytest.mark.asyncio+ async def test_route_order_does_not_affect_matching(+ self, mock_llm_server, proxy_listen_port, mock_server_host_for_docker+ ):+ """Route order should not affect longest-prefix matching."""+ http_port = mock_llm_server["http_port"]++ config = InferencePrivacyProxyConfig(+ listen_port=proxy_listen_port,+ routes=[+ ProxyRoute(+ path_prefix="/api-v2",+ target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",+ api_key="specific-key",+ ),+ ProxyRoute(+ path_prefix="/api",+ target_endpoint=f"http://{mock_server_host_for_docker}:{http_port}",+ api_key="generic-key",+ ),+ ],+ )++ proxy = InferencePrivacyProxy(config)+ proxy.enable_route("/api")+ proxy.enable_route("/api-v2")+ await proxy.start()++ try:+ request = (+ "POST /api-v2/chat HTTP/1.1\r\n"+ f"Authorization: Bearer {PLACEHOLDER}\r\n"+ "Content-Length: 13\r\n"+ "\r\n"+ '{"test": true}'+ )++ reader, writer = await asyncio.open_connection("127.0.0.1", proxy_listen_port)+ writer.write(request.encode())+ await writer.drain()++ response = await reader.read(4096)+ response_text = response.decode()++ assert "specific-key" in response_text+ assert "generic-key" not in response_text++ writer.close()+ await writer.wait_closed()+ finally:+ await proxy.stop()+++ os.environ.get("JIUWENBOX_TEST_LLM_ENDPOINT") is None,+ reason="LLM endpoint not configured (set JIUWENBOX_TEST_LLM_ENDPOINT)"+)+class TestRealLLMIntegration:+ """Test proxy with real LLM endpoints (skipped if not configured)."""++ @pytest.mark.asyncio+ @staticmethod+ async def test_llm_chat_completion(+ llm_test_settings,+ llm_proxy_runtime,+ ):+ """Test chat completion through proxy via socket."""+ if not llm_test_settings["available"]:+ pytest.skip("LLM endpoint not reachable (health check failed)")++ proxy_host = llm_proxy_runtime["proxy_host"]+ proxy_port = llm_proxy_runtime["proxy_port"]+ api_client = llm_proxy_runtime["api_client"]+ test_route_cleanup = llm_proxy_runtime["route_cleanup"]++ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/llm-test",+ "target_endpoint": llm_test_settings["endpoint"],+ "api_key": llm_test_settings["api_key"],+ }+ )+ test_route_cleanup.append("llm-test")+ await api_client.post("/api/v1/proxies/llm-test/start")++ request_body = {+ "model": llm_test_settings["model"],+ "messages": [{"role": "user", "content": "Say 'proxy test ok'"}],+ "max_tokens": 20,+ }+ body_json = json.dumps(request_body)++ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ sock.settimeout(30.0)+ sock.connect((proxy_host, proxy_port))++ request = (+ f"POST /llm-test/chat/completions HTTP/1.1\r\n"+ f"Host: {proxy_host}:{proxy_port}\r\n"+ f"Authorization: Bearer {PLACEHOLDER}\r\n"+ f"Content-Type: application/json\r\n"+ f"Content-Length: {len(body_json)}\r\n"+ f"\r\n"+ f"{body_json}"+ )+ sock.send(request.encode())++ response = b""+ while True:+ chunk = sock.recv(4096)+ if not chunk:+ break+ response += chunk+ if b"\r\n\r\n" in response and len(response) > 200:+ break++ sock.close()+ response_text = response.decode()++ assert "200 OK" in response_text or "201 Created" in response_text, \+ f"Expected success, got: {response_text[:500]}"++ logger.info("[test_llm_chat_completion] LLM chat completion successful")++ @pytest.mark.asyncio+ @staticmethod+ async def test_llm_api_key_injection_anthropic(+ llm_test_settings,+ llm_proxy_runtime,+ ):+ """Test Anthropic-style X-Api-Key injection through proxy."""+ if not llm_test_settings["available"]:+ pytest.skip("LLM endpoint not reachable (health check failed)")++ proxy_host = llm_proxy_runtime["proxy_host"]+ proxy_port = llm_proxy_runtime["proxy_port"]+ api_client = llm_proxy_runtime["api_client"]+ test_route_cleanup = llm_proxy_runtime["route_cleanup"]++ await api_client.post(+ "/api/v1/proxies",+ json={+ "path_prefix": "/anthropic-test",+ "target_endpoint": llm_test_settings["endpoint"],+ "api_key": llm_test_settings["api_key"],+ }+ )+ test_route_cleanup.append("anthropic-test")+ await api_client.post("/api/v1/proxies/anthropic-test/start")++ request_body = {+ "model": llm_test_settings["model"],+ "max_tokens": 10,+ "messages": [{"role": "user", "content": "test"}],+ }+ body_json = json.dumps(request_body)++ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ sock.settimeout(30.0)+ sock.connect((proxy_host, proxy_port))++ request = (+ f"POST /anthropic-test/messages HTTP/1.1\r\n"+ f"Host: {proxy_host}:{proxy_port}\r\n"+ f"X-Api-Key: {PLACEHOLDER}\r\n"+ f"anthropic-version: 2023-06-01\r\n"+ f"Content-Type: application/json\r\n"+ f"Content-Length: {len(body_json)}\r\n"+ f"\r\n"+ f"{body_json}"+ )+ sock.send(request.encode())++ response = b""+ while True:+ chunk = sock.recv(4096)+ if not chunk:+ break+ response += chunk+ if b"\r\n\r\n" in response and len(response) > 200:+ break++ sock.close()+ response_text = response.decode()++ assert "200 OK" in response_text or "201 Created" in response_text, \+ f"Expected success, got: {response_text[:500]}"++ logger.info(+ "[test_llm_api_key_injection_anthropic] Anthropic X-Api-Key injection works"+ )diff --git a/jiuwenbox/tests/integration/test_server_api_default.py b/jiuwenbox/tests/integration/test_server_api_default.pyindex f8ab7eaa60..405804f6c4 100644--- a/jiuwenbox/tests/integration/test_server_api_default.py+++ b/jiuwenbox/tests/integration/test_server_api_default.py@@ -3,35 +3,30 @@import copyimport logging+import socketimport textwrap+import time+from pathlib import Pathimport httpximport pytest+import yamlfrom jiuwenbox.models.policy import SecurityPolicyfrom jiuwenbox.supervisor import network as network_modulefrom jiuwenbox.supervisor.bwrap import BwrapConfig-LONG_RUNNING_COMMAND = ["/usr/bin/python3", "-c", "import time; time.sleep(36000)"]-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/pki", "sandbox_path": "/etc/pki", "mode": "ro"},- {"host_path": "/opt", "sandbox_path": "/opt", "mode": "ro"},-]-DEVICE_MOUNTS = [- {"host_path": "/dev/urandom", "sandbox_path": "/dev/urandom"},- {"host_path": "/dev/null", "sandbox_path": "/dev/null"},-]-TMP_DIRECTORY = {"path": "/tmp", "permissions": "1777"}+_DEFAULT_POLICY = yaml.safe_load(+ (Path(__file__).resolve().parents[2] / "configs" / "default-policy.yaml").read_text(encoding="utf-8")+)+_DEFAULT_FILESYSTEM_POLICY = _DEFAULT_POLICY["filesystem_policy"]++SYSTEM_BIND_MOUNTS = copy.deepcopy(_DEFAULT_FILESYSTEM_POLICY["bind_mounts"])+DEVICE_MOUNTS = copy.deepcopy(_DEFAULT_FILESYSTEM_POLICY["device"])+DEFAULT_FILES = copy.deepcopy(_DEFAULT_FILESYSTEM_POLICY.get("files", []))+SANDBOX_WORKSPACE = "/root/.jiuwenbox"+DIRECTORIES = copy.deepcopy(_DEFAULT_FILESYSTEM_POLICY["directories"])+logger = logging.getLogger(__name__)@@ -91,6 +86,69 @@ def _sandbox_health_url(server_endpoint: str) -> str:return f"{_normalize_endpoint(server_endpoint).rstrip('/')}/health"+def _host_network_ip_from_sandbox(client, sandbox_id: str) -> str:+ script = textwrap.dedent(+ """+ 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 ""++ route = run_ip(["-4", "route", "get", "1.1.1.1"])+ match = re.search(r"\\bsrc\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)", route)+ if match and not match.group(1).startswith("127."):+ print(match.group(1))+ sys.exit(0)++ addresses = run_ip(["-4", "-o", "addr", "show", "scope", "global"])+ for address in re.findall(r"\\binet\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)/", addresses):+ if not address.startswith("127."):+ print(address)+ sys.exit(0)++ print("failed to resolve host-network IPv4 address from sandbox", file=sys.stderr)+ sys.exit(1)+ """+ ).strip()+ response = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={+ "command": ["python3", "-c", script],+ "timeout_seconds": 5,+ })+ assert response.status_code == 200, response.text+ data = response.json()+ assert data["exit_code"] == 0, data+ return data["stdout"].strip()+++def _unused_host_network_tcp_port_from_sandbox(client, sandbox_id: str) -> int:+ script = textwrap.dedent(+ """+ import socket++ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.bind(("0.0.0.0", 0))+ print(sock.getsockname()[1])+ """+ ).strip()+ response = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={+ "command": ["python3", "-c", script],+ "timeout_seconds": 5,+ })+ assert response.status_code == 200, response.text+ data = response.json()+ assert data["exit_code"] == 0, data+ return int(data["stdout"].strip())++def _capability_check_script(cap_bit: int) -> str:return textwrap.dedent(f"""@@ -172,12 +230,8 @@ def _with_runtime_support(policy: dict) -> dict:bind_mounts.append(mount.copy())directories = filesystem_policy.setdefault("directories", [])- if (- "/tmp" in filesystem_policy.get("read_write", [])- and not _has_directory(directories, "/tmp")- and not _has_bind_mount(bind_mounts, "/tmp")- ):- directories.append(TMP_DIRECTORY.copy())+ for directory_entry in DIRECTORIES:+ directories.append(directory_entry.copy())return runtime_policy@@ -213,10 +267,8 @@ def create_sandbox_with_policy(client):name_prefix: str,policy: dict,policy_mode: str = "override",- command: list[str] | None = None,) -> dict:response = client.post("/api/v1/sandboxes", json={- "command": command or LONG_RUNNING_COMMAND,"policy_mode": policy_mode,"policy": _with_runtime_support(policy),})@@ -249,19 +301,18 @@ class TestSandboxCRUD:@staticmethoddef test_create_sandbox(client):- resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "hello"],- })+ resp = client.post("/api/v1/sandboxes", json={})assert resp.status_code == 201data = resp.json()assert "id" in dataassert "name" not in data- assert data["command"] == []+ assert "command" not in data+ assert "workdir" not in dataassert data["phase"] in ("provisioning", "ready", "error")@staticmethoddef test_list_sandboxes_after_create(client):- create_resp = client.post("/api/v1/sandboxes", json={"command": ["/usr/bin/echo"]})+ create_resp = client.post("/api/v1/sandboxes", json={})sandbox_id = create_resp.json()["id"]resp = client.get("/api/v1/sandboxes")assert resp.status_code == 200@@ -271,9 +322,7 @@ class TestSandboxCRUD:@staticmethoddef test_get_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- })+ create_resp = client.post("/api/v1/sandboxes", json={})sandbox_id = create_resp.json()["id"]resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")@@ -289,9 +338,7 @@ class TestSandboxCRUD:@staticmethoddef test_delete_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- })+ create_resp = client.post("/api/v1/sandboxes", json={})sandbox_id = create_resp.json()["id"]resp = client.delete(f"/api/v1/sandboxes/{sandbox_id}")@@ -304,9 +351,7 @@ class TestSandboxCRUD:class TestSandboxLifecycle:@staticmethoddef test_start_stopped_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/sleep", "3600"],- })+ create_resp = client.post("/api/v1/sandboxes", json={})sandbox_id = create_resp.json()["id"]stop_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/stop")@@ -319,9 +364,7 @@ class TestSandboxLifecycle:@staticmethoddef test_stop_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/sleep", "3600"],- })+ create_resp = client.post("/api/v1/sandboxes", json={})sandbox_id = create_resp.json()["id"]resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/stop")@@ -330,9 +373,7 @@ class TestSandboxLifecycle:@staticmethoddef test_restart_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/sleep", "3600"],- })+ create_resp = client.post("/api/v1/sandboxes", json={})sandbox_id = create_resp.json()["id"]resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/restart")@@ -341,9 +382,14 @@ class TestSandboxLifecycle:@staticmethoddef test_sandbox_process_cannot_target_sandbox_daemon(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": LONG_RUNNING_COMMAND,- })+ # The long-running daemon shares the sandbox PID namespace with+ # user-spawned children (the daemon is PID 1 in that namespace).+ # The kernel protects PID 1 of a namespace from in-namespace senders+ # for any signal that PID 1 has not registered a handler for; the+ # daemon registers no handlers, so SIGTERM/SIGINT/SIGKILL from user+ # code must all be silently dropped and the daemon must continue to+ # service requests.+ create_resp = client.post("/api/v1/sandboxes", json={})assert create_resp.status_code == 201sandbox = create_resp.json()assert sandbox["phase"] == "ready", sandbox@@ -351,51 +397,57 @@ class TestSandboxLifecycle:kill_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={"command": [- "/usr/bin/python3",+ "python3","-c",textwrap.dedent("""import os- from pathlib import Path+ import signalimport sys+ import time- needle = "jiuwenbox-sandbox-" + "daemon.py"- daemon_pids = []- current_pid = str(os.getpid())- for cmdline_path in Path("/proc").glob("[0-9]*/cmdline"):- pid = cmdline_path.parent.name- if pid == current_pid:- continue+ targets = [signal.SIGTERM, signal.SIGINT, signal.SIGKILL,+ signal.SIGHUP, signal.SIGUSR1, signal.SIGUSR2]+ delivered = []+ for sig in targets:try:- cmdline = cmdline_path.read_bytes().replace(b"\\0", b" ").decode(- errors="replace",- )- except (FileNotFoundError, PermissionError, ProcessLookupError):+ os.kill(1, sig)+ except ProcessLookupError:+ delivered.append(f"missing:{sig}")+ except PermissionError:continue- if needle in cmdline:- daemon_pids.append(pid)-- if daemon_pids:- print(f"daemon-visible:{','.join(daemon_pids)}")- sys.exit(7)-- print("daemon-hidden")+ except OSError as exc:+ delivered.append(f"error:{sig}:{exc.errno}")+ time.sleep(0.5)++ try:+ os.kill(1, 0)+ except ProcessLookupError:+ print("daemon-killed")+ sys.exit(1)+ except PermissionError:+ pass++ if delivered:+ print(f"unexpected:{','.join(delivered)}")+ sys.exit(2)+ print("daemon-survived")""").strip(),],- "timeout_seconds": 5,+ "timeout_seconds": 10,})assert kill_resp.status_code == 200kill_data = kill_resp.json()assert kill_data["exit_code"] == 0, kill_data- assert kill_data["stdout"].strip() == "daemon-hidden"+ assert kill_data["stdout"].strip() == "daemon-survived"status_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")assert status_resp.status_code == 200assert status_resp.json()["phase"] == "ready", status_resp.json()exec_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={- "command": ["/usr/bin/echo", "daemon-alive"],+ "command": ["echo", "daemon-alive"],"timeout_seconds": 5,})assert exec_resp.status_code == 200@@ -404,10 +456,14 @@ class TestSandboxLifecycle:assert exec_data["stdout"].strip() == "daemon-alive"@staticmethod- def test_sandbox_process_cannot_see_sandbox_daemon(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": LONG_RUNNING_COMMAND,- })+ def test_sandbox_process_cannot_inspect_sandbox_daemon_memory(client):+ # PID 1 of the sandbox PID namespace is the long-running daemon.+ # Reading the daemon's address space (``/proc/1/mem``) requires+ # CAP_SYS_PTRACE (stripped by the default policy) and+ # ``ptrace(PTRACE_ATTACH, 1)`` is blocked by seccomp. Together+ # these prevent a sandboxed process from extracting secrets from+ # or hijacking the long-running daemon.+ create_resp = client.post("/api/v1/sandboxes", json={})assert create_resp.status_code == 201sandbox = create_resp.json()assert sandbox["phase"] == "ready", sandbox@@ -415,47 +471,54 @@ class TestSandboxLifecycle:script = textwrap.dedent("""+ import ctypesimport os- from pathlib import Pathimport sys- needle = "jiuwenbox-sandbox-" + "daemon.py"- daemon_cmdlines = []- current_pid = str(os.getpid())- for cmdline_path in Path("/proc").glob("[0-9]*/cmdline"):- pid = cmdline_path.parent.name- if pid == current_pid:- continue+ try:+ fd = os.open('/proc/1/mem', os.O_RDONLY)+ except PermissionError:+ pass+ except FileNotFoundError:+ pass+ else:try:- cmdline = cmdline_path.read_bytes().replace(b"\\0", b" ").decode(- errors="replace",- )- except (FileNotFoundError, PermissionError, ProcessLookupError):- continue- if needle in cmdline:- daemon_cmdlines.append(cmdline)-- if daemon_cmdlines:- print("\\n".join(daemon_cmdlines))- sys.exit(7)+ os.read(fd, 16)+ except PermissionError:+ pass+ except OSError:+ pass+ else:+ os.close(fd)+ print('daemon-memory-readable')+ sys.exit(2)+ os.close(fd)- print("daemon-hidden")+ try:+ libc = ctypes.CDLL('libc.so.6', use_errno=True)+ PTRACE_ATTACH = 16+ rc = libc.ptrace(PTRACE_ATTACH, 1, 0, 0)+ if rc == 0:+ print('daemon-ptraceable')+ sys.exit(3)+ except OSError:+ pass++ print('daemon-protected')""").strip()response = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={- "command": ["/usr/bin/python3", "-c", script],+ "command": ["python3", "-c", script],"timeout_seconds": 5,})assert response.status_code == 200data = response.json()assert data["exit_code"] == 0, data- assert data["stdout"].strip() == "daemon-hidden"+ assert data["stdout"].strip() == "daemon-protected"@staticmethoddef test_get_logs(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- })+ create_resp = client.post("/api/v1/sandboxes", json={})sandbox_id = create_resp.json()["id"]resp = client.get(f"/api/v1/sandboxes/{sandbox_id}/logs")@@ -465,9 +528,7 @@ class TestSandboxLifecycle:class TestPolicyAPI:@staticmethoddef test_get_sandbox_policy(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- })+ create_resp = client.post("/api/v1/sandboxes", json={})sandbox_id = create_resp.json()["id"]resp = client.get(f"/api/v1/policies/{sandbox_id}")@@ -475,8 +536,10 @@ class TestPolicyAPI:data = resp.json()assert data["version"] == 1assert data["name"] == "server-default"+ assert data["environment"] == {}+ assert "sandbox_workspace" not in dataassert "resources" not in data- assert data["filesystem_policy"]["directories"] == [{'path': '/home', 'permissions': '0755'},+ assert data["filesystem_policy"]["directories"] == [{'path': '/home', 'permissions': '0777'},{'path': '/tmp', 'permissions': '1777'}]assert data["filesystem_policy"]["read_only"] == ["/",@@ -491,6 +554,7 @@ class TestPolicyAPI:assert data["filesystem_policy"]["read_write"] == ["/home", "/tmp"]assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTSassert data["filesystem_policy"]["device"] == DEVICE_MOUNTS+ assert data["filesystem_policy"]["files"] == DEFAULT_FILESassert data["process"]["run_as_user"] == "sandbox"assert data["process"]["run_as_group"] == "sandbox"assert data["namespace"] == {@@ -510,12 +574,12 @@ class TestPolicyAPI:assert data["network"]["egress"]["default"] == "allow"assert data["network"]["egress"]["blocked_domains"] == ["ip.me"]assert data["network"]["egress"]["allowed_ports"] == [443, 80]- assert data["network"]["ingress"]["default"] == "deny"+ assert data["network"]["ingress"]["default"] == "allow"assert data["network"]["ingress"]["allowed_domains"] == ["localhost"]assert data["network"]["ingress"]["allowed_ips"] == ["127.0.0.1/32", "::1/128"]assert data["network"]["ingress"]["blocked_ips"] == []assert data["network"]["ingress"]["allowed_ports"] == [8080]- assert data["network"]["ingress"]["blocked_ports"] == [22]+ assert data["network"]["ingress"]["blocked_ports"] == []assert "profile" not in data["syscall"]assert "blocked" not in data["syscall"]assert "mount" in data["syscall"]["x86_64"]["blocked"]@@ -526,10 +590,12 @@ class TestPolicyAPI:@staticmethoddef test_append_policy_merges_with_server_default(client):create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],"policy_mode": "append","policy": {"name": "appended-policy",+ "environment": {+ "JIUWENBOX_APPEND_ENV": "append-ok",+ },"filesystem_policy": {"directories": [{"path": "/tmp/appended-dir", "permissions": "0700"}],"read_only": ["/var/log"],@@ -577,6 +643,8 @@ class TestPolicyAPI:assert resp.status_code == 200data = resp.json()assert data["name"] == "appended-policy"+ assert data["environment"] == {"JIUWENBOX_APPEND_ENV": "append-ok"}+ assert "sandbox_workspace" not in dataassert data["network"]["egress"]["allowed_domains"] == ["baidu.com","extra.example.com",@@ -607,7 +675,7 @@ class TestPolicyAPI:"/var/log",]assert data["filesystem_policy"]["read_write"] == ["/home", "/tmp", "/var/tmp"]- assert data["filesystem_policy"]["directories"] == [{'path': '/home', 'permissions': '0755'},+ assert data["filesystem_policy"]["directories"] == [{'path': '/home', 'permissions': '0777'},{'path': '/tmp', 'permissions': '1777'},{"path": "/tmp/appended-dir", "permissions": "0700"}]assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTS + [{@@ -616,6 +684,7 @@ class TestPolicyAPI:"mode": "rw",}]assert data["filesystem_policy"]["device"] == DEVICE_MOUNTS+ assert data["filesystem_policy"]["files"] == DEFAULT_FILESassert data["process"]["run_as_user"] == "root"assert data["process"]["run_as_group"] == "root"assert data["namespace"] == {@@ -636,10 +705,12 @@ class TestPolicyAPI:@staticmethoddef test_override_policy_replaces_server_default(client):create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],"policy_mode": "override","policy": {"name": "override-policy",+ "environment": {+ "JIUWENBOX_OVERRIDE_ENV": "override-ok",+ },"filesystem_policy": {"directories": [{"path": "/tmp/override-dir",@@ -697,6 +768,8 @@ class TestPolicyAPI:assert resp.status_code == 200data = resp.json()assert data["name"] == "override-policy"+ assert data["environment"] == {"JIUWENBOX_OVERRIDE_ENV": "override-ok"}+ assert "sandbox_workspace" not in dataassert data["network"]["mode"] == "host"assert data["network"]["egress"]["allowed_domains"] == ["override.example.com"]assert data["network"]["egress"]["allowed_ips"] == ["198.51.100.10/32"]@@ -711,6 +784,7 @@ class TestPolicyAPI:assert data["filesystem_policy"]["read_write"] == ["/var/tmp"]assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTSassert data["filesystem_policy"]["device"] == []+ assert data["filesystem_policy"]["files"] == []assert data["filesystem_policy"]["directories"] == [{"path": "/tmp/override-dir","permissions": "0700",@@ -737,12 +811,11 @@ class TestPolicyAPI:@staticmethoddef test_create_sandbox_rejects_direct_sandbox_bind_mount(client):resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "hello"],"policy": {"name": "bad-sandbox-mount-policy","filesystem_policy": {"bind_mounts": [{- "host_path": "/sandbox/manual",+ "host_path": f"{SANDBOX_WORKSPACE}/manual","sandbox_path": "/tmp/manual","mode": "rw",}],@@ -754,17 +827,16 @@ class TestPolicyAPI:})assert resp.status_code == 400- assert "/sandbox" in resp.json()["error"]+ assert SANDBOX_WORKSPACE in resp.json()["error"]@staticmethoddef test_create_sandbox_rejects_direct_sandbox_device_mount(client):resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "hello"],"policy": {"name": "bad-sandbox-device-policy","filesystem_policy": {"device": [{- "host_path": "/sandbox/manual-device",+ "host_path": f"{SANDBOX_WORKSPACE}/manual-device","sandbox_path": "/dev/manual-device",}],},@@ -775,16 +847,15 @@ class TestPolicyAPI:})assert resp.status_code == 400- assert "/sandbox" in resp.json()["error"]+ assert SANDBOX_WORKSPACE in resp.json()["error"]@staticmethoddef test_create_sandbox_rejects_direct_sandbox_path(client):resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "hello"],"policy": {"name": "bad-sandbox-path-policy","filesystem_policy": {- "read_write": ["/sandbox/manual"],+ "read_write": [f"{SANDBOX_WORKSPACE}/manual"],},"network": {"mode": "host",@@ -793,17 +864,16 @@ class TestPolicyAPI:})assert resp.status_code == 400- assert "/sandbox" in resp.json()["error"]+ assert SANDBOX_WORKSPACE in resp.json()["error"]@staticmethoddef test_create_sandbox_rejects_direct_sandbox_directory(client):resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "hello"],"policy": {"name": "bad-sandbox-dir-policy","filesystem_policy": {"directories": [{- "path": "/sandbox/manual",+ "path": f"{SANDBOX_WORKSPACE}/manual","permissions": "0700",}],},@@ -814,7 +884,27 @@ class TestPolicyAPI:})assert resp.status_code == 400- assert "/sandbox" in resp.json()["error"]+ assert SANDBOX_WORKSPACE in resp.json()["error"]++ @staticmethod+ def test_create_sandbox_rejects_direct_sandbox_file(client):+ resp = client.post("/api/v1/sandboxes", json={+ "policy": {+ "name": "bad-sandbox-file-policy",+ "filesystem_policy": {+ "files": [{+ "path": f"{SANDBOX_WORKSPACE}/manual-file",+ "permissions": "0600",+ }],+ },+ "network": {+ "mode": "host",+ },+ },+ })++ assert resp.status_code == 400+ assert SANDBOX_WORKSPACE in resp.json()["error"]class TestPolicyEnforcement:@@ -907,7 +997,7 @@ class TestPolicyEnforcement:response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={"command": [- "/usr/bin/python3",+ "python","-c",("import os, stat; "@@ -924,6 +1014,105 @@ class TestPolicyEnforcement:assert data["exit_code"] == 0, dataassert data["stdout"].splitlines() == ["True", "0o700"]+ @staticmethod+ def test_filesystem_directories_rule_creates_nested_directory(+ client,+ create_sandbox_with_policy,+ ):+ sandbox = create_sandbox_with_policy(+ name_prefix="fs-nested-dir",+ policy={+ "name": "fs-nested-dir-policy",+ "filesystem_policy": {+ "directories": [{+ "path": "/policy-created/level1/level2",+ "permissions": "0711",+ }],+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {+ "compatibility": "disabled",+ },+ "network": {+ "mode": "host",+ },+ },+ )++ response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={+ "command": [+ "python3",+ "-c",+ (+ "import os, stat; "+ "from pathlib import Path; "+ "parent = Path('/policy-created/level1'); "+ "path = parent / 'level2'; "+ "print(Path('/policy-created').is_dir()); "+ "print(parent.is_dir()); "+ "print(path.is_dir()); "+ "print(oct(stat.S_IMODE(os.stat(path).st_mode)))"+ ),+ ],+ "timeout_seconds": 5,+ })+ assert response.status_code == 200+ data = response.json()+ assert data["exit_code"] == 0, data+ assert data["stdout"].splitlines() == ["True", "True", "True", "0o711"]++ @staticmethod+ def test_filesystem_files_rule_creates_nested_empty_file(+ client,+ create_sandbox_with_policy,+ ):+ sandbox = create_sandbox_with_policy(+ name_prefix="fs-file",+ policy={+ "name": "fs-file-policy",+ "filesystem_policy": {+ "files": [{+ "path": "/policy-created/level1/marker.txt",+ "permissions": "0640",+ }],+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {+ "compatibility": "disabled",+ },+ "network": {+ "mode": "host",+ },+ },+ )++ response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={+ "command": [+ "python3",+ "-c",+ (+ "import os, stat; "+ "from pathlib import Path; "+ "parent = Path('/policy-created/level1'); "+ "path = parent / 'marker.txt'; "+ "print(Path('/policy-created').is_dir()); "+ "print(parent.is_dir()); "+ "print(path.is_file()); "+ "print(path.read_text()); "+ "print(oct(stat.S_IMODE(os.stat(path).st_mode)))"+ ),+ ],+ "timeout_seconds": 5,+ })+ assert response.status_code == 200+ data = response.json()+ assert data["exit_code"] == 0, data+ lines = data["stdout"].splitlines()+ assert lines[:4] == ["True", "True", "True", ""]+ assert lines[4] in {"0o640", "0o646"}, lines+@staticmethoddef test_filesystem_directories_rule_creates_directory_under_home(client,@@ -959,7 +1148,7 @@ class TestPolicyEnforcement:response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={"command": [- "/usr/bin/python3",+ "python3","-c",("import os; "@@ -1014,7 +1203,7 @@ class TestPolicyEnforcement:"print(sys.stdin.read())")response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", script],+ "command": ["python3", "-c", script],"workdir": "/tmp","env": {"BOX_TEST": "env-ok"},"stdin": "stdin-ok",@@ -1025,6 +1214,53 @@ class TestPolicyEnforcement:assert data["exit_code"] == 0, dataassert data["stdout"].splitlines() == ["env-ok", "/tmp", "stdin-ok"]+ @staticmethod+ def test_policy_environment_applies_to_all_exec_processes(+ client,+ create_sandbox_with_policy,+ ):+ sandbox = create_sandbox_with_policy(+ name_prefix="policy-env",+ policy={+ "name": "policy-env-policy",+ "environment": {+ "JIUWENBOX_POLICY_ENV": "policy-env-ok",+ "JIUWENBOX_SHARED_ENV": "from-policy",+ },+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "network": {+ "mode": "host",+ },+ },+ )++ script = (+ "import os; "+ "print(os.environ['JIUWENBOX_POLICY_ENV']); "+ "print(os.environ['JIUWENBOX_SHARED_ENV'])"+ )+ response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={+ "command": ["python3", "-c", script],+ "timeout_seconds": 5,+ })+ assert response.status_code == 200+ data = response.json()+ assert data["exit_code"] == 0, data+ assert data["stdout"].splitlines() == ["policy-env-ok", "from-policy"]++ response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={+ "command": ["python3", "-c", script],+ "env": {"JIUWENBOX_SHARED_ENV": "from-exec"},+ "timeout_seconds": 5,+ })+ assert response.status_code == 200+ data = response.json()+ assert data["exit_code"] == 0, data+ assert data["stdout"].splitlines() == ["policy-env-ok", "from-exec"]+@staticmethoddef test_exec_runs_javascript_code(client,@@ -1051,7 +1287,7 @@ class TestPolicyEnforcement:"console.log(`sum=${sum}`);")response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/node", "-e", js_code],+ "command": ["node", "-e", js_code],"env": {"BOX_JS_TEST": "js-ok"},"timeout_seconds": 5,})@@ -1132,7 +1368,7 @@ class TestPolicyEnforcement:setup = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={"command": [- "/usr/bin/python3",+ "python3","-c",("from pathlib import Path; "@@ -1190,7 +1426,7 @@ class TestPolicyEnforcement:setup = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={"command": [- "/usr/bin/python3",+ "python3","-c",("from pathlib import Path; "@@ -1241,7 +1477,7 @@ class TestPolicyEnforcement:)response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/id", "-u"],+ "command": ["id", "-u"],"timeout_seconds": 5,})assert response.status_code == 200@@ -1250,7 +1486,7 @@ class TestPolicyEnforcement:assert uid_data["stdout"].strip() == "0"response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/id", "-g"],+ "command": ["id", "-g"],"timeout_seconds": 5,})assert response.status_code == 200@@ -1265,7 +1501,6 @@ class TestPolicyEnforcement:):sandbox = create_sandbox_with_policy(name_prefix="syscall-block",- command=["/usr/bin/sleep", "3600"],policy={"name": "syscall-block-policy","filesystem_policy": {@@ -1284,7 +1519,7 @@ class TestPolicyEnforcement:response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={"command": [- "/usr/bin/python3",+ "python3","-c",textwrap.dedent("""@@ -1350,7 +1585,7 @@ class TestPolicyEnforcement:)response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", "import os; print(os.getpid())"],+ "command": ["python3", "-c", "import os; print(os.getpid())"],"timeout_seconds": 5,})assert response.status_code == 200@@ -1389,7 +1624,7 @@ class TestPolicyEnforcement:)response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _capability_check_script(13)],+ "command": ["python", "-c", _capability_check_script(13)],"timeout_seconds": 5,})assert response.status_code == 200@@ -1428,7 +1663,7 @@ class TestPolicyEnforcement:)response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _capability_check_script(13)],+ "command": ["python", "-c", _capability_check_script(13)],"timeout_seconds": 5,})assert response.status_code == 200@@ -1441,7 +1676,6 @@ class TestPolicyEnforcement:client,):create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "landlock-ok"],"policy": _with_runtime_support({"name": "landlock-hard-policy","filesystem_policy": {@@ -1470,7 +1704,6 @@ class TestPolicyEnforcement:):create_resp = client.post("/api/v1/sandboxes", json={"name": "landlock-rules",- "command": LONG_RUNNING_COMMAND,"policy": _with_runtime_support({"name": "landlock-rules-policy","filesystem_policy": {@@ -1502,7 +1735,7 @@ class TestPolicyEnforcement:assert allowed.read_text() == "landlock-allowed"try:- Path("/run/jiuwenbox-landlock-launcher.py").read_text()+ Path("/jiuwenbox/landlock-launcher.py").read_text()except PermissionError:print("landlock-denied")sys.exit(7)@@ -1511,7 +1744,7 @@ class TestPolicyEnforcement:""").strip()response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", script],+ "command": ["python", "-c", script],"timeout_seconds": 5,})assert response.status_code == 200@@ -1547,7 +1780,7 @@ class TestPolicyEnforcement:"print('unexpected-success')")response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", script, _sandbox_health_url(server_endpoint)],+ "command": ["python", "-c", script, _sandbox_health_url(server_endpoint)],"timeout_seconds": 5,})assert response.status_code == 200@@ -1559,7 +1792,6 @@ class TestPolicyEnforcement:def test_network_mode_host_allows_http_requests(client,create_sandbox_with_policy,- server_endpoint,):sandbox = create_sandbox_with_policy(name_prefix="net-host",@@ -1576,24 +1808,108 @@ class TestPolicyEnforcement:},)- script = (- "import sys, urllib.request; "- "print(urllib.request.urlopen(sys.argv[1], timeout=2).read().decode())"- )+ 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": ["/usr/bin/python3", "-c", script, _sandbox_health_url(server_endpoint)],- "timeout_seconds": 5,+ "command": ["python3", "-c", script, "https://www.huawei.com/"],+ "timeout_seconds": 15,})assert response.status_code == 200data = response.json()assert data["exit_code"] == 0- assert '"status":"ok"' in data["stdout"].replace(" ", "")+ assert "huawei.com" in data["stdout"].lower()@staticmethod- def test_default_policy_allows_network_https(client):- response = client.post("/api/v1/sandboxes", json={- "command": LONG_RUNNING_COMMAND,+ def test_host_network_allows_external_tcp_connection_to_sandbox_process(+ client,+ create_sandbox_with_policy,+ ):+ sandbox = create_sandbox_with_policy(+ name_prefix="net-host-listener",+ policy={+ "name": "net-host-listener-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "network": {+ "mode": "host",+ "egress": {"default": "allow"},+ "ingress": {"default": "allow"},+ },+ },+ )+ host = _host_network_ip_from_sandbox(client, sandbox["id"])+ port = _unused_host_network_tcp_port_from_sandbox(client, sandbox["id"])+ script = textwrap.dedent(+ """+ import socket+ import sys++ port = int(sys.argv[1])+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ server.bind(("0.0.0.0", port))+ server.listen(1)+ print("server-listening", flush=True)+ while True:+ conn, _ = server.accept()+ data = conn.recv(64)+ print("received:" + data.decode(), flush=True)+ conn.sendall(b"pong-from-sandbox")+ conn.close()+ """+ ).strip()+ response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec_background", json={+ "command": ["python3", "-c", script, str(port)],+ "timeout_seconds": 10,})+ assert response.status_code == 200, response.text+ background = response.json()+ assert background["started"] is True, background+ assert isinstance(background["pid"], int), background+ assert background["error_message"] is None++ deadline = time.monotonic() + 8+ last_error = None+ payload = b""+ while time.monotonic() < deadline:+ try:+ with socket.create_connection((host, port), timeout=0.5) as sock:+ sock.sendall(b"ping-from-host")+ payload = sock.recv(64)+ break+ except OSError as exc:+ last_error = exc+ time.sleep(0.1)+ else:+ raise AssertionError(+ f"sandbox tcp server did not accept connections: {last_error}; "+ f"background={background}"+ )++ assert payload == b"pong-from-sandbox"+ for index in range(5):+ with socket.create_connection((host, port), timeout=0.5) as sock:+ sock.sendall(f"ping-{index}".encode())+ assert sock.recv(64) == b"pong-from-sandbox"+ time.sleep(0.5)++ @staticmethod+ def test_default_policy_allows_network_https(client):+ response = client.post("/api/v1/sandboxes", json={})assert response.status_code == 201, response.textsandbox = response.json()assert sandbox["phase"] == "ready", sandbox@@ -1613,7 +1929,7 @@ class TestPolicyEnforcement:""").strip()response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", script, "https://www.huawei.com/"],+ "command": ["python3", "-c", script, "https://www.huawei.com/"],"timeout_seconds": 15,})assert response.status_code == 200@@ -1622,10 +1938,38 @@ class TestPolicyEnforcement:assert "huawei.com" in data["stdout"].lower()@staticmethod- def test_default_policy_does_not_expose_sensitive_etc_files(client):- response = client.post("/api/v1/sandboxes", json={- "command": LONG_RUNNING_COMMAND,+ def test_default_policy_blocks_access_to_box_server_health(client, server_endpoint):+ response = client.post("/api/v1/sandboxes", json={})+ assert response.status_code == 201, response.text+ sandbox = response.json()+ assert sandbox["phase"] == "ready", sandbox++ script = textwrap.dedent(+ """+ import sys+ import urllib.request++ try:+ urllib.request.urlopen(sys.argv[1], timeout=3).read()+ except Exception as exc:+ print(type(exc).__name__)+ sys.exit(7)++ print("unexpected-success")+ """+ ).strip()+ response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={+ "command": ["python3", "-c", script, _sandbox_health_url(server_endpoint)],+ "timeout_seconds": 10,})+ assert response.status_code == 200+ data = response.json()+ assert data["exit_code"] == 7, data+ assert "unexpected-success" not in data["stdout"]++ @staticmethod+ def test_default_policy_does_not_expose_sensitive_etc_files(client):+ response = client.post("/api/v1/sandboxes", json={})assert response.status_code == 201, response.textsandbox = response.json()assert sandbox["phase"] == "ready", sandbox@@ -1654,7 +1998,7 @@ class TestPolicyEnforcement:""").strip()response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", script],+ "command": ["python3", "-c", script],"timeout_seconds": 5,})assert response.status_code == 200@@ -1695,7 +2039,7 @@ class TestPolicyEnforcement:)response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _loopback_ingress_script(True), "18081"],+ "command": ["python3", "-c", _loopback_ingress_script(True), "18081"],"timeout_seconds": 5,})assert response.status_code == 200@@ -1730,7 +2074,7 @@ class TestPolicyEnforcement:)response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _loopback_ingress_script(False), "18082"],+ "command": ["python3", "-c", _loopback_ingress_script(False), "18082"],"timeout_seconds": 5,})assert response.status_code == 200@@ -1764,7 +2108,7 @@ class TestPolicyEnforcement:)first_exec = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _loopback_ingress_script(True), "18083"],+ "command": ["python3", "-c", _loopback_ingress_script(True), "18083"],"timeout_seconds": 5,})assert first_exec.status_code == 200@@ -1778,7 +2122,7 @@ class TestPolicyEnforcement:assert start_response.status_code == 200second_exec = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _loopback_ingress_script(True), "18083"],+ "command": ["python3", "-c", _loopback_ingress_script(True), "18083"],"timeout_seconds": 5,})assert second_exec.status_code == 200@@ -1788,6 +2132,558 @@ class TestPolicyEnforcement:delete_response = client.delete(f"/api/v1/sandboxes/{sandbox['id']}")assert delete_response.status_code == 204+ # ------------------------------------------------------------------+ # ``/jiuwenbox`` runtime-script integrity+ #+ # jiuwenbox places two trusted scripts on a tmpfs at ``/jiuwenbox``+ # inside every sandbox:+ #+ # * ``/jiuwenbox/landlock-launcher.py`` - applies the Landlock+ # ruleset, then either ``compile``/``exec``s the daemon+ # in-process or ``execvp``s a one-shot user command.+ # * ``/jiuwenbox/sandbox-daemon.py`` - long-running daemon that+ # fronts ``exec`` / ``write_file`` / ``read_file`` / ``list_dir``+ # IPC requests with the policy uid/gid, mount layout, seccomp+ # filter, and Landlock ruleset already applied.+ #+ # If user code inside the sandbox could read, modify, replace, or+ # unlink either script, the entire trust model collapses: a hostile+ # payload could rewrite the daemon and gain a foothold for every+ # *subsequent* exec the box-server dispatches into the sandbox.+ #+ # The launcher pre-reads both scripts into memory **before** Landlock+ # is installed, so user code (which always runs strictly after+ # Landlock is in force) is supposed to see ``/jiuwenbox`` as+ # completely off-limits. The two cases below pin that contract; the+ # complementary ``TestReservedSandboxPaths`` class below proves that+ # user policies cannot widen the Landlock allowlist to expose+ # ``/jiuwenbox`` from the outside.+ # ------------------------------------------------------------------++ _RESERVED_SCRIPT_DAEMON = "/jiuwenbox/sandbox-daemon.py"+ _RESERVED_SCRIPT_LAUNCHER = "/jiuwenbox/landlock-launcher.py"++ _RESERVED_INTEGRITY_POLICY = {+ "name": "reserved-script-integrity-policy",+ "filesystem_policy": {+ # /jiuwenbox is intentionally NOT listed below - the runtime+ # artifacts there must remain inaccessible to user code, and+ # PolicyEngine would reject the policy outright if it tried.+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {+ "compatibility": "hard_requirement",+ },+ "network": {+ "mode": "host",+ },+ }++ @staticmethod+ def test_reserved_dir_scripts_cannot_be_tampered_with(+ create_sandbox_with_policy,+ client,+ ):+ """User code must hit ``PermissionError`` on every flavour of+ access against ``/jiuwenbox`` and the trusted scripts inside it.++ The script returns exit code 0 only when *every* attempted attack+ was rejected; any successful read/write/delete/symlink/listdir+ would surface as a non-zero exit code with a label in stderr, so+ the happy path here is the locked-down path.+ """+ sandbox = create_sandbox_with_policy(+ name_prefix="reserved-script-integrity",+ policy=TestPolicyEnforcement._RESERVED_INTEGRITY_POLICY,+ )++ daemon_path = TestPolicyEnforcement._RESERVED_SCRIPT_DAEMON+ launcher_path = TestPolicyEnforcement._RESERVED_SCRIPT_LAUNCHER++ attack_script = textwrap.dedent(+ f"""+ import errno+ import os+ import sys++ DAEMON = {daemon_path!r}+ LAUNCHER = {launcher_path!r}++ failures = []++ # Errnos that mean the attack was rejected. The first three+ # come straight from Landlock (EACCES on read/write/exec,+ # EPERM on operations like unlink, EROFS on tmpfs that we+ # remount read-only). The last two come from the filesystem+ # layer doing its own job *before* Landlock even gets to+ # rule:+ # * EEXIST - ``os.symlink(target, link)`` refuses to clobber+ # an existing file at ``link``. The daemon script is+ # therefore not replaced, which is exactly the+ # containment guarantee we are pinning here.+ # * EXDEV - ``os.rename(src, dst)`` cannot move a file+ # across different mounts. ``/jiuwenbox`` is its own+ # tmpfs and ``/tmp`` is another one, so the+ # rename-shadow attack cannot complete regardless of+ # Landlock. Treating this as containment success+ # documents the additional defence-in-depth that the+ # runtime relies on.+ BLOCKED_ERRNOS = (+ errno.EACCES,+ errno.EPERM,+ errno.EROFS,+ errno.EEXIST,+ errno.EXDEV,+ )++ def expect_blocked(label, fn):+ try:+ fn()+ except PermissionError:+ return+ except FileNotFoundError:+ # Landlock can mask the path so it appears not to+ # exist; that is also a containment success.+ return+ except FileExistsError:+ # See BLOCKED_ERRNOS comment above re: EEXIST.+ return+ except OSError as exc:+ if exc.errno in BLOCKED_ERRNOS:+ return+ failures.append(+ f"{{label}}: unexpected OSError errno={{exc.errno}} {{exc!r}}"+ )+ return+ failures.append(f"{{label}}: did not raise")++ # 1. Direct read of the trusted scripts must be denied.+ expect_blocked("read-daemon", lambda: open(DAEMON, "rb").close())+ expect_blocked("read-launcher", lambda: open(LAUNCHER, "rb").close())++ # 2. Truncating / overwriting either script must be denied.+ expect_blocked("write-truncate-daemon", lambda: open(DAEMON, "wb").close())+ expect_blocked("write-append-daemon", lambda: open(DAEMON, "ab").close())+ expect_blocked("write-truncate-launcher", lambda: open(LAUNCHER, "wb").close())++ # 3. Unlinking the scripts must be denied.+ expect_blocked("unlink-daemon", lambda: os.unlink(DAEMON))+ expect_blocked("unlink-launcher", lambda: os.unlink(LAUNCHER))++ # 4. Replacing them via symlink (atomic shadow attack) must+ # be denied. We try both ``symlink`` over the existing+ # path and ``rename`` of an attacker-controlled file.+ expect_blocked(+ "symlink-shadow-daemon",+ lambda: os.symlink("/tmp/evil", DAEMON),+ )+ attacker = "/tmp/jiuwenbox-attacker.py"+ try:+ with open(attacker, "wb") as fh:+ fh.write(b"# planted by user code\\n")+ except OSError as exc:+ failures.append(+ f"setup-attacker-failed: {{exc!r}}"+ )+ else:+ expect_blocked(+ "rename-shadow-daemon",+ lambda: os.rename(attacker, DAEMON),+ )++ # 5. Creating *new* files inside ``/jiuwenbox`` must also+ # be denied so an attacker cannot drop a co-resident+ # decoy that the runtime might later mistakenly load.+ expect_blocked(+ "create-new-file-in-reserved-dir",+ lambda: open("/jiuwenbox/evil.py", "wb").close(),+ )++ # 6. Even directory enumeration must be denied; otherwise an+ # attacker could probe what exists before mounting another+ # technique.+ expect_blocked("listdir-reserved", lambda: os.listdir("/jiuwenbox"))+ expect_blocked("scandir-reserved", lambda: list(os.scandir("/jiuwenbox")))++ # 7. Permission bits must not be mutable from user code.+ expect_blocked("chmod-daemon", lambda: os.chmod(DAEMON, 0o777))++ if failures:+ for fail in failures:+ print(fail, file=sys.stderr)+ sys.exit(1)+ print("all-blocked")+ """+ ).strip()++ response = client.post(+ f"/api/v1/sandboxes/{sandbox['id']}/exec",+ json={+ "command": ["python3", "-c", attack_script],+ "timeout_seconds": 10,+ },+ )+ assert response.status_code == 200, response.text+ data = response.json()+ assert data["exit_code"] == 0, data+ assert data["stdout"].strip() == "all-blocked", data++ @staticmethod+ def test_sandbox_remains_functional_after_attempted_reserved_dir_tampering(+ create_sandbox_with_policy,+ client,+ ):+ """Attempting to tamper with ``/jiuwenbox`` scripts must not+ damage the IPC daemon.++ The daemon is loaded into memory before Landlock applies, so its+ on-disk artifact is consumed only at sandbox-creation time. This+ test guards against a regression where a future change makes+ the daemon reload from ``/jiuwenbox`` on later requests - which+ would mean an attacker who *did* break in could bend subsequent+ execs to their will. We pound the attack endpoint, then verify+ that two different IPC code paths (exec and read_file via+ 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"]++ daemon_path = TestPolicyEnforcement._RESERVED_SCRIPT_DAEMON+ launcher_path = TestPolicyEnforcement._RESERVED_SCRIPT_LAUNCHER++ attack_script = textwrap.dedent(+ f"""+ import os+ DAEMON = {daemon_path!r}+ LAUNCHER = {launcher_path!r}+ for path in (DAEMON, LAUNCHER):+ for opener in (+ lambda p=path: open(p, 'rb').close(),+ lambda p=path: open(p, 'wb').close(),+ lambda p=path: os.unlink(p),+ lambda p=path: os.symlink('/tmp/evil', p),+ lambda p=path: os.chmod(p, 0o777),+ ):+ try:+ opener()+ except OSError:+ pass+ print('attempted')+ """+ ).strip()++ attack_resp = client.post(+ f"/api/v1/sandboxes/{sandbox_id}/exec",+ json={+ "command": ["python3", "-c", attack_script],+ "timeout_seconds": 10,+ },+ )+ assert attack_resp.status_code == 200, attack_resp.text+ # The script swallows every error on purpose; what matters is+ # that the daemon survives the volley of attempted mutations.+ assert attack_resp.json()["exit_code"] == 0, attack_resp.json()++ # IPC-exec must still work end-to-end after the attack.+ followup_resp = client.post(+ f"/api/v1/sandboxes/{sandbox_id}/exec",+ json={+ "command": [+ "python3",+ "-c",+ "print('post-attack-exec-ok')",+ ],+ "timeout_seconds": 10,+ },+ )+ assert followup_resp.status_code == 200, followup_resp.text+ followup = followup_resp.json()+ assert followup["exit_code"] == 0, followup+ assert "post-attack-exec-ok" in followup["stdout"]++ # IPC file-op fast paths must also still work. Round-trip a+ # payload through upload + download to confirm the daemon is+ # still serving non-exec requests too.+ target = "/tmp/post-attack-marker.txt"+ marker = b"post-attack-file-op-ok"+ upload_resp = client.post(+ f"/api/v1/sandboxes/{sandbox_id}/upload",+ params={"sandbox_path": target},+ files={"file": ("marker.txt", marker, "text/plain")},+ )+ assert upload_resp.status_code == 204, upload_resp.text++ download_resp = client.get(+ f"/api/v1/sandboxes/{sandbox_id}/download",+ params={"sandbox_path": target},+ )+ assert download_resp.status_code == 200, download_resp.text+ assert download_resp.content == marker+++# ----------------------------------------------------------------------+# Reserved-sandbox-path validation+#+# ``PolicyEngine`` reserves a small set of in-sandbox paths+# (``_RESERVED_SANDBOX_PATHS``, currently ``("/jiuwenbox",)``) for the+# trusted launcher and daemon scripts. Any user policy that names that+# subtree must be rejected at sandbox-creation time, otherwise:+#+# * ``read_only`` / ``read_write`` / ``directories`` / ``files``+# entries would punch ``/jiuwenbox`` into the Landlock allowlist+# (see ``jiuwenbox/supervisor/landlock.py``), letting user code read+# the launcher and daemon scripts and bypassing the+# ``test_reserved_dir_scripts_cannot_be_tampered_with`` guarantee;+# * ``bind_mounts`` with ``sandbox_path`` under ``/jiuwenbox`` would+# either shadow our launcher mount or bind a user-controlled host+# directory under the reserved name, which would also leak into the+# Landlock allowlist;+# * ``device`` mounts behave the same way as ``bind_mounts``, with+# the additional risk of granting ``--dev-bind`` privileges inside+# a path the runtime treats as trusted.+#+# The cases below assert that every flavour of policy-supplied path+# referencing the reserved subtree is rejected with a 400 response and a+# message that names the offending path.+# ----------------------------------------------------------------------+++class TestReservedSandboxPaths:+ """Server must reject user policies that target ``/jiuwenbox``."""++ _RESERVED_DIR = "/jiuwenbox"+ _RESERVED_NESTED = "/jiuwenbox/landlock-launcher.py"+ _RESERVED_DEEP_NESTED = "/jiuwenbox/sub/dir/file.py"++ @staticmethod+ def _post_policy(client, policy: dict):+ """Submit a policy and return ``(status_code, body)`` pairs.++ ``create_sandbox_with_policy`` asserts ``phase == "ready"`` so it+ is unsuitable for negative tests; we hit the endpoint directly.+ """+ return client.post(+ "/api/v1/sandboxes",+ json={+ "policy_mode": "override",+ "policy": _with_runtime_support(policy),+ },+ )++ @staticmethod+ def _assert_rejected_with_reserved_message(response, expected_path: str):+ assert response.status_code == 400, response.text+ body = response.json()+ assert "error" in body, body+ message = body["error"]+ assert expected_path in message, message+ assert "reserved" in message.lower(), message++ @staticmethod+ @pytest.mark.parametrize(+ "field, sandbox_path",+ [+ ("read_only", _RESERVED_DIR),+ ("read_only", _RESERVED_NESTED),+ ("read_only", _RESERVED_DEEP_NESTED),+ ("read_write", _RESERVED_DIR),+ ("read_write", _RESERVED_NESTED),+ ("read_write", _RESERVED_DEEP_NESTED),+ ],+ )+ def test_read_lists_cannot_reference_reserved_subtree(+ client,+ field: str,+ sandbox_path: str,+ ):+ """``read_only`` / ``read_write`` are pushed straight into the+ Landlock allowlist by ``encode_landlock_payload``. Letting a user+ sneak ``/jiuwenbox`` in there would expose the launcher / daemon+ scripts the moment Landlock applies, so the policy engine has to+ bounce these inputs before any sandbox is created.+ """+ policy = {+ "name": f"reserved-{field}-policy",+ "filesystem_policy": {field: [sandbox_path]},+ }+ response = TestReservedSandboxPaths._post_policy(client, policy)+ TestReservedSandboxPaths._assert_rejected_with_reserved_message(+ response, sandbox_path,+ )++ @staticmethod+ @pytest.mark.parametrize(+ "sandbox_path",+ [_RESERVED_DIR, _RESERVED_NESTED, _RESERVED_DEEP_NESTED],+ )+ def test_directories_field_cannot_reference_reserved_subtree(+ client,+ sandbox_path: str,+ ):+ """``filesystem_policy.directories`` ultimately becomes a+ ``--dir`` mount + Landlock read_write entry; both behaviours+ would clobber our reserved tmpfs.+ """+ policy = {+ "name": "reserved-directories-policy",+ "filesystem_policy": {"directories": [sandbox_path]},+ }+ response = TestReservedSandboxPaths._post_policy(client, policy)+ TestReservedSandboxPaths._assert_rejected_with_reserved_message(+ response, sandbox_path,+ )++ @staticmethod+ @pytest.mark.parametrize(+ "sandbox_path",+ [_RESERVED_DIR, _RESERVED_NESTED, _RESERVED_DEEP_NESTED],+ )+ def test_files_field_cannot_reference_reserved_subtree(+ client,+ sandbox_path: str,+ ):+ """A single user-controlled file inside ``/jiuwenbox`` would+ still leak that path into the Landlock allowlist via+ ``encode_landlock_payload``; reject the whole subtree, not just+ the canonical script names.+ """+ policy = {+ "name": "reserved-files-policy",+ "filesystem_policy": {"files": [sandbox_path]},+ }+ response = TestReservedSandboxPaths._post_policy(client, policy)+ TestReservedSandboxPaths._assert_rejected_with_reserved_message(+ response, sandbox_path,+ )++ @staticmethod+ @pytest.mark.parametrize("mode", ["ro", "rw"])+ @pytest.mark.parametrize(+ "sandbox_path",+ [_RESERVED_DIR, _RESERVED_NESTED, _RESERVED_DEEP_NESTED],+ )+ def test_bind_mounts_cannot_target_reserved_subtree(+ client,+ sandbox_path: str,+ mode: str,+ ):+ """``bind_mounts.sandbox_path`` is the most dangerous knob: it+ mounts a host-controlled directory under the reserved subtree+ and tells Landlock to allow it. ``host_path`` is irrelevant for+ the policy reservation (it lives in the operator's filesystem)+ but we need to supply *something* that exists on host so the+ request reaches validation.+ """+ policy = {+ "name": "reserved-bind-mounts-policy",+ "filesystem_policy": {+ "bind_mounts": [+ {+ "host_path": "/tmp",+ "sandbox_path": sandbox_path,+ "mode": mode,+ },+ ],+ },+ }+ response = TestReservedSandboxPaths._post_policy(client, policy)+ TestReservedSandboxPaths._assert_rejected_with_reserved_message(+ response, sandbox_path,+ )++ @staticmethod+ @pytest.mark.parametrize(+ "sandbox_path",+ [_RESERVED_DIR, _RESERVED_NESTED, _RESERVED_DEEP_NESTED],+ )+ def test_device_mounts_cannot_target_reserved_subtree(+ client,+ sandbox_path: str,+ ):+ """``device`` mounts go through ``--dev-bind`` and the Landlock+ allowlist; if a user can pin ``/jiuwenbox/foo`` here, they+ smuggle the reserved subtree back into Landlock the same way+ ``bind_mounts`` would.+ """+ policy = {+ "name": "reserved-device-policy",+ "filesystem_policy": {+ "device": [+ {+ "host_path": "/dev/null",+ "sandbox_path": sandbox_path,+ },+ ],+ },+ }+ response = TestReservedSandboxPaths._post_policy(client, policy)+ TestReservedSandboxPaths._assert_rejected_with_reserved_message(+ response, sandbox_path,+ )++ @staticmethod+ def test_unrelated_sandbox_paths_are_not_rejected(+ client, create_sandbox_with_policy,+ ):+ """Sanity check: paths that merely resemble the reserved name+ (substring matches, suffix collisions, ``/run`` left over from+ the previous design) must still be allowed. This guards against+ an over-broad ``startswith`` style implementation.+ """+ policy = {+ "name": "non-reserved-policy",+ "filesystem_policy": {+ "read_only": [+ "/usr",+ "/lib",+ "/lib64",+ "/etc",+ "/opt",+ # ``/jiuwenbox-public`` is *not* under+ # ``/jiuwenbox`` because PurePosixPath compares full+ # path components, not raw string prefixes.+ "/jiuwenbox-public",+ # Legacy directory we used to host the launcher in -+ # plain ``/run`` must remain a normal user-policy+ # path now that the reserved subtree has moved.+ "/run",+ ],+ "read_write": ["/tmp"],+ },+ }+ sandbox = create_sandbox_with_policy(+ name_prefix="non-reserved",+ policy=policy,+ )+ assert sandbox["phase"] == "ready", sandbox++ @staticmethod+ def test_reserved_subtree_rejection_runs_before_sandbox_creation(+ client,+ ):+ """The launcher / daemon scripts must never be touched by an+ invalid policy. We assert the failure path returns 400 *and*+ does not surface a non-zero phase, which would imply the runtime+ partially started a sandbox before bouncing.+ """+ policy = {+ "name": "reserved-pre-creation-policy",+ "filesystem_policy": {+ "read_only": [TestReservedSandboxPaths._RESERVED_DIR],+ },+ }+ response = TestReservedSandboxPaths._post_policy(client, policy)+ TestReservedSandboxPaths._assert_rejected_with_reserved_message(+ response, TestReservedSandboxPaths._RESERVED_DIR,+ )+ # The /sandboxes endpoint only returns a created body on 201.+ # 400 responses must not contain phase information.+ assert "phase" not in response.json(), response.json()+class TestBwrapFilesystem:@staticmethod@@ -1811,7 +2707,7 @@ class TestBwrapFilesystem:},})- args = BwrapConfig.from_policy(policy, ["/usr/bin/true"]).to_args()+ args = BwrapConfig.from_policy(policy, ["true"]).to_args()assert not _has_mount(args, "--ro-bind", "/host-read-only", "/host-read-only")assert not _has_mount(args, "--bind", "/host-read-write", "/host-read-write")@@ -1830,7 +2726,7 @@ class TestBwrapFilesystem:},})- args = BwrapConfig.from_policy(policy, ["/usr/bin/true"]).to_args()+ args = BwrapConfig.from_policy(policy, ["true"]).to_args()assert _has_arg_pair(args, "--dir", "/etc")assert _has_mount(args, "--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf")@@ -1846,7 +2742,7 @@ class TestBwrapFilesystem:},})- args = BwrapConfig.from_policy(policy, ["/usr/bin/true"]).to_args()+ args = BwrapConfig.from_policy(policy, ["true"]).to_args()assert not _has_arg_pair(args, "--dir", "/dev")assert _has_arg_pair(args, "--dir", "/dev/dri")@@ -1866,7 +2762,7 @@ class TestBwrapFilesystem:},})- args = BwrapConfig.from_policy(policy, ["/usr/bin/true"]).to_args()+ args = BwrapConfig.from_policy(policy, ["true"]).to_args()assert not _has_arg_pair(args, "--dir", "/etc")assert _has_arg_pair(args, "--tmpfs", "/etc")@@ -1938,16 +2834,14 @@ class TestNetworkIptables:class TestSandboxExec:@staticmethoddef test_exec_requires_running_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/sleep", "3600"],- })+ create_resp = client.post("/api/v1/sandboxes", json={})sandbox_id = create_resp.json()["id"]# Stop it firstclient.post(f"/api/v1/sandboxes/{sandbox_id}/stop")resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={- "command": ["/usr/bin/echo", "hello"],+ "command": ["echo", "hello"],})assert resp.status_code == 409@@ -1956,9 +2850,7 @@ class TestSandboxListing:@staticmethoddef test_list_returns_all_sandboxes(client):for i in range(3):- client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- })+ client.post("/api/v1/sandboxes", json={})resp = client.get("/api/v1/sandboxes")assert resp.status_code == 200diff --git a/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.py b/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.pydeleted file mode 100644index 0aa1f5477c..0000000000--- a/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.py+++ /dev/null@@ -1,1628 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-"""Integration tests for box-server API endpoints."""--import copy-import logging-import os-import textwrap--import httpx-import pytest--LONG_RUNNING_COMMAND = ["/usr/bin/python3", "-c", "import time; time.sleep(36000)"]-JIUWENCLAW_SANDBOX_WORKSPACE = "/tmp/sandbox"-JIUWENCLAW_READ_WRITE_PATHS = ["/tmp", "/home/zzx/.jiuwenclaw"]-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"},-]-DEVICE_MOUNTS = [- {"host_path": "/dev/urandom", "sandbox_path": "/dev/urandom"},- {"host_path": "/dev/null", "sandbox_path": "/dev/null"},-]-JIUWENCLAW_BIND_MOUNT = {- "host_path": "/home/zzx/.jiuwenclaw",- "sandbox_path": "/home/zzx/.jiuwenclaw",- "mode": "rw",-}-TMP_DIRECTORY = {"path": "/tmp", "permissions": "1777"}-logger = logging.getLogger(__name__)---class SandboxTrackingClient:- """Track sandboxes created during a test and clean them up afterwards."""-- def __init__(self, client):- self._client = client- self._created_ids: list[str] = []-- def __getattr__(self, name: str):- return getattr(self._client, name)-- def post(self, url, *args, **kwargs):- response = self._client.post(url, *args, **kwargs)- if str(url).rstrip("/") == "/api/v1/sandboxes" and response.status_code == 201:- try:- sandbox_id = response.json().get("id")- except Exception:- sandbox_id = None- if sandbox_id:- self._created_ids.append(sandbox_id)- return response-- def delete(self, url, *args, **kwargs):- response = self._client.delete(url, *args, **kwargs)- sandbox_id = self._sandbox_id_from_delete_url(url)- if sandbox_id and response.status_code in (200, 202, 204, 404):- self._created_ids = [item for item in self._created_ids if item != sandbox_id]- return response-- def cleanup_sandboxes(self) -> None:- for sandbox_id in reversed(self._created_ids):- try:- self._client.delete(f"/api/v1/sandboxes/{sandbox_id}")- except Exception as exc:- logger.warning("Failed to cleanup sandbox %s: %s", sandbox_id, exc)- self._created_ids.clear()-- @staticmethod- def _sandbox_id_from_delete_url(url) -> str | None:- path = str(url).split("?", 1)[0].rstrip("/")- prefix = "/api/v1/sandboxes/"- if not path.startswith(prefix):- return None- suffix = path[len(prefix):]- if "/" in suffix:- return None- return suffix or None---def _normalize_endpoint(endpoint: str) -> str:- return endpoint if "://" in endpoint else f"http://{endpoint}"---def _sandbox_health_url(server_endpoint: str) -> str:- return f"{_normalize_endpoint(server_endpoint).rstrip('/')}/health"---def _capability_check_script(cap_bit: int) -> str:- return textwrap.dedent(- f"""- cap_eff = 0- with open("/proc/self/status") as f:- for line in f:- if line.startswith("CapEff:"):- cap_eff = int(line.split()[1], 16)- break- print("yes" if cap_eff & (1 << {cap_bit}) else "no")- """- ).strip()---def _loopback_ingress_script(expect_success: bool) -> str:- connect_block = textwrap.dedent(- """- sock = socket.create_connection(("127.0.0.1", port), timeout=1)- conn, _ = srv.accept()- conn.sendall(b"ingress-ok")- conn.close()- print(sock.recv(64).decode())- sock.close()- """- ).strip()- if not expect_success:- connect_block = textwrap.dedent(- """- try:- sock = socket.create_connection(("127.0.0.1", port), timeout=1)- conn, _ = srv.accept()- conn.sendall(b"ingress-ok")- conn.close()- print(sock.recv(64).decode())- sock.close()- print("unexpected-success")- sys.exit(0)- except Exception as exc:- print(type(exc).__name__)- sys.exit(7)- """- ).strip()-- return "\n".join([- "import socket",- "import sys",- "",- "port = int(sys.argv[1])",- "",- "srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)",- "srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",- 'srv.bind(("127.0.0.1", port))',- "srv.listen(1)",- connect_block,- "srv.close()",- "",- ])---def _has_directory(directories: list, path: str) -> bool:- for directory in directories:- if isinstance(directory, str) and directory == path:- return True- if isinstance(directory, dict) and directory.get("path") == path:- return True- return False---def _has_bind_mount(bind_mounts: list, sandbox_path: str) -> bool:- return any(mount.get("sandbox_path") == sandbox_path for mount in bind_mounts)---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 _has_directory(directories, "/tmp")- and not _has_bind_mount(bind_mounts, "/tmp")- ):- directories.append(TMP_DIRECTORY.copy())-- return runtime_policy---def client(server_endpoint):- with httpx.Client(base_url=_normalize_endpoint(server_endpoint), timeout=30.0) as external:- tracking = SandboxTrackingClient(external)- try:- yield tracking- finally:- tracking.cleanup_sandboxes()---def create_sandbox_with_policy(client):- def factory(- *,- name_prefix: str,- policy: dict,- policy_mode: str = "override",- command: list[str] | None = None,- ) -> dict:- response = client.post("/api/v1/sandboxes", json={- "command": command or LONG_RUNNING_COMMAND,- "policy_mode": policy_mode,- "policy": _with_runtime_support(policy),- })- assert response.status_code == 201, response.text- sandbox = response.json()- assert sandbox["phase"] == "ready", sandbox- return sandbox-- return factory---class TestHealthEndpoint:- @staticmethod- def test_health(client):- resp = client.get("/health")- assert resp.status_code == 200- data = resp.json()- assert data["status"] == "ok"- assert "version" in data- assert "landlock_supported" in data- assert "sandboxes_active" in data---class TestSandboxCRUD:- @staticmethod- def test_list_sandboxes_empty(client):- resp = client.get("/api/v1/sandboxes")- assert resp.status_code == 200- assert resp.json() == []-- @staticmethod- def test_create_sandbox(client):- resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "hello"],- })- assert resp.status_code == 201- data = resp.json()- assert "id" in data- assert "name" not in data- assert data["phase"] in ("provisioning", "ready", "error")-- @staticmethod- def test_list_sandboxes_after_create(client):- create_resp = client.post("/api/v1/sandboxes", json={"command": ["/usr/bin/echo"]})- sandbox_id = create_resp.json()["id"]- resp = client.get("/api/v1/sandboxes")- assert resp.status_code == 200- data = resp.json()- assert any(item["id"] == sandbox_id for item in data)- assert len(data) == 1-- @staticmethod- def test_get_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- })- sandbox_id = create_resp.json()["id"]-- resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")- assert resp.status_code == 200- data = resp.json()- assert data["id"] == sandbox_id- assert "name" not in data-- @staticmethod- def test_get_nonexistent_sandbox(client):- resp = client.get("/api/v1/sandboxes/nonexistent")- assert resp.status_code == 404-- @staticmethod- def test_delete_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- })- sandbox_id = create_resp.json()["id"]-- resp = client.delete(f"/api/v1/sandboxes/{sandbox_id}")- assert resp.status_code == 204-- resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")- assert resp.status_code == 404---class TestSandboxLifecycle:- @staticmethod- def test_start_stopped_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/sleep", "3600"],- })- sandbox_id = create_resp.json()["id"]-- stop_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/stop")- assert stop_resp.status_code == 200- assert stop_resp.json()["phase"] == "stopped"-- start_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/start")- assert start_resp.status_code == 200- assert start_resp.json()["phase"] == "ready", start_resp.json()-- @staticmethod- def test_stop_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/sleep", "3600"],- })- sandbox_id = create_resp.json()["id"]-- resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/stop")- assert resp.status_code == 200- assert resp.json()["phase"] == "stopped"-- @staticmethod- def test_restart_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/sleep", "3600"],- })- sandbox_id = create_resp.json()["id"]-- resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/restart")- assert resp.status_code == 200- assert resp.json()["phase"] == "ready"-- @staticmethod- def test_get_logs(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- })- sandbox_id = create_resp.json()["id"]-- resp = client.get(f"/api/v1/sandboxes/{sandbox_id}/logs")- assert resp.status_code == 200---class TestPolicyAPI:- @staticmethod- def test_get_sandbox_policy(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- })- sandbox_id = create_resp.json()["id"]-- resp = client.get(f"/api/v1/policies/{sandbox_id}")- assert resp.status_code == 200- data = resp.json()- assert data["version"] == 1- assert data["name"] == "server-default"- assert data["sandbox_workspace"] == JIUWENCLAW_SANDBOX_WORKSPACE- assert "resources" not in data- assert data["filesystem_policy"]["directories"] == [TMP_DIRECTORY]- assert data["filesystem_policy"]["read_only"] == [- "/bin",- "/sbin",- "/usr",- "/lib",- "/lib64",- "/etc",- "/opt",- ]- assert data["filesystem_policy"]["read_write"] == JIUWENCLAW_READ_WRITE_PATHS- assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTS + [JIUWENCLAW_BIND_MOUNT]- assert data["filesystem_policy"]["device"] == DEVICE_MOUNTS- assert data["namespace"] == {- "user": False,- "pid": True,- "ipc": True,- "cgroup": True,- "uts": True,- }- assert data["capabilities"] == {"add": [], "drop": []}- assert data["landlock"]["compatibility"] == "best_effort"- 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"]- assert data["network"]["egress"]["blocked_ports"] == [22]- assert data["network"]["egress"]["default"] == "allow"- assert data["network"]["egress"]["blocked_domains"] == ["ip.me"]- assert data["network"]["egress"]["allowed_ports"] == [443, 80]- assert data["network"]["ingress"]["default"] == "deny"- assert data["network"]["ingress"]["allowed_domains"] == ["localhost"]- assert data["network"]["ingress"]["allowed_ips"] == ["127.0.0.1/32", "::1/128"]- assert data["network"]["ingress"]["blocked_ips"] == []- assert data["network"]["ingress"]["allowed_ports"] == [8080]- assert data["network"]["ingress"]["blocked_ports"] == [22]- assert "profile" not in data["syscall"]- assert "blocked" not in data["syscall"]- assert "mount" in data["syscall"]["x86_64"]["blocked"]- assert "kexec_file_load" in data["syscall"]["x86_64"]["blocked"]- assert "mount" in data["syscall"]["arm64"]["blocked"]- assert "kexec_file_load" in data["syscall"]["arm64"]["blocked"]-- @staticmethod- def test_append_policy_merges_with_server_default(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- "policy_mode": "append",- "policy": {- "name": "appended-policy",- "filesystem_policy": {- "directories": [{"path": "/tmp/appended-dir", "permissions": "0700"}],- "read_only": ["/var/log"],- "read_write": ["/var/tmp"],- "bind_mounts": [{- "host_path": "/tmp",- "sandbox_path": "/tmp",- "mode": "rw",- }],- },- "network": {- "egress": {- "allowed_domains": ["extra.example.com"],- "allowed_ips": ["203.0.113.10/32"],- },- "ingress": {- "allowed_ips": ["10.0.0.0/8"],- "allowed_ports": [9090],- },- },- "process": {- "run_as_user": "root",- "run_as_group": "root",- },- "namespace": {- "pid": False,- "uts": False,- },- "capabilities": {- "add": ["CAP_NET_RAW"],- "drop": [],- },- "landlock": {- "compatibility": "disabled",- },- "syscall": {- "x86_64": {"blocked": ["getpid"]},- "arm64": {"blocked": ["getpid"]},- },- },- })- sandbox_id = create_resp.json()["id"]-- resp = client.get(f"/api/v1/policies/{sandbox_id}")- assert resp.status_code == 200- data = resp.json()- assert data["name"] == "appended-policy"- assert data["sandbox_workspace"] == JIUWENCLAW_SANDBOX_WORKSPACE- assert data["network"]["egress"]["allowed_domains"] == [- "baidu.com",- "extra.example.com",- ]- assert data["network"]["egress"]["allowed_ips"] == [- "127.0.0.1/32",- "::1/128",- "203.0.113.10/32",- ]- assert data["network"]["egress"]["blocked_ips"] == ["169.254.169.254/32"]- assert data["network"]["egress"]["blocked_ports"] == [22]- assert data["network"]["ingress"]["allowed_domains"] == ["localhost"]- assert data["network"]["ingress"]["allowed_ips"] == [- "127.0.0.1/32",- "::1/128",- "10.0.0.0/8",- ]- assert data["network"]["ingress"]["allowed_ports"] == [8080, 9090]- assert data["filesystem_policy"]["read_only"] == [- "/bin",- "/sbin",- "/usr",- "/lib",- "/lib64",- "/etc",- "/opt",- "/var/log",- ]- assert data["filesystem_policy"]["read_write"] == [- *JIUWENCLAW_READ_WRITE_PATHS,- "/var/tmp",- ]- assert data["filesystem_policy"]["directories"] == [- TMP_DIRECTORY,- {"path": "/tmp/appended-dir", "permissions": "0700"},- ]- assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTS + [- JIUWENCLAW_BIND_MOUNT,- {- "host_path": "/tmp",- "sandbox_path": "/tmp",- "mode": "rw",- },- ]- assert data["filesystem_policy"]["device"] == DEVICE_MOUNTS- assert data["process"]["run_as_user"] == "root"- assert data["process"]["run_as_group"] == "root"- assert data["namespace"] == {- "user": False,- "pid": False,- "ipc": True,- "cgroup": True,- "uts": False,- }- assert data["capabilities"]["add"] == ["CAP_NET_RAW"]- assert data["capabilities"]["drop"] == []- assert data["landlock"]["compatibility"] == "disabled"- assert "getpid" in data["syscall"]["x86_64"]["blocked"]- assert "mount" in data["syscall"]["x86_64"]["blocked"]- assert "getpid" in data["syscall"]["arm64"]["blocked"]- assert "mount" in data["syscall"]["arm64"]["blocked"]-- @staticmethod- def test_override_policy_replaces_server_default(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- "policy_mode": "override",- "policy": {- "name": "override-policy",- "filesystem_policy": {- "directories": [{- "path": "/tmp/override-dir",- "permissions": "0700",- }],- "read_only": ["/usr"],- "read_write": ["/var/tmp"],- "bind_mounts": SYSTEM_BIND_MOUNTS,- },- "network": {- "mode": "host",- "egress": {- "default": "deny",- "allowed_domains": ["override.example.com"],- "allowed_ips": ["198.51.100.10/32"],- "blocked_ips": ["198.51.100.11/32"],- "allowed_ports": [80],- "blocked_ports": [25],- },- "ingress": {- "default": "allow",- "allowed_ips": ["10.0.0.0/8"],- "blocked_ips": ["10.0.5.0/24"],- "allowed_ports": [9090],- "blocked_ports": [22],- },- },- "process": {- "run_as_user": "root",- "run_as_group": "root",- },- "namespace": {- "user": True,- "pid": False,- "ipc": False,- "cgroup": False,- "uts": False,- },- "capabilities": {- "add": ["CAP_NET_RAW"],- "drop": [],- },- "landlock": {- "compatibility": "disabled",- },- "syscall": {- "x86_64": {"blocked": ["getppid"]},- "arm64": {"blocked": ["getppid"]},- },- },- })- sandbox_id = create_resp.json()["id"]-- resp = client.get(f"/api/v1/policies/{sandbox_id}")- assert resp.status_code == 200- data = resp.json()- assert data["name"] == "override-policy"- assert data["sandbox_workspace"] == JIUWENCLAW_SANDBOX_WORKSPACE- assert data["network"]["mode"] == "host"- assert data["network"]["egress"]["allowed_domains"] == ["override.example.com"]- assert data["network"]["egress"]["allowed_ips"] == ["198.51.100.10/32"]- assert data["network"]["egress"]["blocked_ips"] == ["198.51.100.11/32"]- assert data["network"]["egress"]["blocked_ports"] == [25]- assert data["network"]["ingress"]["default"] == "allow"- assert data["network"]["ingress"]["allowed_ips"] == ["10.0.0.0/8"]- assert data["network"]["ingress"]["blocked_ips"] == ["10.0.5.0/24"]- assert data["network"]["ingress"]["allowed_ports"] == [9090]- assert data["network"]["ingress"]["blocked_ports"] == [22]- assert data["filesystem_policy"]["read_only"] == ["/usr"]- assert data["filesystem_policy"]["read_write"] == ["/var/tmp"]- assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTS- assert data["filesystem_policy"]["device"] == []- assert data["filesystem_policy"]["directories"] == [{- "path": "/tmp/override-dir",- "permissions": "0700",- }]- assert data["process"]["run_as_user"] == "root"- assert data["process"]["run_as_group"] == "root"- assert data["namespace"] == {- "user": True,- "pid": False,- "ipc": False,- "cgroup": False,- "uts": False,- }- assert data["capabilities"] == {"add": ["CAP_NET_RAW"], "drop": []}- assert data["landlock"]["compatibility"] == "disabled"- assert data["syscall"]["x86_64"]["blocked"] == ["getppid"]- assert data["syscall"]["arm64"]["blocked"] == ["getppid"]-- @staticmethod- def test_get_nonexistent_policy(client):- resp = client.get("/api/v1/policies/nonexistent")- assert resp.status_code == 404-- @staticmethod- def test_create_sandbox_rejects_direct_sandbox_bind_mount(client):- resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "hello"],- "policy": {- "name": "bad-sandbox-mount-policy",- "filesystem_policy": {- "bind_mounts": [{- "host_path": f"{JIUWENCLAW_SANDBOX_WORKSPACE}/manual",- "sandbox_path": "/tmp/manual",- "mode": "rw",- }],- },- "network": {- "mode": "host",- },- },- })-- assert resp.status_code == 400- assert JIUWENCLAW_SANDBOX_WORKSPACE in resp.json()["error"]-- @staticmethod- def test_create_sandbox_rejects_direct_sandbox_device_mount(client):- resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "hello"],- "policy": {- "name": "bad-sandbox-device-policy",- "filesystem_policy": {- "device": [{- "host_path": f"{JIUWENCLAW_SANDBOX_WORKSPACE}/manual-device",- "sandbox_path": "/dev/manual-device",- }],- },- "network": {- "mode": "host",- },- },- })-- assert resp.status_code == 400- assert JIUWENCLAW_SANDBOX_WORKSPACE in resp.json()["error"]-- @staticmethod- def test_create_sandbox_rejects_direct_sandbox_path(client):- resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "hello"],- "policy": {- "name": "bad-sandbox-path-policy",- "filesystem_policy": {- "read_write": [f"{JIUWENCLAW_SANDBOX_WORKSPACE}/manual"],- },- "network": {- "mode": "host",- },- },- })-- assert resp.status_code == 400- assert JIUWENCLAW_SANDBOX_WORKSPACE in resp.json()["error"]-- @staticmethod- def test_create_sandbox_rejects_direct_sandbox_directory(client):- resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "hello"],- "policy": {- "name": "bad-sandbox-dir-policy",- "filesystem_policy": {- "directories": [{- "path": f"{JIUWENCLAW_SANDBOX_WORKSPACE}/manual",- "permissions": "0700",- }],- },- "network": {- "mode": "host",- },- },- })-- assert resp.status_code == 400- assert JIUWENCLAW_SANDBOX_WORKSPACE in resp.json()["error"]---class TestPolicyEnforcement:- @staticmethod- def test_filesystem_read_write_rule_allows_upload_and_download(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="fs-rw",- policy={- "name": "fs-rw-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "host",- "egress": {"default": "allow"},- },- },- )- sandbox_path = f"/tmp/{sandbox['id']}-policy-ok.txt"-- upload = client.post(- f"/api/v1/sandboxes/{sandbox['id']}/upload",- params={"sandbox_path": sandbox_path},- files={"file": ("policy-ok.txt", b"hello-policy", "text/plain")},- )- assert upload.status_code == 204-- download = client.get(- f"/api/v1/sandboxes/{sandbox['id']}/download",- params={"sandbox_path": sandbox_path},- )- assert download.status_code == 200- assert download.content == b"hello-policy"-- @staticmethod- def test_filesystem_read_only_rule_rejects_upload(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="fs-ro",- policy={- "name": "fs-ro-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "host",- "egress": {"default": "allow"},- },- },- )-- upload = client.post(- f"/api/v1/sandboxes/{sandbox['id']}/upload",- params={"sandbox_path": "/etc/policy-denied.txt"},- files={"file": ("policy-denied.txt", b"nope", "text/plain")},- )- assert upload.status_code == 409-- @staticmethod- def test_filesystem_directories_rule_creates_directory(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="fs-dir",- policy={- "name": "fs-dir-policy",- "filesystem_policy": {- "directories": [{- "path": "/policy-created",- "permissions": 700,- }],- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "landlock": {- "compatibility": "disabled",- },- "network": {- "mode": "host",- },- },- )-- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": [- "/usr/bin/python3",- "-c",- (- "import os, stat; "- "from pathlib import Path; "- "path = Path('/policy-created'); "- "print(path.is_dir()); "- "print(oct(stat.S_IMODE(os.stat(path).st_mode)))"- ),- ],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0, data- assert data["stdout"].splitlines() == ["True", "0o700"]-- @staticmethod- def test_filesystem_directories_rule_creates_directory_under_home(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="fs-home-dir",- policy={- "name": "fs-home-dir-policy",- "filesystem_policy": {- "directories": [{- "path": "/home",- "permissions": "0755",- }],- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "landlock": {- "compatibility": "disabled",- },- "network": {- "mode": "host",- },- },- )-- upload = client.post(- f"/api/v1/sandboxes/{sandbox['id']}/upload",- params={"sandbox_path": "/home/upload-created/file.txt"},- files={"file": ("file.txt", b"hello-home-upload", "text/plain")},- )- assert upload.status_code == 204, upload.text-- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": [- "/usr/bin/python3",- "-c",- (- "import os; "- "from pathlib import Path; "- "home = Path('/home'); "- "exec_path = home / 'exec-created'; "- "exec_path.mkdir(); "- "(exec_path / 'marker.txt').write_text('hello-home-exec'); "- "print(home.is_dir()); "- "print((home / 'upload-created').is_dir()); "- "print((home / 'upload-created/file.txt').read_text()); "- "print(exec_path.is_dir())"- ),- ],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0, data- assert data["stdout"].splitlines() == ["True", "True", "hello-home-upload", "True"]-- download = client.get(- f"/api/v1/sandboxes/{sandbox['id']}/download",- params={"sandbox_path": "/home/exec-created/marker.txt"},- )- assert download.status_code == 200, download.text- assert download.content == b"hello-home-exec"-- @staticmethod- def test_exec_applies_workdir_env_and_stdin(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="exec-options",- policy={- "name": "exec-options-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "host",- },- },- )-- script = (- "import os, pathlib, sys; "- "print(os.environ['BOX_TEST']); "- "print(pathlib.Path.cwd()); "- "print(sys.stdin.read())"- )- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", script],- "workdir": "/tmp",- "env": {"BOX_TEST": "env-ok"},- "stdin": "stdin-ok",- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0, data- assert data["stdout"].splitlines() == ["env-ok", "/tmp", "stdin-ok"]-- @staticmethod- def test_exec_runs_javascript_code(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="exec-js",- policy={- "name": "exec-js-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "host",- },- },- )-- js_code = (- "const label = process.env.BOX_JS_TEST || 'missing'; "- "const sum = [1, 2, 3, 4].reduce((total, value) => total + value, 0); "- "console.log(label); "- "console.log(`sum=${sum}`);"- )- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/node", "-e", js_code],- "env": {"BOX_JS_TEST": "js-ok"},- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0, data- assert data["stdout"].splitlines() == ["js-ok", "sum=10"]- assert data["stderr"] == ""-- @staticmethod- def test_download_missing_file_returns_404(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="download-missing",- policy={- "name": "download-missing-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "host",- },- },- )-- response = client.get(- f"/api/v1/sandboxes/{sandbox['id']}/download",- params={"sandbox_path": "/tmp/not-found.txt"},- )- assert response.status_code == 404-- @staticmethod- def test_download_directory_returns_409(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="download-dir",- policy={- "name": "download-dir-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "host",- },- },- )-- response = client.get(- f"/api/v1/sandboxes/{sandbox['id']}/download",- params={"sandbox_path": "/tmp"},- )- assert response.status_code == 409-- @staticmethod- def test_list_files_endpoint_returns_files_and_directories(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="list-files",- policy={- "name": "list-files-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "host",- },- },- )- root = f"/tmp/{sandbox['id']}-list-api"-- setup = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": [- "/usr/bin/python3",- "-c",- (- "from pathlib import Path; import sys; "- "root = Path(sys.argv[1]); "- "(root / 'sub').mkdir(parents=True, exist_ok=True); "- "(root / 'a.txt').write_text('a'); "- "(root / 'sub/b.log').write_text('b')"- ),- root,- ],- "timeout_seconds": 5,- })- assert setup.status_code == 200- assert setup.json()["exit_code"] == 0-- response = client.get(- f"/api/v1/sandboxes/{sandbox['id']}/files",- params={"sandbox_path": root, "recursive": True},- )- assert response.status_code == 200- items = response.json()["items"]- paths = {item["path"] for item in items}- assert f"{root}/a.txt" in paths- assert f"{root}/sub" in paths- assert f"{root}/sub/b.log" in paths- assert any(item["name"] == "sub" and item["is_directory"] for item in items)-- files_only = client.get(- f"/api/v1/sandboxes/{sandbox['id']}/files",- params={- "sandbox_path": root,- "recursive": True,- "include_dirs": False,- },- )- assert files_only.status_code == 200- assert all(not item["is_directory"] for item in files_only.json()["items"])-- @staticmethod- def test_search_files_endpoint_filters_matches(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="search-files",- policy={- "name": "search-files-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "host",- },- },- )- root = f"/tmp/{sandbox['id']}-search-api"-- setup = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": [- "/usr/bin/python3",- "-c",- (- "from pathlib import Path; import sys; "- "root = Path(sys.argv[1]); "- "root.mkdir(parents=True, exist_ok=True); "- "(root / 'keep.py').write_text('print(1)'); "- "(root / 'drop.py').write_text('print(2)'); "- "(root / 'readme.md').write_text('# hi')"- ),- root,- ],- "timeout_seconds": 5,- })- assert setup.status_code == 200- assert setup.json()["exit_code"] == 0-- response = client.get(- f"/api/v1/sandboxes/{sandbox['id']}/search",- params=[- ("sandbox_path", root),- ("pattern", "*.py"),- ("exclude_patterns", "drop.py"),- ],- )- assert response.status_code == 200- items = response.json()["items"]- assert [item["name"] for item in items] == ["keep.py"]-- @staticmethod- def test_process_user_and_group_policy_is_applied(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="process-root",- policy={- "name": "process-root-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "process": {- "run_as_user": "root",- "run_as_group": "root",- },- "network": {- "mode": "host",- },- },- )-- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/id", "-u"],- "timeout_seconds": 5,- })- assert response.status_code == 200- uid_data = response.json()- assert uid_data["exit_code"] == 0, uid_data- assert uid_data["stdout"].strip() == "0"-- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/id", "-g"],- "timeout_seconds": 5,- })- assert response.status_code == 200- gid_data = response.json()- assert gid_data["exit_code"] == 0, gid_data- assert gid_data["stdout"].strip() == "0"-- @staticmethod- def test_syscall_blocked_rule_is_applied(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="syscall-block",- command=["/usr/bin/sleep", "3600"],- policy={- "name": "syscall-block-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "syscall": {- "x86_64": {"blocked": ["getpid"]},- "arm64": {"blocked": ["getpid"]},- },- "network": {- "mode": "host",- },- },- )-- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": [- "/usr/bin/python3",- "-c",- textwrap.dedent(- """- import ctypes- import errno- import platform- import sys-- syscall_numbers = {- "x86_64": 39,- "AMD64": 39,- "aarch64": 172,- }- nr = syscall_numbers.get(platform.machine())- if nr is None:- print(f"unsupported-arch:{platform.machine()}")- sys.exit(2)-- libc = ctypes.CDLL("libc.so.6", use_errno=True)- libc.syscall.restype = ctypes.c_long- ctypes.set_errno(0)- result = libc.syscall(nr)- err = ctypes.get_errno()- if result == -1 and err == errno.EPERM:- print("syscall-blocked")- sys.exit(7)-- print(f"unexpected-success:{result}:{err}")- """- ).strip(),- ],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 7, data- assert "syscall-blocked" in data["stdout"]- assert "unexpected-success" not in data["stdout"]-- @staticmethod- def test_pid_namespace_policy_is_applied(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="pid-ns",- policy={- "name": "pid-ns-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "namespace": {- "pid": True,- },- "landlock": {- "compatibility": "disabled",- },- "network": {- "mode": "host",- },- },- )-- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", "import os; print(os.getpid())"],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0, data- assert int(data["stdout"].strip()) <= 5-- @staticmethod- def test_capability_drop_removes_net_raw(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="cap-drop",- policy={- "name": "cap-drop-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "process": {- "run_as_user": "root",- "run_as_group": "root",- },- "capabilities": {- "add": ["CAP_NET_RAW"],- "drop": ["CAP_NET_RAW"],- },- "landlock": {- "compatibility": "disabled",- },- "network": {- "mode": "host",- },- },- )-- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _capability_check_script(13)],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0, data- assert data["stdout"].strip() == "no"-- @staticmethod- def test_capability_add_net_raw_sets_effective_capability(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="cap-add",- policy={- "name": "cap-add-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "process": {- "run_as_user": "root",- "run_as_group": "root",- },- "capabilities": {- "add": ["CAP_NET_RAW"],- "drop": [],- },- "landlock": {- "compatibility": "disabled",- },- "network": {- "mode": "host",- },- },- )-- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _capability_check_script(13)],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0, data- assert data["stdout"].strip() == "yes"-- @staticmethod- def test_landlock_hard_requirement_policy_is_enforced(- client,- ):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo", "landlock-ok"],- "policy": _with_runtime_support({- "name": "landlock-hard-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "landlock": {- "compatibility": "hard_requirement",- },- "network": {- "mode": "host",- },- }),- })- assert create_resp.status_code == 201- data = create_resp.json()- if data["phase"] == "ready":- assert data["phase"] == "ready", data- else:- assert data["phase"] == "error", data- assert "landlock" in (data.get("error_message") or "").lower()-- @staticmethod- def test_landlock_rules_allow_policy_paths_and_deny_other_mounted_paths(- client,- ):- create_resp = client.post("/api/v1/sandboxes", json={- "name": "landlock-rules",- "command": LONG_RUNNING_COMMAND,- "policy": _with_runtime_support({- "name": "landlock-rules-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "landlock": {- "compatibility": "hard_requirement",- },- "network": {- "mode": "host",- },- }),- })- assert create_resp.status_code == 201- sandbox = create_resp.json()- if sandbox["phase"] == "error":- assert "landlock" in (sandbox.get("error_message") or "").lower()- return- assert sandbox["phase"] == "ready", sandbox- allowed_path = f"/tmp/{sandbox['id']}-landlock-allowed.txt"-- script = textwrap.dedent(- """- from pathlib import Path- import sys-- allowed = Path(sys.argv[1])- allowed.write_text("landlock-allowed")- assert allowed.read_text() == "landlock-allowed"-- try:- Path("/run/jiuwenbox-landlock-launcher.py").read_text()- except PermissionError:- print("landlock-denied")- sys.exit(7)-- print("unexpected-success")- """- ).strip()- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", script, allowed_path],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 7, data- assert "landlock-denied" in data["stdout"]- assert "unexpected-success" not in data["stdout"]-- @staticmethod- def test_network_mode_isolated_blocks_http_requests(- client,- create_sandbox_with_policy,- server_endpoint,- ):- sandbox = create_sandbox_with_policy(- name_prefix="net-isolated",- policy={- "name": "net-isolated-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "isolated",- "egress": {"default": "allow"},- },- },- )-- script = (- "import sys, urllib.request; "- "urllib.request.urlopen(sys.argv[1], timeout=2).read(); "- "print('unexpected-success')"- )- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", script, _sandbox_health_url(server_endpoint)],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] != 0- assert "unexpected-success" not in data["stdout"]-- @staticmethod- def test_network_mode_host_allows_http_requests(- client,- create_sandbox_with_policy,- server_endpoint,- ):- sandbox = create_sandbox_with_policy(- name_prefix="net-host",- policy={- "name": "net-host-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "host",- "egress": {"default": "allow"},- },- },- )-- script = (- "import sys, urllib.request; "- "print(urllib.request.urlopen(sys.argv[1], timeout=2).read().decode())"- )- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", script, _sandbox_health_url(server_endpoint)],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0- assert '"status":"ok"' in data["stdout"].replace(" ", "")-- @staticmethod- def test_ingress_allowed_port_accepts_loopback_connection(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="ingress-allow",- policy={- "name": "ingress-allow-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "isolated",- "egress": {"default": "allow"},- "ingress": {- "default": "deny",- "allowed_ips": ["127.0.0.1/32"],- "allowed_ports": [18081],- },- },- },- )-- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _loopback_ingress_script(True), "18081"],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0, data- assert "ingress-ok" in data["stdout"]-- @staticmethod- def test_ingress_blocked_port_rejects_loopback_connection(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="ingress-block",- policy={- "name": "ingress-block-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "isolated",- "egress": {"default": "allow"},- "ingress": {- "default": "deny",- "allowed_ips": ["127.0.0.1/32"],- "allowed_ports": [18081],- "blocked_ports": [18082],- },- },- },- )-- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _loopback_ingress_script(False), "18082"],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] != 0- assert "unexpected-success" not in data["stdout"]-- @staticmethod- def test_isolated_sandbox_policy_persists_after_restart(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="netns-persist",- policy={- "name": "netns-persist-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "network": {- "mode": "isolated",- "egress": {"default": "allow"},- "ingress": {- "default": "deny",- "allowed_ips": ["127.0.0.1/32"],- "allowed_ports": [18083],- },- },- },- )-- first_exec = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _loopback_ingress_script(True), "18083"],- "timeout_seconds": 5,- })- assert first_exec.status_code == 200- first_data = first_exec.json()- assert first_data["exit_code"] == 0, first_data-- stop_response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/stop")- assert stop_response.status_code == 200-- start_response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/start")- assert start_response.status_code == 200-- second_exec = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", _loopback_ingress_script(True), "18083"],- "timeout_seconds": 5,- })- assert second_exec.status_code == 200- second_data = second_exec.json()- assert second_data["exit_code"] == 0, second_data-- delete_response = client.delete(f"/api/v1/sandboxes/{sandbox['id']}")- assert delete_response.status_code == 204---class TestSandboxExec:- @staticmethod- def test_exec_requires_running_sandbox(client):- create_resp = client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/sleep", "3600"],- })- sandbox_id = create_resp.json()["id"]-- # Stop it first- client.post(f"/api/v1/sandboxes/{sandbox_id}/stop")-- resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={- "command": ["/usr/bin/echo", "hello"],- })- assert resp.status_code == 409---class TestSandboxListing:- @staticmethod- def test_list_returns_all_sandboxes(client):- for i in range(3):- client.post("/api/v1/sandboxes", json={- "command": ["/usr/bin/echo"],- })-- resp = client.get("/api/v1/sandboxes")- assert resp.status_code == 200- assert len(resp.json()) == 3\ No newline at end of filediff --git a/jiuwenbox/tests/performance/conftest.py b/jiuwenbox/tests/performance/conftest.pynew file mode 100644index 0000000000..b629fc522e--- /dev/null+++ b/jiuwenbox/tests/performance/conftest.py@@ -0,0 +1,156 @@+"""Shared fixtures for jiuwenbox performance tests."""++from __future__ import annotations++import asyncio+import logging+import os++import httpx+import pytest+import pytest_asyncio++logger = logging.getLogger(__name__)+logging.getLogger("httpx").setLevel(logging.WARNING)+logging.getLogger("httpcore").setLevel(logging.WARNING)+++def _normalize_endpoint(endpoint: str) -> str:+ return endpoint if "://" in endpoint else f"http://{endpoint}"+++def _env_int(name: str, default: int, *, minimum: int = 1) -> int:+ raw_value = os.environ.get(name)+ if raw_value is None:+ return default+ try:+ value = int(raw_value)+ except ValueError:+ logger.warning("Ignoring invalid %s=%r; using %s", name, raw_value, default)+ return default+ return max(minimum, value)++[email protected](scope="session")+def perf_sandbox_count() -> int:+ """Number of sandboxes to create for the performance workload."""+ return _env_int("JIUWENBOX_PERF_SANDBOX_COUNT", 1)++[email protected](scope="session")+def perf_concurrency() -> int:+ """Number of concurrent tasks to run inside each sandbox."""+ return _env_int("JIUWENBOX_PERF_CONCURRENCY", 4)++[email protected](scope="session")+def perf_loop() -> int:+ """Number of workload loops each concurrent task runs."""+ return _env_int("JIUWENBOX_PERF_LOOP", 8)++[email protected](scope="session")+def perf_exec_timeout_seconds() -> int:+ """Timeout for each in-sandbox office edit command."""+ return _env_int("JIUWENBOX_PERF_EXEC_TIMEOUT_SECONDS", 180)+++TRANSIENT_HTTP_ERRORS = (+ httpx.ConnectError,+ httpx.ConnectTimeout,+ httpx.PoolTimeout,+ httpx.ReadError,+ httpx.ReadTimeout,+ httpx.RemoteProtocolError,+ httpx.WriteError,+ httpx.WriteTimeout,+)+++class AsyncSandboxTrackingClient:+ """Track sandboxes created during a performance test and clean them up."""++ def __init__(self, client: httpx.AsyncClient):+ self._client = client+ self._created_ids: list[str] = []++ def __getattr__(self, name: str):+ return getattr(self._client, name)++ async def _request(self, method: str, url, *args, **kwargs):+ retry_count = 3+ for attempt in range(retry_count + 1):+ try:+ return await self._client.request(method, url, *args, **kwargs)+ except TRANSIENT_HTTP_ERRORS:+ if attempt >= retry_count:+ raise+ await asyncio.sleep(0.1 * (2 ** attempt))++ raise RuntimeError("unreachable retry state")++ async def post(self, url, *args, **kwargs):+ is_create_sandbox = str(url).rstrip("/") == "/api/v1/sandboxes"+ if is_create_sandbox:+ response = await self._client.post(url, *args, **kwargs)+ else:+ response = await self._request("POST", url, *args, **kwargs)+ if is_create_sandbox and response.status_code == 201:+ try:+ sandbox_id = response.json().get("id")+ except Exception as exc:+ logger.debug("Failed to parse sandbox create response: %s", exc)+ sandbox_id = None+ if sandbox_id:+ self._created_ids.append(sandbox_id)+ return response++ async def delete(self, url, *args, **kwargs):+ response = await self._request("DELETE", url, *args, **kwargs)+ sandbox_id = self._sandbox_id_from_delete_url(url)+ if sandbox_id and response.status_code in (200, 202, 204, 404):+ self._created_ids = [item for item in self._created_ids if item != sandbox_id]+ return response++ async def get(self, url, *args, **kwargs):+ return await self._request("GET", url, *args, **kwargs)++ async def cleanup_sandboxes(self) -> None:+ for sandbox_id in reversed(self._created_ids):+ try:+ await self._client.delete(f"/api/v1/sandboxes/{sandbox_id}")+ except Exception as exc:+ logger.warning("Failed to cleanup sandbox %s: %s", sandbox_id, exc)+ self._created_ids.clear()++ @staticmethod+ def _sandbox_id_from_delete_url(url) -> str | None:+ path = str(url).split("?", 1)[0].rstrip("/")+ prefix = "/api/v1/sandboxes/"+ if not path.startswith(prefix):+ return None+ suffix = path[len(prefix):]+ if "/" in suffix:+ return None+ return suffix or None+++@pytest_asyncio.fixture+async def perf_client(server_endpoint, perf_sandbox_count, perf_concurrency):+ timeout = httpx.Timeout(connect=10.0, read=180.0, write=180.0, pool=180.0)+ max_connections = max(16, perf_sandbox_count * perf_concurrency * 4)+ limits = httpx.Limits(+ max_connections=max_connections,+ max_keepalive_connections=0,+ )+ async with httpx.AsyncClient(+ base_url=_normalize_endpoint(server_endpoint),+ timeout=timeout,+ limits=limits,+ trust_env=False,+ ) as external:+ tracking = AsyncSandboxTrackingClient(external)+ try:+ yield tracking+ finally:+ await tracking.cleanup_sandboxes()diff --git a/jiuwenbox/tests/performance/test_concurrent_office_workload.py b/jiuwenbox/tests/performance/test_concurrent_office_workload.pynew file mode 100644index 0000000000..e8f6d9f1b4--- /dev/null+++ b/jiuwenbox/tests/performance/test_concurrent_office_workload.py@@ -0,0 +1,329 @@+"""Performance tests for concurrent jiuwenbox office-style workloads."""++from __future__ import annotations++import asyncio+import hashlib+import logging+import statistics+import time+from dataclasses import dataclass++import pytest++pytestmark = [pytest.mark.performance, pytest.mark.slow, pytest.mark.asyncio]++logger = logging.getLogger(__name__)++OFFICE_EDIT_SCRIPT = """+import hashlib+import json+import sys+from pathlib import Path++doc_path = Path(sys.argv[1])+report_path = Path(sys.argv[2])+task_id = sys.argv[3]++content = doc_path.read_text()+base_content = content.split("\\n## Meeting Notes\\n", 1)[0]+score = sum((index + ord(task_id[0])) * index for index in range(1800000))+edited = (+ base_content+ + "\\n## Meeting Notes\\n"+ + f"- task: {task_id}\\n"+ + f"- score: {score}\\n"+)+doc_path.write_text(edited)+report_path.write_text(json.dumps({+ "task_id": task_id,+ "bytes": len(edited.encode()),+ "sha256": hashlib.sha256(edited.encode()).hexdigest(),+}))+print(hashlib.sha256(edited.encode()).hexdigest())+""".strip()+++@dataclass(frozen=True)+class PerfSample:+ task_id: int+ total_ms: float+ upload_ms: float+ exec_ms: float+ list_ms: float+ download_ms: float+++@dataclass(frozen=True)+class OfficeEditCall:+ """Per-task inputs for ``_execute_office_edit``.++ Bundled into a value object so the helper signature stays at or below+ five arguments (G.FNM.03) without losing readability at the call site.+ """++ sandbox_id: str+ doc_path: str+ report_path: str+ task_id: int+ timeout_seconds: int+++def _percentile(values: list[float], percentile: float) -> float:+ ordered = sorted(values)+ if not ordered:+ return 0.0+ rank = (len(ordered) - 1) * percentile+ low = int(rank)+ high = min(low + 1, len(ordered) - 1)+ if low == high:+ return ordered[low]+ weight = rank - low+ return ordered[low] * (1 - weight) + ordered[high] * weight+++def _record_summary(+ name: str,+ samples: list[PerfSample],+ elapsed_s: float,+ *,+ sandbox_count: int,+ concurrency: int,+ loop: int,+ setup_s: float,+ workload_s: float,+) -> None:+ totals = [sample.total_ms for sample in samples]+ summary = {+ "operations": len(samples),+ "sandbox_count": sandbox_count,+ "concurrency": concurrency,+ "loop": loop,+ "elapsed_s": round(elapsed_s, 3),+ "setup_s": round(setup_s, 3),+ "workload_s": round(workload_s, 3),+ "throughput_ops_per_s": round(len(samples) / elapsed_s, 3) if elapsed_s else 0,+ "workload_ops_per_s": round(len(samples) / workload_s, 3) if workload_s else 0,+ "avg_ms": round(statistics.fmean(totals), 3),+ "p50_ms": round(_percentile(totals, 0.50), 3),+ "p95_ms": round(_percentile(totals, 0.95), 3),+ "max_ms": round(max(totals), 3),+ "avg_upload_ms": round(statistics.fmean(sample.upload_ms for sample in samples), 3),+ "avg_exec_ms": round(statistics.fmean(sample.exec_ms for sample in samples), 3),+ "avg_list_ms": round(statistics.fmean(sample.list_ms for sample in samples), 3),+ "avg_download_ms": round(statistics.fmean(sample.download_ms for sample in samples), 3),+ }+ summary_text = (+ f"[jiuwenbox-perf] {name}\n"+ f" sandbox_count={summary['sandbox_count']} concurrency={summary['concurrency']} "+ f"loop={summary['loop']} operations={summary['operations']}\n"+ f" elapsed={summary['elapsed_s']}s setup={summary['setup_s']}s "+ f"workload={summary['workload_s']}s "+ f"throughput={summary['throughput_ops_per_s']} ops/s "+ f"workload_throughput={summary['workload_ops_per_s']} ops/s\n"+ f" total_ms: avg={summary['avg_ms']} p50={summary['p50_ms']} "+ f"p95={summary['p95_ms']} max={summary['max_ms']}\n"+ f" stage_avg_ms: upload={summary['avg_upload_ms']} exec={summary['avg_exec_ms']} "+ f"list={summary['avg_list_ms']} download={summary['avg_download_ms']}"+ )+ logger.info("%s", summary_text)+++async def _create_ready_sandbox(client) -> dict:+ response = await client.post("/api/v1/sandboxes", json={})+ assert response.status_code == 201, response.text+ sandbox = response.json()+ assert sandbox["phase"] == "ready", sandbox+ return sandbox+++def _office_source(task_id: int) -> bytes:+ return (+ f"# Weekly Brief {task_id}\\n\\n"+ "Project update: review pull requests, refresh planning notes, "+ "and prepare the customer-facing summary.\\n"+ "Action items:\\n"+ "- reconcile spreadsheet changes\\n"+ "- summarize design discussion\\n"+ "- prepare next sprint checklist\\n"+ ).encode() * 100+++async def _upload_office_document(client, sandbox_id: str, doc_path: str, source: bytes) -> float:+ upload_started = time.perf_counter()+ upload = await client.post(+ f"/api/v1/sandboxes/{sandbox_id}/upload",+ params={"sandbox_path": doc_path},+ files={"file": ("weekly-brief.md", source, "text/markdown")},+ )+ upload_ms = (time.perf_counter() - upload_started) * 1000+ assert upload.status_code == 204, upload.text+ return upload_ms+++async def _execute_office_edit(+ client, call: OfficeEditCall,+) -> tuple[float, str]:+ exec_started = time.perf_counter()+ execution = await client.post(+ f"/api/v1/sandboxes/{call.sandbox_id}/exec",+ json={+ "command": [+ "python3",+ "-c",+ OFFICE_EDIT_SCRIPT,+ call.doc_path,+ call.report_path,+ str(call.task_id),+ ],+ "timeout_seconds": call.timeout_seconds,+ },+ )+ exec_ms = (time.perf_counter() - exec_started) * 1000+ assert execution.status_code == 200, execution.text+ exec_data = execution.json()+ assert exec_data["exit_code"] == 0, exec_data+ expected_digest = exec_data["stdout"].strip()+ return exec_ms, expected_digest+++async def _list_office_outputs(+ client,+ sandbox_id: str,+ task_dir: str,+ doc_path: str,+ report_path: str,+) -> float:+ list_started = time.perf_counter()+ listing = await client.get(+ f"/api/v1/sandboxes/{sandbox_id}/files",+ params={"sandbox_path": task_dir, "recursive": True},+ )+ list_ms = (time.perf_counter() - list_started) * 1000+ assert listing.status_code == 200, listing.text+ paths = {item["path"] for item in listing.json()["items"]}+ assert doc_path in paths+ assert report_path in paths+ return list_ms+++async def _download_office_document(+ client,+ sandbox_id: str,+ doc_path: str,+ expected_digest: str,+) -> float:+ download_started = time.perf_counter()+ download = await client.get(+ f"/api/v1/sandboxes/{sandbox_id}/download",+ params={"sandbox_path": doc_path},+ )+ download_ms = (time.perf_counter() - download_started) * 1000+ assert download.status_code == 200, download.text+ assert b"## Meeting Notes" in download.content+ assert hashlib.sha256(download.content).hexdigest() == expected_digest+ return download_ms+++async def _run_office_task(+ client,+ sandbox_id: str,+ task_id: int,+ exec_timeout_seconds: int,+) -> PerfSample:+ task_dir = f"/tmp/jiuwenbox-perf/task-{task_id}"+ doc_path = f"{task_dir}/weekly-brief.md"+ report_path = f"{task_dir}/analysis.json"+ source = _office_source(task_id)++ started = time.perf_counter()+ upload_ms = await _upload_office_document(client, sandbox_id, doc_path, source)+ exec_ms, expected_digest = await _execute_office_edit(+ client,+ OfficeEditCall(+ sandbox_id=sandbox_id,+ doc_path=doc_path,+ report_path=report_path,+ task_id=task_id,+ timeout_seconds=exec_timeout_seconds,+ ),+ )+ list_ms = await _list_office_outputs(client, sandbox_id, task_dir, doc_path, report_path)+ download_ms = await _download_office_document(+ client,+ sandbox_id,+ doc_path,+ expected_digest,+ )++ total_ms = (time.perf_counter() - started) * 1000+ return PerfSample(+ task_id=task_id,+ total_ms=total_ms,+ upload_ms=upload_ms,+ exec_ms=exec_ms,+ list_ms=list_ms,+ download_ms=download_ms,+ )+++async def test_concurrent_office_workload(+ perf_client,+ perf_sandbox_count,+ perf_concurrency,+ perf_loop,+ perf_exec_timeout_seconds,+):+ started = time.perf_counter()+ sandboxes = await asyncio.gather(+ *(_create_ready_sandbox(perf_client) for _ in range(perf_sandbox_count)),+ )+ setup_s = time.perf_counter() - started++ async def run_worker(+ sandbox_index: int,+ sandbox_id: str,+ worker_index: int,+ ) -> list[PerfSample]:+ samples = []+ base_task_id = sandbox_index * perf_concurrency * perf_loop + worker_index * perf_loop+ for loop_index in range(perf_loop):+ samples.append(+ await _run_office_task(+ perf_client,+ sandbox_id,+ base_task_id + loop_index,+ perf_exec_timeout_seconds,+ )+ )+ return samples++ try:+ workload_started = time.perf_counter()+ worker_samples = await asyncio.gather(+ *(+ run_worker(sandbox_index, sandbox["id"], worker_index)+ for sandbox_index, sandbox in enumerate(sandboxes)+ for worker_index in range(perf_concurrency)+ ),+ )+ workload_s = time.perf_counter() - workload_started+ elapsed_s = time.perf_counter() - started+ finally:+ await asyncio.gather(+ *(perf_client.delete(f"/api/v1/sandboxes/{sandbox['id']}") for sandbox in sandboxes),+ return_exceptions=True,+ )++ samples = [sample for worker_result in worker_samples for sample in worker_result]+ assert len(samples) == perf_sandbox_count * perf_concurrency * perf_loop+ _record_summary(+ "concurrent_office_workload",+ samples,+ elapsed_s,+ sandbox_count=perf_sandbox_count,+ concurrency=perf_concurrency,+ loop=perf_loop,+ setup_s=setup_s,+ workload_s=workload_s,+ )diff --git a/jiuwenbox/tests/test.sh b/jiuwenbox/tests/test.shindex 688576550f..c6c09af69d 100755--- a/jiuwenbox/tests/test.sh+++ b/jiuwenbox/tests/test.sh@@ -6,23 +6,87 @@ TEST_DIR="$(cd "$(dirname "$0")" && pwd)"PROJECT_DIR="$(cd "$TEST_DIR/.." && pwd)"cd "$PROJECT_DIR"-if [ -d ".venv" ]; then- source .venv/bin/activate-fi+JIUWENBOX_DIR="$(realpath "$PROJECT_DIR/src")"TEST_TARGET="tests/integration/"+TEST_KIND="integration"+PERF_SANDBOX_COUNT="${JIUWENBOX_PERF_SANDBOX_COUNT:-1}"+PERF_CONCURRENCY="${JIUWENBOX_PERF_CONCURRENCY:-4}"+PERF_LOOP="${JIUWENBOX_PERF_LOOP:-8}"+PERF_EXEC_TIMEOUT_SECONDS="${JIUWENBOX_PERF_EXEC_TIMEOUT_SECONDS:-180}"++require_value() {+ local option="$1"+ if [[ $# -lt 2 || "$2" == --* ]]; then+ echo "Missing value for ${option}" >&2+ exit 2+ fi+}if [[ $# -gt 0 ]]; thencase "$1" indefault)TEST_TARGET="tests/integration/test_server_api_default.py"+ TEST_KIND="integration"+ shift+ ;;+ inference-privacy-proxy)+ TEST_TARGET="tests/integration/test_inference_privacy_proxy.py"+ TEST_KIND="integration"shift;;- jiuwenclaw-tool)- TEST_TARGET="tests/integration/test_server_api_jiuwenclaw_tool.py"+ performance)+ TEST_TARGET="tests/performance/"+ TEST_KIND="performance"shift;;esacfi-python3 -m pytest "$TEST_TARGET" -v --tb=short "$@"\ No newline at end of file+PYTEST_ARGS=()+if [[ "$TEST_KIND" == "performance" ]]; then+ PYTEST_ARGS+=(+ "-s"+ "--log-cli-level=INFO"+ "--log-cli-format=%(message)s"+ "--log-disable=httpx"+ "--log-disable=httpcore"+ )+ while [[ $# -gt 0 ]]; do+ case "$1" in+ --sandbox-count)+ require_value "$1" "${2:-}"+ PERF_SANDBOX_COUNT="$2"+ shift 2+ ;;+ --concurrency)+ require_value "$1" "${2:-}"+ PERF_CONCURRENCY="$2"+ shift 2+ ;;+ --loop)+ require_value "$1" "${2:-}"+ PERF_LOOP="$2"+ shift 2+ ;;+ *)+ PYTEST_ARGS+=("$1")+ shift+ ;;+ esac+ done+else+ PYTEST_ARGS=("$@")+fi++if [[ "$TEST_KIND" == "performance" ]]; then+ JIUWENBOX_PERF_SANDBOX_COUNT=${PERF_SANDBOX_COUNT} \+ JIUWENBOX_PERF_CONCURRENCY=${PERF_CONCURRENCY} \+ JIUWENBOX_PERF_LOOP=${PERF_LOOP} \+ JIUWENBOX_PERF_EXEC_TIMEOUT_SECONDS=${PERF_EXEC_TIMEOUT_SECONDS} \+ PYTHONPATH=${JIUWENBOX_DIR} \+ python3 -m pytest "$TEST_TARGET" -v --tb=short "${PYTEST_ARGS[@]}"+else+ PYTHONPATH=${JIUWENBOX_DIR} \+ python3 -m pytest "$TEST_TARGET" -v --tb=short "${PYTEST_ARGS[@]}"+fidiff --git a/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py b/jiuwenclaw/server/runtime/agent_adapter/interface_deep.pyindex a60c5408ea..8dc69f2d2a 100644--- a/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py@@ -178,10 +178,16 @@ from jiuwenclaw.agents.harness.common.plugins.rail_manager import get_rail_managfrom jiuwenclaw.gateway.cron import CronTargetChannelfrom jiuwenclaw.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunkfrom jiuwenclaw.common.utils import (+ get_agent_memory_dir,get_agent_skills_dir,get_agent_workspace_dir,get_checkpoint_dir,get_config_dir,+ get_deepagent_agent_md_path,+ get_deepagent_heartbeat_path,+ get_deepagent_identity_md_path,+ get_deepagent_soul_md_path,+ get_deepagent_user_md_path,get_env_file,reset_free_search_runtime_flags,)@@ -1452,6 +1458,91 @@ class JiuWenClawDeepAdapter:rail = Nonereturn rail+ @staticmethod+ def _create_sandbox_sys_operation(sandbox_url, sandbox_type) -> SysOperationCard | None:+ """Create a sandbox sys operation."""+ import openjiuwen.extensions.sys_operation.sandbox.providers+ try:+ file_funcs = [+ get_deepagent_agent_md_path,+ get_deepagent_heartbeat_path,+ get_deepagent_identity_md_path,+ get_deepagent_soul_md_path,+ get_deepagent_user_md_path+ ]+ sandbox_policy = {+ "policy": {+ 'filesystem_policy': {+ 'files': [],+ 'directories': []+ }+ },+ "policy_mode": "append",+ }+ for func in file_funcs:+ path = func()+ if path is not None:+ sandbox_policy["policy"]["filesystem_policy"]["files"].append(+ {"path": str(path), "permissions": "0666"}+ )+ sandbox_policy["policy"]["filesystem_policy"]["directories"].append(+ {"path": str(get_agent_memory_dir() / "daily_memory"), "permissions": "0777"}+ )+ gateway_config = SandboxGatewayConfig(+ isolation=SandboxIsolationConfig(container_scope=ContainerScope.SYSTEM),+ launcher_config=PreDeployLauncherConfig(+ base_url=sandbox_url,+ sandbox_type=sandbox_type,+ idle_ttl_seconds=600,+ extra_params=sandbox_policy,+ ),+ )+ sysop_card = SysOperationCard(+ mode=OperationMode.SANDBOX,+ work_config=LocalWorkConfig(shell_allowlist=None),+ gateway_config=gateway_config,+ )+ return sysop_card+ except Exception as exc:+ logger.warning("[JiuWenClawDeepAdapter] create sandbox sys operation failed: %s", exc)+ return None++ @staticmethod+ def _sys_operation_isolation_key(sysop_card: SysOperationCard) -> str | None:+ try:+ sys_operation = SysOperation(sysop_card)+ return sys_operation.isolation_key_template+ except Exception as exc:+ logger.debug(+ "[JiuWenClawDeepAdapter] failed to resolve sys_operation isolation key: %s",+ exc,+ )+ return None++ @staticmethod+ def _get_registered_sys_operation_by_isolation_key(+ isolation_key_template: str | None,+ ) -> SysOperation | None:+ if not isolation_key_template:+ return None++ try:+ resource_registry = getattr(Runner.resource_mgr, "_resource_registry", None)+ if resource_registry is None:+ return None+ sys_operation_mgr = resource_registry.sys_operation()+ owner_map = getattr(sys_operation_mgr, "_sandbox_key_owner_map", {})+ existing_op_id = owner_map.get(isolation_key_template)+ if not existing_op_id:+ return None+ return Runner.resource_mgr.get_sys_operation(existing_op_id)+ except Exception as exc:+ logger.debug(+ "[JiuWenClawDeepAdapter] failed to get registered sys_operation: %s",+ exc,+ )+ return None+@staticmethoddef _create_sys_operation() -> SysOperation | None:"""Create a sys operation."""@@ -1459,27 +1550,41 @@ class JiuWenClawDeepAdapter:sandbox_url = _sandbox_config.get("url", None)sandbox_type = _sandbox_config.get("type", None)if sandbox_url and sandbox_type:- gateway_config = SandboxGatewayConfig(- isolation=SandboxIsolationConfig(container_scope=ContainerScope.SYSTEM),- launcher_config=PreDeployLauncherConfig(- base_url=sandbox_url,- sandbox_type=sandbox_type,- idle_ttl_seconds=600,- ),- timeout_seconds=30,- )- sysop_card = SysOperationCard(- mode=OperationMode.SANDBOX,- work_config=LocalWorkConfig(shell_allowlist=None),- gateway_config=gateway_config,- )+ sysop_card = JiuWenClawDeepAdapter._create_sandbox_sys_operation(sandbox_url, sandbox_type)else:sysop_card = SysOperationCard(mode=OperationMode.LOCAL,work_config=LocalWorkConfig(shell_allowlist=None),)+ if sysop_card is None:+ logger.warning("[JiuWenClawDeepAdapter] add sys_operation failed: sysop_card is None")+ return None+ isolation_key_template = JiuWenClawDeepAdapter._sys_operation_isolation_key(sysop_card)+ registered_sys_operation = (+ JiuWenClawDeepAdapter._get_registered_sys_operation_by_isolation_key(+ isolation_key_template+ )+ )+ if registered_sys_operation is not None:+ logger.info(+ "[JiuWenClawDeepAdapter] reuse registered sys_operation: %s",+ registered_sys_operation.id,+ )+ return registered_sys_operation+result = Runner.resource_mgr.add_sys_operation(sysop_card)if result.is_err():+ registered_sys_operation = (+ JiuWenClawDeepAdapter._get_registered_sys_operation_by_isolation_key(+ isolation_key_template+ )+ )+ if registered_sys_operation is not None:+ logger.info(+ "[JiuWenClawDeepAdapter] reuse registered sys_operation after add failure: %s",+ registered_sys_operation.id,+ )+ return registered_sys_operationlogger.warning("[JiuWenClawDeepAdapter] add sys_operation failed: %s", result.msg())return Nonereturn Runner.resource_mgr.get_sys_operation(sysop_card.id)