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: add read permission to root directory
zhaozixuan387febe7eb91
diff --git a/jiuwenbox/README.md b/jiuwenbox/README.mdindex 7aeb408678..bf9fac4069 100644--- a/jiuwenbox/README.md+++ b/jiuwenbox/README.md@@ -136,9 +136,11 @@ Important fields:- Directories created by the server and bound into each sandbox for itslifecycle.- `filesystem_policy.read_only`- - Sandbox-visible paths mounted read-only.+ - Sandbox-visible paths granted read-only access. These entries do not mount+ host paths by themselves.- `filesystem_policy.read_write`- - Sandbox-visible paths mounted read-write.+ - Sandbox-visible paths granted read-write access. Use `directories` or+ `bind_mounts` to make the paths exist inside the sandbox.- `filesystem_policy.bind_mounts`- Explicit host-to-sandbox bind mounts.@@ -157,13 +159,48 @@ filesystem_policy:- path: "/tmp"permissions: "1777"read_only:+ - "/bin"+ - "/sbin"- "/usr"- "/lib"- "/lib64"- "/etc"read_write:- "/tmp"- bind_mounts: []+ 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"process:run_as_user: sandbox@@ -268,7 +305,7 @@ Run one policy-specific integration suite:```bash./scripts/test.sh default # jiuwenbox runs the service using default-policy.yaml as the security policy.-./scripts/test.sh jiuwenclaw # jiuwenbox runs the service using jiuwenclaw-policy.yaml as the security policy.+./scripts/test.sh jiuwenclaw-tool # jiuwenbox runs the service using jiuwenclaw-tool-policy.yaml as the security policy.```## Notesdiff --git a/jiuwenbox/README_CN.md b/jiuwenbox/README_CN.mdindex 4c5781e738..32b248b264 100644--- a/jiuwenbox/README_CN.md+++ b/jiuwenbox/README_CN.md@@ -131,9 +131,10 @@ Docker 镜像默认会启动 `./scripts/server.sh`。- `filesystem_policy.directories`- 由服务端创建并在沙箱生命周期内绑定到沙箱中的目录。- `filesystem_policy.read_only`- - 在沙箱内可见并以只读方式挂载的路径。+ - 沙箱内授予只读访问权限的路径;这些条目本身不会挂载 host 路径。- `filesystem_policy.read_write`- - 在沙箱内可见并以读写方式挂载的路径。+ - 沙箱内授予读写访问权限的路径;需要通过 `directories` 或 `bind_mounts`+ 让这些路径实际存在于沙箱内。- `filesystem_policy.bind_mounts`- 显式的宿主机到沙箱路径的 bind mount 配置。@@ -151,13 +152,48 @@ filesystem_policy:- path: "/tmp"permissions: "1777"read_only:+ - "/bin"+ - "/sbin"- "/usr"- "/lib"- "/lib64"- "/etc"read_write:- "/tmp"- bind_mounts: []+ 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"process:run_as_user: sandbox@@ -262,7 +298,7 @@ curl -sS -X DELETE http://127.0.0.1:8321/api/v1/sandboxes/<sandbox-id>```bash./scripts/test.sh default # jiuwenbox 使用 default-policy.yaml 作为安全策略运行服务。-./scripts/test.sh jiuwenclaw # jiuwenbox 使用 jiuwenclaw-policy.yaml 作为安全策略运行服务。+./scripts/test.sh jiuwenclaw-tool # jiuwenbox 使用 jiuwenclaw-tool-policy.yaml 作为安全策略运行服务。```## 注意事项diff --git a/jiuwenbox/configs/default-policy.yaml b/jiuwenbox/configs/default-policy.yamlindex 9d85633d87..ccb3218770 100644--- a/jiuwenbox/configs/default-policy.yaml+++ b/jiuwenbox/configs/default-policy.yaml@@ -24,24 +24,66 @@ filesystem_policy:- path: "/tmp"permissions: "1777"- # Read-only paths. The sandbox can read these paths but should not write them.+ # Read-only paths inside the sandbox. These entries grant read permission only;+ # they do not mount host paths by themselves.read_only:+ - "/"+ - "/bin"+ - "/sbin"- "/usr"- "/lib"- "/lib64"- "/etc"- "/opt"- # Read-write paths. The sandbox can read and write these paths.+ # Read-write paths inside the sandbox. Use directories or bind_mounts to make+ # these paths exist in the sandbox.read_write:- - "/"+ - "/home"+ - "/tmp"# Extra bind mounts from host into sandbox.# Each item uses:# host_path: absolute path on the host# sandbox_path: absolute path visible inside the sandbox# mode: "ro" for read-only or "rw" for read-write- bind_mounts: []+ 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"# Process identity inside the sandbox.process:diff --git a/jiuwenbox/configs/jiuwenclaw-tool-policy.yaml b/jiuwenbox/configs/jiuwenclaw-tool-policy.yamlindex 5e5fcc36e3..69eb74b917 100644--- a/jiuwenbox/configs/jiuwenclaw-tool-policy.yaml+++ b/jiuwenbox/configs/jiuwenclaw-tool-policy.yaml@@ -9,24 +9,72 @@ sandbox_workspace: "/tmp/sandbox"# Filesystem access rules. Paths are sandbox-visible absolute paths.filesystem_policy:- # Read-only paths. The sandbox can read these paths but should not write them.+ directories:+ - path: "/tmp"+ permissions: "1777"++ # Read-only paths inside the sandbox. These entries grant read permission only;+ # they do not mount host paths by themselves.read_only:+ - "/bin"+ - "/sbin"- "/usr"- "/lib"- "/lib64"- "/etc"- "/opt"- # Read-write paths. The sandbox can read and write these paths.+ # Read-write paths inside the sandbox. Use directories or bind_mounts to make+ # these paths exist in the sandbox.read_write:- - "/"+ - "/tmp"+ - "/home/USER/.jiuwenclaw"# Extra bind mounts from host into sandbox.# Each item uses:# host_path: absolute path on the host# sandbox_path: absolute path visible inside the sandbox# mode: "ro" for read-only or "rw" for read-write- bind_mounts: [{host_path: "/home/USER/.jiuwenclaw", sandbox_path: "/home/USER/.jiuwenclaw", mode: "rw"}]+ 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"+ - host_path: "/home/USER/.jiuwenclaw"+ sandbox_path: "/home/USER/.jiuwenclaw"+ mode: "rw"# Process identity inside the sandbox.process:@@ -117,7 +165,7 @@ network:# mode:# isolated: create a dedicated network namespace and apply these rules# host: use host networking and skip namespace firewall setup- mode: isolated+ mode: host# Outbound traffic from sandbox to outside destinations.egress:diff --git a/jiuwenbox/docker/Dockerfile b/jiuwenbox/docker/Dockerfileindex f60d1c4004..d44ae549bb 100644--- a/jiuwenbox/docker/Dockerfile+++ b/jiuwenbox/docker/Dockerfile@@ -4,6 +4,11 @@ ENV 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 apt-get update \&& apt-get install -y --no-install-recommends \bubblewrap \@@ -25,8 +30,8 @@ COPY scripts ./scriptsRUN chmod +x ./scripts/server.sh-RUN pip install --break-system-packages -e . \- && pip install --break-system-packages \+RUN pip install --break-system-packages -e . -i https://pypi.tuna.tsinghua.edu.cn/simple \+ && pip install --break-system-packages -i https://pypi.tuna.tsinghua.edu.cn/simple \"fastapi>=0.104.0" \"uvicorn>=0.24.0" \"pydantic>=2.5.0" \diff --git a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.pyindex 6866103f62..0c35f94131 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py@@ -7,6 +7,7 @@ the lifecycle of the sandboxed process.from __future__ import annotationsimport logging+import posixpathimport signalimport subprocessfrom dataclasses import dataclass, field@@ -39,6 +40,30 @@ def _same_path_bind_is_covered_by_root(src: str, dst: str) -> bool:return src == dst and dst != "/" and dst.startswith("/")+def _path_depth(path: str) -> int:+ return len([part for part in path.split("/") if part])+++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] = []+ seen = {"/", *existing_dirs}++ for _, target in binds:+ parent = posixpath.dirname(target.rstrip("/") or "/")+ parents: list[str] = []+ while parent and parent != "/" and parent not in seen:+ parents.append(parent)+ parent = posixpath.dirname(parent)++ for path in reversed(parents):+ if path not in seen:+ seen.add(path)+ result.append(path)++ return result++@dataclassclass BwrapConfig:"""Configuration that maps to bwrap CLI arguments."""@@ -97,10 +122,8 @@ class BwrapConfig:@staticmethoddef _apply_filesystem(cfg: BwrapConfig, fs: FilesystemPolicy) -> None:- for path in fs.read_only:- cfg.ro_binds.append((path, path))- for path in fs.read_write:- cfg.rw_binds.append((path, path))+ # read_only/read_write are in-sandbox access rules enforced by+ # Landlock. 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))@@ -206,8 +229,16 @@ 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)+ ]+ dir_mounts = [*self.dir_mounts, *auto_dir_mounts]+ dir_mounts.sort(key=lambda item: _path_depth(item[0]))+# create directories before binding over them- for path, permissions in self.dir_mounts:+ for path, permissions in dir_mounts:if permissions:args.extend(["--perms", permissions])args.extend(["--dir", path])diff --git a/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py b/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.pyindex 8cc6bbddcd..6f3475f349 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py@@ -108,11 +108,29 @@ def _fail_or_continue(payload: dict, message: str) -> bool:return False+def _rule_anchor_path(path: str) -> str:+ """Landlock path-beneath rules must be anchored on a directory fd.++ For file mounts such as /etc/resolv.conf, fall back to the parent+ directory (e.g. /etc) so rule installation remains valid.+ """+ if os.path.isdir(path):+ return path++ normalized = path.rstrip("/") or "/"+ parent = os.path.dirname(normalized) or "/"+ return parent++def _add_rule(ruleset_fd: int, path: str, access: int) -> None:if not os.path.exists(path):return- fd = os.open(path, os.O_PATH | os.O_CLOEXEC, 0o600)+ anchor_path = _rule_anchor_path(path)+ if not os.path.exists(anchor_path):+ return++ fd = os.open(anchor_path, os.O_PATH | os.O_CLOEXEC, 0o600)try:rule = LandlockPathBeneathAttr()rule.allowed_access = access@@ -125,7 +143,7 @@ def _add_rule(ruleset_fd: int, path: str, access: int) -> None:0,)if ret < 0:- raise OSError(ctypes.get_errno(), f"landlock_add_rule failed for {path}")+ raise OSError(ctypes.get_errno(), f"landlock_add_rule failed for {anchor_path}")finally:os.close(fd)diff --git a/jiuwenbox/tests/integration/test_server_api_default.py b/jiuwenbox/tests/integration/test_server_api_default.pyindex 15c3dfcb5a..0af6812ab2 100644--- a/jiuwenbox/tests/integration/test_server_api_default.py+++ b/jiuwenbox/tests/integration/test_server_api_default.py@@ -1,12 +1,31 @@"""Integration tests for box-server API endpoints."""+import copyimport loggingimport textwrapimport httpximport pytest-LONG_RUNNING_COMMAND = ["/usr/bin/python3", "-c", "import time; time.sleep(3600)"]+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__)@@ -125,6 +144,52 @@ def _loopback_ingress_script(expect_success: bool) -> str:])+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++@pytest.fixturedef client(server_endpoint):with httpx.Client(base_url=_normalize_endpoint(server_endpoint), timeout=30.0) as external:@@ -147,7 +212,7 @@ def create_sandbox_with_policy(client):response = client.post("/api/v1/sandboxes", json={"command": command or LONG_RUNNING_COMMAND,"policy_mode": policy_mode,- "policy": policy,+ "policy": _with_runtime_support(policy),})assert response.status_code == 201, response.textsandbox = response.json()@@ -294,8 +359,18 @@ class TestPolicyAPI:assert "resources" not in dataassert data["filesystem_policy"]["directories"] == [{'path': '/home', 'permissions': '0755'},{'path': '/tmp', 'permissions': '1777'}]- assert data["filesystem_policy"]["read_only"] == ["/usr", "/lib", "/lib64", "/etc", "/opt"]- assert data["filesystem_policy"]["bind_mounts"] == []+ 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_MOUNTSassert data["process"]["run_as_user"] == "sandbox"assert data["process"]["run_as_group"] == "sandbox"assert data["namespace"] == {@@ -307,7 +382,7 @@ class TestPolicyAPI:}assert data["capabilities"] == {"add": [], "drop": []}assert data["landlock"]["compatibility"] == "best_effort"- assert data["network"]["mode"] == "host"+ 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"]@@ -397,6 +472,9 @@ class TestPolicyAPI:]assert data["network"]["ingress"]["allowed_ports"] == [8080, 9090]assert data["filesystem_policy"]["read_only"] == [+ "/",+ "/bin",+ "/sbin","/usr","/lib","/lib64",@@ -404,11 +482,11 @@ class TestPolicyAPI:"/opt","/var/log",]- assert data["filesystem_policy"]["read_write"] == ["/", "/var/tmp"]+ 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"] == [{+ assert data["filesystem_policy"]["bind_mounts"] == SYSTEM_BIND_MOUNTS + [{"host_path": "/tmp","sandbox_path": "/tmp","mode": "rw",@@ -442,6 +520,7 @@ class TestPolicyAPI:}],"read_only": ["/usr"],"read_write": ["/var/tmp"],+ "bind_mounts": SYSTEM_BIND_MOUNTS,},"network": {"mode": "host",@@ -502,6 +581,7 @@ class TestPolicyAPI: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_MOUNTSassert data["filesystem_policy"]["directories"] == [{"path": "/tmp/override-dir","permissions": "0700",@@ -1352,38 +1432,86 @@ class TestPolicyEnforcement: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_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",+ ]++ @staticmethoddef test_ingress_allowed_port_accepts_loopback_connection(client,create_sandbox_with_policy,@@ -1503,6 +1631,53 @@ class TestPolicyEnforcement: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:@staticmethoddef test_exec_requires_running_sandbox(client):diff --git a/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.py b/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.pyindex 04a2993d3b..bbeb603dd3 100644--- a/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.py+++ b/jiuwenbox/tests/integration/test_server_api_jiuwenclaw_tool.py@@ -1,5 +1,6 @@"""Integration tests for box-server API endpoints."""+import copyimport loggingimport osimport textwrap@@ -7,9 +8,29 @@ import textwrapimport httpximport pytest-LONG_RUNNING_COMMAND = ["/usr/bin/python3", "-c", "import time; time.sleep(3600)"]+LONG_RUNNING_COMMAND = ["/usr/bin/python3", "-c", "import time; time.sleep(36000)"]JIUWENCLAW_SANDBOX_WORKSPACE = "/tmp/sandbox"-JIUWENCLAW_READ_WRITE_PATH = "/"+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__)@@ -128,6 +149,38 @@ def _loopback_ingress_script(expect_success: bool) -> str:])+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++@pytest.fixturedef client(server_endpoint):with httpx.Client(base_url=_normalize_endpoint(server_endpoint), timeout=30.0) as external:@@ -150,7 +203,7 @@ def create_sandbox_with_policy(client):response = client.post("/api/v1/sandboxes", json={"command": command or LONG_RUNNING_COMMAND,"policy_mode": policy_mode,- "policy": policy,+ "policy": _with_runtime_support(policy),})assert response.status_code == 201, response.textsandbox = response.json()@@ -296,9 +349,18 @@ class TestPolicyAPI:assert data["name"] == "server-default"assert data["sandbox_workspace"] == JIUWENCLAW_SANDBOX_WORKSPACEassert "resources" not in data- assert data["filesystem_policy"]["directories"] == []- assert data["filesystem_policy"]["read_only"] == ["/usr", "/lib", "/lib64", "/etc", "/opt"]- assert data["filesystem_policy"]["read_write"] == [JIUWENCLAW_READ_WRITE_PATH]+ 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,@@ -398,6 +460,8 @@ class TestPolicyAPI:]assert data["network"]["ingress"]["allowed_ports"] == [8080, 9090]assert data["filesystem_policy"]["read_only"] == [+ "/bin",+ "/sbin","/usr","/lib","/lib64",@@ -406,12 +470,21 @@ class TestPolicyAPI:"/var/log",]assert data["filesystem_policy"]["read_write"] == [- JIUWENCLAW_READ_WRITE_PATH,+ *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"] == {@@ -441,6 +514,7 @@ class TestPolicyAPI:}],"read_only": ["/usr"],"read_write": ["/var/tmp"],+ "bind_mounts": SYSTEM_BIND_MOUNTS,},"network": {"mode": "host",@@ -502,6 +576,7 @@ class TestPolicyAPI: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_MOUNTSassert data["filesystem_policy"]["directories"] == [{"path": "/tmp/override-dir","permissions": "0700",