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(sandbox): bwrap 嵌套于 rw 父的 ro-bind 改在 rw 父之后发射
openJiuwen-botfb0dc85de5c8
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.pyindex 731db06a4e..62f1e199b2 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py@@ -74,6 +74,46 @@ def _bind_parent_dirs(binds: list[tuple[str, str]], existing_dirs: set[str]) ->return result+def _is_strict_subpath(path: str, ancestor: str) -> bool:+ """Whether ``path`` is a proper descendant of ``ancestor`` (POSIX absolute).++ Equal paths return False. A root ``/`` ancestor is never treated as a+ parent here: root binds are deduplicated and emitted in a separate stage+ of :meth:`BwrapConfig.to_args`, so treating ``/`` as a parent would flag+ every ro-bind as nested. ``posixpath.normpath`` handles trailing slashes+ and ``//``.+ """+ norm_path = posixpath.normpath(path)+ norm_ancestor = posixpath.normpath(ancestor)+ if norm_ancestor == "/" or norm_path == norm_ancestor:+ return False+ return norm_path.startswith(norm_ancestor.rstrip("/") + "/")+++def _partition_nested_ro_binds(+ ro_binds: list[tuple[str, str]],+ rw_binds: list[tuple[str, str]],+) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]:+ """Split ``ro_binds`` into ``(non-nested, nested-under-a-rw-parent)``.++ A nested ro-bind must be emitted *after* the rw parent in+ :meth:`BwrapConfig.to_args` so bwrap's later-wins keeps it as the live+ mountpoint atop the rw tree; otherwise the rw parent overlays the subtree+ and shadows it. Both partitions preserve the original relative order of+ ``ro_binds``.+ """+ rw_dsts = [dst for _, dst in rw_binds]+ non_nested: list[tuple[str, str]] = []+ nested: list[tuple[str, str]] = []+ for bind in ro_binds:+ dst = bind[1]+ if any(_is_strict_subpath(dst, rw_dst) for rw_dst in rw_dsts):+ nested.append(bind)+ else:+ non_nested.append(bind)+ return non_nested, nested++@dataclassclass BwrapConfig:"""Configuration that maps to bwrap CLI arguments."""@@ -467,14 +507,27 @@ class BwrapConfig:else:args.extend(["--tmpfs", path])- # read-only binds- for src, dst in ro_binds:+ # Read-only binds nested under a rw parent are emitted *after* the rw+ # binds so bwrap's later-overrides-earlier makes the ro-bind the live+ # mountpoint atop the rw tree (see ``_partition_nested_ro_binds``).+ # Non-nested ro-binds keep their original pre-rw order so the+ # bind_root_entries-vs-bind_mounts override contract holds for+ # non-overlapping paths.+ non_nested_ro, nested_ro = _partition_nested_ro_binds(ro_binds, rw_binds)++ # read-only binds not nested under a rw parent+ for src, dst in non_nested_ro:args.extend(["--ro-bind", src, dst])# read-write bindsfor src, dst in rw_binds:args.extend(["--bind", src, dst])+ # read-only binds nested under a rw parent — emitted last so the ro+ # mountpoint is created atop the rw tree (later-wins).+ for src, dst in nested_ro:+ args.extend(["--ro-bind", src, dst])+for src, dst in self.device_binds:args.extend(["--dev-bind", src, dst])diff --git a/jiuwenbox/tests/test.sh b/jiuwenbox/tests/test.shindex e31cd80d67..ce2c8cc813 100755--- a/jiuwenbox/tests/test.sh+++ b/jiuwenbox/tests/test.sh@@ -9,7 +9,9 @@ cd "$PROJECT_DIR"JIUWENBOX_DIR="$(realpath "$PROJECT_DIR/src")"# 默认 test 目标 & 类别; 各子命令可以覆盖。-TEST_TARGETS=("tests/integration/")+# tests/unit/ 是纯单测 (无需 server), 始终纳入默认与 default 目标,+# 保证 bwrap/landlock/seccomp 等纯逻辑回归在每次入口都跑到。+TEST_TARGETS=("tests/unit/" "tests/integration/")TEST_KIND="integration"PERF_SANDBOX_COUNT="${JIUWENBOX_PERF_SANDBOX_COUNT:-1}"PERF_CONCURRENCY="${JIUWENBOX_PERF_CONCURRENCY:-4}"@@ -21,11 +23,14 @@ usage() {Usage: tests/test.sh [target] [--server-endpoint=URI] [pytest args...]Targets:- default Run test_server_api_default.py + test_cli_default.py+ default Run tests/unit/ + test_server_api_default.py ++ test_cli_default.py + test_mcp_default.py+ unit Run pure unit tests under tests/unit/ (no server+ needed; safe to run without a live jiuwenbox)inference-privacy-proxy Run test_inference_privacy_proxy.pyperformance Run performance suite (accepts --sandbox-count /--concurrency / --loop)- (omitted) Run the whole tests/integration/ directory+ (omitted) Run tests/unit/ + the whole tests/integration/ directoryServer endpoint:--server-endpoint=URI Pick the listener to test against. Transport is@@ -62,6 +67,7 @@ if [[ $# -gt 0 ]]; then;;default)TEST_TARGETS=(+ "tests/unit/""tests/integration/test_server_api_default.py""tests/integration/test_cli_default.py""tests/integration/test_mcp_default.py"@@ -69,6 +75,11 @@ if [[ $# -gt 0 ]]; thenTEST_KIND="integration"shift;;+ unit)+ TEST_TARGETS=("tests/unit/")+ TEST_KIND="unit"+ shift+ ;;inference-privacy-proxy)TEST_TARGETS=("tests/integration/test_inference_privacy_proxy.py")TEST_KIND="integration"@@ -146,7 +157,9 @@ if (( ${#PYTEST_ARGS[@]} > 0 )); thendonefi-if [[ -n "$user_endpoint" ]]; then+if [[ "$TEST_KIND" == "unit" ]]; then+ : # unit tests need no server endpoint; skip the listener echo.+elif [[ -n "$user_endpoint" ]]; thencase "$user_endpoint" inunix://*)echo "[test.sh] endpoint=${user_endpoint} (uds)" >&2diff --git a/jiuwenbox/tests/unit/__init__.py b/jiuwenbox/tests/unit/__init__.pynew file mode 100644index 0000000000..a52b52dfba--- /dev/null+++ b/jiuwenbox/tests/unit/__init__.py@@ -0,0 +1,2 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""jiuwenbox unit tests (no running server required)."""diff --git a/jiuwenbox/tests/unit/test_bwrap_to_args.py b/jiuwenbox/tests/unit/test_bwrap_to_args.pynew file mode 100644index 0000000000..22330d28a7--- /dev/null+++ b/jiuwenbox/tests/unit/test_bwrap_to_args.py@@ -0,0 +1,182 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Unit tests for :meth:`BwrapConfig.to_args` bind emission ordering.++These tests pin the fix for the bug where a read-only bind nested *under* a+read-write parent bind (e.g. ``config.yaml`` under a rw bind of its parent+``~/.jiuwenswarm`` or under the ``/home`` lifecycle rw bind) was emitted+before the rw parent, got shadowed, and the trailing ``--remount-ro`` then+failed with ``realpath(destination): No such file or directory``.++The tests construct :class:`BwrapConfig` directly (no :class:`SecurityPolicy`+/ pwd / grp resolution) so they run on any host without a sandbox runtime.+"""++from __future__ import annotations++from jiuwenbox.supervisor.bwrap import (+ BwrapConfig,+ _is_strict_subpath,+ _partition_nested_ro_binds,+)++CONFIG_YAML = "/home/user/.jiuwenswarm/config/config.yaml"+JIUWENSWARM = "/home/user/.jiuwenswarm"+HOME = "/home"+AGENT = "/home/user/.jiuwenswarm/service_default/agent_default/agent"+++def _bind_index(args: list[str], flag: str, dst: str) -> int:+ """Index ``i`` where ``args[i]==flag`` and ``args[i+2]==dst``.++ bwrap bind flags (``--ro-bind`` / ``--bind`` / ``--dev-bind``) take two+ operands: ``flag src dst``. Returns -1 if not found.+ """+ for i in range(len(args) - 2):+ if args[i] == flag and args[i + 2] == dst:+ return i+ return -1+++def _remount_index(args: list[str], dst: str) -> int:+ """Index ``i`` where ``args[i]=='--remount-ro'`` and ``args[i+1]==dst``."""+ for i in range(len(args) - 1):+ if args[i] == "--remount-ro" and args[i + 1] == dst:+ return i+ return -1+++# ---------------------------------------------------------------------------+# Helper unit tests (white-box)+# ---------------------------------------------------------------------------+++def test_is_strict_subpath_descendant_and_boundary_cases():+ assert _is_strict_subpath("/home/user/x", "/home") is True+ # equal paths are NOT strict subpaths+ assert _is_strict_subpath("/home", "/home") is False+ # a sibling sharing a string prefix must NOT be misclassified+ assert _is_strict_subpath("/homeless", "/home") is False+ # root ancestor is special-cased away (root binds are deduplicated upstream)+ assert _is_strict_subpath("/home/user/x", "/") is False+ # normalization defends against trailing slashes and doubled separators+ assert _is_strict_subpath("/home//user/x", "/home") is True+ assert _is_strict_subpath("/home/user/x/", "/home/") is True+++def test_partition_nested_ro_binds_splits_and_preserves_order():+ ro = [("/h/bin", "/bin"), ("/h/cfg", CONFIG_YAML), ("/h/opt", "/opt")]+ rw = [("/h/ws", JIUWENSWARM)]+ non_nested, nested = _partition_nested_ro_binds(ro, rw)+ assert non_nested == [("/h/bin", "/bin"), ("/h/opt", "/opt")]+ assert nested == [("/h/cfg", CONFIG_YAML)]+++def test_partition_nested_ro_binds_home_ancestor_from_lifecycle_dirs():+ # /home is a rw ancestor of config.yaml (ProcessRuntime binds the empty+ # lifecycle /home backing dir). This is the case that defeats naive+ # "preserve producer order" fixes (A') because /home is appended by the+ # runtime, not by sysop_builder.+ ro = [("/h/cfg", CONFIG_YAML)]+ rw = [("/h/backing", HOME)]+ non_nested, nested = _partition_nested_ro_binds(ro, rw)+ assert non_nested == []+ assert nested == [("/h/cfg", CONFIG_YAML)]+++# ---------------------------------------------------------------------------+# to_args emission ordering+# ---------------------------------------------------------------------------+++def test_nested_ro_emitted_after_rw_parent_and_remount_resolves():+ cfg = BwrapConfig(command=["/bin/sh"])+ cfg.ro_binds = [("/h/cfg", CONFIG_YAML)]+ cfg.rw_binds = [("/h/ws", JIUWENSWARM)]+ cfg.remount_ro = [CONFIG_YAML]+ args = cfg.to_args()++ rw_parent = _bind_index(args, "--bind", JIUWENSWARM)+ ro_cfg = _bind_index(args, "--ro-bind", CONFIG_YAML)+ remount_cfg = _remount_index(args, CONFIG_YAML)+ assert rw_parent >= 0 and ro_cfg >= 0 and remount_cfg >= 0+ assert rw_parent < ro_cfg < remount_cfg+++def test_nested_ro_under_home_lifecycle_emitted_after_home_rw():+ cfg = BwrapConfig(command=["/bin/sh"])+ cfg.ro_binds = [("/h/cfg", CONFIG_YAML)]+ cfg.rw_binds = [("/h/backing", HOME)]+ cfg.remount_ro = [CONFIG_YAML]+ args = cfg.to_args()++ home_bind = _bind_index(args, "--bind", HOME)+ ro_cfg = _bind_index(args, "--ro-bind", CONFIG_YAML)+ remount_cfg = _remount_index(args, CONFIG_YAML)+ assert home_bind >= 0 and ro_cfg >= 0 and remount_cfg >= 0+ assert home_bind < ro_cfg < remount_cfg+++def test_non_nested_ro_keeps_pre_rw_order():+ # A ro-bind NOT under any rw parent must stay emitted before rw binds,+ # preserving the bind_root_entries-vs-bind_mounts override contract for+ # non-overlapping paths (notably code-agent's ro root entries + rw child dirs).+ cfg = BwrapConfig(command=["/bin/sh"])+ cfg.ro_binds = [("/h/bin", "/bin"), ("/h/opt", "/opt")]+ cfg.rw_binds = [("/h/ws", AGENT)]+ args = cfg.to_args()++ ro_bin = _bind_index(args, "--ro-bind", "/bin")+ ro_opt = _bind_index(args, "--ro-bind", "/opt")+ rw_agent = _bind_index(args, "--bind", AGENT)+ assert ro_bin >= 0 and ro_opt >= 0 and rw_agent >= 0+ assert ro_bin < rw_agent+ assert ro_opt < rw_agent+++def test_mixed_nested_and_non_nested_ro_ordering():+ # One non-nested ro (/bin), one nested ro (config.yaml under ~/.jiuwenswarm rw).+ # Non-nested ro must come before rw; nested ro must come after rw.+ cfg = BwrapConfig(command=["/bin/sh"])+ cfg.ro_binds = [("/h/bin", "/bin"), ("/h/cfg", CONFIG_YAML)]+ cfg.rw_binds = [("/h/ws", JIUWENSWARM)]+ args = cfg.to_args()++ ro_bin = _bind_index(args, "--ro-bind", "/bin")+ rw_parent = _bind_index(args, "--bind", JIUWENSWARM)+ ro_cfg = _bind_index(args, "--ro-bind", CONFIG_YAML)+ assert ro_bin >= 0 and rw_parent >= 0 and ro_cfg >= 0+ assert ro_bin < rw_parent < ro_cfg+++def test_sibling_prefix_not_misclassified_as_nested():+ # /homeless shares the "/home" string prefix with the rw /home bind but is+ # a sibling, not a descendant -- it must NOT be reordered after the rw bind.+ cfg = BwrapConfig(command=["/bin/sh"])+ cfg.ro_binds = [("/h/x", "/homeless")]+ cfg.rw_binds = [("/h/backing", HOME)]+ args = cfg.to_args()++ ro_homeless = _bind_index(args, "--ro-bind", "/homeless")+ home_bind = _bind_index(args, "--bind", HOME)+ assert ro_homeless >= 0 and home_bind >= 0+ assert ro_homeless < home_bind+++def test_same_path_ro_not_nested_remount_still_fires():+ # A ro-bind whose dst equals a rw bind's dst is NOT a strict subpath, so it+ # stays in the non-nested partition (emitted before the rw bind). The rw+ # bind then wins the mountpoint and the trailing --remount-ro flips it back+ # to read-only -- this is the same-path belt-and-suspenders path that+ # remount-ro *can* handle (a live mountpoint, not a shadowed one).+ cfg = BwrapConfig(command=["/bin/sh"])+ same = "/srv/secret"+ cfg.ro_binds = [("/h/ro", same)]+ cfg.rw_binds = [("/h/rw", same)]+ cfg.remount_ro = [same]+ args = cfg.to_args()++ ro = _bind_index(args, "--ro-bind", same)+ rw = _bind_index(args, "--bind", same)+ remount = _remount_index(args, same)+ assert ro >= 0 and rw >= 0 and remount >= 0+ assert ro < rw < remountdiff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.pyindex c1351823eb..be7761dca8 100644--- a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py@@ -526,15 +526,13 @@ def build_filesystem_policy(- ``mode=ro`` makes the first-pass mount land in bwrap's``--ro-bind`` stage, which is the natural and self-documentingencoding for "ro intrinsic resource".- - The :data:`read_only_promote` entry survives the case where a- later rw parent bind (e.g. a user-configured ``files.allow`` on- the parent directory of ``config.yaml``) overlays the same- subtree and silently upgrades the mount back to rw. bwrap's- ``created_paths`` set is the union of ro_binds + rw_binds- destinations (see ``bwrap.py``), so the trailing- ``--remount-ro <path>`` is guaranteed to fire on this dst and- flip it back to read-only regardless of which stage owned the- mount last.+ - The :data:`read_only_promote` entry adds the path to the policy+ ``read_only`` list, granting Landlock read-only access and+ scheduling a trailing ``--remount-ro``. That remount flips the file+ back to read-only when a later rw bind overlays it; it resolves+ because :meth:`BwrapConfig.to_args` emits a ro-bind nested under a+ rw parent *after* the rw parent (see+ ``_partition_nested_ro_binds`` in ``bwrap.py``)."""bind_mounts.append({"host_path": host_path,