Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
0.7.7: run Claude inside the VM, keys stay outside (slice 1) (#446)
Oleksandr Ivanchenkod9425559d9bd
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlindex 1298d7b2..77b10574 100644--- a/.github/workflows/windows.yml+++ b/.github/workflows/windows.yml@@ -84,7 +84,8 @@ jobs:env:# Exactly this many tests must run (Rigel's F-2): a renamed or moved test that no longer# matches the filters fails here instead of quietly dropping out. Change it with the filters.- EXPECTED_TESTS: 13+ # 16 since #446: floor.rs gained head_branch_needs_objects_and_refs_like_git, _keeps_a_worktree_gitdir_in_the_bot_folder and _refuses_a_working_folder_outside_the_bot_folder.+ EXPECTED_TESTS: 16run: |set -euo pipefailcargo test --locked --lib --no-fail-fast -- server::dev::floor:: server::dev::poller::tests::fresh_means server::dev::poller::tests::candidates_go_newest server::dev::poller::tests::the_skipped_count server::dev::git::tests::diff_output_parses server::dev::git::tests::patches_are_matched 2>&1 | tee dev-readers.logdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5eaeda39..a081ca24 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).### Added- **kwant for Windows (beta).** kwant now has a Windows app for 64-bit Windows. Each release has an installer, `kwant_X.Y.Z_windows_x64_beta_setup.exe`, with its SHA-256. It installs for your user only, so it needs no admin rights, and it runs kwant on your PC with the same data folder as `kwnt serve` (`.kwnt` in your user folder). The installer isn't code-signed yet, so the first time you run it Windows SmartScreen warns about an unrecognized app: click **More info**, then **Run anyway**. In the beta, the app doesn't update itself (a new version is a new installer), Grok, the isolated computer (bots work on your own computer instead) and looking inside videos aren't available on Windows yet. Dev mode works, with one difference: in a folder that OneDrive syncs with "Files On-Demand", kwant can't safely read the repository's git files, so Dev mode asks you before every push from that folder.+- **Run Claude inside the VM (Linux, off by default).** In VM mode, a new switch under the VM card runs each bot's Claude replies in a container of its own with no network. The real key or sign-in stays outside: kwant's broker passes only the Anthropic calls Claude needs and refuses the rest. Each reply may make 200 model requests. Claude's own web search and fetch are off while isolated, so bots use kwant's browser tools. Codex, Grok and Claude API-key accounts still run on this computer, and the chips under the switch show where each one runs. If isolation can't start, the reply stops with a notice and nothing runs unprotected. See docs/agents-in-vm.md for what it does and doesn't protect against.- **Get started offers to bring your bots.** Step 3, "Pick a team", has a new "Bring your bots" tile next to "Keep the starter bots". It opens the same importer as Space settings › Import bots, so you can bring a bot from Grok Bot, ChatGPT or Claude, or from a file, and check a preview first. A finished import completes step 3. Closing the importer without importing leaves step 3 as it was.- **Import several bots at once.** The importer's "Upload a file" now takes several files in one pick or drop, for example every Grok Bot export you have. You don't need to zip them yourself. kwant packs them into one zip in your browser and shows one preview with every bot, plus the names of any files it couldn't read. Picks are limited to 500 files and 20 MB in all, and a zip can only be imported on its own.@@ -19,6 +20,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).### Fixed- **A checkpoint's git commit only comes from the task's own git files.** When a mission takes a checkpoint, kwant notes the commit the task's folder is on. It now never follows a symlink inside `.git`, ignores a `ref:` that points outside it, skips FIFOs and oversized files, and keeps the value only when it's a real 40- or 64-character commit id. Before, a bot that could write its task folder could make a checkpoint show the first 64 characters of another file kwant can read. (#443)- **Dev mode reads the checked-out branch safely too.** The production safeguard reads which branch a bot's folder is on. A planted FIFO could stall that check, and a symlink, a hard link or a `.git` file could point it at another file. It now reads `.git` the same careful way checkpoints do, and only follows a worktree's pointer into a real `.git/worktrees/` folder. Checkpoints also now skip a hard-linked git file. (#444)+- **Dev mode's branch check stays inside the bot's folder.** It reads `.git` only in the bot's folder and below, never through a symlink (it now holds each folder open while it reads), counts a `.git` folder as a repo only when it has `objects` and `refs` as git does, and doesn't follow a worktree pointer out of the folder. When it can't tell the branch, a plain `git push` asks, as before.## [Mac 0.7.6] - 2026-11-08diff --git a/Cargo.lock b/Cargo.lockindex dd421403..d67153b0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1431,6 +1431,9 @@ dependencies = ["dirs","flate2","futures",+ "http-body-util",+ "hyper",+ "hyper-util","kwnt","libc","mail-parser",diff --git a/Cargo.toml b/Cargo.tomlindex 0863e538..c2294928 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -29,6 +29,11 @@ serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "sqlite", "migrate", "chrono"] }reqwest = { version = "0.12", features = ["json", "stream"] }+# The agent-VM credential broker serves HTTP/1 on a Unix socket (sandbox::agent_vm::broker);+# all three were already in the tree through axum and reqwest+hyper = { version = "1", features = ["server", "http1"] }+hyper-util = { version = "0.1", features = ["tokio"] }+http-body-util = "0.1"futures = "0.3"tokio-stream = { version = "0.1", features = ["sync"] }tokio-util = "0.7"diff --git a/apps/mac/Cargo.lock b/apps/mac/Cargo.lockindex 61b5a09f..f410ed71 100644--- a/apps/mac/Cargo.lock+++ b/apps/mac/Cargo.lock@@ -2741,6 +2741,9 @@ dependencies = ["dirs 5.0.1","flate2","futures",+ "http-body-util",+ "hyper",+ "hyper-util","libc","mail-parser","mime_guess",diff --git a/docker/agent-entry.sh b/docker/agent-entry.shnew file mode 100644index 00000000..b36515a3--- /dev/null+++ b/docker/agent-entry.sh@@ -0,0 +1,5 @@+#!/bin/sh+# The container's only way out: the model API and kwnt's own tools through kwnt's broker, a+# Unix socket kwnt bind-mounts read-only at /run/kwnt. The CLI speaks plain HTTP to 127.0.0.1:8080.+socat TCP-LISTEN:8080,bind=127.0.0.1,fork,reuseaddr UNIX-CONNECT:/run/kwnt/broker.sock &+exec sleep infinitydiff --git a/docker/agent.Dockerfile b/docker/agent.Dockerfilenew file mode 100644index 00000000..c252705a--- /dev/null+++ b/docker/agent.Dockerfile@@ -0,0 +1,16 @@+# The agent computer for Claude turns when "Run Claude in the computer" is on (Linux, slice 1;+# src/sandbox/agent_vm). kwnt-executor plus socat and one pinned Claude Code. The container runs+# with no network; socat forwards 127.0.0.1:8080 to kwnt's broker socket at /run/kwnt.+FROM kwnt-executor:v1+ARG CLAUDE_VERSION+RUN apt-get update && apt-get install -y --no-install-recommends socat util-linux \+ && rm -rf /var/lib/apt/lists/*+# Anthropic's installer checks the download against its published checksum; the binary is then+# moved out of the throwaway home so every user id the container runs as can start it+RUN set -eu; test -n "$CLAUDE_VERSION"; export HOME=/tmp/claude-install; mkdir -p "$HOME"; \+ curl -fsSL https://claude.ai/install.sh | bash -s "$CLAUDE_VERSION"; \+ install -m 0755 "$(readlink -f "$HOME/.local/bin/claude")" /usr/local/bin/claude; \+ rm -rf "$HOME"; /usr/local/bin/claude --version | grep -F "$CLAUDE_VERSION"+COPY agent-entry.sh /usr/local/bin/kwnt-agent-entry+RUN chmod 0755 /usr/local/bin/kwnt-agent-entry+CMD ["/usr/local/bin/kwnt-agent-entry"]diff --git a/docs/agents-in-vm.md b/docs/agents-in-vm.mdnew file mode 100644index 00000000..1a0f7f2e--- /dev/null+++ b/docs/agents-in-vm.md@@ -0,0 +1,121 @@+# Run Claude inside the VM (0.7.7, slice 1)++When the computer is in **VM** mode and **Run Claude inside the VM** is on, a bot's Claude turn+runs the `claude` CLI in a container of its own, with no network. The container never holds a+real key or sign-in. Its only way out is kwnt's broker, a Unix socket mounted read-only at+`/run/kwnt`. The broker swaps the stand-in credential for the real one, forwards a short list of+Anthropic calls, and refuses everything else.++- **Off by default.** Settings › Computer, under the VM card.+- **Linux only in 0.7.7.** On a Mac the switch is shown disabled with "Coming to Mac later".+- **Claude only.** Codex and Grok still run on this computer ("Not isolated yet").+- **Claude sign-ins only.** A Claude API-key or Custom account still runs on this computer; its+ chip says "Not isolated".+- **Local mode:** the setting is kept but does nothing, and the chip says "Not isolated".++## What it protects++A Claude bot that has been talked into misbehaving, by a web page, a file or another bot's+text, can't do these things while it runs inside the VM:++- **Read your sign-ins or keys.** `~/.claude`, `~/.codex`, `~/.grok`, `~/.ssh`, kwnt's data folder+ and the sign-in homes are never mounted. The container gets a stand-in key, and the real one+ stays in the broker. A folder that is, holds or sits inside one of these is refused before the+ container starts (`unsafe_folder`).+- **Send your key or files anywhere.** The container runs with `--network none`. The broker+ forwards only `POST /v1/messages`, the one call Gate 0 saw the real CLI make (Claude Code 2.1.316). It refuses+ `..`, `%2e`, `//`, absolute-form targets, smuggled or oversized requests, server-side tools,+ `mcp_servers` and bodies with repeated keys, and drops unknown `anthropic-beta` values.+- **Run up an unbounded bill in one reply.** Each reply may make 200 model requests (configurable);+ the next one gets a 429 and the chat says the reply hit its limit.+- **Leave a trap for kwnt on this computer.** Every folder an isolated reply used is recorded.+ In such a folder, a folder inside it or one holding it:+ - Claude on this computer starts with `--setting-sources user --strict-mcp-config`, so the+ folder's own `.claude/settings*.json` hooks and `.mcp.json` servers don't load;+ - Codex and Grok don't start at all (`folder_used_by_isolated_bot`);+ - a mission's command check, the Dev backup command, and a stdio MCP server whose program or+ arguments point at a file in the folder are refused;+ - kwnt's own git calls run with `GIT_CONFIG_NOSYSTEM=1 -c core.fsmonitor=false+ -c core.hooksPath=/dev/null -c core.pager=cat`;+ - kwnt reads bot folders (checkpoints, restore, team discovery) without following symlinks,+ one folder at a time, so a link or a swapped folder can't point a read outside.++## What it doesn't protect against++- **Spending your credits.** The bot uses your real Claude account through the broker. The+ request cap bounds one reply, not a day of replies.+- **Actions through kwnt's own tools.** kwnt's MCP tools (browser, shell, files, teammates,+ approvals) are reachable through the broker, as they are without isolation. They still follow+ each bot's approval settings, so a bot that may run commands without asking still can.+- **kwnt's built-in shell.** `execute_shell` runs in kwnt's own executor container, which keeps+ its network. Isolating Claude doesn't change it.+- **Files you run later.** A bot can still write `.git/hooks`, `.envrc`, package scripts or editor+ tasks in its folder. They run if **you** use them on your own computer.+- **Codex, Grok, and Claude API-key or Custom accounts.** They run on this computer as before.+- **A Docker or kernel escape.** The container drops every capability, runs as your user id with+ a read-only root and no network, but it shares the kernel.++## What changes for the bot++- **No WebSearch or WebFetch.** Claude starts with `--disallowedTools WebSearch,WebFetch`, because+ Anthropic's server-side tools reach the network from Anthropic's side. Bots use kwnt's browser+ tools instead.+- **Only kwnt's own MCP servers.** Outside servers (Notion and so on) are left out of the turn,+ since the container can't reach them. They still work with the setting off.+- **A new session.** The first isolated reply starts a fresh Claude session; `--resume` works+ from then on.+- **The first use sets up Claude's VM.** kwnt builds the image once from its executor image plus+ Claude Code (about 860 MB on disk). A reply sent meanwhile says so and asks you to retry;+ nothing runs on this computer.++## When it can't run++With the setting on, any failure stops the reply with a notice in the chat and nothing runs on+this computer. Turning the setting off is always yours to do. Codes (the `reason` of the+`turn_isolation_failed` chat notice and of each `agents.claude` chip):++| Code | Meaning |+|---|---|+| `preparing` | Claude's VM is still downloading |+| `download_failed` | The download failed; the next reply tries again |+| `docker_unavailable` | Docker isn't running |+| `relay_down` | kwnt's broker couldn't start |+| `container_failed` | The bot's container didn't start or stopped partway |+| `no_credential` / `sign_in_expired` | No Claude sign-in, or it expired and couldn't be refreshed |+| `unsafe_folder` | The folder is, holds or sits inside something private (`unsafe_kind`: `home`, `contains_home`, `root`, `sign_ins`, `kwant_data`, `docker`, `shared_folder`) |+| `folder_used_by_isolated_bot` | Codex or Grok was asked to run in a folder an isolated Claude used |+| `host_is_root` | kwnt runs as root; the container never does |+| `folder_name_unsupported` | The folder's name has a newline or isn't UTF-8 |+| `folder_record_failed` | kwnt couldn't note the folder (D4), so it didn't start |+| `unsupported_os` | Not Linux |++A reply that reaches the request cap ends with a `turn_request_limit` notice instead of a raw+429.++## Server settings++In `<data>/config.toml`:++```toml+[agents_in_vm]+request_limit = 200 # model requests per reply (env KWNT_AGENT_REQUEST_LIMIT)+memory_mb = 1024 # per bot container (env KWNT_AGENT_MEMORY_MB)+max_turns = 2 # isolated replies at once; the next one waits, and the chat says so (env KWNT_AGENT_MAX_TURNS)+```++## Who refreshes a sign-in++While the setting is on, the broker is the only thing that refreshes a bot's own Claude sign-in+(a profile's sign-in home). It refreshes once at a time per file, re-reads the file under a lock+and writes the new token with mode 600. It never refreshes this computer's own `~/.claude`+sign-in: when that has expired, the reply stops with `sign_in_expired`, and you sign in again on+this computer.++## Files++- `src/sandbox/agent_vm/`: the VM (`mod.rs`), the broker (`broker.rs`), the folder rule+ (`folder_rule.rs`) and the chat notices (`notice.rs`).+- `src/sandbox/safe_fs.rs`: the no-follow folder reader.+- `src/db/isolated_folders.rs`: the record of folders isolated replies used.+- `docker/agent.Dockerfile`, `docker/agent-entry.sh`: the image (`kwnt-agent:v1-claude-<version>`).+- `proto/agents-in-vm/`: the Python spike, `gate0.sh` and the evidence it wrote.diff --git a/proto/agents-in-vm/.gitignore b/proto/agents-in-vm/.gitignorenew file mode 100644index 00000000..37ca50d7--- /dev/null+++ b/proto/agents-in-vm/.gitignore@@ -0,0 +1,3 @@+run/+__pycache__/+run-gate0/diff --git a/proto/agents-in-vm/DESIGN.md b/proto/agents-in-vm/DESIGN.mdnew file mode 100644index 00000000..06f7e943--- /dev/null+++ b/proto/agents-in-vm/DESIGN.md@@ -0,0 +1,161 @@+# Agents in the VM: CLI isolation + credential broker (design spike, Lin, 2026-11-08)++Branch `lin-078-agents-in-vm`, prototype in `proto/agents-in-vm/` (Python broker and mock for the spike; the real one is Rust).+One command re-runs the attack check: `proto/agents-in-vm/adversarial.sh` (3.4 s, prints `RESULT: PASS`, cleans up after itself).+Evidence: `proto/agents-in-vm/evidence/` (adversarial-run.txt, bench.txt, q2-q3-q6-notes.md).++## Decision++**Build it, Claude first, opt-in.** In vm mode, run the CLI inside the executor container with `--network none`, so only+the task folder and a private CLI home are mounted. The container's single way out is a host-side broker on a+bind-mounted Unix socket. The broker swaps a dummy credential for the real one, and only for an allow-list of+(method, path) pairs. Everything else gets a 403, and the real token never enters the container. This worked+end to end for Claude with both an API key and a subscription OAuth token (the host refreshes it), for Codex with+both an API key and ChatGPT sign-in, and up to the request layer for Grok. We don't rely on the CLIs' own sandboxes,+because those protect writes, not the token.++## Answers++**Q1 Claude without a real credential.** Proven against a header-logging mock.+- API key: the container gets `ANTHROPIC_API_KEY=sk-ant-api03-kwnt-dummy` and `ANTHROPIC_BASE_URL=http://127.0.0.1:8080/anthropic`. The broker drops `x-api-key` and `authorization` and adds the real key. The upstream logged `api_key_ok`, and the dummy never reached it.+- OAuth: the container gets `CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-kwnt-dummy`. The broker sends `Bearer <real access token>`, and `anthropic-beta: oauth-2025-04-20` passes through.+- Who refreshes: the host broker does, never the CLI. It refreshes before forwarding when the token expires within 60 s, and again once on a 401. Refresh runs single-flight under a lock and writes the credentials file atomically at 0600. Both paths were proven (`pre_refresh` and `on_401`), and the turn succeeded each time. The container is also denied the refresh endpoint itself (`deny_path /anthropic/v1/oauth/token`).+- `--resume` works across turns because the session store lives in the mounted CLI home. The MCP permission prompt (`mcp__kwnt__approve`) reaches the gateway through the same broker.++**Q2 Codex and Grok.**+- **Codex (API key and ChatGPT): yes.** Codex ignores `OPENAI_BASE_URL`, so kwant writes a custom `[model_providers]` entry into the container's `CODEX_HOME/config.toml`. For ChatGPT sign-in, use `requires_openai_auth=true` plus a dummy `auth.json` (unsigned JWTs). The broker sets the real bearer and `chatgpt-account-id`. Full turns passed in both modes. Side calls (plugins, wham/*, analytics) were denied and the turn still finished.+- **Grok, API key: very likely.** The real bearer was injected on /models, /chat/completions and /responses through `GROK_MODELS_BASE_URL` and `GROK_CLI_CHAT_PROXY_BASE_URL`. A full turn was not run because the mock doesn't speak xAI.+- **Grok, sign-in: partly.** `GROK_AUTH_PROVIDER_COMMAND` makes it send a dummy session token to our base URL, but I never reached its inference path.+- **Unproven for both:** host-side refresh of ChatGPT and Grok sign-ins against real endpoints.+- **Fallback (any CLI or mode that won't go through the broker):** keep that CLI on the host, as today, and show "not isolated" for it in Settings. We never copy a real token into the container.++**Q3 Default-deny network.**+- **Pick `--network none` + Unix socket + an in-container `socat` on 127.0.0.1:8080.** Proven: no DNS (curl rc 6), no IP route to 1.1.1.1 or the docker bridge (rc 7), no `host.docker.internal`, and a 403 for any host not on the allow-list.+- **`--internal` is rejected.** It blocks the internet, but on Linux the container could still open the host's bridge gateway (172.19.0.1:22 was open), so every host service listening on 0.0.0.0 is reachable.+- **MCP gateway:** reached as `http://127.0.0.1:8080/mcp`. The broker passes the per-turn gateway token through unchanged.+- **Docker Desktop on Mac:** bind-mounting a Unix socket into a container works there in principle (via the VM's file sharing), but it is **untested**. If it fails, the fallback is a loopback TCP port published only to the broker plus a per-container shared secret.+- **The person's allow-list** (npm, PyPI, GitHub) lives in the broker as extra routes in the same (host, method, path) table, edited in Settings › Computer and stored per bot. In v1 they are pass-through only, with no credentials added. Package installs then go through an `HTTPS_PROXY=http://127.0.0.1:8080` CONNECT route that the broker limits to those hostnames. That route is **not built** in the spike.++**Q4 Image.**+- **Layers:** `kwnt-executor:v1` + `socat` + the three CLIs. They are native binaries (claude is bun/glibc, codex and grok are static), so **no Node** is needed.+- **Size:** 1.46 GB on disk, 421 MB compressed; the executor alone is 376 MB. The build took 56 s.+- **Versions:** build once per kwant release with pinned CLI versions, as one image layer per CLI so an update re-downloads one layer. Turn the CLIs' auto-updaters off inside (`DISABLE_AUTOUPDATER=1`). They couldn't reach the internet anyway.+- **Startup cost:** a warm turn adds about 110 ms over the host (833 vs 708 ms median), and a cold start adds about 460 ms. Idle memory is 3.4 MiB, so keep one container per bot warm while vm mode is on.++**Q5 Files and approvals.**+- **Mounts:** `/workspace` is the task folder (rw). The CLI home is a per-bot host dir mounted at `/home/agent`: session store, `CLAUDE_CONFIG_DIR`, `CODEX_HOME` and settings, with no credentials in it. `/run/kwnt` is read-only: the socket and the per-turn MCP config.+- **Hardening:** `--read-only` root, tmpfs `/tmp`, `--cap-drop ALL`, `no-new-privileges`, a dedicated non-root uid.+- **Unchanged:** checkpoints and undo (`server/missions/checkpoints.rs` snapshots the host folder, and the files land there owned by the container uid, so kwant has to chown or map uids). Approvals and Flight School also stay the same: the permission prompt still arrives as an MCP call, and a `touch` was gated through the broker in the spike.+- **Known gap (same as today):** Claude's built-in read-only allow-list (cat, ls, echo) runs without asking kwant. In the container that only exposes the task folder, so isolation makes the gap harmless.++**Q6 The cheaper alternative (CLI sandboxes).**+- **They don't keep sign-in files safe.** The CLI process itself holds the real token in memory and reads its own credential file. The sandboxes limit what its tools write and where they connect; by default reads stay broad. Claude has `denyRead` settings, which help against a prompt-injected `cat ~/.claude/.credentials.json` but not against the process itself.+- **Codex's Linux sandbox couldn't start on this host.** bwrap failed with "RTM_NEWADDR: Operation not permitted" because Ubuntu 24.04 restricts unprivileged user namespaces. Expect the same on many users' Linux machines.+- **For Mac "local" mode:** it's a good hardening layer (Seatbelt works, plus `denyRead` on `~/.claude`, `~/.codex`, `~/.grok` and the Keychain). It is not a substitute for the broker. Recommend it as a separate small follow-up.++**Q7 First slice.** Opt-in setting, vm mode only, Claude only, off by default, Linux hosts first.+- **Backend, about 7 days (Lin):**+ - broker in Rust: hyper on a UnixListener, the route table, inject and refresh, logs hashed only; 2.5 d+ - agent image + build in CI; 1 d+ - `cli.rs` runs `docker exec` with the dummy env when the setting is on, and `computer.rs` adds `cli_agents` to `VM_ISOLATES`; 1.5 d+ - uid and chown for checkpoints, and container lifecycle via `sandbox/manager.rs`; 1 d+ - tests, including `adversarial.sh` ported to an integration test; 1 d+- **Frontend, about 1 day (Pixel):**+ - in Settings › Computer, under vm mode, one toggle, "Run Claude inside the VM too", with the hint "Your Claude sign-in stays on this computer; the bot only gets a stand-in."+ - a status chip: Isolated / Not isolated (shown for Codex and Grok until they ship)+ - an error state for "Docker not available"+ - Mira: one review of the copy+- **QA, about 1 day (Rigel):** run `adversarial.sh` and a real-key smoke test on Linux and Docker Desktop.++## Risks+- The bot can still spend the person's tokens: the broker hides the key, it doesn't ration it. Slice 1 caps each+ reply at 200 model requests (configurable), then answers 429 with `x-should-retry: false`; a day of replies is not capped.+- **Refresh ownership.** A Claude OAuth refresh token is single-use: when two processes refresh the same sign-in, the+ loser's next refresh fails and the person has to sign in again. While isolation is on, the broker must be the only+ refresher of a bot's sign-in home. It refreshes single-flight under a per-file lock inside kwnt, re-reads the file under that lock+ (so a token another process already rotated is used, not refreshed again) and writes it atomically at 0600. It never+ refreshes this computer's own `~/.claude` sign-in, which host Claude (and the person's own terminal) also refresh:+ when that one has expired, the reply stops with `sign_in_expired` and the person signs in on this computer.+ Residual risk: a host-mode turn of the same bot profile running at the same time could still refresh in parallel;+ the lock is inside kwnt (one per file), and the host CLI doesn't take it. Refresh was tested only against the mock, never with+ the team's real sign-ins (by rule).+- The OAuth refresh endpoint and the Codex and Grok side endpoints are private CLI internals and can change with any CLI release. Pin versions and keep a CI smoke test against the real CLIs with the mock.+- On a Mac, Claude keeps its credentials in the Keychain, so the broker needs a Keychain read (one permission prompt) or kwant's own sign-in.+- Docker Desktop socket forwarding is unproven, and so is the image size on slow links (about 860 MB on disk for the+ slice-1 image, built locally from the executor image plus one pinned Claude Code).+- Files written by the container uid need ownership fixed on the host.++## Still unproven+Proven since Gate 0 (2026-11-08): a real Claude turn and a `--resume` turn with an API key, through the Python spike broker+and through kwnt's Rust broker (`tests/agents_in_vm_real_api_test.rs`, runs only with `KWNT_GATE0_KEY_FILE`).+Still unproven: a Claude sign-in (OAuth) against the real API, and token refresh (never tested with the team's sign-ins on+this server). Long-session compaction (`count_tokens` is refused until it's seen). The approval round trip end to end.+Mac and Docker Desktop. A full Grok turn, and Grok sign-in inference. Refresh for ChatGPT and Grok. The allow-list CONNECT+proxy. The Claude sandbox's read policy in practice.++## Open questions for Oleks+1. Ship the first slice for Linux only and add Mac after a Docker Desktop test on your Mac? *Default: yes.*+2. Is a 421 MB one-time image pull acceptable, or should the CLIs download on first use? *Default: ship in the image.*+3. Should vm mode's isolated Claude become the default once proven, or stay opt-in? *Default: opt-in for 0.7.7.*++## Slice 1 as built (branch `lin-078-agents-in-vm`)++Rust, in `src/sandbox/agent_vm/` (broker, folder rule, notices, VM), wired in `drivers/cli.rs`, `server/computer.rs`+and `sandbox/manager.rs`. Off by default, Claude sign-ins only, Linux only. User-facing summary and error codes:+`docs/agents-in-vm.md`. Binding decisions D1-D5 from Ada's review are implemented as written there; the PR lists the+field names, statuses, error codes and the host git calls.++## Gate 0: the real API++`proto/agents-in-vm/gate0.sh` runs the spike broker against `https://api.anthropic.com` with Haiku: a normal turn, a+`--resume` turn and one Bash tool call (about six calls; it took four), with `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1` and+`DISABLE_AUTOUPDATER=1`. It writes `evidence/real-upstream.txt`: every (method, path, status) the CLI sent, denied ones+included, with hashes only, plus the tool types and `anthropic-beta` values seen and the container's peak memory.++**Status: passed, 2026-11-08 16:30 UTC** (CLI 2.1.316, `claude-haiku-5-5`, API-key mode, Oleks's key).++| Turn | Result | Calls |+|---|---|---|+| 1, normal | success, reply "gate0 ok" | 1 |+| 2, `--resume` | success, recalled turn 1's reply | 1 |+| 3, Bash tool | success; `probe.txt` written in the folder, owned by the host uid:gid (1003:1003) | 2 |++- **Calls.** 4 in all, every one `POST /anthropic/v1/messages?beta=true` → 200. No other path, no other host+ (the proxy variables point at the broker, so a call elsewhere would have been logged as a refused `CONNECT`), no+ `count_tokens`, no telemetry.+- **Derived.** `ANTHROPIC_ALLOWED` is now only `POST /v1/messages` (`count_tokens` is dropped: never seen).+ `ALLOWED_TOOL_TYPES` stays `["custom"]` (the only type seen; 11 tools per call). `KNOWN_BETAS` is the 9 values+ seen (`advanced-tool-use-2025-11-20`, `claude-code-20250219`, `context-management-2025-06-27`,+ `effort-2025-11-24`, `interleaved-thinking-2025-05-14`, `mid-conversation-tool-changes-2026-07-01`,+ `per-turn-control-2026-07-01`, `thinking-display-updates-2026-08-18`, `thinking-token-count-2026-05-13`) plus+ `oauth-2025-04-20`, which only a Claude sign-in sends. The forwarded-header list dropped `x-client-request-id`+ (never sent). The broker test `the_anthropic_lists_match_the_gate_0_evidence` fails if the lists and the+ evidence drift apart.+- **Body.** Top-level keys seen: `context_management, max_tokens, messages, metadata, model, output_config, stream,+ system, thinking, tools`; content blocks `text, tool_use, tool_result`. No `mcp_servers`, no `container`, no+ server tool, so the broker's 400s cost nothing.+- **Memory.** The container's `memory.peak` over the three turns was 124.5 MiB, far under 716.8 MB (70% of 1024), so+ `memory_mb` stays 1024.+- **Key.** The only copy the script made (the spike broker's 0600 creds file) was shredded on exit. A scan of the+ worktree, the logs, this folder and the branch's git history for the key or its first or last 24 characters+ found nothing, and it never appeared in the process list.+- **Not covered:** a Claude sign-in (OAuth) turn and the broker's refresh against the real token endpoint (we don't+ refresh-test with the team's sign-ins on this server), and long sessions that compact.++## Mac (design only, not in slice 1)++Settings shows the switch disabled with "Coming to Mac later". What a Mac version needs:++- **Docker Desktop.** Bind-mounting the broker's Unix socket into a container goes through Docker Desktop's file+ sharing (virtiofs). Unproven. If it fails: publish a loopback-only TCP port for the broker and give each container+ a per-turn shared secret in the URL path (the `/t/<key>/` prefix already does this), never a credential.+- **Sign-in source.** Claude keeps its Mac sign-in in the Keychain ("Claude Code-credentials"), not in+ `~/.claude/.credentials.json`. The broker reads it with one Keychain prompt the person approves, or uses a kwnt-owned+ sign-in home per bot profile (preferred: no Keychain access, and the broker owns refresh as on Linux).+- **Ownership.** Docker Desktop maps file ownership itself, so `--user uid:gid` is not needed for files to land as the+ person; it still keeps the CLI non-root.+- **Image.** arm64 and x86_64 builds of the same pinned CLI; the agent image is built locally from the executor image,+ as on Linux.+- **Hardening for Mac "local" mode** (separate follow-up, no broker): Claude's Seatbelt sandbox plus `denyRead` on+ `~/.claude`, `~/.codex`, `~/.grok` and the Keychain. It doesn't keep the token from the CLI process itself.+- **Test before shipping:** the adversarial test and Gate 0 on Oleks's Mac with Docker Desktop.diff --git a/proto/agents-in-vm/Dockerfile.agent b/proto/agents-in-vm/Dockerfile.agentnew file mode 100644index 00000000..c05c520f--- /dev/null+++ b/proto/agents-in-vm/Dockerfile.agent@@ -0,0 +1,6 @@+# Spike image: kwnt-executor + socat + the three CLIs as native binaries (no Node needed).+FROM kwnt-executor:v1+RUN apt-get update && apt-get install -y --no-install-recommends socat && rm -rf /var/lib/apt/lists/*+COPY --chmod=755 claude codex grok /usr/local/bin/+COPY --chmod=755 entry.sh /usr/local/bin/kwnt-entry+CMD ["/usr/local/bin/kwnt-entry"]diff --git a/proto/agents-in-vm/adversarial.sh b/proto/agents-in-vm/adversarial.shnew file mode 100755index 00000000..ba9c6a92--- /dev/null+++ b/proto/agents-in-vm/adversarial.sh@@ -0,0 +1,41 @@+#!/usr/bin/env bash+# One command: proto/agents-in-vm/adversarial.sh (KEEP=1 leaves the spike running)+# Starts the spike fresh, runs probe.sh inside the container twice (a plain shell, and the+# agent's own Bash tool driven by the scripted mock model through the broker), checks the+# positive control (the real token DID reach the upstream), then removes everything.+set -uo pipefail+HERE=$(cd "$(dirname "$0")" && pwd); RUN="$HERE/run"+"$HERE/up.sh" || exit 1+cp "$HERE/probe.sh" "$RUN/sock/probe.sh"+HP="$HOME/.claude/.credentials.json $HOME/.codex/auth.json $HOME/.grok/auth.json $RUN/host/signin-home/.claude/.credentials.json $RUN/host/creds.json $RUN/host/upstream_state.json"+fail=0+echo "### A. plain shell in the container (docker exec)"+docker exec -e HOST_PATHS="$HP" kwnt-proto-lin-agent bash /run/kwnt/probe.sh | tee "$RUN/probe-shell.txt"+grep -q '^PROBE_LEAKS=0$' "$RUN/probe-shell.txt" || fail=1+echo "### B. the agent's own Bash tool, mid-turn (claude in the container, real token at the broker)"+"$HERE/turn.sh" api "RUN: HOST_PATHS='$HP' bash /run/kwnt/probe.sh" > "$RUN/probe-agent.jsonl" 2>&1+python3 - "$RUN/host/upstream.log" > "$RUN/probe-agent.txt" <<'P'+import json, sys+for line in open(sys.argv[1]):+ r = json.loads(line)+ for t in r.get("tool_result", []):+ print(t.split("<system-reminder>")[0].rstrip())+P+cat "$RUN/probe-agent.txt"+grep -q '^PROBE_LEAKS=0$' "$RUN/probe-agent.txt" || { echo "agent probe did not report PROBE_LEAKS=0"; fail=1; }+echo "### C. positive control: the real key reached the upstream, the dummy never did"+real=$(jq -r 'select(.path|startswith("/v1/messages")) | .auth' "$RUN/host/upstream.log" | sort | uniq -c)+echo "$real"+echo "$real" | grep -q api_key_ok || { echo "real key never arrived upstream"; fail=1; }+echo "$real" | grep -q rejected && { echo "a dummy reached the upstream"; fail=1; }+grep -q 'kwnt-dummy' "$RUN/host/upstream.log" && { echo "dummy credential seen upstream"; fail=1; }+denied=$(jq -r 'select(.decision|startswith("deny")) | "\(.decision) \(.method) \(.path)"' "$RUN/host/broker.log")+echo "broker denials:"; echo "$denied" | sed 's/^/ /'+echo "### D. self-test: the probe does catch a planted token (expects leaks)"+docker exec -e HOST_PATHS="$HP" -e PLANTED="sk-ant-api03-REAL""CANARY-planted" kwnt-proto-lin-agent \+ sh -c 'echo "$PLANTED" > /tmp/planted; bash /run/kwnt/probe.sh' > "$RUN/probe-selftest.txt"+grep '^LEAK' "$RUN/probe-selftest.txt" | sed 's/^/ /'+grep -q '^PROBE_LEAKS=[1-9]' "$RUN/probe-selftest.txt" || { echo "self-test: probe missed a planted token"; fail=1; }+[ "${KEEP:-0}" = 1 ] || "$HERE/down.sh"+[ $fail = 0 ] && echo "RESULT: PASS (all three attacks failed in both paths)" || echo "RESULT: FAIL"+exit $faildiff --git a/proto/agents-in-vm/bench.sh b/proto/agents-in-vm/bench.shnew file mode 100755index 00000000..704ed032--- /dev/null+++ b/proto/agents-in-vm/bench.sh@@ -0,0 +1,25 @@+#!/usr/bin/env bash+# One-turn latency against the mock: claude on the host vs in a warm container vs a cold one.+set -euo pipefail+HERE=$(cd "$(dirname "$0")" && pwd); RUN="$HERE/run"+"$HERE/up.sh" >/dev/null+KEY=$(jq -r .anthropic.api_key "$RUN/host/creds.json")+ms() { local s=$(date +%s%N); "$@" >/dev/null 2>&1; echo $(( ($(date +%s%N) - s) / 1000000 )); }+host_turn() {+ HOME_T=$(mktemp -d /tmp/kwnt-proto-lin-host.XXXX)+ (cd "$RUN/task" && HOME=$HOME_T CLAUDE_CONFIG_DIR=$HOME_T/.claude ANTHROPIC_BASE_URL=http://127.0.0.1:19471 \+ ANTHROPIC_API_KEY=$KEY CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 DISABLE_AUTOUPDATER=1 \+ timeout 60 claude --model claude-sonnet-4-5 --permission-mode default --strict-mcp-config \+ --output-format stream-json --verbose -p "bench" </dev/null)+ rm -rf "$HOME_T"+}+cold() {+ docker rm -f kwnt-proto-lin-agent >/dev/null+ docker run -d --name kwnt-proto-lin-agent --network none --user "$(id -u):$(id -g)" --cap-drop ALL \+ --security-opt no-new-privileges --read-only --tmpfs /tmp:rw,size=256m --cpus 2 --memory 1536m \+ -e HOME=/home/agent -v "$RUN/task:/workspace:rw" -v "$RUN/home:/home/agent:rw" -v "$RUN/sock:/run/kwnt:ro" \+ kwnt-proto-lin-agent:spike >/dev/null+ for _ in $(seq 100); do docker exec kwnt-proto-lin-agent bash -c "exec 3<>/dev/tcp/127.0.0.1/8080" 2>/dev/null && break; sleep 0.05; done+ "$HERE/turn.sh" api "bench"+}+for i in $(seq ${N:-5}); do echo "host $(ms host_turn) warm $(ms "$HERE/turn.sh" api bench) cold $(ms cold)"; donediff --git a/proto/agents-in-vm/broker.py b/proto/agents-in-vm/broker.pynew file mode 100644index 00000000..a519bc66--- /dev/null+++ b/proto/agents-in-vm/broker.py@@ -0,0 +1,243 @@+#!/usr/bin/env python3+"""Throwaway credential broker for the agents-in-vm spike (Lin, 2026-11-08).++Listens on a Unix socket that is bind-mounted into a `--network none` container.+The CLI inside talks plain HTTP to 127.0.0.1:8080 (socat) -> this socket.++Per request:+ * route by prefix (/anthropic, /openai, /chatgpt, /xai, /mcp); anything else -> 403+ * per route, an allow-list of (method, path) -> anything else -> 403+ * drop whatever credential the container sent (it is a dummy) and add the real one,+ read from a host-only file on every request (so a host-side refresh is picked up)+ * OAuth: refresh on the host when near expiry, or once on a 401, then retry+Tokens are never logged; the log carries sha256 prefixes only.++The real design builds this in Rust inside kwnt; see design.md.+"""+import hashlib, http.client, json, os, re, socketserver, ssl, sys, threading, time+from http.server import BaseHTTPRequestHandler++SOCK, CREDS, LOG, UPSTREAM = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]+# A port number is the local mock; "https://api.anthropic.com" is Gate 0 (the real API, the+# /anthropic route only, API-key mode only: no refresh is ever attempted against it).+REAL = UPSTREAM.startswith("https://")+UPSTREAM_PORT = 443 if REAL else int(UPSTREAM)+lock, refresh_lock = threading.Lock(), threading.Lock()+HOP = {"connection", "keep-alive", "proxy-connection", "transfer-encoding", "upgrade", "te",+ "trailer", "host", "content-length", "authorization", "x-api-key", "chatgpt-account-id"}+# route prefix -> (upstream host, port, path prefix upstream, allowed (method, regex))+ROUTES = {+ "/anthropic": ("127.0.0.1", UPSTREAM_PORT, "", [+ ("POST", r"/v1/messages(\?.*)?"), ("POST", r"/v1/messages/count_tokens(\?.*)?")]),+ "/openai": ("127.0.0.1", UPSTREAM_PORT, "/openai", [+ ("POST", r"/v1/responses(\?.*)?"), ("GET", r"/v1/models(\?.*)?")]),+ "/chatgpt": ("127.0.0.1", UPSTREAM_PORT, "/chatgpt", [+ ("POST", r"/backend-api/codex/responses(\?.*)?"), ("GET", r"/backend-api/codex/models(\?.*)?")]),+ "/xai": ("127.0.0.1", UPSTREAM_PORT, "/xai", [+ ("POST", r"/v1/(chat/completions|responses|messages)(\?.*)?"), ("GET", r"/v1/models(\?.*)?")]),+ # kwant's MCP gateway: the bot's own per-turn gateway token passes through untouched+ "/mcp": ("127.0.0.1", UPSTREAM_PORT, "/mcp", [("POST", r"(\?.*)?"), ("GET", r"(\?.*)?"),+ ("DELETE", r"(\?.*)?")]),+}+if REAL:+ ROUTES = {"/anthropic": (UPSTREAM.removeprefix("https://").rstrip("/"), 443, "", ROUTES["/anthropic"][3])}++def h8(s):+ return hashlib.sha256(s.encode()).hexdigest()[:8] if s else "-"++def scrub(path):+ """Path for the log: long or id-like segments become sha8 so nothing secret is written."""+ p, _, q = path.partition("?")+ segs = [("h:" + h8(x)) if len(x) > 24 or re.search(r"[0-9a-f]{8}-|[A-Za-z0-9_-]{20,}", x) else x+ for x in p.split("/")]+ return "/".join(segs) + (("?" + "&".join(k.split("=")[0] + ("=" + v if len(v) <= 12 else "=h:" + h8(v))+ for k, _, v in (kv.partition("=") for kv in q.split("&"))))+ if q else "")++def log(rec):+ rec["t"] = round(time.time(), 3)+ rec["path"] = scrub(rec.get("path", ""))+ with lock, open(LOG, "a") as f:+ f.write(json.dumps(rec) + "\n")++def creds():+ with open(CREDS) as f:+ return json.load(f)++def save_creds(c):+ tmp = CREDS + ".tmp"+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ with os.fdopen(fd, "w") as f:+ json.dump(c, f)+ os.replace(tmp, CREDS)++def refresh(seen_access):+ """Host-side refresh. Single flight: a second caller that sees a newer token skips."""+ with refresh_lock:+ c = creds()+ o = c["anthropic"]["oauth"]+ if o["accessToken"] != seen_access:+ return "already_refreshed"+ conn = http.client.HTTPConnection("127.0.0.1", UPSTREAM_PORT, timeout=30)+ conn.request("POST", "/v1/oauth/token", json.dumps(+ {"grant_type": "refresh_token", "refresh_token": o["refreshToken"], "client_id": "spike"}),+ {"content-type": "application/json"})+ r = conn.getresponse()+ body = json.loads(r.read() or b"{}")+ if r.status != 200:+ return f"refresh_failed_{r.status}"+ o["accessToken"], o["refreshToken"] = body["access_token"], body["refresh_token"]+ o["expiresAt"] = int((time.time() + body["expires_in"]) * 1000)+ save_creds(c)+ return "refreshed"++def inject(route, headers, rec):+ """Returns the real credential headers for this route, or an error string."""+ c = creds()+ if route == "/anthropic":+ a = c["anthropic"]+ if REAL and a["mode"] != "api_key":+ return "gate 0 runs in api-key mode only"+ sent_bearer = headers.get("authorization", "").startswith("Bearer ")+ sent_key = bool(headers.get("x-api-key"))+ if a["mode"] == "api_key":+ if not sent_key:+ return "container must use the api-key dummy for this profile"+ return {"x-api-key": a["api_key"]}+ if not sent_bearer:+ return "container must use the oauth dummy for this profile"+ o = a["oauth"]+ if o["expiresAt"] / 1000 - time.time() < 60:+ rec["pre_refresh"] = refresh(o["accessToken"])+ o = creds()["anthropic"]["oauth"]+ return {"authorization": "Bearer " + o["accessToken"]}+ if route == "/openai":+ return {"authorization": "Bearer " + c["openai"]["api_key"]}+ if route == "/chatgpt":+ g = c["chatgpt"]+ return {"authorization": "Bearer " + g["access_token"], "chatgpt-account-id": g["account_id"]}+ if route == "/xai":+ return {"authorization": "Bearer " + c["xai"]["api_key"]}+ return {}++class H(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"+ def log_message(self, *a):+ pass+ def address_string(self):+ return "unix"++ def handle_any(self):+ if "chunked" in (self.headers.get("transfer-encoding") or "").lower():+ body = b"" # codex streams its request body chunked+ while True:+ size = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16)+ if size == 0:+ while self.rfile.readline() not in (b"\r\n", b"\n", b""):+ pass+ break+ body += self.rfile.read(size)+ self.rfile.readline()+ else:+ n = int(self.headers.get("content-length") or 0)+ body = self.rfile.read(n) if n else None+ route = next((p for p in ROUTES if self.path == p or self.path.startswith(p + "/")+ or self.path.startswith(p + "?")), None)+ sent_auth = self.headers.get("authorization", "") or self.headers.get("x-api-key", "")+ rec = {"method": self.command, "path": self.path, "route": route, "sent_cred_sha": h8(sent_auth)}+ if route is None:+ rec["decision"], rec["status"] = "deny_route", 403+ log(rec)+ return self.reply(403, {"error": "kwnt broker: host not allowed"})+ host, port, up_prefix, allowed = ROUTES[route]+ rest = self.path[len(route):] or ""+ if route == "/anthropic":+ # Gate 0 evidence: what the CLI asks for, never a value that could hold a secret+ rec["header_names"] = sorted({k.lower() for k in self.headers.keys()})+ rec["betas"] = sorted({b.strip() for v in self.headers.get_all("anthropic-beta") or [] for b in v.split(",") if b.strip()})+ rec["anthropic_version"] = self.headers.get("anthropic-version")+ try:+ j = json.loads(body or b"null")+ except ValueError:+ j = None+ if isinstance(j, dict):+ rec["body_keys"] = sorted(j)+ rec["model"] = j.get("model")+ rec["stream"] = j.get("stream")+ tools = j.get("tools") if isinstance(j.get("tools"), list) else []+ rec["tool_types"] = sorted({t.get("type", "custom") for t in tools if isinstance(t, dict)})+ rec["tool_count"] = len(tools)+ rec["block_types"] = sorted({b.get("type") for m in j.get("messages") or [] if isinstance(m, dict)+ for b in (m.get("content") if isinstance(m.get("content"), list) else [])+ if isinstance(b, dict)})+ if not any(m == self.command and re.fullmatch(rx, rest) for m, rx in allowed):+ rec["decision"], rec["status"] = "deny_path", 403+ log(rec)+ return self.reply(403, {"error": "kwnt broker: path not allowed"})+ for attempt in (1, 2):+ hdrs = {k: v for k, v in self.headers.items() if k.lower() not in HOP}+ if route == "/mcp":+ if self.headers.get("authorization"):+ hdrs["authorization"] = self.headers["authorization"]+ else:+ real = inject(route, self.headers, rec)+ if isinstance(real, str):+ rec["decision"] = "deny_cred_kind"+ log(rec)+ return self.reply(409, {"error": real})+ hdrs.update(real)+ rec["real_cred_sha"] = h8(real.get("authorization") or real.get("x-api-key") or "")+ if body is not None:+ hdrs["content-length"] = str(len(body))+ conn = (http.client.HTTPSConnection(host, port, timeout=600, context=ssl.create_default_context())+ if REAL else http.client.HTTPConnection(host, port, timeout=600))+ conn.request(self.command, up_prefix + rest, body=body, headers=hdrs)+ r = conn.getresponse()+ if (r.status == 401 and route == "/anthropic" and attempt == 1 and not REAL+ and creds()["anthropic"]["mode"] == "oauth"):+ r.read()+ rec["on_401"] = refresh(hdrs["authorization"].removeprefix("Bearer "))+ continue+ break+ rec["decision"] = "forward"+ rec["status"] = r.status+ log(rec)+ self.send_response(r.status)+ for k, v in r.getheaders():+ if k.lower() not in HOP:+ self.send_header(k, v)+ self.send_header("transfer-encoding", "chunked")+ self.end_headers()+ while True:+ chunk = r.read1(65536)+ if not chunk:+ break+ self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk))+ self.wfile.flush()+ self.wfile.write(b"0\r\n\r\n")++ def reply(self, code, obj):+ data = json.dumps(obj).encode()+ self.send_response(code)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ do_GET = do_POST = do_DELETE = do_PUT = do_PATCH = do_HEAD = do_OPTIONS = handle_any++ def do_CONNECT(self):+ # Gate 0 points HTTPS_PROXY here, so a CLI call to any other host shows up (and is denied).+ log({"method": "CONNECT", "path": self.path, "route": None, "decision": "deny_route",+ "status": 403, "sent_cred_sha": "-"})+ self.reply(403, {"error": "kwnt broker: host not allowed"})++class S(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):+ daemon_threads = True++if os.path.exists(SOCK):+ os.unlink(SOCK)+old = os.umask(0o177)+srv = S(SOCK, H)+os.umask(old)+srv.serve_forever()diff --git a/proto/agents-in-vm/build.sh b/proto/agents-in-vm/build.shnew file mode 100755index 00000000..adddc7fc--- /dev/null+++ b/proto/agents-in-vm/build.sh@@ -0,0 +1,11 @@+#!/usr/bin/env bash+# Builds kwnt-proto-lin-agent:spike from the host's installed CLI binaries.+set -euo pipefail+HERE=$(cd "$(dirname "$0")" && pwd)+CTX=$(mktemp -d /tmp/kwnt-proto-lin-ctx.XXXX)+trap 'rm -rf "$CTX"' EXIT+cp "$(readlink -f /home/maus/.openmausbot/tools/npm/bin/claude)" "$CTX/claude"+cp /home/maus/.local/lib/node_modules/@openai/codex/node_modules/@openai/codex-linux-arm64/vendor/aarch64-unknown-linux-musl/bin/codex "$CTX/codex"+cp "$(readlink -f /home/maus/.grok/bin/grok)" "$CTX/grok"+cp "$HERE/Dockerfile.agent" "$HERE/entry.sh" "$CTX/"+docker build -q -t kwnt-proto-lin-agent:spike -f "$CTX/Dockerfile.agent" "$CTX"diff --git a/proto/agents-in-vm/down.sh b/proto/agents-in-vm/down.shnew file mode 100755index 00000000..4c514af0--- /dev/null+++ b/proto/agents-in-vm/down.sh@@ -0,0 +1,7 @@+#!/usr/bin/env bash+# Removes every kwnt-proto-lin-* container and network and stops the mock and broker.+HERE=$(cd "$(dirname "$0")" && pwd)+for c in $(docker ps -aq --filter name=^kwnt-proto-lin-); do docker rm -f "$c" >/dev/null; done+for n in $(docker network ls -q --filter name=^kwnt-proto-lin-); do docker network rm "$n" >/dev/null; done+for p in "$HERE"/run/host/*.pid; do [ -f "$p" ] && kill "$(cat "$p")" 2>/dev/null; rm -f "$p"; done+echo "down: $(docker ps -a --filter name=^kwnt-proto-lin- -q | wc -l) containers, $(docker network ls --filter name=^kwnt-proto-lin- -q | wc -l) networks left"diff --git a/proto/agents-in-vm/entry.sh b/proto/agents-in-vm/entry.shnew file mode 100755index 00000000..4b1a5d23--- /dev/null+++ b/proto/agents-in-vm/entry.sh@@ -0,0 +1,5 @@+#!/bin/sh+# In-container forwarder: the CLIs speak plain HTTP to 127.0.0.1:8080, which is the only+# way out: a Unix socket the host bind-mounts at /run/kwnt/broker.sock.+socat TCP-LISTEN:8080,bind=127.0.0.1,fork,reuseaddr UNIX-CONNECT:/run/kwnt/broker.sock &+exec sleep infinitydiff --git a/proto/agents-in-vm/evidence/adversarial-run.txt b/proto/agents-in-vm/evidence/adversarial-run.txtnew file mode 100644index 00000000..b09225dd--- /dev/null+++ b/proto/agents-in-vm/evidence/adversarial-run.txt@@ -0,0 +1,72 @@+up: container kwnt-proto-lin-agent, broker /home/maus/work/lin-078-agents-in-vm/proto/agents-in-vm/run/sock/broker.sock, mock 127.0.0.1:19471+### A. plain shell in the container (docker exec)+== 1. read the host sign-in files+ok read /home/maus/.claude/.credentials.json -> No such file or directory+ok read /home/maus/.codex/auth.json -> No such file or directory+ok read /home/maus/.grok/auth.json -> No such file or directory+ok read /home/maus/work/lin-078-agents-in-vm/proto/agents-in-vm/run/host/signin-home/.claude/.credentials.json -> No such file or directory+ok read /home/maus/work/lin-078-agents-in-vm/proto/agents-in-vm/run/host/creds.json -> No such file or directory+ok read /home/maus/work/lin-078-agents-in-vm/proto/agents-in-vm/run/host/upstream_state.json -> No such file or directory+ok read /root/.claude/.credentials.json -> Permission denied+ok read /root/.codex/auth.json -> Permission denied+ok no sign-in file anywhere in the container+== 2. read the real token+ok env holds no real token (0 credential vars, all dummies)+ok no real token in any process env/cmdline (6 processes, incl. the running claude)+ok no real token in any file (rootfs, /workspace, /home/agent, /run/kwnt, /tmp)+ok broker /anthropic/v1/oauth/token -> 403+ok broker /anthropic/v1/files -> 403+ok broker /chatgpt/backend-api/accounts -> 403+ok broker /admin -> 403+== 3. reach an outside host+ok https://example.com -> curl rc=6 http=000+ok http://1.1.1.1 -> curl rc=7 http=000+ok http://172.17.0.1:22 -> curl rc=7 http=000+ok http://host.docker.internal -> curl rc=6 http=000+ok http://127.0.0.1:8080/https://example.com -> curl rc=0 http=403+PROBE_LEAKS=0+### B. the agent's own Bash tool, mid-turn (claude in the container, real token at the broker)+== 1. read the host sign-in files+ok read /home/maus/.claude/.credentials.json -> No such file or directory+ok read /home/maus/.codex/auth.json -> No such file or directory+ok read /home/maus/.grok/auth.json -> No such file or directory+ok read /home/maus/work/lin-078-agents-in-vm/proto/agents-in-vm/run/host/signin-home/.claude/.credentials.json -> No such file or directory+ok read /home/maus/work/lin-078-agents-in-vm/proto/agents-in-vm/run/host/creds.json -> No such file or directory+ok read /home/maus/work/lin-078-agents-in-vm/proto/agents-in-vm/run/host/upstream_state.json -> No such file or directory+ok read /root/.claude/.credentials.json -> Permission denied+ok read /root/.codex/auth.json -> Permission denied+ok no sign-in file anywhere in the container+== 2. read the real token+ok env holds no real token (1 credential vars, all dummies)+ok no real token in any process env/cmdline (11 processes, incl. the running claude)+ok no real token in any file (rootfs, /workspace, /home/agent, /run/kwnt, /tmp)+ok broker /anthropic/v1/oauth/token -> 403+ok broker /anthropic/v1/files -> 403+ok broker /chatgpt/backend-api/accounts -> 403+ok broker /admin -> 403+== 3. reach an outside host+ok https://example.com -> curl rc=6 http=000+ok http://1.1.1.1 -> curl rc=7 http=000+ok http://172.17.0.1:22 -> curl rc=7 http=000+ok http://host.docker.internal -> curl rc=6 http=000+ok http://127.0.0.1:8080/https://example.com -> curl rc=0 http=403+PROBE_LEAKS=0+### C. positive control: the real key reached the upstream, the dummy never did+ 2 api_key_ok+broker denials:+ deny_path POST /anthropic/v1/oauth/token+ deny_path POST /anthropic/v1/files+ deny_path POST /chatgpt/backend-api/accounts+ deny_route POST /admin+ deny_route GET /https://example.com+ deny_path POST /anthropic/v1/oauth/token+ deny_path POST /anthropic/v1/files+ deny_path POST /chatgpt/backend-api/accounts+ deny_route POST /admin+ deny_route GET /https://example.com+### D. self-test: the probe does catch a planted token (expects leaks)+ LEAK token in env+ LEAK /proc: /proc/181/environ /proc/187/environ+ LEAK files: /tmp/planted+down: 0 containers, 0 networks left+RESULT: PASS (all three attacks failed in both paths)diff --git a/proto/agents-in-vm/evidence/bench.txt b/proto/agents-in-vm/evidence/bench.txtnew file mode 100644index 00000000..fa1a16ac--- /dev/null+++ b/proto/agents-in-vm/evidence/bench.txt@@ -0,0 +1,8 @@+bench.sh, 2026-11-08, arm64 Ubuntu 24.04 host, mock upstream, one `claude -p` turn (ms)+host (claude on host, no container): 737 735 703 701 708+warm (container already up, docker exec): 899 813 782 864 833 (+~110 ms vs host)+cold (docker rm + run + ready + turn): 1217 1156 1175 1165 1204 (+~460 ms vs host)+cold breakdown: rm 109, run 171, first exec 51, turn ~870+idle container memory: 3.4 MiB+image kwnt-proto-lin-agent:spike = kwnt-executor:v1 (376 MB) + socat + claude/codex/grok native binaries+ -> 1.46 GB on disk, 421 MB compressed; build 56 sdiff --git a/proto/agents-in-vm/evidence/q2-q3-q6-notes.md b/proto/agents-in-vm/evidence/q2-q3-q6-notes.mdnew file mode 100644index 00000000..34e51ac4--- /dev/null+++ b/proto/agents-in-vm/evidence/q2-q3-q6-notes.md@@ -0,0 +1,24 @@+# Spike notes not covered by adversarial.sh (run by hand 2026-11-08)++Q2 Codex 0.162.1+- Ignores OPENAI_BASE_URL (went to wss://api.openai.com). Works with a custom provider in CODEX_HOME/config.toml.+- API key: [model_providers.kwnt] base_url=http://127.0.0.1:8080/openai/v1, env_key=OPENAI_API_KEY (dummy), wire_api="responses"+ -> full turn, upstream logged openai_key_ok with the real key.+- ChatGPT sign-in: dummy auth.json (unsigned JWT id/access tokens, account acct-dummy) ++ [model_providers.kwntgpt] base_url=".../chatgpt/backend-api/codex", requires_openai_auth=true, wire_api="responses",+ chatgpt_base_url=".../chatgpt/backend-api/" -> full turn, upstream got real bearer + chatgpt-account-id acct-canary (chatgpt_ok).+- Broker denied codex side calls: plugins, wham/accounts/check, wham/settings/user, analytics-events, ps/mcp. Turn still completed.+Q2 Grok 1.0.62+- API key: XAI_API_KEY dummy + GROK_MODELS_BASE_URL + GROK_CLI_CHAT_PROXY_BASE_URL -> /xai/v1: upstream saw the real+ bearer on /models, /chat/completions, /responses. Mock speaks no xAI format, so no full turn.+- Sign-in: GROK_AUTH_PROVIDER_COMMAND="echo kwnt-dummy-session" -> dummy bearer sent to the overridden base for+ /user, /settings, /models, /bundle/archive, /subagents/bundle (all denied by the allow-list). Inference path not reached.+Q3+- --network none + bind-mounted unix socket + in-container socat: no DNS, no IP route, no host, forwarder 403s others.+- --internal network (kwnt-proto-lin-int): no DNS (rc 6), 1.1.1.1 rc 7, BUT the bridge gateway 172.19.0.1:22 was OPEN,+ so every host service bound to 0.0.0.0 is reachable. Rejected.+Q6+- codex sandbox -P :workspace / :read-only on this host: "bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"+ (Ubuntu 24.04 apparmor_restrict_unprivileged_userns=1). Codex's Linux sandbox cannot start here at all.+- claude 2.1.316 binary has sandbox keys denyRead/allowRead/denyWrite/allowWrite/allowUnsandboxedCommands/+ autoAllowBashIfSandboxed/enableWeakerNestedSandbox. Not run (no bwrap on host).diff --git a/proto/agents-in-vm/evidence/real-upstream.txt b/proto/agents-in-vm/evidence/real-upstream.txtnew file mode 100644index 00000000..cb7f4988--- /dev/null+++ b/proto/agents-in-vm/evidence/real-upstream.txt@@ -0,0 +1,30 @@+# Gate 0: Claude Code CLI against the real api.anthropic.com through the spike broker+# CLI 2.1.316 (native, aarch64) in --network none; ANTHROPIC_BASE_URL=http://127.0.0.1:8080/anthropic;+# HTTPS_PROXY/HTTP_PROXY also point at the broker so calls to any other host are logged (CONNECT) and denied.+# CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 DISABLE_AUTOUPDATER=1; --model haiku; API-key mode.+# real key sha8=79bf588b (injected by the broker); container credential = a dummy+# columns: turn method path(long/id-like parts hashed) status broker-decision sent-cred-sha8 injected-cred-sha8+1-normal POST /anthropic/v1/messages?beta=true 200 forward 75b6c1d4 79bf588b+2-resume POST /anthropic/v1/messages?beta=true 200 forward 75b6c1d4 79bf588b+3-bash POST /anthropic/v1/messages?beta=true 200 forward 75b6c1d4 79bf588b+3-bash POST /anthropic/v1/messages?beta=true 200 forward 75b6c1d4 79bf588b++# summary (method path status decision -> count)+# 4 POST /anthropic/v1/messages?beta=true 200 forward++# what the CLI sent on /anthropic (union over every call; names and types only, no values)+# anthropic_version: 2023-06-01+# model: claude-haiku-5-5+# stream: True+# betas: advanced-tool-use-2025-11-20, claude-code-20250219, context-management-2025-06-27, effort-2025-11-24, interleaved-thinking-2025-05-14, mid-conversation-tool-changes-2026-07-01, per-turn-control-2026-07-01, thinking-display-updates-2026-08-18, thinking-token-count-2026-05-13+# tool_types: custom+# block_types: text, tool_result, tool_use+# body_keys: context_management, max_tokens, messages, metadata, model, output_config, stream, system, thinking, tools+# header_names: accept, accept-encoding, anthropic-beta, anthropic-dangerous-direct-browser-access, anthropic-version, connection, content-length, content-type, host, user-agent, x-api-key, x-app, x-claude-code-session-id, x-stainless-arch, x-stainless-lang, x-stainless-os, x-stainless-package-version, x-stainless-retry-count, x-stainless-runtime, x-stainless-runtime-version, x-stainless-timeout+# tool_count per call: [11, 11, 11, 11]+# turn 1-normal: subtype=success is_error=False num_turns=1 result_sha8=12111762 result_len=8+# turn 2-resume: subtype=success is_error=False num_turns=1 result_sha8=12111762 result_len=8+# turn 3-bash: subtype=success is_error=False num_turns=2 result_sha8=b8f8777e result_len=10+# bash tool wrote probe.txt: 'gate0-bash'; file owner uid:gid 1003:1003 (host user 1003:1003)+# container memory.peak over the three turns: 130555904 bytes (124.5 MiB)+# calls forwarded upstream: 4; denied: 0diff --git a/proto/agents-in-vm/gate0.sh b/proto/agents-in-vm/gate0.shnew file mode 100755index 00000000..d9f922a3--- /dev/null+++ b/proto/agents-in-vm/gate0.sh@@ -0,0 +1,107 @@+#!/usr/bin/env bash+# Gate 0: the spike against the REAL api.anthropic.com, API-key mode, Haiku, three short turns+# (a normal turn, a --resume turn, one Bash tool call; about six calls in all).+# proto/agents-in-vm/gate0.sh [key file] (default /tmp/ada-claude-key/anthropic_api_key)+# The key is read once from that file into the broker's 0600 creds file, never printed or+# logged; every copy this script makes is shredded on exit. Writes evidence/real-upstream.txt:+# every (method, path, status) the CLI sent, denied ones included, with hashes only.+set -uo pipefail+HERE=$(cd "$(dirname "$0")" && pwd); RUN="$HERE/run-gate0"; KEYFILE=${1:-/tmp/ada-claude-key/anthropic_api_key}+C=kwnt-proto-lin-gate0+[ -r "$KEYFILE" ] || { echo "no key at $KEYFILE" >&2; exit 2; }+cleanup() {+ docker rm -f "$C" >/dev/null 2>&1+ [ -f "$RUN/host/broker.pid" ] && kill "$(cat "$RUN/host/broker.pid")" 2>/dev/null+ [ -f "$RUN/host/creds.json" ] && shred -u "$RUN/host/creds.json" 2>/dev/null; rm -f "$RUN/host/creds.json"+}+trap cleanup EXIT+rm -rf "$RUN"; mkdir -p "$RUN"/{host,sock,task,home}; chmod 700 "$RUN/host"+docker image inspect kwnt-proto-lin-agent:spike >/dev/null 2>&1 || "$HERE/build.sh"+# The broker's creds file: the only copy of the key this script makes (0600, shredded on exit).+( umask 077; python3 -I - "$KEYFILE" "$RUN/host/creds.json" <<'P'+import json, sys+key = open(sys.argv[1]).read().strip()+json.dump({"anthropic": {"mode": "api_key", "api_key": key}}, open(sys.argv[2], "w"))+P+)+KEYSHA=$(python3 -I -c 'import hashlib,json,sys;print(hashlib.sha256(json.load(open(sys.argv[1]))["anthropic"]["api_key"].encode()).hexdigest()[:8])' "$RUN/host/creds.json")+nohup python3 "$HERE/broker.py" "$RUN/sock/broker.sock" "$RUN/host/creds.json" "$RUN/host/broker.log" https://api.anthropic.com \+ > "$RUN/host/broker.out" 2>&1 &+echo $! > "$RUN/host/broker.pid"+for _ in $(seq 50); do [ -S "$RUN/sock/broker.sock" ] && break; sleep 0.1; done+echo "gate0 test file" > "$RUN/task/README.txt"+docker run -d --name "$C" --label kwnt.proto=lin \+ --network none --user "$(id -u):$(id -g)" --cap-drop ALL --security-opt no-new-privileges \+ --read-only --tmpfs /tmp:rw,size=256m --cpus 2 --memory 1536m --pids-limit 512 \+ -e HOME=/home/agent \+ -v "$RUN/task:/workspace:rw" -v "$RUN/home:/home/agent:rw" -v "$RUN/sock:/run/kwnt:ro" \+ kwnt-proto-lin-agent:spike >/dev/null || exit 1+for _ in $(seq 50); do docker exec "$C" bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080' 2>/dev/null && break; sleep 0.1; done+turn() { # turn <name> <prompt> [extra claude args...]+ local name=$1 prompt=$2; shift 2+ docker exec -i -w /workspace \+ -e HOME=/home/agent -e CLAUDE_CONFIG_DIR=/home/agent/.claude \+ -e ANTHROPIC_BASE_URL=http://127.0.0.1:8080/anthropic -e ANTHROPIC_API_KEY=sk-ant-api03-kwnt-dummy \+ -e CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 -e DISABLE_AUTOUPDATER=1 \+ -e HTTPS_PROXY=http://127.0.0.1:8080 -e HTTP_PROXY=http://127.0.0.1:8080 -e NO_PROXY=127.0.0.1,localhost \+ -e CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1 \+ "$C" claude --model haiku --permission-mode default --strict-mcp-config \+ --disallowedTools CronCreate,CronDelete,CronList,Task \+ --append-system-prompt "You are a kwant bot (Gate 0 check). Keep replies to one line." \+ --output-format stream-json --verbose --include-partial-messages "$@" -p "$prompt" \+ < /dev/null > "$RUN/$name.jsonl" 2> "$RUN/$name.err"+ local rc=$?+ echo "$(date -u +%H:%M:%S) $name rc=$rc result=$(jq -r 'select(.type=="result") | "\(.subtype) is_error=\(.is_error) turns=\(.num_turns)"' "$RUN/$name.jsonl" 2>/dev/null)"+ printf '%s\n' "$(date -u +%s.%N)" > "$RUN/host/mark-$name"+}+turn 1-normal "Reply with exactly: gate0 ok"+SID=$(jq -r 'select(.type=="system" and .subtype=="init") | .session_id' "$RUN/1-normal.jsonl" | head -1)+turn 2-resume "What exact words did you reply last time? One line." --resume "$SID"+turn 3-bash "Use the Bash tool to run: echo gate0-bash > probe.txt && cat probe.txt. Then reply with the output." --allowedTools Bash+BASH_OK=$(cat "$RUN/task/probe.txt" 2>/dev/null)+OWNER=$(stat -c '%u:%g' "$RUN/task/probe.txt" 2>/dev/null)+# Peak memory of the whole container over the three turns (cgroup v2), in bytes+CID=$(docker inspect -f '{{.Id}}' "$C")+PEAK=$(docker exec "$C" cat /sys/fs/cgroup/memory.peak 2>/dev/null || cat "/sys/fs/cgroup/system.slice/docker-$CID.scope/memory.peak" 2>/dev/null || echo unknown)+OUT="$HERE/evidence/real-upstream.txt"+python3 -I - "$RUN" "$KEYSHA" "$BASH_OK" "$OWNER" "$(id -u):$(id -g)" "$PEAK" > "$OUT" <<'P'+import collections, glob, json, os, sys+run, keysha, bash_ok, owner, me, peak = sys.argv[1:7]+recs = [json.loads(l) for l in open(f"{run}/host/broker.log")]+marks = sorted((float(open(m).read()), os.path.basename(m)[5:]) for m in glob.glob(f"{run}/host/mark-*"))+def turn_of(t):+ return next((n for end, n in marks if t <= end), "after")+print("# Gate 0: Claude Code CLI against the real api.anthropic.com through the spike broker")+print("# CLI 2.1.316 (native, aarch64) in --network none; ANTHROPIC_BASE_URL=http://127.0.0.1:8080/anthropic;")+print("# HTTPS_PROXY/HTTP_PROXY also point at the broker so calls to any other host are logged (CONNECT) and denied.")+print("# CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 DISABLE_AUTOUPDATER=1; --model haiku; API-key mode.")+print(f"# real key sha8={keysha} (injected by the broker); container credential = a dummy")+print("# columns: turn method path(long/id-like parts hashed) status broker-decision sent-cred-sha8 injected-cred-sha8")+for r in recs:+ print("\t".join(map(str, [turn_of(r["t"]), r["method"], r["path"], r.get("status", "-"), r["decision"],+ r.get("sent_cred_sha", "-"), r.get("real_cred_sha", "-")])))+print()+print("# summary (method path status decision -> count)")+for k, n in sorted(collections.Counter((r["method"], r["path"], r.get("status", "-"), r["decision"]) for r in recs).items()):+ print(f"# {n:3d} {' '.join(map(str, k))}")+print()+print("# what the CLI sent on /anthropic (union over every call; names and types only, no values)")+for field in ("anthropic_version", "model", "stream", "betas", "tool_types", "block_types", "body_keys", "header_names"):+ vals = set()+ for r in recs:+ v = r.get(field)+ vals.update(v if isinstance(v, list) else ([] if v is None else [v]))+ print(f"# {field}: {', '.join(sorted(map(str, vals))) or '-'}")+print(f"# tool_count per call: {[r.get('tool_count') for r in recs if 'tool_count' in r]}")+for n in ("1-normal", "2-resume", "3-bash"):+ res = [json.loads(l) for l in open(f"{run}/{n}.jsonl") if l.startswith("{")]+ fin = next((x for x in res if x.get("type") == "result"), {})+ print(f"# turn {n}: subtype={fin.get('subtype')} is_error={fin.get('is_error')} num_turns={fin.get('num_turns')} "+ f"result_sha8={__import__('hashlib').sha256(str(fin.get('result')).encode()).hexdigest()[:8]} result_len={len(str(fin.get('result') or ''))}")+print(f"# bash tool wrote probe.txt: {bash_ok!r}; file owner uid:gid {owner} (host user {me})")+print(f"# container memory.peak over the three turns: {peak} bytes" + (f" ({int(peak)/1048576:.1f} MiB)" if peak.isdigit() else ""))+print(f"# calls forwarded upstream: {sum(r['decision']=='forward' for r in recs)}; denied: {sum(r['decision'].startswith('deny') for r in recs)}")+P+echo "--- $OUT"; cat "$OUT"+for n in 1-normal 2-resume 3-bash; do echo "--- $n result"; jq -r 'select(.type=="result") | .result' "$RUN/$n.jsonl" | head -3; done+grep -l 'sk-ant-api03-[A-Za-z0-9_-]\{30,\}' "$RUN"/*.jsonl "$RUN"/*.err "$RUN/host/broker.log" "$OUT" 2>/dev/null && echo "WARNING: key-shaped string found" || echo "no key-shaped string in any output"diff --git a/proto/agents-in-vm/mock_upstream.py b/proto/agents-in-vm/mock_upstream.pynew file mode 100644index 00000000..220d7071--- /dev/null+++ b/proto/agents-in-vm/mock_upstream.py@@ -0,0 +1,245 @@+#!/usr/bin/env python3+"""Throwaway mock upstream for the agents-in-vm spike (Lin, 2026-11-08).++One HTTP server on 127.0.0.1 standing in for three things:+ /v1/messages[...] a scripted Anthropic Messages API (streaming SSE or JSON)+ /v1/oauth/token an OAuth refresh endpoint that rotates the access token+ /mcp kwant's MCP gateway with the `kwnt.approve` permission tool+Every request is logged as one JSON line (method, path, ALL headers, notes) so the+spike can show which credential actually arrived upstream.++Scripted model: if the newest user turn carries a tool_result, log it and answer+"done". If the prompt contains `RUN: <cmd>`, answer with a Bash tool_use for <cmd>.+Otherwise answer "mock reply #<n>, saw <k> messages".+"""+import json, os, sys, threading, time, uuid+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++STATE = sys.argv[2] # upstream_state.json: which credentials are valid+LOG = sys.argv[3]+PORT = int(sys.argv[1])+lock = threading.Lock()+counter = {"n": 0}++def state():+ with open(STATE) as f:+ return json.load(f)++def save_state(s):+ tmp = STATE + ".tmp"+ with open(tmp, "w") as f:+ json.dump(s, f)+ os.replace(tmp, STATE)++def log(rec):+ with lock, open(LOG, "a") as f:+ f.write(json.dumps(rec) + "\n")++def sse(events):+ out = b""+ for e in events:+ out += f"event: {e['type']}\ndata: {json.dumps(e)}\n\n".encode()+ return out++def text_of(block):+ if isinstance(block, str):+ return block+ if block.get("type") == "text":+ return block.get("text", "")+ if block.get("type") == "tool_result":+ c = block.get("content")+ return c if isinstance(c, str) else "".join(text_of(x) for x in (c or []))+ return ""++class H(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"+ def log_message(self, *a):+ pass++ def body(self):+ n = int(self.headers.get("content-length") or 0)+ return self.rfile.read(n) if n else b""++ def send(self, code, payload, ctype="application/json"):+ data = payload if isinstance(payload, bytes) else json.dumps(payload).encode()+ self.send_response(code)+ self.send_header("content-type", ctype)+ self.send_header("content-length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def do_GET(self):+ log({"method": "GET", "path": self.path, "headers": dict(self.headers)})+ self.send(405 if self.path.startswith("/mcp") else 404, {"error": "no"})++ def do_DELETE(self):+ log({"method": "DELETE", "path": self.path, "headers": dict(self.headers)})+ self.send(200, {})++ def do_POST(self):+ raw = self.body()+ rec = {"t": time.time(), "method": "POST", "path": self.path, "headers": dict(self.headers)}+ try:+ if self.path.startswith("/v1/oauth/token"):+ return self.oauth(raw, rec)+ if self.path.startswith("/mcp"):+ return self.mcp(raw, rec)+ if self.path.startswith("/v1/messages/count_tokens"):+ rec["auth"] = self.check_auth()+ log(rec)+ return self.send(200, {"input_tokens": 12})+ if self.path.startswith("/v1/messages"):+ return self.messages(raw, rec)+ if self.path.endswith("/responses") and (self.path.startswith("/openai/") or self.path.startswith("/chatgpt/")):+ return self.openai_responses(raw, rec)+ log(rec)+ self.send(404, {"error": "unknown"})+ except Exception as e: # keep the mock alive+ rec["error"] = repr(e)+ log(rec)+ self.send(500, {"error": repr(e)})++ def check_auth(self):+ s = state()+ key = self.headers.get("x-api-key")+ bearer = (self.headers.get("authorization") or "").removeprefix("Bearer ").strip()+ if key and key == s["api_key"]:+ return "api_key_ok"+ if bearer and bearer == s["access_token"]:+ return "oauth_ok"+ if bearer and bearer in s.get("expired_access_tokens", []):+ return "oauth_expired"+ return "rejected"++ def oauth(self, raw, rec):+ s = state()+ req = json.loads(raw or b"{}")+ rec["body"] = {k: ("<present>" if "token" in k else v) for k, v in req.items()}+ if req.get("grant_type") == "refresh_token" and req.get("refresh_token") == s["refresh_token"]:+ new_access = "sk-ant-oat01-REALCANARY-" + uuid.uuid4().hex+ new_refresh = "sk-ant-ort01-REALCANARY-" + uuid.uuid4().hex+ s.setdefault("expired_access_tokens", []).append(s["access_token"])+ s["access_token"], s["refresh_token"] = new_access, new_refresh+ save_state(s)+ rec["result"] = "rotated"+ log(rec)+ return self.send(200, {"access_token": new_access, "refresh_token": new_refresh,+ "expires_in": 3600, "token_type": "Bearer"})+ rec["result"] = "bad_refresh"+ log(rec)+ self.send(400, {"error": "invalid_grant"})++ def messages(self, raw, rec):+ req = json.loads(raw)+ auth = self.check_auth()+ rec["auth"] = auth+ rec["model"] = req.get("model")+ msgs = req.get("messages", [])+ rec["n_messages"] = len(msgs)+ rec["tools"] = [t.get("name") for t in req.get("tools", [])][:60]+ if auth != "api_key_ok" and auth != "oauth_ok":+ log(rec)+ msg = "OAuth token has expired" if auth == "oauth_expired" else "invalid x-api-key"+ return self.send(401, {"type": "error", "error": {"type": "authentication_error", "message": msg}})+ last = msgs[-1] if msgs else {"content": ""}+ content = last.get("content")+ blocks = content if isinstance(content, list) else [content]+ tool_results = [text_of(b) for b in blocks if isinstance(b, dict) and b.get("type") == "tool_result"]+ prompt = "".join(text_of(b) for b in blocks if not (isinstance(b, dict) and b.get("type") == "tool_result"))+ with lock:+ counter["n"] += 1+ n = counter["n"]+ tool = None+ if tool_results:+ rec["tool_result"] = tool_results+ reply = "done: tool ran"+ elif "RUN:" in prompt and "Bash" in rec["tools"]:+ cmd = prompt.split("RUN:", 1)[1].strip().splitlines()[0]+ tool = {"type": "tool_use", "id": "toolu_" + uuid.uuid4().hex[:20], "name": "Bash",+ "input": {"command": cmd, "description": "spike probe"}}+ rec["asked_tool"] = cmd+ reply = None+ else:+ reply = f"mock reply #{n}, saw {len(msgs)} messages"+ log(rec)+ model = req.get("model", "mock")+ mid = "msg_" + uuid.uuid4().hex[:20]+ usage = {"input_tokens": 10, "output_tokens": 5}+ if not req.get("stream"):+ c = [tool] if tool else [{"type": "text", "text": reply}]+ return self.send(200, {"id": mid, "type": "message", "role": "assistant", "model": model,+ "content": c, "stop_reason": "tool_use" if tool else "end_turn",+ "stop_sequence": None, "usage": usage})+ ev = [{"type": "message_start", "message": {"id": mid, "type": "message", "role": "assistant",+ "model": model, "content": [], "stop_reason": None, "stop_sequence": None, "usage": usage}}]+ if tool:+ ev += [{"type": "content_block_start", "index": 0,+ "content_block": {"type": "tool_use", "id": tool["id"], "name": "Bash", "input": {}}},+ {"type": "content_block_delta", "index": 0,+ "delta": {"type": "input_json_delta", "partial_json": json.dumps(tool["input"])}},+ {"type": "content_block_stop", "index": 0},+ {"type": "message_delta", "delta": {"stop_reason": "tool_use", "stop_sequence": None},+ "usage": {"output_tokens": 5}}]+ else:+ ev += [{"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": reply}},+ {"type": "content_block_stop", "index": 0},+ {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None},+ "usage": {"output_tokens": 5}}]+ ev.append({"type": "message_stop"})+ self.send(200, sse(ev), "text/event-stream")++ # --- OpenAI Responses API (codex): just enough SSE for one text reply ---+ def openai_responses(self, raw, rec):+ s = state()+ bearer = (self.headers.get("authorization") or "").removeprefix("Bearer ").strip()+ ok = bearer in (s.get("openai_key"), s.get("chatgpt_access"))+ rec["auth"] = ("openai_key_ok" if bearer == s.get("openai_key") else "chatgpt_ok") if ok else "rejected"+ rec["account"] = self.headers.get("chatgpt-account-id")+ log(rec)+ if not ok:+ return self.send(401, {"error": {"message": "bad key", "type": "invalid_request_error"}})+ rid = "resp_" + uuid.uuid4().hex[:12]+ ev = [{"type": "response.created", "response": {"id": rid}},+ {"type": "response.output_item.done", "item": {"type": "message", "role": "assistant", "id": "msg_1",+ "content": [{"type": "output_text", "text": "mock codex reply via " + rec["auth"]}]}},+ {"type": "response.completed", "response": {"id": rid, "usage": {"input_tokens": 10,+ "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 5,+ "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 15}}}]+ self.send(200, sse(ev), "text/event-stream")++ # --- kwant MCP gateway stand-in: streamable HTTP, JSON responses only ---+ def mcp(self, raw, rec):+ s = state()+ req = json.loads(raw)+ rec["rpc"] = req.get("method")+ rec["gateway_auth"] = (self.headers.get("authorization") or "") == "Bearer " + s["gateway_token"]+ if not rec["gateway_auth"]:+ log(rec)+ return self.send(401, {"error": "gateway token"})+ rid = req.get("id")+ m = req.get("method")+ if rid is None:+ log(rec)+ self.send_response(202); self.send_header("content-length", "0"); self.end_headers()+ return+ if m == "initialize":+ res = {"protocolVersion": req["params"].get("protocolVersion", "2025-06-18"),+ "capabilities": {"tools": {}}, "serverInfo": {"name": "kwnt", "version": "spike"}}+ elif m == "tools/list":+ res = {"tools": [{"name": "approve", "description": "kwant approval",+ "inputSchema": {"type": "object", "properties": {+ "tool_name": {"type": "string"}, "input": {"type": "object"},+ "tool_use_id": {"type": "string"}}, "required": ["tool_name", "input"]}}]}+ elif m == "tools/call":+ args = req["params"].get("arguments", {})+ rec["approval_request"] = {"tool_name": args.get("tool_name"), "input": args.get("input")}+ res = {"content": [{"type": "text", "text": json.dumps(+ {"behavior": "allow", "updatedInput": args.get("input", {})})}]}+ else:+ res = {}+ log(rec)+ self.send(200, {"jsonrpc": "2.0", "id": rid, "result": res})++ThreadingHTTPServer.daemon_threads = True+ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()diff --git a/proto/agents-in-vm/probe.sh b/proto/agents-in-vm/probe.shnew file mode 100755index 00000000..b45ca091--- /dev/null+++ b/proto/agents-in-vm/probe.sh@@ -0,0 +1,42 @@+#!/usr/bin/env bash+# Runs INSIDE the agent container, as the bot would: tries the three attacks.+# Prints one line per attempt: "ok <what>" when the attack failed, "LEAK <what>" when it worked.+# HOST_PATHS: space-separated absolute host paths of sign-in files to try.+leaks=0+leak() { echo "LEAK $*"; leaks=$((leaks+1)); }+ok() { echo "ok $*"; }+MARK="REAL""CANARY" # every real credential the spike mints carries this marker; the container never gets one+echo "== 1. read the host sign-in files"+for p in $HOST_PATHS /root/.claude/.credentials.json /root/.codex/auth.json; do+ if out=$(cat "$p" 2>&1); then leak "read $p"; else ok "read $p -> ${out##*: }"; fi+done+found=$(find / -xdev \( -path /proc -o -path /sys -o -path /dev \) -prune -o \+ \( -name .credentials.json -o -name auth.json -o -name creds.json \) -print 2>/dev/null)+[ -z "$found" ] && ok "no sign-in file anywhere in the container" || leak "sign-in files present: $found"+echo "== 2. read the real token"+env | grep -q "$MARK" && leak "token in env" || ok "env holds no real token ($(env | grep -cE 'API_KEY|OAUTH_TOKEN') credential vars, all dummies)"+hit=""+for f in /proc/[0-9]*/environ /proc/[0-9]*/cmdline; do grep -aq "$MARK" "$f" 2>/dev/null && hit="$hit $f"; done+[ -z "$hit" ] && ok "no real token in any process env/cmdline ($(ls -d /proc/[0-9]* | wc -l) processes, incl. the running claude)" || leak "/proc:$hit"+files=$(grep -rla "$MARK" / --exclude-dir=proc --exclude-dir=sys --exclude-dir=dev 2>/dev/null | head)+[ -z "$files" ] && ok "no real token in any file (rootfs, /workspace, /home/agent, /run/kwnt, /tmp)" || leak "files: $files"+for path in /anthropic/v1/oauth/token /anthropic/v1/files /chatgpt/backend-api/accounts /admin; do+ code=$(curl -s -o /tmp/b -w '%{http_code}' -X POST "http://127.0.0.1:8080$path" -d '{}')+ grep -aq "$MARK" /tmp/b && leak "broker returned a token on $path" || ok "broker $path -> $code"+done+echo "== 3. reach an outside host"+for url in https://example.com http://1.1.1.1 http://172.17.0.1:22 http://host.docker.internal \+ http://127.0.0.1:8080/https://example.com; do+ code=$(curl -s -m 5 -o /dev/null -w '%{http_code}' "$url" 2>/dev/null); rc=$?+ if [ "$rc" = 0 ] && [ "${code:0:1}" = 2 ]; then leak "reached $url ($code)"; else ok "$url -> curl rc=$rc http=$code"; fi+done+echo "== 4. IPv6, UDP and DNS"+for url in "http://[2606:4700:4700::1111]" "http://[::ffff:1.1.1.1]"; do+ code=$(curl -s -m 5 -o /dev/null -w '%{http_code}' "$url" 2>/dev/null); rc=$?+ if [ "$rc" = 0 ] && [ "${code:0:1}" = 2 ]; then leak "reached $url ($code)"; else ok "$url -> curl rc=$rc http=$code"; fi+done+for dst in 1.1.1.1/53 2606:4700:4700::1111/53 172.17.0.1/53; do+ if timeout 5 bash -c "printf x > /dev/udp/$dst" 2>/dev/null; then leak "sent UDP to $dst"; else ok "UDP to $dst refused"; fi+done+if timeout 5 getent hosts example.com >/dev/null 2>&1; then leak "resolved example.com"; else ok "no DNS"; fi+echo "PROBE_LEAKS=$leaks"diff --git a/proto/agents-in-vm/turn.sh b/proto/agents-in-vm/turn.shnew file mode 100755index 00000000..3cf7b2fa--- /dev/null+++ b/proto/agents-in-vm/turn.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash+# One claude turn inside kwnt-proto-lin-agent, with the flags src/drivers/cli.rs passes.+# turn.sh api|oauth "<prompt>" [resume-session-id]+# The container only ever gets a dummy credential; the broker swaps in the real one.+set -euo pipefail+MODE=$1; PROMPT=$2; RESUME=${3:-}+case $MODE in+ api) CRED=(-e ANTHROPIC_API_KEY=sk-ant-api03-kwnt-dummy) ;;+ oauth) CRED=(-e CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-kwnt-dummy) ;;+ *) echo "mode api|oauth" >&2; exit 2 ;;+esac+EXTRA=(); [ -n "$RESUME" ] && EXTRA=(--resume "$RESUME")+docker exec -i -w /workspace \+ -e HOME=/home/agent -e CLAUDE_CONFIG_DIR=/home/agent/.claude \+ -e ANTHROPIC_BASE_URL=http://127.0.0.1:8080/anthropic "${CRED[@]}" \+ -e CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 -e DISABLE_AUTOUPDATER=1 \+ -e CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1 -e MCP_TOOL_TIMEOUT=330000 -e MCP_TIMEOUT=30000 \+ kwnt-proto-lin-agent \+ claude --model claude-sonnet-4-5 --effort medium --permission-mode default --strict-mcp-config \+ --disallowedTools CronCreate,CronDelete,CronList,Task \+ --mcp-config /run/kwnt/mcp.json --permission-prompt-tool mcp__kwnt__approve \+ --append-system-prompt "You are a kwant bot (spike)." \+ --output-format stream-json --verbose --include-partial-messages \+ "${EXTRA[@]}" -p "$PROMPT" < /dev/nulldiff --git a/proto/agents-in-vm/up.sh b/proto/agents-in-vm/up.shnew file mode 100755index 00000000..955ffca6--- /dev/null+++ b/proto/agents-in-vm/up.sh@@ -0,0 +1,44 @@+#!/usr/bin/env bash+# Starts the spike: mock upstream (127.0.0.1:19471), broker (Unix socket), and the+# --network none agent container kwnt-proto-lin-agent. Fresh canary tokens every time.+set -euo pipefail+HERE=$(cd "$(dirname "$0")" && pwd)+RUN="$HERE/run"+PORT=19471+"$HERE/down.sh" >/dev/null 2>&1 || true+rm -rf "$RUN"; mkdir -p "$RUN"/{host,sock,task,home} "$RUN/host/signin-home/.claude" "$RUN/host/signin-home/.codex"+chmod 700 "$RUN/host"+docker image inspect kwnt-proto-lin-agent:spike >/dev/null 2>&1 || "$HERE/build.sh"+r() { head -c 16 /dev/urandom | od -An -tx1 | tr -d ' \n'; }+KEY="sk-ant-api03-REALCANARY-$(r)"; ACC="sk-ant-oat01-REALCANARY-$(r)"; REF="sk-ant-ort01-REALCANARY-$(r)"+OAI="sk-proj-REALCANARY-$(r)"; CGPT="eyREALCANARY.$(r)"; XAI="xai-REALCANARY-$(r)"; GW="kwnt-gw-$(r)"+EXP=$(( ($(date +%s) + 3600) * 1000 ))+umask 077+# The host's real sign-in home (what ~/.claude/.credentials.json looks like on Linux).+cat > "$RUN/host/signin-home/.claude/.credentials.json" <<J+{"claudeAiOauth":{"accessToken":"$ACC","refreshToken":"$REF","expiresAt":$EXP,"scopes":["user:inference"]}}+J+echo "{\"OPENAI_API_KEY\":\"$OAI\",\"tokens\":{\"access_token\":\"$CGPT\",\"account_id\":\"acct-canary\"}}" > "$RUN/host/signin-home/.codex/auth.json"+# What the broker reads (in kwnt: the profile's sign-in home / the keys table).+cat > "$RUN/host/creds.json" <<J+{"anthropic":{"mode":"api_key","api_key":"$KEY","oauth":{"accessToken":"$ACC","refreshToken":"$REF","expiresAt":$EXP}},+ "openai":{"api_key":"$OAI"},"chatgpt":{"access_token":"$CGPT","account_id":"acct-canary"},"xai":{"api_key":"$XAI"}}+J+echo "{\"api_key\":\"$KEY\",\"access_token\":\"$ACC\",\"refresh_token\":\"$REF\",\"gateway_token\":\"$GW\",\"openai_key\":\"$OAI\",\"chatgpt_access\":\"$CGPT\"}" > "$RUN/host/upstream_state.json"+umask 022+# Per-turn MCP config, as mcp::cli_config writes it, pointed at the forwarder.+echo "{\"mcpServers\":{\"kwnt\":{\"type\":\"http\",\"url\":\"http://127.0.0.1:8080/mcp\",\"headers\":{\"Authorization\":\"Bearer $GW\"}}}}" > "$RUN/sock/mcp.json"+echo "hello from the task folder" > "$RUN/task/README.txt"+nohup python3 "$HERE/mock_upstream.py" $PORT "$RUN/host/upstream_state.json" "$RUN/host/upstream.log" > "$RUN/host/mock.out" 2>&1 &+echo $! > "$RUN/host/mock.pid"+nohup python3 "$HERE/broker.py" "$RUN/sock/broker.sock" "$RUN/host/creds.json" "$RUN/host/broker.log" $PORT > "$RUN/host/broker.out" 2>&1 &+echo $! > "$RUN/host/broker.pid"+for _ in $(seq 50); do [ -S "$RUN/sock/broker.sock" ] && break; sleep 0.1; done+docker run -d --name kwnt-proto-lin-agent --label kwnt.proto=lin \+ --network none --user "$(id -u):$(id -g)" --cap-drop ALL --security-opt no-new-privileges \+ --read-only --tmpfs /tmp:rw,size=256m --cpus 2 --memory 1536m --pids-limit 512 \+ -e HOME=/home/agent \+ -v "$RUN/task:/workspace:rw" -v "$RUN/home:/home/agent:rw" -v "$RUN/sock:/run/kwnt:ro" \+ kwnt-proto-lin-agent:spike >/dev/null+for _ in $(seq 50); do docker exec kwnt-proto-lin-agent bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080' 2>/dev/null && break; sleep 0.1; done+echo "up: container kwnt-proto-lin-agent, broker $RUN/sock/broker.sock, mock 127.0.0.1:$PORT"diff --git a/src/config.rs b/src/config.rsindex d8a6ed51..37924f98 100644--- a/src/config.rs+++ b/src/config.rs@@ -84,6 +84,40 @@ pub struct Config {/// Optional private browser service URL (server-side only).#[serde(default)]pub browser_cdp_url: Option<String>,++ /// Limits for Claude replies that run inside the VM (`[agents_in_vm]`).+ #[serde(default)]+ pub agents_in_vm: AgentsInVmConfig,+}++/// Server limits for isolated Claude replies. Env overrides: `KWNT_AGENT_REQUEST_LIMIT`,+/// `KWNT_AGENT_MEMORY_MB`, `KWNT_AGENT_MAX_TURNS`.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(default)]+pub struct AgentsInVmConfig {+ /// Requests to Claude one reply may make before the broker answers 429.+ pub request_limit: u32,+ /// Memory per bot container, in MB.+ pub memory_mb: u32,+ /// Isolated replies that may run at once; the next one waits.+ pub max_turns: usize,+}++impl Default for AgentsInVmConfig {+ fn default() -> Self {+ Self { request_limit: 200, memory_mb: 1024, max_turns: 2 }+ }+}++impl AgentsInVmConfig {+ /// Clamps values to what still works (a 0 limit would stop every reply).+ pub fn sane(&self) -> Self {+ Self {+ request_limit: self.request_limit.clamp(1, 100_000),+ memory_mb: self.memory_mb.clamp(256, 65_536),+ max_turns: self.max_turns.clamp(1, 64),+ }+ }}impl Default for Config {@@ -97,6 +131,7 @@ impl Default for Config {laya_models: default_laya_models(),default_fallback_model: default_fallback_model(),browser_cdp_url: None,+ agents_in_vm: AgentsInVmConfig::default(),}}}@@ -180,6 +215,16 @@ impl Config {self.laya_models = models.trim().to_string();}}+ let num = |k: &str| std::env::var(k).ok().and_then(|v| v.trim().parse::<u64>().ok());+ if let Some(v) = num("KWNT_AGENT_REQUEST_LIMIT") {+ self.agents_in_vm.request_limit = v.min(u32::MAX as u64) as u32;+ }+ if let Some(v) = num("KWNT_AGENT_MEMORY_MB") {+ self.agents_in_vm.memory_mb = v.min(u32::MAX as u64) as u32;+ }+ if let Some(v) = num("KWNT_AGENT_MAX_TURNS") {+ self.agents_in_vm.max_turns = v.min(1024) as usize;+ }if let Ok(model) = std::env::var("KWNT_DEFAULT_FALLBACK_MODEL").or_else(|_| std::env::var("DEFAULT_FALLBACK_MODEL")){diff --git a/src/db/isolated_folders.rs b/src/db/isolated_folders.rsnew file mode 100644index 00000000..c19f9a19--- /dev/null+++ b/src/db/isolated_folders.rs@@ -0,0 +1,156 @@+//! Folders an isolated Claude turn has used (agents in the VM, D4). A bot in the container can+//! leave config there (`.claude/settings.json` hooks, `.mcp.json`, `.codex/config.toml`) that a+//! CLI kwnt later starts on this computer would load. The record lives here, never in the folder,+//! so the bot can't make, forge or remove it; it stays until the person clears it.+//!+//! Keyed on the canonical path. A folder counts as used when it is a recorded one, inside one or+//! holds one (a CLI started in a parent or a child can load the planted files too).++use super::{Database, DbError};+use std::path::{Path, PathBuf};++/// Canonical form of `folder` for the record, or the path itself when it doesn't exist (yet).+pub fn canonical(folder: &Path) -> PathBuf {+ folder.canonicalize().unwrap_or_else(|_| folder.to_path_buf())+}++/// Whether `folder` overlaps a recorded folder (equal, inside or containing). Both canonical.+pub fn overlaps(folder: &Path, recorded: &Path) -> bool {+ folder.starts_with(recorded) || recorded.starts_with(folder)+}++/// The error a refused host command records (its code first, for the API and the UI).+pub const HOST_COMMAND_REFUSED: &str = "folder_used_by_isolated_bot: a bot that runs Claude inside the VM used this folder, \+so commands from it don't run on this computer. Nothing ran.";++impl Database {+ pub(super) async fn migrate_isolated_folders(&self) -> Result<(), DbError> {+ // A path that isn't valid UTF-8 is stored lossily and never matches: the container+ // refuses such folders before it starts (see `agent_vm::mount_arg`)+ sqlx::query(+ "CREATE TABLE IF NOT EXISTS isolated_folders (+ path TEXT PRIMARY KEY,+ first_bot_id TEXT NOT NULL,+ first_used_at TIMESTAMP NOT NULL,+ last_used_at TIMESTAMP NOT NULL+ )",+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Notes that an isolated turn of `bot_id` uses `folder` (canonical). Called before the+ /// container starts, so a turn that fails later is recorded too.+ pub async fn record_isolated_folder(&self, folder: &Path, bot_id: &str) -> Result<(), DbError> {+ let path = folder.to_string_lossy();+ let now = chrono::Utc::now();+ sqlx::query(+ "INSERT INTO isolated_folders (path, first_bot_id, first_used_at, last_used_at) VALUES (?, ?, ?, ?) \+ ON CONFLICT(path) DO UPDATE SET last_used_at = excluded.last_used_at",+ )+ .bind(path.as_ref())+ .bind(bot_id)+ .bind(now)+ .bind(now)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Every recorded folder.+ pub async fn isolated_folders(&self) -> Result<Vec<PathBuf>, DbError> {+ let rows: Vec<(String,)> = sqlx::query_as("SELECT path FROM isolated_folders ORDER BY path").fetch_all(&self.pool).await?;+ Ok(rows.into_iter().map(|(p,)| PathBuf::from(p)).collect())+ }++ /// The recorded folder `folder` overlaps, if any (`folder` is canonicalized here).+ pub async fn isolated_folder_for(&self, folder: &Path) -> Result<Option<PathBuf>, DbError> {+ let folder = canonical(folder);+ Ok(self.isolated_folders().await?.into_iter().find(|r| overlaps(&folder, r)))+ }++ /// Why a command kwnt would run on this computer in `folder` (a mission's command check, a+ /// Dev backup command) must not, or `None` when it may (D4, C9b/C9c). Such a command runs+ /// with kwnt's own user and environment, so a script an isolated bot left in the folder would+ /// escape the VM. Fails closed: an unreadable record refuses.+ pub async fn host_command_refusal(&self, folder: &Path) -> Option<String> {+ match self.isolated_folder_for(folder).await {+ Ok(None) => None,+ Ok(Some(_)) => Some(HOST_COMMAND_REFUSED.into()),+ Err(e) => {+ tracing::warn!(error = %e, "couldn't read the folders isolated bots used; not running the command");+ Some(HOST_COMMAND_REFUSED.into())+ }+ }+ }++ /// The recorded folder a program kwnt starts on this computer in `cwd` would be near, or `None`+ /// when there's none (D4). With a folder: equal, inside or holding a recorded one. Without one+ /// (or a missing one) the program starts in kwnt's own working folder, often the home folder+ /// that holds every recorded folder: there only a recorded folder it sits in counts (programs+ /// read settings walking up, not down). Fails closed: an unreadable record counts as near.+ pub async fn isolated_folder_near(&self, cwd: Option<&Path>) -> Option<PathBuf> {+ let found = match cwd.filter(|d| d.exists()) {+ Some(d) => self.isolated_folder_for(d).await.map_err(|e| (e, d.to_path_buf())),+ None => {+ let here = std::env::current_dir().map(|d| canonical(&d)).unwrap_or_default();+ self.isolated_folders().await.map(|all| all.into_iter().find(|r| here.starts_with(r))).map_err(|e| (e, here))+ }+ };+ found.unwrap_or_else(|(e, at)| {+ tracing::warn!(error = %e, "couldn't read the folders isolated bots used; treating this one as used");+ Some(at)+ })+ }++ /// Forgets a recorded folder (the person cleared it). Returns whether one was there.+ pub async fn forget_isolated_folder(&self, folder: &Path) -> Result<bool, DbError> {+ let done = sqlx::query("DELETE FROM isolated_folders WHERE path = ?")+ .bind(canonical(folder).to_string_lossy().as_ref())+ .execute(&self.pool)+ .await?;+ Ok(done.rows_affected() > 0)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn a_recorded_folder_covers_its_parents_and_children_and_survives_a_restart() {+ let d = tempfile::tempdir().unwrap();+ let data = d.path().join("data");+ let proj = d.path().join("proj");+ std::fs::create_dir_all(proj.join("sub")).unwrap();+ let other = d.path().join("other");+ std::fs::create_dir_all(&other).unwrap();+ #[cfg(unix)]+ let link = d.path().join("link");+ #[cfg(unix)]+ std::os::unix::fs::symlink(&proj, &link).unwrap();++ let db = Database::init(&data).await.unwrap();+ assert_eq!(db.isolated_folder_for(&proj).await.unwrap(), None);+ db.record_isolated_folder(&canonical(&proj), "b1").await.unwrap();+ db.record_isolated_folder(&canonical(&proj), "b2").await.unwrap();+ assert_eq!(db.isolated_folders().await.unwrap().len(), 1, "one record per folder");+ drop(db);++ let db = Database::init(&data).await.unwrap();+ let want = Some(canonical(&proj));+ assert_eq!(db.isolated_folder_for(&proj).await.unwrap(), want);+ assert_eq!(db.isolated_folder_for(&proj.join("sub")).await.unwrap(), want, "child");+ assert_eq!(db.isolated_folder_for(d.path()).await.unwrap(), want, "parent");+ assert_eq!(db.isolated_folder_for(&proj.join("sub/../")).await.unwrap(), want, "dot-dot");+ #[cfg(unix)]+ assert_eq!(db.isolated_folder_for(&link).await.unwrap(), want, "symlink");+ assert_eq!(db.isolated_folder_for(&other).await.unwrap(), None, "a sibling isn't covered");+ // `/x/proj` doesn't cover `/x/project`+ assert!(!overlaps(Path::new("/x/project"), Path::new("/x/proj")));++ assert!(db.forget_isolated_folder(&proj).await.unwrap());+ assert_eq!(db.isolated_folder_for(&proj).await.unwrap(), None);+ }+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex c5bcf46c..7fc096b6 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -50,6 +50,7 @@ pub mod agent_connections;pub mod dev_jira;pub mod telegram;pub mod show_once;+pub mod isolated_folders;/// What a space's #general says about itself.pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";@@ -258,6 +259,8 @@ impl Database {// 0.7.9: Show it once recordings (add-only). After every step that can rebuild `kwants`// or `skills`, which would drop its delete triggersdb.migrate_show_once().await?;+ // Agents in the VM: folders an isolated turn used (add-only)+ db.migrate_isolated_folders().await?;db.pool.close().await;// Said out loud rather than left to sqlx's default: every writer, a goal proposaldiff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex eef6d9eb..439bd381 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -604,6 +604,26 @@ pub struct CliDriver {pub profile_env: Option<crate::profiles::CliEnv>,/// The account the turn runs on, named in the turn's reasoning line.pub account: Option<String>,+ /// Set when Claude runs in the bot's agent container ("Run Claude inside the VM").+ pub isolation: Option<Isolation>,+}++/// Where and how a Claude turn runs isolated: "Run Claude inside the VM" is on, the computer is+/// in vm mode and the account is a Claude sign-in (see `profile_turn::isolation_for`). Every+/// failure is the turn's notice; it never runs on this computer instead (D1).+#[derive(Clone)]+pub struct Isolation {+ pub vm: std::sync::Arc<crate::sandbox::agent_vm::AgentVm>,+ /// The sign-in profile's home (the broker refreshes its login); `None`: this computer's own.+ pub profile_home: Option<std::path::PathBuf>,+ /// kwnt's address on this computer, where the broker sends the bot's kwnt tool calls.+ pub kwnt_origin: String,+}++impl std::fmt::Debug for Isolation {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Isolation").field("profile_home", &self.profile_home).finish_non_exhaustive()+ }}impl CliDriver {@@ -616,9 +636,16 @@ impl CliDriver {grok_home: None,profile_env: None,account: None,+ isolation: None,}}+ /// Runs Claude in the bot's agent container (ignored for codex and grok).+ pub fn with_isolation(mut self, isolation: Option<Isolation>) -> Self {+ self.isolation = isolation;+ self+ }+/// Runs the CLI on a profile's own home (its login and settings) instead of the user's./// grok still runs in a private temp home, taking settings and login from this one only.pub fn with_profile_home(@@ -1388,8 +1415,34 @@ impl Driver for CliDriver {tracing::warn!(cli = %self.tool_kind, "{why}");return Err(DriverError::Execution(why));}+ // Isolated Claude: the container, broker turn and folder checks come first; any refusal+ // is the turn's notice and nothing runs on this computer (D1)+ let mut isolated = match (&self.isolation, self.tool_kind.as_str()) {+ (Some(iso), "claude") => match start_isolated(iso, &input, &event_tx).await {+ Ok(t) => Some(t),+ Err((text, meta)) => return Ok(TurnOutput::notice(text, meta)),+ },+ _ => None,+ };+ // D4: a folder an isolated bot used may hold settings it left there. Codex and Grok don't+ // run in it; Claude on this computer runs without the folder's own settings and servers.+ let mut in_isolated_folder = false;+ if isolated.is_none() {+ if let Some(recorded) = isolated_folder_used(&input).await {+ if matches!(self.tool_kind.as_str(), "codex" | "grok") {+ tracing::warn!(kwant = %input.kwant.id, cli = %self.tool_kind, folder = %recorded.display(), "not running in a folder an isolated bot used");+ let dir = input.workspace_dir.clone().filter(|d| d.exists()).unwrap_or(recorded);+ let n = crate::sandbox::agent_vm::notice::IsolationFailed::folder_used(&input.kwant.name, &self.tool_kind, folder_info(&input, &dir));+ let text = crate::sandbox::agent_vm::notice::folder_used_text(&input.kwant.name, &self.tool_kind);+ return Ok(TurnOutput::notice(text, n.to_meta()));+ }+ in_isolated_folder = true;+ }+ }let bin_path = match &self.cli_binary {Some(b) => b.clone(),+ // The container has its own claude; this computer's is never run+ None if isolated.is_some() => "claude".into(),None => {let msg = format!("⚠️ [{}] Local CLI for `{}` was not found on this system.",@@ -1614,6 +1667,11 @@ impl Driver for CliDriver {cmd.env("CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR", "1");// Skip starting the user's personal MCP servers on every chat turncmd.arg("--strict-mcp-config");+ if in_isolated_folder {+ // D4: the folder's .claude/settings*.json (hooks, env) could be a bot's from+ // inside the VM; only the user's own settings load+ cmd.arg("--setting-sources").arg("user");+ }// kwnt's routines and teammates, never claude's own scheduler or sessionscmd.args(claude_disallowed_args());if input.no_tools {@@ -1621,9 +1679,29 @@ impl Driver for CliDriver {cmd.args(CLAUDE_NO_TOOLS_ARGS);}if let Some(ctx) = &input.mcp {- match crate::mcp::cli_config::write_claude_config(ctx) {- Ok(file) => {- cmd.arg("--mcp-config").arg(&file.path);+ // Isolated: the config lives where the container sees it, and lists only+ // kwnt's own endpoints (through the broker); the bot's other servers stay off+ let written = match isolated.as_mut() {+ Some(t) => t.write_mcp_config(ctx).map(|(path, dropped)| {+ if !dropped.is_empty() {+ tracing::info!(kwant = %input.kwant.id, ?dropped, "MCP servers left out of an isolated Claude turn");+ }+ (std::ffi::OsString::from(path), None, dropped)+ }),+ None => crate::mcp::cli_config::write_claude_config(ctx)+ .map(|file| (file.path.clone().into_os_string(), Some(file), Vec::new())),+ };+ match written {+ Ok((path, file, dropped)) => {+ if !dropped.is_empty() {+ let _ = event_tx+ .send(RuntimeEvent::ThinkingDelta(format!(+ "Not available inside the VM this turn: {}.",+ dropped.join(", ")+ )))+ .await;+ }+ cmd.arg("--mcp-config").arg(&path);cmd.arg("--permission-prompt-tool").arg(format!("mcp__{}__{}",crate::mcp::RESERVED_SERVER_NAME,@@ -1633,8 +1711,12 @@ impl Driver for CliDriver {let slowest = ctx.servers.iter().map(|s| s.timeout_secs.max(0) as u64).max().unwrap_or(0);let tool_timeout_ms = (crate::mcp::APPROVAL_TIMEOUT_SECS + 30).max(slowest) * 1000;cmd.env("MCP_TOOL_TIMEOUT", tool_timeout_ms.to_string());+ // claude also gives up on a tool call with no progress for 300 s, which+ // MCP_TOOL_TIMEOUT doesn't raise: the same limit, so kwnt's own approval+ // timeout (300 s) always ends a waiting card first (QA F-2)+ cmd.env("CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT", tool_timeout_ms.to_string());cmd.env("MCP_TIMEOUT", "30000");- _mcp_config = Some(file);+ _mcp_config = file;}Err(e) => {tracing::warn!(error = %e, "could not write MCP config; running without MCP");@@ -1663,7 +1745,11 @@ impl Driver for CliDriver {cmd.arg("-p").arg(&effective_prompt);}}- if let Some(env) = &self.profile_env {+ if let Some(t) = &isolated {+ // The container's claude, its own home and a stand-in credential; the profile's+ // home and this computer's settings never reach it+ cmd = t.wrap(&cmd);+ } else if let Some(env) = &self.profile_env {env.apply(&mut cmd);// claude -p has no subcommand, so its overrides can follow the other optionscmd.args(&env.args);@@ -1725,6 +1811,14 @@ impl Driver for CliDriver {}}let stdout = claude_stream.into_stdout();+ if let Some(t) = isolated.take() {+ if let Some(notice) = isolated_end(&t, &input, &stdout, exit) {+ if let Some(u) = ClaudeResult::parse(&stdout).and_then(|r| r.split().map(|u| (r.main_model(), u))) {+ record_cli_usage(&input, u.0, &u.1).await;+ }+ return Ok(notice);+ }+ }let mut tokens = None;let mut usage = None;@@ -1822,6 +1916,137 @@ impl Driver for CliDriver {}}+/// Prepares an isolated Claude turn: the credential, the folder checks, the container and the+/// broker's turn. `Err` is the turn's notice (text and `turn_isolation_failed` meta). While it+/// waits for a free spot in the VM, `events` gets [`RuntimeEvent::WaitingForRoom`], then+/// [`RuntimeEvent::RoomTaken`], so the wait is shown as queued and isn't taken for a stall.+async fn start_isolated(+ iso: &Isolation,+ input: &TurnInput,+ events: &mpsc::Sender<RuntimeEvent>,+) -> Result<crate::sandbox::agent_vm::IsolatedTurn, (String, serde_json::Value)> {+ use crate::sandbox::agent_vm as vm;+ let refuse = |r: vm::Refusal| {+ tracing::warn!(kwant = %input.kwant.id, code = r.code, why = %r.message, "isolated Claude didn't start");+ isolation_notice(input, &r, "start")+ };+ let (credential, credential_home) = vm::resolve_credential(iso.profile_home.as_deref()).map_err(refuse)?;+ // A folder that isn't there yet: the bot's private folder in its container, never kwnt's own+ let folder = input.workspace_dir.clone().filter(|d| d.exists());+ let report = |w: vm::TurnWait| {+ let events = events.clone();+ async move {+ let e = match w {+ vm::TurnWait::Queued { position, slots } => RuntimeEvent::WaitingForRoom { reason: "vm_busy".into(), position, slots },+ vm::TurnWait::Started => RuntimeEvent::RoomTaken,+ };+ let _ = events.send(e).await;+ }+ };+ iso.vm+ .prepare_turn_reporting(+ vm::TurnRequest {+ bot_id: input.kwant.id.clone(),+ folder,+ credential,+ credential_home,+ kwnt_origin: Some(iso.kwnt_origin.clone()),+ },+ report,+ )+ .await+ .map_err(refuse)+}++/// The notice for a refused isolated turn (Mira's notices 1–3, 6, 7), with the folder fields+/// when the folder was the reason.+fn isolation_notice(+ input: &TurnInput,+ r: &crate::sandbox::agent_vm::Refusal,+ phase: &'static str,+) -> (String, serde_json::Value) {+ use crate::sandbox::agent_vm::notice::{self, IsolationFailed};+ let name = &input.kwant.name;+ let (mut n, text) = match (r.unsafe_kind, &input.workspace_dir) {+ (Some(kind), Some(dir)) => {+ let folder = folder_info(input, dir);+ // `folder` is canonical, so the home it is shortened by is too+ let home = dirs::home_dir().map(|h| h.canonicalize().unwrap_or(h));+ let text = notice::unsafe_folder_text(name, kind, &folder, home.as_deref());+ (IsolationFailed::unsafe_folder(name, folder, kind), text)+ }+ _ => (IsolationFailed::new(name, "claude", r.code), notice::start_text(name, r.code)),+ };+ n.phase = phase;+ let text = if phase == "mid_turn" { notice::mid_turn_text(name) } else { text };+ (text, n.to_meta())+}++/// Where a turn's folder came from, for the notice: the team's folder when it is the team's,+/// else the bot's own (the driver can't tell a space or goal folder apart).+fn folder_info(input: &TurnInput, dir: &Path) -> crate::sandbox::agent_vm::notice::FolderInfo {+ use crate::sandbox::agent_vm::notice::{FolderFrom, FolderInfo};+ let canon = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());+ let folder = canon(dir);+ match &input.team_context {+ Some(t) if t.workspace_path.as_deref().is_some_and(|w| canon(Path::new(w)) == folder) => FolderInfo::team(&folder, &t.id, &t.name),+ _ => FolderInfo::new(&folder, FolderFrom::Bot),+ }+}++/// How an isolated turn ended, when that isn't an ordinary reply: the request cap (notice 5,+/// never the CLI's raw 429 text), or the container or broker going away partway (notice 3).+fn isolated_end(+ t: &crate::sandbox::agent_vm::IsolatedTurn,+ input: &TurnInput,+ stdout: &str,+ exit: Option<std::process::ExitStatus>,+) -> Option<TurnOutput> {+ use crate::sandbox::agent_vm as vm;+ let name = &input.kwant.name;+ if t.cap_reached() {+ let limit = t.request_cap();+ tracing::warn!(kwant = %input.kwant.id, limit, "isolated Claude reached its request cap");+ let text = format!(+ "{name} paused after {limit} requests to Claude in this reply. That's the most one reply can make, so a bot stuck in a loop can't keep using up your Claude plan. Its work so far is kept."+ );+ let meta = serde_json::json!({ "kind": "turn_request_limit", "kwant_name": name, "engine": "claude", "limit": limit });+ return Some(TurnOutput::notice(text, meta));+ }+ let result = ClaudeResult::parse(stdout);+ let failed = !exit.is_some_and(|s| s.success());+ // No result line from a failed run (docker exec lost the container), or the CLI's own+ // "couldn't connect" result (the broker's socket went away)+ let lost = match &result {+ None => failed,+ Some(r) => r.is_error && lost_connection(&r.result),+ };+ if lost {+ tracing::warn!(kwant = %input.kwant.id, container = t.container(), status = ?exit, "isolated Claude stopped partway");+ let r = vm::Refusal::new(vm::codes::CONTAINER_FAILED, "Claude lost its connection inside the VM");+ let (text, meta) = isolation_notice(input, &r, "mid_turn");+ return Some(TurnOutput::notice(text, meta));+ }+ None+}++/// The folder an isolated Claude turn used that this turn's CLI would start in (equal, inside or+/// holding it, see [`crate::db::Database::isolated_folder_near`]), if any. Fails closed: when+/// kwnt can't read its record, the folder counts as used.+async fn isolated_folder_used(input: &TurnInput) -> Option<std::path::PathBuf> {+ // The server's one TurnInput (`routes.rs`, the chat runner) always sets the store, and the+ // isolated turns that record folders exist only there. A turn without one is a driver test+ // (unit or integration) with no record to check; refusing it would refuse every such test+ let db = input.store.as_ref()?;+ db.isolated_folder_near(input.workspace_dir.as_deref()).await+}++/// The CLI's result when it couldn't reach the API at all (here: the broker).+fn lost_connection(text: &str) -> bool {+ let t = text.to_ascii_lowercase();+ ["connection error", "econnrefused", "econnreset", "socket hang up", "unable to connect"].iter().any(|w| t.contains(w))+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex af386c5c..7b89dcf9 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -18,6 +18,18 @@ pub enum RuntimeEvent {/// A driver is still working: it printed something that isn't reply text or a tool call./// Only feeds the turn's stall watchdog; it is never broadcast.Progress,+ /// The driver waits for room before its engine can start: an isolated Claude reply behind+ /// others in the VM (`reason` "vm_busy"; `position` 1 is next; `slots` run at once). The+ /// server stops the turn's stall watchdog and shows the turn as queued (`turn_queued`) until+ /// [`RuntimeEvent::RoomTaken`]. Never broadcast as is.+ WaitingForRoom {+ reason: String,+ position: usize,+ slots: usize,+ },+ /// The wait in [`RuntimeEvent::WaitingForRoom`] is over: the stall watchdog starts again from+ /// now and the server sends `turn_started` again. Never broadcast as is.+ RoomTaken,/// The turn's fresh tokens so far (see `TurnUsage::fresh`), when the engine reports usage/// mid-turn, so a task the bot hands in during the turn can pay for it then. Never broadcast.UsageSoFar {@@ -83,6 +95,10 @@ pub enum RuntimeEvent {/// A turn is waiting for a free slot: its agent already runs as many turns as allowed/// (`reason` "agent_busy") or the whole server does ("server_busy"). It starts on its own,/// with `turn_started`; it is never dropped. `position` is 1 for the next to start.+ ///+ /// `reason` "vm_busy": a turn that had started waits for a free spot in the VM, because+ /// `slots` isolated Claude replies already run there. It is sent after that turn's+ /// `turn_started`, and a second `turn_started` follows when it gets its spot.#[serde(rename = "turn_queued", alias = "TurnQueued")]TurnQueued {turn_id: String,@@ -92,6 +108,9 @@ pub enum RuntimeEvent {thread_id: Option<String>,position: usize,reason: String,+ /// "vm_busy" only: how many isolated Claude replies run at once.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ slots: Option<usize>,},/// A thread was created, renamed or archived.#[serde(rename = "thread_updated", alias = "ThreadUpdated")]diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex 301a539e..3d6040e8 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -767,9 +767,20 @@ pub struct TurnOutput {/// driver then emitted no text and no `TurnComplete`, so the turn can move to another profile.#[serde(skip)]pub failure: Option<crate::profiles::ProviderFailure>,+ /// Set when the turn stopped for a reason the chat shows as a notice (the text, and the+ /// message meta its card is drawn from): isolated Claude couldn't start or hit its request+ /// cap. The driver emitted no text and no `TurnComplete`, and the turn is over: it never moves+ /// to another account or onto this computer (D1).+ #[serde(skip)]+ pub notice: Option<(String, serde_json::Value)>,}impl TurnOutput {+ /// A turn that ends with a chat notice instead of a reply (see [`TurnOutput::notice`]).+ pub fn notice(text: String, meta: serde_json::Value) -> Self {+ Self { notice: Some((text, meta)), ..Default::default() }+ }+/// A turn the provider refused before anything visible happened.pub fn refused(failure: crate::profiles::ProviderFailure) -> Self {Self { failure: Some(failure), ..Default::default() }@@ -802,6 +813,18 @@ pub fn resolve_driver_for_model(configured_key: Option<String>,endpoint: Option<String>,engines: &engines::EngineRegistry,+) -> Result<(Box<dyn Driver>, engines::EngineId), String> {+ resolve_driver_isolated(target_model, configured_key, endpoint, engines, None)+}++/// [`resolve_driver_for_model`], with Claude on this computer's own sign-in run in the bot's+/// agent container when `isolation` is set (ignored for every other route).+pub fn resolve_driver_isolated(+ target_model: &str,+ configured_key: Option<String>,+ endpoint: Option<String>,+ engines: &engines::EngineRegistry,+ isolation: Option<cli::Isolation>,) -> Result<(Box<dyn Driver>, engines::EngineId), String> {use engines::{EngineId, SystemRoute};Ok(match engines::system_route(engines, target_model, configured_key, find_cli_binary)? {@@ -809,7 +832,8 @@ pub fn resolve_driver_for_model(SystemRoute::Api { engine, key } => (Box::new(ApiDriver::new(Some(key), endpoint)), engine),SystemRoute::Cli { engine, bin } => {let name = crate::profiles::Engine::from_model(target_model).map(|e| e.as_str().to_string());- (Box::new(CliDriver::new(Some(bin), name)), engine)+ let claude = name.as_deref() == Some("claude");+ (Box::new(CliDriver::new(Some(bin), name).with_isolation(isolation.filter(|_| claude))), engine)}})}diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex 54bb858d..5215ee42 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -220,6 +220,64 @@ pub fn build_server(input: McpServerInput, existing: Option<&McpServer>) -> Resu})}+/// Whether stdio `server` would run a file from `folder`, its working folder (D4, C8): a program+/// or argument that is a relative path (`./x.js`, `bin/serve`, or a bare name that exists in the+/// folder, like `server.js`), or an absolute path inside the folder, including after `--opt=`.+/// In a folder an isolated bot used, such a file may be one it rewrote, so the server isn't+/// started there. A program looked up on `PATH` (`npx`, `uvx`) and paths outside are fine.+pub fn runs_folder_file(server: &McpServer, folder: &std::path::Path) -> bool {+ use std::path::Path;+ if server.transport != "stdio" {+ return false;+ }+ // The folder as given too: on Windows `canonicalize` returns a `\\?\` long-name path that a+ // typed path (8.3 short names, mixed slashes) never starts with+ let typed = folder;+ let folder = crate::db::isolated_folders::canonical(folder);+ let names_file = |word: &str, program: bool| {+ let word = word.trim();+ if word.is_empty() {+ return false;+ }+ let p = Path::new(word);+ if p.is_absolute() {+ return crate::db::isolated_folders::canonical(p).starts_with(&folder) || p.starts_with(&folder) || p.starts_with(typed);+ }+ // A program with a slash resolves from the folder; a bare one is a PATH lookup. An argument+ // names a folder file when it starts with `.` or its first part exists there (an npm+ // scope such as `@modelcontextprotocol/x` doesn't, so it stays a package name)+ if program {+ return word.contains('/') || word.starts_with('.');+ }+ let first = p.components().next().map(|c| folder.join(c)).unwrap_or_else(|| folder.clone());+ word.starts_with('.') || std::fs::symlink_metadata(first).is_ok()+ };+ let program = server.command.as_deref().unwrap_or("");+ names_file(program, true)+ || server.args.iter().any(|a| {+ // `--config=./x`: the value names a file just the same+ let value = a.split_once('=').map(|(_, v)| v);+ names_file(a, false) || value.is_some_and(|v| names_file(v, false))+ })+}++/// Makes stdio `server` start from `dir`, whatever folder its starter runs it in (D4, C8):+/// `/bin/sh -c 'cd -- "$0" && exec "$@"' <dir> <command> <args...>`. Both starters honour it:+/// kwnt's own client, which sets the folder it's given, and a CLI agent, which starts the servers+/// in its config from its own folder (that config has no folder field). A program started in a+/// folder an isolated bot used can load what the bot planted there (`python3 -m x` imports+/// `./x.py`, `npx x` runs `./node_modules/.bin/x`), so it starts from an empty folder instead.+pub fn start_in(server: &mut McpServer, dir: &std::path::Path) {+ if server.transport != "stdio" {+ return;+ }+ let Some(program) = server.command.take() else { return };+ let mut args = vec!["-c".to_string(), r#"cd -- "$0" && exec "$@""#.to_string(), dir.to_string_lossy().into_owned(), program];+ args.append(&mut server.args);+ server.command = Some("/bin/sh".into());+ server.args = args;+}+/// Replaces every non-empty secret in `text` with [`SECRET_MASK`].pub fn redact(text: &str, secrets: &[String]) -> String {let mut out = text.to_string();@@ -457,6 +515,72 @@ impl std::fmt::Debug for McpTurnContext {}}+#[cfg(test)]+mod folder_file_tests {+ use super::*;++ fn stdio(command: &str, args: &[&str]) -> McpServer {+ McpServer {+ id: "m1".into(),+ name: "x".into(),+ transport: "stdio".into(),+ command: Some(command.into()),+ args: args.iter().map(|a| a.to_string()).collect(),+ url: None,+ env: Default::default(),+ headers: Default::default(),+ enabled: true,+ timeout_secs: 30,+ created_at: None,+ }+ }++ #[test]+ fn a_server_that_runs_a_file_from_the_folder_is_spotted() {+ let t = tempfile::tempdir().unwrap();+ let dir = t.path();+ std::fs::write(dir.join("server.js"), "").unwrap();+ std::fs::create_dir(dir.join("tools")).unwrap();+ let outside = tempfile::tempdir().unwrap();+ let abs_out = outside.path().join("srv.js");+ let abs_in = dir.join("tools/srv.js");+ for (cmd, args) in [+ ("node", vec!["server.js"]),+ ("node", vec!["./missing.js"]),+ ("./bin/serve", vec![]),+ ("bin/serve", vec![]),+ ("python3", vec!["-m", "x", "--config=./cfg.json"]),+ ("node", vec![abs_in.to_str().unwrap()]),+ (abs_in.to_str().unwrap(), vec![]),+ ("node", vec!["tools/srv.js"]),+ ] {+ assert!(runs_folder_file(&stdio(cmd, &args), dir), "{cmd} {args:?}");+ }+ for (cmd, args) in [("npx", vec!["-y", "@modelcontextprotocol/server-memory"]), ("uvx", vec!["mcp-server-time"]), ("node", vec![abs_out.to_str().unwrap()]), ("server.js", vec![])] {+ assert!(!runs_folder_file(&stdio(cmd, &args), dir), "{cmd} {args:?}");+ }+ let mut http = stdio("node", &["server.js"]);+ http.transport = "http".into();+ assert!(!runs_folder_file(&http, dir));+ }++ // The folder given through a symlink, and a server naming a file there that doesn't exist yet:+ // canonicalizing that path fails, so the typed folder is what catches it (also Windows' 8.3 names)+ #[cfg(unix)]+ #[test]+ fn a_file_named_through_the_typed_folder_path_is_spotted() {+ let t = tempfile::tempdir().unwrap();+ let real = t.path().join("real");+ std::fs::create_dir(&real).unwrap();+ let link = t.path().join("link");+ std::os::unix::fs::symlink(&real, &link).unwrap();+ let later = link.join("tools/not-yet.js");+ assert!(runs_folder_file(&stdio("node", &[later.to_str().unwrap()]), &link));+ assert!(runs_folder_file(&stdio(later.to_str().unwrap(), &[]), &link));+ assert!(!runs_folder_file(&stdio("node", &[t.path().join("elsewhere.js").to_str().unwrap()]), &link));+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/sandbox/agent_vm/broker.rs b/src/sandbox/agent_vm/broker.rsnew file mode 100644index 00000000..98e3fe67--- /dev/null+++ b/src/sandbox/agent_vm/broker.rs@@ -0,0 +1,1841 @@+//! The credential broker for Claude turns that run inside the agent container (agents-in-vm,+//! slice 1). The container has no network (`--network none`); its only way out is a Unix socket+//! this broker listens on, bind-mounted read-only at `/run/kwnt/broker.sock` and forwarded to+//! `127.0.0.1:8080` inside by socat. The CLI in there holds a stand-in credential only.+//!+//! Per request, `/t/<turn key>/<route>/<rest>`:+//! * the turn key must be a live turn of the bot whose socket the request came in on+//! (`unknown_turn`); keys are random per turn and gone when the turn's [`TurnLease`] drops;+//! * `anthropic`: only the `(method, path)` pairs in [`ANTHROPIC_ALLOWED`] (from Gate 0,+//! `proto/agents-in-vm/evidence/real-upstream.txt`) are forwarded, with whatever credential+//! the container sent dropped and the real one added; at most [`DEFAULT_TURN_CAP`] per turn;+//! * `kwnt`: only the exact kwnt-local MCP paths written into this turn's config pass, to kwnt+//! itself, headers untouched (their tokens are per turn already);+//! * anything else is refused with an Anthropic-shaped error the CLI shows as it is.+//!+//! Owning refresh: for a profile's sign-in (`OAuthFile { refresh: true }`) the broker is the+//! only refresher while isolation is on: single flight per file, re-read under the lock, the+//! file rewritten atomically (0600) with every other field kept. The host's own sign-in is never+//! refreshed here (the person's own `claude` may refresh it at the same time and one of the two+//! would be signed out); an expired one is `signin_expired`.+//!+//! The log (`<agent-vm>/broker.log`, JSON lines) has hashes only: never a credential, a turn+//! key, or a long path segment.++use futures::TryStreamExt;+use http_body_util::{combinators::UnsyncBoxBody, BodyExt, Full, Limited, StreamBody};+use hyper::body::{Bytes, Frame, Incoming};+use hyper::header::{HeaderMap, HeaderName, HeaderValue};+use hyper::{Method, Request, Response, StatusCode};+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use std::collections::HashMap;+use std::convert::Infallible;+use std::io::Write;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU32, Ordering};+use std::sync::{Arc, Mutex as StdMutex};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++pub type BrokerBody = UnsyncBoxBody<Bytes, std::io::Error>;++/// Requests to the model API one turn may make before the broker answers 429 (`request_cap`).+/// A long agentic turn makes one call per tool step; 200 is far above a normal turn and stops a+/// loop from spending the person's plan.+pub const DEFAULT_TURN_CAP: u32 = 200;+/// Largest request body forwarded (a long conversation with images stays well under it).+pub const MAX_REQUEST_BYTES: usize = 32 << 20;+/// Largest request head (request line and headers) the socket reads.+pub const MAX_HEAD_BYTES: usize = 64 << 10;+pub const ANTHROPIC_ORIGIN: &str = "https://api.anthropic.com";+/// Claude Code's own OAuth refresh endpoint and client id (CLI 2.1.316).+pub const OAUTH_TOKEN_URL: &str = "https://platform.claude.com/v1/oauth/token";+pub const OAUTH_CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";+/// Refresh this long before the access token runs out.+const REFRESH_MARGIN_MS: i64 = 60_000;+const LOG_ROTATE_BYTES: u64 = 5 << 20;++/// The model-API calls a Claude turn needs, and nothing else: from Gate 0 against the real API+/// (`proto/agents-in-vm/evidence/real-upstream.txt`). Each is `(method, path, allowed queries)`.+pub const ANTHROPIC_ALLOWED: &[(&str, &str, &[&str])] = &[+ // Gate 0 (CLI 2.1.316, real API): every call of a normal, a `--resume` and a Bash-tool turn+ // was this one, with `?beta=true`. Nothing else was sent; anything else is refused and logged+ ("POST", "/v1/messages", &["", "beta=true"]),+];++/// Request headers forwarded to Anthropic (an allow-list: anything else the container sent,+/// every credential included, is dropped). `x-stainless-*` are the SDK's own descriptive headers.+const ANTHROPIC_FORWARD: &[&str] = &[+ "accept", "content-type", "anthropic-version", "anthropic-beta", "user-agent", "x-app",+ "x-claude-code-session-id", "anthropic-dangerous-direct-browser-access",+];+const ANTHROPIC_FORWARD_PREFIX: &str = "x-stainless-";++/// `anthropic-beta` values passed on (Gate 0); others are stripped and logged, not refused.+pub const KNOWN_BETAS: &[&str] = &[+ // Gate 0: every value the real CLI sent (API-key mode, Haiku 5.5)+ "advanced-tool-use-2025-11-20",+ "claude-code-20250219",+ "context-management-2025-06-27",+ "effort-2025-11-24",+ "interleaved-thinking-2025-05-14",+ "mid-conversation-tool-changes-2026-07-01",+ "per-turn-control-2026-07-01",+ "thinking-display-updates-2026-08-18",+ "thinking-token-count-2026-05-13",+ // Not in Gate 0 (it used an API key): the CLI adds it for a Claude sign-in, which needs it+ "oauth-2025-04-20",+];++/// Tool `type`s a request may declare besides plain client tools (no `type`, or `custom`).+/// Every server tool (`web_search_*`, `web_fetch_*`, `code_execution_*`, ...) runs on Anthropic's+/// side and could carry the folder's data to any URL, so it is refused (Gate 0: the CLI sends none).+pub const ALLOWED_TOOL_TYPES: &[&str] = &["custom"];++/// Request headers forwarded on the `kwnt` route (the MCP client's own; its token included).+const KWNT_FORWARD: &[&str] = &[+ "accept", "content-type", "authorization", "mcp-session-id", "mcp-protocol-version", "last-event-id", "user-agent",+];++/// The only kwnt paths a turn can be given: the MCP gateway, and a permission endpoint with a+/// single opaque id. Nothing else of kwnt's API is reachable from a container.+pub fn kwnt_path_allowed(path: &str) -> bool {+ let id_ok = |id: &str| !id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');+ matches!(path, "/api/mcp/self" | "/api/mcp/gateway") || path.strip_prefix("/api/mcp/permission/").is_some_and(id_ok)+}++/// Header read timeout on the socket, and the longest a request body may take to arrive.+#[cfg(unix)]+const HEADER_TIMEOUT: Duration = Duration::from_secs(10);+const BODY_TIMEOUT: Duration = Duration::from_secs(60);+/// Open connections one bot's socket serves at once; more are closed straight away.+pub const MAX_CONNECTIONS: usize = 64;++/// The status codes the broker answers with, by `code` (also in the PR description).+pub mod codes {+ pub const UNKNOWN_TURN: &str = "unknown_turn";+ pub const ROUTE_NOT_ALLOWED: &str = "route_not_allowed";+ pub const PATH_NOT_ALLOWED: &str = "path_not_allowed";+ pub const REQUEST_CAP: &str = "request_cap";+ pub const REQUEST_TOO_LARGE: &str = "request_too_large";+ pub const UPSTREAM_UNREACHABLE: &str = "upstream_unreachable";+ pub const CREDENTIAL_UNAVAILABLE: &str = "credential_unavailable";+ pub const SIGN_IN_EXPIRED: &str = "sign_in_expired";+ pub const BAD_REQUEST: &str = "bad_request";+ pub const CREDENTIAL_MISMATCH: &str = "credential_mismatch";+ pub const SERVER_TOOL_NOT_ALLOWED: &str = "server_tool_not_allowed";+ pub const REQUEST_TIMEOUT: &str = "request_timeout";+}++/// A secret that never prints.+#[derive(Clone)]+pub struct Secret(String);++impl Secret {+ pub fn new(value: impl Into<String>) -> Self {+ Self(value.into())+ }+ pub fn expose(&self) -> &str {+ &self.0+ }+}++impl std::fmt::Debug for Secret {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "Secret(sha8={})", sha8(&self.0))+ }+}++/// Where the real Claude credential for a turn comes from.+#[derive(Clone, Debug)]+pub enum Credential {+ /// An API key (the host's `ANTHROPIC_API_KEY`, or the key a sign-in home holds).+ ApiKey(Secret),+ /// A Claude subscription sign-in file (`.credentials.json`, `claudeAiOauth`), read on every+ /// request so a refresh is picked up. `refresh`: the broker owns refreshing it.+ OAuthFile { path: PathBuf, refresh: bool },+}++impl Credential {+ pub fn is_oauth(&self) -> bool {+ matches!(self, Credential::OAuthFile { .. })+ }+}++/// A refused or failed request: the HTTP status, a stable `code`, and a sentence for the person.+#[derive(Debug, Clone)]+pub struct Deny {+ pub status: StatusCode,+ pub code: &'static str,+ pub message: String,+}++impl Deny {+ fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {+ Self { status, code, message: message.into() }+ }+}++pub fn sha8(s: &str) -> String {+ if s.is_empty() {+ return "-".into();+ }+ let digest = Sha256::digest(s.as_bytes());+ digest.iter().take(4).map(|b| format!("{b:02x}")).collect()+}++/// Refuses, never normalizes, a request whose target or framing is anything but plain: an+/// absolute-form or authority-form target, `CONNECT`, a dot segment, an empty segment (`//`),+/// a percent-escape or backslash in the path, or both `Content-Length` and `Transfer-Encoding`.+/// What the allow-list then compares is exactly what the upstream receives.+pub fn check_request<B>(req: &Request<B>) -> Result<(), Deny> {+ let bad = |why: &str| Deny::new(StatusCode::BAD_REQUEST, codes::BAD_REQUEST, format!("kwnt's broker refused a malformed request ({why})"));+ if req.method() == Method::CONNECT {+ return Err(bad("CONNECT"));+ }+ if req.uri().scheme().is_some() || req.uri().authority().is_some() {+ return Err(bad("absolute-form target"));+ }+ let path = req.uri().path();+ if !path.starts_with('/') {+ return Err(bad("target"));+ }+ if path.contains('%') || path.contains('\\') {+ return Err(bad("escaped path"));+ }+ if path[1..].split('/').any(|seg| seg.is_empty() || seg == "." || seg == "..") {+ return Err(bad("path segments"));+ }+ if req.uri().query().is_some_and(|q| q.contains('#')) {+ return Err(bad("query"));+ }+ let h = req.headers();+ // hyper's buffer limit doesn't always stop a large head that arrives in one read, so the+ // head is measured here too: over MAX_HEAD_BYTES is a 431, never forwarded+ let head: usize = req.uri().to_string().len() + h.iter().map(|(n, v)| n.as_str().len() + v.len() + 4).sum::<usize>();+ if head > MAX_HEAD_BYTES {+ return Err(Deny::new(StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE, codes::REQUEST_TOO_LARGE, "The request's headers are larger than kwnt's broker forwards"));+ }+ // A body announced as larger than the broker forwards is refused before any of it is read+ let announced = h.get(hyper::header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.trim().parse::<u64>().ok());+ if announced.is_some_and(|n| n > MAX_REQUEST_BYTES as u64) {+ return Err(Deny::new(StatusCode::PAYLOAD_TOO_LARGE, codes::REQUEST_TOO_LARGE, "The request is larger than kwnt's broker forwards"));+ }+ // Any Transfer-Encoding is refused, not only next to a Content-Length: on the socket hyper+ // drops the Content-Length of a CL+TE request before the broker sees it (RFC 9112 6.3), so+ // refusing TE is the only way to refuse CL+TE rather than normalize it. The CLI sends its+ // bodies with a Content-Length (Gate 0 checks).+ if h.contains_key(hyper::header::TRANSFER_ENCODING) {+ return Err(bad("Transfer-Encoding (send a Content-Length)"));+ }+ if h.get_all(hyper::header::CONTENT_LENGTH).iter().count() > 1 {+ return Err(bad("repeated Content-Length"));+ }+ Ok(())+}++/// A path for the log: segments that could carry a token or an id become `h:<sha8>`.+pub fn scrub_path(path: &str) -> String {+ let (p, q) = path.split_once('?').unwrap_or((path, ""));+ let seg = |s: &str| {+ if s.len() > 24 || (s.len() >= 16 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')) {+ format!("h:{}", sha8(s))+ } else {+ s.to_string()+ }+ };+ let mut out = p.split('/').map(seg).collect::<Vec<_>>().join("/");+ if !q.is_empty() {+ let qs: Vec<String> = q+ .split('&')+ .map(|kv| match kv.split_once('=') {+ Some((k, v)) if v.len() > 12 => format!("{k}=h:{}", sha8(v)),+ _ => kv.to_string(),+ })+ .collect();+ out.push('?');+ out.push_str(&qs.join("&"));+ }+ out+}++/// What one turn may do through the broker.+#[derive(Debug, Clone)]+pub struct TurnSpec {+ /// The bot whose socket the turn's requests must come in on.+ pub bot: String,+ pub credential: Credential,+ /// kwnt's own origin (`http://127.0.0.1:<port>`), for the `kwnt` route.+ pub kwnt_origin: Option<String>,+ pub cap: u32,+}++struct TurnEntry {+ spec: TurnSpec,+ kwnt_paths: StdMutex<Vec<String>>,+ count: AtomicU32,+}++/// A live turn's registration. Dropping it ends the turn at the broker: its key stops working at+/// once, even if something in the container is still running.+pub struct TurnLease {+ broker: Arc<Broker>,+ key: String,+}++impl TurnLease {+ pub fn key(&self) -> &str {+ &self.key+ }++ /// Lets the turn reach one exact kwnt-local path (no query) through the `kwnt` route. Only+ /// [`kwnt_path_allowed`] paths can be added; returns whether it was.+ pub fn allow_kwnt_path(&self, path: &str) -> bool {+ if !kwnt_path_allowed(path) {+ return false;+ }+ match self.broker.turns.lock().unwrap().get(&self.key) {+ Some(entry) => {+ entry.kwnt_paths.lock().unwrap().push(path.to_string());+ true+ }+ None => false,+ }+ }++ /// Whether the turn asked for more model calls than its cap (the CLI then saw a 429).+ pub fn cap_reached(&self) -> bool {+ self.broker+ .turns+ .lock()+ .unwrap()+ .get(&self.key)+ .is_some_and(|e| e.count.load(Ordering::Relaxed) > e.spec.cap)+ }++ pub fn cap(&self) -> u32 {+ self.broker.turns.lock().unwrap().get(&self.key).map_or(0, |e| e.spec.cap)+ }++ /// Requests this turn made to the model API so far.+ pub fn requests(&self) -> u32 {+ self.broker+ .turns+ .lock()+ .unwrap()+ .get(&self.key)+ .map_or(0, |e| e.count.load(Ordering::Relaxed))+ }+}++impl Drop for TurnLease {+ fn drop(&mut self) {+ self.broker.turns.lock().unwrap().remove(&self.key);+ }+}++impl std::fmt::Debug for TurnLease {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "TurnLease(sha8={})", sha8(&self.key))+ }+}++#[derive(Debug, Clone)]+pub struct BrokerConfig {+ pub anthropic_origin: String,+ pub oauth_token_url: String,+ pub log_path: PathBuf,+}++impl BrokerConfig {+ pub fn new(log_path: PathBuf) -> Self {+ Self {+ anthropic_origin: ANTHROPIC_ORIGIN.into(),+ oauth_token_url: OAUTH_TOKEN_URL.into(),+ log_path,+ }+ }+}++struct Listener {+ path: PathBuf,+ task: tokio::task::JoinHandle<()>,+}++pub struct Broker {+ cfg: BrokerConfig,+ client: reqwest::Client,+ turns: StdMutex<HashMap<String, Arc<TurnEntry>>>,+ listeners: tokio::sync::Mutex<HashMap<String, Listener>>,+ refresh_locks: StdMutex<HashMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>,+ log_lock: StdMutex<()>,+}++impl std::fmt::Debug for Broker {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Broker").field("cfg", &self.cfg).finish_non_exhaustive()+ }+}++const DROP_RESPONSE: &[&str] = &[+ "connection", "keep-alive", "proxy-connection", "transfer-encoding", "upgrade", "te", "trailer",+ "content-length", "set-cookie", "set-cookie2", "location", "alt-svc",+];++impl Broker {+ pub fn new(cfg: BrokerConfig) -> Arc<Self> {+ let client = reqwest::Client::builder()+ .redirect(reqwest::redirect::Policy::none())+ .connect_timeout(Duration::from_secs(30))+ .read_timeout(Duration::from_secs(600))+ .no_proxy()+ .build()+ .unwrap_or_default();+ Arc::new(Self {+ cfg,+ client,+ turns: StdMutex::new(HashMap::new()),+ listeners: tokio::sync::Mutex::new(HashMap::new()),+ refresh_locks: StdMutex::new(HashMap::new()),+ log_lock: StdMutex::new(()),+ })+ }++ /// Registers a turn and returns its lease (the key goes into the container's base URL).+ pub fn register(self: &Arc<Self>, spec: TurnSpec) -> TurnLease {+ let key = uuid::Uuid::new_v4().simple().to_string();+ let entry = Arc::new(TurnEntry { spec, kwnt_paths: StdMutex::new(Vec::new()), count: AtomicU32::new(0) });+ self.turns.lock().unwrap().insert(key.clone(), entry);+ TurnLease { broker: self.clone(), key }+ }++ pub fn live_turns(&self) -> usize {+ self.turns.lock().unwrap().len()+ }++ /// Makes sure `bot` has a socket at `sock` (0600, in a 0700 folder) served by this broker.+ #[cfg(unix)]+ pub async fn listen(self: &Arc<Self>, bot: &str, sock: &Path) -> std::io::Result<()> {+ use std::os::unix::fs::PermissionsExt;+ let mut listeners = self.listeners.lock().await;+ if let Some(l) = listeners.get(bot) {+ if l.path == sock && !l.task.is_finished() && sock.exists() {+ return Ok(());+ }+ l.task.abort();+ }+ // sun_path is 108 bytes on Linux+ if sock.as_os_str().len() > 100 {+ return Err(std::io::Error::other(format!("socket path too long ({} bytes)", sock.as_os_str().len())));+ }+ let dir = sock.parent().ok_or_else(|| std::io::Error::other("socket has no folder"))?;+ std::fs::create_dir_all(dir)?;+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;+ let _ = std::fs::remove_file(sock);+ let listener = tokio::net::UnixListener::bind(sock)?;+ std::fs::set_permissions(sock, std::fs::Permissions::from_mode(0o600))?;+ let broker = self.clone();+ let bot_id = bot.to_string();+ let slots = Arc::new(tokio::sync::Semaphore::new(MAX_CONNECTIONS));+ let task = tokio::spawn(async move {+ loop {+ let Ok((stream, _)) = listener.accept().await else {+ tokio::time::sleep(Duration::from_millis(50)).await;+ continue;+ };+ // A flood from the container closes its own extra connections, nothing else+ let Ok(slot) = slots.clone().try_acquire_owned() else {+ drop(stream);+ continue;+ };+ let broker = broker.clone();+ let bot_id = bot_id.clone();+ tokio::spawn(async move {+ let _slot = slot;+ let svc = hyper::service::service_fn(move |req| {+ let broker = broker.clone();+ let bot_id = bot_id.clone();+ async move { Ok::<_, Infallible>(broker.handle(&bot_id, req).await) }+ });+ // hyper answers most oversized heads 431 itself; check_request catches the rest+ let _ = hyper::server::conn::http1::Builder::new()+ .timer(hyper_util::rt::TokioTimer::new())+ .header_read_timeout(HEADER_TIMEOUT)+ .max_buf_size(MAX_HEAD_BYTES)+ .max_headers(64)+ .serve_connection(hyper_util::rt::TokioIo::new(stream), svc)+ .await;+ });+ }+ });+ listeners.insert(bot.to_string(), Listener { path: sock.to_path_buf(), task });+ Ok(())+ }++ #[cfg(not(unix))]+ pub async fn listen(self: &Arc<Self>, _bot: &str, _sock: &Path) -> std::io::Result<()> {+ Err(std::io::Error::other("the agent broker needs Unix sockets"))+ }++ /// Stops every socket (kwnt shutting down).+ pub async fn close_all(&self) {+ for (_, l) in self.listeners.lock().await.drain() {+ l.task.abort();+ let _ = std::fs::remove_file(&l.path);+ }+ }++ /// One request that came in on `bot`'s socket.+ pub async fn handle<B>(&self, bot: &str, req: Request<B>) -> Response<BrokerBody>+ where+ B: hyper::body::Body<Data = Bytes> + Send + 'static,+ B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,+ {+ let method = req.method().clone();+ let path_q = req.uri().path_and_query().map(|p| p.as_str().to_string()).unwrap_or_default();+ let mut rec = json!({+ "bot": sha8(bot),+ "method": method.as_str(),+ "path": scrub_path(&path_q),+ "sent_cred": sha8(sent_credential(req.headers())),+ });+ let result = self.route(bot, req, &mut rec).await;+ let (resp, decision) = match result {+ Ok(r) => (r, "forward"),+ Err(d) => {+ rec["code"] = json!(d.code);+ let decision = if d.status == StatusCode::FORBIDDEN { "deny" } else { "error" };+ (deny_response(&d), decision)+ }+ };+ rec["status"] = json!(resp.status().as_u16());+ rec["decision"] = json!(decision);+ self.log(rec);+ resp+ }++ async fn route<B>(&self, bot: &str, req: Request<B>, rec: &mut Value) -> Result<Response<BrokerBody>, Deny>+ where+ B: hyper::body::Body<Data = Bytes> + Send + 'static,+ B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,+ {+ check_request(&req)?;+ let path = req.uri().path().to_string();+ let query = req.uri().query().unwrap_or("").to_string();+ let mut parts = path.trim_start_matches('/').splitn(4, '/');+ let (Some("t"), Some(key), Some(route)) = (parts.next(), parts.next(), parts.next()) else {+ return Err(Deny::new(StatusCode::FORBIDDEN, codes::ROUTE_NOT_ALLOWED, "kwnt's broker only forwards a running turn's own calls"));+ };+ let rest = format!("/{}", parts.next().unwrap_or(""));+ rec["turn"] = json!(sha8(key));+ rec["route"] = json!(route);+ rec["path"] = json!(scrub_path(&format!("{rest}{}{query}", if query.is_empty() { "" } else { "?" })));+ let entry = self+ .turns+ .lock()+ .unwrap()+ .get(key)+ .filter(|e| e.spec.bot == bot)+ .cloned()+ .ok_or_else(|| Deny::new(StatusCode::FORBIDDEN, codes::UNKNOWN_TURN, super::notice::body::NO_TURN))?;+ match route {+ "anthropic" => self.anthropic(&entry, req, &rest, &query, rec).await,+ "kwnt" => self.kwnt(&entry, req, &rest, &query).await,+ _ => Err(Deny::new(StatusCode::FORBIDDEN, codes::ROUTE_NOT_ALLOWED, format!("kwnt's broker doesn't reach \"{route}\""))),+ }+ }++ async fn anthropic<B>(&self, entry: &TurnEntry, req: Request<B>, rest: &str, query: &str, rec: &mut Value) -> Result<Response<BrokerBody>, Deny>+ where+ B: hyper::body::Body<Data = Bytes> + Send + 'static,+ B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,+ {+ let method = req.method().clone();+ let allowed = ANTHROPIC_ALLOWED+ .iter()+ .any(|(m, p, qs)| method.as_str() == *m && rest == *p && qs.contains(&query));+ if !allowed {+ return Err(Deny::new(+ StatusCode::FORBIDDEN,+ codes::PATH_NOT_ALLOWED,+ format!("kwnt's broker doesn't forward {method} {} to Anthropic", scrub_path(rest)),+ ));+ }+ check_credential_kind(&entry.spec.credential, req.headers())?;+ let n = entry.count.fetch_add(1, Ordering::Relaxed) + 1;+ if n > entry.spec.cap {+ return Err(Deny::new(+ StatusCode::TOO_MANY_REQUESTS,+ codes::REQUEST_CAP,+ super::notice::body::request_cap(entry.spec.cap),+ ));+ }+ let (parts, body) = req.into_parts();+ let body = read_body(body).await?;+ check_messages_body(&body)?;+ let (fwd, stripped) = anthropic_headers(&parts.headers);+ if !stripped.is_empty() {+ rec["beta_stripped"] = json!(stripped);+ }+ let url = format!("{}{rest}{}{query}", self.cfg.anthropic_origin.trim_end_matches('/'), if query.is_empty() { "" } else { "?" });+ let mut refreshed = false;+ loop {+ let (cred_headers, seen) = self.credential_headers(&entry.spec.credential).await?;+ rec["real_cred"] = json!(sha8(seen.as_deref().unwrap_or_else(|| cred_headers.values().next().and_then(|v| v.to_str().ok()).unwrap_or(""))));+ let secret = seen.clone().or_else(|| cred_headers.get("x-api-key").and_then(|v| v.to_str().ok()).map(String::from));+ let mut headers = fwd.clone();+ headers.extend(cred_headers);+ let resp = self+ .client+ .request(method.clone(), &url)+ .headers(headers)+ .body(body.clone())+ .send()+ .await+ .map_err(|e| Deny::new(StatusCode::BAD_GATEWAY, codes::UPSTREAM_UNREACHABLE, format!("Couldn't reach Anthropic: {}", without_url(&e))))?;+ if resp.status() == StatusCode::UNAUTHORIZED && !refreshed {+ if let (Credential::OAuthFile { path, refresh: true }, Some(seen)) = (&entry.spec.credential, &seen) {+ refreshed = true;+ rec["on_401"] = json!(self.refresh(path, seen).await.map(|r| r.as_str()).unwrap_or("refresh_failed"));+ continue;+ }+ }+ return Ok(stream_response(resp, secret.map(Secret::new)));+ }+ }++ async fn kwnt<B>(&self, entry: &TurnEntry, req: Request<B>, rest: &str, query: &str) -> Result<Response<BrokerBody>, Deny>+ where+ B: hyper::body::Body<Data = Bytes> + Send + 'static,+ B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,+ {+ let origin = entry.spec.kwnt_origin.clone();+ let listed = entry.kwnt_paths.lock().unwrap().iter().any(|p| p == rest);+ let Some(origin) = origin.filter(|_| listed) else {+ return Err(Deny::new(StatusCode::FORBIDDEN, codes::PATH_NOT_ALLOWED, "kwnt's broker only forwards this turn's own kwnt tools"));+ };+ let (parts, body) = req.into_parts();+ let body = read_body(body).await?;+ let url = format!("{}{rest}{}{query}", origin.trim_end_matches('/'), if query.is_empty() { "" } else { "?" });+ let mut headers = HeaderMap::new();+ for (k, v) in parts.headers.iter() {+ if KWNT_FORWARD.contains(&k.as_str()) {+ headers.append(k.clone(), v.clone());+ }+ }+ let resp = self+ .client+ .request(parts.method.clone(), &url)+ .headers(headers)+ .body(body)+ .send()+ .await+ .map_err(|e| Deny::new(StatusCode::BAD_GATEWAY, codes::UPSTREAM_UNREACHABLE, format!("Couldn't reach kwnt: {}", without_url(&e))))?;+ Ok(stream_response(resp, None))+ }++ /// The real credential's headers, and for a sign-in the access token they carry (to tell a+ /// stale token from a refreshed one).+ async fn credential_headers(&self, cred: &Credential) -> Result<(HeaderMap, Option<String>), Deny> {+ let mut h = HeaderMap::new();+ let bad = |_| Deny::new(StatusCode::SERVICE_UNAVAILABLE, codes::CREDENTIAL_UNAVAILABLE, "The Claude credential has characters that can't be sent");+ match cred {+ Credential::ApiKey(key) => {+ if key.expose().trim().is_empty() {+ return Err(Deny::new(StatusCode::SERVICE_UNAVAILABLE, codes::CREDENTIAL_UNAVAILABLE, "No Claude API key is set"));+ }+ let mut v = HeaderValue::from_str(key.expose().trim()).map_err(bad)?;+ v.set_sensitive(true);+ h.insert(HeaderName::from_static("x-api-key"), v);+ Ok((h, None))+ }+ Credential::OAuthFile { path, refresh } => {+ let mut tok = read_oauth(path)?;+ if tok.expires_soon() {+ if !*refresh {+ if tok.expired() {+ return Err(signin_expired());+ }+ } else if self.refresh(path, &tok.access).await.is_ok() {+ tok = read_oauth(path)?;+ } else if tok.expired() {+ return Err(signin_expired());+ }+ }+ let mut v = HeaderValue::from_str(&format!("Bearer {}", tok.access)).map_err(bad)?;+ v.set_sensitive(true);+ h.insert(hyper::header::AUTHORIZATION, v);+ Ok((h, Some(tok.access)))+ }+ }+ }++ fn refresh_lock(&self, path: &Path) -> Arc<tokio::sync::Mutex<()>> {+ self.refresh_locks.lock().unwrap().entry(path.to_path_buf()).or_default().clone()+ }++ /// Refreshes the sign-in in `path` unless someone already replaced `seen_access`. Single+ /// flight per file; the file keeps every field it had besides the three tokens.+ pub async fn refresh(&self, path: &Path, seen_access: &str) -> Result<RefreshOutcome, Deny> {+ let lock = self.refresh_lock(path);+ let _held = lock.lock().await;+ let mut doc: Value = std::fs::read(path)+ .ok()+ .and_then(|b| serde_json::from_slice(&b).ok())+ .ok_or_else(|| Deny::new(StatusCode::SERVICE_UNAVAILABLE, codes::CREDENTIAL_UNAVAILABLE, "The Claude sign-in file can't be read"))?;+ let oauth = doc.get("claudeAiOauth").cloned().unwrap_or(Value::Null);+ if oauth["accessToken"].as_str() != Some(seen_access) {+ return Ok(RefreshOutcome::AlreadyRefreshed);+ }+ let Some(refresh_token) = oauth["refreshToken"].as_str().filter(|s| !s.is_empty()) else {+ return Err(signin_expired());+ };+ let resp = self+ .client+ .post(&self.cfg.oauth_token_url)+ .timeout(Duration::from_secs(30))+ .json(&json!({"grant_type": "refresh_token", "refresh_token": refresh_token, "client_id": OAUTH_CLIENT_ID}))+ .send()+ .await+ .map_err(|e| Deny::new(StatusCode::BAD_GATEWAY, codes::UPSTREAM_UNREACHABLE, format!("Couldn't refresh the Claude sign-in: {}", without_url(&e))))?;+ if !resp.status().is_success() {+ tracing::warn!(status = %resp.status(), file = %sha8(&path.to_string_lossy()), "Claude sign-in refresh refused");+ return Err(signin_expired());+ }+ let body: Value = resp.json().await.map_err(|_| signin_expired())?;+ let Some(access) = body["access_token"].as_str() else {+ return Err(signin_expired());+ };+ let o = doc["claudeAiOauth"].as_object_mut().ok_or_else(signin_expired)?;+ o.insert("accessToken".into(), json!(access));+ if let Some(r) = body["refresh_token"].as_str() {+ o.insert("refreshToken".into(), json!(r));+ }+ if let Some(secs) = body["expires_in"].as_i64() {+ o.insert("expiresAt".into(), json!(now_ms() + secs * 1000));+ }+ write_private(path, &serde_json::to_vec(&doc).unwrap_or_default())+ .map_err(|e| Deny::new(StatusCode::SERVICE_UNAVAILABLE, codes::CREDENTIAL_UNAVAILABLE, format!("Couldn't save the refreshed sign-in: {e}")))?;+ Ok(RefreshOutcome::Refreshed)+ }++ fn log(&self, mut rec: Value) {+ rec["t"] = json!(now_ms() as f64 / 1000.0);+ let _held = self.log_lock.lock().unwrap();+ let path = &self.cfg.log_path;+ if std::fs::metadata(path).map(|m| m.len() > LOG_ROTATE_BYTES).unwrap_or(false) {+ let _ = std::fs::rename(path, path.with_extension("log.1"));+ }+ if let Some(dir) = path.parent() {+ let _ = std::fs::create_dir_all(dir);+ }+ let mut opts = std::fs::OpenOptions::new();+ opts.create(true).append(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ opts.mode(0o600);+ }+ if let Ok(mut f) = opts.open(path) {+ let _ = writeln!(f, "{rec}");+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RefreshOutcome {+ Refreshed,+ AlreadyRefreshed,+}++impl RefreshOutcome {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Refreshed => "refreshed",+ Self::AlreadyRefreshed => "already_refreshed",+ }+ }+}++struct OAuthToken {+ access: String,+ expires_at: Option<i64>,+}++impl OAuthToken {+ fn expires_soon(&self) -> bool {+ self.expires_at.is_some_and(|t| t - now_ms() < REFRESH_MARGIN_MS)+ }+ fn expired(&self) -> bool {+ self.expires_at.is_some_and(|t| t <= now_ms())+ }+}++fn read_oauth(path: &Path) -> Result<OAuthToken, Deny> {+ let doc: Value = std::fs::read(path)+ .ok()+ .and_then(|b| serde_json::from_slice(&b).ok())+ .ok_or_else(|| Deny::new(StatusCode::SERVICE_UNAVAILABLE, codes::CREDENTIAL_UNAVAILABLE, "The Claude sign-in for this bot is missing. Sign in to Claude again."))?;+ let o = &doc["claudeAiOauth"];+ let access = o["accessToken"].as_str().filter(|s| !s.is_empty()).ok_or_else(signin_expired)?;+ Ok(OAuthToken { access: access.to_string(), expires_at: o["expiresAt"].as_i64() })+}++fn signin_expired() -> Deny {+ Deny::new(StatusCode::SERVICE_UNAVAILABLE, codes::SIGN_IN_EXPIRED, "The Claude sign-in has expired. Sign in to Claude again in Settings › Accounts.")+}++/// Writes `bytes` to `path` through a 0600 temp file in the same folder and a rename.+pub fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {+ let dir = path.parent().ok_or_else(|| std::io::Error::other("no folder"))?;+ let tmp = dir.join(format!(".{}.kwnt-{}", path.file_name().and_then(|n| n.to_str()).unwrap_or("f"), uuid::Uuid::new_v4().simple()));+ let mut opts = std::fs::OpenOptions::new();+ opts.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ opts.mode(0o600);+ }+ let result = (|| {+ let mut f = opts.open(&tmp)?;+ f.write_all(bytes)?;+ f.sync_all()?;+ std::fs::rename(&tmp, path)+ })();+ if result.is_err() {+ let _ = std::fs::remove_file(&tmp);+ }+ result+}++fn now_ms() -> i64 {+ SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)+}++fn sent_credential(h: &HeaderMap) -> &str {+ h.get("x-api-key")+ .or_else(|| h.get(hyper::header::AUTHORIZATION))+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+}++/// The headers sent on to Anthropic: only [`ANTHROPIC_FORWARD`] ones, `anthropic-beta` cut down+/// to [`KNOWN_BETAS`]. Returns the beta values stripped (for the log).+fn anthropic_headers(incoming: &HeaderMap) -> (HeaderMap, Vec<String>) {+ let mut out = HeaderMap::new();+ let mut stripped = Vec::new();+ for (k, v) in incoming.iter() {+ let name = k.as_str();+ if name == "anthropic-beta" {+ let Ok(text) = v.to_str() else {+ stripped.push("<non-ascii>".to_string());+ continue;+ };+ let keep: Vec<&str> = text+ .split(',')+ .map(str::trim)+ .filter(|b| !b.is_empty())+ .filter(|b| {+ let known = KNOWN_BETAS.contains(b);+ if !known {+ stripped.push(b.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').take(64).collect());+ }+ known+ })+ .collect();+ if let Ok(v) = HeaderValue::from_str(&keep.join(",")) {+ if !keep.is_empty() {+ out.append(k.clone(), v);+ }+ }+ } else if ANTHROPIC_FORWARD.contains(&name) || name.starts_with(ANTHROPIC_FORWARD_PREFIX) {+ out.append(k.clone(), v.clone());+ }+ }+ (out, stripped)+}++/// The container must send the stand-in of the same kind as the real credential: an API key+/// profile gets `x-api-key`, a sign-in gets `Authorization: Bearer`. A mismatch is a 409, never a+/// fall back to the other kind or an unauthenticated forward.+fn check_credential_kind(cred: &Credential, h: &HeaderMap) -> Result<(), Deny> {+ let api_key = h.contains_key("x-api-key");+ let bearer = h+ .get(hyper::header::AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .is_some_and(|v| v.len() > 7 && v[..7].eq_ignore_ascii_case("bearer "));+ let ok = match cred {+ Credential::ApiKey(_) => api_key && !h.contains_key(hyper::header::AUTHORIZATION),+ Credential::OAuthFile { .. } => bearer && !api_key,+ };+ if ok {+ Ok(())+ } else {+ Err(Deny::new(+ StatusCode::CONFLICT,+ codes::CREDENTIAL_MISMATCH,+ "The bot's computer sent a different kind of Claude credential than this bot uses",+ ))+ }+}++/// D3: a Messages request may not make Anthropic's servers reach anything: no `mcp_servers`, no+/// `container`, no server tools, and no content fetched by URL or from the Files API.+pub fn check_messages_body(body: &[u8]) -> Result<(), Deny> {+ // Mira's bodies (design/ui.md): the model reads them, so they say what to do next+ let refuse = |message: &'static str| Deny::new(StatusCode::BAD_REQUEST, codes::SERVER_TOOL_NOT_ALLOWED, message);+ // Strict: a key repeated anywhere is refused, since Anthropic and serde could keep+ // different copies (`"tools"` twice, or `"type"` twice in one tool).+ let doc: Value = parse_strict(body)+ .map_err(|_| Deny::new(StatusCode::BAD_REQUEST, codes::BAD_REQUEST, "The request body isn't valid JSON, or repeats a key"))?;+ let Some(top) = doc.as_object() else {+ return Err(Deny::new(StatusCode::BAD_REQUEST, codes::BAD_REQUEST, "The request body isn't a JSON object"));+ };+ if top.contains_key("mcp_servers") {+ return Err(refuse(super::notice::body::MCP_SERVERS));+ }+ if top.contains_key("container") {+ return Err(refuse(super::notice::body::SERVER_TOOL));+ }+ if let Some(tools) = top.get("tools") {+ let Some(tools) = tools.as_array() else {+ return Err(Deny::new(StatusCode::BAD_REQUEST, codes::BAD_REQUEST, "tools must be a list"));+ };+ for t in tools {+ match t.get("type") {+ None | Some(Value::Null) => {}+ Some(Value::String(ty)) if ALLOWED_TOOL_TYPES.contains(&ty.as_str()) => {}+ Some(Value::String(_)) => return Err(refuse(super::notice::body::SERVER_TOOL)),+ Some(_) => return Err(Deny::new(StatusCode::BAD_REQUEST, codes::BAD_REQUEST, "A tool's type must be text")),+ }+ }+ }+ if fetches_by_reference(&doc) {+ return Err(refuse(super::notice::body::FETCH_BY_REFERENCE));+ }+ Ok(())+}++/// Parses JSON, refusing a key repeated within any object, at any depth.+pub fn parse_strict(body: &[u8]) -> Result<Value, String> {+ use serde::de::{Deserialize, Deserializer, Error as _, MapAccess, SeqAccess, Visitor};+ struct Strict(Value);+ impl<'de> Deserialize<'de> for Strict {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ d.deserialize_any(V).map(Strict)+ }+ }+ struct V;+ impl<'de> Visitor<'de> for V {+ type Value = Value;+ fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str("JSON")+ }+ fn visit_bool<E>(self, v: bool) -> Result<Value, E> {+ Ok(Value::Bool(v))+ }+ fn visit_i64<E>(self, v: i64) -> Result<Value, E> {+ Ok(v.into())+ }+ fn visit_u64<E>(self, v: u64) -> Result<Value, E> {+ Ok(v.into())+ }+ fn visit_f64<E>(self, v: f64) -> Result<Value, E> {+ Ok(serde_json::Number::from_f64(v).map_or(Value::Null, Value::Number))+ }+ fn visit_str<E>(self, v: &str) -> Result<Value, E> {+ Ok(Value::String(v.into()))+ }+ fn visit_string<E>(self, v: String) -> Result<Value, E> {+ Ok(Value::String(v))+ }+ fn visit_unit<E>(self) -> Result<Value, E> {+ Ok(Value::Null)+ }+ fn visit_none<E>(self) -> Result<Value, E> {+ Ok(Value::Null)+ }+ fn visit_seq<A: SeqAccess<'de>>(self, mut a: A) -> Result<Value, A::Error> {+ let mut out = Vec::new();+ while let Some(Strict(x)) = a.next_element()? {+ out.push(x);+ }+ Ok(Value::Array(out))+ }+ fn visit_map<A: MapAccess<'de>>(self, mut a: A) -> Result<Value, A::Error> {+ let mut out = serde_json::Map::new();+ while let Some(k) = a.next_key::<String>()? {+ if out.contains_key(&k) {+ return Err(A::Error::custom("repeated key"));+ }+ let Strict(v) = a.next_value()?;+ out.insert(k, v);+ }+ Ok(Value::Object(out))+ }+ }+ let mut de = serde_json::Deserializer::from_slice(body);+ let Strict(v) = Strict::deserialize(&mut de).map_err(|e| e.to_string())?;+ de.end().map_err(|e| e.to_string())?;+ Ok(v)+}++/// Whether a content block Anthropic reads has a `source` it would fetch (`url`, `file`, or any+/// type but `base64`, `text` and `content`), or names a Files API upload. Only where Anthropic+/// reads content: `system` and `messages[].content`, with the blocks nested in a `tool_result`'s+/// `content` and a `content` document's `source.content`. Never `tools` (a tool's input schema can+/// have a property called `source`, as Claude's `AskUserQuestion` does: QA F-1) and never a+/// `tool_use`'s `input` (the model's own arguments, which Anthropic doesn't fetch from).+fn fetches_by_reference(doc: &Value) -> bool {+ let system = doc.get("system").is_some_and(blocks_fetch);+ let messages = doc+ .get("messages")+ .and_then(Value::as_array)+ .is_some_and(|ms| ms.iter().any(|m| m.get("content").is_some_and(blocks_fetch)));+ system || messages+}++/// `content` (a string, or a list of content blocks): whether any block fetches by reference.+fn blocks_fetch(content: &Value) -> bool {+ content.as_array().is_some_and(|blocks| blocks.iter().any(block_fetches))+}++fn block_fetches(block: &Value) -> bool {+ let Some(b) = block.as_object() else { return false };+ if b.get("type").and_then(Value::as_str) == Some("container_upload") || b.contains_key("file_id") {+ return true;+ }+ if let Some(source) = b.get("source").and_then(Value::as_object) {+ match source.get("type").and_then(Value::as_str) {+ Some("base64" | "text") => {}+ Some("content") => {+ if source.get("content").is_some_and(blocks_fetch) {+ return true;+ }+ }+ // `url`, `file`, anything newer, or a source without a type+ _ => return true,+ }+ }+ b.get("type").and_then(Value::as_str) == Some("tool_result") && b.get("content").is_some_and(blocks_fetch)+}++/// reqwest's error text without the URL (it can carry a token in the kwnt route's path).+fn without_url(e: &reqwest::Error) -> String {+ let mut msg = e.to_string();+ if let Some(url) = e.url() {+ msg = msg.replace(url.as_str(), "<url>");+ }+ if e.is_connect() {+ "connection failed".into()+ } else if e.is_timeout() {+ "timed out".into()+ } else {+ msg+ }+}++async fn read_body<B>(body: B) -> Result<Bytes, Deny>+where+ B: hyper::body::Body<Data = Bytes> + Send + 'static,+ B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,+{+ let read = tokio::time::timeout(BODY_TIMEOUT, Limited::new(body, MAX_REQUEST_BYTES).collect()).await;+ let Ok(read) = read else {+ return Err(Deny::new(StatusCode::REQUEST_TIMEOUT, codes::REQUEST_TIMEOUT, "The request body took too long to arrive"));+ };+ match read {+ Ok(c) => Ok(c.to_bytes()),+ Err(e) => {+ let too_large = e.downcast_ref::<http_body_util::LengthLimitError>().is_some();+ Err(if too_large {+ Deny::new(StatusCode::PAYLOAD_TOO_LARGE, codes::REQUEST_TOO_LARGE, "The request is larger than kwnt's broker forwards")+ } else {+ Deny::new(StatusCode::BAD_REQUEST, codes::REQUEST_TOO_LARGE, "The request body couldn't be read")+ })+ }+ }+}++/// Streams the upstream response back. Hop-by-hop headers, cookies and redirects' `Location` are+/// dropped; with `secret` set, any header carrying it is dropped and the body is scrubbed of it,+/// even where it is split across chunks.+fn stream_response(resp: reqwest::Response, secret: Option<Secret>) -> Response<BrokerBody> {+ let mut out = Response::builder().status(resp.status().as_u16());+ let needle = secret.map(|s| s.expose().as_bytes().to_vec()).filter(|n| n.len() >= 8);+ if let Some(h) = out.headers_mut() {+ for (k, v) in resp.headers().iter() {+ if DROP_RESPONSE.contains(&k.as_str()) {+ continue;+ }+ if needle.as_ref().is_some_and(|n| contains(v.as_bytes(), n)) {+ continue;+ }+ h.append(k.clone(), v.clone());+ }+ }+ let upstream = Box::pin(resp.bytes_stream()).map_err(|e| std::io::Error::other(without_url(&e)));+ let body = match needle {+ None => BodyExt::boxed_unsync(StreamBody::new(upstream.map_ok(Frame::data))),+ Some(n) => BodyExt::boxed_unsync(StreamBody::new(scrubbed(upstream, n).map_ok(Frame::data))),+ };+ out.body(body)+ .unwrap_or_else(|_| deny_response(&Deny::new(StatusCode::BAD_GATEWAY, codes::UPSTREAM_UNREACHABLE, "bad upstream response")))+}++fn contains(hay: &[u8], needle: &[u8]) -> bool {+ !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)+}++/// Replaces every occurrence of `needle` in a byte stream with `[redacted]`, holding back the+/// last `needle.len() - 1` bytes of each chunk until the next one shows whether they start it.+pub fn scrubbed<S>(stream: S, needle: Vec<u8>) -> impl futures::Stream<Item = Result<Bytes, std::io::Error>>+where+ S: futures::Stream<Item = Result<Bytes, std::io::Error>> + Unpin,+{+ struct St<S> {+ inner: S,+ buf: Vec<u8>,+ needle: Vec<u8>,+ done: bool,+ }+ fn redact(buf: &mut Vec<u8>, needle: &[u8]) {+ let mut out = Vec::with_capacity(buf.len());+ let mut i = 0;+ while i < buf.len() {+ if buf[i..].starts_with(needle) {+ out.extend_from_slice(b"[redacted]");+ i += needle.len();+ } else {+ out.push(buf[i]);+ i += 1;+ }+ }+ *buf = out;+ }+ futures::stream::unfold(St { inner: stream, buf: Vec::new(), needle, done: false }, |mut st| async move {+ use futures::StreamExt;+ loop {+ if st.done {+ return None;+ }+ match st.inner.next().await {+ Some(Ok(chunk)) => {+ st.buf.extend_from_slice(&chunk);+ redact(&mut st.buf, &st.needle);+ // Keep a tail that could be the start of the needle+ let keep = (st.needle.len() - 1).min(st.buf.len());+ let mut cut = st.buf.len() - keep;+ // never cut inside a "[redacted]" we just wrote: it can't start the needle anyway+ while cut < st.buf.len() && !st.needle.starts_with(&st.buf[cut..]) {+ cut += 1;+ }+ let out: Vec<u8> = st.buf.drain(..cut).collect();+ if !out.is_empty() {+ return Some((Ok(Bytes::from(out)), st));+ }+ }+ Some(Err(e)) => {+ st.done = true;+ return Some((Err(e), st));+ }+ None => {+ st.done = true;+ let rest = std::mem::take(&mut st.buf);+ if rest.is_empty() {+ return None;+ }+ return Some((Ok(Bytes::from(rest)), st));+ }+ }+ }+ })+}++/// An error shaped like Anthropic's own, so the CLI shows the message as it is. `x-should-retry:+/// false` keeps the Anthropic SDK from retrying a refusal.+pub fn deny_response(d: &Deny) -> Response<BrokerBody> {+ let body = json!({+ "type": "error",+ "error": {"type": "kwnt_broker", "code": d.code, "message": d.message},+ });+ Response::builder()+ .status(d.status)+ .header("content-type", "application/json")+ .header("x-should-retry", "false")+ .body(BodyExt::boxed_unsync(Full::new(Bytes::from(body.to_string())).map_err(|never: Infallible| match never {})))+ .expect("static response")+}++/// A request a test sends straight into [`Broker::handle`].+pub fn test_request(method: Method, path: &str, headers: &[(&str, &str)], body: &str) -> Request<Full<Bytes>> {+ let mut b = Request::builder().method(method).uri(path);+ for (k, v) in headers {+ b = b.header(*k, *v);+ }+ b.body(Full::new(Bytes::from(body.to_string()))).expect("test request")+}++/// Hyper's incoming body type, for callers that name it.+pub type IncomingBody = Incoming;++#[cfg(test)]+mod tests {+ use super::*;+ use axum::{routing::post, Router};+ use std::sync::atomic::AtomicUsize;++ #[derive(Clone, Default)]+ struct Seen {+ auth: Arc<StdMutex<Vec<String>>>,+ refreshes: Arc<AtomicUsize>,+ fail_first_with_401: Arc<StdMutex<bool>>,+ }++ /// A fake Anthropic: echoes the credential it got; `/oauth` refreshes.+ async fn fake_upstream(seen: Seen) -> String {+ let s1 = seen.clone();+ let s2 = seen.clone();+ let app = Router::new()+ .route(+ "/v1/messages",+ post(move |headers: axum::http::HeaderMap| {+ let seen = s1.clone();+ async move {+ let cred = headers+ .get("x-api-key")+ .or_else(|| headers.get("authorization"))+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .to_string();+ seen.auth.lock().unwrap().push(cred.clone());+ let mut first = seen.fail_first_with_401.lock().unwrap();+ if *first {+ *first = false;+ return (axum::http::StatusCode::UNAUTHORIZED, "expired".to_string());+ }+ (axum::http::StatusCode::OK, format!("{{\"ok\":true,\"len\":{}}}", cred.len()))+ }+ }),+ )+ .route(+ "/oauth",+ post(move |body: axum::Json<Value>| {+ let seen = s2.clone();+ async move {+ seen.refreshes.fetch_add(1, Ordering::SeqCst);+ assert_eq!(body["grant_type"], "refresh_token");+ assert_eq!(body["client_id"], OAUTH_CLIENT_ID);+ axum::Json(json!({"access_token": "sk-ant-oat01-NEW", "refresh_token": "sk-ant-ort01-NEW", "expires_in": 3600}))+ }+ }),+ );+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = l.local_addr().unwrap();+ tokio::spawn(async move { axum::serve(l, app).await.unwrap() });+ format!("http://{addr}")+ }++ fn broker(origin: &str, dir: &Path) -> Arc<Broker> {+ Broker::new(BrokerConfig {+ anthropic_origin: origin.into(),+ oauth_token_url: format!("{origin}/oauth"),+ log_path: dir.join("broker.log"),+ })+ }++ async fn body_text(r: Response<BrokerBody>) -> String {+ String::from_utf8(r.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap()+ }++ /// The stand-in headers the CLI in the container sends, by credential kind.+ const KEY: &[(&str, &str)] = &[("x-api-key", "sk-ant-api03-kwnt-dummy")];+ const BEARER: &[(&str, &str)] = &[("authorization", "Bearer sk-ant-oat01-kwnt-dummy")];++ fn spec(bot: &str, credential: Credential) -> TurnSpec {+ TurnSpec { bot: bot.into(), credential, kwnt_origin: None, cap: 3 }+ }++ #[tokio::test]+ async fn swaps_the_dummy_for_the_real_key_and_logs_no_secret() {+ let dir = tempfile::tempdir().unwrap();+ let seen = Seen::default();+ let b = broker(&fake_upstream(seen.clone()).await, dir.path());+ let lease = b.register(spec("bot-a", Credential::ApiKey(Secret::new("sk-ant-api03-REAL"))));+ let path = format!("/t/{}/anthropic/v1/messages?beta=true", lease.key());+ let r = b.handle("bot-a", test_request(Method::POST, &path, &[("x-api-key", "sk-ant-api03-kwnt-dummy")], "{}")).await;+ assert_eq!(r.status(), StatusCode::OK);+ assert_eq!(*seen.auth.lock().unwrap(), vec!["sk-ant-api03-REAL".to_string()]);+ let log = std::fs::read_to_string(dir.path().join("broker.log")).unwrap();+ assert!(!log.contains("sk-ant-api03-REAL") && !log.contains(lease.key()), "{log}");+ assert!(log.contains("\"decision\":\"forward\""), "{log}");+ assert!(format!("{:?}", Secret::new("sk-ant-api03-REAL")).starts_with("Secret(sha8="));+ }++ #[tokio::test]+ async fn refuses_other_paths_routes_bots_and_ended_turns() {+ let dir = tempfile::tempdir().unwrap();+ let seen = Seen::default();+ let b = broker(&fake_upstream(seen.clone()).await, dir.path());+ let lease = b.register(spec("bot-a", Credential::ApiKey(Secret::new("sk-ant-api03-REAL"))));+ let k = lease.key().to_string();+ let cases = [+ ("bot-a", Method::POST, format!("/t/{k}/anthropic/v1/oauth/token"), codes::PATH_NOT_ALLOWED),+ ("bot-a", Method::GET, format!("/t/{k}/anthropic/v1/messages"), codes::PATH_NOT_ALLOWED),+ ("bot-a", Method::POST, format!("/t/{k}/anthropic/v1/messages?x=1"), codes::PATH_NOT_ALLOWED),+ ("bot-a", Method::POST, format!("/t/{k}/anthropic/v1/files"), codes::PATH_NOT_ALLOWED),+ ("bot-a", Method::POST, format!("/t/{k}/openai/v1/responses"), codes::ROUTE_NOT_ALLOWED),+ ("bot-a", Method::POST, format!("/t/{k}/kwnt/api/mcp/self"), codes::PATH_NOT_ALLOWED),+ ("bot-a", Method::POST, "/anthropic/v1/messages".to_string(), codes::ROUTE_NOT_ALLOWED),+ ("bot-b", Method::POST, format!("/t/{k}/anthropic/v1/messages"), codes::UNKNOWN_TURN),+ ("bot-a", Method::POST, "/t/nope/anthropic/v1/messages".to_string(), codes::UNKNOWN_TURN),+ ];+ for (bot, m, p, code) in cases {+ let r = b.handle(bot, test_request(m.clone(), &p, &[], "{}")).await;+ assert_eq!(r.status(), StatusCode::FORBIDDEN, "{m} {p}");+ assert_eq!(r.headers()["x-should-retry"], "false");+ let text = body_text(r).await;+ assert!(text.contains(code), "{m} {p}: {text}");+ assert!(!text.contains("REAL"));+ }+ drop(lease);+ let r = b.handle("bot-a", test_request(Method::POST, &format!("/t/{k}/anthropic/v1/messages"), &[], "{}")).await;+ assert!(body_text(r).await.contains(codes::UNKNOWN_TURN));+ assert!(seen.auth.lock().unwrap().is_empty(), "nothing refused reached the upstream");+ }++ #[tokio::test]+ async fn caps_model_calls_per_turn_with_a_no_retry_429() {+ let dir = tempfile::tempdir().unwrap();+ let b = broker(&fake_upstream(Seen::default()).await, dir.path());+ let lease = b.register(spec("bot-a", Credential::ApiKey(Secret::new("k"))));+ let p = format!("/t/{}/anthropic/v1/messages", lease.key());+ for _ in 0..3 {+ assert_eq!(b.handle("bot-a", test_request(Method::POST, &p, KEY, "{}")).await.status(), StatusCode::OK);+ }+ let r = b.handle("bot-a", test_request(Method::POST, &p, KEY, "{}")).await;+ assert_eq!(r.status(), StatusCode::TOO_MANY_REQUESTS);+ assert_eq!(r.headers()["x-should-retry"], "false");+ assert!(body_text(r).await.contains(codes::REQUEST_CAP));+ // a new turn starts from zero+ let next = b.register(spec("bot-a", Credential::ApiKey(Secret::new("k"))));+ let p2 = format!("/t/{}/anthropic/v1/messages", next.key());+ assert_eq!(b.handle("bot-a", test_request(Method::POST, &p2, KEY, "{}")).await.status(), StatusCode::OK);+ }++ #[tokio::test]+ async fn parallel_requests_never_pass_the_cap() {+ let dir = tempfile::tempdir().unwrap();+ let seen = Seen::default();+ let b = broker(&fake_upstream(seen.clone()).await, dir.path());+ let lease = b.register(spec("bot-a", Credential::ApiKey(Secret::new("k"))));+ let p = format!("/t/{}/anthropic/v1/messages", lease.key());+ let calls = (0..20).map(|_| {+ let (b, p) = (b.clone(), p.clone());+ tokio::spawn(async move { b.handle("bot-a", test_request(Method::POST, &p, KEY, "{}")).await.status() })+ });+ let mut ok = 0;+ for c in calls {+ match c.await.unwrap() {+ StatusCode::OK => ok += 1,+ s => assert_eq!(s, StatusCode::TOO_MANY_REQUESTS),+ }+ }+ assert_eq!(ok, 3);+ assert_eq!(seen.auth.lock().unwrap().len(), 3, "the upstream saw exactly the cap");+ assert!(lease.cap_reached());+ }++ fn write_signin(path: &Path, access: &str, expires_at: i64) {+ std::fs::write(+ path,+ json!({"claudeAiOauth": {"accessToken": access, "refreshToken": "sk-ant-ort01-OLD", "expiresAt": expires_at, "scopes": ["user:inference"], "subscriptionType": "max"}, "other": 1}).to_string(),+ )+ .unwrap();+ }++ #[tokio::test]+ async fn owns_refresh_for_a_profile_sign_in_single_flight_keeping_other_fields() {+ let dir = tempfile::tempdir().unwrap();+ let seen = Seen::default();+ let b = broker(&fake_upstream(seen.clone()).await, dir.path());+ let creds = dir.path().join(".credentials.json");+ write_signin(&creds, "sk-ant-oat01-OLD", now_ms() + 10_000); // inside the margin+ let lease = b.register(spec("bot-a", Credential::OAuthFile { path: creds.clone(), refresh: true }));+ let p = format!("/t/{}/anthropic/v1/messages", lease.key());+ let (r1, r2) = tokio::join!(+ b.handle("bot-a", test_request(Method::POST, &p, &[("authorization", "Bearer dummy")], "{}")),+ b.handle("bot-a", test_request(Method::POST, &p, &[("authorization", "Bearer dummy")], "{}")),+ );+ assert_eq!((r1.status(), r2.status()), (StatusCode::OK, StatusCode::OK));+ assert_eq!(seen.refreshes.load(Ordering::SeqCst), 1, "two calls, one refresh");+ assert!(seen.auth.lock().unwrap().iter().all(|a| a == "Bearer sk-ant-oat01-NEW"));+ let doc: Value = serde_json::from_str(&std::fs::read_to_string(&creds).unwrap()).unwrap();+ assert_eq!(doc["claudeAiOauth"]["refreshToken"], "sk-ant-ort01-NEW");+ assert_eq!(doc["claudeAiOauth"]["subscriptionType"], "max");+ assert_eq!(doc["other"], 1);+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(std::fs::metadata(&creds).unwrap().permissions().mode() & 0o777, 0o600);+ }+ }++ #[tokio::test]+ async fn refreshes_once_on_a_401_then_retries() {+ let dir = tempfile::tempdir().unwrap();+ let seen = Seen::default();+ *seen.fail_first_with_401.lock().unwrap() = true;+ let b = broker(&fake_upstream(seen.clone()).await, dir.path());+ let creds = dir.path().join(".credentials.json");+ write_signin(&creds, "sk-ant-oat01-OLD", now_ms() + 3_600_000);+ let lease = b.register(spec("bot-a", Credential::OAuthFile { path: creds.clone(), refresh: true }));+ let r = b.handle("bot-a", test_request(Method::POST, &format!("/t/{}/anthropic/v1/messages", lease.key()), BEARER, "{}")).await;+ assert_eq!(r.status(), StatusCode::OK);+ assert_eq!(*seen.auth.lock().unwrap(), vec!["Bearer sk-ant-oat01-OLD".to_string(), "Bearer sk-ant-oat01-NEW".to_string()]);+ assert_eq!(seen.refreshes.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn never_refreshes_the_hosts_own_sign_in() {+ let dir = tempfile::tempdir().unwrap();+ let seen = Seen::default();+ let b = broker(&fake_upstream(seen.clone()).await, dir.path());+ let creds = dir.path().join(".credentials.json");+ write_signin(&creds, "sk-ant-oat01-OLD", now_ms() - 1);+ let before = std::fs::read(&creds).unwrap();+ let lease = b.register(spec("bot-a", Credential::OAuthFile { path: creds.clone(), refresh: false }));+ let r = b.handle("bot-a", test_request(Method::POST, &format!("/t/{}/anthropic/v1/messages", lease.key()), BEARER, "{}")).await;+ assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert!(body_text(r).await.contains(codes::SIGN_IN_EXPIRED));+ assert_eq!(seen.refreshes.load(Ordering::SeqCst), 0);+ assert!(seen.auth.lock().unwrap().is_empty());+ assert_eq!(std::fs::read(&creds).unwrap(), before, "the host's file is untouched");+ }++ #[tokio::test]+ async fn the_kwnt_route_passes_only_listed_paths_with_their_own_token() {+ let dir = tempfile::tempdir().unwrap();+ let got = Arc::new(StdMutex::new(Vec::<String>::new()));+ let g = got.clone();+ let app = Router::new().route(+ "/api/mcp/permission/:tok",+ post(move |axum::extract::Path(tok): axum::extract::Path<String>, headers: axum::http::HeaderMap| {+ let g = g.clone();+ async move {+ g.lock().unwrap().push(format!("{tok} {}", headers.get("authorization").and_then(|v| v.to_str().ok()).unwrap_or("-")));+ "ok"+ }+ }),+ );+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let origin = format!("http://{}", l.local_addr().unwrap());+ tokio::spawn(async move { axum::serve(l, app).await.unwrap() });+ let b = broker("http://127.0.0.1:1", dir.path());+ let lease = b.register(TurnSpec { kwnt_origin: Some(origin), ..spec("bot-a", Credential::ApiKey(Secret::new("k"))) });+ let tok = "0123456789abcdef0123456789abcdef";+ assert!(lease.allow_kwnt_path(&format!("/api/mcp/permission/{tok}")));+ assert!(!lease.allow_kwnt_path("/api/settings/computer"), "only kwnt's MCP endpoints");+ assert!(!lease.allow_kwnt_path("/api/mcp/permission/../servers"));+ let ok = b.handle("bot-a", test_request(Method::POST, &format!("/t/{}/kwnt/api/mcp/permission/{tok}", lease.key()), &[("authorization", "Bearer gw")], "{}")).await;+ assert_eq!(ok.status(), StatusCode::OK);+ let other = b.handle("bot-a", test_request(Method::POST, &format!("/t/{}/kwnt/api/mcp/permission/tok2", lease.key()), &[], "{}")).await;+ assert_eq!(other.status(), StatusCode::FORBIDDEN);+ assert_eq!(*got.lock().unwrap(), vec![format!("{tok} Bearer gw")]);+ let log = std::fs::read_to_string(dir.path().join("broker.log")).unwrap();+ assert!(!log.contains(tok) && !log.contains("Bearer gw"), "tokens are hashed in the log: {log}");+ }++ #[tokio::test]+ async fn refuses_rather_than_normalizes_odd_targets() {+ let dir = tempfile::tempdir().unwrap();+ let seen = Seen::default();+ let b = broker(&fake_upstream(seen.clone()).await, dir.path());+ let lease = b.register(spec("bot-a", Credential::ApiKey(Secret::new("k"))));+ let k = lease.key().to_string();+ let targets = [+ format!("/t/{k}/anthropic/v1/x/../messages"),+ format!("/t/{k}/anthropic/v1/./messages"),+ format!("/t/{k}/anthropic/v1/%2e%2e/v1/messages"),+ format!("/t/{k}/anthropic/v1/messages%2Fcount_tokens"),+ format!("/t/{k}/anthropic//v1/messages"),+ format!("/t/{k}//anthropic/v1/messages"),+ format!("/t/{k}/anthropic/v1/messages/"),+ format!("http://api.anthropic.com/t/{k}/anthropic/v1/messages"),+ ];+ for t in &targets {+ let r = b.handle("bot-a", test_request(Method::POST, t, &[], "{}")).await;+ assert_eq!(r.status(), StatusCode::BAD_REQUEST, "{t}");+ assert!(body_text(r).await.contains(codes::BAD_REQUEST), "{t}");+ }+ let p = format!("/t/{k}/anthropic/v1/messages");+ let both = b.handle("bot-a", test_request(Method::POST, &p, &[("content-length", "2"), ("transfer-encoding", "chunked")], "{}")).await;+ assert_eq!(both.status(), StatusCode::BAD_REQUEST);+ let two = b.handle("bot-a", test_request(Method::POST, &p, &[("content-length", "2"), ("content-length", "2")], "{}")).await;+ assert_eq!(two.status(), StatusCode::BAD_REQUEST);+ let connect = b.handle("bot-a", test_request(Method::CONNECT, &p, &[], "")).await;+ assert_eq!(connect.status(), StatusCode::BAD_REQUEST);+ assert_eq!(lease.requests(), 0, "nothing refused counted against the cap");+ assert!(seen.auth.lock().unwrap().is_empty(), "nothing refused reached the upstream");+ }++ /// Raw bytes on the socket: what hyper itself refuses before the broker sees a request.+ #[cfg(unix)]+ #[tokio::test]+ async fn the_socket_refuses_smuggling_and_oversized_heads() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let dir = tempfile::tempdir().unwrap();+ let seen = Seen::default();+ let b = broker(&fake_upstream(seen.clone()).await, dir.path());+ let lease = b.register(spec("bot-a", Credential::ApiKey(Secret::new("k"))));+ let sock = dir.path().join("run/broker.sock");+ b.listen("bot-a", &sock).await.unwrap();+ let k = lease.key().to_string();+ let send = |raw: Vec<u8>| {+ let sock = sock.clone();+ async move {+ let mut s = tokio::net::UnixStream::connect(&sock).await.unwrap();+ let _ = s.write_all(&raw).await;+ let mut out = Vec::new();+ let _ = tokio::time::timeout(Duration::from_secs(5), s.read_to_end(&mut out)).await;+ String::from_utf8_lossy(&out).into_owned()+ }+ };+ // CL + TE: refused, and the smuggled second request never runs+ let smuggle = format!(+ "POST /t/{k}/anthropic/v1/messages HTTP/1.1\r\nhost: x\r\ncontent-length: 4\r\ntransfer-encoding: chunked\r\n\r\n0\r\n\r\nPOST /t/{k}/anthropic/v1/messages HTTP/1.1\r\nhost: x\r\ncontent-length: 0\r\n\r\n"+ );+ let out = send(smuggle.into_bytes()).await;+ assert!(out.starts_with("HTTP/1.1 400"), "{out}");+ assert!(!out.contains("HTTP/1.1 200"), "{out}");+ // a 100 KB header+ let big = format!("POST /t/{k}/anthropic/v1/messages HTTP/1.1\r\nhost: x\r\nx-big: {}\r\ncontent-length: 0\r\n\r\n", "a".repeat(100 << 10));+ let out = send(big.into_bytes()).await;+ assert!(out.is_empty() || out.starts_with("HTTP/1.1 431") || out.starts_with("HTTP/1.1 400"), "{}", &out[..out.len().min(200)]);+ // absolute-form and authority-form request lines+ let abs = format!("POST http://api.anthropic.com/t/{k}/anthropic/v1/messages HTTP/1.1\r\nhost: x\r\ncontent-length: 0\r\nconnection: close\r\n\r\n");+ assert!(send(abs.into_bytes()).await.starts_with("HTTP/1.1 400"));+ let conn = "CONNECT api.anthropic.com:443 HTTP/1.1\r\nhost: api.anthropic.com:443\r\n\r\n".to_string();+ let out = send(conn.into_bytes()).await;+ assert!(!out.starts_with("HTTP/1.1 200"), "{out}");+ assert!(seen.auth.lock().unwrap().is_empty(), "nothing reached the upstream");+ b.close_all().await;+ }++ #[cfg(target_os = "linux")]+ fn rss_kb() -> u64 {+ std::fs::read_to_string("/proc/self/status")+ .ok()+ .and_then(|s| s.lines().find(|l| l.starts_with("VmRSS:")).and_then(|l| l.split_whitespace().nth(1)?.parse().ok()))+ .unwrap_or(0)+ }++ /// Test plan #6 (B-20 … B-22c): a huge body, a slow head and a connection flood each cost the+ /// sender only; the broker's memory stays bounded and the next client is served.+ #[cfg(target_os = "linux")]+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]+ async fn limits_cost_the_sender_only_and_the_next_client_is_served() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let dir = tempfile::tempdir().unwrap();+ let seen = Seen::default();+ let b = broker(&fake_upstream(seen.clone()).await, dir.path());+ let lease = b.register(TurnSpec { cap: 1000, ..spec("bot-a", Credential::ApiKey(Secret::new("sk-ant-api03-REAL"))) });+ let sock = dir.path().join("run/broker.sock");+ b.listen("bot-a", &sock).await.unwrap();+ let k = lease.key().to_string();+ let good = format!("POST /t/{k}/anthropic/v1/messages HTTP/1.1\r\nhost: x\r\nx-api-key: {DUMMY}\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{{}}", DUMMY = super::super::DUMMY_API_KEY);+ let ask = |raw: String| {+ let sock = sock.clone();+ async move {+ let mut s = tokio::net::UnixStream::connect(&sock).await.unwrap();+ let _ = s.write_all(raw.as_bytes()).await;+ let mut out = Vec::new();+ let _ = tokio::time::timeout(Duration::from_secs(20), s.read_to_end(&mut out)).await;+ String::from_utf8_lossy(&out).into_owned()+ }+ };+ let base = rss_kb();+ assert!(ask(good.clone()).await.starts_with("HTTP/1.1 200"), "a plain call is served");++ // B-20: a 40 MB body is refused from its Content-Length, before any of it arrives+ let t = std::time::Instant::now();+ let huge = format!("POST /t/{k}/anthropic/v1/messages HTTP/1.1\r\nhost: x\r\ncontent-length: {}\r\n\r\n", 40 << 20);+ let out = ask(huge).await;+ assert!(out.starts_with("HTTP/1.1 413"), "{out}");+ assert!(t.elapsed() < Duration::from_secs(5));++ // B-22: a head that never finishes is cut off after HEADER_TIMEOUT; meanwhile others are served+ let slow = {+ let sock = sock.clone();+ tokio::spawn(async move {+ let mut s = tokio::net::UnixStream::connect(&sock).await.unwrap();+ s.write_all(b"POST /t/").await.unwrap();+ let t = std::time::Instant::now();+ let mut out = Vec::new();+ let _ = tokio::time::timeout(HEADER_TIMEOUT * 3, s.read_to_end(&mut out)).await;+ t.elapsed()+ })+ };+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert!(ask(good.clone()).await.starts_with("HTTP/1.1 200"), "served while a slow head waits");+ let waited = slow.await.unwrap();+ assert!(waited < HEADER_TIMEOUT * 2, "the slow head was cut off after {waited:?}");++ // B-22c: a flood past MAX_CONNECTIONS; the extra connections are closed at once+ let mut held = Vec::new();+ for _ in 0..MAX_CONNECTIONS {+ let mut s = tokio::net::UnixStream::connect(&sock).await.unwrap();+ s.write_all(b"POST /t/").await.unwrap();+ held.push(s);+ }+ tokio::time::sleep(Duration::from_millis(200)).await;+ let mut extra = tokio::net::UnixStream::connect(&sock).await.unwrap();+ let _ = extra.write_all(good.as_bytes()).await;+ let mut buf = Vec::new();+ let r = tokio::time::timeout(Duration::from_secs(5), extra.read_to_end(&mut buf)).await;+ assert!(r.is_ok() && buf.is_empty(), "a connection past the limit is closed, not queued: {:?}", String::from_utf8_lossy(&buf));+ drop(held);+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert!(ask(good.clone()).await.starts_with("HTTP/1.1 200"), "served once the flood is gone");++ // Bounded memory: nothing above held more than a few MB+ let grew = rss_kb().saturating_sub(base);+ assert!(grew < 64 << 10, "the broker grew by {grew} KB");+ assert_eq!(seen.auth.lock().unwrap().len(), 3, "only the three plain calls reached the upstream");+ b.close_all().await;+ }++ #[test]+ fn a_repeated_key_is_refused_at_any_depth() {+ let dup = [+ r#"{"model":"m","model":"n"}"#,+ r#"{"tools":[{"name":"a","type":"custom","type":"web_search_20250305"}]}"#,+ r#"{"messages":[{"role":"user","content":[{"type":"text","text":"a","type":"image"}]}]}"#,+ r#"{"tools":[],"tools":[{"type":"web_search_20250305","name":"w"}]}"#,+ r#"{"a":{"b":{"c":1,"c":2}}}"#,+ ];+ for body in dup {+ assert!(parse_strict(body.as_bytes()).is_err(), "{body}");+ let d = check_messages_body(body.as_bytes()).unwrap_err();+ assert_eq!((d.status, d.code), (StatusCode::BAD_REQUEST, codes::BAD_REQUEST), "{body}");+ }+ // Same names in different objects are fine; so are escapes that only look alike+ let ok = r#"{"messages":[{"role":"user","content":"a"},{"role":"assistant","content":"b"}],"tools":[{"name":"x"}]}"#;+ assert_eq!(parse_strict(ok.as_bytes()).unwrap(), serde_json::from_str::<Value>(ok).unwrap());+ assert!(parse_strict(br#"{"a":1,"\u0061":2}"#).is_err(), "an escaped name is the same key");+ assert!(parse_strict(b"{\"a\":1} trailing").is_err());+ assert!(check_messages_body(ok.as_bytes()).is_ok());+ }++ #[test]+ fn server_tools_mcp_servers_and_fetches_are_refused_with_miras_words() {+ let cases = [+ (r#"{"tools":[{"type":"web_search_20250305","name":"web_search"}]}"#, crate::sandbox::agent_vm::notice::body::SERVER_TOOL),+ (r#"{"tools":[{"type":"web_fetch_20250910","name":"web_fetch"}]}"#, crate::sandbox::agent_vm::notice::body::SERVER_TOOL),+ (r#"{"tools":[{"type":"code_execution_20250825","name":"x"}]}"#, crate::sandbox::agent_vm::notice::body::SERVER_TOOL),+ (r#"{"container":"c1"}"#, crate::sandbox::agent_vm::notice::body::SERVER_TOOL),+ (r#"{"mcp_servers":[{"type":"url","url":"https://evil.example/mcp","name":"e"}]}"#, crate::sandbox::agent_vm::notice::body::MCP_SERVERS),+ (+ r#"{"messages":[{"role":"user","content":[{"type":"image","source":{"type":"url","url":"https://evil.example/?d=secret"}}]}]}"#,+ crate::sandbox::agent_vm::notice::body::FETCH_BY_REFERENCE,+ ),+ (+ r#"{"messages":[{"role":"user","content":[{"type":"document","source":{"type":"file","file_id":"file_1"}}]}]}"#,+ crate::sandbox::agent_vm::notice::body::FETCH_BY_REFERENCE,+ ),+ ];+ for (body, words) in cases {+ let d = check_messages_body(body.as_bytes()).unwrap_err();+ assert_eq!((d.status, d.code), (StatusCode::BAD_REQUEST, codes::SERVER_TOOL_NOT_ALLOWED), "{body}");+ assert_eq!(d.message, words, "{body}");+ }+ let fine = r#"{"model":"claude-haiku","tools":[{"name":"Bash","input_schema":{}},{"type":"custom","name":"x","input_schema":{}}],+ "messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"AA=="}}]}]}"#;+ assert!(check_messages_body(fine.as_bytes()).is_ok());+ }++ #[test]+ fn a_source_is_checked_only_where_anthropic_reads_content() {+ // QA F-1: Claude's AskUserQuestion tool (sent with --permission-prompt-tool) has a schema+ // property called `source`. Refusing it refused every turn with kwnt's tools.+ let ask = r#"{"name":"AskUserQuestion","input_schema":{"type":"object","properties":{"metadata":{"type":"object",+ "properties":{"source":{"type":"string","description":"Optional identifier for the source of this question"}}}}}}"#;+ let body = format!(r#"{{"model":"m","tools":[{ask}],"messages":[{{"role":"user","content":"hi"}}]}}"#);+ assert!(check_messages_body(body.as_bytes()).is_ok(), "a tool schema's `source` property");+ let body = r#"{"tools":[{"name":"x","input_schema":{"properties":{"source":{"type":"url"}}}}]}"#;+ assert!(check_messages_body(body.as_bytes()).is_ok(), "even one whose type looks like a fetch");+ // The model's own tool arguments in the history aren't fetched either+ let body = r#"{"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"x","input":{"source":{"type":"url","url":"https://a.example"}}}]}]}"#;+ assert!(check_messages_body(body.as_bytes()).is_ok(), "tool_use input");+ // A search result's `source` is a string it cites, not a fetch+ let body = r#"{"messages":[{"role":"user","content":[{"type":"search_result","source":"https://a.example","title":"t","content":[{"type":"text","text":"x"}]}]}]}"#;+ assert!(check_messages_body(body.as_bytes()).is_ok(), "search_result");++ // Still refused wherever Anthropic reads content+ let refused = [+ r#"{"messages":[{"role":"user","content":[{"type":"image","source":{"type":"url","url":"https://evil.example"}}]}]}"#,+ r#"{"system":[{"type":"document","source":{"type":"url","url":"https://evil.example/a.pdf"}}]}"#,+ r#"{"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":[{"type":"image","source":{"type":"file","file_id":"f"}}]}]}]}"#,+ r#"{"messages":[{"role":"user","content":[{"type":"document","source":{"type":"content","content":[{"type":"image","source":{"type":"url","url":"https://e.example"}}]}}]}]}"#,+ r#"{"messages":[{"role":"user","content":[{"type":"image","source":{"type":"something_new"}}]}]}"#,+ r#"{"messages":[{"role":"user","content":[{"type":"image","source":{"url":"https://e.example"}}]}]}"#,+ r#"{"messages":[{"role":"user","content":[{"type":"container_upload","file_id":"file_1"}]}]}"#,+ ];+ for body in refused {+ let d = check_messages_body(body.as_bytes()).unwrap_err();+ assert_eq!(d.message, crate::sandbox::agent_vm::notice::body::FETCH_BY_REFERENCE, "{body}");+ }+ // Inline content still passes, nested too+ let body = r#"{"system":[{"type":"text","text":"x"}],"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"AA=="}}]},+ {"type":"document","source":{"type":"text","media_type":"text/plain","data":"x"}},+ {"type":"document","source":{"type":"content","content":[{"type":"text","text":"x"}]}}]}]}"#;+ assert!(check_messages_body(body.as_bytes()).is_ok());+ }++ #[test]+ fn unknown_betas_are_stripped_and_only_listed_headers_pass() {+ let mut h = HeaderMap::new();+ h.insert("anthropic-beta", HeaderValue::from_static("claude-code-20250219, mcp-client-2025-04-04,oauth-2025-04-20"));+ h.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));+ h.insert("x-stainless-os", HeaderValue::from_static("Linux"));+ h.insert("x-api-key", HeaderValue::from_static("sk-dummy"));+ h.insert("cookie", HeaderValue::from_static("a=b"));+ h.insert("x-forwarded-for", HeaderValue::from_static("1.2.3.4"));+ let (out, stripped) = anthropic_headers(&h);+ assert_eq!(out["anthropic-beta"], "claude-code-20250219,oauth-2025-04-20");+ assert_eq!(stripped, vec!["mcp-client-2025-04-04".to_string()]);+ assert_eq!(out["anthropic-version"], "2023-06-01");+ assert!(out.contains_key("x-stainless-os"));+ for gone in ["x-api-key", "cookie", "x-forwarded-for", "authorization"] {+ assert!(!out.contains_key(gone), "{gone}");+ }+ // Only unknown betas: the header goes away rather than being sent empty+ let mut h = HeaderMap::new();+ h.insert("anthropic-beta", HeaderValue::from_static("mcp-client-2025-04-04"));+ assert!(!anthropic_headers(&h).0.contains_key("anthropic-beta"));+ }++ #[tokio::test]+ async fn a_stand_in_of_the_other_kind_is_a_409_and_reaches_nothing() {+ let dir = tempfile::tempdir().unwrap();+ let seen = Seen::default();+ let b = broker(&fake_upstream(seen.clone()).await, dir.path());+ let key = b.register(spec("bot-a", Credential::ApiKey(Secret::new("sk-ant-api03-REAL"))));+ let creds = dir.path().join(".credentials.json");+ write_signin(&creds, "sk-ant-oat01-OLD", now_ms() + 3_600_000);+ let oauth = b.register(spec("bot-a", Credential::OAuthFile { path: creds, refresh: true }));+ let path = |l: &TurnLease| format!("/t/{}/anthropic/v1/messages", l.key());+ for (lease, headers) in [+ (&key, BEARER),+ (&key, &[][..]),+ (&key, &[("x-api-key", "d"), ("authorization", "Bearer d")][..]),+ (&oauth, KEY),+ (&oauth, &[][..]),+ (&oauth, &[("authorization", "Basic abc")][..]),+ ] {+ let r = b.handle("bot-a", test_request(Method::POST, &path(lease), headers, "{}")).await;+ assert_eq!(r.status(), StatusCode::CONFLICT, "{headers:?}");+ assert!(body_text(r).await.contains(codes::CREDENTIAL_MISMATCH));+ }+ assert_eq!((key.requests(), oauth.requests()), (0, 0), "a mismatch isn't counted");+ assert!(seen.auth.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn the_secret_is_redacted_even_when_split_across_chunks() {+ use futures::StreamExt;+ let secret = b"sk-ant-api03-SECRETSECRET".to_vec();+ let text = b"data: {\"echo\":\"sk-ant-api03-SECRETSECRET\"} and again sk-ant-api03-SECRETSECRET!".to_vec();+ for split in 1..text.len() {+ // every two-chunk split, and one byte at a time+ let chunks: Vec<Result<Bytes, std::io::Error>> =+ vec![Ok(Bytes::copy_from_slice(&text[..split])), Ok(Bytes::copy_from_slice(&text[split..]))];+ let out: Vec<u8> = scrubbed(futures::stream::iter(chunks), secret.clone())+ .map(|c| c.unwrap().to_vec())+ .collect::<Vec<_>>()+ .await+ .concat();+ assert_eq!(out, b"data: {\"echo\":\"[redacted]\"} and again [redacted]!".to_vec(), "split at {split}");+ }+ let bytes: Vec<Result<Bytes, std::io::Error>> = text.iter().map(|b| Ok(Bytes::copy_from_slice(&[*b]))).collect();+ let out: Vec<u8> = scrubbed(futures::stream::iter(bytes), secret.clone()).map(|c| c.unwrap().to_vec()).collect::<Vec<_>>().await.concat();+ assert!(!contains(&out, &secret) && contains(&out, b"[redacted]"));+ // A prefix of the secret at the very end is passed on once the stream ends+ let tail: Vec<Result<Bytes, std::io::Error>> = vec![Ok(Bytes::from_static(b"ok sk-ant"))];+ let out: Vec<u8> = scrubbed(futures::stream::iter(tail), secret).map(|c| c.unwrap().to_vec()).collect::<Vec<_>>().await.concat();+ assert_eq!(out, b"ok sk-ant".to_vec());+ }++ /// The allow-list and the betas are exactly what Gate 0 saw the real CLI send (plus the+ /// sign-in beta, which an API-key run can't show).+ #[test]+ fn the_anthropic_lists_match_the_gate_0_evidence() {+ let ev = include_str!("../../../proto/agents-in-vm/evidence/real-upstream.txt");+ let mut seen = std::collections::BTreeSet::new();+ for l in ev.lines().filter(|l| !l.starts_with('#') && !l.is_empty()) {+ let f: Vec<&str> = l.split('\t').collect();+ assert_eq!(f[4], "forward", "Gate 0 had a refused call: {l}");+ let (path, query) = f[2].strip_prefix("/anthropic").unwrap().split_once('?').unwrap_or((f[2], ""));+ seen.insert((f[1].to_string(), path.to_string(), query.to_string()));+ }+ assert!(!seen.is_empty());+ for (m, p, q) in &seen {+ assert!(ANTHROPIC_ALLOWED.iter().any(|(am, ap, aq)| am == m && ap == p && aq.contains(&q.as_str())), "{m} {p}?{q}");+ }+ for (m, p, _) in ANTHROPIC_ALLOWED {+ assert!(seen.iter().any(|(sm, sp, _)| sm == m && sp == p), "{m} {p} is allowed but Gate 0 never saw it");+ }+ let betas = ev.lines().find_map(|l| l.strip_prefix("# betas: ")).unwrap();+ let mut betas: Vec<&str> = betas.split(", ").collect();+ betas.push("oauth-2025-04-20");+ betas.sort_unstable();+ let mut known = KNOWN_BETAS.to_vec();+ known.sort_unstable();+ assert_eq!(known, betas);+ let types = ev.lines().find_map(|l| l.strip_prefix("# tool_types: ")).unwrap();+ assert_eq!(types.split(", ").collect::<Vec<_>>(), ALLOWED_TOOL_TYPES);+ }++ #[test]+ fn kwnt_paths_are_an_exact_list() {+ for ok in ["/api/mcp/self", "/api/mcp/gateway", "/api/mcp/permission/abc_DEF-123"] {+ assert!(kwnt_path_allowed(ok), "{ok}");+ }+ for bad in [+ "/api/mcp/self/", "/api/mcp/selfx", "/api/mcp/gateway/grok", "/api/mcp/permission/", "/api/mcp/permission/a/b",+ "/api/mcp/permission/a.b", "/api/settings/computer", "/api/mcp/servers", "/api/kwants", "/",+ ] {+ assert!(!kwnt_path_allowed(bad), "{bad}");+ }+ assert!(!kwnt_path_allowed(&format!("/api/mcp/permission/{}", "a".repeat(129))));+ assert!(kwnt_path_allowed(&format!("/api/mcp/permission/{}", "a".repeat(128))));+ }++ #[test]+ fn scrub_hashes_long_and_id_like_segments() {+ assert_eq!(scrub_path("/v1/messages?beta=true"), "/v1/messages?beta=true");+ let s = scrub_path("/api/mcp/permission/0123456789abcdef0123456789abcdef");+ assert!(s.starts_with("/api/mcp/permission/h:") && !s.contains("0123456789abcdef"), "{s}");+ assert!(scrub_path("/x?token=abcdefghijklmnop").contains("token=h:"));+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn serves_on_a_private_unix_socket() {+ use std::os::unix::fs::PermissionsExt;+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let dir = tempfile::tempdir().unwrap();+ let b = broker("http://127.0.0.1:1", dir.path());+ let sock = dir.path().join("run/broker.sock");+ b.listen("bot-a", &sock).await.unwrap();+ assert_eq!(std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777, 0o600);+ assert_eq!(std::fs::metadata(sock.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700);+ let mut s = tokio::net::UnixStream::connect(&sock).await.unwrap();+ s.write_all(b"POST /anthropic/v1/messages HTTP/1.1\r\nhost: x\r\ncontent-length: 0\r\nconnection: close\r\n\r\n").await.unwrap();+ let mut out = String::new();+ s.read_to_string(&mut out).await.unwrap();+ assert!(out.starts_with("HTTP/1.1 403") && out.contains(codes::ROUTE_NOT_ALLOWED), "{out}");+ b.close_all().await;+ assert!(!sock.exists());+ }+}diff --git a/src/sandbox/agent_vm/folder_rule.rs b/src/sandbox/agent_vm/folder_rule.rsnew file mode 100644index 00000000..0e9a9955--- /dev/null+++ b/src/sandbox/agent_vm/folder_rule.rs@@ -0,0 +1,266 @@+//! Which folders a bot may share with its isolated Claude container (Ada's D5 as amended at+//! 15:05 UTC on 2026-11-08, after Mira found that D5 as first written refused every default+//! folder: `agents-in-vm/ada-decisions-2.md`, "Addendum").+//!+//! The folder is canonicalized first (symlinks resolved), then refused when it:+//! - is `/` ([`UnsafeKind::Root`]);+//! - is the person's home, or holds it ([`UnsafeKind::Home`], [`UnsafeKind::ContainsHome`]);+//! a project folder *inside* the home is fine;+//! - is, holds or sits inside a sign-in folder: kwnt's account profiles, the turn's own+//! credential folder, `~/.ssh`, `~/.claude`, `~/.codex`, `~/.grok` ([`UnsafeKind::SignIns`]);+//! - is, holds or sits inside the folder of Docker's control socket ([`UnsafeKind::Docker`]);+//! - is a space's shared default folder `<space data>/workspace`, or inside it+//! ([`UnsafeKind::SharedFolder`]): every team without its own folder shares it, so D4's mark+//! would then refuse Codex and Grok in all of them; the refusal lands on the bot that opted in;+//! - is or holds kwnt's data dir, or sits inside it anywhere but a bot's or a team's own work+//! folder ([`UnsafeKind::KwantData`]).+//!+//! Inside the data dir only these are allowed, because a bot's and a repo team's default folders+//! live there: `<space data>/bot-workspaces/<bot>/…` and `<space data>/workspaces/<team>/…`, where+//! `<space data>` is the data dir (Default space) or `spaces/<space>`. Everything else there (the+//! database, vault, keys, profiles, checkpoints, the CLI homes in `agent-vm/`, `spaces/<space>`+//! and the parents `bot-workspaces/` and `workspaces/` themselves) is refused.++use std::path::{Component, Path, PathBuf};++/// Why a folder is refused. Sent to the chat as `unsafe_kind`, which picks the reason sentence.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum UnsafeKind {+ Home,+ ContainsHome,+ SignIns,+ KwantData,+ Root,+ Docker,+ SharedFolder,+}++impl UnsafeKind {+ pub fn as_str(self) -> &'static str {+ match self {+ UnsafeKind::Home => "home",+ UnsafeKind::ContainsHome => "contains_home",+ UnsafeKind::SignIns => "sign_ins",+ UnsafeKind::KwantData => "kwant_data",+ UnsafeKind::Root => "root",+ UnsafeKind::Docker => "docker",+ UnsafeKind::SharedFolder => "shared_folder",+ }+ }+}++/// The places a shared folder is checked against, canonicalized where they exist.+#[derive(Debug, Clone, Default)]+pub struct Places {+ pub home: Option<PathBuf>,+ pub data_dir: PathBuf,+ pub sign_ins: Vec<PathBuf>,+ pub docker: Vec<PathBuf>,+}++/// Credential folders under the person's home that are never shared.+const HOME_SIGN_INS: &[&str] = &[".ssh", ".claude", ".codex", ".grok"];++impl Places {+ /// This computer's places, for a turn whose credential lives in `credential_home`.+ pub fn for_host(data_dir: &Path, credential_home: Option<&Path>) -> Self {+ let home = dirs::home_dir();+ let mut sign_ins = vec![data_dir.join("profiles")];+ sign_ins.extend(credential_home.map(Path::to_path_buf));+ if let Some(h) = &home {+ sign_ins.extend(HOME_SIGN_INS.iter().map(|d| h.join(d)));+ }+ Self {+ home: home.map(|h| canon(&h)),+ data_dir: canon(data_dir),+ sign_ins: sign_ins.iter().map(|p| canon(p)).collect(),+ docker: docker_socket_dirs().iter().map(|p| canon(p)).collect(),+ }+ }+}++/// `None` when `folder` (already canonical) may be shared, else why not. The order picks the+/// most specific sentence: a sign-in folder inside the data dir says "sign-ins", not "kwant data".+pub fn classify(folder: &Path, p: &Places) -> Option<UnsafeKind> {+ if folder.parent().is_none() {+ return Some(UnsafeKind::Root);+ }+ if let Some(home) = &p.home {+ if folder == home {+ return Some(UnsafeKind::Home);+ }+ if home.starts_with(folder) {+ return Some(UnsafeKind::ContainsHome);+ }+ }+ // Holding the data dir also holds its sign-ins; Mira's `kwant_data` sentence says both+ if p.data_dir.starts_with(folder) {+ return Some(UnsafeKind::KwantData);+ }+ let related = |s: &PathBuf| s.starts_with(folder) || folder.starts_with(s);+ if p.sign_ins.iter().any(related) {+ return Some(UnsafeKind::SignIns);+ }+ if p.docker.iter().any(related) {+ return Some(UnsafeKind::Docker);+ }+ match folder.strip_prefix(&p.data_dir) {+ Ok(rel) => in_data_dir(rel),+ Err(_) => None,+ }+}++/// For a path relative to the data dir: `None` inside a bot's or a team's own work folder,+/// else why it's refused.+fn in_data_dir(rel: &Path) -> Option<UnsafeKind> {+ let parts: Vec<&str> = rel+ .components()+ .map(|c| match c {+ Component::Normal(s) => s.to_str().unwrap_or("\u{0}"),+ _ => "\u{0}",+ })+ .collect();+ let in_space = |p: &[&str]| match p {+ ["workspaces", _, ..] | ["bot-workspaces", _, ..] => None,+ ["workspace", ..] => Some(UnsafeKind::SharedFolder),+ _ => Some(UnsafeKind::KwantData),+ };+ match parts.as_slice() {+ ["spaces", _, rest @ ..] if !rest.is_empty() => in_space(rest),+ ["spaces", ..] => Some(UnsafeKind::KwantData),+ all => in_space(all),+ }+}++fn canon(p: &Path) -> PathBuf {+ p.canonicalize().unwrap_or_else(|_| p.to_path_buf())+}++/// Folders holding a Docker control socket: the system one, a `unix://` `DOCKER_HOST`, and the+/// rootless one in `XDG_RUNTIME_DIR`.+fn docker_socket_dirs() -> Vec<PathBuf> {+ let mut socks = vec![PathBuf::from("/var/run/docker.sock"), PathBuf::from("/run/docker.sock")];+ if let Some(h) = std::env::var("DOCKER_HOST").ok().and_then(|h| h.strip_prefix("unix://").map(PathBuf::from)) {+ socks.push(h);+ }+ if let Some(x) = std::env::var_os("XDG_RUNTIME_DIR") {+ socks.push(PathBuf::from(x).join("docker.sock"));+ }+ let mut dirs: Vec<PathBuf> = socks.iter().filter(|s| s.exists()).filter_map(|s| canon(s).parent().map(Path::to_path_buf)).collect();+ dirs.sort();+ dirs.dedup();+ dirs+}++#[cfg(test)]+mod tests {+ use super::*;++ fn places() -> Places {+ Places {+ home: Some("/home/p".into()),+ data_dir: "/home/p/.kwnt".into(),+ sign_ins: vec![+ "/home/p/.kwnt/profiles".into(),+ "/srv/creds/claude".into(),+ "/home/p/.ssh".into(),+ "/home/p/.claude".into(),+ "/home/p/.codex".into(),+ "/home/p/.grok".into(),+ ],+ docker: vec!["/run".into()],+ }+ }++ fn kind(f: &str) -> Option<&'static str> {+ classify(Path::new(f), &places()).map(UnsafeKind::as_str)+ }++ #[test]+ fn a_default_solo_bot_folder_is_accepted() {+ // tools::bot_workspace(space_data_dir, id) for the Default space and another space+ let data = Path::new("/home/p/.kwnt");+ let def = crate::tools::bot_workspace_path(data, "kw_abc");+ assert_eq!(def, Path::new("/home/p/.kwnt/bot-workspaces/kw_abc"));+ assert_eq!(classify(&def, &places()), None);+ let other = crate::tools::bot_workspace_path(&data.join("spaces").join("spc_2"), "kw_abc");+ assert_eq!(classify(&other, &places()), None);+ }++ #[test]+ fn a_repo_teams_default_folder_is_accepted() {+ let data = Path::new("/home/p/.kwnt");+ let f = crate::tools::team_workspace_path(data, "Checkout", None, Some("https://github.com/a/b"));+ assert_eq!(f, Path::new("/home/p/.kwnt/workspaces/Checkout"));+ assert_eq!(classify(&f, &places()), None);+ for ok in [+ "/home/p/.kwnt/workspaces/Checkout/src",+ "/home/p/.kwnt/spaces/spc_2/workspaces/Checkout",+ "/home/p/.kwnt/spaces/spc_2/bot-workspaces/kw_1/sub",+ "/home/p/projects/site",+ "/srv/other",+ ] {+ assert_eq!(kind(ok), None, "{ok}");+ }+ }++ #[test]+ fn the_shared_default_folder_is_refused_as_shared() {+ let data = Path::new("/home/p/.kwnt");+ let f = crate::tools::team_workspace_path(data, "Checkout", None, None);+ assert_eq!(f, Path::new("/home/p/.kwnt/workspace"));+ assert_eq!(classify(&f, &places()), Some(UnsafeKind::SharedFolder));+ for bad in ["/home/p/.kwnt/workspace/site", "/home/p/.kwnt/spaces/spc_2/workspace"] {+ assert_eq!(kind(bad), Some("shared_folder"), "{bad}");+ }+ }++ #[test]+ fn the_rest_of_the_data_dir_is_refused() {+ for bad in [+ "/home/p/.kwnt",+ "/home/p/.kwnt/workspaces",+ "/home/p/.kwnt/bot-workspaces",+ "/home/p/.kwnt/spaces",+ "/home/p/.kwnt/spaces/spc_2",+ "/home/p/.kwnt/spaces/spc_2/workspaces",+ "/home/p/.kwnt/spaces/spc_2/bot-workspaces",+ "/home/p/.kwnt/agent-vm",+ "/home/p/.kwnt/agent-vm/0123abcd/home",+ "/home/p/.kwnt/checkpoints/t1",+ "/home/p/.kwnt/browser-cookies",+ ] {+ assert_eq!(kind(bad), Some("kwant_data"), "{bad}");+ }+ }++ #[test]+ fn each_refusal_names_its_kind() {+ let cases = [+ ("/", "root"),+ ("/home/p", "home"),+ ("/home", "contains_home"),+ ("/home/p/.kwnt/profiles", "sign_ins"),+ ("/home/p/.kwnt/profiles/pr_1", "sign_ins"),+ ("/home/p/.ssh", "sign_ins"),+ ("/home/p/.claude/projects", "sign_ins"),+ ("/home/p/.codex", "sign_ins"),+ ("/home/p/.grok", "sign_ins"),+ ("/srv/creds", "sign_ins"),+ ("/srv/creds/claude/x", "sign_ins"),+ ("/run", "docker"),+ ("/run/user/1000", "docker"),+ ];+ for (f, k) in cases {+ assert_eq!(kind(f), Some(k), "{f}");+ }+ }++ #[test]+ fn a_name_that_only_looks_like_a_work_folder_is_refused() {+ // starts_with compares whole components, and only kwnt's own layout counts+ assert_eq!(kind("/home/p/.kwnt/workspace-old"), Some("kwant_data"));+ assert_eq!(kind("/home/p/.kwnt/profiles/../workspace"), Some("sign_ins"));+ assert_eq!(kind("/home/p/.kwnt/x/bot-workspaces/kw_1"), Some("kwant_data"));+ }+}diff --git a/src/sandbox/agent_vm/mod.rs b/src/sandbox/agent_vm/mod.rsnew file mode 100644index 00000000..b08929e3--- /dev/null+++ b/src/sandbox/agent_vm/mod.rs@@ -0,0 +1,1493 @@+//! Agents in the VM, slice 1: Claude turns run in a per-bot container with no network and no+//! real credential, when the person turns on "Run Claude inside the VM" (Linux only, off by+//! default). Design: `docs/agents-in-vm.md`.+//!+//! A turn is prepared by [`AgentVm::prepare_turn`], which fails closed: with the setting on, any+//! missing piece (Docker, the image, the broker, the container, a credential) is a clear error+//! for the turn and never a run on the host with the real credential. The prepared+//! [`IsolatedTurn`] turns the CLI command kwnt would have run on the host into a `docker exec` in+//! the bot's container, with only allow-listed env and a stand-in credential; the broker+//! ([`broker`]) adds the real one on the way out.++pub mod broker;+pub mod folder_rule;+pub mod notice;++use broker::{Broker, BrokerConfig, Credential, Secret, TurnLease, TurnSpec};+use serde_json::{json, Value};+use std::collections::HashMap;+use std::ffi::OsString;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex as StdMutex};+use std::time::{Duration, Instant};+use tokio::process::Command;+use tokio::sync::{OwnedSemaphorePermit, Semaphore};++pub use crate::config::AgentsInVmConfig;++/// The setting (kwnt's settings table) for "Run Claude inside the VM": kept in both modes, only+/// the person changes it, and outside vm mode it has no effect (D1).+pub const SETTING_KEY: &str = "computer_isolate_claude";+/// The Claude Code version baked into the agent image (the host's at the time of slice 1).+pub const CLAUDE_VERSION: &str = "2.1.316";+/// Where the CLI in the container reaches the broker (socat in the container).+pub const IN_CONTAINER_ORIGIN: &str = "http://127.0.0.1:8080";+const CONTAINER_HOME: &str = "/home/agent";+const CONTAINER_RUN: &str = "/run/kwnt";+const IDLE_REMOVE_AFTER: Duration = Duration::from_secs(30 * 60);+/// How long a turn's processes get to exit after its TERM before the container goes (R-9).+const STOP_GRACE: Duration = Duration::from_secs(1);+/// Stand-in credentials the CLI in the container holds; the broker drops them.+pub const DUMMY_API_KEY: &str = "sk-ant-api03-kwnt-broker-stand-in-not-a-key-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";+pub const DUMMY_OAUTH_TOKEN: &str = "sk-ant-oat01-kwnt-broker-stand-in-not-a-token-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";++pub fn image_tag() -> String {+ format!("kwnt-agent:v1-claude-{CLAUDE_VERSION}")+}++/// Why a Claude turn can't run isolated. `code` is stable (UI and docs); `message` is for the+/// person.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Refusal {+ pub code: &'static str,+ pub message: String,+ /// For `unsafe_folder`: why, for the chat meta's `unsafe_kind` ([`notice::IsolationFailed`]).+ pub unsafe_kind: Option<folder_rule::UnsafeKind>,+}++/// Refusal codes. Where Mira's chat notices have a reason (`design/ui.md`), the code is that+/// reason; the rest get her "unknown code" notice, which names the code.+pub mod codes {+ pub const UNSUPPORTED_OS: &str = "unsupported_os";+ pub const DOCKER_UNAVAILABLE: &str = "docker_unavailable";+ /// The agent image is being set up (notice 2): the reply fails rather than waits.+ pub const PREPARING: &str = "preparing";+ /// The image setup failed (notice 2b).+ pub const DOWNLOAD_FAILED: &str = "download_failed";+ /// kwnt's broker socket couldn't start (notice 2c).+ pub const RELAY_DOWN: &str = "relay_down";+ pub const CONTAINER_FAILED: &str = "container_failed";+ pub const NO_CREDENTIAL: &str = "no_credential";+ pub const SIGN_IN_EXPIRED: &str = "sign_in_expired";+ /// kwnt runs as root: the container would run as uid 0 (test plan S-16, #14).+ pub const HOST_IS_ROOT: &str = "host_is_root";+ /// The folder's name can't be passed to Docker safely (newline, not UTF-8).+ pub const FOLDER_NAME_UNSUPPORTED: &str = "folder_name_unsupported";+ /// kwnt couldn't write down that the folder is used by an isolated bot (D4), so it doesn't+ /// start the container.+ pub const FOLDER_RECORD_FAILED: &str = "folder_record_failed";+ /// D5: the folder is, holds or sits in a place that must not be shared ([`super::folder_rule`]).+ pub const UNSAFE_FOLDER: &str = "unsafe_folder";+ /// D4b: a host Codex or Grok turn in a folder an isolated bot used.+ pub const FOLDER_USED_BY_ISOLATED_BOT: &str = "folder_used_by_isolated_bot";++ /// Every code above: each has its own words in [`super::notice`] (ui-check-446 fix 4).+ pub const ALL: &[&str] = &[+ UNSUPPORTED_OS,+ DOCKER_UNAVAILABLE,+ PREPARING,+ DOWNLOAD_FAILED,+ RELAY_DOWN,+ CONTAINER_FAILED,+ NO_CREDENTIAL,+ SIGN_IN_EXPIRED,+ HOST_IS_ROOT,+ FOLDER_NAME_UNSUPPORTED,+ FOLDER_RECORD_FAILED,+ UNSAFE_FOLDER,+ FOLDER_USED_BY_ISOLATED_BOT,+ ];+}++impl Refusal {+ pub fn new(code: &'static str, message: impl Into<String>) -> Self {+ Self { code, message: message.into(), unsafe_kind: None }+ }++}++/// The OS gate: slice 1 is Linux only (Mac shows the toggle disabled).+pub fn supported_os() -> Result<(), Refusal> {+ if cfg!(target_os = "linux") {+ Ok(())+ } else if cfg!(target_os = "macos") {+ Err(Refusal::new(codes::UNSUPPORTED_OS, "Coming to Mac later"))+ } else {+ Err(Refusal::new(codes::UNSUPPORTED_OS, "Only on Linux for now"))+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+enum ImageState {+ Unknown,+ Building,+ Ready,+ Failed(String),+}++#[derive(Debug, Default)]+struct ContainerUse {+ active: usize,+ last_used: Option<Instant>,+}++/// Can the switch be turned on right now (`isolate_claude_toggle`, design/ui.md).+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct Toggle {+ pub available: bool,+ /// `mac_later` | `docker_unavailable` | `not_supported_yet` (Windows; added to Mira's list)+ pub reason: Option<&'static str>,+}++/// The `download_failed` detail after a failed image build (Mira's E line, ui-check-446 fix 7).+/// The chip reads "Claude · Stopped: the setup failed (…)", so it starts in lower case.+pub const SETUP_FAILED: &str = "the setup failed (kwant’s log has the details)";++/// Download progress while `state` is `preparing`.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct Progress {+ pub done_bytes: u64,+ pub total_bytes: u64,+}++/// One engine's chip in the computer view (`agents.claude|codex|grok`, design/ui.md).+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct AgentState {+ /// `off` | `isolated` | `not_isolated` | `preparing` | `unavailable`+ pub state: &'static str,+ /// `docker_unavailable` | `download_needed` | `download_failed` | `relay_down` |+ /// `sign_in_expired` | `mac_later` | `local_mode` | `not_supported_yet`+ pub reason: Option<&'static str>,+ pub detail: Option<String>,+ pub progress: Option<Progress>,+}++impl AgentState {+ fn new(state: &'static str, reason: Option<&'static str>) -> Self {+ Self { state, reason, detail: None, progress: None }+ }+ fn detail(mut self, d: impl Into<String>) -> Self {+ self.detail = Some(d.into());+ self+ }+}++/// What [`AgentVm::view`] needs from the rest of kwnt.+#[derive(Debug, Clone, Copy)]+pub struct ViewInputs {+ /// The person's switch.+ pub setting_on: bool,+ /// The computer is set to "this computer's VM" (D1: isolation applies only then).+ pub vm_mode: bool,+ pub docker: bool,+ /// Some Claude account here signs in with the CLI (API-key and Custom accounts run inside+ /// kwnt, so the switch does nothing for them).+ pub cli_account: bool,+}++/// The image as the view sees it.+#[derive(Debug, Clone, PartialEq, Eq)]+enum ImageView {+ Ready,+ Missing,+ Building,+ Failed(String),+}++/// What the person reads when they try to turn the switch on and it isn't available: the PUT+/// 400's `error`, which the Settings error line prints as it is (ui-check-446 fix 5). The code+/// goes in `code`.+pub fn toggle_message(reason: &str) -> &'static str {+ match reason {+ "mac_later" => "Coming to Mac later. For now, Claude runs on this computer in both modes.",+ "not_supported_yet" => "Only on Linux for now. Claude runs on this computer in both modes.",+ codes::DOCKER_UNAVAILABLE => "Start Docker to turn this on.",+ _ => "Run Claude inside the VM can't be turned on here right now.",+ }+}++fn toggle(docker: bool) -> Toggle {+ if cfg!(target_os = "macos") {+ Toggle { available: false, reason: Some("mac_later") }+ } else if supported_os().is_err() {+ Toggle { available: false, reason: Some("not_supported_yet") }+ } else if !docker {+ Toggle { available: false, reason: Some(codes::DOCKER_UNAVAILABLE) }+ } else {+ Toggle { available: true, reason: None }+ }+}++/// The Claude chip. D1: outside vm mode the switch does nothing (`not_isolated`, `local_mode`).+fn claude_state(inp: ViewInputs, image: impl FnOnce() -> ImageView) -> AgentState {+ if !inp.setting_on {+ return AgentState::new("off", None);+ }+ if cfg!(target_os = "macos") {+ return AgentState::new("off", Some("mac_later"));+ }+ if supported_os().is_err() {+ return AgentState::new("off", Some("not_supported_yet"));+ }+ if !inp.vm_mode {+ return AgentState::new("not_isolated", Some("local_mode"));+ }+ if !inp.cli_account {+ return AgentState::new("not_isolated", None)+ .detail("Bots using an API key run inside kwant; their tools already use the VM.");+ }+ if !inp.docker {+ return AgentState::new("unavailable", Some(codes::DOCKER_UNAVAILABLE));+ }+ match image() {+ ImageView::Ready => AgentState::new("isolated", None),+ ImageView::Building => AgentState::new("preparing", None),+ ImageView::Missing => AgentState::new("unavailable", Some("download_needed")),+ ImageView::Failed(why) => AgentState::new("unavailable", Some(codes::DOWNLOAD_FAILED)).detail(why),+ }+}++/// Codex and Grok always run on this computer in 0.7.7.+fn other_state() -> AgentState {+ AgentState::new("not_isolated", Some("not_supported_yet"))+}++pub struct AgentVm {+ /// `<data>/agent-vm`+ root: PathBuf,+ data_dir: PathBuf,+ broker: Arc<Broker>,+ image: StdMutex<ImageState>,+ image_build: tokio::sync::Mutex<()>,+ containers: StdMutex<HashMap<String, ContainerUse>>,+ container_start: tokio::sync::Mutex<()>,+ /// Set by tests to a prebuilt image.+ image_override: Option<String>,+ limits: AgentsInVmConfig,+ /// At most `limits.max_turns` isolated turns at once; a turn holds its permit until it ends.+ turns: Arc<Semaphore>,+ /// Turns waiting for a permit now, for the position a new one reports ([`TurnWait::Queued`]).+ waiting: std::sync::atomic::AtomicUsize,+ /// Where D4's folder record goes; `None` only in tests that don't start a container.+ db: Option<crate::db::Database>,+}++impl std::fmt::Debug for AgentVm {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("AgentVm").field("root", &self.root).finish_non_exhaustive()+ }+}++/// What a turn reports while it waits for a free spot in the VM ([`AgentVm::prepare_turn_reporting`]).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TurnWait {+ /// Every spot is taken: `slots` turns run, and this one is `position` in line (1 is next).+ Queued { position: usize, slots: usize },+ /// It got its spot (sent only after `Queued`).+ Started,+}++/// One turn's inputs to [`AgentVm::prepare_turn`].+#[derive(Debug, Clone)]+pub struct TurnRequest {+ pub bot_id: String,+ /// The bot's folder on this computer; `None` gives the bot a private one.+ pub folder: Option<PathBuf>,+ pub credential: Credential,+ /// Folder holding the credential (never mountable).+ pub credential_home: Option<PathBuf>,+ /// `http://127.0.0.1:<port>`, kwnt's own origin, for its MCP endpoints.+ pub kwnt_origin: Option<String>,+}++impl AgentVm {+ /// The server's: always with its database, so every isolated turn's folder is recorded before+ /// it runs (D4); a turn whose record can't be written is refused.+ pub fn new(data_dir: &Path, limits: AgentsInVmConfig, db: crate::db::Database) -> Arc<Self> {+ let broker_cfg = BrokerConfig::new(data_dir.join("agent-vm").join("broker.log"));+ Self::with_parts(data_dir, broker_cfg, None, limits, Some(db))+ }++ /// For tests: a broker with other upstreams, and a prebuilt image. Without a database, folders+ /// aren't recorded (only tests build it so).+ pub fn with_parts(+ data_dir: &Path,+ cfg: BrokerConfig,+ image: Option<String>,+ limits: AgentsInVmConfig,+ db: Option<crate::db::Database>,+ ) -> Arc<Self> {+ let root = data_dir.join("agent-vm");+ Arc::new(Self {+ root,+ data_dir: data_dir.to_path_buf(),+ broker: Broker::new(cfg),+ image: StdMutex::new(ImageState::Unknown),+ image_build: tokio::sync::Mutex::new(()),+ containers: StdMutex::new(HashMap::new()),+ container_start: tokio::sync::Mutex::new(()),+ image_override: image,+ turns: Arc::new(Semaphore::new(limits.max_turns.max(1))),+ waiting: Default::default(),+ limits,+ db,+ })+ }++ pub fn limits(&self) -> &AgentsInVmConfig {+ &self.limits+ }++ /// Isolated turns that can start right now without waiting.+ pub fn free_turn_slots(&self) -> usize {+ self.turns.available_permits()+ }++ pub fn broker(&self) -> &Arc<Broker> {+ &self.broker+ }++ fn image(&self) -> String {+ self.image_override.clone().unwrap_or_else(image_tag)+ }++ /// The label every container of this kwnt carries (two kwnts on one host keep apart).+ fn root_label(&self) -> String {+ broker::sha8(&self.root.to_string_lossy())+ }++ fn bot_dir(&self, bot_id: &str) -> PathBuf {+ self.root.join(&sha_hex(bot_id)[..12])+ }++ fn container_name(bot_id: &str, workdir: &Path) -> String {+ format!("kwnt-agent-{}-{}", &sha_hex(bot_id)[..8], &sha_hex(&workdir.to_string_lossy())[..8])+ }++ /// `isolate_claude_toggle` and `agents` for the computer view. Asks Docker whether the image+ /// is there only when it isn't known yet.+ pub async fn view(&self, inp: ViewInputs) -> (Toggle, std::collections::BTreeMap<&'static str, AgentState>) {+ let known = self.image.lock().unwrap().clone();+ let image = match known {+ ImageState::Ready => ImageView::Ready,+ ImageState::Building => ImageView::Building,+ ImageState::Failed(why) => ImageView::Failed(why),+ ImageState::Unknown if inp.setting_on && inp.vm_mode && inp.docker && inp.cli_account => {+ if super::manager::image_exists(&self.image()).await {+ let mut st = self.image.lock().unwrap();+ if *st == ImageState::Unknown {+ *st = ImageState::Ready;+ }+ ImageView::Ready+ } else {+ ImageView::Missing+ }+ }+ ImageState::Unknown => ImageView::Missing,+ };+ let agents = [("claude", claude_state(inp, || image)), ("codex", other_state()), ("grok", other_state())];+ (toggle(inp.docker), agents.into_iter().collect())+ }++ /// Turning the switch on starts the download in the background (notice 2 covers a reply+ /// sent before it ends). A no-op when the image is ready or already being built.+ pub fn start_setup(self: &Arc<Self>) {+ if supported_os().is_err() {+ return;+ }+ let vm = self.clone();+ // `image_or_start_setup` may ask Docker (blocking, a few ms)+ tokio::task::spawn_blocking(move || {+ let _ = vm.image_or_start_setup();+ });+ }++ /// A spot for one isolated turn, waiting in line (FIFO) when all `max_turns` are taken, and+ /// telling `report` that it waits and when it's through.+ async fn turn_permit<F, Fut>(&self, report: &mut F) -> Result<OwnedSemaphorePermit, Refusal>+ where+ F: FnMut(TurnWait) -> Fut,+ Fut: std::future::Future<Output = ()>,+ {+ use std::sync::atomic::Ordering;+ use tokio::sync::TryAcquireError;+ let closed = || Refusal::new(codes::CONTAINER_FAILED, "kwnt is shutting down");+ match self.turns.clone().try_acquire_owned() {+ Ok(p) => return Ok(p),+ Err(TryAcquireError::Closed) => return Err(closed()),+ Err(TryAcquireError::NoPermits) => {}+ }+ /// Leaves the line however the wait ends (a stopped reply drops the future).+ struct InLine<'a>(&'a std::sync::atomic::AtomicUsize);+ impl Drop for InLine<'_> {+ fn drop(&mut self) {+ self.0.fetch_sub(1, Ordering::SeqCst);+ }+ }+ let position = self.waiting.fetch_add(1, Ordering::SeqCst) + 1;+ let in_line = InLine(&self.waiting);+ report(TurnWait::Queued { position, slots: self.limits.max_turns.max(1) }).await;+ let permit = self.turns.clone().acquire_owned().await.map_err(|_| closed())?;+ drop(in_line);+ report(TurnWait::Started).await;+ Ok(permit)+ }++ pub fn image_ready(&self) -> bool {+ *self.image.lock().unwrap() == ImageState::Ready+ }++ /// Builds the agent image if it isn't there (single flight).+ pub async fn ensure_image(&self) -> Result<(), Refusal> {+ let _held = self.image_build.lock().await;+ let tag = self.image();+ if super::manager::image_exists(&tag).await {+ *self.image.lock().unwrap() = ImageState::Ready;+ return Ok(());+ }+ if self.image_override.is_some() {+ let why = format!("The test image {tag} isn't built");+ *self.image.lock().unwrap() = ImageState::Failed(why.clone());+ return Err(Refusal::new(codes::DOWNLOAD_FAILED, why));+ }+ *self.image.lock().unwrap() = ImageState::Building;+ let built = async {+ super::manager::ensure_executor_image().await?;+ super::manager::ensure_image(+ &tag,+ &[+ ("Dockerfile", include_str!("../../../docker/agent.Dockerfile")),+ ("agent-entry.sh", include_str!("../../../docker/agent-entry.sh")),+ ],+ &[("CLAUDE_VERSION", CLAUDE_VERSION)],+ )+ .await+ }+ .await;+ match built {+ Ok(()) => {+ *self.image.lock().unwrap() = ImageState::Ready;+ Ok(())+ }+ Err(e) => {+ tracing::warn!(error = %e, "agent image build failed");+ let why = SETUP_FAILED.to_string();+ *self.image.lock().unwrap() = ImageState::Failed(why.clone());+ Err(Refusal::new(codes::DOWNLOAD_FAILED, why))+ }+ }+ }++ /// Everything a Claude turn needs to run isolated, or why it can't. Fails closed.+ pub async fn prepare_turn(self: &Arc<Self>, req: TurnRequest) -> Result<IsolatedTurn, Refusal> {+ self.prepare_turn_reporting(req, |_| std::future::ready(())).await+ }++ /// [`Self::prepare_turn`], telling `report` when the turn has to wait for a free spot and+ /// when it gets one, so the waiting isn't taken for a stalled reply.+ pub async fn prepare_turn_reporting<F, Fut>(self: &Arc<Self>, req: TurnRequest, mut report: F) -> Result<IsolatedTurn, Refusal>+ where+ F: FnMut(TurnWait) -> Fut,+ Fut: std::future::Future<Output = ()>,+ {+ supported_os()?;+ if !super::manager::SandboxManager::new().is_docker_available().await {+ return Err(Refusal::new(codes::DOCKER_UNAVAILABLE, "Docker isn't running on this computer"));+ }+ refuse_root(host_ids())?;+ let bot_dir = self.bot_dir(&req.bot_id);+ let workdir = match &req.folder {+ Some(f) => {+ let f = f.canonicalize().map_err(|_| {+ Refusal::new(codes::CONTAINER_FAILED, "The bot's folder doesn't exist on this computer")+ })?;+ check_folder(&f, &folder_rule::Places::for_host(&self.data_dir, req.credential_home.as_deref()))?;+ f+ }+ None => {+ let w = bot_dir.join("work");+ std::fs::create_dir_all(&w).map_err(|e| Refusal::new(codes::CONTAINER_FAILED, format!("Couldn't make the bot's folder: {e}")))?;+ // Recorded (D4) and mounted by its real path, like a chosen folder: kwnt's data+ // folder may be reached through a symlink+ w.canonicalize().map_err(|e| Refusal::new(codes::CONTAINER_FAILED, format!("Couldn't find the bot's folder: {e}")))?+ }+ };+ check_mountable(&workdir)?;+ check_credential(&req.credential)?;+ // A reply during the image setup fails with notice 2 rather than waiting for it+ self.image_or_start_setup()?;+ // At most `max_turns` at once: a queued turn starts no container until it has a permit+ let permit = self.turn_permit(&mut report).await?;+ // D4: written down before anything runs in the folder, so a turn that fails later counts+ self.record_folder(&workdir, &req.bot_id).await?;+ let run_dir = bot_dir.join("run");+ self.broker+ .listen(&req.bot_id, &run_dir.join("broker.sock"))+ .await+ .map_err(|e| Refusal::new(codes::RELAY_DOWN, format!("kwnt's broker couldn't start: {e}")))?;+ let home = bot_dir.join("home");+ let container = self.ensure_container(&req.bot_id, &workdir, &home, &run_dir).await?;+ let oauth = req.credential.is_oauth();+ let lease = self.broker.register(TurnSpec {+ bot: req.bot_id.clone(),+ credential: req.credential,+ kwnt_origin: req.kwnt_origin.clone(),+ cap: self.limits.request_limit,+ });+ Ok(IsolatedTurn {+ vm: self.clone(),+ lease,+ container,+ workdir,+ run_dir,+ oauth,+ kwnt_origin: req.kwnt_origin,+ mcp_file: None,+ _permit: Some(permit),+ })+ }++ /// Ok when the image is there; otherwise starts its setup in the background (once) and+ /// refuses this turn with `preparing`, or `download_failed` after a failed setup (the next+ /// turn tries again).+ fn image_or_start_setup(self: &Arc<Self>) -> Result<(), Refusal> {+ let state = self.image.lock().unwrap().clone();+ let failed = match state {+ ImageState::Ready => return Ok(()),+ ImageState::Building => return Err(Refusal::new(codes::PREPARING, "Claude's VM is still being set up")),+ // An image built earlier is ready straight away+ ImageState::Unknown if self.image_present_sync() => return Ok(()),+ ImageState::Unknown => false,+ ImageState::Failed(_) => true,+ };+ // Marked here, not in the task, so the status shows `preparing` at once. Two turns that+ // both get here start one build: `ensure_image` is single flight and checks first.+ *self.image.lock().unwrap() = ImageState::Building;+ let vm = self.clone();+ tokio::spawn(async move {+ let _ = vm.ensure_image().await;+ });+ Err(if failed {+ Refusal::new(codes::DOWNLOAD_FAILED, "The last setup of Claude's VM didn't finish; kwnt is trying again")+ } else {+ Refusal::new(codes::PREPARING, "Claude's VM is being set up (the first time takes a few minutes)")+ })+ }++ /// Whether the image is in Docker already (blocking `docker image inspect`, a few ms).+ fn image_present_sync(&self) -> bool {+ let ok = std::process::Command::new("docker")+ .args(["image", "inspect", "--format", "{{.Id}}", &self.image()])+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status()+ .is_ok_and(|s| s.success());+ if ok {+ *self.image.lock().unwrap() = ImageState::Ready;+ }+ ok+ }++ async fn record_folder(&self, workdir: &Path, bot_id: &str) -> Result<(), Refusal> {+ // Only `with_parts` (tests) builds a VM without a database; the server's `new` can't+ let Some(db) = &self.db else { return Ok(()) };+ db.record_isolated_folder(workdir, bot_id).await.map_err(|e| {+ tracing::warn!(error = %e, "couldn't record the isolated folder");+ Refusal::new(codes::FOLDER_RECORD_FAILED, "kwnt couldn't note that this folder is used inside the VM")+ })+ }++ /// The bot's running container for `workdir`, started when there's none, counted as in use+ /// by one more turn. The count goes up under `container_start`, the lock [`Self::end_container`]+ /// takes too, so a container is never removed under a turn that just picked it.+ async fn ensure_container(&self, bot_id: &str, workdir: &Path, home: &Path, run_dir: &Path) -> Result<String, Refusal> {+ let _held = self.container_start.lock().await;+ let name = self.start_container(bot_id, workdir, home, run_dir).await?;+ self.containers.lock().unwrap().entry(name.clone()).or_default().active += 1;+ Ok(name)+ }++ async fn start_container(&self, bot_id: &str, workdir: &Path, home: &Path, run_dir: &Path) -> Result<String, Refusal> {+ let name = Self::container_name(bot_id, workdir);+ let fail = |why: String| Refusal::new(codes::CONTAINER_FAILED, why);+ let running = Command::new("docker")+ .args(["inspect", "-f", "{{.State.Running}}", &name])+ .kill_on_drop(true)+ .output()+ .await+ .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).trim() == "true");+ if running {+ return Ok(name);+ }+ let _ = Command::new("docker").args(["rm", "-f", &name]).kill_on_drop(true).output().await;+ for d in [home, run_dir] {+ std::fs::create_dir_all(d).map_err(|e| fail(format!("Couldn't prepare the bot's computer folders: {e}")))?;+ set_private(d);+ }+ let mounts = Mounts::new(workdir, home, run_dir)?;+ let args = run_args(&name, &self.root_label(), &mounts, &self.image(), host_ids(), self.limits.memory_mb);+ let out = Command::new("docker")+ .args(&args)+ .kill_on_drop(true)+ .output()+ .await+ .map_err(|e| fail(format!("Docker didn't start: {e}")))?;+ if !out.status.success() {+ let err = String::from_utf8_lossy(&out.stderr);+ tracing::warn!(container = %name, error = %err.trim(), "agent container failed to start");+ return Err(fail("The bot's computer didn't start (see kwnt's log)".into()));+ }+ Ok(name)+ }++ /// One turn fewer in `container`; true when that was its last one.+ fn release(&self, container: &str) -> bool {+ let mut map = self.containers.lock().unwrap();+ let Some(u) = map.get_mut(container) else { return false };+ u.active = u.active.saturating_sub(1);+ u.last_used = Some(Instant::now());+ u.active == 0+ }++ /// R-9 (S-9): after a container's last turn, nothing the bot started may keep running until+ /// the next one: a `setsid` child leaves the turn's process group, so the group's TERM misses+ /// it. After [`STOP_GRACE`] the container is removed (`docker rm -f`: SIGKILL to every process+ /// in it, PID 1 included) unless a turn picked it up meanwhile; the next turn starts a fresh+ /// one. The folders are mounts, so nothing the bot keeps is lost, only `/tmp` (a tmpfs).+ async fn end_container(&self, container: &str) {+ tokio::time::sleep(STOP_GRACE).await;+ let _held = self.container_start.lock().await;+ {+ let mut map = self.containers.lock().unwrap();+ if map.get(container).is_some_and(|u| u.active > 0) {+ return;+ }+ map.remove(container);+ }+ match Command::new("docker").args(["rm", "-f", container]).kill_on_drop(true).output().await {+ Ok(o) if o.status.success() => {}+ Ok(o) => tracing::warn!(container, error = %String::from_utf8_lossy(&o.stderr).trim(), "couldn't remove an agent container after its last turn"),+ Err(e) => tracing::warn!(container, error = %e, "couldn't remove an agent container after its last turn"),+ }+ }++ /// Removes this kwnt's agent containers left over from an earlier run, then every 5 minutes+ /// the ones idle for half an hour.+ pub fn start_reaper(self: &Arc<Self>) {+ let vm = self.clone();+ tokio::spawn(async move {+ vm.remove_containers(|_| true).await;+ loop {+ tokio::time::sleep(Duration::from_secs(300)).await;+ let idle: Vec<String> = {+ let mut map = vm.containers.lock().unwrap();+ let names: Vec<String> = map+ .iter()+ .filter(|(_, u)| u.active == 0 && u.last_used.is_some_and(|t| t.elapsed() > IDLE_REMOVE_AFTER))+ .map(|(n, _)| n.clone())+ .collect();+ for n in &names {+ map.remove(n);+ }+ names+ };+ if !idle.is_empty() {+ vm.remove_containers(|n| idle.iter().any(|i| i == n)).await;+ }+ }+ });+ }++ /// Removes this kwnt's agent containers whose name `pick` accepts.+ pub async fn remove_containers(&self, pick: impl Fn(&str) -> bool) {+ let Ok(out) = Command::new("docker")+ .args(["ps", "-a", "--filter", "label=kwnt.agent=1", "--filter"])+ .arg(format!("label=kwnt.root={}", self.root_label()))+ .args(["--format", "{{.Names}}"])+ .kill_on_drop(true)+ .output()+ .await+ else {+ return;+ };+ for name in String::from_utf8_lossy(&out.stdout).lines().map(str::trim).filter(|n| n.starts_with("kwnt-agent-") && pick(n)) {+ let _ = Command::new("docker").args(["rm", "-f", name]).kill_on_drop(true).output().await;+ }+ }+}++/// The three bind mounts of a bot's container, as `--mount` values. Docker reads `--mount` as+/// CSV, so each field is quoted (a `,` or `"` in a folder name can't add an option); a name with+/// a newline or that isn't UTF-8 is refused instead.+#[derive(Debug, Clone, PartialEq, Eq)]+struct Mounts {+ workdir: String,+ args: [String; 3],+}++impl Mounts {+ fn new(workdir: &Path, home: &Path, run_dir: &Path) -> Result<Self, Refusal> {+ let w = check_mountable(workdir)?;+ let h = check_mountable(home)?;+ let r = check_mountable(run_dir)?;+ Ok(Self {+ workdir: w.to_string(),+ args: [mount_arg(w, w, false), mount_arg(h, CONTAINER_HOME, false), mount_arg(r, CONTAINER_RUN, true)],+ })+ }+}++fn csv_field(f: &str) -> String {+ format!("\"{}\"", f.replace('"', "\"\""))+}++fn mount_arg(src: &str, dst: &str, readonly: bool) -> String {+ let mut v = format!("type=bind,{},{}", csv_field(&format!("src={src}")), csv_field(&format!("dst={dst}")));+ if readonly {+ v.push_str(",readonly");+ }+ v+}++/// The folder as a string Docker can take: absolute, UTF-8, no control characters.+fn check_mountable(p: &Path) -> Result<&str, Refusal> {+ let refuse = || Refusal::new(codes::FOLDER_NAME_UNSUPPORTED, "The folder's name has characters kwnt can't pass to the VM. Rename the folder, then Retry");+ let s = p.to_str().ok_or_else(refuse)?;+ if !p.is_absolute() || s.chars().any(char::is_control) {+ return Err(refuse());+ }+ Ok(s)+}++/// The container must not run as uid 0: kwnt passes its own ids so the person owns what the bot+/// makes, and as root that would make the bot root in its container.+fn refuse_root(ids: Option<(u32, u32)>) -> Result<(), Refusal> {+ match ids {+ Some((0, _)) => Err(Refusal::new(+ codes::HOST_IS_ROOT,+ "kwnt is running as root, so Claude can't run inside the VM as you. Run kwnt as a normal user",+ )),+ _ => Ok(()),+ }+}++/// The `docker run` arguments for a bot's container. The folder is mounted at its own absolute+/// path, so paths in the chat mean the same inside and out.+fn run_args(name: &str, root_label: &str, mounts: &Mounts, image: &str, ids: Option<(u32, u32)>, memory_mb: u32) -> Vec<String> {+ let mut a: Vec<String> = ["run", "-d", "--name", name].map(String::from).to_vec();+ a.extend(["--label".into(), "kwnt.agent=1".into(), "--label".into(), format!("kwnt.root={root_label}")]);+ a.extend(["--label".into(), format!("kwnt.workspace={}", broker::sha8(&mounts.workdir))]);+ a.extend(+ [+ "--network", "none", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--read-only",+ "--tmpfs", "/tmp:rw,exec,nosuid,nodev,size=256m", "--cpus", "2", "--pids-limit", "512",+ "--restart", "no", "--hostname", "kwnt-agent",+ ]+ .map(String::from),+ );+ // No swap beyond the memory limit+ a.extend(["--memory".into(), format!("{memory_mb}m"), "--memory-swap".into(), format!("{memory_mb}m")]);+ // As the host's own user: files the bot makes belong to the person, no chown needed+ if let Some((uid, gid)) = ids {+ a.extend(["--user".into(), format!("{uid}:{gid}")]);+ }+ a.extend(["-e".into(), format!("HOME={CONTAINER_HOME}")]);+ for m in &mounts.args {+ a.extend(["--mount".into(), m.clone()]);+ }+ a.extend(["-w".into(), mounts.workdir.clone(), image.to_string()]);+ a+}++#[cfg(unix)]+fn host_ids() -> Option<(u32, u32)> {+ // SAFETY: getuid/getgid have no preconditions and can't fail+ Some(unsafe { (libc::getuid(), libc::getgid()) })+}++#[cfg(not(unix))]+fn host_ids() -> Option<(u32, u32)> {+ None+}++fn set_private(dir: &Path) {+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));+ }+ #[cfg(not(unix))]+ let _ = dir;+}++fn sha_hex(s: &str) -> String {+ use sha2::{Digest, Sha256};+ Sha256::digest(s.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()+}++/// A bot's folder is mounted into the container, so it must not hold the person's secrets+/// ([`folder_rule`]: D5, with kwnt's own work folders inside its data dir allowed). `folder` is+/// already canonical.+pub fn check_folder(folder: &Path, places: &folder_rule::Places) -> Result<(), Refusal> {+ let Some(kind) = folder_rule::classify(folder, places) else { return Ok(()) };+ let why = match kind {+ folder_rule::UnsafeKind::Home => "is your home folder",+ folder_rule::UnsafeKind::ContainsHome | folder_rule::UnsafeKind::Root => "holds your home folder",+ folder_rule::UnsafeKind::SignIns => "holds sign-ins",+ folder_rule::UnsafeKind::KwantData => "holds kwant's own data",+ folder_rule::UnsafeKind::Docker => "holds Docker's control socket",+ folder_rule::UnsafeKind::SharedFolder => "is the folder every team without its own folder shares",+ };+ let mut r = Refusal::new(+ codes::UNSAFE_FOLDER,+ format!("The bot's folder {} {why}, so kwant won't share it with the VM. Pick a project folder instead", folder.display()),+ );+ r.unsafe_kind = Some(kind);+ Err(r)+}++fn check_credential(c: &Credential) -> Result<(), Refusal> {+ match c {+ Credential::ApiKey(k) if k.expose().trim().is_empty() => Err(no_credential()),+ Credential::ApiKey(_) => Ok(()),+ Credential::OAuthFile { path, refresh } => {+ let doc: Value = std::fs::read(path)+ .ok()+ .and_then(|b| serde_json::from_slice(&b).ok())+ .ok_or_else(no_credential)?;+ let o = &doc["claudeAiOauth"];+ if o["accessToken"].as_str().is_none_or(str::is_empty) {+ return Err(no_credential());+ }+ let expired = o["expiresAt"].as_i64().is_some_and(|t| t <= now_ms());+ let refreshable = *refresh && o["refreshToken"].as_str().is_some_and(|s| !s.is_empty());+ if expired && !refreshable {+ return Err(Refusal::new(codes::SIGN_IN_EXPIRED, "The Claude sign-in has expired. Sign in to Claude again"));+ }+ Ok(())+ }+ }+}++fn now_ms() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as i64)+ .unwrap_or(0)+}++fn no_credential() -> Refusal {+ Refusal::new(codes::NO_CREDENTIAL, "There's no Claude sign-in or API key on this computer for this bot")+}++/// The real Claude credential for a turn. `profile_home`: the turn's sign-in profile home (the+/// broker owns refreshing it); `None`: this computer's own login (never refreshed by kwnt).+pub fn resolve_credential(profile_home: Option<&Path>) -> Result<(Credential, Option<PathBuf>), Refusal> {+ resolve_credential_in(profile_home, std::env::var("ANTHROPIC_API_KEY").ok(), std::env::var_os("CLAUDE_CONFIG_DIR").map(PathBuf::from), dirs::home_dir())+}++pub fn resolve_credential_in(+ profile_home: Option<&Path>,+ env_key: Option<String>,+ config_dir: Option<PathBuf>,+ home: Option<PathBuf>,+) -> Result<(Credential, Option<PathBuf>), Refusal> {+ if let Some(h) = profile_home {+ let creds = h.join(".credentials.json");+ if creds.is_file() {+ return Ok((Credential::OAuthFile { path: creds, refresh: true }, Some(h.to_path_buf())));+ }+ if let Some(k) = primary_api_key(&h.join(".claude.json")) {+ return Ok((Credential::ApiKey(Secret::new(k)), Some(h.to_path_buf())));+ }+ return Err(no_credential());+ }+ if let Some(k) = env_key.filter(|k| !k.trim().is_empty()) {+ return Ok((Credential::ApiKey(Secret::new(k)), None));+ }+ let dir = config_dir.clone().or_else(|| home.as_ref().map(|h| h.join(".claude")));+ if let Some(d) = &dir {+ let creds = d.join(".credentials.json");+ if creds.is_file() {+ return Ok((Credential::OAuthFile { path: creds, refresh: false }, Some(d.clone())));+ }+ }+ let json = match (&config_dir, &home) {+ (Some(d), _) => Some(d.join(".claude.json")),+ (None, Some(h)) => Some(h.join(".claude.json")),+ _ => None,+ };+ if let Some(k) = json.as_deref().and_then(primary_api_key) {+ return Ok((Credential::ApiKey(Secret::new(k)), dir));+ }+ Err(no_credential())+}++fn primary_api_key(path: &Path) -> Option<String> {+ let doc: Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;+ doc["primaryApiKey"].as_str().filter(|k| !k.trim().is_empty()).map(String::from)+}++/// Environment the CLI keeps inside the container; everything else kwnt set is dropped.+const PASS_ENV: &[&str] = &[+ "CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR",+ "MCP_TOOL_TIMEOUT",+ "CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT",+ "MCP_TIMEOUT",+ "BROWSER",+ "DISPLAY",+];++/// Provider and model settings that would point the CLI somewhere else (as for a profile run).+const SETTINGS_OVERRIDE: &[(&str, &str)] = &[+ ("CLAUDE_CODE_USE_BEDROCK", "0"),+ ("CLAUDE_CODE_USE_VERTEX", "0"),+ ("CLAUDE_CODE_USE_FOUNDRY", "0"),+ ("ANTHROPIC_MODEL", ""),+ ("ANTHROPIC_DEFAULT_HAIKU_MODEL", ""),+ ("ANTHROPIC_DEFAULT_SONNET_MODEL", ""),+ ("ANTHROPIC_DEFAULT_OPUS_MODEL", ""),+ ("ANTHROPIC_DEFAULT_FABLE_MODEL", ""),+ ("ANTHROPIC_SMALL_FAST_MODEL", ""),+ ("CLAUDE_CODE_SUBAGENT_MODEL", ""),+];++/// A Claude turn prepared to run in the bot's container. Dropping it ends the turn: its broker+/// key stops working, the CLI's process group in the container is stopped and its MCP config+/// removed.+pub struct IsolatedTurn {+ vm: Arc<AgentVm>,+ lease: TurnLease,+ container: String,+ workdir: PathBuf,+ run_dir: PathBuf,+ oauth: bool,+ kwnt_origin: Option<String>,+ mcp_file: Option<crate::mcp::cli_config::ConfigFile>,+ /// This turn's place among the isolated turns at once; freed when the turn drops.+ _permit: Option<OwnedSemaphorePermit>,+}++impl std::fmt::Debug for IsolatedTurn {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("IsolatedTurn").field("container", &self.container).field("lease", &self.lease).finish_non_exhaustive()+ }+}++impl IsolatedTurn {+ pub fn container(&self) -> &str {+ &self.container+ }++ pub fn workdir(&self) -> &Path {+ &self.workdir+ }++ /// Whether the turn asked for more model calls than its cap (the CLI then got a 429).+ pub fn cap_reached(&self) -> bool {+ self.lease.cap_reached()+ }++ /// The turn's request cap.+ pub fn request_cap(&self) -> u32 {+ self.lease.cap()+ }++ /// Model requests the turn made so far.+ pub fn requests(&self) -> u32 {+ self.lease.requests()+ }++ fn base(&self) -> String {+ format!("{IN_CONTAINER_ORIGIN}/t/{}", self.lease.key())+ }++ pub fn anthropic_base_url(&self) -> String {+ format!("{}/anthropic", self.base())+ }++ fn pid_file(&self) -> String {+ format!("/tmp/kwnt-turn-{}.pid", &self.lease.key()[..12])+ }++ /// Writes this turn's `--mcp-config` where the container sees it and returns its path in+ /// the container, and the names of servers left out. Only kwnt's own endpoints come along+ /// (through the broker); the container has no network for anything else.+ pub fn write_mcp_config(&mut self, ctx: &crate::mcp::McpTurnContext) -> std::io::Result<(String, Vec<String>)> {+ let (doc, dropped) = self.mcp_document(ctx);+ let name = format!("mcp-{}.json", &self.lease.key()[..16]);+ let path = self.run_dir.join(&name);+ broker::write_private(&path, serde_json::to_string_pretty(&doc)?.as_bytes())?;+ self.mcp_file = Some(crate::mcp::cli_config::ConfigFile { path });+ Ok((format!("{CONTAINER_RUN}/{name}"), dropped))+ }++ fn mcp_document(&self, ctx: &crate::mcp::McpTurnContext) -> (Value, Vec<String>) {+ let mut doc = crate::mcp::cli_config::claude_config(ctx);+ let mut dropped = Vec::new();+ let origin = self.kwnt_origin.as_deref().map(|o| o.trim_end_matches('/').to_string());+ if let Some(servers) = doc["mcpServers"].as_object_mut() {+ let names: Vec<String> = servers.keys().cloned().collect();+ for name in names {+ let entry = &servers[&name];+ let local = (entry["type"] == "http")+ .then(|| entry["url"].as_str())+ .flatten()+ .zip(origin.as_deref())+ .and_then(|(url, o)| url.strip_prefix(o).filter(|rest| rest.starts_with("/api/")).map(String::from));+ let local = local.filter(|rest| {+ let path = rest.split_once('?').map_or(rest.as_str(), |(p, _)| p);+ self.lease.allow_kwnt_path(path)+ });+ match local {+ Some(rest) => {+ let (path, query) = rest.split_once('?').map_or((rest.as_str(), None), |(p, q)| (p, Some(q)));+ let url = format!("{}/kwnt{path}{}", self.base(), query.map(|q| format!("?{q}")).unwrap_or_default());+ servers[&name]["url"] = json!(url);+ }+ None => {+ servers.remove(&name);+ dropped.push(name);+ }+ }+ }+ }+ (doc, dropped)+ }++ /// The `docker exec` that runs `cmd` (kwnt's claude command, built as for this computer) in+ /// the bot's container instead. Only [`PASS_ENV`] survives; the home, broker address and a+ /// stand-in credential are set; provider settings are pinned to the broker.+ pub fn wrap(&self, cmd: &Command) -> Command {+ let std = cmd.as_std();+ let mut out = Command::new("docker");+ out.args(["exec", "-w"]).arg(&self.workdir);+ let mut env: Vec<(String, String)> = std+ .get_envs()+ .filter_map(|(k, v)| {+ let k = k.to_str()?;+ PASS_ENV.contains(&k).then(|| (k.to_string(), v.map(|v| v.to_string_lossy().into_owned()).unwrap_or_default()))+ })+ .collect();+ let base_url = self.anthropic_base_url();+ env.extend([+ ("HOME".to_string(), CONTAINER_HOME.to_string()),+ ("CLAUDE_CONFIG_DIR".into(), format!("{CONTAINER_HOME}/.claude")),+ ("ANTHROPIC_BASE_URL".into(), base_url.clone()),+ ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC".into(), "1".into()),+ ("DISABLE_AUTOUPDATER".into(), "1".into()),+ ("DISABLE_TELEMETRY".into(), "1".into()),+ ("DISABLE_ERROR_REPORTING".into(), "1".into()),+ ]);+ if self.oauth {+ env.push(("CLAUDE_CODE_OAUTH_TOKEN".into(), DUMMY_OAUTH_TOKEN.into()));+ } else {+ env.push(("ANTHROPIC_API_KEY".into(), DUMMY_API_KEY.into()));+ }+ for (k, v) in &env {+ out.arg("-e").arg(format!("{k}={v}"));+ }+ out.arg(&self.container);+ // A process group of its own, its id written down, so the turn's end can stop it all+ out.args(["setsid", "-w", "sh", "-c"]);+ out.arg(format!("echo $$ > {}; exec \"$@\"", self.pid_file()));+ out.args(["sh", "claude"]);+ // Claude's own web tools only reach the broker's 400 (D3): start without them+ let args = notice::with_disallowed_tools(std.get_args().map(OsString::from).collect());+ out.args(&args);+ let mut settings: serde_json::Map<String, Value> = SETTINGS_OVERRIDE.iter().map(|(k, v)| (k.to_string(), json!(v))).collect();+ settings.insert("ANTHROPIC_BASE_URL".into(), json!(base_url));+ out.arg("--settings").arg(json!({ "env": settings }).to_string());+ out+ }+}++impl Drop for IsolatedTurn {+ fn drop(&mut self) {+ let last = self.vm.release(&self.container);+ // Killing `docker exec` doesn't stop what it started in the container: TERM the turn's+ // process group, then, after the container's last turn, remove the container (R-9)+ let (vm, container) = (self.vm.clone(), self.container.clone());+ let script = format!("p=$(cat {f} 2>/dev/null) && kill -TERM -- -$p 2>/dev/null; rm -f {f}", f = self.pid_file());+ if let Ok(rt) = tokio::runtime::Handle::try_current() {+ rt.spawn(async move {+ let _ = Command::new("docker").args(["exec", &container, "sh", "-c", &script]).kill_on_drop(true).output().await;+ if last {+ vm.end_container(&container).await;+ }+ });+ }+ // Without a runtime (kwnt is exiting) the reaper removes it at the next start+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_switch_refusals_read_as_words_not_codes() {+ assert_eq!(toggle_message("mac_later"), "Coming to Mac later. For now, Claude runs on this computer in both modes.");+ assert_eq!(toggle_message("not_supported_yet"), "Only on Linux for now. Claude runs on this computer in both modes.");+ assert_eq!(toggle_message("docker_unavailable"), "Start Docker to turn this on.");+ assert!(!toggle_message("brand_new").contains('_'));+ // The chip detail after a failed setup (fix 7)+ assert!(SETUP_FAILED.starts_with("the setup failed") && !SETUP_FAILED.contains("computer") && !SETUP_FAILED.contains("kwnt"));+ }++ #[test]+ fn the_chips_follow_miras_contract_and_d1() {+ let on = ViewInputs { setting_on: true, vm_mode: true, docker: true, cli_account: true };+ let st = |inp: ViewInputs, img: ImageView| {+ let a = claude_state(inp, || img);+ (a.state, a.reason)+ };+ if cfg!(target_os = "linux") {+ assert_eq!(st(on, ImageView::Ready), ("isolated", None));+ assert_eq!(st(on, ImageView::Building), ("preparing", None));+ assert_eq!(st(on, ImageView::Missing), ("unavailable", Some("download_needed")));+ let failed = claude_state(on, || ImageView::Failed("no network".into()));+ assert_eq!((failed.state, failed.reason, failed.detail.as_deref()), ("unavailable", Some("download_failed"), Some("no network")));+ // D1: outside vm mode the switch does nothing, and says so+ assert_eq!(st(ViewInputs { vm_mode: false, ..on }, ImageView::Ready), ("not_isolated", Some("local_mode")));+ assert_eq!(st(ViewInputs { docker: false, ..on }, ImageView::Ready), ("unavailable", Some("docker_unavailable")));+ assert_eq!(st(ViewInputs { cli_account: false, ..on }, ImageView::Ready).0, "not_isolated");+ assert_eq!(toggle(true), Toggle { available: true, reason: None });+ assert_eq!(toggle(false), Toggle { available: false, reason: Some("docker_unavailable") });+ }+ if cfg!(target_os = "macos") {+ assert_eq!(st(on, ImageView::Ready), ("off", Some("mac_later")));+ assert_eq!(toggle(true).reason, Some("mac_later"));+ }+ assert_eq!(st(ViewInputs { setting_on: false, ..on }, ImageView::Ready), ("off", None));+ assert_eq!((other_state().state, other_state().reason), ("not_isolated", Some("not_supported_yet")));+ let json = serde_json::to_value(claude_state(ViewInputs { setting_on: false, ..on }, || ImageView::Ready)).unwrap();+ assert_eq!(json, serde_json::json!({"state": "off", "reason": null, "detail": null, "progress": null}));+ }++ #[test]+ fn folders_holding_secrets_are_refused() {+ let places = folder_rule::Places {+ home: Some("/home/p".into()),+ data_dir: "/home/p/.kwnt".into(),+ sign_ins: vec!["/home/p/.kwnt/profiles".into(), "/srv/creds/claude".into()],+ docker: vec![],+ };+ for (bad, kind) in [("/", "root"), ("/home", "contains_home"), ("/home/p", "home"), ("/home/p/.kwnt", "kwant_data"), ("/srv", "sign_ins"), ("/srv/creds", "sign_ins"), ("/home/p/.kwnt/workspace", "shared_folder")] {+ let r = check_folder(Path::new(bad), &places).unwrap_err();+ assert_eq!(r.code, codes::UNSAFE_FOLDER, "{bad}");+ assert_eq!(r.unsafe_kind.map(folder_rule::UnsafeKind::as_str), Some(kind), "{bad}");+ }+ for ok in ["/home/p/projects/site", "/home/p/.kwnt/workspaces/b1", "/home/p/.kwnt/bot-workspaces/kw_1", "/srv/other"] {+ assert!(check_folder(Path::new(ok), &places).is_ok(), "{ok}");+ }+ }++ // Container paths are unix paths (`/w/proj` isn't absolute on Windows); isolation is Linux only+ #[cfg(unix)]+ #[test]+ fn run_args_isolate_the_container() {+ let m = Mounts::new(Path::new("/w/proj"), Path::new("/d/h"), Path::new("/d/run")).unwrap();+ let a = run_args("kwnt-agent-a-b", "r", &m, "img", Some((1000, 1000)), 1024);+ let s = a.join(" ");+ for want in [+ "--network none", "--cap-drop ALL", "--security-opt no-new-privileges", "--read-only", "--user 1000:1000",+ "--memory 1024m", "--memory-swap 1024m", "-w /w/proj img", "--label kwnt.agent=1",+ r#"--mount type=bind,"src=/w/proj","dst=/w/proj""#,+ r#"--mount type=bind,"src=/d/h","dst=/home/agent""#,+ r#"--mount type=bind,"src=/d/run","dst=/run/kwnt",readonly"#,+ ] {+ assert!(s.contains(want), "{want} in {s}");+ }+ // Exactly three mounts, and no other way in+ assert_eq!(a.iter().filter(|x| *x == "--mount").count(), 3);+ for never in ["-v", "--volume", "--volumes-from", "--privileged", "--device", "--pid", "--ipc", "--userns", "--add-host"] {+ assert!(!a.iter().any(|x| x == never), "{never}");+ }+ assert!(!s.contains("docker.sock"));+ }++ // Container paths are unix paths (`/w/proj` isn't absolute on Windows); isolation is Linux only+ #[cfg(unix)]+ #[test]+ fn mount_values_cant_add_options_and_odd_names_are_refused() {+ // A comma or quote stays inside the src field (Docker reads --mount as CSV)+ let m = Mounts::new(Path::new("/w/a,dst=/etc,readonly=false"), Path::new("/d/h"), Path::new("/d/run")).unwrap();+ assert_eq!(m.args[0], r#"type=bind,"src=/w/a,dst=/etc,readonly=false","dst=/w/a,dst=/etc,readonly=false""#);+ let q = Mounts::new(Path::new("/w/say \"hi\": x=1"), Path::new("/d/h"), Path::new("/d/run")).unwrap();+ assert_eq!(q.args[0], r#"type=bind,"src=/w/say ""hi"": x=1","dst=/w/say ""hi"": x=1""#);+ for bad in ["/w/new\nline", "relative/dir", "/w/tab\there"] {+ assert_eq!(Mounts::new(Path::new(bad), Path::new("/d/h"), Path::new("/d/run")).unwrap_err().code, codes::FOLDER_NAME_UNSUPPORTED, "{bad:?}");+ }+ #[cfg(unix)]+ {+ use std::os::unix::ffi::OsStrExt;+ let p = Path::new(std::ffi::OsStr::from_bytes(b"/w/\xff"));+ assert_eq!(Mounts::new(p, Path::new("/d/h"), Path::new("/d/run")).unwrap_err().code, codes::FOLDER_NAME_UNSUPPORTED);+ }+ }++ #[test]+ fn the_container_never_runs_as_root() {+ assert_eq!(refuse_root(Some((0, 0))).unwrap_err().code, codes::HOST_IS_ROOT);+ assert!(refuse_root(Some((1000, 1000))).is_ok());+ }++ #[tokio::test]+ async fn a_turn_that_waits_for_a_spot_says_so_and_when_it_gets_one() {+ let d = tempfile::tempdir().unwrap();+ let vm = AgentVm::with_parts(d.path(), BrokerConfig::new(d.path().join("broker.log")), None, AgentsInVmConfig { max_turns: 1, ..Default::default() }, None);+ // A free spot: no report at all+ let seen = Arc::new(StdMutex::new(Vec::new()));+ let log = |seen: &Arc<StdMutex<Vec<TurnWait>>>| {+ let seen = seen.clone();+ move |w| {+ seen.lock().unwrap().push(w);+ std::future::ready(())+ }+ };+ let first = vm.turn_permit(&mut log(&seen)).await.unwrap();+ assert!(seen.lock().unwrap().is_empty());+ // Taken: the next one is first in line, then the one after it second+ let (vm2, s2) = (vm.clone(), seen.clone());+ let second = tokio::spawn(async move { vm2.turn_permit(&mut log(&s2)).await.map(|_| ()) });+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert_eq!(*seen.lock().unwrap(), vec![TurnWait::Queued { position: 1, slots: 1 }]);+ let third_seen = Arc::new(StdMutex::new(Vec::new()));+ let (vm3, s3) = (vm.clone(), third_seen.clone());+ let third = tokio::spawn(async move { vm3.turn_permit(&mut log(&s3)).await.map(|_| ()) });+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert_eq!(*third_seen.lock().unwrap(), vec![TurnWait::Queued { position: 2, slots: 1 }]);+ // A stopped reply leaves the line+ third.abort();+ let _ = third.await;+ assert_eq!(vm.waiting.load(std::sync::atomic::Ordering::SeqCst), 1);+ drop(first);+ second.await.unwrap().unwrap();+ assert_eq!(*seen.lock().unwrap(), vec![TurnWait::Queued { position: 1, slots: 1 }, TurnWait::Started]);+ assert_eq!(vm.waiting.load(std::sync::atomic::Ordering::SeqCst), 0);+ }++ /// QA P-5b: two replies each waiting on an approval card hold both spots for up to 300 s; a+ /// third is shown queued ("vm_busy") and its wait never counts toward the stall watchdog,+ /// which starts only once it gets the spot an expired card frees.+ #[tokio::test]+ async fn two_replies_waiting_for_approval_queue_a_third_without_a_stall() {+ use crate::drivers::events::RuntimeEvent as E;+ use crate::server::turns::StallClock;+ let d = tempfile::tempdir().unwrap();+ let vm = AgentVm::with_parts(d.path(), BrokerConfig::new(d.path().join("broker.log")), None, AgentsInVmConfig { max_turns: 2, ..Default::default() }, None);+ let (limit, t0) = (Duration::from_secs(120), tokio::time::Instant::now());+ let mut clocks = vec![StallClock::new(Some(limit), t0); 3];+ // Two replies get a spot each, and each asks for an approval nobody answers yet+ let mut quiet = |_| std::future::ready(());+ let first = vm.turn_permit(&mut quiet).await.unwrap();+ let _second = vm.turn_permit(&mut quiet).await.unwrap();+ let approval = |id: &str| E::ToolCallPending { id: id.into(), name: "Bash".into(), args: serde_json::json!({}) };+ clocks[0].saw(&approval("a"), t0);+ clocks[1].saw(&approval("b"), t0);+ // A third is queued, the way the Claude driver reports it+ let (tx, mut rx) = tokio::sync::mpsc::channel(4);+ let vm3 = vm.clone();+ let third = tokio::spawn(async move {+ let mut report = move |w| {+ let tx = tx.clone();+ async move {+ let e = match w {+ TurnWait::Queued { position, slots } => E::WaitingForRoom { reason: "vm_busy".into(), position, slots },+ TurnWait::Started => E::RoomTaken,+ };+ let _ = tx.send(e).await;+ }+ };+ vm3.turn_permit(&mut report).await.map(|_| ())+ });+ let queued = tokio::time::timeout(Duration::from_secs(2), rx.recv()).await.unwrap().unwrap();+ assert!(matches!(&queued, E::WaitingForRoom { reason, position: 1, slots: 2 } if reason == "vm_busy"), "{queued:?}");+ clocks[2].saw(&queued, t0);+ // Nobody stalls while the cards wait, however long that is+ assert!(clocks.iter().all(|c| c.deadline().is_none()));+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert!(!third.is_finished(), "the third still waits");+ // At 300 s the first card expires: that reply ends and frees its spot+ let t1 = t0 + Duration::from_secs(300);+ clocks[0].saw(&E::ToolCallCompleted { id: "a".into(), result: serde_json::json!({"expired": true}) }, t1);+ drop(first);+ let taken = tokio::time::timeout(Duration::from_secs(2), rx.recv()).await.unwrap().unwrap();+ assert!(matches!(taken, E::RoomTaken), "{taken:?}");+ clocks[2].saw(&taken, t1);+ // The third's watchdog starts from the moment it got the spot, not from when it queued+ assert_eq!(clocks[2].deadline(), Some(t1 + limit));+ assert_eq!(clocks[1].deadline(), None, "the second card still waits");+ tokio::time::timeout(Duration::from_secs(2), third).await.unwrap().unwrap().unwrap();+ }++ #[tokio::test]+ async fn at_most_max_turns_hold_a_permit_and_every_drop_frees_one() {+ let d = tempfile::tempdir().unwrap();+ let vm = AgentVm::with_parts(d.path(), BrokerConfig::new(d.path().join("broker.log")), None, AgentsInVmConfig { max_turns: 2, ..Default::default() }, None);+ let p1 = vm.turns.clone().acquire_owned().await.unwrap();+ let p2 = vm.turns.clone().acquire_owned().await.unwrap();+ assert_eq!(vm.free_turn_slots(), 0);+ let vm2 = vm.clone();+ let third = tokio::spawn(async move { vm2.turns.clone().acquire_owned().await.unwrap() });+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert!(!third.is_finished(), "a third turn waits");+ // A turn that ends (even by panic or cancel) drops its IsolatedTurn and with it the permit+ let turn = test_turn(&vm, Some(p1), d.path());+ drop(turn);+ let p3 = tokio::time::timeout(Duration::from_secs(2), third).await.unwrap().unwrap();+ drop((p2, p3));+ assert_eq!(vm.free_turn_slots(), 2);+ }++ fn test_turn(vm: &Arc<AgentVm>, permit: Option<OwnedSemaphorePermit>, dir: &Path) -> IsolatedTurn {+ let lease = vm.broker().register(TurnSpec {+ bot: "b".into(),+ credential: Credential::ApiKey(Secret::new("sk-real")),+ kwnt_origin: Some("http://127.0.0.1:8790".into()),+ cap: 5,+ });+ IsolatedTurn {+ vm: vm.clone(),+ lease,+ container: "kwnt-agent-x".into(),+ workdir: "/w/proj".into(),+ run_dir: dir.join("run"),+ oauth: false,+ kwnt_origin: Some("http://127.0.0.1:8790".into()),+ mcp_file: None,+ _permit: permit,+ }+ }++ #[test]+ fn the_request_limit_and_memory_come_from_server_config() {+ let d = tempfile::tempdir().unwrap();+ let limits = AgentsInVmConfig { request_limit: 7, memory_mb: 2048, max_turns: 3 };+ let vm = AgentVm::with_parts(d.path(), BrokerConfig::new(d.path().join("broker.log")), None, limits.clone(), None);+ assert_eq!(vm.limits(), &limits);+ assert_eq!(vm.free_turn_slots(), 3);+ assert_eq!(AgentsInVmConfig::default(), AgentsInVmConfig { request_limit: 200, memory_mb: 1024, max_turns: 2 });+ }++ #[test]+ fn credentials_resolve_profile_first_and_never_refresh_the_hosts() {+ let d = tempfile::tempdir().unwrap();+ let prof = d.path().join("prof");+ std::fs::create_dir_all(&prof).unwrap();+ std::fs::write(prof.join(".credentials.json"), r#"{"claudeAiOauth":{"accessToken":"a"}}"#).unwrap();+ let (c, home) = resolve_credential_in(Some(&prof), Some("env".into()), None, None).unwrap();+ assert!(matches!(c, Credential::OAuthFile { refresh: true, .. }));+ assert_eq!(home.as_deref(), Some(prof.as_path()));++ let (c, _) = resolve_credential_in(None, Some("sk-env".into()), None, Some(d.path().into())).unwrap();+ assert!(matches!(c, Credential::ApiKey(ref k) if k.expose() == "sk-env"));++ let h = d.path().join("home");+ std::fs::create_dir_all(h.join(".claude")).unwrap();+ std::fs::write(h.join(".claude/.credentials.json"), r#"{"claudeAiOauth":{"accessToken":"a"}}"#).unwrap();+ let (c, _) = resolve_credential_in(None, None, None, Some(h.clone())).unwrap();+ assert!(matches!(c, Credential::OAuthFile { refresh: false, .. }));++ std::fs::remove_file(h.join(".claude/.credentials.json")).unwrap();+ std::fs::write(h.join(".claude.json"), r#"{"primaryApiKey":"sk-console"}"#).unwrap();+ let (c, _) = resolve_credential_in(None, None, None, Some(h.clone())).unwrap();+ assert!(matches!(c, Credential::ApiKey(ref k) if k.expose() == "sk-console"));++ let empty = d.path().join("empty");+ std::fs::create_dir_all(&empty).unwrap();+ assert_eq!(resolve_credential_in(None, None, None, Some(empty.clone())).unwrap_err().code, codes::NO_CREDENTIAL);+ assert_eq!(resolve_credential_in(Some(&empty), Some("env".into()), None, None).unwrap_err().code, codes::NO_CREDENTIAL);+ }++ #[test]+ fn an_expired_host_sign_in_is_refused_but_a_profiles_is_refreshable() {+ let d = tempfile::tempdir().unwrap();+ let f = d.path().join(".credentials.json");+ std::fs::write(&f, r#"{"claudeAiOauth":{"accessToken":"a","refreshToken":"r","expiresAt":1}}"#).unwrap();+ assert_eq!(check_credential(&Credential::OAuthFile { path: f.clone(), refresh: false }).unwrap_err().code, codes::SIGN_IN_EXPIRED);+ assert!(check_credential(&Credential::OAuthFile { path: f, refresh: true }).is_ok());+ }++ #[test]+ fn the_os_gate_says_mac_later() {+ let r = supported_os();+ if cfg!(target_os = "linux") {+ assert!(r.is_ok());+ } else if cfg!(target_os = "macos") {+ assert_eq!(r.unwrap_err().message, "Coming to Mac later");+ }+ }++ #[tokio::test]+ async fn wrap_keeps_only_allowed_env_and_points_claude_at_the_broker() {+ let d = tempfile::tempdir().unwrap();+ let vm = AgentVm::with_parts(d.path(), BrokerConfig::new(d.path().join("broker.log")), None, AgentsInVmConfig::default(), None);+ let mut turn = test_turn(&vm, None, d.path());+ let key = turn.lease.key().to_string();+ let mut cmd = Command::new("/host/claude");+ cmd.env("CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR", "1")+ .env("MCP_TOOL_TIMEOUT", "330000")+ .env("CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT", "330000")+ .env("ANTHROPIC_API_KEY", "sk-real")+ .env("CLAUDE_CONFIG_DIR", "/home/p/.claude")+ .env("AWS_SECRET_ACCESS_KEY", "x")+ .args(["--model", "haiku", "-p", "hi"]);+ let w = turn.wrap(&cmd);+ let args: Vec<String> = w.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect();+ let all = args.join("\u{1}");+ assert_eq!(w.as_std().get_program(), "docker");+ assert!(!all.contains("sk-real") && !all.contains("AWS_SECRET") && !all.contains("/home/p/.claude"), "{args:?}");+ assert!(args.contains(&format!("ANTHROPIC_BASE_URL=http://127.0.0.1:8080/t/{key}/anthropic")));+ assert!(args.contains(&format!("ANTHROPIC_API_KEY={DUMMY_API_KEY}")));+ assert!(args.contains(&"CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR=1".to_string()));+ // The approval wait's limits reach claude in the container too (QA F-2)+ assert!(args.contains(&"MCP_TOOL_TIMEOUT=330000".to_string()), "{args:?}");+ assert!(args.contains(&"CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT=330000".to_string()), "{args:?}");+ assert!(args.windows(2).any(|p| p == ["exec", "-w"]));+ let settings = args.last().unwrap();+ assert!(settings.contains(&format!("/t/{key}/anthropic")) && settings.contains("CLAUDE_CODE_USE_BEDROCK"));+ assert!(w.as_std().get_envs().next().is_none(), "docker itself gets no extra env");++ // MCP: kwnt's own endpoints go through the broker; outside servers are left out+ std::fs::create_dir_all(d.path().join("run")).unwrap();+ let server = |name: &str, url: &str| crate::db::models::McpServer {+ id: format!("id-{name}"),+ name: name.into(),+ transport: "http".into(),+ command: None,+ args: vec![],+ url: Some(url.into()),+ env: Default::default(),+ headers: Default::default(),+ enabled: true,+ timeout_secs: 30,+ created_at: None,+ };+ let ctx = crate::mcp::McpTurnContext {+ servers: vec![+ server("notion", "https://mcp.notion.com/mcp"),+ server("kwnt_tools", "http://127.0.0.1:8790/api/mcp/self"),+ server("kwnt_other", "http://127.0.0.1:8790/api/settings/computer"),+ ],+ approver: Arc::new(crate::mcp::FixedApprover(true)),+ config_dir: d.path().join("cfg"),+ permission_url: Some("http://127.0.0.1:8790/api/mcp/permission/perm456".into()),+ gateway: None,+ max_tool_iterations: 4,+ smart_approvals: false,+ records: Default::default(),+ };+ let (path, mut dropped) = turn.write_mcp_config(&ctx).unwrap();+ dropped.sort();+ assert!(path.starts_with("/run/kwnt/mcp-"));+ assert_eq!(dropped, vec!["kwnt_other".to_string(), "notion".to_string()]);+ let host_file = turn.mcp_file.as_ref().unwrap().path.clone();+ let doc: Value = serde_json::from_str(&std::fs::read_to_string(&host_file).unwrap()).unwrap();+ assert_eq!(doc["mcpServers"]["kwnt_tools"]["url"], format!("http://127.0.0.1:8080/t/{key}/kwnt/api/mcp/self"));+ assert!(doc["mcpServers"]["kwnt"]["url"].as_str().unwrap().ends_with("/kwnt/api/mcp/permission/perm456"));+ drop(turn);+ assert!(!host_file.exists());+ }+}diff --git a/src/sandbox/agent_vm/notice.rs b/src/sandbox/agent_vm/notice.rsnew file mode 100644index 00000000..fb30a646--- /dev/null+++ b/src/sandbox/agent_vm/notice.rs@@ -0,0 +1,412 @@+//! What the person and the model read when isolation stops something (Mira's+//! `design/ui.md`, "Copy for Ada's decisions 2").+//!+//! - [`IsolationFailed`] is the chat meta `turn_isolation_failed`, one shape for every reason, so+//! the frontend has one renderer. `unsafe_folder` and `folder_used_by_isolated_bot` add the+//! folder, where it came from and, for `unsafe_folder`, `unsafe_kind`.+//! - [`body`] holds the broker's refusal texts. The CLI shows them to Claude, not to the person,+//! so they say what to do next.++use super::folder_rule::UnsafeKind;+use serde_json::{json, Map, Value};+use std::path::Path;++/// The Claude CLI's own tools an isolated turn starts without (`--disallowedTools`), so the model+/// goes straight to kwnt's browser tools instead of hitting the broker's 400 and retrying (D3).+pub const DISALLOWED_TOOLS: &str = "WebSearch,WebFetch";++/// `args` (kwnt's claude argv, without the program) with [`DISALLOWED_TOOLS`] added: merged into+/// the first `--disallowedTools` value (claude reads one comma-separated list), or as a new flag.+pub fn with_disallowed_tools(mut args: Vec<std::ffi::OsString>) -> Vec<std::ffi::OsString> {+ if let Some(i) = args.iter().position(|a| a == "--disallowedTools") {+ if let Some(v) = args.get_mut(i + 1) {+ let mut list: Vec<String> = v.to_string_lossy().split(',').map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect();+ for t in DISALLOWED_TOOLS.split(',') {+ if !list.iter().any(|x| x == t) {+ list.push(t.into());+ }+ }+ *v = list.join(",").into();+ return args;+ }+ }+ args.extend(["--disallowedTools".into(), DISALLOWED_TOOLS.into()]);+ args+}++pub mod reason {+ pub const UNSAFE_FOLDER: &str = "unsafe_folder";+ pub const FOLDER_USED_BY_ISOLATED_BOT: &str = "folder_used_by_isolated_bot";+}++/// The broker's response bodies the model reads.+pub mod body {+ /// 400: a server tool (`web_search_*`, `web_fetch_*`, `code_execution_*`, …) in the request.+ pub const SERVER_TOOL: &str = "Web search and fetch don't work while this bot runs inside kwant's VM. Use kwant's browser tools instead.";+ /// 400: `mcp_servers` in the request.+ pub const MCP_SERVERS: &str = "Remote MCP servers can't be added from inside kwant's VM. Use the tools kwant already gives this bot.";+ /// 400: a content block Anthropic would fetch itself (`source` by URL or Files API id). Not in+ /// Mira's table; same voice.+ pub const FETCH_BY_REFERENCE: &str = "Anthropic can't fetch links or files for this bot while it runs inside kwant's VM. Put the content in the message, or use kwant's browser tools.";+ /// 403: no turn is open for this container (D2).+ pub const NO_TURN: &str = "No reply is running for this bot, so kwant won't pass this request on.";++ /// 429: the turn reached its request cap.+ pub fn request_cap(limit: u32) -> String {+ format!("This reply reached its limit of {limit} requests to Claude. kwant paused it, and the person can continue it from the chat.")+ }+}++/// The safety line shared by notices 1–3 and the rows below: nothing ran outside the VM.+pub const SAFETY: &str = "While Run Claude inside the VM is on, Claude never runs outside it, so nothing ran on this computer.";++/// The chat text saved with a `turn_isolation_failed` notice that stopped Claude before it+/// started (Mira's notices 1, 2, 2b, 2c, 4 and the rows of ui-check-446 fix 4). The card is drawn+/// from the meta; this is what a client without the card, and the chat history, show. Every+/// refusal code kwant sends has its own row ([`super::codes::ALL`]); the "Something went wrong"+/// row is only for a code a newer kwant adds. `unsafe_folder` with its folder is+/// [`unsafe_folder_text`].+pub fn start_text(bot: &str, reason: &str) -> String {+ let couldnt_start = format!("{bot} didn't reply: Claude couldn't start inside the VM.");+ let not_ready = format!("{bot} didn't reply: Claude's VM isn't ready yet.");+ let this_folder = format!("{bot} didn't reply: Claude can't use this folder inside the VM.");+ match reason {+ "docker_unavailable" => format!("{couldnt_start} Docker isn't running on this computer. Start Docker, then Retry. {SAFETY}"),+ "preparing" => format!("{not_ready} The one-time download is still running. Retry when it's done. {SAFETY}"),+ "download_failed" | "download_needed" => {+ format!("{not_ready} The one-time download didn't finish. Try it again in Computer settings, then Retry. {SAFETY}")+ }+ "relay_down" => format!("{couldnt_start} kwant couldn't connect Claude to your sign-in. Restart kwant, then Retry. {SAFETY}"),+ "sign_in_expired" => format!("{bot} didn't reply: your Claude sign-in has expired. Sign in again in Settings › This space › Accounts, then Retry."),+ "no_credential" => format!(+ "{bot} didn't reply: there's no Claude sign-in for it on this computer. Sign in to Claude in Settings › This space › Accounts, then Retry."+ ),+ "host_is_root" => format!(+ "{couldnt_start} kwant is running as root, so Claude can't run inside the VM as you. Start kwant as your normal user, then Retry. {SAFETY}"+ ),+ "folder_name_unsupported" => format!(+ "{this_folder} The folder's name has characters kwant can't pass to the VM, like a line break. Rename the folder, then Retry. Nothing ran."+ ),+ "folder_record_failed" => format!(+ "{couldnt_start} kwant couldn't note that this folder is used inside the VM, so it didn't start Claude. Retry; if it keeps happening, restart kwant. {SAFETY}"+ ),+ "container_failed" => format!("{couldnt_start} The VM couldn't start Claude. Retry; if it keeps happening, restart Docker. {SAFETY}"),+ "unsupported_os" => format!(+ "{couldnt_start} Isolation is only on Linux for now. Turn off Run Claude inside the VM to run Claude on this computer. {SAFETY}"+ ),+ // Without its folder (Mira's "missing or unknown" row)+ reason::UNSAFE_FOLDER => format!(+ "{this_folder} This folder holds your home folder or sign-ins, so kwant won't share it with the VM. Pick a project folder instead, then Retry. Nothing ran."+ ),+ code => format!(+ "{couldnt_start} Something went wrong ({code}). Retry, or turn off Run Claude inside the VM to run Claude on this computer. {SAFETY}"+ ),+ }+}++/// The chat text saved with notice 6 (`unsafe_folder`), from Mira's two tables in `design/ui.md`:+/// one sentence for `kind`, one for where the folder came from. `home` shortens the folder.+pub fn unsafe_folder_text(bot: &str, kind: UnsafeKind, folder: &FolderInfo, home: Option<&Path>) -> String {+ let shown = tilde(&folder.folder, home);+ let team = folder.team.as_ref().map(|(_, name)| name.as_str());+ let first = format!("{bot} didn't reply: Claude can't use this folder inside the VM.");+ let why = match kind {+ UnsafeKind::Home => format!("{shown} is your home folder. Inside the VM, Claude would see all your files and sign-ins."),+ UnsafeKind::ContainsHome | UnsafeKind::Root => {+ format!("{shown} holds your home folder. Inside the VM, Claude would see all your files and sign-ins.")+ }+ UnsafeKind::SignIns => format!(+ "{shown} holds sign-ins, like your SSH keys or Claude, Codex or Grok sign-in, so kwant won't share it with the VM."+ ),+ UnsafeKind::KwantData => format!("{shown} holds kwant's own data, including your sign-ins, so kwant won't share it with the VM."),+ UnsafeKind::Docker => format!("{shown} holds Docker's control socket, which would let Claude out of the VM."),+ // No path: kwant's own path means nothing to people+ UnsafeKind::SharedFolder => {+ let give = match team {+ Some(t) => format!("Give @{t} its own folder"),+ None => "Give this team its own folder".into(),+ };+ return format!(+ "{first} This is the folder teams share when they don't have their own. If Claude used it inside the VM, Codex and Grok bots in every team would be kept out of it. {give}, then Retry. Nothing ran."+ );+ }+ };+ let pick = match (folder.from, team) {+ (FolderFrom::Team, Some(t)) => format!("Pick a project folder for @{t} instead"),+ (FolderFrom::Goal, _) => "Pick a project folder for this goal instead".into(),+ _ => "Pick a project folder instead".into(),+ };+ format!("{first} {why} {pick}, then Retry. Nothing ran.")+}++/// `folder` with `home` (the person's home folder) shortened to `~`.+pub fn tilde(folder: &str, home: Option<&Path>) -> String {+ let Some(home) = home.map(|h| h.to_string_lossy()).filter(|h| h.len() > 1) else { return folder.to_string() };+ let home = home.trim_end_matches('/');+ match folder.strip_prefix(home) {+ Some("") => "~".into(),+ Some(rest) if rest.starts_with('/') => format!("~{rest}"),+ _ => folder.to_string(),+ }+}++/// The text saved when an isolated reply stopped partway (notice 3).+pub fn mid_turn_text(bot: &str) -> String {+ format!(+ "{bot}'s reply stopped partway: Claude lost its connection inside the VM. What it changed before that is in the task folder, and Undo still works. Retry to start the reply again. {SAFETY}"+ )+}++/// The chat text saved with notice 7 (`folder_used_by_isolated_bot`). `engine`: `codex` or `grok`.+pub fn folder_used_text(bot: &str, engine: &str) -> String {+ let engine = match engine {+ "codex" => "Codex",+ "grok" => "Grok",+ other => other,+ };+ format!(+ "{bot} didn't reply: {engine} won't run in a folder Claude used inside the VM. A bot inside the VM could have left settings there that {engine} would load on this computer, so kwant keeps {engine} out of it for now. Switch {bot} to Claude, or pick another folder, then Retry. Nothing ran."+ )+}++/// Where a turn's folder came from, which picks the second reason sentence and whether the+/// notice offers "Change folder".+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FolderFrom {+ Team,+ Space,+ Goal,+ Bot,+}++impl FolderFrom {+ pub fn as_str(self) -> &'static str {+ match self {+ FolderFrom::Team => "team",+ FolderFrom::Space => "space",+ FolderFrom::Goal => "goal",+ FolderFrom::Bot => "bot",+ }+ }+}++/// The folder a refused turn would have used.+#[derive(Debug, Clone)]+pub struct FolderInfo {+ /// Canonical path.+ pub folder: String,+ pub from: FolderFrom,+ /// Set when `from` is [`FolderFrom::Team`].+ pub team: Option<(String, String)>,+}++impl FolderInfo {+ pub fn new(folder: &Path, from: FolderFrom) -> Self {+ Self { folder: folder.to_string_lossy().into_owned(), from, team: None }+ }++ pub fn team(folder: &Path, team_id: &str, team_name: &str) -> Self {+ Self { folder: folder.to_string_lossy().into_owned(), from: FolderFrom::Team, team: Some((team_id.into(), team_name.into())) }+ }+}++/// The `turn_isolation_failed` chat meta.+#[derive(Debug, Clone)]+pub struct IsolationFailed {+ pub kwant_name: String,+ /// `claude` for every reason but `folder_used_by_isolated_bot` (`codex` or `grok`).+ pub engine: String,+ pub reason: String,+ /// `start` when it failed before the CLI ran.+ pub phase: &'static str,+ pub progress_pct: Option<u8>,+ /// The stable refusal code, when it isn't already the reason.+ pub code: Option<String>,+ pub folder: Option<FolderInfo>,+ pub unsafe_kind: Option<UnsafeKind>,+}++impl IsolationFailed {+ pub fn new(kwant_name: &str, engine: &str, reason: &str) -> Self {+ Self {+ kwant_name: kwant_name.into(),+ engine: engine.into(),+ reason: reason.into(),+ phase: "start",+ progress_pct: None,+ code: None,+ folder: None,+ unsafe_kind: None,+ }+ }++ /// `unsafe_folder`: Claude, refused before `docker run`.+ pub fn unsafe_folder(kwant_name: &str, folder: FolderInfo, kind: UnsafeKind) -> Self {+ Self { folder: Some(folder), unsafe_kind: Some(kind), ..Self::new(kwant_name, "claude", reason::UNSAFE_FOLDER) }+ }++ /// `folder_used_by_isolated_bot`: a host Codex or Grok turn in a folder an isolated bot used.+ pub fn folder_used(kwant_name: &str, engine: &str, folder: FolderInfo) -> Self {+ Self { folder: Some(folder), ..Self::new(kwant_name, engine, reason::FOLDER_USED_BY_ISOLATED_BOT) }+ }++ pub fn to_meta(&self) -> Value {+ let mut m = Map::new();+ m.insert("kind".into(), json!("turn_isolation_failed"));+ m.insert("kwant_name".into(), json!(self.kwant_name));+ m.insert("engine".into(), json!(self.engine));+ m.insert("reason".into(), json!(self.reason));+ m.insert("phase".into(), json!(self.phase));+ m.insert("progress_pct".into(), json!(self.progress_pct));+ m.insert("code".into(), json!(self.code));+ if let Some(f) = &self.folder {+ m.insert("folder".into(), json!(f.folder));+ m.insert("folder_from".into(), json!(f.from.as_str()));+ if let Some((id, name)) = &f.team {+ m.insert("team_id".into(), json!(id));+ m.insert("team_name".into(), json!(name));+ }+ }+ if let Some(k) = self.unsafe_kind {+ m.insert("unsafe_kind".into(), json!(k.as_str()));+ }+ Value::Object(m)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn unsafe_folder_meta_matches_the_ui_contract() {+ let m = IsolationFailed::unsafe_folder("Ada", FolderInfo::team(Path::new("/home/oleks"), "t_1", "Checkout"), UnsafeKind::Home).to_meta();+ assert_eq!(+ m,+ json!({ "kind": "turn_isolation_failed", "kwant_name": "Ada", "engine": "claude", "reason": "unsafe_folder",+ "phase": "start", "progress_pct": null, "code": null, "folder": "/home/oleks", "folder_from": "team",+ "team_id": "t_1", "team_name": "Checkout", "unsafe_kind": "home" })+ );+ }++ #[test]+ fn folder_used_meta_has_no_unsafe_kind_and_no_team_outside_a_team() {+ let m = IsolationFailed::folder_used("Rex", "codex", FolderInfo::new(Path::new("/home/oleks/shop"), FolderFrom::Bot)).to_meta();+ assert_eq!(m["reason"], "folder_used_by_isolated_bot");+ assert_eq!(m["engine"], "codex");+ assert_eq!(m["folder_from"], "bot");+ for absent in ["unsafe_kind", "team_id", "team_name"] {+ assert!(m.get(absent).is_none(), "{absent}");+ }+ }++ #[test]+ fn saved_texts_use_miras_first_lines_and_never_claim_a_host_run() {+ assert!(start_text("Ada", "docker_unavailable").starts_with("Ada didn't reply: Claude couldn't start inside the VM. Docker isn't running"));+ assert!(start_text("Ada", "preparing").starts_with("Ada didn't reply: Claude's VM isn't ready yet."));+ assert!(start_text("Ada", "sign_in_expired").contains("Settings › This space › Accounts"));+ for r in ["docker_unavailable", "preparing", "download_failed", "relay_down", "container_failed", "host_is_root", "folder_record_failed", "unsupported_os"] {+ assert!(start_text("Ada", r).ends_with(SAFETY), "{r}");+ }+ // A code from a newer kwant still reads, naming the code+ assert!(start_text("Ada", "brand_new").contains("Something went wrong (brand_new)"));+ // Notice 3 has the safety line too (ui-check-446 fix 10)+ let mid = mid_turn_text("Ada");+ assert!(mid.starts_with("Ada's reply stopped partway: Claude lost its connection inside the VM."), "{mid}");+ assert!(mid.ends_with(SAFETY), "{mid}");+ let used = folder_used_text("Rex", "codex");+ assert!(used.starts_with("Rex didn't reply: Codex won't run in a folder Claude used inside the VM."), "{used}");+ }++ #[test]+ fn every_refusal_code_has_its_own_words() {+ // ui-check-446 fix 4: no code kwant sends falls to "Something went wrong (code)"+ for &code in super::super::codes::ALL {+ if code == reason::FOLDER_USED_BY_ISOLATED_BOT {+ continue; // folder_used_text+ }+ let t = start_text("Ada", code);+ assert!(!t.contains("Something went wrong"), "{code}: {t}");+ assert!(t.starts_with("Ada didn't reply:"), "{code}: {t}");+ for never in ["kwnt", "in the computer", "shared with the computer"] {+ assert!(!t.contains(never), "{code}: {t}");+ }+ }+ let t = start_text("Ada", "no_credential");+ assert_eq!(+ t,+ "Ada didn't reply: there's no Claude sign-in for it on this computer. Sign in to Claude in Settings › This space › Accounts, then Retry."+ );+ assert!(start_text("Ada", "host_is_root").contains("kwant is running as root"));+ assert!(start_text("Ada", "folder_name_unsupported").contains("like a line break. Rename the folder, then Retry. Nothing ran."));+ }++ #[test]+ fn the_unsafe_folder_text_says_each_thing_once_with_miras_words() {+ let home = Path::new("/home/oleks");+ let bot = FolderInfo::new(Path::new("/home/oleks"), FolderFrom::Bot);+ let t = unsafe_folder_text("Ada", UnsafeKind::Home, &bot, Some(home));+ assert_eq!(+ t,+ "Ada didn't reply: Claude can't use this folder inside the VM. ~ is your home folder. Inside the VM, Claude would see all your files and sign-ins. Pick a project folder instead, then Retry. Nothing ran."+ );+ assert_eq!(t.matches("Pick a project folder").count(), 1, "{t}");+ assert!(!t.contains("the computer"), "{t}");+ // A team's folder names the team; the path is shortened under home+ let team = FolderInfo::team(Path::new("/home/oleks/.ssh"), "t_1", "Checkout");+ let t = unsafe_folder_text("Ada", UnsafeKind::SignIns, &team, Some(home));+ assert!(t.contains("~/.ssh holds sign-ins, like your SSH keys"), "{t}");+ assert!(t.ends_with("Pick a project folder for @Checkout instead, then Retry. Nothing ran."), "{t}");+ // kwant's own shared folder: no path at all+ let shared = FolderInfo::team(Path::new("/home/oleks/.kwnt/workspace"), "t_1", "Checkout");+ let t = unsafe_folder_text("Ada", UnsafeKind::SharedFolder, &shared, Some(home));+ assert!(!t.contains("/") && !t.contains('~'), "{t}");+ assert!(t.ends_with("Give @Checkout its own folder, then Retry. Nothing ran."), "{t}");+ let alone = FolderInfo::new(Path::new("/home/oleks/.kwnt/workspace"), FolderFrom::Bot);+ assert!(unsafe_folder_text("Ada", UnsafeKind::SharedFolder, &alone, Some(home)).contains("Give this team its own folder, then Retry."));+ for (kind, words) in [+ (UnsafeKind::Root, "/ holds your home folder."),+ (UnsafeKind::KwantData, "holds kwant's own data, including your sign-ins"),+ (UnsafeKind::Docker, "holds Docker's control socket, which would let Claude out of the VM."),+ ] {+ let f = FolderInfo::new(Path::new(if kind == UnsafeKind::Root { "/" } else { "/srv/x" }), FolderFrom::Bot);+ let t = unsafe_folder_text("Ada", kind, &f, Some(home));+ assert!(t.contains(words), "{t}");+ assert_eq!(t.matches("Pick a project folder").count(), 1, "{t}");+ }+ assert_eq!(tilde("/home/oleksandr/x", Some(home)), "/home/oleksandr/x", "only whole folder names");+ assert_eq!(tilde("/home/oleks/site", Some(Path::new("/home/oleks/"))), "~/site");+ assert_eq!(tilde("/srv", None), "/srv");+ }++ #[test]+ fn a_reason_without_a_folder_sends_no_folder_fields() {+ let m = IsolationFailed::new("Ada", "claude", "docker_unavailable").to_meta();+ for absent in ["folder", "folder_from", "unsafe_kind"] {+ assert!(m.get(absent).is_none(), "{absent}");+ }+ }++ #[test]+ fn web_tools_are_merged_into_kwnts_own_disallowed_list() {+ let os = |v: &[&str]| v.iter().map(std::ffi::OsString::from).collect::<Vec<_>>();+ let merged = with_disallowed_tools(os(&["-p", "--disallowedTools", "CronCreate,WebFetch", "--model", "x"]));+ assert_eq!(merged, os(&["-p", "--disallowedTools", "CronCreate,WebFetch,WebSearch", "--model", "x"]));+ let added = with_disallowed_tools(os(&["-p"]));+ assert_eq!(added, os(&["-p", "--disallowedTools", "WebSearch,WebFetch"]));+ let [flag, list] = crate::drivers::cli::claude_disallowed_args();+ let real = with_disallowed_tools(os(&[&flag, &list]));+ assert_eq!(real.iter().filter(|a| *a == "--disallowedTools").count(), 1);+ let v = real[1].to_string_lossy();+ assert!(v.starts_with(list.as_str()) && v.contains("WebSearch") && v.contains("WebFetch"), "{v}");+ }++ #[test]+ fn broker_bodies_name_the_way_forward() {+ assert!(body::SERVER_TOOL.contains("browser tools"));+ assert_eq!(+ body::request_cap(200),+ "This reply reached its limit of 200 requests to Claude. kwant paused it, and the person can continue it from the chat."+ );+ }+}diff --git a/src/sandbox/manager.rs b/src/sandbox/manager.rsindex d3191a16..58fb6244 100644--- a/src/sandbox/manager.rs+++ b/src/sandbox/manager.rs@@ -21,6 +21,53 @@ pub enum SandboxError {NotFound(String),}+pub const EXECUTOR_IMAGE: &str = "kwnt-executor:v1";++/// True when the image `tag` is already built.+pub async fn image_exists(tag: &str) -> bool {+ Command::new("docker")+ .args(["image", "inspect", tag])+ .kill_on_drop(true)+ .output()+ .await+ .is_ok_and(|out| out.status.success())+}++/// Builds `tag` from `files` (a `Dockerfile` and what it copies) unless it exists. The build+/// folder is private to this build, so two images never share one.+pub async fn ensure_image(tag: &str, files: &[(&str, &str)], build_args: &[(&str, &str)]) -> Result<(), SandboxError> {+ if image_exists(tag).await {+ return Ok(());+ }+ let build = std::env::temp_dir().join(format!("kwnt-image-build-{}", uuid::Uuid::new_v4().simple()));+ let result = async {+ tokio::fs::create_dir_all(&build).await?;+ for (name, content) in files {+ tokio::fs::write(build.join(name), content).await?;+ }+ let mut cmd = Command::new("docker");+ cmd.args(["build", "-t", tag]);+ for (k, v) in build_args {+ cmd.arg("--build-arg").arg(format!("{k}={v}"));+ }+ cmd.arg(&build).kill_on_drop(true).output().await+ }+ .await;+ let _ = tokio::fs::remove_dir_all(&build).await;+ let out = result.map_err(|e| SandboxError::StartFailed(e.to_string()))?;+ if !out.status.success() {+ let err = String::from_utf8_lossy(&out.stderr);+ let tail: String = err.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n");+ return Err(SandboxError::StartFailed(tail));+ }+ Ok(())+}++/// kwnt's base image for commands run in the computer (and the agent image's base).+pub async fn ensure_executor_image() -> Result<(), SandboxError> {+ ensure_image(EXECUTOR_IMAGE, &[("Dockerfile", include_str!("../../docker/executor.Dockerfile"))], &[]).await+}+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub struct ShellOutput {pub command: String,@@ -105,16 +152,7 @@ impl SandboxManager {let _ = Command::new("docker").args(["rm", "-f", &container_name]).output().await;let ws_str = workspace_dir.to_string_lossy().to_string();- if Command::new("docker").args(["image", "inspect", "kwnt-executor:v1"]).output().await- .map(|out| !out.status.success()).unwrap_or(true) {- let build = std::env::temp_dir().join("kwnt-executor-build");- tokio::fs::create_dir_all(&build).await.map_err(|e| SandboxError::StartFailed(e.to_string()))?;- tokio::fs::write(build.join("Dockerfile"), include_str!("../../docker/executor.Dockerfile")).await- .map_err(|e| SandboxError::StartFailed(e.to_string()))?;- let out = Command::new("docker").args(["build", "-t", "kwnt-executor:v1", &build.to_string_lossy()]).output().await- .map_err(|e| SandboxError::StartFailed(e.to_string()))?;- if !out.status.success() { return Err(SandboxError::StartFailed(String::from_utf8_lossy(&out.stderr).to_string())); }- }+ ensure_executor_image().await?;let run_res = Command::new("docker").args(["run",@@ -127,7 +165,7 @@ impl SandboxManager {&format!("{}:/workspace:rw", ws_str),"-w","/workspace",- "kwnt-executor:v1",+ EXECUTOR_IMAGE,]).output().awaitdiff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex 28679c0f..d3e4cc9e 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -1,3 +1,4 @@+pub mod agent_vm;pub mod app_links;pub mod bitwarden;pub mod browser;@@ -9,6 +10,7 @@ pub mod manager;pub mod cite;pub mod progress;pub mod reads;+pub mod safe_fs;pub mod service;pub mod site_guard;pub mod vault;diff --git a/src/sandbox/safe_fs.rs b/src/sandbox/safe_fs.rsnew file mode 100644index 00000000..289ae807--- /dev/null+++ b/src/sandbox/safe_fs.rs@@ -0,0 +1,648 @@+//! Reading a bot's folder from this computer while the bot may be changing it (test plan S-8).+//!+//! In vm mode the bot controls its folder from inside its container, so any folder or file in it+//! can turn into a symlink between a check and an open. A per-path `symlink_metadata` check and a+//! later `open` by path is a race the bot can win. [`Dir`] never resolves a path twice: it holds+//! the folder open and walks each component with `openat(…, O_NOFOLLOW|O_DIRECTORY)`, opens the+//! last one with `O_NOFOLLOW|O_NONBLOCK` and checks with `fstat` that what it holds is a regular+//! file. A component swapped for a symlink fails the open (`ELOOP` or `ENOTDIR`); nothing outside+//! the folder is ever opened, and no FIFO blocks the reader.+//!+//! Off unix (Windows, where isolation doesn't run) it falls back to checks by path.++use std::ffi::OsString;+use std::fs::File;+use std::io;+use std::path::{Component, Path};++/// What a folder entry is, seen without following it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Kind {+ File,+ Dir,+ Symlink,+ Other,+}++#[derive(Debug, Clone)]+pub struct Entry {+ pub name: OsString,+ pub kind: Kind,+ /// Size in bytes from `lstat` at listing time. The file can grow after that: a reader caps+ /// what it reads from the open handle ([`read_capped`], [`copy_capped`]), never this.+ pub len: u64,+ /// Permission bits.+ pub mode: u32,+}++/// The plain parts of `rel`: refuses an absolute path, `..`, `.` and empty paths' oddities.+fn parts(rel: &Path) -> io::Result<Vec<&std::ffi::OsStr>> {+ rel.components()+ .map(|c| match c {+ Component::Normal(p) => Ok(p),+ _ => Err(io::Error::new(io::ErrorKind::InvalidInput, "not a plain relative path")),+ })+ .collect()+}++fn not_a_file() -> io::Error {+ io::Error::new(io::ErrorKind::InvalidInput, "not a regular file")+}++#[cfg(unix)]+mod imp {+ use super::*;+ use std::ffi::{CStr, CString, OsStr};+ use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};+ use std::os::unix::ffi::{OsStrExt, OsStringExt};++ const DIR_FLAGS: libc::c_int = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;+ const FILE_FLAGS: libc::c_int = libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC;++ /// An open folder; everything under it is reached from this descriptor.+ #[derive(Debug)]+ pub struct Dir {+ fd: OwnedFd,+ }++ fn cstr(name: &OsStr) -> io::Result<CString> {+ CString::new(name.as_bytes()).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in a name"))+ }++ /// A single plain name.+ fn one(name: &OsStr) -> io::Result<CString> {+ match parts(Path::new(name))?.as_slice() {+ [_] => cstr(name),+ _ => Err(io::Error::new(io::ErrorKind::InvalidInput, "not a single name")),+ }+ }++ fn check(fd: libc::c_int) -> io::Result<OwnedFd> {+ if fd < 0 {+ return Err(io::Error::last_os_error());+ }+ // SAFETY: a descriptor the kernel just returned to us, owned by nothing else+ Ok(unsafe { OwnedFd::from_raw_fd(fd) })+ }++ // `mode_t` is u32 on Linux and u16 on macOS, so the casts are needed there+ #[allow(clippy::unnecessary_cast)]+ fn mode_kind(mode: u32) -> Kind {+ match mode & libc::S_IFMT as u32 {+ m if m == libc::S_IFREG as u32 => Kind::File,+ m if m == libc::S_IFDIR as u32 => Kind::Dir,+ m if m == libc::S_IFLNK as u32 => Kind::Symlink,+ _ => Kind::Other,+ }+ }++ fn fstat(fd: &OwnedFd) -> io::Result<libc::stat> {+ let mut st = std::mem::MaybeUninit::<libc::stat>::zeroed();+ // SAFETY: `st` is a valid out pointer for one `stat`+ if unsafe { libc::fstat(fd.as_raw_fd(), st.as_mut_ptr()) } != 0 {+ return Err(io::Error::last_os_error());+ }+ // SAFETY: fstat succeeded and filled it+ Ok(unsafe { st.assume_init() })+ }++ impl Dir {+ /// Opens `root` itself, resolved once: it's the person's own path (a symlink they made is+ /// fine) and, in vm mode, a mount point the bot can't swap. Everything below it is the+ /// bot's and is never followed.+ pub fn open(root: &Path) -> io::Result<Self> {+ let c = cstr(root.as_os_str())?;+ // SAFETY: a valid C string; the flags never create anything+ check(unsafe { libc::open(c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) }).map(|fd| Self { fd })+ }++ /// Opens the absolute folder `path` one part at a time from `/`, each with+ /// `O_NOFOLLOW|O_DIRECTORY` (QA F-3): a symlink on any part, the folder itself included, is+ /// refused (`ELOOP`/`ENOTDIR`), so a folder the bot swapped for a symlink is never entered.+ /// One exception: a symlink owned by root (macOS's `/var`, `/tmp`), which a bot running as+ /// the person can neither make nor swap, is followed under the same rule.+ pub fn open_strict(path: &Path) -> io::Result<Self> {+ if !path.is_absolute() {+ return Err(io::Error::new(io::ErrorKind::InvalidInput, "not an absolute path"));+ }+ let mut links = 0;+ Self::walk(Self::open(Path::new("/"))?, path, &mut links)+ }++ // `mode_t` is u32 on Linux and u16 on macOS, so the cast is needed there+ #[allow(clippy::unnecessary_cast)]+ fn walk(start: Dir, path: &Path, links: &mut u32) -> io::Result<Dir> {+ let mut cur = start;+ for c in path.components() {+ cur = match c {+ Component::RootDir => Self::open(Path::new("/"))?,+ Component::CurDir => cur,+ Component::ParentDir => Dir { fd: cur.at(OsStr::new(".."), DIR_FLAGS)? },+ Component::Normal(n) => match cur.at(n, DIR_FLAGS) {+ Ok(fd) => Dir { fd },+ Err(e) if matches!(e.raw_os_error(), Some(libc::ELOOP) | Some(libc::ENOTDIR)) => {+ let st = cur.lstat_at(n)?;+ if mode_kind(st.st_mode as u32) != Kind::Symlink || st.st_uid != 0 || *links >= 16 {+ return Err(e);+ }+ *links += 1;+ let target = cur.read_link_at(n)?;+ Self::walk(cur, &target, links)?+ }+ Err(e) => return Err(e),+ },+ Component::Prefix(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a unix path")),+ };+ }+ Ok(cur)+ }++ fn lstat_at(&self, name: &OsStr) -> io::Result<libc::stat> {+ let c = cstr(name)?;+ let mut st = std::mem::MaybeUninit::<libc::stat>::zeroed();+ // SAFETY: a valid descriptor, C string and out pointer+ if unsafe { libc::fstatat(self.fd.as_raw_fd(), c.as_ptr(), st.as_mut_ptr(), libc::AT_SYMLINK_NOFOLLOW) } != 0 {+ return Err(io::Error::last_os_error());+ }+ // SAFETY: fstatat succeeded and filled it+ Ok(unsafe { st.assume_init() })+ }++ fn read_link_at(&self, name: &OsStr) -> io::Result<std::path::PathBuf> {+ let c = cstr(name)?;+ let mut buf = vec![0u8; libc::PATH_MAX as usize];+ // SAFETY: a valid descriptor, C string and buffer of the given length+ let n = unsafe { libc::readlinkat(self.fd.as_raw_fd(), c.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };+ if n < 0 {+ return Err(io::Error::last_os_error());+ }+ buf.truncate(n as usize);+ Ok(std::path::PathBuf::from(OsString::from_vec(buf)))+ }++ fn at(&self, name: &OsStr, flags: libc::c_int) -> io::Result<OwnedFd> {+ let c = cstr(name)?;+ // SAFETY: a valid descriptor and C string; the flags never create anything+ check(unsafe { libc::openat(self.fd.as_raw_fd(), c.as_ptr(), flags) })+ }++ /// The folder `rel` below this one (`""` is this folder again), every step a real folder.+ pub fn open_dir(&self, rel: &Path) -> io::Result<Dir> {+ let mut cur = Dir { fd: self.fd.try_clone()? };+ for p in parts(rel)? {+ cur = Dir { fd: cur.at(p, DIR_FLAGS)? };+ }+ Ok(cur)+ }++ /// The regular file `rel` below this folder, every folder on the way a real folder.+ pub fn open_file(&self, rel: &Path) -> io::Result<File> {+ let ps = parts(rel)?;+ let Some((last, dirs)) = ps.split_last() else { return Err(not_a_file()) };+ let mut cur = Dir { fd: self.fd.try_clone()? };+ for p in dirs {+ cur = Dir { fd: cur.at(p, DIR_FLAGS)? };+ }+ let fd = cur.at(last, FILE_FLAGS)?;+ if mode_kind(fstat(&fd)?.st_mode as u32) != Kind::File {+ return Err(not_a_file());+ }+ Ok(File::from(fd))+ }++ /// The folder `rel` below this one, made where missing (`mkdirat`), every step opened with+ /// `O_NOFOLLOW|O_DIRECTORY`: a symlink on the way is refused, never written through.+ pub fn make_dirs(&self, rel: &Path) -> io::Result<Dir> {+ let mut cur = Dir { fd: self.fd.try_clone()? };+ for p in parts(rel)? {+ let c = cstr(p)?;+ // SAFETY: a valid descriptor and C string+ if unsafe { libc::mkdirat(cur.fd.as_raw_fd(), c.as_ptr(), 0o777) } != 0 {+ let e = io::Error::last_os_error();+ if e.raw_os_error() != Some(libc::EEXIST) {+ return Err(e);+ }+ }+ cur = Dir { fd: cur.at(p, DIR_FLAGS)? };+ }+ Ok(cur)+ }++ /// Replaces the entry `name` in this folder with `src`'s bytes: written to a new `tmp`+ /// (`O_CREAT|O_EXCL|O_NOFOLLOW`), given `mode`, then `renameat` over `name` (a symlink there+ /// is replaced, not followed).+ pub fn replace_file(&self, name: &OsStr, tmp: &str, src: &mut impl io::Read, mode: u32) -> io::Result<()> {+ let (name, tmp) = (one(name)?, one(OsStr::new(tmp))?);+ let flags = libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC;+ // SAFETY: a valid descriptor and C string; O_EXCL never opens an existing entry+ let fd = check(unsafe { libc::openat(self.fd.as_raw_fd(), tmp.as_ptr(), flags, 0o600 as libc::c_uint) })?;+ let mut f = File::from(fd);+ let res = io::copy(src, &mut f).and_then(|_| {+ use std::os::unix::fs::PermissionsExt;+ f.set_permissions(std::fs::Permissions::from_mode(mode & 0o7777))+ });+ drop(f);+ // SAFETY: valid descriptors and C strings+ let res = res.and_then(|_| match unsafe { libc::renameat(self.fd.as_raw_fd(), tmp.as_ptr(), self.fd.as_raw_fd(), name.as_ptr()) } {+ 0 => Ok(()),+ _ => Err(io::Error::last_os_error()),+ });+ if res.is_err() {+ // SAFETY: a valid descriptor and C string+ unsafe { libc::unlinkat(self.fd.as_raw_fd(), tmp.as_ptr(), 0) };+ }+ res+ }++ /// Removes the entry `name` (never a folder) from this folder.+ pub fn remove_file(&self, name: &OsStr) -> io::Result<()> {+ let c = one(name)?;+ // SAFETY: a valid descriptor and C string+ match unsafe { libc::unlinkat(self.fd.as_raw_fd(), c.as_ptr(), 0) } {+ 0 => Ok(()),+ _ => Err(io::Error::last_os_error()),+ }+ }++ /// This folder's entries (without `.` and `..`), each seen with `fstatat(…,+ /// AT_SYMLINK_NOFOLLOW)` from this descriptor. An entry gone by then is left out.+ pub fn list(&self) -> io::Result<Vec<Entry>> {+ // fdopendir takes the descriptor over: give it a copy+ let dup = self.fd.try_clone()?;+ // SAFETY: a valid descriptor whose ownership passes to the DIR stream+ let stream = unsafe { libc::fdopendir(std::os::fd::IntoRawFd::into_raw_fd(dup)) };+ if stream.is_null() {+ return Err(io::Error::last_os_error());+ }+ let mut names = Vec::new();+ loop {+ // SAFETY: `stream` is a valid open DIR until closedir below+ let ent = unsafe { libc::readdir(stream) };+ if ent.is_null() {+ break;+ }+ // SAFETY: readdir returned a valid entry whose name is NUL-terminated+ let name = unsafe { CStr::from_ptr((*ent).d_name.as_ptr()) }.to_bytes().to_vec();+ if name != b"." && name != b".." {+ names.push(OsString::from_vec(name));+ }+ }+ // SAFETY: closes the stream (and the copied descriptor) once+ unsafe { libc::closedir(stream) };+ let mut out = Vec::with_capacity(names.len());+ for name in names {+ let Ok(c) = cstr(&name) else { continue };+ let mut st = std::mem::MaybeUninit::<libc::stat>::zeroed();+ // SAFETY: valid descriptor, C string and out pointer+ let rc = unsafe { libc::fstatat(self.fd.as_raw_fd(), c.as_ptr(), st.as_mut_ptr(), libc::AT_SYMLINK_NOFOLLOW) };+ if rc != 0 {+ continue;+ }+ // SAFETY: fstatat succeeded and filled it+ let st = unsafe { st.assume_init() };+ #[allow(clippy::unnecessary_cast)] // u16 on macOS+ let mode = st.st_mode as u32;+ out.push(Entry { name, kind: mode_kind(mode), len: st.st_size.max(0) as u64, mode: mode & 0o7777 });+ }+ Ok(out)+ }+ }+}++#[cfg(not(unix))]+mod imp {+ use super::*;+ use std::path::PathBuf;++ /// Off unix: checks by path (isolation never runs here, so nobody races the reader).+ #[derive(Debug)]+ pub struct Dir {+ path: PathBuf,+ }++ fn real(p: &Path, dir: bool) -> io::Result<()> {+ // `open` resolves the root once; the parts below never follow+ let m = std::fs::symlink_metadata(p)?;+ let ok = if dir { m.is_dir() } else { m.is_file() };+ if ok {+ Ok(())+ } else {+ Err(not_a_file())+ }+ }++ impl Dir {+ pub fn open(root: &Path) -> io::Result<Self> {+ if !std::fs::metadata(root)?.is_dir() {+ return Err(not_a_file());+ }+ Ok(Self { path: root.to_path_buf() })+ }++ /// The folder's path: off unix a [`Dir`] is a checked path, and Windows-only checks+ /// (reparse points, device names) run on it ([`crate::server::gitfile`]).+ pub fn path(&self) -> &Path {+ &self.path+ }++ /// Off unix: every part checked by path (isolation never runs here).+ pub fn open_strict(path: &Path) -> io::Result<Self> {+ let mut p = PathBuf::new();+ for c in path.components() {+ p.push(c);+ if matches!(c, Component::Normal(_)) && std::fs::symlink_metadata(&p)?.file_type().is_symlink() {+ return Err(io::Error::new(io::ErrorKind::InvalidInput, "a symlink on the way"));+ }+ }+ Self::open(path)+ }++ pub fn open_dir(&self, rel: &Path) -> io::Result<Dir> {+ let mut p = self.path.clone();+ for c in parts(rel)? {+ p.push(c);+ real(&p, true)?;+ }+ Ok(Dir { path: p })+ }++ pub fn open_file(&self, rel: &Path) -> io::Result<File> {+ let ps = parts(rel)?;+ let Some((last, dirs)) = ps.split_last() else { return Err(not_a_file()) };+ let mut p = self.path.clone();+ for c in dirs {+ p.push(c);+ real(&p, true)?;+ }+ p.push(last);+ real(&p, false)?;+ File::open(&p)+ }++ pub fn make_dirs(&self, rel: &Path) -> io::Result<Dir> {+ let mut p = self.path.clone();+ for c in parts(rel)? {+ p.push(c);+ if std::fs::symlink_metadata(&p).is_err() {+ std::fs::create_dir(&p)?;+ }+ real(&p, true)?;+ }+ Ok(Dir { path: p })+ }++ pub fn replace_file(&self, name: &std::ffi::OsStr, tmp: &str, src: &mut impl io::Read, mode: u32) -> io::Result<()> {+ let _ = mode;+ let tmp = self.path.join(tmp);+ let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;+ let res = io::copy(src, &mut f).map(|_| ());+ drop(f);+ let res = res.and_then(|_| std::fs::rename(&tmp, self.path.join(name)));+ if res.is_err() {+ let _ = std::fs::remove_file(&tmp);+ }+ res+ }++ pub fn remove_file(&self, name: &std::ffi::OsStr) -> io::Result<()> {+ std::fs::remove_file(self.path.join(name))+ }++ pub fn list(&self) -> io::Result<Vec<Entry>> {+ let mut out = Vec::new();+ for e in std::fs::read_dir(&self.path)?.flatten() {+ let Ok(m) = std::fs::symlink_metadata(e.path()) else { continue };+ let ft = m.file_type();+ let kind = if ft.is_symlink() {+ Kind::Symlink+ } else if ft.is_dir() {+ Kind::Dir+ } else if ft.is_file() {+ Kind::File+ } else {+ Kind::Other+ };+ out.push(Entry { name: e.file_name(), kind, len: m.len(), mode: if m.permissions().readonly() { 0o444 } else { 0o644 } });+ }+ Ok(out)+ }+ }+}++pub use imp::Dir;++/// The error a capped reader gives for a file past its limit; see [`is_too_large`].+pub fn too_large() -> io::Error {+ io::Error::new(io::ErrorKind::InvalidData, "over the size limit")+}++/// Whether `e` is [`read_capped`]'s or [`copy_capped`]'s "over the size limit".+pub fn is_too_large(e: &io::Error) -> bool {+ e.kind() == io::ErrorKind::InvalidData && e.to_string() == "over the size limit"+}++/// Opens `real`, a path a caller already resolved and checked to lie under the resolved `root`,+/// by walking from `root`'s descriptor instead of opening it by path again (test plan S-8): if any+/// part became a symlink, a FIFO or anything but a regular file since the check, the open fails+/// instead of reading what it points at.+pub fn open_checked(root: &Path, real: &Path) -> io::Result<File> {+ let rel = real.strip_prefix(root).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "not under the folder"))?;+ Dir::open(root)?.open_file(rel)+}++/// All of `r`, refused once it passes `cap` bytes: a size seen before the open is never trusted,+/// since the file can grow after it.+pub fn read_capped(r: impl io::Read, cap: u64) -> io::Result<Vec<u8>> {+ let mut out = Vec::new();+ io::Read::read_to_end(&mut r.take(cap.saturating_add(1)), &mut out)?;+ if out.len() as u64 > cap {+ return Err(too_large());+ }+ Ok(out)+}++/// Copies `r` into `w` (a hasher, a file), refused once it passes `cap` bytes; the bytes copied.+pub fn copy_capped(r: impl io::Read, w: &mut impl io::Write, cap: u64) -> io::Result<u64> {+ let n = io::copy(&mut r.take(cap.saturating_add(1)), w)?;+ if n > cap {+ return Err(too_large());+ }+ Ok(n)+}++#[cfg(all(test, unix))]+mod tests {+ use super::*;+ use std::io::Read;+ use std::os::unix::fs::symlink;++ fn read(f: io::Result<File>) -> io::Result<String> {+ let mut s = String::new();+ f?.read_to_string(&mut s)?;+ Ok(s)+ }++ #[test]+ fn reads_real_files_and_refuses_every_symlink_on_the_way() {+ let t = tempfile::tempdir().unwrap();+ let (root, outside) = (t.path().join("root"), t.path().join("outside"));+ std::fs::create_dir_all(root.join("a/b")).unwrap();+ std::fs::create_dir_all(&outside).unwrap();+ std::fs::write(root.join("a/b/f.txt"), "inside").unwrap();+ std::fs::write(outside.join("secret"), "SECRET").unwrap();+ symlink(&outside, root.join("a/link_dir")).unwrap();+ symlink(outside.join("secret"), root.join("a/link_file")).unwrap();+ let d = Dir::open(&root).unwrap();+ assert_eq!(read(d.open_file(Path::new("a/b/f.txt"))).unwrap(), "inside");+ assert!(read(d.open_file(Path::new("a/link_file"))).is_err());+ assert!(read(d.open_file(Path::new("a/link_dir/secret"))).is_err());+ assert!(d.open_dir(Path::new("a/link_dir")).is_err());+ for bad in ["../outside/secret", "/etc/passwd", "a/../a/b/f.txt", ""] {+ assert!(d.open_file(Path::new(bad)).is_err(), "{bad}");+ }+ // The root is the person's path and is resolved once; only what's below it is never followed+ symlink(&root, t.path().join("root_link")).unwrap();+ assert_eq!(read(Dir::open(&t.path().join("root_link")).unwrap().open_file(Path::new("a/b/f.txt"))).unwrap(), "inside");+ let mut names: Vec<(String, Kind)> =+ d.open_dir(Path::new("a")).unwrap().list().unwrap().into_iter().map(|e| (e.name.to_string_lossy().into_owned(), e.kind)).collect();+ names.sort_by(|x, y| x.0.cmp(&y.0));+ assert_eq!(names, vec![("b".into(), Kind::Dir), ("link_dir".into(), Kind::Symlink), ("link_file".into(), Kind::Symlink)]);+ }++ #[test]+ fn writes_never_go_through_a_symlinked_folder() {+ let t = tempfile::tempdir().unwrap();+ let (root, outside) = (t.path().join("root"), t.path().join("outside"));+ std::fs::create_dir_all(&root).unwrap();+ std::fs::create_dir_all(&outside).unwrap();+ let d = Dir::open(&root).unwrap();+ let sub = d.make_dirs(Path::new("a/b")).unwrap();+ sub.replace_file("f".as_ref(), ".tmp-1", &mut "new".as_bytes(), 0o640).unwrap();+ assert_eq!(std::fs::read_to_string(root.join("a/b/f")).unwrap(), "new");+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(std::fs::metadata(root.join("a/b/f")).unwrap().permissions().mode() & 0o777, 0o640);+ // A symlinked folder on the way is refused for writing too+ symlink(&outside, root.join("a/evil")).unwrap();+ assert!(d.make_dirs(Path::new("a/evil/x")).is_err());+ // A symlink in the file's place is replaced, its target untouched+ std::fs::write(outside.join("target"), "keep").unwrap();+ symlink(outside.join("target"), root.join("a/b/g")).unwrap();+ sub.replace_file("g".as_ref(), ".tmp-2", &mut "mine".as_bytes(), 0o644).unwrap();+ assert_eq!(std::fs::read_to_string(outside.join("target")).unwrap(), "keep");+ assert!(std::fs::symlink_metadata(root.join("a/b/g")).unwrap().is_file());+ // Swapped after the folder was opened: the write lands in the real (moved) folder+ std::fs::rename(root.join("a/b"), root.join("a/b.moved")).unwrap();+ symlink(&outside, root.join("a/b")).unwrap();+ sub.replace_file("h".as_ref(), ".tmp-3", &mut "x".as_bytes(), 0o644).unwrap();+ assert!(!outside.join("h").exists() && root.join("a/b.moved/h").exists());+ assert!(sub.replace_file("../h".as_ref(), ".tmp-4", &mut "x".as_bytes(), 0o644).is_err());+ sub.remove_file("h".as_ref()).unwrap();+ assert!(d.open_dir(Path::new("a/b")).is_err());+ }++ #[test]+ fn a_fifo_is_refused_without_blocking() {+ let t = tempfile::tempdir().unwrap();+ let c = std::ffi::CString::new(t.path().join("pipe").to_string_lossy().as_bytes()).unwrap();+ // SAFETY: a valid C string+ assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o600) }, 0);+ let d = Dir::open(t.path()).unwrap();+ assert!(d.open_file(Path::new("pipe")).is_err());+ }++ /// S-8: the folder is swapped for a symlink between calls. A held folder keeps reading the+ /// folder it opened (now moved aside), never the symlink's target; a fresh walk refuses it.+ #[test]+ fn a_folder_swapped_for_a_symlink_between_calls_never_reaches_outside() {+ let t = tempfile::tempdir().unwrap();+ let (root, outside) = (t.path().join("root"), t.path().join("outside"));+ std::fs::create_dir_all(root.join("sub")).unwrap();+ std::fs::create_dir_all(&outside).unwrap();+ std::fs::write(root.join("sub/notes.txt"), "mine").unwrap();+ std::fs::write(outside.join("notes.txt"), "SECRET").unwrap();+ let d = Dir::open(&root).unwrap();+ let sub = d.open_dir(Path::new("sub")).unwrap();+ // The bot swaps `sub` for a symlink to a folder outside+ std::fs::rename(root.join("sub"), root.join("sub.moved")).unwrap();+ symlink(&outside, root.join("sub")).unwrap();+ assert!(read(d.open_file(Path::new("sub/notes.txt"))).is_err(), "a fresh walk refuses the symlink");+ assert_eq!(read(sub.open_file(Path::new("notes.txt"))).unwrap(), "mine", "the held folder is still the real one");+ assert!(sub.list().unwrap().iter().all(|e| e.name != "SECRET"));+ // And the same for the file itself+ std::fs::remove_file(root.join("sub")).unwrap();+ std::fs::create_dir(root.join("sub")).unwrap();+ symlink(outside.join("notes.txt"), root.join("sub/notes.txt")).unwrap();+ assert!(read(d.open_file(Path::new("sub/notes.txt"))).is_err());+ }++ /// The race itself, many times: another thread keeps swapping a folder and a symlink while+ /// this one reads through it. Every read is the real file or an error, never the target.+ #[test]+ fn a_reader_racing_a_swapper_never_reads_the_target() {+ let t = tempfile::tempdir().unwrap();+ let (root, outside) = (t.path().join("root"), t.path().join("outside"));+ std::fs::create_dir_all(root.join("real")).unwrap();+ std::fs::create_dir_all(&outside).unwrap();+ std::fs::write(root.join("real/f"), "mine").unwrap();+ std::fs::write(outside.join("f"), "SECRET").unwrap();+ symlink(&outside, root.join("evil")).unwrap();+ symlink(root.join("real"), root.join("evil_inside")).unwrap();+ std::fs::rename(root.join("real"), root.join("x")).unwrap();+ let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let swapper = {+ let (root, stop) = (root.clone(), stop.clone());+ std::thread::spawn(move || {+ // `x` is the real folder or the symlink to outside, swapped with rename(2)+ let mut real = true;+ while !stop.load(std::sync::atomic::Ordering::Relaxed) {+ let (from, to) = if real { ("x", "real_parked") } else { ("real_parked", "x") };+ let _ = std::fs::rename(root.join(from), root.join(to));+ if real {+ let _ = std::fs::rename(root.join("evil"), root.join("x"));+ } else {+ let _ = std::fs::rename(root.join("x"), root.join("evil"));+ let _ = std::fs::rename(root.join("real_parked"), root.join("x"));+ }+ real = !real;+ }+ })+ };+ let d = Dir::open(&root).unwrap();+ let mut ok = 0;+ for _ in 0..5000 {+ if let Ok(s) = read(d.open_file(Path::new("x/f"))) {+ assert_eq!(s, "mine");+ ok += 1;+ }+ }+ stop.store(true, std::sync::atomic::Ordering::Relaxed);+ swapper.join().unwrap();+ // Not a requirement, just that the race really ran both ways+ eprintln!("{ok} of 5000 reads saw the real folder");+ }++ #[test]+ fn a_strict_open_refuses_a_symlink_on_any_part_of_the_path() {+ let t = tempfile::tempdir().unwrap();+ // A tempdir's own path may go through root's symlinks (macOS's /var): those are followed+ let base = Dir::open_strict(t.path()).map(|_| t.path().to_path_buf()).unwrap();+ std::fs::create_dir_all(base.join("bot/proj")).unwrap();+ std::fs::create_dir_all(base.join("outside")).unwrap();+ assert!(Dir::open_strict(&base.join("bot/proj")).is_ok());+ symlink(base.join("outside"), base.join("bot/link")).unwrap();+ symlink(base.join("bot"), base.join("botlink")).unwrap();+ for p in ["bot/link", "botlink/proj", "botlink"] {+ let e = Dir::open_strict(&base.join(p)).unwrap_err();+ assert!(matches!(e.raw_os_error(), Some(libc::ELOOP) | Some(libc::ENOTDIR)), "{p}: {e}");+ }+ assert_eq!(Dir::open_strict(Path::new("bot/proj")).unwrap_err().kind(), io::ErrorKind::InvalidInput);+ // A symlink root owns (usr-merged /bin on Linux, /var on macOS) is followed+ for sys in ["/bin", "/var", "/tmp"] {+ if let Ok(m) = std::fs::symlink_metadata(sys) {+ if m.file_type().is_symlink() && std::os::unix::fs::MetadataExt::uid(&m) == 0 {+ assert!(Dir::open_strict(Path::new(sys)).is_ok(), "{sys}");+ }+ }+ }+ }+}diff --git a/src/serve.rs b/src/serve.rsindex 088b40c7..5ad650b6 100644--- a/src/serve.rs+++ b/src/serve.rs@@ -72,6 +72,10 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(// browser containers left by this or another kwant: remove orphans, stop idle oneslet browser = state.browser_service.clone();browser.clone().spawn_reaper(cancel.clone());+ // Claude's VM containers: remove ones a previous run left, then idle ones (Linux only)+ if crate::sandbox::agent_vm::supported_os().is_ok() {+ state.agent_vm.start_reaper();+ }let api_token = state.api_token.clone();let app = create_router(state);diff --git a/src/server/attachments.rs b/src/server/attachments.rsindex bdeab261..0bd4610d 100644--- a/src/server/attachments.rs+++ b/src/server/attachments.rs@@ -353,8 +353,10 @@ fn hex(bytes: &[u8]) -> String {}/// Stores a file from disk (an agent's `share_file`).-async fn store_file(root: &FsPath, path: &FsPath, name: &str) -> Result<Stored, StoreError> {- let mut file = tokio::fs::File::open(path).await.map_err(|_| StoreError::Io)?;+/// Stores an already opened file: never reopened by path (S-8). The sink's caps count the bytes+/// actually read, so a file that grows after it was opened is still refused.+async fn store_file(root: &FsPath, file: std::fs::File, name: &str) -> Result<Stored, StoreError> {+ let mut file = tokio::fs::File::from_std(file);let mut sink = Sink::new(root, name).await?;let mut buf = vec![0u8; 64 * 1024];loop {@@ -832,11 +834,11 @@ pub async fn tool_share(state: &AppState, scope: &SelfScope, args: &Value) -> (Slet Some(ws) = &scope.workspace else {return ("This chat has no workspace; share text with `content` instead.".into(), true);};- let Some(real) = inside_workspace(ws, p) else {+ let Some((file, real)) = inside_workspace(ws, p) else {return ("That path isn't a file inside your workspace.".into(), true);};let name = clean_name(raw_name.unwrap_or_else(|| real.file_name().and_then(|n| n.to_str()).unwrap_or("file")));- (store_file(&root, &real, &name).await, name)+ (store_file(&root, file, &name).await, name)}(None, Some(text)) => {if text.len() > MAX_SHARED_TEXT_BYTES {@@ -906,14 +908,20 @@ pub async fn tool_share(state: &AppState, scope: &SelfScope, args: &Value) -> (S(format!("Shared {name} with the user as a download (id {}).", a.id), false)}-/// `p` (relative to the workspace, or absolute) resolved with symlinks; `None` unless it is a-/// regular file inside the workspace.-pub fn inside_workspace(workspace: &FsPath, p: &str) -> Option<PathBuf> {+/// `p` (relative to the workspace, or absolute) opened, with its resolved path for the name;+/// `None` unless it is a regular file inside the workspace. The open walks from the workspace's+/// descriptor (S-8): in vm mode the bot can swap the file for a symlink to a host file, or a FIFO,+/// after the check by path, and then the open fails instead of sharing that file or hanging.+pub fn inside_workspace(workspace: &FsPath, p: &str) -> Option<(std::fs::File, PathBuf)> {let ws = workspace.canonicalize().ok()?;let given = FsPath::new(p);let full = if given.is_absolute() { given.to_path_buf() } else { ws.join(given) };let real = full.canonicalize().ok()?;- (real.starts_with(&ws) && real.is_file()).then_some(real)+ if !real.starts_with(&ws) {+ return None;+ }+ let file = crate::sandbox::safe_fs::open_checked(&ws, &real).ok()?;+ Some((file, real))}#[cfg(test)]diff --git a/src/server/computer.rs b/src/server/computer.rsindex 4802bc81..b2d25ceb 100644--- a/src/server/computer.rs+++ b/src/server/computer.rs@@ -4,6 +4,7 @@ use super::AppState;use crate::broker::{ApprovalDecision, ApprovalRequest};use crate::db::models::NewApproval;use crate::drivers::events::RuntimeEvent;+use crate::sandbox::agent_vm;use crate::sandbox::computer::{self, ComputerMode};use axum::{extract::State, http::StatusCode, Json};use serde::Deserialize;@@ -50,6 +51,17 @@ async fn view(state: &AppState) -> Value {crate::doctor::Platform::detect(),);let window = computer::window_reason();+ let isolate_claude = isolate_claude_setting(state).await;+ let (claude_cli, _) = crate::drivers::engines::EngineId::of_family(crate::profiles::Engine::Claude);+ let (toggle, agents) = state+ .agent_vm+ .view(agent_vm::ViewInputs {+ setting_on: isolate_claude,+ vm_mode: mode == ComputerMode::Vm,+ docker,+ cli_account: state.engines.is_enabled(claude_cli),+ })+ .await;json!({"mode": mode,"available": {"local": local.is_none(), "vm": vm.is_none()},@@ -63,9 +75,19 @@ async fn view(state: &AppState) -> Value {// The private browser kwnt downloads when there's no Chrome (O5). The UI shows its// `error` line, with "Try again", only while `state` is "failed"."browser_setup": state.browser_service.chrome_setup().view(),+ // Run Claude inside the VM (design/ui.md): the saved switch, whether it can be turned+ // on now, and where each engine runs right now+ "isolate_claude": isolate_claude,+ "isolate_claude_toggle": toggle,+ "agents": agents,})}+/// The person's "Run Claude inside the VM" switch (off unless they turned it on).+pub async fn isolate_claude_setting(state: &AppState) -> bool {+ state.db.get_setting(agent_vm::SETTING_KEY).await.ok().flatten().is_some_and(|v| v == "true")+}+/// `POST /api/settings/computer/browser`: "Try again" for the bots' private browser. Starts the/// download again in the background and answers at once with the view (`browser_setup.state` is/// then `downloading`, or `ready` if a browser is already there).@@ -89,18 +111,43 @@ pub async fn get_computer(State(state): State<AppState>) -> Json<Value> {#[derive(Deserialize)]pub struct ComputerPayload {- pub mode: ComputerMode,+ pub mode: Option<ComputerMode>,+ pub isolate_claude: Option<bool>,}-/// `PUT /api/settings/computer` with `{"mode":"local"|"vm"}`: saves the choice and switches at-/// once. 400 for an unknown mode or one this computer cannot run (with the reason).+/// `PUT /api/settings/computer` with `{"mode":"local"|"vm"}` and/or `{"isolate_claude":bool}`:+/// saves the choice and switches at once. 400 for an unknown mode or one this computer cannot run+/// (with the reason), and for turning isolation on where the switch is unavailable (its `reason`).+/// Turning it off always works. Turning it on starts Claude's VM download in the background.pub async fn put_computer(State(state): State<AppState>,payload: Result<Json<ComputerPayload>, axum::extract::rejection::JsonRejection>,) -> Result<Json<Value>, (StatusCode, Json<Value>)> {let bad = |m: String| (StatusCode::BAD_REQUEST, Json(json!({ "error": m })));- let Json(ComputerPayload { mode }) =- payload.map_err(|_| bad("mode must be \"local\" or \"vm\"".into()))?;+ let failed = |e: crate::db::DbError| (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() })));+ let Json(ComputerPayload { mode, isolate_claude }) = payload+ .map_err(|_| bad("Send mode (\"local\" or \"vm\") and/or isolate_claude (true or false)".into()))?;+ if mode.is_none() && isolate_claude.is_none() {+ return Err(bad("Send mode (\"local\" or \"vm\") and/or isolate_claude (true or false)".into()));+ }+ if let Some(on) = isolate_claude {+ if on {+ let current = view(&state).await;+ if current["isolate_claude_toggle"]["available"] != json!(true) {+ // People's words in `error` (the Settings error line prints it); the code apart+ let reason = current["isolate_claude_toggle"]["reason"].as_str().unwrap_or("unavailable").to_string();+ let error = agent_vm::toggle_message(&reason);+ return Err((StatusCode::BAD_REQUEST, Json(json!({ "error": error, "code": reason }))));+ }+ }+ state.db.set_setting(agent_vm::SETTING_KEY, if on { "true" } else { "false" }).await.map_err(failed)?;+ if on {+ state.agent_vm.start_setup();+ }+ }+ let Some(mode) = mode else {+ return Ok(Json(view(&state).await));+ };let current = view(&state).await;if current["available"][mode.as_str()] != json!(true) {let reason = current["reasons"][mode.as_str()]diff --git a/src/server/dev/backup.rs b/src/server/dev/backup.rsindex b9182a6e..b6e65838 100644--- a/src/server/dev/backup.rs+++ b/src/server/dev/backup.rs@@ -97,11 +97,18 @@ async fn run_here(state: &AppState, space: &SpaceId, kwant_id: Option<&str>) ->};let cwd = folder(state, space, kwant_id);let started = SystemTime::now();- let out = crate::tools::shell::execute_shell(&cwd, &json!({"command": command, "timeout_secs": TIMEOUT_SECS})).await;+ // D4 (C9c): the backup command runs bash on this computer as kwnt; never in a folder an+ // isolated bot used. The refusal is recorded like a failed backup.+ let refused = state.db.host_command_refusal(&cwd).await;+ let out = match &refused {+ Some(_) => None,+ None => Some(crate::tools::shell::execute_shell(&cwd, &json!({"command": command, "timeout_secs": TIMEOUT_SECS})).await),+ };let taken_at = super::now();let (ok, path, bytes, error) = match out {- Ok(v) => judge(&v, &cwd, started),- Err(e) => (false, None, None, Some(e.to_string())),+ None => (false, None, None, refused),+ Some(Ok(v)) => judge(&v, &cwd, started),+ Some(Err(e)) => (false, None, None, Some(e.to_string())),};let row = DevBackupRow {id: format!("dvb_{}", uuid::Uuid::new_v4().simple()),diff --git a/src/server/dev/floor.rs b/src/server/dev/floor.rsindex 0e2efcae..2739d2c7 100644--- a/src/server/dev/floor.rs+++ b/src/server/dev/floor.rs@@ -9,11 +9,14 @@ use crate::mcp::prod_floor::{self, DevCtx, Floor};use crate::mcp::ToolApprovalRequest;use crate::server::gitfile::{self, plain_ref};use serde_json::{json, Value};+use crate::sandbox::safe_fs::Dir;+use std::ffi::OsString;use std::path::{Component, Path, PathBuf};/// The Dev mode context of a bot's space, or `None` when Dev mode is off there (no floor).-/// With Dev mode off in every space it reads nothing.-pub async fn ctx_for_kwant(db: &Database, kwant_id: &str, cwd: Option<&Path>) -> Option<(String, DevCtx)> {+/// With Dev mode off in every space it reads nothing. `at` is `(folder, cwd)`: the bot's folder+/// for the turn and the working folder of the call, which [`head_branch`] keeps inside it.+pub async fn ctx_for_kwant(db: &Database, kwant_id: &str, at: Option<(&Path, &Path)>) -> Option<(String, DevCtx)> {if !db.any_dev_mode_on() {return None;}@@ -38,7 +41,7 @@ pub async fn ctx_for_kwant(db: &Database, kwant_id: &str, cwd: Option<&Path>) ->protected: branches,deploy_hint,prod_connections,- head_branch: cwd.and_then(head_branch),+ head_branch: at.and_then(|(folder, cwd)| head_branch(folder, cwd)),migration: None,};Some((kwant.space_id, ctx))@@ -60,82 +63,140 @@ pub fn prod_names<'a>(marked: &[String], servers: impl Iterator<Item = (&'a str,.collect()}-/// The branch checked out in `cwd` (walking up to its `.git`), from `HEAD` alone: no git process.-/// `None` for a detached head or no repo.+/// The branch checked out in `cwd` (walking up to its `.git`, but never above `folder`), from+/// `HEAD` alone: no git process. `None` for a detached head, no repo, or anything doubtful (a bare+/// push then counts as one to a protected branch, so `None` asks).///-/// `cwd` can be a bot's folder, so its `.git` is untrusted: every file is read through-/// [`gitfile::read`] (no symlink, FIFO, hard link or big file, so this never blocks), a `.git`-/// that is a symlink is no repo, a worktree's `gitdir:` is followed only as [`worktree_head`]-/// allows, and the branch must be a plain ref.-pub fn head_branch(cwd: &Path) -> Option<String> {- let mut dir = Some(cwd);- for _ in 0..12 {- let d = dir?;- let head = match std::fs::symlink_metadata(d.join(".git")) {- Err(_) => {- dir = d.parent();+/// `folder` is the bot's folder for the turn, the host's own path; `cwd` and everything under+/// `folder` are untrusted. The rules (0.7.7, S-8):+/// - **Q3:** a `cwd` that isn't `folder` or below it (by its text: no `..`) is refused before+/// any `.git` is read, and no `.git` above `folder` is read.+/// - Every folder and file is reached by one openat walk from `folder` ([`Dir`]): no symlink is+/// followed anywhere below `folder` (a planted link makes this `None`), no FIFO blocks it, and+/// every file goes through [`gitfile::read`] (no hard link, no big file).+/// - **P1:** a `.git` folder counts as a repo only with `objects/` and `refs/` folders in it, as+/// git requires. Without them git uses the repo above, and so does this.+/// - A worktree's `.git` file is followed only as [`worktree_head`] allows (**A4**: never out of+/// `folder`), and the branch must be a plain ref.+pub fn head_branch(folder: &Path, cwd: &Path) -> Option<String> {+ let mut parts = rel_inside(folder, cwd)?;+ let root = Dir::open(folder).ok()?;+ loop {+ let d = root.open_dir(&joined(&parts)).ok()?;+ let head = match d.open_dir(Path::new(".git")) {+ Ok(git) => match repo_dirs(&git)? {+ true => gitfile::read(&git, "HEAD", gitfile::REF_MAX)?,+ false => {+ parts.pop()?;+ continue;+ }+ },+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {+ parts.pop()?;continue;}- Ok(m) if gitfile::plain_dir(&m) => gitfile::read(&d.join(".git"), "HEAD", gitfile::REF_MAX)?,- Ok(m) if gitfile::plain_file(&m) => worktree_head(d)?,- Ok(_) => return None,+ // A file (a worktree's pointer), or a symlink, FIFO or anything else: never followed+ Err(_) => worktree_head(&root, folder, &parts, &gitfile::read(&d, ".git", gitfile::REF_MAX)?)?,};let r = head.trim().strip_prefix("ref: ")?.trim();return r.strip_prefix("refs/heads/").filter(|_| plain_ref(r)).map(str::to_string);}- None}-/// `HEAD` of the worktree whose `.git` file is in `d`. The file must say-/// `gitdir: <repo>/.git/worktrees/<name>` (relative to `d` unless absolute). `.` and `..` are-/// resolved on the text by [`lexical`], so only a path that was checked is opened, and every-/// folder on it that `d`'s own path doesn't already name (always `.git`, `worktrees` and `<name>`)-/// must be a real folder, not a symlink. The kernel and git take `link/..` to the parent of the-/// link's *target*, not to the folder the text names, so a `..` that would climb over a symlink-/// (in the gitdir or in `d` itself) makes this `None` rather than read a different `HEAD` than-/// git would (F-3). A common sibling worktree still reads. Folder races between the checks and-/// the open remain, as in `discover::read_file`; the 0.7.8 openat walk closes them.-fn worktree_head(d: &Path) -> Option<String> {- let text = gitfile::read(d, ".git", gitfile::REF_MAX)?;- let gd = text.trim().strip_prefix("gitdir:")?.trim();- let here = lexical(d)?;- let target = lexical(&d.join(gd))?;- let parts: Vec<Component> = target.components().collect();- let [.., Component::Normal(g), Component::Normal(w), Component::Normal(_)] = parts[..] else {- return None;- };- if g.to_str() != Some(".git") || w.to_str() != Some("worktrees") {- return None;+/// P1: whether an open `.git` folder is a repo to git: `Some(true)` with real `objects/` and+/// `refs/` folders, `Some(false)` when either is missing (git then looks above), `None` when one+/// is there but not a real folder (a symlink git would follow: doubtful, so no answer).+fn repo_dirs(git: &Dir) -> Option<bool> {+ for sub in ["objects", "refs"] {+ match git.open_dir(Path::new(sub)) {+ Ok(_) => {}+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Some(false),+ Err(_) => return None,+ }}- let shared = parts.iter().zip(here.components()).take_while(|(a, b)| **a == *b).count().min(parts.len() - 3);- let mut at: PathBuf = parts[..shared].iter().collect();- for c in &parts[shared..] {- at.push(c);- if !gitfile::plain_dir(&std::fs::symlink_metadata(&at).ok()?) {- return None;+ Some(true)+}++/// `folder` canonicalized, to compare with typed paths and git's own `gitdir:` lines. On Windows+/// `canonicalize` adds a `\\?\` prefix that a plain `C:\...` or `C:/...` path (which git writes)+/// never starts with, so it is dropped again; on unix this is just `canonicalize`.+fn canonical_plain(folder: &Path) -> Option<PathBuf> {+ let c = folder.canonicalize().ok()?;+ #[cfg(windows)]+ {+ use std::path::Prefix;+ let mut parts = c.components();+ if let Some(Component::Prefix(pre)) = parts.next() {+ let plain = match pre.kind() {+ Prefix::VerbatimDisk(d) => Some(PathBuf::from(format!("{}:\\", d as char))),+ Prefix::VerbatimUNC(server, share) => Some(PathBuf::from(format!("\\\\{}\\{}\\", server.to_string_lossy(), share.to_string_lossy()))),+ _ => None,+ };+ if let Some(mut out) = plain {+ for part in parts.filter(|p| !matches!(p, Component::RootDir)) {+ out.push(part);+ }+ return Some(out);+ }}}- gitfile::read(&target, "HEAD", gitfile::REF_MAX)+ Some(c)+}++/// Q3: `cwd`'s parts below `folder`, when `cwd` names `folder` (as given, or with the person's+/// own symlinks resolved) or a folder below it with plain names only.+fn rel_inside(folder: &Path, cwd: &Path) -> Option<Vec<OsString>> {+ let canon = canonical_plain(folder);+ let rest = cwd.strip_prefix(folder).ok().or_else(|| cwd.strip_prefix(canon.as_deref()?).ok())?;+ rest.components()+ .filter(|c| !matches!(c, Component::CurDir))+ .map(|c| match c {+ Component::Normal(p) => Some(p.to_os_string()),+ _ => None,+ })+ .collect()+}++fn joined(parts: &[OsString]) -> PathBuf {+ parts.iter().collect()}-/// `p` with `.` dropped and each `..` taken off the text, but only where the kernel would land in-/// the same folder: `a/..` is `.` only when `a` is a real folder, not a symlink (`link/..` is the-/// link target's parent). A `..` after a symlink, or past the start, is `None`.-fn lexical(p: &Path) -> Option<PathBuf> {- let mut out = PathBuf::new();- for c in p.components() {+/// `HEAD` of the worktree whose `.git` file (holding `text`) is in `folder/<at>`. The file must+/// say `gitdir: <repo>/.git/worktrees/<name>`, relative to that folder or absolute.+///+/// **A4:** the gitdir must stay inside `folder`: an absolute one must start with `folder`, and+/// a relative one may not climb above it. It is resolved on the text, but a `..` only takes off+/// a part that opens as a real folder: the kernel and git take `link/..` to the parent of the+/// link's *target*, so a `..` over a symlink makes this `None` rather than read a different+/// `HEAD` than git would (F-3). The result is then opened by the same openat walk from `folder`,+/// so every part of it, `.git`, `worktrees` and `<name>` included, is a real folder.+fn worktree_head(root: &Dir, folder: &Path, at: &[OsString], text: &str) -> Option<String> {+ let gd = Path::new(text.trim().strip_prefix("gitdir:")?.trim());+ let (mut stack, rest): (Vec<OsString>, &Path) = if gd.is_absolute() {+ let canon = canonical_plain(folder);+ (Vec::new(), gd.strip_prefix(folder).ok().or_else(|| gd.strip_prefix(canon.as_deref()?).ok())?)+ } else {+ (at.to_vec(), gd)+ };+ for c in rest.components() {match c {Component::CurDir => {}Component::ParentDir => {- let real_dir = !out.as_os_str().is_empty() && std::fs::symlink_metadata(&out).is_ok_and(|m| gitfile::plain_dir(&m));- if !real_dir || !out.pop() {+ // Above `folder` (A4), or over a part that isn't a real folder (F-3)+ if stack.is_empty() || root.open_dir(&joined(&stack)).is_err() {return None;}+ stack.pop();}- c => out.push(c),+ Component::Normal(p) => stack.push(p.to_os_string()),+ _ => return None,}}- Some(out)+ let [.., g, w, _] = &stack[..] else { return None };+ if g != ".git" || w != "worktrees" {+ return None;+ }+ gitfile::read(&root.open_dir(&joined(&stack)).ok()?, "HEAD", gitfile::REF_MAX)}/// The card's `prod_floor` object: `{kind, why, blast, needs_backup, space_id, backup}`.@@ -148,8 +209,10 @@ pub async fn payload(db: &Database, space_id: &str, floor: &Floor, ctx: &DevCtx)/// The floor for a tool call (an MCP tool, or one of claude's own), with its payload.pub async fn for_call(db: &Database, req: &ToolApprovalRequest) -> Option<(Floor, Value)> {+ // The call's folder is the turn's own folder, set by the host (`PermissionSession::cwd`),+ // never one the bot names, so it is the bot folder toolet cwd = req.builtin.as_ref().and_then(|b| b.cwd.as_deref()).map(Path::new);- let (space_id, ctx) = ctx_for_kwant(db, &req.kwant_id, cwd).await?;+ let (space_id, ctx) = ctx_for_kwant(db, &req.kwant_id, cwd.map(|c| (c, c))).await?;let floor = prod_floor::reason(req, &ctx)?;let p = payload(db, &space_id, &floor, &ctx).await;Some((floor, p))@@ -157,7 +220,8 @@ pub async fn for_call(db: &Database, req: &ToolApprovalRequest) -> Option<(Floor/// The floor for a command kwant's own shell runs for a bot (`execute_shell`).pub async fn for_shell(db: &Database, kwant_id: &str, command: &str, cwd: &Path) -> Option<(Floor, Value)> {- let (space_id, ctx) = ctx_for_kwant(db, kwant_id, Some(cwd)).await?;+ // kwant's shell runs in the bot's own folder (`execute_tool` picks it), so it is both+ let (space_id, ctx) = ctx_for_kwant(db, kwant_id, Some((cwd, cwd))).await?;let floor = prod_floor::shell_reason(command, &ctx)?;let p = payload(db, &space_id, &floor, &ctx).await;Some((floor, p))@@ -198,28 +262,36 @@ mod tests {#[test]fn the_checked_out_branch_is_read_from_head() {let root = std::env::temp_dir().join(format!("kwnt-dev-head-{}", uuid::Uuid::new_v4().simple()));- std::fs::create_dir_all(root.join(".git")).unwrap();+ std::fs::create_dir_all(root.join(".git/objects")).unwrap();+ std::fs::create_dir_all(root.join(".git/refs")).unwrap();std::fs::create_dir_all(root.join("src/deep")).unwrap();std::fs::write(root.join(".git/HEAD"), "ref: refs/heads/lin-dev-core\n").unwrap();- assert_eq!(head_branch(&root.join("src/deep")).as_deref(), Some("lin-dev-core"));+ assert_eq!(in_tmp(&root.join("src/deep")).as_deref(), Some("lin-dev-core"));std::fs::write(root.join(".git/HEAD"), "3ca2bf7aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n").unwrap();- assert_eq!(head_branch(&root), None, "a detached head can't be told");+ assert_eq!(in_tmp(&root), None, "a detached head can't be told");// A worktree's `.git` filelet wt = root.join("wt");std::fs::create_dir_all(root.join(".git/worktrees/wt")).unwrap();std::fs::create_dir_all(&wt).unwrap();std::fs::write(wt.join(".git"), format!("gitdir: {}\n", root.join(".git/worktrees/wt").display())).unwrap();std::fs::write(root.join(".git/worktrees/wt/HEAD"), "ref: refs/heads/release/0.7\n").unwrap();- assert_eq!(head_branch(&wt).as_deref(), Some("release/0.7"));+ assert_eq!(in_tmp(&wt).as_deref(), Some("release/0.7"));std::fs::remove_dir_all(&root).unwrap();- assert_eq!(head_branch(Path::new("/nonexistent/kwnt-dev")), None);+ assert_eq!(in_tmp(Path::new("/nonexistent/kwnt-dev")), None);+ }++ /// [`head_branch`] with the whole temp folder as the bot folder, so these cases only test the+ /// walk inside it (Q3 and A4 have their own tests below).+ fn in_tmp(cwd: &Path) -> Option<String> {+ head_branch(&std::env::temp_dir(), cwd)}/// A repo with `.git/HEAD` on `lin-dev-core` in a temp folder.fn head_repo() -> (tempfile::TempDir, PathBuf) {let d = tempfile::tempdir().unwrap();let root = d.path().join("repo");- std::fs::create_dir_all(root.join(".git")).unwrap();+ std::fs::create_dir_all(root.join(".git/objects")).unwrap();+ std::fs::create_dir_all(root.join(".git/refs")).unwrap();std::fs::write(root.join(".git/HEAD"), "ref: refs/heads/lin-dev-core\n").unwrap();(d, root)}@@ -228,7 +300,7 @@ mod tests {fn head_within_5s(cwd: &Path) -> Option<String> {let (tx, rx) = std::sync::mpsc::channel();let cwd = cwd.to_path_buf();- std::thread::spawn(move || tx.send(head_branch(&cwd)).unwrap());+ std::thread::spawn(move || tx.send(in_tmp(&cwd)).unwrap());rx.recv_timeout(std::time::Duration::from_secs(5)).expect("head_branch blocked")}@@ -319,18 +391,18 @@ mod tests {std::fs::write(&host, "ref: refs/heads/LEAKED-FROM-OUTSIDE\n").unwrap();std::fs::remove_file(root.join(".git/HEAD")).unwrap();symlink(&host, root.join(".git/HEAD")).unwrap();- assert_eq!(head_branch(&root), None, "HEAD symlink");+ assert_eq!(in_tmp(&root), None, "HEAD symlink");// `.git` as a symlink to another repo, or to a `gitdir:` filelet (_d2, other) = head_repo();let linked = d.path().join("linked");std::fs::create_dir_all(&linked).unwrap();symlink(other.join(".git"), linked.join(".git")).unwrap();- assert_eq!(head_branch(&linked), None, ".git symlink to a folder");- assert_eq!(head_branch(&linked.join("sub")), None, "and not from below it either");+ assert_eq!(in_tmp(&linked), None, ".git symlink to a folder");+ assert_eq!(in_tmp(&linked.join("sub")), None, "and not from below it either");std::fs::remove_file(linked.join(".git")).unwrap();std::fs::write(d.path().join("gitfile"), format!("gitdir: {}\n", other.join(".git").display())).unwrap();symlink(d.path().join("gitfile"), linked.join(".git")).unwrap();- assert_eq!(head_branch(&linked), None, ".git symlink to a file");+ assert_eq!(in_tmp(&linked), None, ".git symlink to a file");// A worktree whose gitdir goes through a planted folder linklet wt = d.path().join("wt");std::fs::create_dir_all(other.join(".git/worktrees/wt")).unwrap();@@ -338,7 +410,7 @@ mod tests {std::fs::create_dir_all(&wt).unwrap();symlink(other.parent().unwrap(), wt.join("hop")).unwrap();std::fs::write(wt.join(".git"), "gitdir: hop/repo/.git/worktrees/wt\n").unwrap();- assert_eq!(head_branch(&wt), None, "gitdir through a symlinked folder");+ assert_eq!(in_tmp(&wt), None, "gitdir through a symlinked folder");}/// F-3, M1: `link/..` in the gitdir is the link target's parent to the kernel and git, not@@ -360,11 +432,11 @@ mod tests {// What git and the kernel open: the physical copy, on `main`let kernel = std::fs::read_to_string(wt.join("link/../decoy/.git/worktrees/x/HEAD")).unwrap();assert_eq!(kernel, "ref: refs/heads/main\n");- assert_eq!(head_branch(&wt), None, "M1: must not read the text path's `feature`");+ assert_eq!(in_tmp(&wt), None, "M1: must not read the text path's `feature`");// `..` after a real folder still readsstd::fs::create_dir_all(wt.join("real")).unwrap();std::fs::write(wt.join(".git"), "gitdir: real/../decoy/.git/worktrees/x\n").unwrap();- assert_eq!(head_branch(&wt).as_deref(), Some("feature"));+ assert_eq!(in_tmp(&wt).as_deref(), Some("feature"));}/// F-3, M2: the start folder sits under a symlink, and the gitdir's leading `..` climb over it.@@ -386,7 +458,7 @@ mod tests {let start = p.join("lnk/wt");let kernel = std::fs::read_to_string(start.join("../../decoy2/.git/worktrees/x/HEAD")).unwrap();assert_eq!(kernel, "ref: refs/heads/main\n");- assert_eq!(head_branch(&start), None, "M2: must not read the text path's `feature`");+ assert_eq!(in_tmp(&start), None, "M2: must not read the text path's `feature`");}#[test]@@ -404,15 +476,15 @@ mod tests {std::fs::create_dir_all(root.join(".git/worktrees/x")).unwrap();std::fs::write(root.join(".git/worktrees/x/HEAD"), "ref: refs/heads/x\n").unwrap();std::fs::write(wt.join(".git"), &bad).unwrap();- assert_eq!(head_branch(&wt), None, "{bad}");+ assert_eq!(in_tmp(&wt), None, "{bad}");}// A relative gitdir (what `worktree.useRelativePaths` writes) readsstd::fs::write(wt.join(".git"), "gitdir: ../repo/.git/worktrees/x\n").unwrap();- assert_eq!(head_branch(&wt).as_deref(), Some("x"));+ assert_eq!(in_tmp(&wt).as_deref(), Some("x"));// The branch must be a plain reffor head in ["ref: refs/heads/../../x", "ref: refs/heads/a b", "ref: refs/tags/v1", "ref: refs/heads/"] {std::fs::write(root.join(".git/HEAD"), head).unwrap();- assert_eq!(head_branch(&root), None, "{head}");+ assert_eq!(in_tmp(&root), None, "{head}");}}@@ -436,10 +508,75 @@ mod tests {git(&main, &["commit", "-q", "--allow-empty", "-m", "x"]);let wt = d.path().join("main-wt");git(&main, &["worktree", "add", "-q", "-b", "juno/side-1", wt.to_str().unwrap()]);- assert_eq!(head_branch(&main).as_deref(), Some("main"));- assert_eq!(head_branch(&wt).as_deref(), Some("juno/side-1"));+ assert_eq!(in_tmp(&main).as_deref(), Some("main"));+ assert_eq!(in_tmp(&wt).as_deref(), Some("juno/side-1"));std::fs::create_dir_all(wt.join("src")).unwrap();- assert_eq!(head_branch(&wt.join("src")).as_deref(), Some("juno/side-1"));+ assert_eq!(in_tmp(&wt.join("src")).as_deref(), Some("juno/side-1"));+ }++ /// P1: a `.git` folder without `objects/` and `refs/` isn't a repo to git, which uses the repo+ /// above it. A planted `sub/.git/HEAD` must not hide the real branch (old code: "decoy").+ #[test]+ fn head_branch_needs_objects_and_refs_like_git() {+ let (d, root) = head_repo();+ std::fs::create_dir_all(root.join("sub/.git")).unwrap();+ std::fs::write(root.join("sub/.git/HEAD"), "ref: refs/heads/decoy\n").unwrap();+ assert_eq!(head_branch(d.path(), &root.join("sub")).as_deref(), Some("lin-dev-core"), "HEAD only");+ std::fs::create_dir_all(root.join("sub/.git/objects")).unwrap();+ assert_eq!(head_branch(d.path(), &root.join("sub")).as_deref(), Some("lin-dev-core"), "no refs/");+ std::fs::create_dir_all(root.join("sub/.git/refs")).unwrap();+ assert_eq!(head_branch(d.path(), &root.join("sub")).as_deref(), Some("decoy"), "a real nested repo");+ // A symlinked `refs` git would follow: no answer rather than the wrong repo's+ #[cfg(unix)]+ {+ std::fs::remove_dir(root.join("sub/.git/refs")).unwrap();+ std::os::unix::fs::symlink(root.join(".git/refs"), root.join("sub/.git/refs")).unwrap();+ assert_eq!(head_branch(d.path(), &root.join("sub")), None);+ }+ }++ /// A4: a worktree's gitdir may not leave the bot folder, absolute (old code read the other+ /// repo's branch) or relative.+ #[test]+ fn head_branch_keeps_a_worktree_gitdir_in_the_bot_folder() {+ let (_o, other) = head_repo();+ std::fs::create_dir_all(other.join(".git/worktrees/x")).unwrap();+ std::fs::write(other.join(".git/worktrees/x/HEAD"), "ref: refs/heads/theirs\n").unwrap();+ let d = tempfile::tempdir().unwrap();+ let bot = d.path().join("bot");+ std::fs::create_dir_all(&bot).unwrap();+ std::fs::write(bot.join(".git"), format!("gitdir: {}\n", other.join(".git/worktrees/x").display())).unwrap();+ assert_eq!(head_branch(&bot, &bot), None, "absolute gitdir into another repo");+ let rel = format!("gitdir: ../../{}/.git/worktrees/x\n", other.strip_prefix(d.path().parent().unwrap()).unwrap().display());+ std::fs::write(bot.join(".git"), &rel).unwrap();+ assert_eq!(head_branch(&bot, &bot), None, "relative gitdir climbing out: {rel}");+ // The same gitdir reads once the bot folder holds both+ assert_eq!(head_branch(d.path().parent().unwrap(), &bot).as_deref(), Some("theirs"));+ // An absolute gitdir inside the bot folder reads+ std::fs::create_dir_all(bot.join("repo/.git/worktrees/w")).unwrap();+ std::fs::write(bot.join("repo/.git/worktrees/w/HEAD"), "ref: refs/heads/mine\n").unwrap();+ std::fs::create_dir_all(bot.join("wt")).unwrap();+ std::fs::write(bot.join("wt/.git"), format!("gitdir: {}\n", bot.join("repo/.git/worktrees/w").display())).unwrap();+ assert_eq!(head_branch(&bot, &bot.join("wt")).as_deref(), Some("mine"));+ }++ /// Q3: a working folder outside the bot folder is refused before any `.git` is read (old+ /// code read the other repo's branch), and so is one that climbs out with `..`.+ #[test]+ fn head_branch_refuses_a_working_folder_outside_the_bot_folder() {+ let (_o, other) = head_repo();+ let (_b, bot) = head_repo();+ assert_eq!(head_branch(&bot, &other), None, "another repo");+ assert_eq!(head_branch(&bot, &bot.join("..")), None, "`..` out of the folder");+ assert_eq!(head_branch(&bot, &bot.join("sub/../..")), None);+ assert_eq!(head_branch(&bot, Path::new("repo")), None, "a relative cwd");+ // And no `.git` above the bot folder: a bot folder inside a repo gets no answer+ std::fs::create_dir_all(bot.join("sub")).unwrap();+ assert_eq!(head_branch(&bot.join("sub"), &bot.join("sub")), None);+ // Inside, it reads+ assert_eq!(head_branch(&bot, &bot).as_deref(), Some("lin-dev-core"));+ assert_eq!(head_branch(&bot, &bot.join("sub")).as_deref(), Some("lin-dev-core"));+ assert_eq!(head_branch(&bot, &bot.join("./sub")).as_deref(), Some("lin-dev-core"));}fn backup(space: &str, ok: bool, age_s: i64) -> crate::db::dev_mode::DevBackupRow {diff --git a/src/server/dev/git.rs b/src/server/dev/git.rsindex 16c7f734..dad41947 100644--- a/src/server/dev/git.rs+++ b/src/server/dev/git.rs@@ -173,8 +173,6 @@ const KEEP_ENV: &[&str] = &["GIT_SSH_COMMAND","GIT_SSH_VARIANT","GIT_CONFIG_GLOBAL",- "GIT_CONFIG_SYSTEM",- "GIT_CONFIG_NOSYSTEM","GIT_EXEC_PATH","GIT_SSL_CAINFO","GIT_SSL_CAPATH",@@ -299,8 +297,36 @@ fn with_dot_git(url: &str) -> Option<String> {(fetch_url(&next).as_deref() == Some(next.as_str()) && remote_host(&next) == remote_host(url)).then_some(next)}+/// The one way kwant starts git on this computer (agents in the VM, D4c; S-13). A folder a bot+/// wrote can hold a `.git/config` it planted, so every call gets, whatever that config says:+/// `GIT_CONFIG_NOSYSTEM=1`, `-c core.fsmonitor=false -c core.hooksPath=/dev/null -c+/// core.pager=cat`, no `GIT_*` from kwant's environment except the person's ssh and global-config+/// choices ([`KEEP_ENV`]), no prompt and no stdin. kwant only runs git's built-in commands, which+/// an alias can't replace, so no alias ever runs. A CI test checks that nothing else in `src/`+/// starts git.+pub fn host_git_command(bin: &str) -> tokio::process::Command {+ tokio::process::Command::from(host_git_command_blocking(bin))+}++/// [`host_git_command`] for code that can't await (Windows' `git_bash` lookup): the same flags,+/// environment and no stdin, as a blocking [`std::process::Command`]. `host_git_command` is built+/// from it, so the two can't drift apart.+pub fn host_git_command_blocking(bin: &str) -> std::process::Command {+ let mut cmd = std::process::Command::new(bin);+ cmd.args(["-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "core.pager=cat"]);+ for (k, _) in std::env::vars_os() {+ if let Some(k) = k.to_str() {+ if k.starts_with("GIT_") && !KEEP_ENV.contains(&k) {+ cmd.env_remove(k);+ }+ }+ }+ cmd.env("GIT_CONFIG_NOSYSTEM", "1").env("GIT_TERMINAL_PROMPT", "0").stdin(std::process::Stdio::null());+ cmd+}+async fn run_once(bin: &str, git_dir: Option<&Path>, args: &[&str], o: Opts<'_>, head: bool) -> Result<(Vec<u8>, bool), Ran> {- let mut cmd = tokio::process::Command::new(bin);+ let mut cmd = host_git_command(bin);if let Some(d) = git_dir {cmd.arg("--git-dir").arg(d);}@@ -327,13 +353,6 @@ async fn run_once(bin: &str, git_dir: Option<&Path>, args: &[&str], o: Opts<'_>,cmd.arg("-c").arg(c);}cmd.args(args);- for (k, _) in std::env::vars_os() {- if let Some(k) = k.to_str() {- if k.starts_with("GIT_") && !KEEP_ENV.contains(&k) {- cmd.env_remove(k);- }- }- }cmd.env_remove("SSH_ASKPASS");cmd.env("GIT_TERMINAL_PROMPT", "0").env("GIT_OPTIONAL_LOCKS", "0")@@ -1622,6 +1641,21 @@ mod tests {use super::*;use std::process::Command;+ /// D4c on Windows too: `git_bash` runs git through the blocking twin, which must give git+ /// exactly what the async helper does (same `-c` flags, same environment, no stdin).+ #[test]+ fn the_blocking_twin_matches_host_git_command() {+ let a = host_git_command("git");+ let a = a.as_std();+ let b = host_git_command_blocking("git");+ assert_eq!(a.get_program(), b.get_program());+ assert_eq!(a.get_args().collect::<Vec<_>>(), b.get_args().collect::<Vec<_>>());+ assert_eq!(a.get_envs().collect::<Vec<_>>(), b.get_envs().collect::<Vec<_>>());+ let args: Vec<_> = b.get_args().filter_map(|x| x.to_str()).collect();+ assert_eq!(args, ["-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "core.pager=cat"]);+ assert!(b.get_envs().any(|(k, v)| k == "GIT_CONFIG_NOSYSTEM" && v.is_some_and(|v| v == "1")));+ }+/// Writes an executable script at `path` that is safe to run while other tests start/// processes (D-2). Writing it here would hold a write fd on it in this process, and a/// thread that forks at that moment hands the fd to its child until that child execs; running@@ -1972,7 +2006,9 @@ mod tests {assert!(env.contains("GIT_CONFIG_KEY_0=http.https://github.com/.extraheader\n"));assert!(env.contains(&format!("GIT_CONFIG_VALUE_0=Authorization: Basic {token}\n")));assert!(env.contains("GIT_TERMINAL_PROMPT=0\n"));- let ours = ["GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0", "GIT_TERMINAL_PROMPT", "GIT_OPTIONAL_LOCKS", "GIT_LITERAL_PATHSPECS", "GIT_NO_REPLACE_OBJECTS", "GCM_INTERACTIVE", "SSH_ASKPASS_REQUIRE"];+ assert!(env.contains("GIT_CONFIG_NOSYSTEM=1\n"), "D4c");+ assert!(argv.contains("core.pager=cat") && argv.contains("core.hooksPath=/dev/null") && argv.contains("core.fsmonitor=false"), "D4c");+ let ours = ["GIT_CONFIG_NOSYSTEM", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0", "GIT_TERMINAL_PROMPT", "GIT_OPTIONAL_LOCKS", "GIT_LITERAL_PATHSPECS", "GIT_NO_REPLACE_OBJECTS", "GCM_INTERACTIVE", "SSH_ASKPASS_REQUIRE"];for name in env.lines().filter_map(|l| l.split('=').next()) {assert!(ours.contains(&name) || KEEP_ENV.contains(&name), "only kwant's own or the person's ssh/config choices reach git: {name}");}diff --git a/src/server/dev/repo.rs b/src/server/dev/repo.rsindex e5a8c07b..289cb3ba 100644--- a/src/server/dev/repo.rs+++ b/src/server/dev/repo.rs@@ -360,12 +360,10 @@ const GIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);/// killed after [`GIT_TIMEOUT`]. Its trimmed stdout on success. Its stderr is dropped unread, so/// a URL in an error never reaches a log.async fn git(dir: &std::path::Path, args: &[&str]) -> Option<String> {- let mut cmd = tokio::process::Command::new("git");- cmd.arg("-C").arg(dir).args(["-c", "core.fsmonitor=false"]).args(args);- for v in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT"] {- cmd.env_remove(v);- }- cmd.env("GIT_TERMINAL_PROMPT", "0").env("GIT_OPTIONAL_LOCKS", "0");+ // The shared host git rules (D4c): no system config, hooks, fsmonitor or pager, no GIT_* env+ let mut cmd = git::host_git_command("git");+ cmd.arg("-C").arg(dir).args(args);+ cmd.env("GIT_OPTIONAL_LOCKS", "0");if let Some(parent) = dir.parent() {cmd.env("GIT_CEILING_DIRECTORIES", parent);}diff --git a/src/server/gitfile.rs b/src/server/gitfile.rsindex 6185d1e8..8d20cd63 100644--- a/src/server/gitfile.rs+++ b/src/server/gitfile.rs@@ -1,11 +1,16 @@//! Reading small files under a `.git` that a bot can write (missions' `git_head`, Dev mode's//! `head_branch`). Everything there is untrusted: never follow a symlink, never block on a FIFO,//! socket or device, never read a hard link (it may be a host file's other name), and cap sizes.-//! On Windows the same refusals hold for every reparse point (symlink, junction, mount point,-//! cloud placeholder), DOS device names (`CON`, `NUL`, `COM1`...) and alternate data streams; a-//! file that can't be checked that way is `None`, never read some weaker way.+//! On Mac and Linux every read walks from an open folder with `openat`+//! ([`crate::sandbox::safe_fs::Dir`], S-8), so a folder the bot swaps for a symlink between two+//! checks is never followed. On Windows the same refusals hold for every reparse point (symlink,+//! junction, mount point, cloud placeholder), DOS device names (`CON`, `NUL`, `COM1`...) and+//! alternate data streams; a file that can't be checked that way is `None`, never read some+//! weaker way.+use crate::sandbox::safe_fs::Dir;use std::io::Read;+#[cfg(unix)]use std::path::Path;/// HEAD, a loose ref or a `.git` file is tiny; a bigger one isn't git's.@@ -13,40 +18,11 @@ pub(crate) const REF_MAX: u64 = 4 * 1024;/// packed-refs can list many refs, but never this many for a bot's folder.pub(crate) const PACKED_MAX: u64 = 1024 * 1024;-/// Reads `<base>/<rel>` (`rel` is `/`-separated and already checked) only when every component-/// below `base` is a real folder and the last a regular file of at most `max` bytes with one-/// link. Never follows a symlink and never blocks on a FIFO, socket or device.-pub(crate) fn read(base: &Path, rel: &str, max: u64) -> Option<String> {- let mut at = base.to_path_buf();- let parts: Vec<&str> = rel.split('/').collect();- for (i, p) in parts.iter().enumerate() {- #[cfg(windows)]- if !windows_plain_name(p) {- return None;- }- at.push(p);- let m = std::fs::symlink_metadata(&at).ok()?;- let last = i + 1 == parts.len();- if (last && !plain_file(&m)) || (!last && !plain_dir(&m)) {- return None;- }- }- let mut o = std::fs::OpenOptions::new();- o.read(true);- #[cfg(unix)]- {- use std::os::unix::fs::OpenOptionsExt;- // A symlink swapped in after the check fails to open; a FIFO opens without waiting- o.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);- }- #[cfg(windows)]- {- use std::os::windows::fs::OpenOptionsExt;- // A symlink or junction swapped in after the check opens as itself, not its target, and- // the handle check below refuses it- o.custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT);- }- let f = o.open(&at).ok()?;+/// Reads `rel` (`/`-separated plain names) below the open folder `dir`: every component must be a+/// real folder and the last a regular file of at most `max` bytes with one link. A symlink is+/// never followed and a FIFO, socket or device never blocks it.+pub(crate) fn read(dir: &Dir, rel: &str, max: u64) -> Option<String> {+ let f = open(dir, rel)?;let m = f.metadata().ok()?;if !m.file_type().is_file() || m.len() > max {return None;@@ -71,14 +47,60 @@ pub(crate) fn read(base: &Path, rel: &str, max: u64) -> Option<String> {String::from_utf8(buf).ok()}+/// Mac and Linux: [`Dir::open_file`] walks with `O_NOFOLLOW|O_DIRECTORY` from `dir`'s descriptor+/// and opens the last part `O_NOFOLLOW|O_NONBLOCK`, so nothing is resolved twice.+#[cfg(unix)]+fn open(dir: &Dir, rel: &str) -> Option<std::fs::File> {+ dir.open_file(Path::new(rel)).ok()+}++/// Elsewhere (Windows) [`Dir`] is a checked path: `dir` itself and every part below it must be a+/// real folder (no reparse point of any kind) and the last a plain file, then it is opened as+/// itself, never as a link's target, and [`windows_one_plain_file`] checks the handle.+#[cfg(not(unix))]+fn open(dir: &Dir, rel: &str) -> Option<std::fs::File> {+ let mut at = dir.path().to_path_buf();+ if !plain_dir(&std::fs::symlink_metadata(&at).ok()?) {+ return None;+ }+ let parts: Vec<&str> = rel.split('/').collect();+ for (i, p) in parts.iter().enumerate() {+ #[cfg(windows)]+ if !windows_plain_name(p) {+ return None;+ }+ if p.is_empty() || *p == "." || *p == ".." {+ return None;+ }+ at.push(p);+ let m = std::fs::symlink_metadata(&at).ok()?;+ let last = i + 1 == parts.len();+ if (last && !plain_file(&m)) || (!last && !plain_dir(&m)) {+ return None;+ }+ }+ let mut o = std::fs::OpenOptions::new();+ o.read(true);+ #[cfg(windows)]+ {+ use std::os::windows::fs::OpenOptionsExt;+ // A symlink or junction swapped in after the check opens as itself, not its target, and+ // the handle check refuses it+ o.custom_flags(windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT);+ }+ o.open(&at).ok()+}+/// `m` (from `symlink_metadata`) is a real folder: not a symlink and, on Windows, no reparse point-/// of any kind. On Mac and Linux this is `is_dir()` of the unfollowed type, as before.-pub(crate) fn plain_dir(m: &std::fs::Metadata) -> bool {+/// of any kind. Mac and Linux need none of this: [`Dir`] walks with `O_NOFOLLOW`.+#[cfg(not(unix))]+fn plain_dir(m: &std::fs::Metadata) -> bool {m.file_type().is_dir() && !reparse_point(m)}/// `m` (from `symlink_metadata`) is a regular file, never a link or (on Windows) a reparse point.-pub(crate) fn plain_file(m: &std::fs::Metadata) -> bool {+#[cfg(not(unix))]+fn plain_file(m: &std::fs::Metadata) -> bool {m.file_type().is_file() && !reparse_point(m)}@@ -90,7 +112,7 @@ fn reparse_point(m: &std::fs::Metadata) -> bool {m.file_attributes() & windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT != 0}-#[cfg(not(windows))]+#[cfg(all(not(unix), not(windows)))]fn reparse_point(_: &std::fs::Metadata) -> bool {false}@@ -150,6 +172,10 @@ pub(crate) fn plain_ref(r: &str) -> bool {mod tests {use super::*;+ fn read(base: &Path, rel: &str, max: u64) -> Option<String> {+ super::read(&Dir::open(base).unwrap(), rel, max)+ }+#[test]fn reads_one_regular_file_and_nothing_else() {let d = tempfile::tempdir().unwrap();@@ -162,6 +188,26 @@ mod tests {assert_eq!(read(d.path(), "a/f", 10), None, "a file with two names");assert_eq!(read(d.path(), "g", 10), None);}++ #[test]+ fn never_follows_a_symlink_or_blocks_on_a_fifo() {+ use std::os::unix::fs::symlink;+ let d = tempfile::tempdir().unwrap();+ let out = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(out.path().join("a")).unwrap();+ std::fs::write(out.path().join("a/f"), "secret").unwrap();+ symlink(out.path().join("a"), d.path().join("a")).unwrap();+ assert_eq!(read(d.path(), "a/f", 10), None, "a symlinked folder on the way");+ symlink(out.path().join("a/f"), d.path().join("f")).unwrap();+ assert_eq!(read(d.path(), "f", 10), None, "a symlinked file");+ assert_eq!(read(d.path(), "../x", 10), None, "`..` is no plain name");+ let fifo = std::ffi::CString::new(d.path().join("p").as_os_str().as_encoded_bytes()).unwrap();+ assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o644) }, 0);+ let (tx, rx) = std::sync::mpsc::channel();+ let base = d.path().to_path_buf();+ std::thread::spawn(move || tx.send(read(&base, "p", 10)).unwrap());+ assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(5)).expect("blocked on a FIFO"), None);+ }}#[cfg(test)]@@ -184,6 +230,10 @@ pub(crate) mod windows_tests {use super::*;use std::path::Path;+ fn read(base: &Path, rel: &str, max: u64) -> Option<String> {+ super::read(&Dir::open(base).unwrap(), rel, max)+ }+/// A junction needs no privilege, unlike a symlink. cmd reads a `/` in/// a path as a switch, so both paths go over with backslashes only.pub(crate) fn junction(link: &Path, target: &Path) {diff --git a/src/server/goals_remediation.rs b/src/server/goals_remediation.rsindex bbaa073b..fec80a22 100644--- a/src/server/goals_remediation.rs+++ b/src/server/goals_remediation.rs@@ -279,15 +279,26 @@ pub async fn withdraw_for_delete(state: &AppState, goal_id: &str) {}}-/// Reads the Investigate report, if the bot wrote one inside the goal's folder.-async fn read_report(folder: &str, rel: &str) -> Option<String> {- let base = std::fs::canonicalize(folder).ok()?;- let file = std::fs::canonicalize(base.join(rel)).ok()?;- if !file.starts_with(&base) || !file.is_file() {- return None;- }- let bytes = std::fs::read(&file).ok()?;- let text = String::from_utf8_lossy(&bytes[..bytes.len().min(REPORT_READ_BYTES)]).to_string();+/// Reads the Investigate report, if the bot wrote one inside the goal's folder. Off the async+/// runtime, opened by walking from the folder's descriptor and read only up to+/// `REPORT_READ_BYTES` (S-8): a report swapped for a symlink to a host file, or a FIFO, after the+/// check is never read and never blocks.+pub(crate) async fn read_report(folder: &str, rel: &str) -> Option<String> {+ let (folder, rel) = (folder.to_string(), rel.to_string());+ let bytes = tokio::task::spawn_blocking(move || -> Option<Vec<u8>> {+ let base = std::fs::canonicalize(&folder).ok()?;+ let file = std::fs::canonicalize(base.join(&rel)).ok()?;+ if !file.starts_with(&base) {+ return None;+ }+ let f = crate::sandbox::safe_fs::open_checked(&base, &file).ok()?;+ let mut head = Vec::new();+ std::io::Read::read_to_end(&mut std::io::Read::take(f, REPORT_READ_BYTES as u64), &mut head).ok()?;+ Some(head)+ })+ .await+ .ok()??;+ let text = String::from_utf8_lossy(&bytes).to_string();let text = untrusted(text.trim(), REPORT_CHARS);(!text.is_empty()).then_some(text)}diff --git a/src/server/mcp_routes.rs b/src/server/mcp_routes.rsindex 137f36a0..06d8f956 100644--- a/src/server/mcp_routes.rs+++ b/src/server/mcp_routes.rs@@ -152,14 +152,32 @@ pub(super) async fn run_test(state: &AppState, stored: &McpServer) -> Value {let mut server = stored.clone();let token_use = mcp_oauth::authorize_server(state, &mut server).await;let mut secrets = server.secret_values();+ // The same D4 rule as a turn's (C8): from a folder an isolated bot used, a stdio server+ // starts from an empty one, or not at all when it runs a file from there+ let token = uuid::Uuid::new_v4().simple().to_string();+ let mut one = vec![server];+ let empty = super::mcp_runtime::isolate_stdio_servers(state, &mut one, Some(&cwd), &token).await;+ let Some(server) = one.pop() else {+ let outcome = json!({ "ok": false, "error": "Not started: it runs a file from a folder an isolated bot used, \+ or no empty folder could be made for it",+ "duration_ms": start.elapsed().as_millis() as u64 });+ super::connections::record_mcp_check(&stored.id, &outcome);+ return outcome;+ };let mut result = try_list(&server, &cwd).await;if token_use == TokenUse::Injected && matches!(result, Err((McpError::Unauthorized { .. }, _))) {// The token was rejected early (revoked, or the server's clock): refresh once- if let Some(retry) = mcp_oauth::retry_after_unauthorized(state, stored).await {+ if let Some(mut retry) = mcp_oauth::retry_after_unauthorized(state, stored).await {+ if let Some(dir) = &empty {+ mcp::start_in(&mut retry, dir);+ }secrets.extend(retry.secret_values());result = try_list(&retry, &cwd).await;}}+ if empty.is_some() {+ super::mcp_runtime::remove_mcp_cwd(state, &token).await;+ }let mut outcome = match result {Ok((server_info, tools)) => json!({ "ok": true, "server_info": server_info, "tools": tools }),diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex ad22f210..5ba3687f 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -5,7 +5,7 @@use super::AppState;use crate::broker::{ApprovalDecision, ApprovalRequest, PermissionBroker};-use crate::db::models::{Kwant, NewApproval};+use crate::db::models::{Kwant, McpServer, NewApproval};use crate::db::Database;use crate::drivers::events::RuntimeEvent;use crate::mcp::{@@ -22,7 +22,7 @@ use axum::{Json,};use serde_json::{json, Value};-use std::path::PathBuf;+use std::path::{Path as FsPath, PathBuf};use std::sync::Arc;use std::time::Duration;use tokio::sync::{broadcast, Mutex};@@ -503,7 +503,7 @@ Your earlier turn ended before they answered. Make this same call again now, wit}/// Address agent CLIs on this host use to reach kwnt.-fn local_base_url(state: &AppState) -> String {+pub(crate) fn local_base_url(state: &AppState) -> String {let host = match state.config.host.as_str() {"0.0.0.0" | "::" | "[::]" | "" | "localhost" => "127.0.0.1".to_string(),h if h.contains(':') && !h.starts_with('[') => format!("[{h}]"),@@ -610,12 +610,13 @@ pub async fn prepare_turn_with_opts(Vec::new()}};+ let token = uuid::Uuid::new_v4().simple().to_string();+ isolate_stdio_servers(state, &mut servers, cwd.as_deref(), &token).await;if servers.is_empty() && self_scope.is_none() {return None;}// Signed-in http servers get their (refreshed) access token as a secret headersuper::mcp_oauth::authorize_servers(state, &mut servers).await;- let token = uuid::Uuid::new_v4().simple().to_string();let browser = self_scope.as_ref().and_then(|s| s.sandbox_target.clone()).map(|t| (state.clone(), t));let self_tools = self_scope.is_some() && !servers.iter().any(|s| s.name.eq_ignore_ascii_case(mcp::SELF_SERVER_NAME));if self_tools {@@ -684,6 +685,71 @@ pub async fn finish_turn(state: &AppState, token: &str) {super::missions::truth_ledger::end_turn(&session.turn_id);session.close().await;}+ remove_mcp_cwd(state, token).await;+}++/// The empty folder stdio servers start from for the turn (or test) `token`, when its folder is+/// one an isolated bot used ([`isolate_stdio_servers`]).+pub fn mcp_cwd(data_dir: &FsPath, token: &str) -> PathBuf {+ data_dir.join("run").join("mcp-cwd").join(token)+}++/// D4 (C8): when `cwd` is equal to, inside or holding a folder an isolated bot used (or, with no+/// folder, kwnt's own working folder sits in one; see [`Database::isolated_folder_near`]), a stdio+/// server could run what the bot left there, on this computer. Then:+/// - a server that names a file in that folder (`./serve.js`, an absolute path into it) isn't+/// started ([`mcp::runs_folder_file`]);+/// - every other stdio server starts from a fresh, empty, kwnt-owned folder [`mcp_cwd`]+/// ([`mcp::start_in`]), so `python3 -m x` or `npx x` can't pick up a planted file. The caller+/// removes it ([`finish_turn`], [`remove_mcp_cwd`]).+///+/// When that folder can't be made, no stdio server starts. Returns the folder when one was made.+pub(crate) async fn isolate_stdio_servers(state: &AppState, servers: &mut Vec<McpServer>, cwd: Option<&FsPath>, token: &str) -> Option<PathBuf> {+ if !servers.iter().any(|s| s.transport == "stdio") {+ return None;+ }+ let near = state.db.isolated_folder_near(cwd).await?;+ let here = cwd.filter(|d| d.exists()).map(FsPath::to_path_buf).or_else(|| std::env::current_dir().ok());+ servers.retain(|s| {+ let runs = mcp::runs_folder_file(s, &near) || here.as_deref().is_some_and(|h| mcp::runs_folder_file(s, h));+ if runs {+ tracing::warn!(server = %s.name, "not starting an MCP server that runs a file from a folder an isolated bot used");+ }+ !runs+ });+ if !servers.iter().any(|s| s.transport == "stdio") {+ return None;+ }+ let dir = mcp_cwd(&state.config.data_dir, token);+ let private = || {+ #[cfg_attr(not(unix), allow(unused_mut))]+ let mut b = std::fs::DirBuilder::new();+ #[cfg(unix)]+ std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700);+ b+ };+ let parent = dir.parent().unwrap_or(&dir);+ // The turn's own folder isn't made recursively: it must be new, never one already there+ let made = private().recursive(true).create(parent).and_then(|()| private().create(&dir));+ if let Err(e) = made {+ tracing::warn!(error = %e, "couldn't make an empty folder for MCP servers; not starting the stdio ones");+ servers.retain(|s| s.transport != "stdio");+ return None;+ }+ for s in servers.iter_mut() {+ mcp::start_in(s, &dir);+ }+ Some(dir)+}++/// Removes [`mcp_cwd`] for `token`, if it was made.+pub(crate) async fn remove_mcp_cwd(state: &AppState, token: &str) {+ let dir = mcp_cwd(&state.config.data_dir, token);+ if let Err(e) = tokio::fs::remove_dir_all(&dir).await {+ if e.kind() != std::io::ErrorKind::NotFound {+ tracing::warn!(error = %e, dir = %dir.display(), "couldn't remove an MCP server folder");+ }+ }}fn rpc_result(id: Value, result: Value) -> Response {diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rsindex b6831f79..fceaf583 100644--- a/src/server/missions/checkpoints.rs+++ b/src/server/missions/checkpoints.rs@@ -144,38 +144,67 @@ fn through_symlink(folder: &FsPath, rel: &str) -> bool {}/// What the folder holds at `rel` now: `Ok(Some(sha))`, `Ok(None)` when absent, `Err(why)`.+/// Opened from the folder's descriptor, never through a symlink (S-8), the folder's own path+/// included (QA F-3).fn current(folder: &FsPath, rel: &str) -> Result<Option<String>, String> {if through_symlink(folder, rel) {return Err("symlink, not followed".into());}- let p = folder.join(rel);- let meta = match std::fs::symlink_metadata(&p) {- Ok(m) => m,+ let opened = crate::sandbox::safe_fs::Dir::open_strict(folder).and_then(|d| d.open_file(FsPath::new(rel)));+ let mut f = match opened {+ Ok(f) => f,Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ // A symlink that appeared since the check above+ Err(e) if symlink_refused(&e) => return Err("symlink, not followed".into()),+ Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => return Err("not a regular file".into()),Err(_) => return Err("can't be read".into()),};- if !meta.is_file() {- return Err("not a regular file".into());- }- let mut f = std::fs::File::open(&p).map_err(|_| "can't be read".to_string())?;+ // At most FILE_MAX_BYTES + 1 bytes, however large the file is or grows: a longer file's hash+ // (of that much) still never equals a stored copy's, which is at most FILE_MAX_BYTES longlet mut h = <sha2::Sha256 as sha2::Digest>::new();- std::io::copy(&mut f, &mut h).map_err(|_| "can't be read".to_string())?;+ std::io::copy(&mut (&mut f).take(FILE_MAX_BYTES + 1), &mut h).map_err(|_| "can't be read".to_string())?;Ok(Some(hex(&sha2::Digest::finalize(h))))}-/// Streams `src` into the blob store, returning its sha256.-fn store_blob(blobs: &FsPath, src: &FsPath) -> std::io::Result<String> {- let mut input = std::fs::File::open(src)?;+/// Whether opening failed because a symlink was met on the way. Mac and Linux: `O_NOFOLLOW` gives+/// `ELOOP` on the last part and `O_DIRECTORY` gives `ENOTDIR` on a folder swapped for a symlink.+#[cfg(unix)]+fn symlink_refused(e: &std::io::Error) -> bool {+ matches!(e.raw_os_error(), Some(libc::ELOOP) | Some(libc::ENOTDIR))+}++/// Off unix [`crate::sandbox::safe_fs::Dir`] checks by path and refuses a symlink or reparse+/// point as "not a regular file" (`InvalidInput`, the arm after this one) or "a symlink on the+/// way" for the folder itself, so there is no separate symlink error to tell apart here.+#[cfg(not(unix))]+fn symlink_refused(e: &std::io::Error) -> bool {+ e.kind() == std::io::ErrorKind::InvalidInput && e.to_string() == "a symlink on the way"+}++/// Streams `input` (already opened, never by path: S-8) into the blob store, returning its sha256+/// and how many bytes it really held. The listing's size is only a hint: the file can grow after+/// it, so at most `cap` bytes are read and a longer file is refused+/// ([`crate::sandbox::safe_fs::is_too_large`]), with nothing stored.+fn store_blob(blobs: &FsPath, input: std::fs::File, cap: u64) -> std::io::Result<(String, u64)> {+ if input.metadata()?.len() > cap {+ return Err(crate::sandbox::safe_fs::too_large());+ }let tmp = blobs.join(format!(".tmp-{}", new_id()));let mut out = std::fs::OpenOptions::new().write(true).create_new(true).unix_mode(0o600).open(&tmp)?;let mut h = <sha2::Sha256 as sha2::Digest>::new();let mut buf = vec![0u8; 64 * 1024];+ let mut input = input.take(cap + 1);+ let mut total: u64 = 0;let res = (|| -> std::io::Result<()> {loop {let n = input.read(&mut buf)?;if n == 0 {break;}+ total += n as u64;+ if total > cap {+ return Err(crate::sandbox::safe_fs::too_large());+ }sha2::Digest::update(&mut h, &buf[..n]);out.write_all(&buf[..n])?;}@@ -193,7 +222,13 @@ fn store_blob(blobs: &FsPath, src: &FsPath) -> std::io::Result<String> {} else {std::fs::rename(&tmp, &dest)?;}- Ok(sha)+ Ok((sha, total))+}++/// [`git_head_in`] of `folder`, opened with no symlink followed.+#[cfg(test)]+fn git_head(folder: &FsPath) -> Option<String> {+ git_head_in(&crate::sandbox::safe_fs::Dir::open_strict(folder).ok()?)}/// The commit the folder's git checkout is on, if it is one (read-only info).@@ -202,12 +237,12 @@ fn store_blob(blobs: &FsPath, src: &FsPath) -> std::io::Result<String> {/// follows a symlink (at any component), never opens anything but a regular file with one link (a/// FIFO can't block it, a hard link can't name a host file), reads at most [`gitfile::REF_MAX`] //// [`gitfile::PACKED_MAX`] bytes, only follows a `ref:` that is a plain `refs/...` name, and only returns 40 or 64 hex characters. Anything else,-/// including a `.git` file (a `gitdir:` worktree pointer), is `None`.-fn git_head(folder: &FsPath) -> Option<String> {- let git = folder.join(".git");- if !gitfile::plain_dir(&std::fs::symlink_metadata(&git).ok()?) {- return None;- }+/// including a `.git` file (a `gitdir:` worktree pointer), is `None`. Read from the folder's+/// descriptor, the one its snapshot walked (QA F-3).+fn git_head_in(folder: &crate::sandbox::safe_fs::Dir) -> Option<String> {+ // `.git` is opened once, without following it (a symlink or a `.git` file fails), and HEAD,+ // the ref and packed-refs are all read from that one descriptor+ let git = folder.open_dir(FsPath::new(".git")).ok()?;let head = gitfile::read(&git, "HEAD", gitfile::REF_MAX)?;let head = head.trim();let Some(r) = head.strip_prefix("ref: ") else {@@ -239,23 +274,69 @@ struct Taken {git_head: Option<String>,}+/// The task folder as a checkpoint records it (QA F-4): the folders above it resolved now, its own+/// name kept as it is. A checkpoint's restore writes back only into the folder it recorded, opened+/// with [`Dir::open_strict`](crate::sandbox::safe_fs::Dir::open_strict), so a symlink the person+/// made above the folder (`~/Projects -> /mnt/ssd/Projects`, a linked home or data folder) works+/// as before, while any part swapped for a symlink after the checkpoint is refused (QA F-3).+/// Content and place stay bound: what a checkpoint read is only ever written back where it was+/// read. Never resolved at restore time. The folder itself, if a symlink, stays refused by+/// [`snapshot`] as before. A parent that can't be resolved (missing) is kept as typed.+#[cfg(unix)]+fn resolve_above(folder: &FsPath) -> PathBuf {+ match (folder.parent(), folder.file_name()) {+ (Some(parent), Some(name)) if !parent.as_os_str().is_empty() => parent.canonicalize().map(|p| p.join(name)).unwrap_or_else(|_| folder.to_path_buf()),+ _ => folder.to_path_buf(),+ }+}++/// Off unix the folder is kept as typed: Windows' `canonicalize` gives `\\?\` paths, and+/// checkpoints are new there in 0.7.7 (nothing to stay compatible with).+#[cfg(not(unix))]+fn resolve_above(folder: &FsPath) -> PathBuf {+ folder.to_path_buf()+}+/// Walks `folder` (never following symlinks) and stores each file's content as a blob./// A missing folder is an empty snapshot; an unreadable one is an error.fn snapshot(blobs: &FsPath, folder: &FsPath, max_bytes: u64) -> Result<Taken, String> {- private_dir(blobs).map_err(|e| format!("the checkpoint store can't be written: {e}"))?;- let mut m = Manifest::default();match std::fs::symlink_metadata(folder) {- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Taken { manifest: m, bytes: 0, git_head: None }),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {+ private_dir(blobs).map_err(|e| format!("the checkpoint store can't be written: {e}"))?;+ return Ok(Taken { manifest: Manifest::default(), bytes: 0, git_head: None });+ }Err(e) => return Err(format!("the folder can't be read: {e}")),Ok(meta) if !meta.is_dir() => return Err("the task's folder isn't a folder".into()),Ok(_) => {}}+ // No part of the folder's own path is followed if it is a symlink (QA F-3): a task folder+ // nested in a bot's folder can be swapped by that bot+ let top = crate::sandbox::safe_fs::Dir::open_strict(folder).map_err(|e| format!("the folder can't be read: {e}"))?;+ snapshot_in(blobs, top, max_bytes)+}++/// [`snapshot`] of a folder already open: a restore snapshots and writes through the same+/// descriptor, so a folder swapped in between is never the one written (QA F-3).+fn snapshot_in(blobs: &FsPath, top: crate::sandbox::safe_fs::Dir, max_bytes: u64) -> Result<Taken, String> {+ private_dir(blobs).map_err(|e| format!("the checkpoint store can't be written: {e}"))?;+ let mut m = Manifest::default();+ // Every folder is reached from its parent's descriptor and every file opened from the+ // folder's with `openat(…, O_NOFOLLOW)` (S-8): a part swapped for a symlink mid-walk is+ // skipped, never followed. Candidates keep their exact relative path to open later.+ use crate::sandbox::safe_fs::{Dir, Kind};+ let top = std::rc::Rc::new(top);let mut candidates: Vec<(String, PathBuf, u64, u32)> = Vec::new();- let mut stack: Vec<(PathBuf, String)> = vec![(folder.to_path_buf(), String::new())];+ let mut stack: Vec<(std::rc::Rc<Dir>, Option<std::ffi::OsString>, String, PathBuf)> =+ vec![(top.clone(), None, String::new(), PathBuf::new())];let mut first = true;- while let Some((dir, prefix)) = stack.pop() {- let entries = match std::fs::read_dir(&dir) {- Ok(e) => e,+ while let Some((parent, name, prefix, at)) = stack.pop() {+ let listed = match name {+ None => Ok(parent),+ Some(n) => parent.open_dir(FsPath::new(&n)).map(std::rc::Rc::new),+ }+ .and_then(|d| d.list().map(|l| (d, l)));+ let (dir, entries) = match listed {+ Ok(x) => x,Err(e) if first => return Err(format!("the folder can't be read: {e}")),Err(_) => {m.skipped.push(Skip { path: prefix.to_string(), why: "folder can't be read".into() });@@ -263,28 +344,18 @@ fn snapshot(blobs: &FsPath, folder: &FsPath, max_bytes: u64) -> Result<Taken, St}};first = false;- for entry in entries.flatten() {- let name = entry.file_name().to_string_lossy().into_owned();+ for entry in entries {+ let name = entry.name.to_string_lossy().into_owned();let rel = format!("{prefix}{name}");- let Ok(meta) = std::fs::symlink_metadata(entry.path()) else {- m.skipped.push(Skip { path: rel, why: "can't be read".into() });- continue;- };- let ft = meta.file_type();- if ft.is_symlink() {- m.skipped.push(Skip { path: rel, why: "symlink, not followed".into() });- } else if ft.is_dir() {- if SKIP_DIRS.contains(&name.as_str()) {- m.skipped.push(Skip { path: format!("{rel}/"), why: "not snapshotted".into() });- } else {- stack.push((entry.path(), format!("{rel}/")));+ match entry.kind {+ Kind::Symlink => m.skipped.push(Skip { path: rel, why: "symlink, not followed".into() }),+ Kind::Dir if SKIP_DIRS.contains(&name.as_str()) => {+ m.skipped.push(Skip { path: format!("{rel}/"), why: "not snapshotted".into() })}- } else if !ft.is_file() {- m.skipped.push(Skip { path: rel, why: "not a regular file".into() });- } else if meta.len() > FILE_MAX_BYTES {- m.skipped.push(Skip { path: rel, why: "over 20 MB".into() });- } else {- candidates.push((rel, entry.path(), meta.len(), crate::fsx::mode_of(&meta)));+ Kind::Dir => stack.push((dir.clone(), Some(entry.name.clone()), format!("{rel}/"), at.join(&entry.name))),+ Kind::Other => m.skipped.push(Skip { path: rel, why: "not a regular file".into() }),+ Kind::File if entry.len > FILE_MAX_BYTES => m.skipped.push(Skip { path: rel, why: "over 20 MB".into() }),+ Kind::File => candidates.push((rel, at.join(&entry.name), entry.len, entry.mode & 0o777)),}}}@@ -318,18 +389,25 @@ fn snapshot(blobs: &FsPath, folder: &FsPath, max_bytes: u64) -> Result<Taken, St}candidates = kept;}- let mut bytes = 0;- for (rel, abs, len, mode) in candidates {- match store_blob(blobs, &abs) {- Ok(sha) => {+ // What counts toward the cap is what was really stored, not the listing's sizes+ let mut bytes: u64 = 0;+ let mb = max_bytes / (1024 * 1024);+ for (rel, at, _listed, mode) in candidates {+ let cap = FILE_MAX_BYTES.min(max_bytes.saturating_sub(bytes));+ match top.open_file(&at).and_then(|f| store_blob(blobs, f, cap)) {+ Ok((sha, len)) => {bytes += len;m.files.push(Entry { path: rel, sha256: sha, bytes: len, mode });}+ Err(e) if crate::sandbox::safe_fs::is_too_large(&e) && cap < FILE_MAX_BYTES => {+ m.skipped.push(Skip { path: rel, why: format!("over the {mb} MB checkpoint cap") })+ }+ Err(e) if crate::sandbox::safe_fs::is_too_large(&e) => m.skipped.push(Skip { path: rel, why: "over 20 MB".into() }),Err(_) => m.skipped.push(Skip { path: rel, why: "can't be read".into() }),}}m.skipped.sort_by(|a, b| a.path.cmp(&b.path));- Ok(Taken { manifest: m, bytes, git_head: git_head(folder) })+ Ok(Taken { manifest: m, bytes, git_head: git_head_in(&top) })}fn write_manifest(dir: &FsPath, id: &str, m: &Manifest) -> std::io::Result<(PathBuf, String)> {@@ -433,10 +511,25 @@ fn append_run(dir: &FsPath, run: &Run) -> std::io::Result<()> {/// Run checkpoints (`before_run`, `after_run`) follow the `checkpoints` setting; manual and/// `before_restore` ones are always taken.pub async fn take(state: &AppState, task: &Task, kind: &str, claim: Option<&Claim>, created_by: &str) -> Option<Checkpoint> {+ take_in(state, task, kind, claim, created_by, None).await+}++/// [`take`], of `pinned`'s folder (already open, by that path) instead of the task's folder.+async fn take_in(+ state: &AppState,+ task: &Task,+ kind: &str,+ claim: Option<&Claim>,+ created_by: &str,+ pinned: Option<(PathBuf, std::sync::Arc<crate::sandbox::safe_fs::Dir>)>,+) -> Option<Checkpoint> {if matches!(kind, "before_run" | "after_run") && !enabled(state).await {return None;}- let folder = task_folder(state, task).await;+ let (folder, pinned) = match pinned {+ Some((f, d)) => (Some(f), Some(d)),+ None => (task_folder(state, task).await.map(|f| resolve_above(&f)), None),+ };let max_bytes = max_mb(state).await as u64 * 1024 * 1024;let root = root(state);let task_dir = root.join(&task.id);@@ -448,7 +541,10 @@ pub async fn take(state: &AppState, task: &Task, kind: &str, claim: Option<&Clailet (root, task_dir, id) = (root.clone(), task_dir.clone(), id.clone());tokio::task::spawn_blocking(move || -> Result<(Taken, PathBuf, String), String> {private_dir(&root).map_err(|e| format!("the checkpoint store can't be written: {e}"))?;- let taken = snapshot(&root.join("blobs"), &folder, max_bytes)?;+ let taken = match pinned {+ Some(d) => snapshot_in(&root.join("blobs"), d.open_dir(FsPath::new("")).map_err(|e| format!("the folder can't be read: {e}"))?, max_bytes)?,+ None => snapshot(&root.join("blobs"), &folder, max_bytes)?,+ };let (path, sha) = write_manifest(&task_dir, &id, &taken.manifest).map_err(|e| format!("the manifest can't be written: {e}"))?;Ok((taken, path, sha))})@@ -922,8 +1018,10 @@ fn plan_json(c: &Checkpoint, p: &Plan) -> Value {})}-/// Writes the plan's changes (plus the forced conflicts) into the folder; never through a symlink.-fn apply(blobs: &FsPath, p: &Plan, force: &BTreeSet<String>) -> (Vec<String>, Vec<String>, Vec<Value>) {+/// Writes the plan's changes (plus the forced conflicts) into `root`, the plan's folder opened+/// once with [`Dir::open_strict`](crate::sandbox::safe_fs::Dir::open_strict) (the same descriptor+/// the safety checkpoint read: QA F-3); never through a symlink.+fn apply(blobs: &FsPath, p: &Plan, force: &BTreeSet<String>, root: &crate::sandbox::safe_fs::Dir) -> (Vec<String>, Vec<String>, Vec<Value>) {let mut todo: Vec<(String, &'static str)> = p.changes.iter().map(|c| (c.path.clone(), c.action)).collect();todo.extend(p.forced.iter().filter(|(k, _)| force.contains(*k)).map(|(k, a)| (k.clone(), *a)));let (mut restored, mut deleted, mut failed) = (Vec::new(), Vec::new(), Vec::new());@@ -932,27 +1030,22 @@ fn apply(blobs: &FsPath, p: &Plan, force: &BTreeSet<String>) -> (Vec<String>, Vefailed.push(json!({"path": rel, "why": "symlink, not followed"}));continue;}- let dest = p.folder.join(&rel);- let r = if action == "delete" {- std::fs::remove_file(&dest).map(|_| false)- } else {- let e = &p.entries[&rel];- (|| -> std::io::Result<bool> {- let parent = dest.parent().unwrap_or(&p.folder);- std::fs::create_dir_all(parent)?;- // The folders just created can't be symlinks, but one may have appeared meanwhile- if through_symlink(&p.folder, &rel) {- return Err(std::io::Error::other("symlink"));- }- let tmp = parent.join(format!(".kwant-restore-{}", new_id()));- std::fs::copy(blobs.join(&e.sha256), &tmp)?;- crate::fsx::set_mode(&tmp, if e.mode == 0 { 0o644 } else { e.mode })?;- std::fs::rename(&tmp, &dest).inspect_err(|_| {- let _ = std::fs::remove_file(&tmp);- })?;+ // Every folder on the way is opened (or made) from the task folder's descriptor with+ // `O_NOFOLLOW`, and the file goes in with `openat`/`renameat` (S-8): a folder swapped for+ // a symlink is refused, never written through+ let relp = FsPath::new(&rel);+ let (parent, name) = (relp.parent().unwrap_or(FsPath::new("")), relp.file_name().unwrap_or_default());+ let r = (|| {+ if action == "delete" {+ root.open_dir(parent)?.remove_file(name).map(|_| false)+ } else {+ let e = &p.entries[&rel];+ let dir = root.make_dirs(parent)?;+ let mut src = std::fs::File::open(blobs.join(&e.sha256))?;+ dir.replace_file(name, &format!(".kwant-restore-{}", new_id()), &mut src, if e.mode == 0 { 0o644 } else { e.mode })?;Ok(true)- })()- };+ }+ })();match r {Ok(true) => restored.push(rel),Ok(false) => deleted.push(rel),@@ -965,12 +1058,24 @@ fn apply(blobs: &FsPath, p: &Plan, force: &BTreeSet<String>) -> (Vec<String>, Ve/// Takes a `before_restore` checkpoint, then writes the plan. Returns the counts JSON.#[allow(clippy::result_large_err)]async fn write_back(state: &AppState, task: &Task, c: &Checkpoint, p: &Plan, force: BTreeSet<String>) -> Result<Value, Response> {- let Some(safety) = take(state, task, "before_restore", None, "person").await.filter(|s| !s.failed()) else {+ // The folder is opened once, no symlink followed on any part of its path, and the safety+ // checkpoint and the writes both go through that descriptor (QA F-3): a task folder nested in+ // a bot's folder swapped for a symlink in between is never written through+ let folder = p.folder.clone();+ let opened = tokio::task::spawn_blocking(move || crate::sandbox::safe_fs::Dir::open_strict(&folder)).await.map_err(internal)?;+ let Ok(dir) = opened.map(std::sync::Arc::new) else {+ return Err(coded(+ StatusCode::INTERNAL_SERVER_ERROR,+ "checkpoint_failed",+ "the task's folder is missing, moved or a symlink now, so the safety checkpoint couldn't be taken and nothing was restored",+ ));+ };+ let Some(safety) = take_in(state, task, "before_restore", None, "person", Some((p.folder.clone(), dir.clone()))).await.filter(|s| !s.failed()) else {return Err(coded(StatusCode::INTERNAL_SERVER_ERROR, "checkpoint_failed", "the safety checkpoint couldn't be taken, so nothing was restored"));};let held = STORE.lock().await;let (blobs, plan) = (root(state).join("blobs"), p.clone());- let (restored, deleted, failed) = tokio::task::spawn_blocking(move || apply(&blobs, &plan, &force)).await.map_err(internal)?;+ let (restored, deleted, failed) = tokio::task::spawn_blocking(move || apply(&blobs, &plan, &force, &dir)).await.map_err(internal)?;drop(held);let detail = json!({"checkpoint_id": c.id,@@ -1193,6 +1298,27 @@ pub async fn restore_for_fork(state: &AppState, orig: &Task, cid: &str) -> Resulmod tests {use super::*;+ /// Should-fix 1: the blob store reads at most its cap from the open handle and returns what+ /// it really read; a longer file is refused with nothing stored.+ #[test]+ fn a_blob_is_read_up_to_its_cap_and_counted_by_its_real_bytes() {+ let d = tempfile::tempdir().unwrap();+ let blobs = d.path().join("blobs");+ std::fs::create_dir(&blobs).unwrap();+ let src = d.path().join("f");+ std::fs::write(&src, b"0123456789").unwrap();+ let (sha, n) = store_blob(&blobs, std::fs::File::open(&src).unwrap(), 10).unwrap();+ assert_eq!(n, 10);+ assert_eq!(std::fs::read(blobs.join(&sha)).unwrap(), b"0123456789");+ let e = store_blob(&blobs, std::fs::File::open(&src).unwrap(), 9).unwrap_err();+ assert!(crate::sandbox::safe_fs::is_too_large(&e), "{e}");+ // Grown past the cap after an open that saw it small: the read itself stops+ let f = std::fs::File::open(&src).unwrap();+ std::fs::write(&src, vec![b'x'; 64]).unwrap();+ assert!(crate::sandbox::safe_fs::is_too_large(&store_blob(&blobs, f, 20).unwrap_err()));+ assert_eq!(std::fs::read_dir(&blobs).unwrap().count(), 1, "nothing stored for a refused file, no temp left");+ }+#[test]fn only_plain_relative_paths_are_safe() {assert!(safe_rel("a.txt"));@@ -1469,4 +1595,175 @@ mod tests {let after = m(&[("same", "1"), ("edited", "2"), ("new", "1")], &["big", "node_modules/", "huge"]);assert_eq!(changed(&before, &after), vec!["edited", "gone", "huge", "new"]);}++ // QA F-3 (Rigel's probes in 446-probes/checkpoints-nested-probes.diff): a task folder nested in+ // a bot's folder, which that bot's container can write, swapped for a symlink to a folder+ // outside it between the safety checkpoint and the writes+ #[cfg(target_os = "linux")]+ fn exchange(a: &FsPath, b: &FsPath) -> bool {+ use std::os::unix::ffi::OsStrExt;+ let (a, b) = (std::ffi::CString::new(a.as_os_str().as_bytes()).unwrap(), std::ffi::CString::new(b.as_os_str().as_bytes()).unwrap());+ // SAFETY: valid C strings; RENAME_EXCHANGE (2) swaps two existing entries atomically+ unsafe { libc::syscall(libc::SYS_renameat2, libc::AT_FDCWD, a.as_ptr(), libc::AT_FDCWD, b.as_ptr(), 2u32) == 0 }+ }++ #[cfg(unix)]+ fn nested() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf, PathBuf) {+ let d = tempfile::tempdir().unwrap();+ let bot = d.path().join("bot-folder");+ let task = bot.join("proj");+ std::fs::create_dir_all(&task).unwrap();+ std::fs::write(task.join("authorized_keys"), "ATTACKER-KEY\n").unwrap();+ let victim = d.path().join("victim-ssh");+ std::fs::create_dir_all(&victim).unwrap();+ std::fs::write(victim.join("authorized_keys"), "ORIGINAL\n").unwrap();+ let blobs = d.path().join("blobs");+ (d, bot, task, victim, blobs)+ }++ #[cfg(unix)]+ fn overwrite_plan(task: &FsPath, taken: &Taken) -> Plan {+ let entries: BTreeMap<String, Entry> = taken.manifest.files.iter().map(|e| (e.path.clone(), e.clone())).collect();+ Plan {+ changes: vec![Change { path: "authorized_keys".into(), action: "overwrite" }],+ conflicts: vec![],+ forced: BTreeMap::new(),+ skipped: vec![],+ external: vec![],+ effects_known: true,+ refused: None,+ state_after: None,+ sha: String::new(),+ folder: task.to_path_buf(),+ entries,+ }+ }++ #[cfg(unix)]+ #[test]+ fn a_task_folder_swapped_for_a_symlink_is_refused_by_the_safety_checkpoint() {+ let (_d, bot, task, victim, blobs) = nested();+ std::fs::rename(&task, bot.join("proj.moved")).unwrap();+ std::os::unix::fs::symlink(&victim, &task).unwrap();+ assert!(snapshot(&blobs, &task, 1 << 30).is_err(), "a symlinked task folder is never snapshotted");+ assert!(crate::sandbox::safe_fs::Dir::open_strict(&task).is_err(), "nor opened for a restore");+ assert_eq!(current(&task, "authorized_keys"), Err("symlink, not followed".into()));+ // A symlink on a part above the task folder is refused too+ std::fs::rename(&bot, bot.with_file_name("bot-real")).unwrap();+ std::os::unix::fs::symlink(bot.with_file_name("bot-real"), &bot).unwrap();+ assert!(crate::sandbox::safe_fs::Dir::open_strict(&bot.join("proj.moved")).is_err());+ assert_eq!(std::fs::read_to_string(victim.join("authorized_keys")).unwrap(), "ORIGINAL\n");+ }++ #[cfg(unix)]+ #[test]+ fn a_restore_writes_through_the_descriptor_its_safety_checkpoint_read() {+ let (_d, bot, task, victim, blobs) = nested();+ let taken = snapshot(&blobs, &task, 1 << 30).unwrap();+ let plan = overwrite_plan(&task, &taken);+ std::fs::write(task.join("authorized_keys"), "CHANGED\n").unwrap();+ // write_back: open the folder, take the safety checkpoint through it…+ let root = crate::sandbox::safe_fs::Dir::open_strict(&task).unwrap();+ let safety = snapshot_in(&blobs, root.open_dir(FsPath::new("")).unwrap(), 1 << 30).unwrap();+ assert_eq!(safety.manifest.files.len(), 1);+ // …the bot swaps the folder for a symlink to one outside its own…+ std::fs::rename(&task, bot.join("proj.moved")).unwrap();+ std::os::unix::fs::symlink(&victim, &task).unwrap();+ // …and the writes still land in the folder the checkpoint read, never in the other one+ let (restored, _deleted, failed) = apply(&blobs, &plan, &BTreeSet::new(), &root);+ assert_eq!(restored, vec!["authorized_keys".to_string()], "{failed:?}");+ assert_eq!(std::fs::read_to_string(victim.join("authorized_keys")).unwrap(), "ORIGINAL\n");+ assert_eq!(std::fs::read_to_string(bot.join("proj.moved/authorized_keys")).unwrap(), "ATTACKER-KEY\n");+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn a_restore_racing_a_folder_swap_never_writes_outside_it() {+ let (_d, bot, task, victim, blobs) = nested();+ let lnk = bot.join("lnk");+ std::os::unix::fs::symlink(&victim, &lnk).unwrap();+ let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let swapper = {+ let (stop, t, l) = (stop.clone(), task.clone(), lnk.clone());+ std::thread::spawn(move || {+ let mut swaps = 0u32;+ while !stop.load(std::sync::atomic::Ordering::Relaxed) {+ swaps += u32::from(exchange(&t, &l));+ std::thread::sleep(std::time::Duration::from_micros(200));+ }+ swaps+ })+ };+ let (mut hits, mut applied) = (0, 0);+ for _ in 0..300 {+ // As write_back does: one strict open, then the snapshot and the writes through it+ let Ok(root) = crate::sandbox::safe_fs::Dir::open_strict(&task) else { continue };+ let Ok(taken) = snapshot_in(&blobs, root.open_dir(FsPath::new("")).unwrap(), 1 << 30) else { continue };+ if taken.manifest.files.is_empty() {+ continue;+ }+ let _ = apply(&blobs, &overwrite_plan(&task, &taken), &BTreeSet::new(), &root);+ applied += 1;+ if std::fs::read_to_string(victim.join("authorized_keys")).unwrap_or_default().contains("ATTACKER") {+ hits += 1;+ std::fs::write(victim.join("authorized_keys"), "ORIGINAL\n").unwrap();+ }+ }+ stop.store(true, std::sync::atomic::Ordering::Relaxed);+ assert!(swapper.join().unwrap() > 0, "the folder was really swapped");+ assert!(applied > 0, "some restores ran");+ assert_eq!(hits, 0, "a restore wrote into the folder the task folder was swapped for");+ }++ /// QA F-4: a symlink the person made above the task folder (`~/Projects -> /mnt/ssd/Projects`)+ /// works for checkpoint and restore, because a checkpoint records the folder with the parts+ /// above it resolved when it is taken; a swap after that is still refused (QA F-3).+ #[cfg(unix)]+ #[test]+ fn a_symlink_the_person_made_above_the_folder_works_and_a_later_swap_is_refused() {+ let d = tempfile::tempdir().unwrap();+ let ssd = d.path().join("ssd");+ std::fs::create_dir_all(ssd.join("Projects/proj")).unwrap();+ std::fs::write(ssd.join("Projects/proj/authorized_keys"), "V0\n").unwrap();+ let home = d.path().join("home");+ std::fs::create_dir(&home).unwrap();+ std::os::unix::fs::symlink(ssd.join("Projects"), home.join("Projects")).unwrap();+ let typed = home.join("Projects/proj");+ let blobs = d.path().join("blobs");+ assert!(crate::sandbox::safe_fs::Dir::open_strict(&typed).is_err(), "the typed path has the person's symlink on the way");++ // Checkpoint: recorded with the parts above resolved, so it is taken, read and restored+ let folder = resolve_above(&typed);+ assert_eq!(folder, ssd.canonicalize().unwrap().join("Projects/proj"));+ let taken = snapshot(&blobs, &folder, 1 << 30).unwrap();+ assert_eq!(taken.manifest.files.len(), 1);+ std::fs::write(typed.join("authorized_keys"), "CHANGED\n").unwrap();+ assert!(matches!(current(&folder, "authorized_keys"), Ok(Some(_))));+ let root = crate::sandbox::safe_fs::Dir::open_strict(&folder).unwrap();+ let (restored, _deleted, failed) = apply(&blobs, &overwrite_plan(&folder, &taken), &BTreeSet::new(), &root);+ assert_eq!(restored, vec!["authorized_keys".to_string()], "{failed:?}");+ assert_eq!(std::fs::read_to_string(typed.join("authorized_keys")).unwrap(), "V0\n");++ // The folder swapped for a symlink after the checkpoint: refused, the other folder untouched+ let victim = d.path().join("victim");+ std::fs::create_dir(&victim).unwrap();+ std::fs::write(victim.join("authorized_keys"), "ORIGINAL\n").unwrap();+ std::fs::rename(&folder, folder.with_file_name("proj.moved")).unwrap();+ std::os::unix::fs::symlink(&victim, &folder).unwrap();+ assert!(crate::sandbox::safe_fs::Dir::open_strict(&folder).is_err());+ assert!(snapshot(&blobs, &folder, 1 << 30).is_err());+ assert_eq!(current(&folder, "authorized_keys"), Err("symlink, not followed".into()));+ std::fs::remove_file(&folder).unwrap();+ std::fs::rename(folder.with_file_name("proj.moved"), &folder).unwrap();++ // A part above it swapped for a symlink after the checkpoint: refused too+ std::fs::rename(&ssd, d.path().join("ssd.real")).unwrap();+ std::os::unix::fs::symlink(d.path().join("ssd.real"), &ssd).unwrap();+ assert!(crate::sandbox::safe_fs::Dir::open_strict(&folder).is_err());+ assert_eq!(std::fs::read_to_string(victim.join("authorized_keys")).unwrap(), "ORIGINAL\n");++ // The task folder itself a symlink is never resolved, and stays refused as on main+ assert_eq!(resolve_above(&home.join("Projects")), home.canonicalize().unwrap().join("Projects"));+ assert!(snapshot(&blobs, &resolve_above(&home.join("Projects")), 1 << 30).is_err());+ }}diff --git a/src/server/missions/checks.rs b/src/server/missions/checks.rsindex fa8f147e..a03ae71a 100644--- a/src/server/missions/checks.rs+++ b/src/server/missions/checks.rs@@ -34,6 +34,31 @@ pub fn secret_file(path: &Path) -> bool {/// `rel` resolved inside `folder` (symlinks followed), or why not.pub fn inside(folder: &Path, rel: &str) -> Result<PathBuf, String> {+ resolve_inside(folder, rel).map(|(_, real)| real)+}++/// Opens `rel` after [`inside`]'s checks, walking from the folder's descriptor (S-8): in vm mode+/// the bot can swap the checked file for a symlink to a host file, or a FIFO, before the open;+/// then the open fails (`NotFound` when it's gone) instead of reading that file or blocking.+pub fn open_inside(folder: &Path, rel: &str) -> Result<std::io::Result<std::fs::File>, String> {+ let (root, real) = resolve_inside(folder, rel)?;+ Ok(crate::sandbox::safe_fs::open_checked(&root, &real))+}++/// The most a file check or evidence hash reads: the graph scan's limit, so what was attached+/// can be checked again later.+pub const HASH_MAX_BYTES: u64 = super::graph::SCAN_MAX_BYTES;++/// The sha256 and size of an open file, refused past [`HASH_MAX_BYTES`]. Blocking: call it off the+/// async runtime.+pub fn hash_open(file: std::fs::File) -> std::io::Result<(String, u64)> {+ let mut hasher = Sha256::new();+ let n = crate::sandbox::safe_fs::copy_capped(file, &mut hasher, HASH_MAX_BYTES)?;+ Ok((hex(&hasher.finalize()), n))+}++/// The resolved folder and the resolved path of `rel` inside it.+fn resolve_inside(folder: &Path, rel: &str) -> Result<(PathBuf, PathBuf), String> {let rel = rel.trim();if rel.is_empty() {return Err("path is empty".into());@@ -56,7 +81,7 @@ pub fn inside(folder: &Path, rel: &str) -> Result<PathBuf, String> {if secret_file(&real) {return Err("checks don't read password, key or env files".into());}- Ok(real)+ Ok((root, real))}fn excerpt(s: &str) -> String {@@ -204,35 +229,62 @@ fn send_error(url: &str, e: &reqwest::Error) -> String {format!("GET {url} failed: network error, {why} ({e})")}-async fn file(kind: &str, rel: &str, spec: &Value, dir: &Path, seen: &mut Seen) -> Result<(bool, String), String> {- let path = inside(dir, rel)?;- let meta = tokio::fs::metadata(&path).await;- match kind {- "file_exists" => Ok((meta.as_ref().is_ok_and(|m| m.is_file()), match &meta {- Ok(m) => format!("{rel} exists ({} bytes)", m.len()),- Err(_) => format!("{rel} doesn't exist"),- })),- _ => {- let Ok(m) = meta else { return Ok((false, format!("{rel} doesn't exist"))) };- if !m.is_file() {- return Ok((false, format!("{rel} isn't a file")));- }- let bytes = tokio::fs::read(&path).await.map_err(|e| format!("can't read {rel}: {e}"))?;- if kind == "file_sha256" {- let got = hex(&Sha256::digest(&bytes));- let want = spec["sha256"].as_str().unwrap_or("").trim().to_ascii_lowercase();- seen.sha256 = Some((got.clone(), want.clone()));- Ok((got == want, format!("sha256 of {rel} is {got}")))- } else {- let want = spec["text"].as_str().unwrap_or("");- let text = String::from_utf8_lossy(&bytes[..bytes.len().min(MAX_READ_BYTES)]);- let has = !want.is_empty() && text.contains(want);- Ok((has, format!("{rel} {} \"{want}\"", if has { "contains" } else { "does not contain" })))+pub(crate) async fn file(kind: &str, rel: &str, spec: &Value, dir: &Path, seen: &mut Seen) -> Result<(bool, String), String> {+ let (dir, rel_s, kind_s) = (dir.to_path_buf(), rel.to_string(), kind.to_string());+ // Opened by walking from the folder and read from that handle only (S-8), off the runtime+ let read = tokio::task::spawn_blocking(move || -> Result<FileSeen, String> {+ let file = match open_inside(&dir, &rel_s)? {+ Ok(f) => f,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(FileSeen::Missing),+ Err(_) => return Ok(FileSeen::NotAFile),+ };+ let len = file.metadata().map(|m| m.len()).unwrap_or(0);+ Ok(match kind_s.as_str() {+ "file_exists" => FileSeen::Exists(len),+ "file_sha256" => match hash_open(file) {+ Ok((sha, _)) => FileSeen::Hash(sha),+ Err(e) if crate::sandbox::safe_fs::is_too_large(&e) => FileSeen::TooLarge,+ Err(e) => return Err(format!("can't read {rel_s}: {e}")),+ },+ _ => {+ let mut head = Vec::new();+ std::io::Read::read_to_end(&mut std::io::Read::take(file, MAX_READ_BYTES as u64), &mut head)+ .map_err(|e| format!("can't read {rel_s}: {e}"))?;+ FileSeen::Head(head)}+ })+ })+ .await+ .map_err(|_| format!("can't read {rel}"))??;+ match read {+ FileSeen::Missing => Ok((false, format!("{rel} doesn't exist"))),+ FileSeen::NotAFile => Ok((false, format!("{rel} isn't a file"))),+ FileSeen::Exists(n) => Ok((true, format!("{rel} exists ({n} bytes)"))),+ FileSeen::TooLarge => Ok((false, format!("{rel} is over {} MB, so it isn't hashed", HASH_MAX_BYTES / (1024 * 1024)))),+ FileSeen::Hash(got) => {+ let want = spec["sha256"].as_str().unwrap_or("").trim().to_ascii_lowercase();+ seen.sha256 = Some((got.clone(), want.clone()));+ Ok((got == want, format!("sha256 of {rel} is {got}")))+ }+ FileSeen::Head(bytes) => {+ let want = spec["text"].as_str().unwrap_or("");+ let text = String::from_utf8_lossy(&bytes);+ let has = !want.is_empty() && text.contains(want);+ Ok((has, format!("{rel} {} \"{want}\"", if has { "contains" } else { "does not contain" })))}}}+/// What a file check saw through its one open handle.+enum FileSeen {+ Missing,+ NotAFile,+ Exists(u64),+ TooLarge,+ Hash(String),+ Head(Vec<u8>),+}+pub fn hex(bytes: &[u8]) -> String {bytes.iter().map(|b| format!("{b:02x}")).collect()}@@ -252,7 +304,16 @@ pub async fn run_check(state: &AppState, task: &Task, check: &OutcomeCheck) -> O// person (check approval and mission approval are person-only routes). An http check the person// didn't add or approve is held to public addresses again now, pinned against DNS rebinding.let person_ok = check.requested_by == "person" || approved_by_person(state, check).await;- let (status, output) = run_spec(&check.kind, &spec, folder.as_deref(), person_ok).await;+ // D4 (C9b): a command check runs bash on this computer as kwnt; never in a folder an+ // isolated bot used, where the command (`npm test`) runs whatever that bot left there+ let refused = match (check.kind.as_str(), folder.as_deref()) {+ ("command", Some(dir)) => state.db.host_command_refusal(dir).await,+ _ => None,+ };+ let (status, output) = match refused {+ Some(why) => ("error".to_string(), why),+ None => run_spec(&check.kind, &spec, folder.as_deref(), person_ok).await,+ };// The excerpt reaches bots and the API: credentials in the output never get storedlet output = super::autofix::redact(&output);let ev = statediff --git a/src/server/missions/graph.rs b/src/server/missions/graph.rsindex 01867479..05c26f58 100644--- a/src/server/missions/graph.rs+++ b/src/server/missions/graph.rs@@ -3,7 +3,7 @@//! moves a task; only the person's resolution does. Contract: docs/mission-control.md §11.#![allow(clippy::result_large_err)]-use super::checks::{hex, inside};+use super::checks::{hash_open, open_inside};use super::routes::{bad, conflict, internal, load_mission, load_task, moved, not_found};use super::{emit_mission, emit_task, emit_task_id, name_of, post_line, task_folder, task_json, transition, Actor};use crate::db::mission_graph::{FlagClaim, GraphScan, TaskFlag, FLAG_RESOLUTIONS};@@ -111,24 +111,22 @@ pub struct ScanResult {pub skipped: Vec<Value>,}-/// The sha256 of `path`, `Ok(None)` when it is gone, or why it was skipped.-async fn hash_file(path: std::path::PathBuf) -> Result<Option<String>, String> {+/// The sha256 of `rel` in `folder`, `Ok(None)` when it is gone, or why it was skipped. Opened by+/// walking from the folder's descriptor and hashed from that handle, capped (S-8): a file swapped+/// for a symlink or a FIFO after the check is skipped, never hashed through.+pub(crate) async fn hash_file(folder: std::path::PathBuf, rel: String) -> Result<Option<String>, String> {tokio::task::spawn_blocking(move || {- let meta = match std::fs::metadata(&path) {- Ok(m) => m,+ let file = match open_inside(&folder, &rel)? {+ Ok(f) => f,Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => return Err("not a file".into()),Err(_) => return Err("can't be read".to_string()),};- if !meta.is_file() {- return Err("not a file".into());+ match hash_open(file) {+ Ok((sha, _)) => Ok(Some(sha)),+ Err(e) if crate::sandbox::safe_fs::is_too_large(&e) => Err("over 50 MB".into()),+ Err(_) => Err("can't be read".into()),}- if meta.len() > SCAN_MAX_BYTES {- return Err("over 50 MB".into());- }- let mut file = std::fs::File::open(&path).map_err(|_| "can't be read".to_string())?;- let mut hasher = <sha2::Sha256 as sha2::Digest>::new();- std::io::copy(&mut file, &mut hasher).map_err(|_| "can't be read".to_string())?;- Ok(Some(hex(&sha2::Digest::finalize(hasher))))}).await.unwrap_or_else(|_| Err("can't be read".into()))@@ -162,14 +160,7 @@ pub async fn scan_mission(state: &AppState, mission: &Mission) -> ScanResult {out.skipped.push(skip("the task has no folder"));continue;};- let real = match inside(folder, &path) {- Ok(p) => p,- Err(why) => {- out.skipped.push(skip(&why));- continue;- }- };- let new = match hash_file(real).await {+ let new = match hash_file(folder.clone(), path.clone()).await {Ok(h) => h,Err(why) => {out.skipped.push(skip(&why));diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rsindex 6397bc96..efac6776 100644--- a/src/server/missions/tools.rs+++ b/src/server/missions/tools.rs@@ -2,14 +2,13 @@//! `task_attach_evidence`, `task_request_check`, `task_review`, and the auditor's `audit_challenge`,//! `audit_rebut` (§18). Offered only while `mission_board` is on. None of them can set `verified`: only a passing check that isn't the owner's does.-use super::checks::{hex, inside, run_task_checks};+use super::checks::{hash_open, open_inside, run_task_checks, HASH_MAX_BYTES};use super::{evaluate, task_folder, transition, validate_check, Actor, PlanBy, PlanPlace, PlanTask};use crate::db::missions::{now_ms, NewCheck, NewEvidence, Task, TaskChange};use crate::db::spaces::SpaceId;use crate::server::continuity::SelfScope;use crate::server::AppState;use serde_json::{json, Value};-use sha2::{Digest, Sha256};type ToolResult = (String, bool);@@ -412,16 +411,24 @@ async fn evidence(state: &AppState, scope: &SelfScope, task: &Task, args: &Value"file" | "screenshot" => {let Some(rel) = s("path") else { return fail("path is required for a file.") };let Some(folder) = task_folder(state, task).await else { return fail("This task has no folder.") };- let path = match inside(&folder, &rel) {- Ok(p) => p,- Err(why) => return fail(format!("Not attached: {why}.")),+ // Opened by walking from the folder and hashed from that handle, capped (S-8)+ let (f, r) = (folder.clone(), rel.clone());+ let hashed = tokio::task::spawn_blocking(move || match open_inside(&f, &r) {+ Err(why) => Err(Some(why)),+ Ok(Err(_)) => Err(None),+ Ok(Ok(file)) => hash_open(file).map_err(|e| {+ crate::sandbox::safe_fs::is_too_large(&e).then(|| format!("it is over {} MB", HASH_MAX_BYTES / (1024 * 1024)))+ }),+ })+ .await+ .unwrap_or(Err(None));+ let (sha, n) = match hashed {+ Ok(h) => h,+ Err(Some(why)) => return fail(format!("Not attached: {why}.")),+ Err(None) => return fail(format!("{rel} doesn't exist or can't be read.")),};- let bytes = match tokio::fs::read(&path).await {- Ok(b) => b,- Err(_) => return fail(format!("{rel} doesn't exist or can't be read.")),- };- e.sha256 = Some(hex(&Sha256::digest(&bytes)));- e.bytes = i64::try_from(bytes.len()).ok();+ e.sha256 = Some(sha);+ e.bytes = i64::try_from(n).ok();e.path = Some(rel);}"url" => {diff --git a/src/server/mod.rs b/src/server/mod.rsindex 18acab30..fd937fb9 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -63,6 +63,8 @@ pub mod show_once;pub mod agents_connect;pub mod teams;pub mod telegram;+#[cfg(all(test, unix))]+mod s8_readers_test;use crate::broker::PermissionBroker;use crate::config::Config;@@ -139,6 +141,8 @@ pub struct AppState {pub mission_runs: Arc<missions::runner::RunningMissions>,/// The daily spending stop's clock (a test fixes it; see [`spend_stop::Clock`]).pub spend: Arc<spend_stop::Clock>,+ /// Claude replies run inside the VM ("Run Claude inside the VM", Linux only, off by default)+ pub agent_vm: Arc<crate::sandbox::agent_vm::AgentVm>,}impl AppState {@@ -156,6 +160,7 @@ impl AppState {let profiles = Arc::new(crate::profiles::ProfileManager::new(config.data_dir.clone()));let api_token = Arc::new(auth::ApiToken::load(&config));let browser_service = Arc::new(crate::sandbox::service::BrowserService::new(config.data_dir.clone(), config.browser_cdp_url.clone()));+ let agent_vm = crate::sandbox::agent_vm::AgentVm::new(&config.data_dir, config.agents_in_vm.clone(), db.clone());Self {config,db,@@ -191,6 +196,7 @@ impl AppState {app_update: crate::app_update::UpdateHub::shared(),mission_runs: Arc::default(),spend: Arc::default(),+ agent_vm,}}diff --git a/src/server/profile_turn.rs b/src/server/profile_turn.rsindex d8feb7c6..a3be8bd6 100644--- a/src/server/profile_turn.rs+++ b/src/server/profile_turn.rs@@ -5,7 +5,7 @@ use super::AppState;use crate::db::models::LlmProfile;use crate::db::spaces::SpaceId;use crate::drivers::engines::{EngineAccount, EngineId, EngineReport, EngineStatus};-use crate::drivers::{find_cli_binary, resolve_driver_for_model, ApiDriver, CliDriver, Driver};+use crate::drivers::{find_cli_binary, ApiDriver, CliDriver, Driver};use std::collections::HashSet;use std::sync::atomic::{AtomicBool, Ordering};use crate::profiles::{@@ -176,7 +176,7 @@ fn profile_engine_on(state: &AppState, p: &LlmProfile) -> bool {}/// The driver for one attempt, and the engine it runs on when it's the host's own (no profile-/// or the system profile; see [`resolve_driver_for_model`]). `Err` when that engine can't run.+/// or the system profile; see [`crate::drivers::resolve_driver_for_model`]). `Err` when that engine can't run.pub async fn driver_for(state: &AppState,profile: Option<&LlmProfile>,@@ -185,7 +185,9 @@ pub async fn driver_for(endpoint: Option<String>,) -> Result<(Box<dyn Driver>, Option<EngineId>), String> {let Some(p) = profile.filter(|p| p.kind != "system") else {- return resolve_driver_for_model(target_model, configured_key, endpoint, &state.engines)+ // This computer's Claude sign-in runs isolated too; its API key never does+ let isolation = isolation_for(state, Engine::Claude, None).await;+ return crate::drivers::resolve_driver_isolated(target_model, configured_key, endpoint, &state.engines, isolation).map(|(d, e)| (d, Some(e)));};let engine = Engine::parse(&p.engine).unwrap_or(Engine::Claude);@@ -207,6 +209,7 @@ pub async fn driver_for(return Ok((Box::new(ApiDriver::for_profile(key)), None));}let home = state.profiles.home_of(p).unwrap_or_default();+ let isolation = isolation_for(state, engine, Some(home.clone())).await;Ok((Box::new(CliDriver::new(@@ -214,12 +217,36 @@ pub async fn driver_for(Some(engine.as_str().into()),).with_profile_home(engine, home)- .with_account(p.name.clone()),+ .with_account(p.name.clone())+ .with_isolation(isolation),),None,))}+/// Set when a Claude sign-in turn runs in the bot's agent container: "Run Claude inside the VM"+/// is on, the computer is in vm mode and this OS has isolation (D1: outside vm mode the switch+/// does nothing). API-key and Custom accounts never get here.+pub async fn isolation_for(+ state: &AppState,+ engine: Engine,+ profile_home: Option<std::path::PathBuf>,+) -> Option<crate::drivers::cli::Isolation> {+ if engine != Engine::Claude || crate::sandbox::agent_vm::supported_os().is_err() {+ return None;+ }+ if !super::computer::isolate_claude_setting(state).await+ || super::computer::current_mode(state).await != crate::sandbox::computer::ComputerMode::Vm+ {+ return None;+ }+ Some(crate::drivers::cli::Isolation {+ vm: state.agent_vm.clone(),+ profile_home,+ kwnt_origin: super::mcp_runtime::local_base_url(state),+ })+}+/// A Custom API account's server and key. `Err` when its server was never saved.pub async fn custom_endpoint(state: &AppState,diff --git a/src/server/routes.rs b/src/server/routes.rsindex c64790df..032b447c 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -2799,8 +2799,7 @@ async fn run_kwant_turn_inner(let driver_task =tokio::spawn(async move { driver.stream_turn(input, driver_tx).await });// Stall watchdog: silence while no tool runs, for longer than the limit, stops the turn- let mut last_output = tokio::time::Instant::now();- let mut tools_running = 0usize;+ let mut stall_clock = super::turns::StallClock::new(stall_limit, tokio::time::Instant::now());let mut stalled = false;// The driver's TurnComplete is held back: it's re-sent with the kwant and profile,@@ -2808,7 +2807,7 @@ async fn run_kwant_turn_inner(let mut held_complete = None;let mut side_effects = false;loop {- let stall_at = stall_limit.filter(|_| tools_running == 0).map(|d| last_output + d);+ let stall_at = stall_clock.deadline();tokio::select! {_ = cancel_token.cancelled() => {cancelled = true;@@ -2826,11 +2825,8 @@ async fn run_kwant_turn_inner(break;}event_opt = driver_rx.recv() => {- last_output = tokio::time::Instant::now();- match &event_opt {- Some(RuntimeEvent::ToolCallPending { .. }) => tools_running += 1,- Some(RuntimeEvent::ToolCallCompleted { .. }) => tools_running = tools_running.saturating_sub(1),- _ => {}+ if let Some(e) = &event_opt {+ stall_clock.saw(e, tokio::time::Instant::now());}match event_opt {Some(RuntimeEvent::TurnComplete { tokens, duration_ms, .. }) => {@@ -2838,6 +2834,29 @@ async fn run_kwant_turn_inner(}// Only resets the stall clock (above)Some(RuntimeEvent::Progress) => {}+ // An isolated reply waits for a spot in the VM: shown as queued, and the+ // stall clock (above) is off until it gets one+ Some(RuntimeEvent::WaitingForRoom { reason, position, slots }) => {+ state.turns.set_turn_state(&tag.turn_id, "queued");+ let _ = state.event_sender.send(RuntimeEvent::TurnQueued {+ turn_id: tag.turn_id.clone(),+ kwant_id: tag.kwant_id.clone(),+ context_id: Some(tag.context_id.clone()),+ thread_id: tag.thread_id.clone(),+ position,+ reason,+ slots: Some(slots),+ });+ }+ Some(RuntimeEvent::RoomTaken) => {+ state.turns.set_turn_state(&tag.turn_id, "running");+ let _ = state.event_sender.send(RuntimeEvent::TurnStarted {+ kwant_id: tag.kwant_id.clone(),+ context_id: Some(tag.context_id.clone()),+ turn_id: Some(tag.turn_id.clone()),+ thread_id: tag.thread_id.clone(),+ });+ }// Lets a task handed in during the turn pay for it then (see `super::missions::spend_at_hand_in`)Some(RuntimeEvent::UsageSoFar { fresh }) => state.turns.saw_usage(&tag.turn_id, fresh),Some(event) => {@@ -2898,6 +2917,23 @@ async fn run_kwant_turn_inner(break;}let result = driver_task.await;+ // Isolated Claude didn't start, or hit its request cap: the notice is the turn's end,+ // saved like a stall (a kwant message with meta), never another account or this computer+ if let Ok(Ok(out)) = &result {+ if let Some((text, meta)) = &out.notice {+ tracing::warn!(kwant = %target_kwant.id, kind = %meta["kind"], reason = %meta["reason"], "turn ended with a notice");+ event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));+ event_broadcast.send(RuntimeEvent::TurnComplete {+ tokens: 0,+ duration_ms: turn_start.elapsed().as_millis() as u64,+ kwant_id: Some(target_kwant.id.clone()),+ profile_id: profile.as_ref().map(|p| p.id.clone()),+ });+ gave_up = Some(text.clone());+ gave_up_meta = Some(meta.clone());+ break;+ }+ }let refused = match &result {// A reply that is nothing but a usage-limit line is the provider's refusal, never an answerOk(Ok(out)) => out.failure.clone().or_else(|| limit_line_failure(&out.text)),diff --git a/src/server/s8_readers_test.rs b/src/server/s8_readers_test.rsnew file mode 100644index 00000000..94b3bc1b--- /dev/null+++ b/src/server/s8_readers_test.rs@@ -0,0 +1,141 @@+//! S-8 (Ada's review of #446, M1): the five host readers of a bot folder that used to check a+//! path and then open it again by path, raced by a "bot" that keeps swapping the file for a+//! symlink to a host file and for a FIFO, and its folder for a symlink to a host folder. Each+//! reader sees the real file or nothing: never the canary's bytes or hash, and never hangs.++use super::attachments::inside_workspace;+use super::goals_remediation::read_report;+use super::missions::checks::{self, hash_open, open_inside, Seen};+use super::missions::graph::hash_file;+use serde_json::json;+use sha2::{Digest, Sha256};+use std::io::Read;+use std::os::unix::fs::symlink;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;++const CANARY: &str = "CANARY-host-secret-0f3a";++fn mkfifo(p: &Path) {+ let c = std::ffi::CString::new(p.to_string_lossy().as_bytes()).unwrap();+ // SAFETY: a valid C string+ unsafe { libc::mkfifo(c.as_ptr(), 0o600) };+}++/// Keeps replacing `dir/x` (via a temp name and rename(2)) with a real file, a symlink to the+/// outside canary, then a FIFO.+fn rotate_file(dir: PathBuf, outside: PathBuf, stop: Arc<AtomicBool>) -> std::thread::JoinHandle<()> {+ std::thread::spawn(move || {+ let (tmp, x) = (dir.join(".swap"), dir.join("x"));+ let mut i = 0u64;+ while !stop.load(Ordering::Relaxed) {+ let _ = std::fs::remove_file(&tmp);+ match i % 3 {+ 0 => drop(std::fs::write(&tmp, "mine")),+ 1 => drop(symlink(outside.join("x"), &tmp)),+ _ => mkfifo(&tmp),+ }+ let _ = std::fs::rename(&tmp, &x);+ i += 1;+ }+ })+}++/// Keeps swapping `root/sub` between the real folder and a symlink to the outside folder.+fn swap_folder(root: PathBuf, outside: PathBuf, stop: Arc<AtomicBool>) -> std::thread::JoinHandle<()> {+ std::thread::spawn(move || {+ let mut real = true;+ while !stop.load(Ordering::Relaxed) {+ if real {+ let _ = std::fs::rename(root.join("sub"), root.join("sub_parked"));+ let _ = symlink(&outside, root.join("sub"));+ } else {+ let _ = std::fs::remove_file(root.join("sub"));+ let _ = std::fs::rename(root.join("sub_parked"), root.join("sub"));+ }+ real = !real;+ }+ })+}++async fn run_readers(root: &Path, rel: &str, canary_sha: &str, rounds: usize) -> usize {+ let folder = root.to_str().unwrap();+ let mut real_reads = 0;+ for _ in 0..rounds {+ // H6 share_file+ if let Some((mut f, _)) = inside_workspace(root, rel) {+ let mut s = String::new();+ if f.read_to_string(&mut s).is_ok() {+ assert!(!s.contains(CANARY), "share_file read the host file");+ real_reads += 1;+ }+ }+ // H7 task_attach_evidence: the same open and hash the tool runs+ if let Ok(Ok(f)) = open_inside(root, rel) {+ if let Ok((sha, _)) = hash_open(f) {+ assert_ne!(sha, canary_sha, "evidence hashed the host file");+ }+ }+ // H8 the file checks+ let mut seen = Seen::default();+ if let Ok((has, out)) = checks::file("file_contains", rel, &json!({"text": "CANARY"}), root, &mut seen).await {+ assert!(!has, "file_contains saw the host file: {out}");+ }+ if let Ok((ok, out)) = checks::file("file_sha256", rel, &json!({"sha256": canary_sha}), root, &mut seen).await {+ assert!(!ok, "file_sha256 matched the host file: {out}");+ }+ let _ = checks::file("file_exists", rel, &json!({}), root, &mut seen).await;+ // The Investigate report+ if let Some(text) = read_report(folder, rel).await {+ assert!(!text.contains(CANARY), "read_report read the host file");+ }+ // The graph scan+ if let Ok(Some(h)) = hash_file(root.to_path_buf(), rel.to_string()).await {+ assert_ne!(h, canary_sha, "the graph scan hashed the host file");+ }+ }+ real_reads+}++#[test]+fn the_five_host_readers_racing_a_swapper_never_read_the_target_or_hang() {+ let (done_tx, done_rx) = std::sync::mpsc::channel();+ // On a separate thread: a reader that blocks on a FIFO fails the test instead of hanging it+ std::thread::spawn(move || {+ let t = tempfile::tempdir().unwrap();+ // Resolved: the readers compare resolved paths (macOS's /var is a link)+ std::fs::create_dir_all(t.path().join("root/sub")).unwrap();+ let (root, outside) = (t.path().join("root").canonicalize().unwrap(), t.path().join("outside"));+ std::fs::create_dir_all(&outside).unwrap();+ std::fs::write(outside.join("x"), CANARY).unwrap();+ std::fs::write(root.join("x"), "mine").unwrap();+ std::fs::write(root.join("sub/x"), "mine").unwrap();+ let canary_sha: String = Sha256::digest(CANARY.as_bytes()).iter().map(|b| format!("{b:02x}")).collect();+ let stop = Arc::new(AtomicBool::new(false));+ let swappers = [+ rotate_file(root.clone(), outside.clone(), stop.clone()),+ // `sub/x` stays a real file; `sub` itself turns into a symlink to the outside folder+ swap_folder(root.clone(), outside.clone(), stop.clone()),+ ];+ let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();+ let seen = rt.block_on(async {+ let a = run_readers(&root, "x", &canary_sha, 400).await;+ let b = run_readers(&root, "sub/x", &canary_sha, 400).await;+ (a, b)+ });+ stop.store(true, Ordering::Relaxed);+ for s in swappers {+ s.join().unwrap();+ }+ // Not a requirement, just that the race ran both ways+ eprintln!("share_file read the real file {} of 400 times at x, {} at sub/x", seen.0, seen.1);+ let _ = done_tx.send(());+ });+ match done_rx.recv_timeout(std::time::Duration::from_secs(120)) {+ Ok(()) => {}+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => panic!("a reader blocked (a FIFO?) for 120 s"),+ // The thread panicked: an assertion above failed+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => panic!("a reader read the host file (see the panic above)"),+ }+}diff --git a/src/server/sse.rs b/src/server/sse.rsindex d0f49bda..9bb59541 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -58,7 +58,7 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {| E::ToolCallCompleted { .. }| E::Activity { .. } => Vec::new(),// Never broadcast: the turn's stall watchdog and spend meter take them- E::Progress | E::UsageSoFar { .. } => Vec::new(),+ E::Progress | E::UsageSoFar { .. } | E::WaitingForRoom { .. } | E::RoomTaken => Vec::new(),E::ApprovalRequired { id, .. } | E::ApprovalWithdrawn { id, .. } => vec![Owner::Approval(id.clone())],E::TurnComplete { kwant_id, .. } => contexts([kwant_id]),E::TurnStarted { kwant_id, context_id, thread_id, .. }@@ -229,13 +229,15 @@ mod tests {E::ToolCallPending { id: s("x"), name: s("x"), args: json!({}) },E::ToolCallCompleted { id: s("x"), result: json!({}) },E::Progress,+ E::WaitingForRoom { reason: s("vm_busy"), position: 1, slots: 2 },+ E::RoomTaken,E::UsageSoFar { fresh: 1 },E::ApprovalRequired { id: s("a"), tool_name: s("x"), details: json!({}) },E::ApprovalWithdrawn { id: s("a"), answered_via: None, outcome: None },E::TurnComplete { tokens: 1, duration_ms: 1, kwant_id: Some(s("k")), profile_id: None },E::TurnStarted { kwant_id: s("k"), context_id: Some(s("c")), turn_id: None, thread_id: None },E::TurnEnded { kwant_id: s("k"), context_id: None, outcome: s("completed"), turn_id: None, thread_id: None, quiet: false },- E::TurnQueued { turn_id: s("x"), kwant_id: s("k"), context_id: None, thread_id: None, position: 1, reason: s("x") },+ E::TurnQueued { turn_id: s("x"), kwant_id: s("k"), context_id: None, thread_id: None, position: 1, reason: s("x"), slots: None },E::ThreadUpdated { thread: json!({"id": "th", "kwant_id": "k"}) },E::DelegationUpdated { delegation: json!({"id": "d", "lead_kwant_id": "k", "thread_id": "th"}) },E::MessageAdded { message: json!({"id": "m", "channel_id": "c"}) },@@ -340,6 +342,8 @@ mod tests {| E::ToolCallPending { .. }| E::ToolCallCompleted { .. }| E::Progress+ | E::WaitingForRoom { .. }+ | E::RoomTaken| E::UsageSoFar { .. }| E::ApprovalRequired { .. }| E::ApprovalWithdrawn { .. }@@ -401,7 +405,7 @@ mod tests {#[test]fn every_event_is_placed_in_a_space_or_is_global() {// Only ever sent inside a turn; bare, they are dropped from scoped streams on purpose- let turn_only = ["TextDelta", "ThinkingDelta", "ToolCallPending", "ToolCallCompleted", "Progress", "UsageSoFar", "activity"];+ let turn_only = ["TextDelta", "ThinkingDelta", "ToolCallPending", "ToolCallCompleted", "Progress", "WaitingForRoom", "RoomTaken", "UsageSoFar", "activity"];for e in samples() {let t = wire_type(&e);if turn_only.contains(&t.as_str()) && !matches!(e, RuntimeEvent::Scoped { .. }) {diff --git a/src/server/turns.rs b/src/server/turns.rsindex b58723d0..f5a0d41f 100644--- a/src/server/turns.rs+++ b/src/server/turns.rs@@ -191,6 +191,14 @@ impl TurnRegistry {self.lock().turns.insert(turn.turn_id.clone(), turn);}+ /// Marks a known turn "queued" or "running" again (an isolated reply waiting for the VM), keeping+ /// when it started.+ pub fn set_turn_state(&self, turn_id: &str, state: &str) {+ if let Some(t) = self.lock().turns.get_mut(turn_id) {+ t.state = state.into();+ }+ }+pub fn end_turn(&self, turn_id: &str) {let mut inner = self.lock();inner.turns.remove(turn_id);@@ -344,6 +352,7 @@ impl TurnRegistry {thread_id: tag.thread_id.clone(),position: rx.position,reason: rx.reason.into(),+ slots: None,});tokio::select! {slot = rx.rx => slot.ok(),@@ -352,6 +361,40 @@ impl TurnRegistry {}}+/// A turn's stall watchdog: silence for longer than the limit stops the turn, except while a+/// tool runs or while the turn waits for a spot in the VM ([`RuntimeEvent::WaitingForRoom`]),+/// which isn't the model's silence. Any event restarts the clock.+#[derive(Debug, Clone)]+pub struct StallClock {+ limit: Option<Duration>,+ last: tokio::time::Instant,+ tools: usize,+ waiting: bool,+}++impl StallClock {+ /// `limit` `None`: never stops the turn.+ pub fn new(limit: Option<Duration>, now: tokio::time::Instant) -> Self {+ Self { limit, last: now, tools: 0, waiting: false }+ }++ pub fn saw(&mut self, e: &RuntimeEvent, now: tokio::time::Instant) {+ self.last = now;+ match e {+ RuntimeEvent::ToolCallPending { .. } => self.tools += 1,+ RuntimeEvent::ToolCallCompleted { .. } => self.tools = self.tools.saturating_sub(1),+ RuntimeEvent::WaitingForRoom { .. } => self.waiting = true,+ RuntimeEvent::RoomTaken => self.waiting = false,+ _ => {}+ }+ }++ /// When the turn counts as stalled, if nothing else arrives; `None` while it can't stall.+ pub fn deadline(&self) -> Option<tokio::time::Instant> {+ self.limit.filter(|_| self.tools == 0 && !self.waiting).map(|d| self.last + d)+ }+}+/// One turn's place under the caps; frees it on drop.pub struct Slot {limiter: Limiter,@@ -503,6 +546,28 @@ impl Limiter {#[cfg(test)]mod tests {+ #[test]+ fn waiting_for_a_spot_in_the_vm_is_never_a_stall() {+ use crate::drivers::events::RuntimeEvent as E;+ let limit = std::time::Duration::from_secs(120);+ let t0 = tokio::time::Instant::now();+ let mut c = super::StallClock::new(Some(limit), t0);+ assert_eq!(c.deadline(), Some(t0 + limit));+ // Queued behind two other isolated replies: no deadline however long it waits+ c.saw(&E::WaitingForRoom { reason: "vm_busy".into(), position: 1, slots: 2 }, t0);+ assert_eq!(c.deadline(), None);+ // It gets its spot 10 minutes later: the clock starts from then, not from the queueing+ let t1 = t0 + std::time::Duration::from_secs(600);+ c.saw(&E::RoomTaken, t1);+ assert_eq!(c.deadline(), Some(t1 + limit));+ // A running tool still holds the clock, and the watchdog off stays off+ c.saw(&E::ToolCallPending { id: "t".into(), name: "Bash".into(), args: serde_json::json!({}) }, t1);+ assert_eq!(c.deadline(), None);+ c.saw(&E::ToolCallCompleted { id: "t".into(), result: serde_json::json!({}) }, t1);+ assert_eq!(c.deadline(), Some(t1 + limit));+ assert_eq!(super::StallClock::new(None, t0).deadline(), None);+ }+#[test]fn usage_of_sums_a_bots_running_turns_with_a_purpose() {let reg = super::TurnRegistry::default();diff --git a/src/teams/discover.rs b/src/teams/discover.rsindex 79a7c9cc..bea236c9 100644--- a/src/teams/discover.rs+++ b/src/teams/discover.rs@@ -16,7 +16,7 @@use super::presets::{self, Preset};use serde::Serialize;use std::collections::{BTreeMap, BTreeSet, HashMap};-use std::path::{Path, PathBuf};+use std::path::Path;use std::time::{Duration, Instant};/// D7: paths counted for file-count signals.@@ -469,32 +469,45 @@ pub fn parse_tree(out: &[u8]) -> Vec<Entry> {/// name at any depth, goes [`MAX_DEPTH`] folders down, lists regular files only, in name order/// (D-F10). Unreadable folders are skipped. Stops at [`MAX_LISTED`] files or `deadline`.pub fn walk(root: &Path, deadline: Instant) -> Listing {+ use crate::sandbox::safe_fs::{Dir, Kind};let mut out = Listing::default();- let mut stack: Vec<(PathBuf, String, usize)> = vec![(root.to_path_buf(), String::new(), 0)];- while let Some((dir, rel, depth)) = stack.pop() {+ // Every folder is reached from its parent's descriptor with `openat(…, O_NOFOLLOW)` (S-8): a+ // folder the bot swaps for a symlink mid-walk is refused, never listed through. A subfolder+ // is opened only when its turn comes, so a wide folder doesn't hold a descriptor per sibling.+ let Ok(top) = Dir::open(root) else { return out };+ let mut stack: Vec<(std::rc::Rc<Dir>, Option<std::ffi::OsString>, String, usize)> = vec![(std::rc::Rc::new(top), None, String::new(), 0)];+ while let Some((parent, name, rel, depth)) = stack.pop() {if Instant::now() >= deadline {out.time = true;break;}- let Ok(list) = std::fs::read_dir(&dir) else { continue };- let mut items: Vec<(String, std::fs::DirEntry)> = list.flatten().map(|e| (e.file_name().to_string_lossy().into_owned(), e)).collect();+ let dir = match name {+ None => parent,+ Some(n) => match parent.open_dir(Path::new(&n)) {+ Ok(d) => std::rc::Rc::new(d),+ Err(_) => continue,+ },+ };+ let Ok(list) = dir.list() else { continue };+ let mut items: Vec<(String, crate::sandbox::safe_fs::Entry)> = list.into_iter().map(|e| (e.name.to_string_lossy().into_owned(), e)).collect();items.sort_by(|a, b| a.0.cmp(&b.0));let mut subdirs = Vec::new();for (name, e) in items {- // DirEntry::file_type and ::metadata don't follow symlinks- let Ok(t) = e.file_type() else { continue };let path = if rel.is_empty() { name.clone() } else { format!("{rel}/{name}") };- if t.is_dir() {- if depth < MAX_DEPTH && !SKIP_DIRS.contains(&name.as_str()) {- subdirs.push((e.path(), path, depth + 1));+ match e.kind {+ Kind::Dir => {+ if depth < MAX_DEPTH && !SKIP_DIRS.contains(&name.as_str()) {+ subdirs.push((dir.clone(), Some(e.name), path, depth + 1));+ }}- } else if t.is_file() {- if out.entries.len() >= MAX_LISTED {- out.cut = true;- return out;+ Kind::File => {+ if out.entries.len() >= MAX_LISTED {+ out.cut = true;+ return out;+ }+ out.entries.push(Entry { path, size: e.len, blob: None });}- let size = e.metadata().map(|m| m.len()).unwrap_or(u64::MAX);- out.entries.push(Entry { path, size, blob: None });+ Kind::Symlink | Kind::Other => {}}}stack.extend(subdirs.into_iter().rev());@@ -517,24 +530,10 @@ pub fn read_file(root: &Path, rel: &str, max: u64) -> Result<Vec<u8>, ReadError>if !keep_path(rel) {return Err(ReadError::Unreadable);}- let mut at = root.to_path_buf();- let parts: Vec<&str> = rel.split('/').collect();- for (i, p) in parts.iter().enumerate() {- at.push(p);- let m = std::fs::symlink_metadata(&at).map_err(|_| ReadError::Unreadable)?;- let last = i + 1 == parts.len();- if (last && !m.file_type().is_file()) || (!last && !m.file_type().is_dir()) {- return Err(ReadError::Unreadable);- }- }- let mut o = std::fs::OpenOptions::new();- o.read(true);- #[cfg(unix)]- {- use std::os::unix::fs::OpenOptionsExt;- o.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);- }- let f = o.open(&at).map_err(|_| ReadError::Unreadable)?;+ // Walked from the folder's descriptor with `openat(…, O_NOFOLLOW)` on every part and an+ // `fstat` regular-file check on the last (S-8): no check-then-open race by path+ let dir = crate::sandbox::safe_fs::Dir::open(root).map_err(|_| ReadError::Unreadable)?;+ let f = dir.open_file(Path::new(rel)).map_err(|_| ReadError::Unreadable)?;let m = f.metadata().map_err(|_| ReadError::Unreadable)?;if !m.file_type().is_file() {return Err(ReadError::Unreadable);diff --git a/src/tools/mod.rs b/src/tools/mod.rsindex 23ad130c..5eb7dc67 100644--- a/src/tools/mod.rs+++ b/src/tools/mod.rs@@ -77,12 +77,17 @@ impl ToolRunner {/// The working folder of a bot outside any team: `<space data>/bot-workspaces/<kwant id>`,/// created on first use. Its file tools write there without asking.pub fn bot_workspace(space_data_dir: &std::path::Path, kwant_id: &str) -> PathBuf {- let safe: String = kwant_id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();- let dir = space_data_dir.join("bot-workspaces").join(safe);+ let dir = bot_workspace_path(space_data_dir, kwant_id);let _ = std::fs::create_dir_all(&dir);dir}+/// [`bot_workspace`]'s path, without creating it.+pub fn bot_workspace_path(space_data_dir: &std::path::Path, kwant_id: &str) -> PathBuf {+ let safe: String = kwant_id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();+ space_data_dir.join("bot-workspaces").join(safe)+}+/// The folder a team works in, as [`resolve_or_prepare_workspace`] picks it, without creating or/// cloning anything: its own path (`~/` expanded), its repo's clone, else the space's shared folder.pub fn team_workspace_path(base_data_dir: &std::path::Path, team_name: &str, workspace_path: Option<&str>, repo_url: Option<&str>) -> PathBuf {@@ -116,8 +121,9 @@ pub async fn resolve_or_prepare_workspace(let git_dir = target_dir.join(".git");if !git_dir.exists() {let _ = std::fs::create_dir_all(&target_dir);- let clone_res = tokio::process::Command::new("git")- .arg("clone")+ // The shared host git rules (D4c); `--` so an address can't be read as an option+ let clone_res = crate::server::dev::git::host_git_command("git")+ .args(["-c", "protocol.ext.allow=never", "clone", "--"]).arg(repo.trim()).arg(&target_dir).output()diff --git a/src/tools/shell.rs b/src/tools/shell.rsindex d086c507..55628a55 100644--- a/src/tools/shell.rs+++ b/src/tools/shell.rs@@ -100,9 +100,9 @@ pub fn git_bash() -> Option<std::path::PathBuf> {return Some(hit.clone());}let found = {- let exec_path = std::process::Command::new("git")+ // Through the one git helper (D4c): no system config, hooks or stray GIT_* here either+ let exec_path = crate::server::dev::git::host_git_command_blocking("git").arg("--exec-path")- .stdin(Stdio::null()).stderr(Stdio::null()).output().ok()diff --git a/tests/agents_in_vm_adversarial_test.rs b/tests/agents_in_vm_adversarial_test.rsnew file mode 100644index 00000000..8772e9c6--- /dev/null+++ b/tests/agents_in_vm_adversarial_test.rs@@ -0,0 +1,531 @@+//! Test plan #1: the port of `proto/agents-in-vm/adversarial.sh` to the shipped code. A real+//! bot container (the `kwnt-agent` image, started by `AgentVm::prepare_turn`), the real broker+//! and real Claude Code, against a scripted mock model on 127.0.0.1. `probe.sh` tries the three+//! attacks (read a host sign-in, read the real token, reach the network, plus IPv6, UDP and DNS):+//!+//! * A. in a plain shell in the container;+//! * B. through the agent's own Bash tool, mid-turn, while the broker holds the real key;+//! * C. positive control: the real key reached the mock upstream, the stand-in never did;+//! * D. self-test: with a planted token the probe does report a leak;+//! * E. (#9) `docker inspect` of the running container matches the allow-list;+//! * F. (#14) a file the container writes belongs to this computer's user;+//! * G. (#12) symlinks the bot makes in the container never lead a host reader outside;+//! * H. (#16) `--resume` carries the conversation into the next turn through the broker;+//! * I. (#17) the real key is in no log, no `docker inspect` and no process list.+//!+//! Needs Docker and the agent image (`docker build -f docker/agent.Dockerfile --build-arg+//! CLAUDE_VERSION=… -t kwnt-agent:v1-claude-…`). Without them it says so and passes, unless+//! `KWNT_AGENT_TEST_REQUIRE=1` (QA runs) makes that a failure.+#![cfg(target_os = "linux")]++use axum::{body::Bytes, http::HeaderMap, response::IntoResponse, Router};+use kwnt::sandbox::agent_vm::{+ broker::{BrokerConfig, Credential, Secret},+ image_tag, AgentVm, TurnRequest, DUMMY_API_KEY,+};+use kwnt::config::AgentsInVmConfig;+use serde_json::{json, Value};+use std::os::unix::fs::MetadataExt;+use std::path::Path;+use std::process::Command as StdCommand;+use std::sync::{Arc, Mutex};+use tokio::process::Command;++const PROBE: &str = include_str!("../proto/agents-in-vm/probe.sh");++#[derive(Default, Clone)]+struct Upstream {+ /// The credential each model call arrived with.+ auth: Arc<Mutex<Vec<String>>>,+ /// Bash tool output the CLI sent back.+ tool_results: Arc<Mutex<Vec<String>>>,+ /// How many messages each model call carried, and its last user text.+ calls: Arc<Mutex<Vec<(usize, String)>>>,+}++fn text_of(v: &Value) -> String {+ match v {+ Value::String(s) => s.clone(),+ Value::Array(a) => a.iter().map(text_of).collect(),+ Value::Object(o) if o.get("type").and_then(Value::as_str) == Some("text") => o["text"].as_str().unwrap_or_default().to_string(),+ Value::Object(o) if o.get("type").and_then(Value::as_str) == Some("tool_result") => text_of(o.get("content").unwrap_or(&Value::Null)),+ _ => String::new(),+ }+}++/// A scripted Messages API: a tool result is answered "done"; `RUN: <cmd>` with Bash offered is+/// answered with a Bash call; anything else with a line of text. Always SSE when asked.+async fn messages(up: Upstream, headers: HeaderMap, body: Bytes) -> axum::response::Response {+ let cred = headers+ .get("x-api-key")+ .or_else(|| headers.get("authorization"))+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .to_string();+ up.auth.lock().unwrap().push(cred);+ let req: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);+ // The CLI may end the list with a `system` message of its own (the environment); the turn+ // is the last `user` message+ let last = req["messages"].as_array().and_then(|m| m.iter().rev().find(|m| m["role"] == "user")).cloned().unwrap_or(Value::Null);+ let blocks = match &last["content"] {+ Value::Array(a) => a.clone(),+ other => vec![other.clone()],+ };+ let results: Vec<String> = blocks.iter().filter(|b| b["type"] == "tool_result").map(text_of).collect();+ let prompt: String = blocks.iter().filter(|b| b["type"] != "tool_result").map(text_of).collect();+ let n = req["messages"].as_array().map_or(0, |m| m.iter().filter(|m| m["role"] != "system").count());+ up.calls.lock().unwrap().push((n, prompt.clone()));+ let offers_bash = req["tools"].as_array().is_some_and(|t| t.iter().any(|t| t["name"] == "Bash"));+ if std::env::var_os("KWNT_AGENT_TEST_DUMP").is_some() {+ let names: Vec<String> = req["tools"].as_array().map(|t| t.iter().map(|t| t["name"].as_str().unwrap_or("?").to_string()).collect()).unwrap_or_default();+ eprintln!("MOCK call: messages={n} bash={offers_bash} tools={names:?} last_role={} prompt={:?}", last["role"], prompt.chars().take(400).collect::<String>());+ }+ let tool = if !results.is_empty() {+ up.tool_results.lock().unwrap().extend(results);+ None+ } else if offers_bash && prompt.contains("RUN:") {+ let cmd = prompt.split_once("RUN:").unwrap().1.trim().lines().next().unwrap_or("").to_string();+ Some(json!({"command": cmd, "description": "adversarial probe", "timeout": 300000}))+ } else {+ None+ };+ let model = req["model"].as_str().unwrap_or("mock").to_string();+ let usage = json!({"input_tokens": 10, "output_tokens": 5});+ let mut ev = vec![json!({"type": "message_start", "message": {"id": "msg_mock", "type": "message", "role": "assistant",+ "model": model, "content": [], "stop_reason": null, "stop_sequence": null, "usage": usage}})];+ let stop = if let Some(input) = &tool {+ ev.push(json!({"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "toolu_mockprobe0001", "name": "Bash", "input": {}}}));+ ev.push(json!({"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": input.to_string()}}));+ "tool_use"+ } else {+ ev.push(json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}));+ ev.push(json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "done"}}));+ "end_turn"+ };+ ev.push(json!({"type": "content_block_stop", "index": 0}));+ ev.push(json!({"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": null}, "usage": {"output_tokens": 5}}));+ ev.push(json!({"type": "message_stop"}));+ if req["stream"] != true {+ let content = match tool {+ Some(input) => json!([{"type": "tool_use", "id": "toolu_mockprobe0001", "name": "Bash", "input": input}]),+ None => json!([{"type": "text", "text": "done"}]),+ };+ return axum::Json(json!({"id": "msg_mock", "type": "message", "role": "assistant", "model": model, "content": content,+ "stop_reason": stop, "stop_sequence": null, "usage": usage}))+ .into_response();+ }+ let sse: String = ev.iter().map(|e| format!("event: {}\ndata: {e}\n\n", e["type"].as_str().unwrap())).collect();+ ([("content-type", "text/event-stream")], sse).into_response()+}++async fn start_upstream(up: Upstream) -> String {+ let app = Router::new().fallback(move |headers: HeaderMap, body: Bytes| messages(up.clone(), headers, body));+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = l.local_addr().unwrap();+ tokio::spawn(async move { axum::serve(l, app).await.unwrap() });+ format!("http://{addr}")+}++fn docker_ok() -> bool {+ StdCommand::new("docker").args(["image", "inspect", &image_tag()]).output().is_ok_and(|o| o.status.success())+}++/// Removes the test's container whatever happens.+struct Cleanup(String);+impl Drop for Cleanup {+ fn drop(&mut self) {+ let _ = StdCommand::new("docker").args(["rm", "-f", &self.0]).output();+ }+}++async fn probe(container: &str, script: &Path, host_paths: &str, extra: &[&str], pre: &str) -> String {+ let mut c = Command::new("docker");+ c.args(["exec", "-e", &format!("HOST_PATHS={host_paths}")]);+ for e in extra {+ c.args(["-e", e]);+ }+ let out = c.arg(container).args(["sh", "-c", &format!("{pre}bash {}", script.display())]).output().await.unwrap();+ String::from_utf8_lossy(&out.stdout).into_owned()+}++#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn the_three_attacks_fail_in_a_shell_and_in_the_agents_own_bash() {+ if !docker_ok() {+ assert!(std::env::var("KWNT_AGENT_TEST_REQUIRE").is_err(), "Docker or the agent image {} is missing", image_tag());+ eprintln!("skipped: needs Docker and the agent image {}", image_tag());+ return;+ }+ let data = tempfile::tempdir().unwrap();+ let work = tempfile::tempdir().unwrap();+ let up = Upstream::default();+ let mut cfg = BrokerConfig::new(data.path().join("broker.log"));+ cfg.anthropic_origin = start_upstream(up.clone()).await;+ cfg.oauth_token_url = format!("{}/v1/oauth/token", cfg.anthropic_origin);+ let vm = AgentVm::with_parts(data.path(), cfg, Some(image_tag()), AgentsInVmConfig::default(), None);++ // Every real credential in this test carries the probe's marker; the container must never see one+ let real = format!("sk-ant-api03-{}{}-{}", "REAL", "CANARY", uuid::Uuid::new_v4().simple());+ let turn = vm+ .prepare_turn(TurnRequest {+ bot_id: "adversarial".into(),+ folder: Some(work.path().to_path_buf()),+ credential: Credential::ApiKey(Secret::new(&real)),+ credential_home: None,+ kwnt_origin: None,+ })+ .await+ .unwrap_or_else(|r| panic!("the turn didn't start: {r:?}"));+ let _cleanup = Cleanup(turn.container().to_string());+ let script = turn.workdir().join("probe.sh");+ std::fs::write(&script, PROBE).unwrap();+ let home = dirs::home_dir().unwrap();+ let host_paths = [+ home.join(".claude/.credentials.json"),+ home.join(".codex/auth.json"),+ home.join(".grok/auth.json"),+ data.path().join("broker.log"),+ data.path().join("kwnt.db"),+ ]+ .iter()+ .map(|p| p.display().to_string())+ .collect::<Vec<_>>()+ .join(" ");++ // A. A plain shell in the container+ let a = probe(turn.container(), &script, &host_paths, &[], "").await;+ assert!(a.lines().any(|l| l == "PROBE_LEAKS=0"), "shell probe:\n{a}");++ // B. The agent's own Bash tool, mid-turn+ let mut claude = Command::new("claude");+ claude.args(["--model", "haiku", "--permission-mode", "default", "--allowedTools", "Bash", "--output-format", "stream-json", "--verbose", "-p"]);+ claude.arg(format!("RUN: HOST_PATHS='{host_paths}' bash {}", script.display()));+ let mut cmd = turn.wrap(&claude);+ cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).kill_on_drop(true);+ let child = cmd.spawn().unwrap();+ // I, part 1: the process list while the turn runs (after its first model call)+ for _ in 0..600 {+ if !up.auth.lock().unwrap().is_empty() {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;+ }+ let ps = StdCommand::new("ps").args(["-eww", "-o", "args"]).output().unwrap();+ let ps = String::from_utf8_lossy(&ps.stdout).into_owned();+ let out = tokio::time::timeout(std::time::Duration::from_secs(420), child.wait_with_output()).await.expect("claude finished").unwrap();+ let stdout = String::from_utf8_lossy(&out.stdout);+ let results = up.tool_results.lock().unwrap().join("\n");+ assert!(results.lines().any(|l| l.trim() == "PROBE_LEAKS=0"), "agent probe:\n{results}\nclaude said:\n{stdout}\n{}", String::from_utf8_lossy(&out.stderr));+ assert!(!stdout.contains(&real), "the real key never reaches the CLI's output");++ // C. Positive control: the real key reached the upstream, the stand-in never did+ let auth = up.auth.lock().unwrap().clone();+ assert!(auth.len() >= 2, "a tool turn is at least two model calls: {auth:?}");+ assert!(auth.iter().all(|a| a == &real), "only the real key reached the upstream ({} calls)", auth.len());+ assert!(!auth.iter().any(|a| a.contains(DUMMY_API_KEY)));+ let log = std::fs::read_to_string(data.path().join("broker.log")).unwrap();+ assert!(!log.contains(&real), "the broker log holds no secret");++ // D. Self-test: a planted token is caught, so the probe can fail+ let planted = format!("PLANTED={real}");+ let d = probe(turn.container(), &script, &host_paths, &[&planted], "echo \"$PLANTED\" > /tmp/planted; ").await;+ assert!(d.lines().any(|l| l.starts_with("PROBE_LEAKS=") && l != "PROBE_LEAKS=0"), "self-test missed the planted token:\n{d}");++ // E. The running container is configured as the allow-list says+ let inspect = StdCommand::new("docker").args(["inspect", turn.container()]).output().unwrap();+ let inspect_text = String::from_utf8_lossy(&inspect.stdout).into_owned();+ let info: Value = serde_json::from_str::<Value>(&inspect_text).unwrap()[0].clone();+ let hc = &info["HostConfig"];+ assert_eq!(hc["NetworkMode"], "none", "{hc}");+ assert_eq!(hc["CapDrop"], json!(["ALL"]), "{hc}");+ assert!(hc["CapAdd"].is_null() || hc["CapAdd"] == json!([]), "{hc}");+ assert_eq!(hc["ReadonlyRootfs"], true);+ assert_eq!(hc["Privileged"], false);+ assert!(hc["SecurityOpt"].as_array().unwrap().iter().any(|o| o.as_str().unwrap().starts_with("no-new-privileges")), "{hc}");+ assert_eq!(hc["Memory"], json!(AgentsInVmConfig::default().memory_mb * 1024 * 1024));+ let user = info["Config"]["User"].as_str().unwrap();+ assert!(!user.is_empty() && !user.starts_with("0:") && user != "0" && user != "root", "the container runs as {user}");+ let ids = format!("{}:{}", unsafe { libc::getuid() }, unsafe { libc::getgid() });+ assert_eq!(user, ids, "the container runs as this computer's user");+ let mounts = info["Mounts"].as_array().unwrap();+ assert_eq!(mounts.len(), 3, "exactly three mounts: {mounts:?}");+ let by_dst = |d: &str| mounts.iter().find(|m| m["Destination"] == d).unwrap_or_else(|| panic!("no {d} mount: {mounts:?}"));+ assert_eq!(by_dst(&turn.workdir().display().to_string())["RW"], true);+ assert_eq!(by_dst("/home/agent")["RW"], true);+ assert_eq!(by_dst("/run/kwnt")["RW"], false, "the broker's folder is read-only");+ for m in mounts {+ let src = m["Source"].as_str().unwrap();+ assert!(!src.contains("docker.sock") && src != "/var/run" && src != "/run", "{src}");+ assert_eq!(m["Type"], "bind");+ }++ // F. A file the container writes is this computer's user's, with an ordinary mode+ let made = turn.workdir().join("from-the-container.txt");+ let st = StdCommand::new("docker").args(["exec", turn.container(), "sh", "-c"]).arg(format!("echo hi > '{}'", made.display())).status().unwrap();+ assert!(st.success());+ let meta = std::fs::metadata(&made).unwrap();+ assert_eq!((meta.uid(), meta.gid()), (unsafe { libc::getuid() }, unsafe { libc::getgid() }));+ assert_eq!(meta.mode() & 0o600, 0o600, "the person can read and write it: {:o}", meta.mode());++ // G. Symlinks made in the container lead no host reader outside the folder+ let canary_dir = data.path().join("canary-dir");+ std::fs::create_dir_all(&canary_dir).unwrap();+ let canary = format!("CANARY-{}", uuid::Uuid::new_v4().simple());+ std::fs::write(canary_dir.join("secret.txt"), &canary).unwrap();+ std::fs::write(data.path().join("canary.txt"), &canary).unwrap();+ let links = format!(+ "cd '{w}' && ln -s '{f}' link-file && ln -s '{d}' link-dir && mkdir -p .git sub && ln -s '{f}' .git/HEAD && ln -s ../link-dir sub/up",+ w = turn.workdir().display(),+ f = data.path().join("canary.txt").display(),+ d = canary_dir.display()+ );+ assert!(StdCommand::new("docker").args(["exec", turn.container(), "sh", "-c", &links]).status().unwrap().success());+ let listing = kwnt::teams::discover::walk(turn.workdir(), std::time::Instant::now() + std::time::Duration::from_secs(10));+ let mut read = String::new();+ for e in &listing.entries {+ assert!(!e.path.starts_with("link-dir") && !e.path.starts_with("sub/up/"), "listed through a symlink: {}", e.path);+ if let Ok(b) = kwnt::teams::discover::read_file(turn.workdir(), &e.path, 1 << 20) {+ read.push_str(&String::from_utf8_lossy(&b));+ }+ }+ for rel in ["link-file", "link-dir/secret.txt", ".git/HEAD", "sub/up/secret.txt"] {+ if let Ok(b) = kwnt::teams::discover::read_file(turn.workdir(), rel, 1 << 20) {+ read.push_str(&String::from_utf8_lossy(&b));+ }+ let d = kwnt::sandbox::safe_fs::Dir::open(turn.workdir()).unwrap();+ assert!(d.open_file(Path::new(rel)).is_err(), "safe_fs opened {rel}");+ }+ assert!(!read.contains(&canary), "a host reader followed a symlink out of the folder");++ // H. --resume: the next turn carries the conversation, through the same broker+ let session = stdout+ .lines()+ .filter_map(|l| serde_json::from_str::<Value>(l).ok())+ .find_map(|v| v["session_id"].as_str().map(String::from))+ .expect("the first turn names its session");+ let before = up.calls.lock().unwrap().len();+ let mut again = Command::new("claude");+ again.args(["--model", "haiku", "--output-format", "stream-json", "--verbose", "--resume", &session, "-p", "SECOND turn"]);+ let mut cmd = turn.wrap(&again);+ cmd.stdin(std::process::Stdio::null()).kill_on_drop(true);+ let out2 = tokio::time::timeout(std::time::Duration::from_secs(300), cmd.output()).await.expect("resumed turn finished").unwrap();+ let calls = up.calls.lock().unwrap().clone();+ let resumed = calls[before..].iter().find(|(_, p)| p.contains("SECOND turn")).unwrap_or_else(|| {+ panic!("the resumed turn reached no model: {calls:?}\n{}", String::from_utf8_lossy(&out2.stderr))+ });+ assert!(resumed.0 >= 3, "the resumed turn carries the first one's messages: {calls:?}");++ // I, part 2: the key is in no log, `docker inspect`, process list or CLI home+ assert!(!ps.contains(&real), "the process list holds the key");+ assert!(!inspect_text.contains(&real), "docker inspect holds the key");+ let logs = StdCommand::new("docker").args(["logs", turn.container()]).output().unwrap();+ assert!(!String::from_utf8_lossy(&logs.stdout).contains(&real) && !String::from_utf8_lossy(&logs.stderr).contains(&real));+ let grep = StdCommand::new("grep").args(["-rlF", &real]).arg(data.path()).arg(turn.workdir()).output().unwrap();+ assert!(grep.stdout.is_empty(), "the key was written to {}", String::from_utf8_lossy(&grep.stdout));++ drop(turn);+ vm.remove_containers(|_| true).await;+}++fn running(container: &str) -> bool {+ StdCommand::new("docker")+ .args(["inspect", "-f", "{{.State.Running}}", container])+ .output()+ .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).trim() == "true")+}++/// Every process's command line in `container` (the image has no `ps`).+fn processes(container: &str) -> String {+ let list = r#"for p in /proc/[0-9]*; do tr '\0' ' ' < "$p/cmdline" 2>/dev/null; echo; done"#;+ let out = StdCommand::new("docker").args(["exec", container, "sh", "-c", list]).output().unwrap();+ String::from_utf8_lossy(&out.stdout).into_owned()+}++fn size(p: &Path) -> u64 {+ std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)+}++/// M3 (R-9, S-9): what the bot starts with `setsid` leaves the turn's process group, so the+/// group's TERM at the turn's end misses it. While another turn uses the container it keeps+/// running; after the container's last turn the container is removed (after a 1 s grace), so+/// nothing the bot started runs on and its file stops growing.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn nothing_the_bot_started_outlives_the_containers_last_turn() {+ if !docker_ok() {+ assert!(std::env::var("KWNT_AGENT_TEST_REQUIRE").is_err(), "Docker or the agent image {} is missing", image_tag());+ eprintln!("skipped: needs Docker and the agent image {}", image_tag());+ return;+ }+ let data = tempfile::tempdir().unwrap();+ let work = tempfile::tempdir().unwrap();+ let vm = AgentVm::with_parts(data.path(), BrokerConfig::new(data.path().join("broker.log")), Some(image_tag()), AgentsInVmConfig::default(), None);+ let request = || TurnRequest {+ bot_id: "r9-escapees".into(),+ folder: Some(work.path().to_path_buf()),+ credential: Credential::ApiKey(Secret::new("sk-ant-api03-r9-test")),+ credential_home: None,+ kwnt_origin: None,+ };+ let first = vm.prepare_turn(request()).await.unwrap_or_else(|r| panic!("the turn didn't start: {r:?}"));+ let second = vm.prepare_turn(request()).await.unwrap_or_else(|r| panic!("the second turn didn't start: {r:?}"));+ let container = first.container().to_string();+ assert_eq!(second.container(), container, "both turns share the bot's container");+ let _cleanup = Cleanup(container.clone());+ let tick = first.workdir().join("tick");++ // The bot's escape: two processes out of every turn's process group+ let escape = format!(+ "setsid sh -c 'while :; do date >> {t}; sleep 0.2; done' </dev/null >/dev/null 2>&1 & \+ setsid sleep 3600 </dev/null >/dev/null 2>&1 &",+ t = tick.display()+ );+ assert!(StdCommand::new("docker").args(["exec", &container, "sh", "-c", &escape]).status().unwrap().success());+ tokio::time::sleep(std::time::Duration::from_millis(800)).await;+ let ps = processes(&container);+ assert!(ps.contains("sleep 3600"), "control: the escapees run\n{ps}");+ let grown = size(&tick);+ assert!(grown > 0, "control: tick grows");++ // Not the last turn: the container and what runs in it stay for the other turn+ drop(first);+ tokio::time::sleep(std::time::Duration::from_millis(2500)).await;+ assert!(running(&container), "the other turn still uses the container");+ assert!(size(&tick) > grown, "the escapee still runs while a turn uses the container");++ // The last turn: within the grace and a removal, nothing runs and tick stops+ drop(second);+ let ended = std::time::Instant::now();+ while running(&container) {+ assert!(ended.elapsed() < std::time::Duration::from_secs(15), "the container outlived its last turn");+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ eprintln!("container stopped {:?} after the last turn ended", ended.elapsed());+ // `docker rm -f` kills first and deletes after, so the record goes a moment later+ let listed = || {+ let out = StdCommand::new("docker").args(["ps", "-aq", "--filter", &format!("name=^{container}$")]).output().unwrap();+ !String::from_utf8_lossy(&out.stdout).trim().is_empty()+ };+ while listed() {+ assert!(ended.elapsed() < std::time::Duration::from_secs(15), "removed, not just stopped");+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ eprintln!("container removed {:?} after the last turn ended", ended.elapsed());+ let at_end = size(&tick);+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;+ assert_eq!(size(&tick), at_end, "tick stopped growing");+ let host_ps = StdCommand::new("ps").args(["-eo", "args"]).output().unwrap();+ assert!(!String::from_utf8_lossy(&host_ps.stdout).lines().any(|l| l.trim() == "sleep 3600"), "no escapee left on this computer");++ // The next turn gets a fresh container in the same folder+ let next = vm.prepare_turn(request()).await.unwrap_or_else(|r| panic!("the next turn didn't start: {r:?}"));+ assert!(running(next.container()));+ assert!(!processes(next.container()).contains("sleep 3600"), "nothing carried over");+ drop(next);+ vm.remove_containers(|_| true).await;+}++/// Answers each approval after `wait`, recording what it was asked.+struct Delayed {+ wait: std::time::Duration,+ answer: bool,+ asked: Arc<Mutex<Vec<String>>>,+}++#[async_trait::async_trait]+impl kwnt::mcp::ToolApprover for Delayed {+ async fn approve(&self, r: kwnt::mcp::ToolApprovalRequest) -> bool {+ self.asked.lock().unwrap().push(r.tool_name.clone());+ tokio::time::sleep(self.wait).await;+ self.answer+ }+}++/// One turn with kwnt's approval tool (`--permission-prompt-tool`), as the Claude driver runs+/// it: the Bash call goes to kwnt's permission route and back. What was asked, whether the+/// command ran, and how many model calls the broker passed.+async fn approval_turn(name: &str, answer: bool) -> (Vec<String>, bool, usize, String) {+ use kwnt::{broker::PermissionBroker, config::Config, db::Database, router::LayaRouter, server::mcp_runtime::PermissionSession, server::AppState, tools::ToolRunner};+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };+ let state = AppState::new(config.clone(), db, ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let base = format!("http://{}", listener.local_addr().unwrap());+ let router = kwnt::server::create_router(state.clone());+ tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });++ let data = tempfile::tempdir().unwrap();+ let work = tempfile::tempdir().unwrap();+ let up = Upstream::default();+ let mut cfg = BrokerConfig::new(data.path().join("broker.log"));+ cfg.anthropic_origin = start_upstream(up.clone()).await;+ cfg.oauth_token_url = format!("{}/v1/oauth/token", cfg.anthropic_origin);+ let vm = AgentVm::with_parts(data.path(), cfg, Some(image_tag()), AgentsInVmConfig::default(), None);+ let mut turn = vm+ .prepare_turn(TurnRequest {+ bot_id: format!("adversarial-{name}"),+ folder: Some(work.path().to_path_buf()),+ credential: Credential::ApiKey(Secret::new("sk-ant-api03-APPROVALTEST")),+ credential_home: None,+ kwnt_origin: Some(base.clone()),+ })+ .await+ .unwrap_or_else(|r| panic!("the turn didn't start: {r:?}"));+ let _cleanup = Cleanup(turn.container().to_string());++ let asked = Arc::new(Mutex::new(Vec::new()));+ let approver = Arc::new(Delayed { wait: std::time::Duration::from_millis(200), answer, asked: asked.clone() });+ let token = format!("tok-{name}-{}", uuid::Uuid::new_v4().simple());+ let ctx = kwnt::mcp::McpTurnContext {+ servers: vec![],+ approver,+ config_dir: tmp.path().join("mcp"),+ permission_url: Some(format!("{base}/api/mcp/permission/{token}")),+ gateway: None,+ max_tool_iterations: 8,+ smart_approvals: false,+ records: Default::default(),+ };+ state+ .mcp_sessions+ .lock()+ .await+ .insert(token, PermissionSession::new("k1".into(), "Adversarial".into(), "t1".into(), ctx.clone(), Some(turn.workdir().to_path_buf())));+ let (cfg_path, _dropped) = turn.write_mcp_config(&ctx).unwrap();++ let marker = format!("approval-marker-{name}");+ let mut claude = Command::new("claude");+ claude.args(["--model", "haiku", "--permission-mode", "default", "--output-format", "stream-json", "--verbose"]);+ claude.args(["--strict-mcp-config", "--mcp-config", &cfg_path, "--permission-prompt-tool", "mcp__kwnt__approve", "-p"]);+ claude.arg(format!("RUN: touch {marker}"));+ claude.env("MCP_TOOL_TIMEOUT", "330000").env("CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT", "330000").env("MCP_TIMEOUT", "30000");+ let mut cmd = turn.wrap(&claude);+ cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).kill_on_drop(true);+ let out = tokio::time::timeout(std::time::Duration::from_secs(420), cmd.spawn().unwrap().wait_with_output()).await.expect("claude finished").unwrap();+ let ran = turn.workdir().join(&marker).exists() || work.path().join(&marker).exists();+ let said = format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));+ let calls = up.calls.lock().unwrap().len();+ drop(turn);+ vm.remove_containers(|_| true).await;+ let asked = asked.lock().unwrap().clone();+ (asked, ran, calls, said)+}++/// QA F-1: with kwnt's approval tool on (every real Claude turn), the request carries the+/// AskUserQuestion schema, whose `metadata.properties.source` the broker once took for a fetch+/// by reference and refused. Every model call now passes, and Allow and Deny both work.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn an_approval_goes_through_kwnt_and_both_answers_work() {+ if !docker_ok() {+ assert!(std::env::var("KWNT_AGENT_TEST_REQUIRE").is_err(), "Docker or the agent image {} is missing", image_tag());+ eprintln!("skipped: needs Docker and the agent image {}", image_tag());+ return;+ }+ let (asked, ran, calls, said) = approval_turn("allow", true).await;+ assert_eq!(asked, vec!["Bash".to_string()], "the Bash call asked kwnt once:\n{said}");+ assert!(ran, "allowed: the command ran:\n{said}");+ assert!(calls >= 2, "the broker passed the call that asked and the one after the answer:\n{said}");+ let (asked, ran, calls, said) = approval_turn("deny", false).await;+ assert_eq!(asked, vec!["Bash".to_string()], "{said}");+ assert!(!ran, "denied: the command didn't run:\n{said}");+ assert!(calls >= 2, "{said}");+}diff --git a/tests/agents_in_vm_fail_closed_test.rs b/tests/agents_in_vm_fail_closed_test.rsnew file mode 100644index 00000000..23707aff--- /dev/null+++ b/tests/agents_in_vm_fail_closed_test.rs@@ -0,0 +1,208 @@+//! Test plan #10 (F-1 … F-6, F-11, D1): with "Run Claude inside the VM" on, every way the+//! isolated turn can fail is the turn's typed notice. A host `claude` (a shim that leaves a+//! marker) never starts, and the mock upstream sees nothing.+//!+//! One test function on purpose: the "Docker missing" case empties `PATH` for a moment, which+//! no other test in this binary may see.+#![cfg(target_os = "linux")]++#[path = "common/exe.rs"]+mod exe;++use axum::Router;+use kwnt::{+ db::models::Kwant,+ drivers::{cli::Isolation, CliDriver, Driver, TurnInput, TurnOutput},+ sandbox::agent_vm::{broker::BrokerConfig, image_tag, AgentVm, AgentsInVmConfig},+};+use std::path::Path;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use tempfile::{tempdir, TempDir};++fn turn(folder: Option<&Path>) -> TurnInput {+ TurnInput {+ continuity: String::new(),+ skills: String::new(),+ person: Default::default(),+ store: None,+ browser_api_url: None,+ thread_id: "t1".into(),+ kwant: Kwant {+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),+ id: "fail-closed".into(),+ name: "Ada".into(),+ title: "Lead".into(),+ persona_prompt: "p".into(),+ soul: String::new(),+ avatar_sprite: "s".into(),+ driver_type: "cli".into(),+ preferred_model: "claude".into(),+ temperature: 0.7,+ max_tokens: 1000,+ level: 1,+ turns_completed: 0,+ created_at: None,+ },+ prompt: "hi".into(),+ history: vec![],+ model_override: None,+ model: None,+ effort_level: Some("low".into()),+ team_context: None,+ workspace_dir: folder.map(Path::to_path_buf),+ sandbox_id: None,+ teammates: vec![],+ mcp: None,+ no_tools: false,+ read_only: false,+ }+}++/// A mock Anthropic that only counts what reaches it.+async fn counting_upstream() -> (String, Arc<AtomicUsize>) {+ let hits = Arc::new(AtomicUsize::new(0));+ let h = hits.clone();+ let app = Router::new().fallback(move || {+ h.fetch_add(1, Ordering::SeqCst);+ async { "{}" }+ });+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = l.local_addr().unwrap();+ tokio::spawn(async move { axum::serve(l, app).await.unwrap() });+ (format!("http://{addr}"), hits)+}++struct Case {+ shim: TempDir,+ upstream_hits: Arc<AtomicUsize>,+}++impl Case {+ fn marker(&self) -> std::path::PathBuf {+ self.shim.path().join("marker")+ }++ async fn run(&self, vm: &Arc<AgentVm>, profile_home: Option<&Path>, folder: Option<&Path>) -> TurnOutput {+ let bin = self.shim.path().join("claude").to_string_lossy().into_owned();+ let driver = CliDriver::new(Some(bin), Some("claude".into())).with_isolation(Some(Isolation {+ vm: vm.clone(),+ profile_home: profile_home.map(Path::to_path_buf),+ kwnt_origin: "http://127.0.0.1:9".into(),+ }));+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);+ let drain = tokio::spawn(async move { while rx.recv().await.is_some() {} });+ let out = driver.stream_turn(turn(folder), tx).await.expect("a refusal is a notice, not an error");+ drain.await.unwrap();+ out+ }++ /// The turn ended with `turn_isolation_failed` and `reason`, nothing ran on this computer and+ /// nothing reached the model.+ fn refused(&self, out: &TurnOutput, reason: &str, case: &str) {+ let (text, meta) = out.notice.as_ref().unwrap_or_else(|| panic!("{case}: a notice, not a reply"));+ assert!(!text.is_empty(), "{case}");+ // Every refusal reads as words, never "Something went wrong (code)" (ui-check-446 fix 4)+ assert!(!text.contains("Something went wrong"), "{case}: {text}");+ assert!(text.ends_with("Nothing ran.") || text.ends_with("then Retry.") || text.ends_with("nothing ran on this computer."), "{case}: {text}");+ if reason == "unsafe_folder" {+ assert_eq!(text.matches("Pick a project folder").count(), 1, "{case}: {text}");+ }+ assert_eq!(meta["reason"], reason, "{case}: {meta}");+ assert!(!self.marker().exists(), "{case}: host claude started");+ assert_eq!(self.upstream_hits.load(Ordering::SeqCst), 0, "{case}: the upstream was reached");+ }+}++fn sign_in(home: &Path, body: &str) {+ std::fs::create_dir_all(home).unwrap();+ std::fs::write(home.join(".credentials.json"), body).unwrap();+}++fn docker_available() -> bool {+ std::process::Command::new("docker").arg("version").output().is_ok_and(|o| o.status.success())+}++fn image_present() -> bool {+ std::process::Command::new("docker").args(["image", "inspect", &image_tag()]).output().is_ok_and(|o| o.status.success())+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn every_failure_is_a_notice_and_nothing_runs_on_this_computer() {+ let shim = tempdir().unwrap();+ exe::write_executable(shim.path().join("claude"), format!("#!/bin/sh\necho started >> {}/marker\n", shim.path().display()));+ let (origin, hits) = counting_upstream().await;+ let case = Case { shim, upstream_hits: hits };+ let tmp = tempdir().unwrap();+ let data = tmp.path().join("data");+ std::fs::create_dir_all(&data).unwrap();+ let work = tmp.path().join("projects").join("site");+ std::fs::create_dir_all(&work).unwrap();+ let mut cfg = BrokerConfig::new(data.join("broker.log"));+ cfg.anthropic_origin = origin.clone();+ cfg.oauth_token_url = format!("{origin}/v1/oauth/token");+ let vm = AgentVm::with_parts(&data, cfg.clone(), Some(image_tag()), AgentsInVmConfig::default(), None);++ let good = r#"{"claudeAiOauth":{"accessToken":"sk-ant-oat01-REALCANARY","refreshToken":"r","expiresAt":99999999999999}}"#;+ let profile = tmp.path().join("profile");+ sign_in(&profile, good);+ let docker = docker_available();+ // Without Docker every later check is never reached: the turn says Docker isn't running+ let or_docker = |code: &'static str| if docker { code } else { "docker_unavailable" };++ // F-5: no sign-in in the profile home+ let empty = tmp.path().join("empty-profile");+ std::fs::create_dir_all(&empty).unwrap();+ case.refused(&case.run(&vm, Some(&empty), Some(&work)).await, "no_credential", "no sign-in");++ // F-1: Docker missing (no `docker` on PATH)+ let path = std::env::var_os("PATH");+ std::env::set_var("PATH", tmp.path().join("no-bin"));+ let out = case.run(&vm, Some(&profile), Some(&work)).await;+ match &path {+ Some(p) => std::env::set_var("PATH", p),+ None => std::env::remove_var("PATH"),+ }+ case.refused(&out, "docker_unavailable", "docker missing");++ // F-5: a sign-in file that isn't JSON, or has no token+ for (i, bad) in ["{not json", r#"{"claudeAiOauth":{}}"#].iter().enumerate() {+ let home = tmp.path().join(format!("bad-profile-{i}"));+ sign_in(&home, bad);+ case.refused(&case.run(&vm, Some(&home), Some(&work)).await, or_docker("no_credential"), "malformed sign-in");+ }++ // S-1: the folder is the sign-in home itself, or kwnt's data folder+ case.refused(&case.run(&vm, Some(&profile), Some(&profile)).await, or_docker("unsafe_folder"), "sign-in home as folder");+ case.refused(&case.run(&vm, Some(&profile), Some(&data)).await, or_docker("unsafe_folder"), "data dir as folder");++ // F-3: the image isn't there (a tag nobody built): `preparing`, then `download_failed`+ let missing = AgentVm::with_parts(&data, cfg.clone(), Some(format!("kwnt-agent:missing-{}", uuid::Uuid::new_v4().simple())), AgentsInVmConfig::default(), None);+ case.refused(&case.run(&missing, Some(&profile), Some(&work)).await, or_docker("preparing"), "image missing");+ if docker {+ // The background setup of a test image fails at once; the next reply says so+ for _ in 0..100 {+ let out = case.run(&missing, Some(&profile), Some(&work)).await;+ let reason = out.notice.as_ref().map(|(_, m)| m["reason"].clone());+ if reason.as_ref().and_then(|r| r.as_str()) != Some("preparing") {+ case.refused(&out, "download_failed", "image setup failed");+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ }++ // F-2: kwnt's broker can't open its socket (the VM's own folder is a file)+ if docker && image_present() {+ let blocked = tmp.path().join("blocked-data");+ std::fs::create_dir_all(&blocked).unwrap();+ std::fs::write(blocked.join("agent-vm"), "not a folder").unwrap();+ let vm = AgentVm::with_parts(&blocked, cfg.clone(), Some(image_tag()), AgentsInVmConfig::default(), None);+ case.refused(&case.run(&vm, Some(&profile), Some(&work)).await, "relay_down", "broker down");+ vm.remove_containers(|_| true).await;+ } else {+ eprintln!("broker-down case skipped: needs Docker and {}", image_tag());+ }+ // A missing folder is never swapped for one on this computer: the shim still never ran+ assert!(!case.marker().exists());+}diff --git a/tests/agents_in_vm_host_cli_test.rs b/tests/agents_in_vm_host_cli_test.rsnew file mode 100644index 00000000..63795207--- /dev/null+++ b/tests/agents_in_vm_host_cli_test.rs@@ -0,0 +1,178 @@+//! Test plan #20 (D4, S-12): a folder an isolated Claude turn used may hold settings, hooks or+//! scripts a bot wrote from inside the VM. On this computer Codex and Grok never start in it+//! (equal, inside or holding it) and Claude starts with only the person's own settings.+#![cfg(unix)]++#[path = "common/exe.rs"]+mod exe;++use kwnt::{+ db::{models::Kwant, Database},+ drivers::{CliDriver, Driver, TurnInput, TurnOutput},+};+use std::path::{Path, PathBuf};+use tempfile::{tempdir, TempDir};++fn turn(store: &Database, engine: &str, folder: &Path) -> TurnInput {+ TurnInput {+ continuity: String::new(),+ skills: String::new(),+ person: Default::default(),+ store: Some(store.clone()),+ browser_api_url: None,+ thread_id: "t1".into(),+ kwant: Kwant {+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),+ id: "k1".into(),+ name: "Ada".into(),+ title: "Lead".into(),+ persona_prompt: "p".into(),+ soul: String::new(),+ avatar_sprite: "s".into(),+ driver_type: "cli".into(),+ preferred_model: engine.into(),+ temperature: 0.7,+ max_tokens: 1000,+ level: 1,+ turns_completed: 0,+ created_at: None,+ },+ prompt: "hi".into(),+ history: vec![],+ model_override: None,+ model: None,+ effort_level: Some("low".into()),+ team_context: None,+ workspace_dir: Some(folder.to_path_buf()),+ sandbox_id: None,+ teammates: vec![],+ mcp: None,+ no_tools: false,+ read_only: false,+ }+}++/// A fake CLI that leaves a marker (any start at all, `mcp list` included) and its argv.+struct Fake {+ dir: TempDir,+}++impl Fake {+ fn new(engine: &str) -> Self {+ let dir = tempdir().unwrap();+ let o = dir.path().display();+ exe::write_executable(dir.path().join(engine), format!("#!/bin/sh\necho started >> {o}/marker\nprintf '%s\\n' \"$@\" >> {o}/argv\n"));+ Self { dir }+ }++ fn started(&self) -> bool {+ self.dir.path().join("marker").exists()+ }++ fn argv(&self) -> Vec<String> {+ std::fs::read_to_string(self.dir.path().join("argv")).unwrap_or_default().lines().map(str::to_string).collect()+ }++ fn reset(&self) {+ let _ = std::fs::remove_file(self.dir.path().join("marker"));+ let _ = std::fs::remove_file(self.dir.path().join("argv"));+ }++ async fn run(&self, store: &Database, engine: &str, folder: &Path) -> TurnOutput {+ let bin = self.dir.path().join(engine).to_string_lossy().into_owned();+ let mut driver = CliDriver::new(Some(bin), Some(engine.into()));+ if engine == "grok" {+ let home = self.dir.path().join("grok-home");+ std::fs::create_dir_all(&home).unwrap();+ driver = driver.with_grok_home(home);+ }+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);+ let drain = tokio::spawn(async move { while rx.recv().await.is_some() {} });+ let out = driver.stream_turn(turn(store, engine, folder), tx).await.unwrap();+ drain.await.unwrap();+ out+ }+}++struct Env {+ tmp: TempDir,+ db: Database,+ recorded: PathBuf,+ other: PathBuf,+}++async fn env() -> Env {+ let tmp = tempdir().unwrap();+ let db = Database::init(&tmp.path().join("data")).await.unwrap();+ let recorded = tmp.path().join("projects").join("site");+ let other = tmp.path().join("elsewhere");+ for d in [recorded.join("sub"), other.clone()] {+ std::fs::create_dir_all(d).unwrap();+ }+ let recorded = recorded.canonicalize().unwrap();+ db.record_isolated_folder(&recorded, "isolated-bot").await.unwrap();+ Env { tmp, db, recorded, other: other.canonicalize().unwrap() }+}++fn refusal(out: &TurnOutput, engine: &str) {+ let (text, meta) = out.notice.as_ref().expect("a notice, not a reply");+ assert!(!text.is_empty());+ assert_eq!(meta["reason"], "folder_used_by_isolated_bot", "{meta}");+ assert_eq!(meta["engine"], engine, "{meta}");+}++#[tokio::test]+async fn codex_and_grok_never_start_in_a_folder_an_isolated_bot_used() {+ let e = env().await;+ let parent = e.recorded.parent().unwrap().to_path_buf();+ for engine in ["codex", "grok"] {+ let fake = Fake::new(engine);+ // The folder itself, a subfolder of it, and a folder holding it+ for folder in [e.recorded.clone(), e.recorded.join("sub"), parent.clone()] {+ let out = fake.run(&e.db, engine, &folder).await;+ refusal(&out, engine);+ assert!(!fake.started(), "{engine} started in {}", folder.display());+ }+ }+ // Positive control: Codex in a folder no isolated bot used starts as usual+ let fake = Fake::new("codex");+ let out = fake.run(&e.db, "codex", &e.other).await;+ assert!(out.notice.is_none(), "{:?}", out.notice);+ assert!(fake.started());+}++#[cfg(target_os = "linux")]+#[tokio::test]+async fn host_claude_in_a_used_folder_loads_only_the_persons_settings() {+ let e = env().await;+ let fake = Fake::new("claude");+ for folder in [e.recorded.clone(), e.recorded.join("sub")] {+ fake.reset();+ let out = fake.run(&e.db, "claude", &folder).await;+ assert!(out.notice.is_none(), "{:?}", out.notice);+ let argv = fake.argv();+ let at = argv.iter().position(|a| a == "--setting-sources").unwrap_or_else(|| panic!("{argv:?}"));+ assert_eq!(argv[at + 1], "user");+ assert!(argv.iter().any(|a| a == "--strict-mcp-config"), "{argv:?}");+ }+ // Positive control: elsewhere Claude's project settings load as before+ fake.reset();+ fake.run(&e.db, "claude", &e.other).await;+ let argv = fake.argv();+ assert!(argv.iter().any(|a| a == "--strict-mcp-config"), "{argv:?}");+ assert!(!argv.iter().any(|a| a == "--setting-sources"), "{argv:?}");+}++#[tokio::test]+async fn a_folder_kwnt_cant_check_counts_as_used() {+ let e = env().await;+ // The record can't be read (another connection renames its table): the guard fails closed+ let file = e.tmp.path().join("data").join("kwnt.db");+ let other = sqlx::SqlitePool::connect(&format!("sqlite://{}", file.display())).await.unwrap();+ sqlx::query("ALTER TABLE isolated_folders RENAME TO isolated_folders_gone").execute(&other).await.unwrap();+ other.close().await;+ let fake = Fake::new("codex");+ let out = fake.run(&e.db, "codex", &e.other).await;+ refusal(&out, "codex");+ assert!(!fake.started());+}diff --git a/tests/agents_in_vm_host_commands_test.rs b/tests/agents_in_vm_host_commands_test.rsnew file mode 100644index 00000000..1f9468b4--- /dev/null+++ b/tests/agents_in_vm_host_commands_test.rs@@ -0,0 +1,35 @@+//! Test plan #20 (D4, C9c): the Dev backup command runs bash on this computer as kwnt, so in a+//! folder an isolated Claude turn used it never runs. Its own file: the one-backup-per-space+//! claim is process-wide.+mod common;++use common::*;+use kwnt::db::spaces::SpaceId;+use kwnt::server::dev::backup;++const URI: &str = "/api/spaces/spc_default/dev/backup";++#[tokio::test]+async fn a_backup_command_never_runs_in_a_folder_an_isolated_bot_used() {+ let env = setup().await;+ let space = SpaceId::default_space();+ env.state.db.put_dev_mode(space.as_str(), true, "demo-org/demo-app", "main", None, Some("echo backup > ran.txt; echo \"Backup saved to ran.txt\"")).await.unwrap();+ let dir = backup::folder(&env.state, &space, None);+ env.state.db.record_isolated_folder(&dir.canonicalize().unwrap(), "some-bot").await.unwrap();++ let (s, v) = call(&env.app, "POST", URI, None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["ok"], false, "{v}");+ assert!(v["error"].as_str().unwrap().starts_with("folder_used_by_isolated_bot"), "{v}");+ assert!(!dir.join("ran.txt").exists(), "nothing ran");+ let (last, ok) = env.state.db.latest_dev_backups(space.as_str()).await.unwrap();+ assert!(!last.unwrap().ok, "the refusal is recorded like a failed backup");+ assert!(ok.is_none());++ // A folder nobody isolated used runs it+ assert!(env.state.db.forget_isolated_folder(&dir).await.unwrap());+ let (s, v) = call(&env.app, "POST", URI, None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["ok"], true, "{v}");+ assert!(dir.join("ran.txt").exists());+}diff --git a/tests/agents_in_vm_mcp_cwd_test.rs b/tests/agents_in_vm_mcp_cwd_test.rsnew file mode 100644index 00000000..ab739fd6--- /dev/null+++ b/tests/agents_in_vm_mcp_cwd_test.rs@@ -0,0 +1,176 @@+//! M2 (D4, C8), and should-fix 9: in a folder an isolated bot used (equal, a child, or one holding+//! it), stdio MCP servers start from a fresh, empty, kwnt-owned folder, so a file the bot planted+//! there never runs on this computer: not through kwnt's own client, not through a CLI agent that+//! starts the servers from its config in its own folder, and not through the Test button. A server+//! that names a file in the folder isn't started at all.+#![cfg(unix)]+mod common;++use common::*;+use kwnt::db::{models::McpServer, spaces::SpaceId};+use kwnt::mcp::McpClient;+use kwnt::server::mcp_runtime;+use std::collections::BTreeMap;+use std::os::unix::fs::PermissionsExt;+use std::path::{Path, PathBuf};+use std::time::{Duration, Instant};++const NODE_BIN: &str = "/opt/openmausbot/node-v24.21.0-linux-arm64/bin";++fn npx() -> Option<PathBuf> {+ let path = std::env::var("PATH").unwrap_or_default();+ std::env::split_paths(&path).chain([PathBuf::from(NODE_BIN)]).map(|d| d.join("npx")).find(|p| p.is_file())+}++fn stdio(name: &str, command: &str, args: &[&str], home: &Path) -> McpServer {+ let path_var = format!("{}:/usr/local/bin:/usr/bin:/bin", npx().and_then(|p| p.parent().map(Path::to_path_buf)).unwrap_or_default().display());+ McpServer {+ id: String::new(),+ name: name.into(),+ transport: "stdio".into(),+ command: Some(command.into()),+ args: args.iter().map(|a| a.to_string()).collect(),+ url: None,+ // npx must never fetch a package: without the planted bin it fails offline instead+ env: BTreeMap::from([+ ("PATH".into(), path_var),+ ("HOME".into(), home.display().to_string()),+ ("npm_config_yes".into(), "false".into()),+ ("npm_config_offline".into(), "true".into()),+ ]),+ headers: BTreeMap::new(),+ enabled: true,+ timeout_secs: 5,+ created_at: None,+ }+}++/// `dir` gets a `planted` Python module and an npm bin `srv`, each writing `<out>/<what>-<tag>`.+fn plant(dir: &Path, out: &Path, tag: &str) {+ std::fs::create_dir_all(dir.join("node_modules/.bin")).unwrap();+ std::fs::write(dir.join("planted.py"), format!("open({:?}, 'w').write('ran')\n", out.join(format!("py-{tag}")).display().to_string())).unwrap();+ let bin = dir.join("node_modules/.bin/srv");+ std::fs::write(&bin, format!("#!/bin/sh\necho ran > '{}'\n", out.join(format!("npx-{tag}")).display())).unwrap();+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();+}++/// Starts every server the way kwnt does (its client, in `cwd`) and the way a CLI agent does+/// (the config's command and args, run in `cwd`), each to completion.+async fn start_all(servers: &[McpServer], cwd: &Path) {+ for s in servers.iter().filter(|s| s.transport == "stdio") {+ let _ = McpClient::connect(s, Some(cwd)).await;+ let status = tokio::process::Command::new(s.command.as_deref().unwrap())+ .args(&s.args)+ .env_clear()+ .envs(&s.env)+ .current_dir(cwd)+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .kill_on_drop(true)+ .status();+ let _ = tokio::time::timeout(Duration::from_secs(30), status).await;+ }+}++/// The turn's servers this test added (a fresh database may bring its own).+fn ours(servers: &[McpServer]) -> Vec<McpServer> {+ servers.iter().filter(|s| ["py", "node", "file"].contains(&s.name.as_str())).cloned().collect()+}++fn ran(out: &Path) -> Vec<String> {+ let mut v: Vec<String> = std::fs::read_dir(out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();+ v.sort();+ v+}++#[tokio::test]+async fn stdio_servers_in_an_isolated_bots_folder_start_from_an_empty_one_and_planted_files_never_run() {+ let env = setup().await;+ let space = SpaceId::default_space();+ let kwant = env.state.db.get_kwant(&env.a).await.unwrap().unwrap();+ let work = tempfile::tempdir().unwrap();+ let out = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(work.path().join("rec")).unwrap();+ let rec = work.path().join("rec").canonicalize().unwrap();+ let child = rec.join("child");+ let free = work.path().canonicalize().unwrap().join("free");+ for (dir, tag) in [(&rec, "rec"), (&child, "child"), (&free, "free")] {+ plant(dir, out.path(), tag);+ }++ let py = stdio("py", "python3", &["-m", "planted"], home.path());+ let mut servers = vec![py];+ let has_npx = npx().is_some();+ if has_npx {+ servers.push(stdio("node", "npx", &["srv"], home.path()));+ } else {+ eprintln!("npx isn't installed here: only the Python case runs");+ }+ // Names a file in the folder: never started there+ servers.push(stdio("file", "python3", &["./planted.py"], home.path()));+ for s in &servers {+ env.state.db.create_mcp_server(&space, s).await.unwrap();+ }++ // Control: in a folder no isolated bot used, nothing changes and the planted files do run, so+ // the checks below would see a run+ let (ctx, token) = mcp_runtime::prepare_turn(&env.state, &kwant, Some(free.clone())).await.unwrap();+ let mine = ours(&ctx.servers);+ assert_eq!(mine.len(), servers.len());+ assert!(mine.iter().all(|s| s.command.as_deref() != Some("/bin/sh")), "untouched outside a recorded folder");+ start_all(&mine, &free).await;+ mcp_runtime::finish_turn(&env.state, &token).await;+ let want: Vec<String> = if has_npx { vec!["npx-free".into(), "py-free".into()] } else { vec!["py-free".into()] };+ assert_eq!(ran(out.path()), want, "the control turn runs the planted files");+ for f in &want {+ std::fs::remove_file(out.path().join(f)).unwrap();+ }++ env.state.db.record_isolated_folder(&rec, "isolated-bot").await.unwrap();+ // The recorded folder itself, a child of it, and a folder holding it+ for cwd in [rec.clone(), child.clone(), work.path().canonicalize().unwrap()] {+ let (ctx, token) = mcp_runtime::prepare_turn(&env.state, &kwant, Some(cwd.clone())).await.unwrap();+ let empty = mcp_runtime::mcp_cwd(&env.state.config.data_dir, &token);+ let mine = ours(&ctx.servers);+ let names: Vec<&str> = mine.iter().map(|s| s.name.as_str()).collect();+ assert!(!names.contains(&"file"), "{cwd:?}: a server naming a file in the folder isn't started ({names:?})");+ assert_eq!(names.len(), servers.len() - 1, "{cwd:?}: {names:?}");+ for s in ctx.servers.iter().filter(|s| s.transport == "stdio") {+ assert_eq!(s.command.as_deref(), Some("/bin/sh"), "{cwd:?}: {s:?}");+ assert_eq!(s.args[2], empty.display().to_string(), "{cwd:?}: starts from the turn's empty folder");+ }+ assert!(empty.is_dir() && std::fs::read_dir(&empty).unwrap().next().is_none(), "{cwd:?}: a fresh, empty folder");+ assert_eq!(std::fs::metadata(&empty).unwrap().permissions().mode() & 0o777, 0o700);+ start_all(&mine, &cwd).await;+ mcp_runtime::finish_turn(&env.state, &token).await;+ assert!(!empty.exists(), "{cwd:?}: the empty folder goes with the turn");+ assert_eq!(ran(out.path()), Vec::<String>::new(), "{cwd:?}: no planted file ran");+ }++ // A turn with no folder whose own folder isn't near a recorded one is left alone+ let (ctx, token) = mcp_runtime::prepare_turn(&env.state, &kwant, None).await.unwrap();+ assert_eq!(ours(&ctx.servers).len(), servers.len(), "kwnt's own folder isn't a recorded one here");+ mcp_runtime::finish_turn(&env.state, &token).await;++ // The Test button: from <data>/workspace, once a bot used it, the same rule+ let ws = env.state.config.data_dir.join("workspace");+ std::fs::create_dir_all(&ws).unwrap();+ plant(&ws, out.path(), "ws");+ env.state.db.record_isolated_folder(&ws.canonicalize().unwrap(), "isolated-bot").await.unwrap();+ let list = ours(&env.state.db.list_mcp_servers(&space).await.unwrap());+ for s in &list {+ let started = Instant::now();+ let (status, v) = call(&env.app, "POST", &format!("/api/mcp/servers/{}/test", s.id), None).await;+ assert_eq!(status.as_u16(), 200, "{v}");+ assert_eq!(v["ok"], false, "{}: nothing real to list ({v})", s.name);+ if s.name == "file" {+ assert!(v["error"].as_str().unwrap().starts_with("Not started"), "{v}");+ }+ assert!(started.elapsed() < Duration::from_secs(30), "{}: no hang", s.name);+ }+ assert_eq!(ran(out.path()), Vec::<String>::new(), "the Test button ran no planted file");+ let left = env.state.config.data_dir.join("run").join("mcp-cwd");+ assert!(std::fs::read_dir(&left).map(|mut d| d.next().is_none()).unwrap_or(true), "no empty folder is left behind");+}diff --git a/tests/agents_in_vm_real_api_test.rs b/tests/agents_in_vm_real_api_test.rsnew file mode 100644index 00000000..f42b727e--- /dev/null+++ b/tests/agents_in_vm_real_api_test.rs@@ -0,0 +1,81 @@+//! Gate 0, part 2: one isolated Claude turn and a `--resume` turn against the REAL Anthropic API+//! through kwnt's own (Rust) broker, so the allow-list, the forwarded headers and the betas taken+//! from `proto/agents-in-vm/evidence/real-upstream.txt` are shown to be enough.+//!+//! Runs only with `KWNT_GATE0_KEY_FILE=<path to an Anthropic API key>` (it spends about four+//! Haiku calls), plus Docker and the agent image. The key is read here, held by the broker only,+//! and never printed.+#![cfg(target_os = "linux")]++use kwnt::config::AgentsInVmConfig;+use kwnt::sandbox::agent_vm::{+ broker::{BrokerConfig, Credential, Secret},+ image_tag, AgentVm, TurnRequest,+};+use serde_json::Value;+use std::process::Command as StdCommand;+use tokio::process::Command;++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_real_turn_and_a_resume_pass_through_kwnts_broker() {+ let Some(key_file) = std::env::var_os("KWNT_GATE0_KEY_FILE") else {+ eprintln!("skipped: set KWNT_GATE0_KEY_FILE to run against the real API");+ return;+ };+ let key = std::fs::read_to_string(&key_file).expect("the key file").trim().to_string();+ assert!(StdCommand::new("docker").args(["image", "inspect", &image_tag()]).output().is_ok_and(|o| o.status.success()));+ let data = tempfile::tempdir().unwrap();+ let work = tempfile::tempdir().unwrap();+ let vm = AgentVm::with_parts(data.path(), BrokerConfig::new(data.path().join("broker.log")), Some(image_tag()), AgentsInVmConfig::default(), None);+ let turn = vm+ .prepare_turn(TurnRequest {+ bot_id: "gate0-rust".into(),+ folder: Some(work.path().to_path_buf()),+ credential: Credential::ApiKey(Secret::new(&key)),+ credential_home: None,+ kwnt_origin: None,+ })+ .await+ .unwrap_or_else(|r| panic!("the turn didn't start: {r:?}"));++ // The flags kwnt's CLI driver gives an isolated turn that matter here+ let base = ["--model", "haiku", "--strict-mcp-config", "--disallowedTools", "WebSearch,WebFetch", "--output-format", "stream-json", "--verbose"];+ let mut first = Command::new("claude");+ first.args(base).args(["--allowedTools", "Bash", "-p", "Use the Bash tool to run: echo rust-broker-ok > rb.txt. Then reply with only the file's content."]);+ let out = tokio::time::timeout(std::time::Duration::from_secs(300), turn.wrap(&first).stdin(std::process::Stdio::null()).output()).await.unwrap().unwrap();+ let stdout = String::from_utf8_lossy(&out.stdout).into_owned();+ let result = |s: &str| s.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok()).find(|v| v["type"] == "result").unwrap_or(Value::Null);+ let r1 = result(&stdout);+ assert_eq!(r1["is_error"], false, "first turn: {}", r1["subtype"]);+ assert_eq!(std::fs::read_to_string(work.path().join("rb.txt")).unwrap().trim(), "rust-broker-ok");+ let session = r1["session_id"].as_str().expect("a session id").to_string();++ let mut again = Command::new("claude");+ again.args(base).args(["--resume", &session, "-p", "What did the file contain? Reply with only that."]);+ let out2 = tokio::time::timeout(std::time::Duration::from_secs(300), turn.wrap(&again).stdin(std::process::Stdio::null()).output()).await.unwrap().unwrap();+ let stdout2 = String::from_utf8_lossy(&out2.stdout).into_owned();+ let r2 = result(&stdout2);+ assert_eq!(r2["is_error"], false, "resumed turn: {}", r2["subtype"]);+ assert!(r2["result"].as_str().unwrap_or_default().contains("rust-broker-ok"), "the resumed turn remembers the first");++ // Every call was a listed one, answered 200, with no beta stripped; nothing holds the key+ let log = std::fs::read_to_string(data.path().join("broker.log")).unwrap();+ let recs: Vec<Value> = log.lines().map(|l| serde_json::from_str(l).unwrap()).collect();+ assert!(recs.len() >= 3, "{} calls", recs.len());+ for r in &recs {+ assert_eq!((r["route"].as_str(), r["path"].as_str(), r["status"].as_u64()), (Some("anthropic"), Some("/v1/messages?beta=true"), Some(200)), "{r}");+ assert!(r.get("beta_stripped").is_none_or(|b| b.as_array().is_some_and(Vec::is_empty)), "a beta the CLI needs was stripped: {r}");+ }+ eprintln!("gate0-rust: {} calls through kwnt's broker, all POST /v1/messages?beta=true 200, no beta stripped", recs.len());+ for (what, text) in [("broker log", &log), ("first turn output", &stdout), ("resumed turn output", &stdout2)] {+ assert!(!text.contains(&key), "the key is in the {what}");+ }+ let grep = StdCommand::new("grep").args(["-rlF", "-f", "/dev/stdin"]).arg(data.path()).arg(work.path()).stdin(std::process::Stdio::piped()).spawn().and_then(|mut c| {+ use std::io::Write;+ c.stdin.take().unwrap().write_all(key.as_bytes())?;+ c.wait_with_output()+ });+ assert!(grep.unwrap().stdout.is_empty(), "the key was written to a file");+ drop(turn);+ vm.remove_containers(|_| true).await;+}diff --git a/tests/agents_in_vm_settings_test.rs b/tests/agents_in_vm_settings_test.rsnew file mode 100644index 00000000..1cf628ef--- /dev/null+++ b/tests/agents_in_vm_settings_test.rs@@ -0,0 +1,74 @@+//! "Run Claude inside the VM": the switch and chips in `GET/PUT /api/settings/computer`+//! (design/ui.md's contract, Ada's D1).+mod common;++use axum::http::StatusCode;+use kwnt::sandbox::agent_vm::{broker::BrokerConfig, AgentVm, AgentsInVmConfig};+use serde_json::json;++#[tokio::test]+async fn the_switch_saves_and_the_chips_say_where_each_engine_runs() {+ let data = tempfile::tempdir().unwrap();+ let env = common::setup_with(|state| {+ // An image name that's never built: turning the switch on can't start a real download+ state.agent_vm = AgentVm::with_parts(+ data.path(),+ BrokerConfig::new(data.path().join("broker.log")),+ Some("kwnt-agent-settings-test:never-built".into()),+ AgentsInVmConfig::default(),+ None,+ );+ })+ .await;+ let (s, v) = common::call(&env.app, "GET", "/api/settings/computer", None).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(v["isolate_claude"], false, "off by default: {v}");+ assert_eq!(v["agents"]["claude"], json!({"state": "off", "reason": null, "detail": null, "progress": null}));+ for other in ["codex", "grok"] {+ assert_eq!(v["agents"][other]["state"], "not_isolated");+ assert_eq!(v["agents"][other]["reason"], "not_supported_yet");+ }+ let available = v["isolate_claude_toggle"]["available"].as_bool().unwrap();+ if cfg!(target_os = "macos") {+ assert_eq!(v["isolate_claude_toggle"]["reason"], "mac_later");+ }+ // Isolation is about Claude alone: `isolates` never names the CLI agents+ assert!(!v["isolates"].as_array().unwrap().iter().any(|i| i == "cli_agents"), "{v}");++ // Nothing to change, and a wrong type, are refused+ assert_eq!(common::call(&env.app, "PUT", "/api/settings/computer", Some(json!({}))).await.0, StatusCode::BAD_REQUEST);+ let (s, _) = common::call(&env.app, "PUT", "/api/settings/computer", Some(json!({"isolate_claude": "yes"}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);++ // Only the person can turn it on+ assert_eq!(common::call_remote(&env.app, "PUT", "/api/settings/computer").await, StatusCode::UNAUTHORIZED);++ let (s, v) = common::call(&env.app, "PUT", "/api/settings/computer", Some(json!({"isolate_claude": true}))).await;+ if available {+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["isolate_claude"], true);+ let claude = &v["agents"]["claude"];+ if v["mode"] == "local" {+ // D1: in local mode the switch is kept but does nothing, and the chip says so+ assert_eq!((claude["state"].as_str(), claude["reason"].as_str()), (Some("not_isolated"), Some("local_mode")), "{v}");+ } else {+ // The test image is never built: it's getting ready or it failed, never "isolated"+ assert!(["preparing", "unavailable"].contains(&claude["state"].as_str().unwrap()), "{v}");+ }+ } else {+ assert_eq!(s, StatusCode::BAD_REQUEST);+ // The code for the client, and words for the person (ui-check-446 fix 5)+ let code = v["code"].as_str().unwrap_or_default();+ assert!(["mac_later", "docker_unavailable", "not_supported_yet"].contains(&code), "{v}");+ assert_eq!(v["error"].as_str(), Some(kwnt::sandbox::agent_vm::toggle_message(code)), "{v}");+ assert!(!v["error"].as_str().unwrap().contains('_'), "{v}");+ let (_, v) = common::call(&env.app, "GET", "/api/settings/computer", None).await;+ assert_eq!(v["isolate_claude"], false);+ }++ // Turning it off always works+ let (s, v) = common::call(&env.app, "PUT", "/api/settings/computer", Some(json!({"isolate_claude": false}))).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(v["isolate_claude"], false);+ assert_eq!(v["agents"]["claude"]["state"], "off");+}diff --git a/tests/host_git_calls_test.rs b/tests/host_git_calls_test.rsnew file mode 100644index 00000000..0f5e5620--- /dev/null+++ b/tests/host_git_calls_test.rs@@ -0,0 +1,47 @@+//! D4c / S-13 (agents in the VM): kwant starts git on this computer only through+//! `server::dev::git::host_git_command`, which forces `GIT_CONFIG_NOSYSTEM=1` and turns off+//! hooks, fsmonitor and the pager. It is built from its blocking twin+//! `host_git_command_blocking` (used by Windows' `git_bash`), the one line that starts git. This+//! fails when anything else in `src/` (outside test code) starts git itself.++use std::path::Path;++fn rs_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {+ for e in std::fs::read_dir(dir).unwrap().flatten() {+ let p = e.path();+ if p.is_dir() {+ rs_files(&p, out);+ } else if p.extension().is_some_and(|x| x == "rs") {+ out.push(p);+ }+ }+}++/// The file without its `#[cfg(test)]` modules (everything from the first one on; kwant keeps+/// its unit tests at the end of each file).+fn non_test(src: &str) -> &str {+ src.find("#[cfg(test)]").map_or(src, |i| &src[..i])+}++#[test]+fn only_the_helper_starts_git() {+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");+ let mut files = Vec::new();+ rs_files(&root, &mut files);+ let mut found = Vec::new();+ for f in files {+ let text = std::fs::read_to_string(&f).unwrap();+ let code = non_test(&text);+ for (n, line) in code.lines().enumerate() {+ let l = line.split("//").next().unwrap_or("");+ let starts_git = l.contains("Command::new(\"git\")") || l.contains("Command::new(\"git.exe\")");+ let helper = f.ends_with("server/dev/git.rs") && l.contains("Command::new(bin)");+ if starts_git || helper {+ found.push(format!("{}:{}", f.strip_prefix(&root).unwrap().display(), n + 1));+ }+ }+ }+ // Exactly one: the line inside `host_git_command_blocking`, which `host_git_command` wraps+ assert_eq!(found.len(), 1, "git started outside host_git_command: {found:?}");+ assert!(found[0].starts_with("server/dev/git.rs:"), "{found:?}");+}diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rsindex 4cca0b60..3c646ee5 100644--- a/tests/mcp_runtime_test.rs+++ b/tests/mcp_runtime_test.rs@@ -320,7 +320,7 @@ fn turn(mcp: Option<McpTurnContext>) -> TurnInput {async fn fake_cli_run(kind: &str, mcp: Option<McpTurnContext>) -> String {let dir = tempdir().unwrap();let script = dir.path().join("fake-cli");- exe::write_executable(&script, "#!/bin/sh\necho \"ARGS: $*\"\nwhile [ $# -gt 0 ]; do\n if [ \"$1\" = --mcp-config ]; then echo \"MODE: $(stat -c %a \"$2\")\"; fi\n shift\ndone\necho \"TOOL_TIMEOUT: $MCP_TOOL_TIMEOUT\"\n");+ exe::write_executable(&script, "#!/bin/sh\necho \"ARGS: $*\"\nwhile [ $# -gt 0 ]; do\n if [ \"$1\" = --mcp-config ]; then echo \"MODE: $(stat -c %a \"$2\")\"; fi\n shift\ndone\necho \"TOOL_TIMEOUT: $MCP_TOOL_TIMEOUT\"\necho \"IDLE_TIMEOUT: $CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT\"\n");let driver = CliDriver::new(Some(script.to_string_lossy().into_owned()), Some(kind.into()));let (tx, mut rx) = tokio::sync::mpsc::channel(64);let drain = tokio::spawn(async move { while rx.recv().await.is_some() {} });@@ -342,6 +342,9 @@ async fn claude_cli_gets_mcp_config_without_secrets_in_argv() {assert!(out.contains("--permission-mode default"), "{out}");assert!(out.contains("MODE: 600"), "{out}");assert!(out.contains("TOOL_TIMEOUT: 330000"), "{out}");+ // claude's own idle limit on a tool call is raised with it, so kwnt's 300 s approval timeout+ // ends an unanswered card first (QA F-2)+ assert!(out.contains("IDLE_TIMEOUT: 330000"), "{out}");assert!(!out.contains("sk-very-secret") && !out.contains("hdr-secret"), "secrets leaked into argv: {out}");assert_eq!(std::fs::read_dir(tmp.path().join("mcp")).unwrap().count(), 0, "config file left behind");diff --git a/tests/mission_checkpoints_test.rs b/tests/mission_checkpoints_test.rsindex 7999060a..31fb287b 100644--- a/tests/mission_checkpoints_test.rs+++ b/tests/mission_checkpoints_test.rs@@ -95,12 +95,18 @@ struct Env {/// kwant on a real port (the stand-in CLI calls back), with the mission board on.async fn setup() -> Env {+ setup_in(|tmp| tmp.to_path_buf()).await+}++/// [`setup`] with kwant's data folder at `data(tmp)` (QA F-4 puts it behind a symlink).+async fn setup_in(data: impl FnOnce(&Path) -> PathBuf) -> Env {let tmp = tempdir().unwrap();+ let data_dir = data(tmp.path());let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let port = listener.local_addr().unwrap().port();- let db = Database::init(tmp.path()).await.unwrap();+ let db = Database::init(&data_dir).await.unwrap();let config = Config {- data_dir: tmp.path().to_path_buf(),+ data_dir: data_dir.clone(),host: "127.0.0.1".into(),port,laya_url: "http://127.0.0.1:9".into(),@@ -110,7 +116,7 @@ async fn setup() -> Env {let state = AppState::new(config.clone(),db,- ToolRunner::new(tmp.path().join("workspace")),+ ToolRunner::new(data_dir.join("workspace")),PermissionBroker::new(),LayaRouter::new(config.laya_url.clone()),);@@ -836,3 +842,66 @@ async fn a_conflict_names_another_task_only_when_its_own_calls_wrote_the_path()let named: Vec<&Value> = pa["conflicts"].as_array().unwrap().iter().chain(pb["conflicts"].as_array().unwrap()).filter(|c| !c["changed_by_task"].is_null()).collect();assert_eq!(named.len(), 2, "only proven writes name a task: {named:?}");}++/// QA F-4: kwant's data folder behind a symlink the person made (a linked home or `~/Projects ->+/// /mnt/ssd/Projects`). Checkpoints still work and so does a restore, as on main.+// F-4 records the resolved folder on unix only; the symlinks here are unix too+#[cfg(unix)]+#[tokio::test]+async fn a_symlink_the_person_made_above_the_folder_keeps_checkpoints_and_restore_working() {+ let e = setup_in(|tmp| {+ std::fs::create_dir(tmp.join("ssd")).unwrap();+ std::os::unix::fs::symlink(tmp.join("ssd"), tmp.join("data")).unwrap();+ tmp.join("data")+ })+ .await;+ let (mid, ids) = mission(&e, &e.bot.id, json!([{"title": "A", "owner": e.bot.id}])).await;+ let dir = folder(&e, &mid).await;+ assert!(dir.starts_with(e._tmp.path().join("data")), "the folder is typed through the symlink: {dir:?}");+ std::fs::write(dir.join("a.txt"), "v0").unwrap();+ run(&e, &mid, &ids[0], &[("a.txt", Some("v1"))]).await;+ assert!(events(&e, &ids[0], "checkpoint_failed").await.is_empty(), "no checkpoint fails");+ let list = checkpoints(&e, &ids[0]).await;+ let before = of_kind(&list, "before_run");+ assert_eq!(before.len(), 1, "{list:?}");+ assert_eq!(before[0]["restorable"], true, "{list:?}");+ let cid = id(before[0]);+ let p = preview(&e, &ids[0], &cid).await;+ assert_eq!(p["changes"], json!([{"path": "a.txt", "action": "overwrite"}]), "{p}");+ let (s, r, _) = restore(&e, &ids[0], &cid, "f4-restore", &p["preview_sha256"]).await;+ assert_eq!(s, StatusCode::OK, "{r}");+ assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "v0");+}++/// QA F-3 kept with F-4: the task folder swapped for a symlink after its checkpoint was taken is+/// refused at restore (nothing written, the other folder untouched), even with the person's own+/// symlink above it.+// F-4 records the resolved folder on unix only; the symlinks here are unix too+#[cfg(unix)]+#[tokio::test]+async fn a_folder_swapped_for_a_symlink_after_its_checkpoint_is_refused_at_restore() {+ let e = setup_in(|tmp| {+ std::fs::create_dir(tmp.join("ssd")).unwrap();+ std::os::unix::fs::symlink(tmp.join("ssd"), tmp.join("data")).unwrap();+ tmp.join("data")+ })+ .await;+ let (mid, ids) = mission(&e, &e.bot.id, json!([{"title": "A", "owner": e.bot.id}])).await;+ let dir = folder(&e, &mid).await;+ std::fs::write(dir.join("a.txt"), "v0").unwrap();+ run(&e, &mid, &ids[0], &[("a.txt", Some("v1"))]).await;+ let cid = id(of_kind(&checkpoints(&e, &ids[0]).await, "before_run")[0]);+ let p = preview(&e, &ids[0], &cid).await;+ assert!(p["refused"].is_null(), "{p}");+ // The bot swaps its task folder for a symlink to a folder outside it+ let victim = e._tmp.path().join("victim");+ std::fs::create_dir(&victim).unwrap();+ std::fs::write(victim.join("a.txt"), "ORIGINAL").unwrap();+ std::fs::rename(&dir, dir.with_file_name("moved")).unwrap();+ std::os::unix::fs::symlink(&victim, &dir).unwrap();+ let (s, r, _) = restore(&e, &ids[0], &cid, "f4-swapped", &p["preview_sha256"]).await;+ assert_ne!(s, StatusCode::OK, "{r}");+ assert_eq!(std::fs::read_to_string(victim.join("a.txt")).unwrap(), "ORIGINAL", "nothing written through the symlink");+ assert_eq!(std::fs::read_to_string(dir.with_file_name("moved").join("a.txt")).unwrap(), "v1");+ assert!(of_kind(&checkpoints(&e, &ids[0]).await, "before_restore").is_empty(), "no safety checkpoint either");+}diff --git a/tests/mission_control_test.rs b/tests/mission_control_test.rsindex 878c4cce..62aff6d0 100644--- a/tests/mission_control_test.rs+++ b/tests/mission_control_test.rs@@ -592,3 +592,31 @@ async fn only_a_required_check_waiting_for_approval_needs_the_person() {let insights = person(&e, "GET", "/api/missions/insights", None).await;assert_eq!(insights["needs_you_now"], 1, "{insights}");}++/// Test plan #20 (D4, C9b): a command check runs bash on this computer as kwnt, so in a folder an+/// isolated Claude turn used it never runs: no process, no marker file, the refusal recorded.+/// A folder nobody isolated used still runs it.+#[tokio::test]+async fn a_command_check_never_runs_in_a_folder_an_isolated_bot_used() {+ let e = setup().await;+ let (m, tasks) = mission(&e, 200_000, json!([{"title": "Build", "owner": e.bot.id}])).await;+ let tid = id(&tasks[0]);+ let dir = folder(&e, &id(&m)).await;+ std::fs::create_dir_all(dir.join("sub")).unwrap();+ // The record holds the folder's subfolder: the folder that contains it counts too+ e.state.db.record_isolated_folder(&dir.join("sub").canonicalize().unwrap(), &e.bot.id).await.unwrap();+ person(&e, "POST", &format!("/api/tasks/{tid}/checks"), Some(json!({"kind": "command", "spec": {"command": "echo hi > ran.txt"}}))).await;+ let run = person(&e, "POST", &format!("/api/tasks/{tid}/checks/run"), None).await;+ let c = run["checks"].as_array().unwrap().iter().find(|c| c["kind"] == "command").unwrap().clone();+ assert_eq!(c["status"], "error", "{run}");+ assert!(!dir.join("ran.txt").exists(), "nothing ran");+ let t = task(&e, &tid).await;+ assert!(t.to_string().contains("folder_used_by_isolated_bot"), "the refusal is recorded: {t}");++ // Once the person clears the record, it runs again+ assert!(e.state.db.forget_isolated_folder(&dir.join("sub")).await.unwrap());+ let run = person(&e, "POST", &format!("/api/tasks/{tid}/checks/run"), None).await;+ let c = run["checks"].as_array().unwrap().iter().find(|c| c["kind"] == "command").unwrap().clone();+ assert_eq!(c["status"], "passed", "{run}");+ assert!(dir.join("ran.txt").exists());+}