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 auth for jiuwenbox
zhaozixuan0ba510217a54
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.mdindex 1a5fc80b59..130b7a923d 100644--- a/docs/en/SlashCommands.md+++ b/docs/en/SlashCommands.md@@ -635,7 +635,7 @@ Enter / leave jiuwenbox sandbox mode and tune its runtime policy. Calls `command- **Platform support**: `/sandbox` is Linux-only (jiuwenbox depends on Linux kernel features such as bwrap, Landlock, and Linux namespaces). On a Windows or macOS agent-server, every `/sandbox` sub-command returns a `SANDBOX_BAD_REQUEST` error. If the TUI runs on Windows/macOS but the agent-server is on a Linux host, the command works — what matters is the agent-server's platform.- **Write policy semantics**: `allow` / `deny` control **write access** (rw/ro) inside the sandbox, not Unix octal modes. Enforcement uses bwrap bind mounts + `--remount-ro`; Landlock is defense-in-depth (when `landlock.compatibility=disabled`, bwrap is primary).- **Nested paths**: Supported: parent allow + child deny (e.g. allow `/tmp`, deny `/tmp/secret`). Not supported: child allow + parent deny (parent deny wins); the server rejects such configs.-- **Effective write policy**: `files.allow_write` / `files.deny_write` in the status panel show the merged view of auto-managed and user-configured entries, each labeled `(rw)` or `(ro)`. Auto-managed entries are server-injected (intrinsic files such as `AGENT.md`, `HEARTBEAT.md`, `IDENTITY.md`, `SOUL.md`, `USER.md`, the `memory/daily_memory/` directory, and depending on the mode, `project_dir` and `config/config.yaml`) and cannot be removed via `/sandbox files remove`.+- **Effective write policy**: `files.allow_write` / `files.deny_write` in the status panel show the merged view of auto-managed and user-configured entries, each labeled `(rw)` or `(ro)`.- **preserve_file_sharing_mode**: Controlled by jiuwenswarm config, not by `/sandbox`. Only `mount` is supported: intrinsic files and `project_dir` are bind-mounted into the sandbox and `project_dir/config/config.yaml` is explicitly added to `deny_write`. Writing any other value into config.yaml is rejected by the server.- **excluded_commands**: Match the full command string (not just `argv[0]`); a match makes that tool call run on the host, effectively granting the command's side effects to the local environment.- **Add / remove are strict**: `exclude add` rejects a pattern that is already in the list; `exclude remove` rejects a pattern that is not in the list. `files allow|deny` rejects a path that is already in the same bucket, and rejects a path that exists in the opposite bucket (allow vs deny conflict) — run `files remove` first if you want to flip it. `files remove` rejects paths that have no matching user-configured entry.diff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"index 9ad1083a9f..69dbd4b6eb 100644--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"@@ -647,7 +647,7 @@- **平台限制**:`/sandbox` 仅支持 Linux 平台(jiuwenbox 依赖 bwrap / Landlock / Linux namespace 等内核能力)。 在 Windows / macOS 上运行的 agent-server 收到任何 `/sandbox` 子命令都会返回 `SANDBOX_BAD_REQUEST` 错误;如果 TUI 在 Mac/Windows 上、agent-server 在 Linux 主机上,是支持的(看 agent-server 所在主机的平台)。- **写入策略语义**:`allow` / `deny` 控制的是沙箱内的**写访问**(rw/ro),不是 Unix 八进制权限;enforcement 由 bwrap bind mount + `--remount-ro` 实现,Landlock 为纵深防御(`landlock.compatibility=disabled` 时主要依赖 bwrap)。- **嵌套路径**:支持「父 allow + 子 deny」(例如 allow `/tmp`、deny `/tmp/secret`);不支持「子 allow + 父 deny」(父 deny 会覆盖子 allow),服务端会拒绝此类配置。-- **生效写入策略**:状态面板里的 `files.allow_write` / `files.deny_write` 是 auto-managed 与 user-configured 合并后的视图,每条路径显示 `(rw)` 或 `(ro)`。auto-managed 条目由服务端自动注入(intrinsic 文件 `AGENT.md`、`HEARTBEAT.md`、`IDENTITY.md`、`SOUL.md`、`USER.md`,`memory/daily_memory/` 目录,以及按 mode 决定的 `project_dir` 与 `config/config.yaml`),不能通过 `/sandbox files remove` 移除。+- **生效写入策略**:状态面板里的 `files.allow_write` / `files.deny_write` 是 auto-managed 与 user-configured 合并后的视图,每条路径显示 `(rw)` 或 `(ro)`。- **preserve_file_sharing_mode**:由 jiuwenswarm 配置决定,不通过 `/sandbox` 切换。仅支持 `mount`:intrinsic 文件与 `project_dir` 通过 bind mount 注入沙箱,`project_dir/config/config.yaml` 会显式加进 `deny_write`;yaml 里写入其它值会被服务端拒绝。- **excluded_commands**:按完整命令字符串匹配(不是只看 `argv[0]`),命中后该次调用穿透到本地,相当于把对应命令的副作用授权给本地环境。- **add / remove 的去重与冲突**:`exclude add` 在已存在同名 pattern 时报错;`exclude remove` 在不存在该 pattern 时报错。`files allow|deny` 在同一 bucket 已有同 path 时报错,在对侧 bucket(allow vs deny)已登记同 path 时也报错,需要先 `files remove` 再 add;`files remove` 在用户配置里找不到该 path 时报错。diff --git "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"index 83644d290a..77b8d385d3 100644--- "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"+++ "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"@@ -399,7 +399,7 @@- `excluded_commands` — 命中后穿透到本地执行的 shell glob 列表。- `landlock` — jiuwenbox Landlock 支持情况(`supported` + `compatibility`)。- `files.allow_write` / `files.deny_write` — 生效(auto-managed ∪ user-configured,去重)的写入策略,显示 `(rw)` / `(ro)`。-- 自动配置路径:文件 `AGENT.md`、`HEARTBEAT.md`、`IDENTITY.md`、`SOUL.md`、`USER.md`,目录 `memory/daily_memory/`,以及 `project_dir`(allow_write)与 `project_dir/config/config.yaml`(deny_write)。`preserve_file_sharing_mode` 仅支持 `mount`。+- 自动配置路径:当前工作路径。`preserve_file_sharing_mode` 仅支持 `mount`。- `excluded_commands` 的匹配:按完整命令字符串匹配,不仅看 `argv[0]`;写 glob 时要把参数也覆盖进去(例如 `"git *"` 而不是 `git`)。本质等同于沙箱穿透口,不要对 `rm -rf` / `curl` 这类高风险命令使用。- add / remove 严格校验:`exclude add` 已存在 pattern、`exclude remove` 不存在 pattern 都会报错;`files allow|deny` 在同 bucket 已有 path 或对侧 bucket 已有 path(allow/deny 冲突)会报错,先 `files remove` 再 add;`files remove` 没匹配到也会报错。避免"看起来执行了实际什么也没改"。- 写入策略:`allow` / `deny` 控制写访问(rw/ro),不是 Unix 八进制权限;支持「父 allow + 子 deny」,不支持「子 allow + 父 deny」。diff --git a/jiuwenbox/README.md b/jiuwenbox/README.mdindex 9b30530327..b70963aca3 100644--- a/jiuwenbox/README.md+++ b/jiuwenbox/README.md@@ -180,6 +180,32 @@ UDS-related env vars:| `JIUWENBOX_UDS_HOST_DIR` | `/tmp/jiuwenbox-sock` | Host directory bind-mounted by `run_docker.sh` to expose the socket. || `JIUWENBOX_UDS_CONTAINER_DIR` | `/run/jiuwenbox` | Container-side mount point; must match the directory in `JIUWENBOX_LISTEN`'s socket path. |+### API authentication (opt-in)++When `JIUWENBOX_API_TOKEN` is set, every HTTP endpoint (including `/health`, `/api/v1/*`, and `/mcp`) requires:++```http+Authorization: Bearer <token>+```++Missing or invalid tokens return `401` with `{"error":"unauthorized"}`.++```bash+export JIUWENBOX_API_TOKEN="$(openssl rand -hex 32)"+JIUWENBOX_API_TOKEN=$JIUWENBOX_API_TOKEN jiuwenbox-server++export JIUWENBOX_API_TOKEN=$JIUWENBOX_API_TOKEN+jiuwenbox health++curl -H "Authorization: Bearer $JIUWENBOX_API_TOKEN" http://127.0.0.1:8321/health+```++| Variable / flag | Notes |+| --- | --- |+| `JIUWENBOX_API_TOKEN` | Shared by server and CLI; unset = auth disabled |+| `jiuwenbox-server --api-token` | Launch flag; overrides env |+| `jiuwenbox --api-token` | CLI flag; overrides env |+### Persisting the audit log (`--save-logs DIR`)**By default jiuwenbox writes no log files at all.** Audit events@@ -889,6 +915,7 @@ Global flags:| Flag | Default | Env var | Description || --- | --- | --- | --- || `--base-url` | `http://127.0.0.1:8321` | `JIUWENBOX_URL` | Server endpoint. Accepts `http://host:port` or `unix:///abs/socket/path` |+| `--api-token` | _unset_ | `JIUWENBOX_API_TOKEN` | Bearer token; required when the server has auth enabled || `--timeout` | `30` | `JIUWENBOX_TIMEOUT` | HTTP timeout seconds || `--verbose / -v` | off | – | Debug logging on stderr || `--no-color` | off | `NO_COLOR` | Disable ANSI colors on stderr |diff --git a/jiuwenbox/README_CN.md b/jiuwenbox/README_CN.mdindex a86568f376..43ce463abb 100644--- a/jiuwenbox/README_CN.md+++ b/jiuwenbox/README_CN.md@@ -174,6 +174,36 @@ UDS 相关环境变量:| `JIUWENBOX_UDS_HOST_DIR` | `/tmp/jiuwenbox-sock` | `run_docker.sh` 把宿主 socket 目录挂载到容器内的位置。 || `JIUWENBOX_UDS_CONTAINER_DIR` | `/run/jiuwenbox` | 容器内挂载点,必须与 `JIUWENBOX_LISTEN` 里 socket 路径所在的目录一致。 |+### API 认证(opt-in)++设置 `JIUWENBOX_API_TOKEN` 后,所有 HTTP 端点(含 `/health`、`/api/v1/*`、`/mcp`)均要求请求头:++```http+Authorization: Bearer <token>+```++未携带或 token 错误时返回 `401`,响应体 `{"error":"unauthorized"}`。++```bash+# 生成 token 并启动服务端+export JIUWENBOX_API_TOKEN="$(openssl rand -hex 32)"+JIUWENBOX_API_TOKEN=$JIUWENBOX_API_TOKEN jiuwenbox-server+# 或: jiuwenbox-server --api-token "$JIUWENBOX_API_TOKEN"++# CLI+export JIUWENBOX_API_TOKEN=$JIUWENBOX_API_TOKEN+jiuwenbox health++# curl+curl -H "Authorization: Bearer $JIUWENBOX_API_TOKEN" http://127.0.0.1:8321/health+```++| 变量 / 参数 | 说明 |+| --- | --- |+| `JIUWENBOX_API_TOKEN` | 服务端与 CLI **共用**;未设置 = 不启用认证 |+| `jiuwenbox-server --api-token` | 启动参数,优先级高于 env |+| `jiuwenbox --api-token` | CLI 参数,优先级高于 env |+### 持久化审计日志(`--save-logs DIR`)**默认情况下 jiuwenbox 不会写任何日志文件**:审计事件只在 Python 标@@ -850,6 +880,7 @@ jiuwenbox proxy logs openai --lines 50| 选项 | 默认值 | 环境变量 | 说明 || --- | --- | --- | --- || `--base-url` | `http://127.0.0.1:8321` | `JIUWENBOX_URL` | jiuwenbox 服务地址。接受 `http://host:port` 或 `unix:///abs/socket/path` |+| `--api-token` | _未设置_ | `JIUWENBOX_API_TOKEN` | Bearer token;服务端启用认证时必须与服务端 token 一致 || `--timeout` | `30` | `JIUWENBOX_TIMEOUT` | HTTP 超时秒数 || `--verbose / -v` | 关闭 | – | stderr 打印 debug 日志 || `--no-color` | 关闭 | `NO_COLOR` | 关闭 stderr ANSI 颜色 |diff --git a/jiuwenbox/docs/jiuwenbox_server_api.md b/jiuwenbox/docs/jiuwenbox_server_api.mdindex 877783a97e..257d8490de 100644--- a/jiuwenbox/docs/jiuwenbox_server_api.md+++ b/jiuwenbox/docs/jiuwenbox_server_api.md@@ -32,6 +32,22 @@ unix:///run/jiuwenbox/jiuwenbox.sock # 容器内 uvicorn 绑定的路业务接口统一使用 `/api/v1` 前缀,健康检查接口为 `/health`。+### API 认证(opt-in)++设置环境变量 `JIUWENBOX_API_TOKEN`(或 `jiuwenbox-server --api-token`)后启用。+所有 HTTP 端点(含 `/health`、`/api/v1/*`、`/mcp`)均需在请求头携带:++```http+Authorization: Bearer <token>+```++未设置 `JIUWENBOX_API_TOKEN` 时行为与旧版一致(无认证)。错误 token 返回+`401`,响应体 `{"error":"unauthorized"}`。++服务端与 jiuwenbox CLI 共用 `JIUWENBOX_API_TOKEN`;CLI 亦支持 `--api-token`+(优先级高于 env)。jiuwenclaw / openjiuwen provider 当前不会自动发送该+header,启用认证后需自行在 HTTP 客户端层携带 token。+### 通用接入示例以下三种方式分别通过 TCP 与 UDS 访问同一个 `/health`,请求行为完全等价;@@ -43,6 +59,9 @@ curl:# TCPcurl http://127.0.0.1:8321/health+# TCP 并设置认证 token+curl -H "Authorization: Bearer $JIUWENBOX_API_TOKEN" http://127.0.0.1:8321/health+# UDScurl --unix-socket /tmp/jiuwenbox-sock/jiuwenbox.sock http://localhost/health```diff --git a/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py b/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.pyindex b6744d60f9..83882f7e79 100644--- a/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py+++ b/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py@@ -115,6 +115,7 @@ def _flush_stderr() -> None:_ENV_BASE_URL = "JIUWENBOX_URL"_ENV_TIMEOUT = "JIUWENBOX_TIMEOUT"+_ENV_API_TOKEN_NAME = "JIUWENBOX_API_TOKEN"_DEFAULT_BASE_URL = "http://127.0.0.1:8321"_DEFAULT_TIMEOUT = 30.0_API_PREFIX = "/api/v1"@@ -222,20 +223,31 @@ class _CliClient:``cannot connect to unix:///tmp/jw.sock``) 仍可读。"""- def __init__(self, base_url: str, timeout_seconds: float = _DEFAULT_TIMEOUT) -> None:+ def __init__(+ self,+ base_url: str,+ timeout_seconds: float = _DEFAULT_TIMEOUT,+ api_token: str | None = None,+ ) -> None:cleaned = base_url.rstrip("/")self._base_url = cleanedself._timeout = timeout_seconds+ client_headers: dict[str, str] = {}+ if api_token:+ client_headers["Authorization"] = f"Bearer {api_token}"uds_path = _split_uds_endpoint(cleaned)if uds_path is not None:self._client = httpx.Client(transport=httpx.HTTPTransport(uds=uds_path),base_url=_UDS_PLACEHOLDER_BASE_URL,timeout=timeout_seconds,+ headers=client_headers or None,)else:self._client = httpx.Client(- base_url=cleaned, timeout=timeout_seconds,+ base_url=cleaned,+ timeout=timeout_seconds,+ headers=client_headers or None,)def __enter__(self) -> "_CliClient":@@ -895,6 +907,14 @@ def _add_global_options(parser: argparse.ArgumentParser) -> None:default=float(os.environ.get(_ENV_TIMEOUT, _DEFAULT_TIMEOUT)),help=f"HTTP client timeout seconds (env {_ENV_TIMEOUT}, default {int(_DEFAULT_TIMEOUT)})",)+ parser.add_argument(+ "--api-token",+ default=os.environ.get(_ENV_API_TOKEN_NAME),+ help=(+ f"Bearer token for API authentication (env {_ENV_API_TOKEN_NAME}; "+ f"must match server-side {_ENV_API_TOKEN_NAME} when enabled)"+ ),+ )parser.add_argument("--verbose", "-v",action="store_true",@@ -956,7 +976,7 @@ def build_parser() -> argparse.ArgumentParser:)p.add_argument("--sandbox-id",- help="optional sandbox id (4-16 chars: lowercase letters, digits, -, _)",+ help="optional sandbox id (4-40 chars: lowercase letters, digits, -, _)",)p.set_defaults(_handler=cmd_sandbox_create)@@ -1025,7 +1045,7 @@ def build_parser() -> argparse.ArgumentParser:)p.add_argument("--job-id",- help="optional background job id (4-16 chars, [0-9a-z_-])",+ help="optional background job id (4-40 chars, [0-9a-z_-])",)p.add_argument("--no-capture",@@ -1263,8 +1283,15 @@ def main(argv: list[str] | None = None) -> int:parser.error("no command specified")base_url = args.base_url+ api_token = getattr(args, "api_token", None)+ if isinstance(api_token, str):+ api_token = api_token.strip() or Nonetry:- with _CliClient(base_url=base_url, timeout_seconds=args.timeout) as client:+ with _CliClient(+ base_url=base_url,+ timeout_seconds=args.timeout,+ api_token=api_token,+ ) as client:try:result = handler(args, client)except _CliError:diff --git a/jiuwenbox/src/jiuwenbox/models/sandbox.py b/jiuwenbox/src/jiuwenbox/models/sandbox.pyindex 64e881fa6a..cb75275bfb 100644--- a/jiuwenbox/src/jiuwenbox/models/sandbox.py+++ b/jiuwenbox/src/jiuwenbox/models/sandbox.py@@ -11,12 +11,15 @@ from datetime import datetimefrom pydantic import BaseModel, FieldSANDBOX_ID_MIN_LEN = 4-SANDBOX_ID_MAX_LEN = 16-CUSTOM_SANDBOX_ID_RE = re.compile(r"^[0-9a-z_-]{4,16}$")+SANDBOX_ID_MAX_LEN = 40+CUSTOM_SANDBOX_ID_RE = re.compile(+ rf"^[0-9a-z_-]{{{SANDBOX_ID_MIN_LEN},{SANDBOX_ID_MAX_LEN}}}$"+)SANDBOX_ID_FORMAT_MESSAGE = (- "sandbox_id must be 4-16 characters and contain only lowercase letters, "- "digits, hyphens, and underscores (e.g. my-sb_01)"+ f"sandbox_id must be {SANDBOX_ID_MIN_LEN}-{SANDBOX_ID_MAX_LEN} characters "+ "and contain only lowercase letters, digits, hyphens, and underscores "+ "(e.g. my-sb_01)")@@ -25,12 +28,14 @@ class InvalidSandboxIdError(Exception):JOB_ID_MIN_LEN = 4-JOB_ID_MAX_LEN = 16-CUSTOM_JOB_ID_RE = re.compile(r"^[0-9a-z_-]{4,16}$")+JOB_ID_MAX_LEN = 40+CUSTOM_JOB_ID_RE = re.compile(+ rf"^[0-9a-z_-]{{{JOB_ID_MIN_LEN},{JOB_ID_MAX_LEN}}}$"+)JOB_ID_FORMAT_MESSAGE = (- "job_id must be 4-16 characters and contain only lowercase letters, "- "digits, hyphens, and underscores (e.g. http-srv)"+ f"job_id must be {JOB_ID_MIN_LEN}-{JOB_ID_MAX_LEN} characters and contain "+ "only lowercase letters, digits, hyphens, and underscores (e.g. http-srv)")diff --git a/jiuwenbox/src/jiuwenbox/server/app.py b/jiuwenbox/src/jiuwenbox/server/app.pyindex 35389444b2..c6564fb835 100644--- a/jiuwenbox/src/jiuwenbox/server/app.py+++ b/jiuwenbox/src/jiuwenbox/server/app.py@@ -17,6 +17,7 @@ from pydantic import ValidationErrorfrom jiuwenbox.logging_config import configure_loggingfrom jiuwenbox import __version__+from jiuwenbox.server.auth import BearerTokenAuthMiddleware, get_configured_tokenfrom jiuwenbox.server.audit_logger import AuditLoggerfrom jiuwenbox.models.sandbox import InvalidJobIdError, InvalidSandboxIdErrorfrom jiuwenbox.server.runtime.process import BackgroundJobNotFoundError@@ -298,6 +299,8 @@ async def lifespan(_application: FastAPI):)_proxy_manager = ProxyManager(policy_reader=policy_reader)logger.info("box-server started (version %s)", __version__)+ if get_configured_token() is not None:+ logger.info("API authentication enabled")await _proxy_manager.start()# 在 proxy 起来之后、yield (接受请求) 之前给 UDS 打权限: 此刻 uvicorn 已# 经 bind 并 listen 完成, socket inode 必然存在; 改 mode 不会和首个请求@@ -397,6 +400,7 @@ def create_app() -> FastAPI:allow_methods=["*"],allow_headers=["*"],)+ application.add_middleware(BearerTokenAuthMiddleware)@application.exception_handler(SandboxNotFoundError)async def not_found_handler(request: Request, exc: SandboxNotFoundError):diff --git a/jiuwenbox/src/jiuwenbox/server/auth.py b/jiuwenbox/src/jiuwenbox/server/auth.pynew file mode 100644index 0000000000..e614aa6db5--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/server/auth.py@@ -0,0 +1,59 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Opt-in Bearer token authentication for the jiuwenbox HTTP API."""++from __future__ import annotations++import hmac+import os++from starlette.middleware.base import BaseHTTPMiddleware+from starlette.requests import Request+from starlette.responses import JSONResponse, Response++_ENV_API_TOKEN_NAME = "JIUWENBOX_API_TOKEN"+++def get_configured_token() -> str | None:+ """Return the configured API token, or ``None`` when auth is disabled."""+ raw = os.environ.get(_ENV_API_TOKEN_NAME)+ if raw is None:+ return None+ token = raw.strip()+ return token or None+++def extract_bearer_token(authorization: str | None) -> str | None:+ if not authorization:+ return None+ scheme, _, token = authorization.partition(" ")+ if scheme.lower() != "bearer" or not token:+ return None+ stripped = token.strip()+ return stripped or None+++def token_is_valid(provided: str | None, expected: str) -> bool:+ if provided is None:+ return False+ return hmac.compare_digest(+ provided.encode("utf-8"),+ expected.encode("utf-8"),+ )+++class BearerTokenAuthMiddleware(BaseHTTPMiddleware):+ """Require ``Authorization: Bearer <token>`` when the API token env is set."""++ async def dispatch(self, request: Request, call_next) -> Response:+ expected = get_configured_token()+ if expected is None:+ return await call_next(request)++ provided = extract_bearer_token(request.headers.get("Authorization"))+ if not token_is_valid(provided, expected):+ return JSONResponse(+ status_code=401,+ content={"error": "unauthorized"},+ headers={"WWW-Authenticate": "Bearer"},+ )+ return await call_next(request)diff --git a/jiuwenbox/src/jiuwenbox/server/launcher.py b/jiuwenbox/src/jiuwenbox/server/launcher.pyindex 7fed0aeab8..31de59bc3f 100644--- a/jiuwenbox/src/jiuwenbox/server/launcher.py+++ b/jiuwenbox/src/jiuwenbox/server/launcher.py@@ -26,7 +26,7 @@ ENV_UDS_MODE = "JIUWENBOX_UDS_MODE"# the launcher independent of the FastAPI app module (``main`` runs before# anything imports ``jiuwenbox.server.app`` lazily inside ``uvicorn.run``).ENV_SAVE_LOGS_DIR = "JIUWENBOX_SAVE_LOGS_DIR"-+_ENV_API_TOKEN_NAME = "JIUWENBOX_API_TOKEN"DEFAULT_LISTEN = "http://0.0.0.0:8321"HttpSpec = Tuple[str, str, int] # ("http", host, port)@@ -177,6 +177,15 @@ def _build_parser() -> argparse.ArgumentParser:"kept across boots."),)+ parser.add_argument(+ "--api-token",+ default=None,+ help=(+ "Enable Bearer token authentication for all HTTP endpoints "+ f"(including /health and /mcp). Falls back to ${_ENV_API_TOKEN_NAME} "+ "env; unset means authentication is disabled."+ ),+ )return parser@@ -189,6 +198,14 @@ def _resolve_listen_uri(cli_value: str | None) -> str:return DEFAULT_LISTEN+def _resolve_api_token(cli_value: str | None) -> str | None:+ raw = cli_value if cli_value else os.environ.get(_ENV_API_TOKEN_NAME)+ if not raw:+ return None+ token = raw.strip()+ return token or None++def _resolve_save_logs_dir(cli_value: str | None) -> str | None:"""Pick CLI > env > unset; normalize to absolute path.@@ -241,6 +258,13 @@ def main(argv: list[str] | None = None) -> int:else:os.environ.pop(ENV_SAVE_LOGS_DIR, None)+ api_token = _resolve_api_token(args.api_token)+ if api_token:+ os.environ[_ENV_API_TOKEN_NAME] = api_token+ logger.info("[launcher] API authentication enabled")+ else:+ os.environ.pop(_ENV_API_TOKEN_NAME, None)+try:import uvicorn # 延迟导入: argparse / URI 校验失败时不必拖 uvicorn 进来except ImportError as exc: # pragma: no cover - declared in pyprojectdiff --git a/jiuwenbox/src/jiuwenbox/server/runtime/process.py b/jiuwenbox/src/jiuwenbox/server/runtime/process.pyindex bce4761389..d3c4fcd5c6 100644--- a/jiuwenbox/src/jiuwenbox/server/runtime/process.py+++ b/jiuwenbox/src/jiuwenbox/server/runtime/process.py@@ -836,6 +836,8 @@ class ProcessRuntime(RuntimeAdapter):scripts, seccomp BPF, landlock payload) keep the per-call cost low."""config = BwrapConfig.from_policy(policy, list(command))+ process_uid = config.uid+ process_gid = config.gidif sandbox_env:config.env.update(sandbox_env)if workdir:@@ -921,6 +923,24 @@ class ProcessRuntime(RuntimeAdapter):]config.seccomp_fd = seccomp_fd+ if self._needs_privdrop_for_process_identity(+ process_uid,+ use_user_namespace=policy.namespace.user,+ ):+ if process_uid is None or process_gid is None:+ raise RuntimeError(+ "run_as_user/run_as_group could not be resolved for privilege drop",+ )+ config.command = self._wrap_command_with_privdrop(+ config.command,+ process_uid,+ process_gid,+ )+ logger.info(+ "Dropping sandbox command to host uid %d gid %d via Python",+ process_uid,+ process_gid,+ )return config.to_args()def _get_netns_name(self, sandbox_id: str) -> str:@@ -1278,6 +1298,47 @@ class ProcessRuntime(RuntimeAdapter):)os.chmod(path, fallback_mode)+ @staticmethod+ def _needs_privdrop_for_process_identity(+ uid: int | None,+ *,+ use_user_namespace: bool,+ ) -> bool:+ """Whether to drop to the host uid before running the sandbox command.++ When ``namespace.user`` is enabled, bubblewrap already applies+ ``--uid`` / ``--gid`` together with ``--unshare-user``.++ Privilege drop is only needed when the server runs as root *and* the+ sandbox reuses the host user namespace (``namespace.user: false``).+ """+ if use_user_namespace:+ return False+ return os.geteuid() == 0 and uid is not None and uid != 0++ @staticmethod+ def _wrap_command_with_privdrop(+ command: list[str],+ uid: int,+ gid: int,+ ) -> list[str]:+ """Wrap ``command`` in a short Python helper that drops uid/gid.++ Uses stdlib ``os.setuid`` / ``os.setgid`` so jiuwenbox does not depend+ on the external ``setpriv(1)`` binary from util-linux.+ """+ encoded_command = json.dumps(command)+ script = "; ".join([+ "import json, os",+ f"uid, gid = {uid}, {gid}",+ f"cmd = json.loads({encoded_command!r})",+ "exec('try:\\n os.setgroups([])\\nexcept OSError:\\n pass', globals())",+ "os.setgid(gid)",+ "os.setuid(uid)",+ "os.execvp(cmd[0], cmd)",+ ])+ return [PYTHON_EXECUTABLE, "-S", "-c", script]+def _ensure_policy_directories(self,sandbox_id: str,diff --git a/jiuwenbox/tests/integration/test_server_api_default.py b/jiuwenbox/tests/integration/test_server_api_default.pyindex a7d3b31e3b..974d81a57f 100644--- a/jiuwenbox/tests/integration/test_server_api_default.py+++ b/jiuwenbox/tests/integration/test_server_api_default.py@@ -518,7 +518,7 @@ class TestSandboxCRUD:"ABC123","my sb"," abcd ",- "a" * 17,+ "a" * 41,"id!",],)@@ -3638,7 +3638,7 @@ class TestBackgroundJobs:)@staticmethod- @pytest.mark.parametrize("invalid_id", ["ab", "ABC123", "my job", "a" * 17])+ @pytest.mark.parametrize("invalid_id", ["ab", "ABC123", "my job", "a" * 41])def test_invalid_job_id_returns_400(client, invalid_id):create_resp = client.post("/api/v1/sandboxes", json={})sandbox_id = create_resp.json()["id"]diff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.pyindex 293b7c91cd..1f511a3798 100644--- a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py@@ -364,7 +364,6 @@ def build_filesystem_policy(_mount_rw_dir(resolved_workspace)resolved_project = _resolve_project_dir(project_dir)- logger.info(f'zzx: resolved_project: {resolved_project}')if resolved_project is not None:_mount_rw_dir(resolved_project)