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 add support for arm64
zhaozixuan1d4fcf87bc0d
diff --git a/jiuwenbox/README.md b/jiuwenbox/README.mdindex bf9fac4069..df86ec24a6 100644--- a/jiuwenbox/README.md+++ b/jiuwenbox/README.md@@ -56,7 +56,7 @@ tests/- Linux- Python 3.11+- `bubblewrap`-- `iproute2` and `iptables` when `network.mode: isolated` is used+- `iproute2`, `iptables`, and `nftables` when `network.mode: isolated` is used- Kernel support for Landlock and seccomp when those features are enabled- `nodejs` if JavaScript execution is needed@@ -64,7 +64,7 @@ On Ubuntu:```bashsudo apt-get update-sudo apt-get install -y bubblewrap iproute2 iptables python3-pip nodejs+sudo apt-get install -y bubblewrap iproute2 iptables nftables python3-pip nodejs```## Install@@ -143,6 +143,8 @@ Important fields:`bind_mounts` to make the paths exist inside the sandbox.- `filesystem_policy.bind_mounts`- Explicit host-to-sandbox bind mounts.+- `filesystem_policy.device`+ - Explicit device nodes exposed inside the sandbox with `bwrap --dev-bind`.Path fields support shell-style expansion such as `~` and environmentvariables.@@ -201,6 +203,9 @@ filesystem_policy:- host_path: "/etc/ssl/openssl.cnf"sandbox_path: "/etc/ssl/openssl.cnf"mode: "ro"+ device:+ - host_path: "/dev/null"+ sandbox_path: "/dev/null"process:run_as_user: sandbox@@ -221,12 +226,20 @@ landlock:compatibility: best_effortsyscall:- blocked:- - "ptrace"- - "mount"- - "umount2"- - "reboot"- - "kexec_load"+ x86_64:+ blocked:+ - "ptrace"+ - "mount"+ - "umount2"+ - "reboot"+ - "kexec_load"+ arm64:+ blocked:+ - "ptrace"+ - "mount"+ - "umount2"+ - "reboot"+ - "kexec_load"network:mode: isolated@@ -297,10 +310,6 @@ curl -sS -X DELETE http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>## Run Integration Tests-```bash-./scripts/test.sh-```-Run one policy-specific integration suite:```bash@@ -308,6 +317,12 @@ Run one policy-specific integration suite:./scripts/test.sh jiuwenclaw-tool # jiuwenbox runs the service using jiuwenclaw-tool-policy.yaml as the security policy.```+Run specific test-case:++```bash+python3 -m pytest tests/integration/test_server_api_default.py::TestPolicyEnforcement::test_network_mode_isolated_blocks_http_requests -s --server-endpoint 127.0.0.1:8321+```+## Notes- Restart the server after changing the startup policy file.diff --git a/jiuwenbox/README_CN.md b/jiuwenbox/README_CN.mdindex 32b248b264..d8e706c8b4 100644--- a/jiuwenbox/README_CN.md+++ b/jiuwenbox/README_CN.md@@ -54,7 +54,7 @@ tests/- Linux- Python 3.11+- `bubblewrap`-- 使用 `network.mode: isolated` 时需要 `iproute2` 和 `iptables`+- 使用 `network.mode: isolated` 时需要 `iproute2`、`iptables` 和 `nftables`- 启用 Landlock 和 seccomp 时需要内核支持对应能力- 如果需要执行 JavaScript,则需要 `nodejs`@@ -62,7 +62,7 @@ Ubuntu 安装示例:```bashsudo apt-get update-sudo apt-get install -y bubblewrap iproute2 iptables python3-pip nodejs+sudo apt-get install -y bubblewrap iproute2 iptables nftables python3-pip nodejs```## 安装@@ -137,6 +137,8 @@ Docker 镜像默认会启动 `./scripts/server.sh`。让这些路径实际存在于沙箱内。- `filesystem_policy.bind_mounts`- 显式的宿主机到沙箱路径的 bind mount 配置。+- `filesystem_policy.device`+ - 使用 `bwrap --dev-bind` 暴露到沙箱内的显式设备节点。路径字段支持 shell 风格的展开,例如 `~` 和环境变量。@@ -194,6 +196,9 @@ filesystem_policy:- host_path: "/etc/ssl/openssl.cnf"sandbox_path: "/etc/ssl/openssl.cnf"mode: "ro"+ device:+ - host_path: "/dev/null"+ sandbox_path: "/dev/null"process:run_as_user: sandbox@@ -214,12 +219,20 @@ landlock:compatibility: best_effortsyscall:- blocked:- - "ptrace"- - "mount"- - "umount2"- - "reboot"- - "kexec_load"+ x86_64:+ blocked:+ - "ptrace"+ - "mount"+ - "umount2"+ - "reboot"+ - "kexec_load"+ arm64:+ blocked:+ - "ptrace"+ - "mount"+ - "umount2"+ - "reboot"+ - "kexec_load"network:mode: isolated@@ -290,10 +303,6 @@ curl -sS -X DELETE http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>## 运行集成测试-```bash-./scripts/test.sh-```-运行指定 policy 对应的集成测试:```bash@@ -301,6 +310,12 @@ curl -sS -X DELETE http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>./scripts/test.sh jiuwenclaw-tool # jiuwenbox 使用 jiuwenclaw-tool-policy.yaml 作为安全策略运行服务。```+运行指定测试用例:++```bash+python3 -m pytest tests/integration/test_server_api_default.py::TestPolicyEnforcement::test_network_mode_isolated_blocks_http_requests -s --server-endpoint 127.0.0.1:8321+```+## 注意事项- 修改启动 policy 文件后,需要重启服务。diff --git a/jiuwenbox/configs/default-policy.yaml b/jiuwenbox/configs/default-policy.yamlindex ccb3218770..2a94894fa4 100644--- a/jiuwenbox/configs/default-policy.yaml+++ b/jiuwenbox/configs/default-policy.yaml@@ -78,13 +78,23 @@ 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"+ # Device nodes to expose inside the sandbox with bwrap --dev-bind.+ # Each item uses:+ # host_path: absolute device path on the host+ # sandbox_path: absolute path visible inside the sandbox+ device:+ - host_path: "/dev/urandom"+ sandbox_path: "/dev/urandom"+ - host_path: "/dev/null"+ sandbox_path: "/dev/null"+# Process identity inside the sandbox.process:# User name to run as. If the user cannot be resolved, runtime falls back to nobody-style IDs.@@ -138,36 +148,68 @@ landlock:# Seccomp syscall filtering.syscall:- # Syscall names to block. Leave empty to disable explicit syscall blocking.- blocked:- - "kexec_load"- - "kexec_file_load"- - "reboot"- - "pivot_root"- - "swapon"- - "swapoff"- - "nfsservctl"- - "lookup_dcookie"- - "ptrace"- - "mount"- - "umount2"- - "unshare"- - "setns"- - "userfaultfd"- - "perf_event_open"- - "bpf"- - "add_key"- - "request_key"- - "keyctl"- - "io_uring_setup"- - "io_uring_enter"- - "io_uring_register"- - "open_by_handle_at"- - "name_to_handle_at"- - "init_module"- - "finit_module"- - "delete_module"- - "acct"+ # Syscall names to block on x86_64. Leave empty to disable explicit syscall blocking.+ x86_64:+ blocked:+ - "kexec_load"+ - "kexec_file_load"+ - "reboot"+ - "pivot_root"+ - "swapon"+ - "swapoff"+ - "nfsservctl"+ - "lookup_dcookie"+ - "ptrace"+ - "mount"+ - "umount2"+ - "unshare"+ - "setns"+ - "userfaultfd"+ - "perf_event_open"+ - "bpf"+ - "add_key"+ - "request_key"+ - "keyctl"+ - "io_uring_setup"+ - "io_uring_enter"+ - "io_uring_register"+ - "open_by_handle_at"+ - "name_to_handle_at"+ - "init_module"+ - "finit_module"+ - "delete_module"+ - "acct"+ # Syscall names to block on arm64/aarch64.+ arm64:+ blocked:+ - "kexec_load"+ - "kexec_file_load"+ - "reboot"+ - "pivot_root"+ - "swapon"+ - "swapoff"+ - "nfsservctl"+ - "lookup_dcookie"+ - "ptrace"+ - "mount"+ - "umount2"+ - "unshare"+ - "setns"+ - "userfaultfd"+ - "perf_event_open"+ - "bpf"+ - "add_key"+ - "request_key"+ - "keyctl"+ - "io_uring_setup"+ - "io_uring_enter"+ - "io_uring_register"+ - "open_by_handle_at"+ - "name_to_handle_at"+ - "init_module"+ - "finit_module"+ - "delete_module"+ - "acct"# Network policy. Egress controls outbound traffic; ingress controls inbound traffic.network:diff --git a/jiuwenbox/configs/jiuwenclaw-tool-policy.yaml b/jiuwenbox/configs/jiuwenclaw-tool-policy.yamlindex 69eb74b917..fa62976029 100644--- a/jiuwenbox/configs/jiuwenclaw-tool-policy.yaml+++ b/jiuwenbox/configs/jiuwenclaw-tool-policy.yaml@@ -76,6 +76,16 @@ filesystem_policy:sandbox_path: "/home/USER/.jiuwenclaw"mode: "rw"+ # Device nodes to expose inside the sandbox with bwrap --dev-bind.+ # Each item uses:+ # host_path: absolute device path on the host+ # sandbox_path: absolute path visible inside the sandbox+ device:+ - host_path: "/dev/urandom"+ sandbox_path: "/dev/urandom"+ - host_path: "/dev/null"+ sandbox_path: "/dev/null"+# Process identity inside the sandbox.process:# User name to run as. If the user cannot be resolved, runtime falls back to nobody-style IDs.@@ -129,36 +139,68 @@ landlock:# Seccomp syscall filtering.syscall:- # Syscall names to block. Leave empty to disable explicit syscall blocking.- blocked:- - "kexec_load"- - "kexec_file_load"- - "reboot"- - "pivot_root"- - "swapon"- - "swapoff"- - "nfsservctl"- - "lookup_dcookie"- - "ptrace"- - "mount"- - "umount2"- - "unshare"- - "setns"- - "userfaultfd"- - "perf_event_open"- - "bpf"- - "add_key"- - "request_key"- - "keyctl"- - "io_uring_setup"- - "io_uring_enter"- - "io_uring_register"- - "open_by_handle_at"- - "name_to_handle_at"- - "init_module"- - "finit_module"- - "delete_module"- - "acct"+ # Syscall names to block on x86_64. Leave empty to disable explicit syscall blocking.+ x86_64:+ blocked:+ - "kexec_load"+ - "kexec_file_load"+ - "reboot"+ - "pivot_root"+ - "swapon"+ - "swapoff"+ - "nfsservctl"+ - "lookup_dcookie"+ - "ptrace"+ - "mount"+ - "umount2"+ - "unshare"+ - "setns"+ - "userfaultfd"+ - "perf_event_open"+ - "bpf"+ - "add_key"+ - "request_key"+ - "keyctl"+ - "io_uring_setup"+ - "io_uring_enter"+ - "io_uring_register"+ - "open_by_handle_at"+ - "name_to_handle_at"+ - "init_module"+ - "finit_module"+ - "delete_module"+ - "acct"+ # Syscall names to block on arm64/aarch64.+ arm64:+ blocked:+ - "kexec_load"+ - "kexec_file_load"+ - "reboot"+ - "pivot_root"+ - "swapon"+ - "swapoff"+ - "nfsservctl"+ - "lookup_dcookie"+ - "ptrace"+ - "mount"+ - "umount2"+ - "unshare"+ - "setns"+ - "userfaultfd"+ - "perf_event_open"+ - "bpf"+ - "add_key"+ - "request_key"+ - "keyctl"+ - "io_uring_setup"+ - "io_uring_enter"+ - "io_uring_register"+ - "open_by_handle_at"+ - "name_to_handle_at"+ - "init_module"+ - "finit_module"+ - "delete_module"+ - "acct"# Network policy. Egress controls outbound traffic; ingress controls inbound traffic.network:diff --git a/jiuwenbox/docker/Dockerfile b/jiuwenbox/docker/Dockerfileindex d44ae549bb..19720104ef 100644--- a/jiuwenbox/docker/Dockerfile+++ b/jiuwenbox/docker/Dockerfile@@ -1,25 +1,26 @@-FROM ubuntu:24.04+FROM openeuler/openeuler:24.03ENV PYTHONDONTWRITEBYTECODE=1 \PYTHONUNBUFFERED=1 \PIP_NO_CACHE_DIR=1-RUN sed -i \- -e 's|http://archive.ubuntu.com/ubuntu|http://mirrors.tuna.tsinghua.edu.cn/ubuntu|g' \- -e 's|http://security.ubuntu.com/ubuntu|http://mirrors.tuna.tsinghua.edu.cn/ubuntu|g' \- /etc/apt/sources.list.d/ubuntu.sources+RUN echo "sslverify=false" >> /etc/yum.conf+RUN echo "insecure" >> ~/.curlrc+RUN sed -i 's/gpgcheck=1/gpgcheck=0/g' /etc/yum.conf /etc/yum.repos.d/openEuler.repo-RUN apt-get update \- && apt-get install -y --no-install-recommends \+RUN yum makecache \+ && yum install -y \bubblewrap \- iproute2 \+ iproute \iptables \+ iptables-nft \+ nftables \ca-certificates \nodejs \python3-pip \git \vim \- && rm -rf /var/lib/apt/lists/*+ unzipWORKDIR /appdiff --git a/jiuwenbox/docker/build_docker.sh b/jiuwenbox/docker/build_docker.shdeleted file mode 100755index 5a84e3af7b..0000000000--- a/jiuwenbox/docker/build_docker.sh+++ /dev/null@@ -1,11 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--DOCKER_DIR="$(cd "$(dirname "$0")" && pwd)"-PROJECT_DIR="$(cd "$DOCKER_DIR/.." && pwd)"--IMAGE_NAME="${JIUWENBOX_IMAGE_NAME:-jiuwenbox}"-IMAGE_TAG="${JIUWENBOX_IMAGE_TAG:-latest}"-IMAGE_REF="${IMAGE_NAME}:${IMAGE_TAG}"--docker build -f "$DOCKER_DIR/Dockerfile" --no-cache -t "$IMAGE_REF" "$PROJECT_DIR" "$@"diff --git a/jiuwenbox/scripts/build_docker.sh b/jiuwenbox/scripts/build_docker.shnew file mode 100755index 0000000000..db29b3a8bd--- /dev/null+++ b/jiuwenbox/scripts/build_docker.sh@@ -0,0 +1,12 @@+#!/usr/bin/env bash+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"++IMAGE_NAME="${JIUWENBOX_IMAGE_NAME:-jiuwenbox}"+IMAGE_TAG="${JIUWENBOX_IMAGE_TAG:-latest}"+IMAGE_REF="${IMAGE_NAME}:${IMAGE_TAG}"++docker build -f "$PROJECT_DIR/docker/Dockerfile" --no-cache -t "$IMAGE_REF" "$PROJECT_DIR" "$@"diff --git a/jiuwenbox/docker/run_docker.sh b/jiuwenbox/scripts/run_docker.shsimilarity index 87%rename from jiuwenbox/docker/run_docker.shrename to jiuwenbox/scripts/run_docker.shindex 47d0fe3942..697161312e 100755--- a/jiuwenbox/docker/run_docker.sh+++ b/jiuwenbox/scripts/run_docker.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.set -euo pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"diff --git a/jiuwenbox/src/jiuwenbox/__init__.py b/jiuwenbox/src/jiuwenbox/__init__.pyindex 46a81a307d..7b21aafb6c 100644--- a/jiuwenbox/src/jiuwenbox/__init__.py+++ b/jiuwenbox/src/jiuwenbox/__init__.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""jiuwenbox - Full-scenario Agent sandbox system."""__version__ = "0.1.0"diff --git a/jiuwenbox/src/jiuwenbox/models/__init__.py b/jiuwenbox/src/jiuwenbox/models/__init__.pyindex 43bc05deb2..358ef2005a 100644--- a/jiuwenbox/src/jiuwenbox/models/__init__.py+++ b/jiuwenbox/src/jiuwenbox/models/__init__.py@@ -1,3 +1,5 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+from jiuwenbox.models.sandbox import (ExecResult,SandboxPhase,@@ -5,6 +7,7 @@ from jiuwenbox.models.sandbox import (SandboxSpec,)from jiuwenbox.models.policy import (+ ArchitectureSyscallPolicy,BindMount,DirectoryMount,FilesystemPolicy,@@ -29,6 +32,7 @@ __all__ = ["SandboxRef","SandboxSpec","BindMount",+ "ArchitectureSyscallPolicy","DirectoryMount","FilesystemPolicy","CapabilityPolicy",diff --git a/jiuwenbox/src/jiuwenbox/models/common.py b/jiuwenbox/src/jiuwenbox/models/common.pyindex 02983e2c37..e6f4334913 100644--- a/jiuwenbox/src/jiuwenbox/models/common.py+++ b/jiuwenbox/src/jiuwenbox/models/common.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Common data models shared across components."""from __future__ import annotationsdiff --git a/jiuwenbox/src/jiuwenbox/models/policy.py b/jiuwenbox/src/jiuwenbox/models/policy.pyindex b8c834399c..d8033c9e48 100644--- a/jiuwenbox/src/jiuwenbox/models/policy.py+++ b/jiuwenbox/src/jiuwenbox/models/policy.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Security policy data models (static only)."""from __future__ import annotations@@ -7,7 +8,7 @@ import osfrom pathlib import Pathfrom typing import Literal-from pydantic import BaseModel, Field, field_validator+from pydantic import BaseModel, ConfigDict, Field, field_validatordef _expand_path(value: str) -> str:@@ -28,6 +29,18 @@ class BindMount(BaseModel):return value+class DeviceMount(BaseModel):+ host_path: str+ sandbox_path: str++ @field_validator("host_path", "sandbox_path", mode="before")+ @classmethod+ def expand_paths(cls, value: object) -> object:+ if isinstance(value, str):+ return _expand_path(value)+ return value++class DirectoryMount(BaseModel):path: strpermissions: str | int | None = None@@ -65,6 +78,7 @@ class FilesystemPolicy(BaseModel):read_only: list[str] = Field(default_factory=list)read_write: list[str] = Field(default_factory=list)bind_mounts: list[BindMount] = Field(default_factory=list)+ device: list[DeviceMount] = Field(default_factory=list)@field_validator("directories", mode="before")@classmethod@@ -103,10 +117,17 @@ class LandlockPolicy(BaseModel):compatibility: Literal["disabled", "best_effort", "hard_requirement"] = "best_effort"-class SyscallPolicy(BaseModel):+class ArchitectureSyscallPolicy(BaseModel):blocked: list[str] = Field(default_factory=list)+class SyscallPolicy(BaseModel):+ model_config = ConfigDict(extra="forbid")++ x86_64: ArchitectureSyscallPolicy = Field(default_factory=ArchitectureSyscallPolicy)+ arm64: ArchitectureSyscallPolicy = Field(default_factory=ArchitectureSyscallPolicy)++class NetworkMode(str, enum.Enum):ISOLATED = "isolated"HOST = "host"diff --git a/jiuwenbox/src/jiuwenbox/models/sandbox.py b/jiuwenbox/src/jiuwenbox/models/sandbox.pyindex 07501c9dce..e164de6cd3 100644--- a/jiuwenbox/src/jiuwenbox/models/sandbox.py+++ b/jiuwenbox/src/jiuwenbox/models/sandbox.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Sandbox data models."""from __future__ import annotationsdiff --git a/jiuwenbox/src/jiuwenbox/server/__init__.py b/jiuwenbox/src/jiuwenbox/server/__init__.pyindex e69de29bb2..fef222497f 100644--- a/jiuwenbox/src/jiuwenbox/server/__init__.py+++ b/jiuwenbox/src/jiuwenbox/server/__init__.py@@ -0,0 +1 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.\ No newline at end of filediff --git a/jiuwenbox/src/jiuwenbox/server/app.py b/jiuwenbox/src/jiuwenbox/server/app.pyindex 94e1265210..2071a35a77 100644--- a/jiuwenbox/src/jiuwenbox/server/app.py+++ b/jiuwenbox/src/jiuwenbox/server/app.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""FastAPI application for box-server."""from __future__ import annotationsdiff --git a/jiuwenbox/src/jiuwenbox/server/audit_logger.py b/jiuwenbox/src/jiuwenbox/server/audit_logger.pyindex fbfde0f086..d164c4ee8a 100644--- a/jiuwenbox/src/jiuwenbox/server/audit_logger.py+++ b/jiuwenbox/src/jiuwenbox/server/audit_logger.py@@ -1,3 +1,4 @@+# 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/.diff --git a/jiuwenbox/src/jiuwenbox/server/policy_engine.py b/jiuwenbox/src/jiuwenbox/server/policy_engine.pyindex a97018fef1..5072b3e81a 100644--- a/jiuwenbox/src/jiuwenbox/server/policy_engine.py+++ b/jiuwenbox/src/jiuwenbox/server/policy_engine.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Policy Engine - validates and resolves static security policies."""from __future__ import annotations@@ -101,6 +102,27 @@ class PolicyEngine:"backing storage")+ for device in policy.filesystem_policy.device:+ if (+ not self._is_absolute_sandbox_path(device.host_path)+ or not self._is_absolute_sandbox_path(device.sandbox_path)+ ):+ raise PolicyValidationError(+ "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(+ device.sandbox_path,+ policy.sandbox_workspace,+ )+ ):+ raise PolicyValidationError(+ f"Policy cannot directly reference '{policy.sandbox_workspace}' "+ "or its child paths; this path is reserved for server-managed "+ "backing storage"+ )+if policy.network.mode.value == "isolated":if self._denies_without_allow_rules(policy.network.egress):warnings.append(diff --git a/jiuwenbox/src/jiuwenbox/server/routes/__init__.py b/jiuwenbox/src/jiuwenbox/server/routes/__init__.pyindex e69de29bb2..fef222497f 100644--- a/jiuwenbox/src/jiuwenbox/server/routes/__init__.py+++ b/jiuwenbox/src/jiuwenbox/server/routes/__init__.py@@ -0,0 +1 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.\ No newline at end of filediff --git a/jiuwenbox/src/jiuwenbox/server/routes/policy.py b/jiuwenbox/src/jiuwenbox/server/routes/policy.pyindex a15f8d74d6..4d71da6a9f 100644--- a/jiuwenbox/src/jiuwenbox/server/routes/policy.py+++ b/jiuwenbox/src/jiuwenbox/server/routes/policy.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Policy API routes (static policies only)."""from __future__ import annotationsdiff --git a/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py b/jiuwenbox/src/jiuwenbox/server/routes/sandbox.pyindex 1c0f40451b..2f1d6571fd 100644--- a/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py+++ b/jiuwenbox/src/jiuwenbox/server/routes/sandbox.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Sandbox API routes."""from __future__ import annotationsdiff --git a/jiuwenbox/src/jiuwenbox/server/runtime/__init__.py b/jiuwenbox/src/jiuwenbox/server/runtime/__init__.pyindex e69de29bb2..fef222497f 100644--- a/jiuwenbox/src/jiuwenbox/server/runtime/__init__.py+++ b/jiuwenbox/src/jiuwenbox/server/runtime/__init__.py@@ -0,0 +1 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.\ No newline at end of filediff --git a/jiuwenbox/src/jiuwenbox/server/runtime/base.py b/jiuwenbox/src/jiuwenbox/server/runtime/base.pyindex 4482ad043d..36dc335b8f 100644--- a/jiuwenbox/src/jiuwenbox/server/runtime/base.py+++ b/jiuwenbox/src/jiuwenbox/server/runtime/base.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Abstract base class for sandbox runtime adapters."""from __future__ import annotationsdiff --git a/jiuwenbox/src/jiuwenbox/server/runtime/process.py b/jiuwenbox/src/jiuwenbox/server/runtime/process.pyindex c54bd3a3a6..9c52ad562c 100644--- a/jiuwenbox/src/jiuwenbox/server/runtime/process.py+++ b/jiuwenbox/src/jiuwenbox/server/runtime/process.py@@ -1,3 +1,4 @@+# 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.@@ -25,6 +26,7 @@ from jiuwenbox.models.policy import NetworkMode, SecurityPolicyfrom jiuwenbox.models.sandbox import ExecResultfrom jiuwenbox.server.runtime.base import RuntimeAdapter, RuntimeExecRequestfrom jiuwenbox.supervisor import network as network_module+from jiuwenbox.supervisor.sandbox_daemon import SANDBOX_DAEMON_COMMANDlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)@@ -104,9 +106,13 @@ class ProcessRuntime(RuntimeAdapter):@staticmethoddef _resolve_backing_identity(policy: SecurityPolicy) -> tuple[int, int]:if policy.namespace.user:- # With bwrap user namespaces, the server process uid is mapped to- # the sandbox run uid. Keep lifecycle backing dirs owned by that uid.- return os.getuid(), os.getgid()+ # For unprivileged user namespaces, the server uid is mapped to the+ # sandbox uid, so keeping the backing directory owned by the current+ # process is the writable choice. When the server runs as root, bwrap+ # can drop to the requested sandbox uid; root-owned 0755 directories+ # would then reject writes such as uploads under /home.+ if os.geteuid() != 0:+ return os.getuid(), os.getgid()try:uid = pwd.getpwnam(policy.process.run_as_user).pw_uid@@ -138,6 +144,39 @@ class ProcessRuntime(RuntimeAdapter):returnos.chmod(path, int(permissions, 8))+ @staticmethod+ def _needs_userns_write_fallback(+ policy: SecurityPolicy,+ uid: int,+ permissions: str | None,+ ) -> bool:+ if os.geteuid() != 0 or not policy.namespace.user or uid == 0:+ return False+ if permissions is None:+ return True+ mode = int(permissions, 8)+ return (+ bool(mode & 0o200)+ and (mode & 0o005) == 0o005+ and not bool(mode & 0o002)+ )++ @staticmethod+ def _apply_userns_write_fallback(path: Path) -> None:+ mode = path.stat().st_mode & 0o777+ fallback_mode = mode | 0o003+ if fallback_mode == mode:+ return+ logger.warning(+ "Relaxing policy directory %s permissions from %s to %s because "+ "root-run user namespaces cannot map the sandbox uid onto the "+ "bind-mounted backing directory owner",+ path,+ oct(mode),+ oct(fallback_mode),+ )+ os.chmod(path, fallback_mode)+@staticmethoddef _ensure_writable_when_chown_unavailable(path: Path, owner_applied: bool) -> None:if owner_applied:@@ -186,6 +225,8 @@ class ProcessRuntime(RuntimeAdapter):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)+ 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),@@ -251,9 +292,8 @@ class ProcessRuntime(RuntimeAdapter):netns_name = self._ensure_named_netns(sandbox_id, policy)directory_binds = self._ensure_policy_directories(sandbox_id, policy)- # Build supervisor commandsupervisor_cmd = self._wrap_command_in_namespace(- self._build_supervisor_command(policy_path, command),+ self._build_supervisor_command(policy_path, SANDBOX_DAEMON_COMMAND),netns_name,)@@ -266,7 +306,12 @@ class ProcessRuntime(RuntimeAdapter):log_file = self._log_dir / f"{sandbox_id}.log"- logger.info("Spawning supervisor for %s: %s", sandbox_id, supervisor_cmd)+ logger.info(+ "Spawning sandbox daemon for %s; ignoring requested command: %s",+ sandbox_id,+ command,+ )+ logger.info("Sandbox daemon supervisor command for %s: %s", sandbox_id, supervisor_cmd)try:with open(log_file, "w", encoding="utf-8") as log_fd:@@ -289,6 +334,23 @@ class ProcessRuntime(RuntimeAdapter):self._processes[sandbox_id] = procself._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)return proc.pid@@ -328,6 +390,19 @@ class ProcessRuntime(RuntimeAdapter):return Falsereturn proc.poll() is None+ def get_exit_diagnostics(self, sandbox_id: str) -> str:+ """Return diagnostics for a sandbox whose lifecycle process is not running."""+ proc = self._processes.get(sandbox_id)+ returncode = None if proc is None else proc.poll()+ log_file = self._log_dir / f"{sandbox_id}.log"+ log_tail = ""+ if log_file.exists():+ log_tail = log_file.read_text(encoding="utf-8", errors="replace")[-4000:]+ return (+ f"Sandbox lifecycle process is not running; "+ f"returncode={returncode}; log={log_file}; log_tail={log_tail}"+ )+async def exec(self,sandbox_id: str,diff --git a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.pyindex 6f1eb656c0..2f1ad636d1 100644--- a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py+++ b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Sandbox lifecycle manager.Coordinates runtime adapters, policy engine, and audit logger to manage@@ -174,14 +175,13 @@ class SandboxManager:"""Create a new sandbox."""async with self._lock:sandbox_id = str(uuid.uuid4())[:12]- effective_command = list(command or [])policy = self._resolve_effective_policy(policy_data, policy_mode)self.policy_engine.validate_policy(policy)# Create sandbox refref = SandboxRef(id=sandbox_id,phase=SandboxPhase.PROVISIONING,- command=effective_command,+ command=[],workdir=spec.workdir,env=dict(spec.env),)@@ -222,6 +222,9 @@ class SandboxManager:if ref.phase == SandboxPhase.READY:if not await self.runtime.is_running(sandbox_id):ref.phase = SandboxPhase.STOPPED+ diagnostics = getattr(self.runtime, "get_exit_diagnostics", None)+ if diagnostics is not None:+ ref.error_message = diagnostics(sandbox_id)self._save_state(ref)return ref@@ -346,19 +349,41 @@ class SandboxManager:)encoded_content = base64.b64encode(content)+ upload_script = textwrap.dedent(+ """+ set -euo pipefail+ target="$1"+ parent=$(/usr/bin/dirname -- "$target") || {+ status=$?+ printf "dirname failed for upload target '%s' (exit %s)\\n" "$target" "$status" >&2+ exit "$status"+ }+ /usr/bin/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)+ printf "mkdir failed: parent='%s' target='%s'\\n" "$parent" "$target" >&2+ printf "sandbox identity: uid=%s gid=%s exit=%s\\n" "$uid" "$gid" "$status" >&2+ if [ -n "$parent_parent" ]; then+ /usr/bin/ls -ld -- "$parent_parent" "$parent" >&2 || true+ fi+ exit "$status"+ }+ /usr/bin/base64 -d > "$target" || {+ status=$?+ printf "base64 decode/write failed: target='%s' exit=%s\\n" "$target" "$status" >&2+ exit "$status"+ }+ """+ ).strip()result = await self.exec_in_sandbox(sandbox_id,SandboxExecRequest(command=["/usr/bin/bash","-c",- (- "set -euo pipefail; "- 'target="$1"; '- 'parent=$(/usr/bin/dirname -- "$target"); '- '/usr/bin/mkdir -p -- "$parent"; '- '/usr/bin/base64 -d > "$target"'- ),+ upload_script,"jiuwenbox-upload",sandbox_path,],@@ -366,8 +391,11 @@ class SandboxManager:),)if result.exit_code != 0:+ detail = (result.stderr or result.stdout).strip()+ if not detail:+ detail = f"command exited with code {result.exit_code} without stderr/stdout"raise SandboxStateError(- f"Failed to upload file to '{sandbox_path}': {result.stderr or result.stdout}"+ f"Failed to upload file to '{sandbox_path}': {detail}")async def download_file_from_sandbox(diff --git a/jiuwenbox/src/jiuwenbox/supervisor/__init__.py b/jiuwenbox/src/jiuwenbox/supervisor/__init__.pyindex e69de29bb2..fef222497f 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/__init__.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/__init__.py@@ -0,0 +1 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.\ No newline at end of filediff --git a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.pyindex 0c35f94131..105750f56c 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Bubblewrap (bwrap) sandbox wrapper.Translates a SecurityPolicy into bwrap command-line arguments and manages@@ -44,6 +45,11 @@ def _path_depth(path: str) -> int:return len([part for part in path.split("/") if part])+def _append_unique(paths: list[str], path: str) -> None:+ if path not in paths:+ paths.append(path)++def _bind_parent_dirs(binds: list[tuple[str, str]], existing_dirs: set[str]) -> list[str]:"""Return parent directories bwrap must create before nested bind targets."""result: list[str] = []@@ -86,8 +92,10 @@ class BwrapConfig:rootfs: str | None = Nonero_binds: list[tuple[str, str]] = field(default_factory=list)rw_binds: list[tuple[str, str]] = field(default_factory=list)+ device_binds: list[tuple[str, str]] = field(default_factory=list)dir_mounts: list[tuple[str, str | None]] = field(default_factory=list)tmpfs_mounts: list[str] = field(default_factory=list)+ remount_ro: list[str] = field(default_factory=list)dev_path: str = "/dev"proc_path: str = "/proc"@@ -122,13 +130,20 @@ class BwrapConfig:@staticmethoddef _apply_filesystem(cfg: BwrapConfig, fs: FilesystemPolicy) -> None:- # read_only/read_write are in-sandbox access rules enforced by- # Landlock. Only bind_mounts expose host paths in the sandbox.+ read_write_paths = set(fs.read_write)+ for path in fs.read_only:+ if path not in read_write_paths and path not in cfg.remount_ro:+ cfg.remount_ro.append(path)++ # read_only/read_write are also enforced by Landlock when available.+ # Only bind_mounts expose host paths in the sandbox.for mount in fs.bind_mounts:if mount.mode == "ro":cfg.ro_binds.append((mount.host_path, mount.sandbox_path))else:cfg.rw_binds.append((mount.host_path, mount.sandbox_path))+ for device in fs.device:+ cfg.device_binds.append((device.host_path, device.sandbox_path))@staticmethoddef _apply_process(cfg: BwrapConfig, proc: ProcessPolicy) -> None:@@ -229,19 +244,55 @@ class BwrapConfig:args.extend(["--proc", self.proc_path])args.extend(["--dev", self.dev_path])- explicit_dir_paths = {path for path, _ in self.dir_mounts}- auto_dir_mounts = [- (path, None)- for path in _bind_parent_dirs([*ro_binds, *rw_binds], explicit_dir_paths)- ]+ explicit_dir_paths = {+ self.proc_path,+ self.dev_path,+ *[path for path, _ in self.dir_mounts],+ }+ bind_targets = [*ro_binds, *rw_binds, *self.device_binds]+ auto_dir_paths = _bind_parent_dirs(bind_targets, explicit_dir_paths)+ auto_dir_mounts = [(path, None) for path in auto_dir_paths]dir_mounts = [*self.dir_mounts, *auto_dir_mounts]dir_mounts.sort(key=lambda item: _path_depth(item[0]))+ remount_ro_paths = set(self.remount_ro)+ read_only_dir_paths = {path for path, _ in dir_mounts if path in remount_ro_paths}+ writable_dir_mounts = [+ (path, permissions)+ for path, permissions in dir_mounts+ if path not in read_only_dir_paths+ ]+ tmpfs_mounts: list[str] = []+ for path in self.tmpfs_mounts:+ _append_unique(tmpfs_mounts, path)+ for path in sorted(read_only_dir_paths, key=_path_depth):+ _append_unique(tmpfs_mounts, path)+ created_paths = {+ "/",+ self.proc_path,+ self.dev_path,+ *[dst for _, dst in root_ro_binds],+ *[dst for _, dst in root_rw_binds],+ *[dst for _, dst in ro_binds],+ *[dst for _, dst in rw_binds],+ *[dst for _, dst in self.device_binds],+ *[path for path, _ in writable_dir_mounts],+ *tmpfs_mounts,+ }# create directories before binding over them- for path, permissions in dir_mounts:- if permissions:- args.extend(["--perms", permissions])- args.extend(["--dir", path])+ creation_ops = [+ ("dir", path, permissions)+ for path, permissions in writable_dir_mounts+ ]+ creation_ops.extend(("tmpfs", path, None) for path in tmpfs_mounts)+ creation_ops.sort(key=lambda item: _path_depth(item[1]))+ for op, path, permissions in creation_ops:+ if op == "dir":+ if permissions:+ args.extend(["--perms", permissions])+ args.extend(["--dir", path])+ else:+ args.extend(["--tmpfs", path])# read-only bindsfor src, dst in ro_binds:@@ -251,9 +302,13 @@ class BwrapConfig:for src, dst in rw_binds:args.extend(["--bind", src, dst])- # tmpfs mounts- for path in self.tmpfs_mounts:- args.extend(["--tmpfs", path])+ for src, dst in self.device_binds:+ args.extend(["--dev-bind", src, dst])++ for path in sorted(self.remount_ro, key=_path_depth, reverse=True):+ if path not in created_paths:+ continue+ args.extend(["--remount-ro", path])if self.seccomp_fd is not None:args.extend(["--seccomp", str(self.seccomp_fd)])diff --git a/jiuwenbox/src/jiuwenbox/supervisor/landlock.py b/jiuwenbox/src/jiuwenbox/supervisor/landlock.pyindex 60f146429c..433acd92d2 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/landlock.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/landlock.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Landlock policy helpers shared by the supervisor and launcher."""from __future__ import annotations@@ -44,6 +45,8 @@ def encode_landlock_payload(policy: SecurityPolicy) -> str:read_only.append(mount.sandbox_path)else:read_write.append(mount.sandbox_path)+ for device in policy.filesystem_policy.device:+ read_write.append(device.sandbox_path)# These pseudo-filesystems are created by bwrap and are needed by common runtimes.read_only.append("/proc")read_write.append("/dev")diff --git a/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py b/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.pyindex 6f3475f349..48472cccaa 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""In-sandbox Landlock launcher.This module is executed inside bubblewrap after mounts/namespaces are in place.diff --git a/jiuwenbox/src/jiuwenbox/supervisor/main.py b/jiuwenbox/src/jiuwenbox/supervisor/main.pyindex 1284a88f7c..165979f711 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/main.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/main.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""box-supervisor main entry point."""from __future__ import annotations@@ -16,6 +17,10 @@ import yamlfrom jiuwenbox.models.policy import NetworkMode, SecurityPolicyfrom jiuwenbox.supervisor.bwrap import BwrapConfig, BwrapProcessfrom jiuwenbox.supervisor.landlock import encode_landlock_payload+from jiuwenbox.supervisor.sandbox_daemon import (+ SANDBOX_DAEMON_COMMAND,+ SANDBOX_DAEMON_SANDBOX_PATH,+)from jiuwenbox.supervisor.seccomp import open_seccomp_filterlogging.basicConfig(level=logging.INFO)@@ -38,6 +43,7 @@ class Supervisor:self.env = env or {}self._bwrap: BwrapProcess | None = Noneself._seccomp_fd: int | None = None+ self._sandbox_daemon_path: Path | None = Noneself._landlock_launcher_path: Path | None = Noneself._shutting_down = False@@ -84,8 +90,23 @@ class Supervisor:for entry in json.loads(raw_binds):config.rw_binds.append((entry["host_path"], entry["sandbox_path"]))+ def _setup_sandbox_daemon_mount(self, config: BwrapConfig, temp_dir: Path) -> None:+ """Expose the internal lifecycle daemon when this supervisor is a holder."""+ if config.command != SANDBOX_DAEMON_COMMAND:+ return++ daemon_path = Path(__file__).with_name("sandbox_daemon.py")+ temp_daemon_path = temp_dir / "jiuwenbox-sandbox-daemon.py"+ temp_daemon_path.write_bytes(daemon_path.read_bytes())+ os.chmod(temp_daemon_path, 0o644)+ self._sandbox_daemon_path = temp_daemon_path+ config.ro_binds.append((str(self._sandbox_daemon_path), SANDBOX_DAEMON_SANDBOX_PATH))+def _setup_landlock_launcher(self, config: BwrapConfig, temp_dir: Path) -> None:"""Run a fixed in-sandbox launcher that applies Landlock before exec."""+ if config.command == SANDBOX_DAEMON_COMMAND:+ return+if self.policy.landlock.compatibility == "disabled":return@@ -117,6 +138,7 @@ class Supervisor:config.workdir = self.workdirself._setup_network_namespace(config)self._setup_policy_directory_mounts(config)+ self._setup_sandbox_daemon_mount(config, Path(temp_dir))self._setup_landlock_launcher(config, Path(temp_dir))# 2. Setup seccomp@@ -157,6 +179,8 @@ class Supervisor:async def _cleanup(self) -> None:"""Clean up resources."""self._close_seccomp_fd()+ if self._sandbox_daemon_path and self._sandbox_daemon_path.exists():+ self._sandbox_daemon_path.unlink(missing_ok=True)if self._landlock_launcher_path and self._landlock_launcher_path.exists():self._landlock_launcher_path.unlink(missing_ok=True)diff --git a/jiuwenbox/src/jiuwenbox/supervisor/network.py b/jiuwenbox/src/jiuwenbox/supervisor/network.pyindex 20ba1b3576..282535f8ff 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/network.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/network.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Network isolation via iptables rules inside an unshared network namespace.This module configures iptables rules within a sandbox network namespace.@@ -7,9 +8,11 @@ from __future__ import annotationsimport ipaddressimport logging+import shutilimport socketimport subprocessfrom dataclasses import dataclass, field+from functools import lru_cachefrom jiuwenbox.models.policy import NetworkPolicy, NetworkMode, NetworkRulePolicy@@ -19,6 +22,25 @@ 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"+++class NetworkSetupError(RuntimeError):+ """Raised when required network isolation setup fails."""+++def _format_command_error(cmd: list[str], result: subprocess.CompletedProcess) -> str:+ details = [+ f"Command '{' '.join(cmd)}' failed with exit code {result.returncode}.",+ ]+ if result.stderr:+ details.append(f"stderr: {result.stderr.strip()}")+ if result.stdout:+ details.append(f"stdout: {result.stdout.strip()}")+ return " ".join(details)@dataclass@@ -91,19 +113,88 @@ def build_network_rules(policy: NetworkRulePolicy) -> ResolvedNetworkRules:return rules-def _run_iptables(+def _existing_binaries(paths: tuple[str, ...]) -> list[str]:+ result: list[str] = []+ for path in paths:+ if path in result:+ continue+ if path.startswith("/") and not shutil.which(path):+ continue+ result.append(path)+ return result+++def _iptables_candidates(ip_version: int) -> list[str]:+ if ip_version == 6:+ return _existing_binaries((+ IP6TABLES_BINARY,+ IP6TABLES_NFT_BINARY,+ IP6TABLES_LEGACY_BINARY,+ ))+ return _existing_binaries((+ IPTABLES_BINARY,+ IPTABLES_NFT_BINARY,+ IPTABLES_LEGACY_BINARY,+ ))+++def _run_iptables_binary(+ binary: str,args: list[str],+ *,check: bool = True,namespace: str | None = None,- ip_version: int = 4,) -> subprocess.CompletedProcess:- """Run an iptables/ip6tables command."""- binary = IP6TABLES_BINARY if ip_version == 6 else IPTABLES_BINARYcmd = [binary] + argsif namespace:cmd = [IP_BINARY, "netns", "exec", namespace, *cmd]logger.debug("%s: %s", binary, " ".join(cmd))- return subprocess.run(cmd, capture_output=True, text=True, check=check)+ result = subprocess.run(cmd, capture_output=True, text=True, check=False)+ if check and result.returncode != 0:+ raise NetworkSetupError(_format_command_error(cmd, result))+ return result+++@lru_cache(maxsize=128)+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,+ while older or constrained kernels only support legacy xtables. Probe both+ and keep the sandbox creation failure explicit if neither backend works.+ """+ failures: list[str] = []+ for binary in _iptables_candidates(ip_version):+ result = _run_iptables_binary(+ binary,+ ["-L", "OUTPUT", "-n"],+ check=False,+ namespace=namespace,+ )+ if result.returncode == 0:+ return binary+ failures.append(_format_command_error(+ [IP_BINARY, "netns", "exec", namespace, binary, "-L", "OUTPUT", "-n"]+ if namespace+ else [binary, "-L", "OUTPUT", "-n"],+ result,+ ))++ family = "IPv6" if ip_version == 6 else "IPv4"+ target = f" in netns {namespace}" if namespace else ""+ detail = " ".join(failures) if failures else "No iptables binary found."+ raise NetworkSetupError(f"No working {family} iptables backend{target}. {detail}")+++def _run_iptables(+ args: list[str],+ check: bool = True,+ namespace: str | None = None,+ ip_version: int = 4,+) -> subprocess.CompletedProcess:+ """Run an iptables/ip6tables command."""+ binary = _select_iptables_binary(ip_version, namespace)+ return _run_iptables_binary(binary, args, check=check, namespace=namespace)def _ip_version(value: str) -> int:@@ -118,11 +209,15 @@ def _run_iptables_for_ip(namespace: str | None = None,) -> subprocess.CompletedProcess:"""Run a firewall rule in the table matching the IP/CIDR version."""+ ip_version = _ip_version(ip_value)+ if ip_version == 6 and not _ip6tables_available(namespace):+ return subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr="")+return _run_iptables(args,check=check,namespace=namespace,- ip_version=_ip_version(ip_value),+ ip_version=ip_version,)@@ -133,7 +228,31 @@ def _run_iptables_both() -> None:"""Run a protocol-agnostic firewall rule for both IPv4 and IPv6."""_run_iptables(args, check=check, namespace=namespace, ip_version=4)- _run_iptables(args, check=check, namespace=namespace, ip_version=6)+ if _ip6tables_available(namespace):+ _run_iptables(args, check=check, namespace=namespace, ip_version=6)+++@lru_cache(maxsize=128)+def _ip6tables_available(namespace: str | None = None) -> bool:+ """Return whether ip6tables can manage rules in the target namespace."""+ try:+ result = _run_iptables(+ ["-L", "OUTPUT", "-n"],+ check=False,+ namespace=namespace,+ ip_version=6,+ )+ except (OSError, NetworkSetupError) as exc:+ logger.warning("Skipping IPv6 firewall rules because ip6tables is unavailable: %s", exc)+ return False++ if result.returncode == 0:+ return True++ target = f" in netns {namespace}" if namespace else ""+ stderr = result.stderr.strip() or result.stdout.strip() or f"exit code {result.returncode}"+ logger.warning("Skipping IPv6 firewall rules%s because ip6tables is unavailable: %s", target, stderr)+ return Falsedef _run_ip(diff --git a/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py b/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.pynew file mode 100644index 0000000000..26d49a7433--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py@@ -0,0 +1,29 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Long-running in-sandbox daemon used to hold a sandbox lifecycle open."""++from __future__ import annotations++import signal+import threading++SANDBOX_DAEMON_SANDBOX_PATH = "/jiuwenbox-sandbox-daemon.py"+SANDBOX_DAEMON_COMMAND = ["/usr/bin/python3", SANDBOX_DAEMON_SANDBOX_PATH]++_SHUTDOWN_EVENT = threading.Event()+++def _handle_shutdown(_signum: int, _frame: object) -> None:+ _SHUTDOWN_EVENT.set()+++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)++ _SHUTDOWN_EVENT.wait()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py b/jiuwenbox/src/jiuwenbox/supervisor/seccomp.pyindex 084cb8295a..b788cd4cbe 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/seccomp.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Seccomp BPF filter generation for sandbox syscall restriction.Generates binary seccomp-bpf programs that can be loaded via bwrap --seccomp.@@ -8,6 +9,7 @@ from __future__ import annotationsimport loggingimport os+import platformimport structfrom pathlib import Path@@ -37,44 +39,84 @@ ERRNO_ENOSYS = 38AUDIT_ARCH_X86_64 = 0xC000_003EAUDIT_ARCH_AARCH64 = 0xC000_00B7+SUPPORTED_AUDIT_ARCHES = {+ "amd64": AUDIT_ARCH_X86_64,+ "x86_64": AUDIT_ARCH_X86_64,+ "aarch64": AUDIT_ARCH_AARCH64,+ "arm64": AUDIT_ARCH_AARCH64,+}++ARCH_ALIASES = {+ "amd64": ("x86_64", "amd64"),+ "x86_64": ("x86_64", "amd64"),+ "aarch64": ("arm64", "aarch64"),+ "arm64": ("arm64", "aarch64"),+}+# offsetof(struct seccomp_data, nr)SECCOMP_DATA_NR_OFFSET = 0# offsetof(struct seccomp_data, arch)SECCOMP_DATA_ARCH_OFFSET = 4-def _get_syscall_numbers() -> dict[str, int]:- """Load the syscall number table for the current architecture.-- Falls back to a built-in x86_64 subset if /usr/include headers are absent.- """- table: dict[str, int] = {}+def _machine() -> str:+ """Return the normalized machine name used for syscall/seccomp tables."""+ return platform.machine().lower()- # Try to parse from unistd_64.h (common on x86_64 Linux)- for header in [- Path("/usr/include/asm/unistd_64.h"),- Path("/usr/include/x86_64-linux-gnu/asm/unistd_64.h"),- Path("/usr/include/asm-generic/unistd.h"),- ]:- if header.exists():- try:- for line in header.read_text().splitlines():- line = line.strip()- if line.startswith("#define __NR_"):- parts = line.split()- if len(parts) >= 3:- name = parts[1].removeprefix("__NR_")- try:- table[name] = int(parts[2])- except ValueError:- continue- if table:- return table- except OSError:- continue- # Fallback: x86_64 subset covering the syscalls we care about- table = {+def _audit_arch() -> int:+ """Return the Linux audit architecture constant for this process."""+ machine = _machine()+ try:+ return SUPPORTED_AUDIT_ARCHES[machine]+ except KeyError as exc:+ raise RuntimeError(f"Unsupported seccomp architecture: {machine}") from exc+++def _arch_aliases() -> tuple[str, ...]:+ """Return policy key aliases for the current architecture."""+ return ARCH_ALIASES.get(_machine(), (_machine(),))+++def _fallback_syscall_numbers() -> dict[str, int]:+ """Return a small syscall table for the current architecture."""+ if _audit_arch() == AUDIT_ARCH_AARCH64:+ return {+ "lookup_dcookie": 18,+ "umount2": 39,+ "mount": 40,+ "pivot_root": 41,+ "nfsservctl": 42,+ "acct": 89,+ "exit": 93,+ "unshare": 97,+ "kexec_load": 104,+ "init_module": 105,+ "delete_module": 106,+ "ptrace": 117,+ "reboot": 142,+ "getpid": 172,+ "getppid": 173,+ "add_key": 217,+ "request_key": 218,+ "keyctl": 219,+ "swapon": 224,+ "swapoff": 225,+ "perf_event_open": 241,+ "name_to_handle_at": 264,+ "open_by_handle_at": 265,+ "setns": 268,+ "finit_module": 273,+ "bpf": 280,+ "userfaultfd": 282,+ "kexec_file_load": 294,+ "io_uring_setup": 425,+ "io_uring_enter": 426,+ "io_uring_register": 427,+ "clone3": 435,+ }++ return {"read": 0, "write": 1, "open": 2, "close": 3, "stat": 4,"fstat": 5, "lstat": 6, "poll": 7, "lseek": 8, "mmap": 9,"mprotect": 10, "munmap": 11, "brk": 12, "ioctl": 16,@@ -99,7 +141,59 @@ def _get_syscall_numbers() -> dict[str, int]:"init_module": 175, "finit_module": 313, "delete_module": 176,"acct": 163, "nfsservctl": 180, "lookup_dcookie": 212,}- return table+++def _get_syscall_numbers() -> dict[str, int]:+ """Load the syscall number table for the current architecture.++ Falls back to a small architecture-specific subset if /usr/include headers+ are absent.+ """+ table: dict[str, int] = {}++ machine = _machine()+ if machine in {"aarch64", "arm64"}:+ headers = [+ Path("/usr/include/asm/unistd.h"),+ Path("/usr/include/aarch64-linux-gnu/asm/unistd.h"),+ Path("/usr/include/asm-generic/unistd.h"),+ ]+ else:+ headers = [+ Path("/usr/include/asm/unistd_64.h"),+ Path("/usr/include/x86_64-linux-gnu/asm/unistd_64.h"),+ Path("/usr/include/asm-generic/unistd.h"),+ ]++ for header in headers:+ if header.exists():+ try:+ for line in header.read_text().splitlines():+ line = line.strip()+ if line.startswith("#define __NR_"):+ parts = line.split()+ if len(parts) >= 3:+ name = parts[1].removeprefix("__NR_")+ try:+ table[name] = int(parts[2])+ except ValueError:+ continue+ if table:+ return table+ except OSError:+ continue++ return _fallback_syscall_numbers()+++def _blocked_syscalls_for_current_arch(policy: SyscallPolicy) -> list[str]:+ """Return the syscall block list for the current architecture."""+ for key in _arch_aliases():+ arch_policy = getattr(policy, key, None)+ if arch_policy is not None:+ return list(dict.fromkeys(arch_policy.blocked))++ return []def _bpf_stmt(code: int, k: int) -> bytes:@@ -117,7 +211,7 @@ def build_seccomp_filter(policy: SyscallPolicy) -> bytes:Returns raw bytes suitable for writing to a memfd and passing tobwrap via --seccomp <fd>."""- blocked_names = set(policy.blocked)+ blocked_names = set(_blocked_syscalls_for_current_arch(policy))syscall_table = _get_syscall_numbers()blocked_nrs: list[int] = []@@ -135,7 +229,7 @@ def _assemble_bpf(blocked_nrs: list[int]) -> bytes:"""Assemble a BPF program that blocks the given syscall numbers.Structure:- 1. Validate arch == x86_64+ 1. Validate arch == current process architecture2. Load syscall number3. For each blocked nr: if match -> return configured errno4. Default: ALLOW@@ -154,8 +248,8 @@ def _assemble_bpf(blocked_nrs: list[int]) -> bytes:# Load archprog += _bpf_stmt(BPF_LD | BPF_W | BPF_ABS, SECCOMP_DATA_ARCH_OFFSET)- # If arch != x86_64 -> kill (jump over next instruction if equal)- prog += _bpf_jump(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 1, 0)+ # If arch does not match, kill; jump over the kill instruction when it does.+ prog += _bpf_jump(BPF_JMP | BPF_JEQ | BPF_K, _audit_arch(), 1, 0)prog += _bpf_stmt(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS)# Load syscall numberdiff --git a/jiuwenbox/tests/__init__.py b/jiuwenbox/tests/__init__.pyindex e69de29bb2..fef222497f 100644--- a/jiuwenbox/tests/__init__.py+++ b/jiuwenbox/tests/__init__.py@@ -0,0 +1 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.\ No newline at end of filediff --git a/jiuwenbox/tests/conftest.py b/jiuwenbox/tests/conftest.pyindex 6632be1ec0..315fd1d78d 100644--- a/jiuwenbox/tests/conftest.py+++ b/jiuwenbox/tests/conftest.py@@ -1,3 +1,4 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Shared test fixtures."""from __future__ import annotationsdiff --git a/jiuwenbox/tests/integration/__init__.py b/jiuwenbox/tests/integration/__init__.pyindex e69de29bb2..fef222497f 100644--- a/jiuwenbox/tests/integration/__init__.py+++ b/jiuwenbox/tests/integration/__init__.py@@ -0,0 +1 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.\ No newline at end of filediff --git a/jiuwenbox/tests/integration/test_server_api_default.py b/jiuwenbox/tests/integration/test_server_api_default.pyindex 0af6812ab2..f8ab7eaa60 100644--- a/jiuwenbox/tests/integration/test_server_api_default.py+++ b/jiuwenbox/tests/integration/test_server_api_default.py@@ -1,1708 +1,1965 @@-"""Integration tests for box-server API endpoints."""--import copy-import logging-import textwrap--import httpx-import pytest--from jiuwenbox.models.policy import SecurityPolicy-from 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/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__)---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 _has_mount(args: list[str], flag: str, source: str, target: str) -> bool:- for index, value in enumerate(args[:-2]):- if value == flag and args[index + 1] == source and args[index + 2] == target:- return True- return False---def _has_arg_pair(args: list[str], flag: str, value: str) -> bool:- for index, item in enumerate(args[:-1]):- if item == flag and args[index + 1] == value:- return True- return False---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 "resources" not in data- assert data["filesystem_policy"]["directories"] == [{'path': '/home', 'permissions': '0755'},- {'path': '/tmp', 'permissions': '1777'}]- assert data["filesystem_policy"]["read_only"] == [- "/",- "/bin",- "/sbin",- "/usr",- "/lib",- "/lib64",- "/etc",- "/opt",- ]- assert data["filesystem_policy"]["read_write"] == ["/home", "/tmp"]- assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTS- assert data["process"]["run_as_user"] == "sandbox"- assert data["process"]["run_as_group"] == "sandbox"- assert data["namespace"] == {- "user": True,- "pid": True,- "ipc": True,- "cgroup": True,- "uts": True,- }- assert data["capabilities"] == {"add": [], "drop": []}- assert data["landlock"]["compatibility"] == "best_effort"- assert data["network"]["mode"] == "host"- 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 "mount" in data["syscall"]["blocked"]- assert "kexec_file_load" in data["syscall"]["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": {- "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["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"] == ["/home", "/tmp", "/var/tmp"]- assert data["filesystem_policy"]["directories"] == [{'path': '/home', 'permissions': '0755'},- {'path': '/tmp', 'permissions': '1777'},- {"path": "/tmp/appended-dir", "permissions": "0700"}]- assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTS + [{- "host_path": "/tmp",- "sandbox_path": "/tmp",- "mode": "rw",- }]- assert data["process"]["run_as_user"] == "root"- assert data["process"]["run_as_group"] == "root"- assert data["namespace"] == {- "user": True,- "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"]["blocked"]- assert "mount" in data["syscall"]["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": {- "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["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"]["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"]["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": "/sandbox/manual",- "sandbox_path": "/tmp/manual",- "mode": "rw",- }],- },- "network": {- "mode": "host",- },- },- })-- assert resp.status_code == 400- assert "/sandbox" 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": ["/sandbox/manual"],- },- "network": {- "mode": "host",- },- },- })-- assert resp.status_code == 400- assert "/sandbox" 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": "/sandbox/manual",- "permissions": "0700",- }],- },- "network": {- "mode": "host",- },- },- })-- assert resp.status_code == 400- assert "/sandbox" 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"},- },- },- )-- upload = client.post(- f"/api/v1/sandboxes/{sandbox['id']}/upload",- params={"sandbox_path": "/tmp/policy-ok.txt"},- 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": "/tmp/policy-ok.txt"},- )- 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",- },- },- )-- setup = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": [- "/usr/bin/python3",- "-c",- (- "from pathlib import Path; "- "Path('/tmp/list-api/sub').mkdir(parents=True, exist_ok=True); "- "Path('/tmp/list-api/a.txt').write_text('a'); "- "Path('/tmp/list-api/sub/b.log').write_text('b')"- ),- ],- "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": "/tmp/list-api", "recursive": True},- )- assert response.status_code == 200- items = response.json()["items"]- paths = {item["path"] for item in items}- assert "/tmp/list-api/a.txt" in paths- assert "/tmp/list-api/sub" in paths- assert "/tmp/list-api/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": "/tmp/list-api",- "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",- },- },- )-- setup = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": [- "/usr/bin/python3",- "-c",- (- "from pathlib import Path; "- "Path('/tmp/search-api').mkdir(parents=True, exist_ok=True); "- "Path('/tmp/search-api/keep.py').write_text('print(1)'); "- "Path('/tmp/search-api/drop.py').write_text('print(2)'); "- "Path('/tmp/search-api/readme.md').write_text('# hi')"- ),- ],- "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", "/tmp/search-api"),- ("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": {- "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": {- "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["error_message"].lower()-- @staticmethod- def test_landlock_rules_allow_policy_paths_and_deny_other_mounted_paths(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="landlock-rules",- policy={- "name": "landlock-rules-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "landlock": {- "compatibility": "hard_requirement",- },- "network": {- "mode": "host",- },- },- )-- script = textwrap.dedent(- """- from pathlib import Path- import sys-- allowed = Path("/tmp/landlock-allowed.txt")- 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],- "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_default_policy_allows_network_https(client):- response = client.post("/api/v1/sandboxes", json={- "command": LONG_RUNNING_COMMAND,- })- assert response.status_code == 201, response.text- sandbox = response.json()- assert sandbox["phase"] == "ready", sandbox-- 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, "https://www.huawei.com/"],- "timeout_seconds": 15,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0, data- 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,- })- assert response.status_code == 201, response.text- sandbox = response.json()- assert sandbox["phase"] == "ready", sandbox-- script = textwrap.dedent(- """- from pathlib import Path- import sys-- sensitive_paths = [- "/etc/passwd",- "/etc/shadow",- "/etc/group",- "/etc/gshadow",- ]-- for sensitive_path in sensitive_paths:- try:- content = Path(sensitive_path).read_text()- except (FileNotFoundError, PermissionError):- print(f"denied:{sensitive_path}")- continue-- print(f"leaked:{sensitive_path}:{content[:80]!r}")- sys.exit(1)- """- ).strip()- response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={- "command": ["/usr/bin/python3", "-c", script],- "timeout_seconds": 5,- })- assert response.status_code == 200- data = response.json()- assert data["exit_code"] == 0, data- assert "leaked:" not in data["stdout"]- assert "root:" not in data["stdout"]- assert data["stdout"].splitlines() == [- "denied:/etc/passwd",- "denied:/etc/shadow",- "denied:/etc/group",- "denied:/etc/gshadow",- ]-- @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 TestBwrapFilesystem:- @staticmethod- def test_read_rules_do_not_mount_host_paths():- policy = SecurityPolicy.model_validate({- "filesystem_policy": {- "read_only": ["/host-read-only"],- "read_write": ["/host-read-write"],- "bind_mounts": [- {- "host_path": "/host-source-ro",- "sandbox_path": "/sandbox-target-ro",- "mode": "ro",- },- {- "host_path": "/host-source-rw",- "sandbox_path": "/sandbox-target-rw",- "mode": "rw",- },- ],- },- })-- args = BwrapConfig.from_policy(policy, ["/usr/bin/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")- assert _has_mount(args, "--ro-bind", "/host-source-ro", "/sandbox-target-ro")- assert _has_mount(args, "--bind", "/host-source-rw", "/sandbox-target-rw")-- @staticmethod- def test_nested_bind_targets_create_parent_directories():- policy = SecurityPolicy.model_validate({- "filesystem_policy": {- "bind_mounts": [{- "host_path": "/etc/resolv.conf",- "sandbox_path": "/etc/resolv.conf",- "mode": "ro",- }],- },- })-- args = BwrapConfig.from_policy(policy, ["/usr/bin/true"]).to_args()-- assert _has_arg_pair(args, "--dir", "/etc")- assert _has_mount(args, "--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf")---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+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Integration tests for box-server API endpoints."""++import copy+import logging+import textwrap++import httpx+import pytest++from jiuwenbox.models.policy import SecurityPolicy+from jiuwenbox.supervisor import network as network_module+from 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"}+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 _has_mount(args: list[str], flag: str, source: str, target: str) -> bool:+ for index, value in enumerate(args[:-2]):+ if value == flag and args[index + 1] == source and args[index + 2] == target:+ return True+ return False+++def _has_arg_pair(args: list[str], flag: str, value: str) -> bool:+ for index, item in enumerate(args[:-1]):+ if item == flag and args[index + 1] == value:+ return True+ return False+++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["command"] == []+ 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_sandbox_process_cannot_target_sandbox_daemon(client):+ create_resp = client.post("/api/v1/sandboxes", json={+ "command": LONG_RUNNING_COMMAND,+ })+ assert create_resp.status_code == 201+ sandbox = create_resp.json()+ assert sandbox["phase"] == "ready", sandbox+ sandbox_id = sandbox["id"]++ kill_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={+ "command": [+ "/usr/bin/python3",+ "-c",+ textwrap.dedent(+ """+ import os+ from pathlib import Path+ import sys++ 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+ try:+ cmdline = cmdline_path.read_bytes().replace(b"\\0", b" ").decode(+ errors="replace",+ )+ except (FileNotFoundError, PermissionError, ProcessLookupError):+ 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")+ """+ ).strip(),+ ],+ "timeout_seconds": 5,+ })+ assert kill_resp.status_code == 200+ kill_data = kill_resp.json()+ assert kill_data["exit_code"] == 0, kill_data+ assert kill_data["stdout"].strip() == "daemon-hidden"++ status_resp = client.get(f"/api/v1/sandboxes/{sandbox_id}")+ assert status_resp.status_code == 200+ assert status_resp.json()["phase"] == "ready", status_resp.json()++ exec_resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={+ "command": ["/usr/bin/echo", "daemon-alive"],+ "timeout_seconds": 5,+ })+ assert exec_resp.status_code == 200+ exec_data = exec_resp.json()+ assert exec_data["exit_code"] == 0, exec_data+ assert exec_data["stdout"].strip() == "daemon-alive"++ @staticmethod+ def test_sandbox_process_cannot_see_sandbox_daemon(client):+ create_resp = client.post("/api/v1/sandboxes", json={+ "command": LONG_RUNNING_COMMAND,+ })+ assert create_resp.status_code == 201+ sandbox = create_resp.json()+ assert sandbox["phase"] == "ready", sandbox+ sandbox_id = sandbox["id"]++ script = textwrap.dedent(+ """+ import os+ from pathlib import Path+ import 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:+ 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)++ print("daemon-hidden")+ """+ ).strip()+ response = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json={+ "command": ["/usr/bin/python3", "-c", script],+ "timeout_seconds": 5,+ })+ assert response.status_code == 200+ data = response.json()+ assert data["exit_code"] == 0, data+ assert data["stdout"].strip() == "daemon-hidden"++ @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 "resources" not in data+ assert data["filesystem_policy"]["directories"] == [{'path': '/home', 'permissions': '0755'},+ {'path': '/tmp', 'permissions': '1777'}]+ assert data["filesystem_policy"]["read_only"] == [+ "/",+ "/bin",+ "/sbin",+ "/usr",+ "/lib",+ "/lib64",+ "/etc",+ "/opt",+ ]+ assert data["filesystem_policy"]["read_write"] == ["/home", "/tmp"]+ assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTS+ assert data["filesystem_policy"]["device"] == DEVICE_MOUNTS+ assert data["process"]["run_as_user"] == "sandbox"+ assert data["process"]["run_as_group"] == "sandbox"+ assert data["namespace"] == {+ "user": True,+ "pid": True,+ "ipc": True,+ "cgroup": True,+ "uts": True,+ }+ assert data["capabilities"] == {"add": [], "drop": []}+ assert data["landlock"]["compatibility"] == "best_effort"+ assert data["network"]["mode"] == "host"+ 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["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"] == ["/home", "/tmp", "/var/tmp"]+ assert data["filesystem_policy"]["directories"] == [{'path': '/home', 'permissions': '0755'},+ {'path': '/tmp', 'permissions': '1777'},+ {"path": "/tmp/appended-dir", "permissions": "0700"}]+ assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTS + [{+ "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": True,+ "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["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": "/sandbox/manual",+ "sandbox_path": "/tmp/manual",+ "mode": "rw",+ }],+ },+ "network": {+ "mode": "host",+ },+ },+ })++ assert resp.status_code == 400+ assert "/sandbox" 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": "/sandbox/manual-device",+ "sandbox_path": "/dev/manual-device",+ }],+ },+ "network": {+ "mode": "host",+ },+ },+ })++ assert resp.status_code == 400+ assert "/sandbox" 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": ["/sandbox/manual"],+ },+ "network": {+ "mode": "host",+ },+ },+ })++ assert resp.status_code == 400+ assert "/sandbox" 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": "/sandbox/manual",+ "permissions": "0700",+ }],+ },+ "network": {+ "mode": "host",+ },+ },+ })++ assert resp.status_code == 400+ assert "/sandbox" 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"},+ },+ },+ )++ upload = client.post(+ f"/api/v1/sandboxes/{sandbox['id']}/upload",+ params={"sandbox_path": "/tmp/policy-ok.txt"},+ 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": "/tmp/policy-ok.txt"},+ )+ 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",+ },+ },+ )++ setup = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={+ "command": [+ "/usr/bin/python3",+ "-c",+ (+ "from pathlib import Path; "+ "Path('/tmp/list-api/sub').mkdir(parents=True, exist_ok=True); "+ "Path('/tmp/list-api/a.txt').write_text('a'); "+ "Path('/tmp/list-api/sub/b.log').write_text('b')"+ ),+ ],+ "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": "/tmp/list-api", "recursive": True},+ )+ assert response.status_code == 200+ items = response.json()["items"]+ paths = {item["path"] for item in items}+ assert "/tmp/list-api/a.txt" in paths+ assert "/tmp/list-api/sub" in paths+ assert "/tmp/list-api/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": "/tmp/list-api",+ "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",+ },+ },+ )++ setup = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={+ "command": [+ "/usr/bin/python3",+ "-c",+ (+ "from pathlib import Path; "+ "Path('/tmp/search-api').mkdir(parents=True, exist_ok=True); "+ "Path('/tmp/search-api/keep.py').write_text('print(1)'); "+ "Path('/tmp/search-api/drop.py').write_text('print(2)'); "+ "Path('/tmp/search-api/readme.md').write_text('# hi')"+ ),+ ],+ "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", "/tmp/search-api"),+ ("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++ script = textwrap.dedent(+ """+ from pathlib import Path+ import sys++ allowed = Path("/tmp/landlock-allowed.txt")+ 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],+ "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_default_policy_allows_network_https(client):+ response = client.post("/api/v1/sandboxes", json={+ "command": LONG_RUNNING_COMMAND,+ })+ assert response.status_code == 201, response.text+ sandbox = response.json()+ assert sandbox["phase"] == "ready", sandbox++ 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, "https://www.huawei.com/"],+ "timeout_seconds": 15,+ })+ assert response.status_code == 200+ data = response.json()+ assert data["exit_code"] == 0, data+ 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,+ })+ assert response.status_code == 201, response.text+ sandbox = response.json()+ assert sandbox["phase"] == "ready", sandbox++ script = textwrap.dedent(+ """+ from pathlib import Path+ import sys++ sensitive_paths = [+ "/etc/passwd",+ "/etc/shadow",+ "/etc/group",+ "/etc/gshadow",+ ]++ for sensitive_path in sensitive_paths:+ try:+ content = Path(sensitive_path).read_text()+ except (FileNotFoundError, PermissionError):+ print(f"denied:{sensitive_path}")+ continue++ print(f"leaked:{sensitive_path}:{content[:80]!r}")+ sys.exit(1)+ """+ ).strip()+ response = client.post(f"/api/v1/sandboxes/{sandbox['id']}/exec", json={+ "command": ["/usr/bin/python3", "-c", script],+ "timeout_seconds": 5,+ })+ assert response.status_code == 200+ data = response.json()+ assert data["exit_code"] == 0, data+ assert "leaked:" not in data["stdout"]+ assert "root:" not in data["stdout"]+ assert data["stdout"].splitlines() == [+ "denied:/etc/passwd",+ "denied:/etc/shadow",+ "denied:/etc/group",+ "denied:/etc/gshadow",+ ]++ @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 TestBwrapFilesystem:+ @staticmethod+ def test_read_rules_do_not_mount_host_paths():+ policy = SecurityPolicy.model_validate({+ "filesystem_policy": {+ "read_only": ["/host-read-only"],+ "read_write": ["/host-read-write"],+ "bind_mounts": [+ {+ "host_path": "/host-source-ro",+ "sandbox_path": "/sandbox-target-ro",+ "mode": "ro",+ },+ {+ "host_path": "/host-source-rw",+ "sandbox_path": "/sandbox-target-rw",+ "mode": "rw",+ },+ ],+ },+ })++ args = BwrapConfig.from_policy(policy, ["/usr/bin/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")+ assert _has_mount(args, "--ro-bind", "/host-source-ro", "/sandbox-target-ro")+ assert _has_mount(args, "--bind", "/host-source-rw", "/sandbox-target-rw")++ @staticmethod+ def test_nested_bind_targets_create_parent_directories():+ policy = SecurityPolicy.model_validate({+ "filesystem_policy": {+ "bind_mounts": [{+ "host_path": "/etc/resolv.conf",+ "sandbox_path": "/etc/resolv.conf",+ "mode": "ro",+ }],+ },+ })++ args = BwrapConfig.from_policy(policy, ["/usr/bin/true"]).to_args()++ assert _has_arg_pair(args, "--dir", "/etc")+ assert _has_mount(args, "--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf")++ @staticmethod+ def test_device_mounts_use_dev_bind_and_create_parent_directories():+ policy = SecurityPolicy.model_validate({+ "filesystem_policy": {+ "device": [{+ "host_path": "/dev/dri/renderD128",+ "sandbox_path": "/dev/dri/renderD128",+ }],+ },+ })++ args = BwrapConfig.from_policy(policy, ["/usr/bin/true"]).to_args()++ assert not _has_arg_pair(args, "--dir", "/dev")+ assert _has_arg_pair(args, "--dir", "/dev/dri")+ assert _has_mount(args, "--dev-bind", "/dev/dri/renderD128", "/dev/dri/renderD128")++ @staticmethod+ def test_read_only_parent_of_nested_bind_is_remounted_read_only():+ policy = SecurityPolicy.model_validate({+ "filesystem_policy": {+ "read_only": ["/etc"],+ "read_write": ["/tmp"],+ "bind_mounts": [{+ "host_path": "/etc/resolv.conf",+ "sandbox_path": "/etc/resolv.conf",+ "mode": "ro",+ }],+ },+ })++ args = BwrapConfig.from_policy(policy, ["/usr/bin/true"]).to_args()++ assert not _has_arg_pair(args, "--dir", "/etc")+ assert _has_arg_pair(args, "--tmpfs", "/etc")+ assert _has_mount(args, "--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf")+ assert _has_arg_pair(args, "--remount-ro", "/etc")+++class TestNetworkIptables:+ @staticmethod+ def test_iptables_backend_falls_back_to_legacy(monkeypatch):+ select_iptables_binary = getattr(network_module, "_select_iptables_binary")+ select_iptables_binary.cache_clear()++ def fake_candidates(ip_version):+ assert ip_version == 4+ return [+ network_module.IPTABLES_BINARY,+ network_module.IPTABLES_LEGACY_BINARY,+ ]++ def fake_run(binary, args, *, check=True, namespace=None):+ if binary == network_module.IPTABLES_BINARY:+ return network_module.subprocess.CompletedProcess(+ args=[binary, *args],+ returncode=3,+ stdout="",+ stderr="iptables-nft failed",+ )+ return network_module.subprocess.CompletedProcess(+ args=[binary, *args],+ returncode=0,+ stdout="",+ stderr="",+ )++ monkeypatch.setattr(network_module, "_iptables_candidates", fake_candidates)+ monkeypatch.setattr(network_module, "_run_iptables_binary", fake_run)++ assert select_iptables_binary(4, "test-netns") == (+ network_module.IPTABLES_LEGACY_BINARY+ )++ @staticmethod+ def test_iptables_backend_error_includes_stderr(monkeypatch):+ select_iptables_binary = getattr(network_module, "_select_iptables_binary")+ select_iptables_binary.cache_clear()++ def fake_candidates(ip_version):+ assert ip_version == 4+ return [network_module.IPTABLES_BINARY]++ def fake_run(binary, args, *, check=True, namespace=None):+ return network_module.subprocess.CompletedProcess(+ args=[binary, *args],+ returncode=3,+ stdout="",+ stderr="kernel/userspace mismatch",+ )++ monkeypatch.setattr(network_module, "_iptables_candidates", fake_candidates)+ monkeypatch.setattr(network_module, "_run_iptables_binary", fake_run)++ with pytest.raises(network_module.NetworkSetupError) as exc_info:+ select_iptables_binary(4, "test-netns")++ assert "kernel/userspace mismatch" in str(exc_info.value)+++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()) == 3diff --git a/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.py b/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.pyindex bbeb603dd3..0aa1f5477c 100644--- a/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.py+++ b/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.py@@ -1,1584 +1,1628 @@-"""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"},-]-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["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 "mount" in data["syscall"]["blocked"]- assert "kexec_file_load" in data["syscall"]["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": {- "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["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"]["blocked"]- assert "mount" in data["syscall"]["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": {- "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"]["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"]["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_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": {- "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": {- "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["error_message"].lower()-- @staticmethod- def test_landlock_rules_allow_policy_paths_and_deny_other_mounted_paths(- client,- create_sandbox_with_policy,- ):- sandbox = create_sandbox_with_policy(- name_prefix="landlock-rules",- policy={- "name": "landlock-rules-policy",- "filesystem_policy": {- "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],- "read_write": ["/tmp"],- },- "landlock": {- "compatibility": "hard_requirement",- },- "network": {- "mode": "host",- },- },- )- 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+# 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/scripts/test.sh b/jiuwenbox/tests/test.shsimilarity index 68%rename from jiuwenbox/scripts/test.shrename to jiuwenbox/tests/test.shindex 08252e78b8..688576550f 100755--- a/jiuwenbox/scripts/test.sh+++ b/jiuwenbox/tests/test.sh@@ -1,8 +1,9 @@#!/usr/bin/env bash+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.set -euo pipefail-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"-PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"+TEST_DIR="$(cd "$(dirname "$0")" && pwd)"+PROJECT_DIR="$(cd "$TEST_DIR/.." && pwd)"cd "$PROJECT_DIR"if [ -d ".venv" ]; then@@ -24,4 +25,4 @@ if [[ $# -gt 0 ]]; thenesacfi-python3 -m pytest "$TEST_TARGET" -v --tb=short "$@"+python3 -m pytest "$TEST_TARGET" -v --tb=short "$@"\ No newline at end of file