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.8.0 Mac local hardening: deny sign-ins and kwnt's secrets to Claude on a Mac (#463)
Oleksandr Ivanchenkodfeabfcb0a89
diff --git a/.github/workflows/mac-local.yml b/.github/workflows/mac-local.ymlnew file mode 100644index 00000000..8486a9ae--- /dev/null+++ b/.github/workflows/mac-local.yml@@ -0,0 +1,88 @@+name: mac-local++# 0.8.0 079-mac-local-hardening: Claude on this computer, on a Mac (src/drivers/mac_local.rs).+# ci.yml's rust job runs on Linux and mac.yml only builds apps/mac, so kwnt's macOS code path+# (cfg!(target_os = "macos") in drivers/cli.rs) would otherwise never run in CI. This job:+# - runs the hardening's unit tests on macOS (exactly 12, so a rename can't skip them), and+# - runs scripts/mac_local_probe.sh: the real Claude Code accepts kwnt's settings, Seatbelt+# (sandbox-runtime, what Claude's Bash sandbox is built on) enforces the denied places, and+# whether the Keychain is reachable through the security service (reported, not enforced).+# Not in scripts/release_required_checks.txt: it runs only when these paths change.+on:+ workflow_dispatch:+ pull_request:+ paths:+ - "src/drivers/**"+ - "src/profiles/**"+ - "scripts/mac_local_probe.sh"+ - ".github/workflows/mac-local.yml"++permissions:+ contents: read++concurrency:+ group: mac-local-${{ github.ref }}+ cancel-in-progress: true++env:+ CARGO_TERM_COLOR: always+ CARGO_INCREMENTAL: 0+ CARGO_PROFILE_DEV_DEBUG: 0+ CARGO_PROFILE_TEST_DEBUG: 0++jobs:+ frontend:+ name: frontend+ runs-on: ubuntu-latest+ defaults:+ run:+ working-directory: frontend+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 20+ cache: npm+ cache-dependency-path: frontend/package-lock.json+ - run: npm ci+ - run: npm run build+ - uses: actions/upload-artifact@v4+ with:+ name: mac-local-frontend-dist+ path: frontend/dist+ retention-days: 1++ mac-local:+ name: mac-local+ runs-on: macos-15+ needs: frontend+ timeout-minutes: 60+ steps:+ - uses: actions/checkout@v4+ # The binary embeds frontend/dist, so the Rust build needs it+ - uses: actions/download-artifact@v4+ with:+ name: mac-local-frontend-dist+ path: frontend/dist+ - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable+ - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3+ # sandbox-runtime needs node >= 22.12+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ - name: The hardening's unit tests, on macOS+ run: |+ set -o pipefail+ cargo test --locked --lib -- mac_local:: no_tools::a_mac_claude_turn no_tools::the_hardening_reaches 2>&1 | tee unit.log+ grep -q "test result: ok. 12 passed; 0 failed; 1 ignored" unit.log || { echo "::error::expected exactly 12 hardening tests to pass"; exit 1; }+ - name: Probe the real Claude and Seatbelt+ run: |+ set -o pipefail+ # The lib test binary's path from cargo's JSON (the human-readable "Executable" line is+ # colored by CARGO_TERM_COLOR=always, which broke matching it)+ bin=$(cargo test --locked --lib --no-run --message-format=json 2>/dev/null \+ | python3 -c 'import json,sys; [print(m["executable"]) for m in map(json.loads, sys.stdin) if m.get("reason") == "compiler-artifact" and m["profile"]["test"] and "lib" in m["target"]["kind"] and m.get("executable")]' \+ | tail -1)+ echo "lib test binary: ${bin:-<none>}"+ test -x "$bin" || { echo "::error::no lib test binary"; exit 1; }+ bash scripts/mac_local_probe.sh "$bin"diff --git a/docs/agents-in-vm.md b/docs/agents-in-vm.mdindex bff98967..42797c2b 100644--- a/docs/agents-in-vm.md+++ b/docs/agents-in-vm.md@@ -125,6 +125,59 @@ 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)```+## Claude on this computer, on a Mac (0.8.0)++Without the VM, a Claude turn on a Mac runs on the Mac itself. A bot talked into it by a web+page, a file or another bot could read a sign-in with its file tools or a shell command. kwnt+now passes Claude one more `--settings` layer for those turns (`src/drivers/mac_local.rs`):++- **Always on.** Claude's Read, Grep, Glob, Edit and Write tools are denied `~/.claude`,+ `~/.claude.json`, `~/.codex`, `~/.grok`, `~/Library/Keychains`, the profile's own sign-in+ home, and in kwnt's data folder (the one the server runs on, from `--data-dir`, config.toml's+ `data_dir`, `KWNT_DATA_DIR` or `~/.kwnt`) `profiles/`, `kwnt-vault/`, `backups/`, `mcp/`,+ `run/`, `kwnt-vault.key`, `api-token` and `kwnt.db` with its `-wal` and `-shm` files (plus+ `$CLAUDE_CONFIG_DIR`, `$CODEX_HOME` and `$GROK_HOME` when set). What kwnt loads or runs at its+ next start, `config.toml`, `laya/` and `bin/`, stays readable but can't be changed. Where a+ place is reached through a link, its resolved path is listed too. They're `Read(…)`/`Edit(…)`+ deny rules, which outrank anything the folder's or your own settings allow.+ - **Without `KWNT_MAC_SEATBELT` these rules cover Claude's file tools only.** A shell command+ you approve can still read these places and Keychain items.+ - Claude's auto memory is turned off for these turns (`autoMemoryEnabled: false`): it writes+ inside the denied `~/.claude`. Your personal skills and plugins under `~/.claude` still load,+ but Claude's file tools can't open their extra files in these turns.+- **Opt-in: Seatbelt for Bash** (`KWNT_MAC_SEATBELT=1` in kwnt's environment). Claude runs each+ shell command in macOS's sandbox with the same paths unreadable and unwritable (kwnt's start+ files: unwritable only). kwnt still+ approves every command as before (`autoAllowBashIfSandboxed: false`), and a bot can't ask to+ run a command outside the sandbox (`allowUnsandboxedCommands: false`). It's off by default+ until it has been tried on a real Mac, because with it on:+ - the shell's network goes through Claude's proxy, which asks before each new domain, and kwnt+ shows that as an approval card (`localhost` and `127.0.0.1` are allowed);+ - Unix sockets are blocked except `$SSH_AUTH_SOCK`, so Docker from a bot's shell fails;+ - writes outside your home folder fail.++What it doesn't do: the `claude` process itself still reads its own sign-in and the Keychain, as+it has to in order to run. This stops a tricked bot's tools, not the CLI. `~/.ssh` isn't denied,+so git over ssh keeps working. Only the VM keeps sign-ins off the machine the bot runs on.++**The Keychain is only half covered.** kwnt always stops Claude's file tools from reading the+`~/Library/Keychains` files, and with `KWNT_MAC_SEATBELT=1` it stops shell commands reading them+too. Claude keeps its sign-in in the Keychain itself ("Claude Code-credentials"), and a shell+command reaches items through macOS's security service, not the files. That isn't proven safe:+- On CI's Mac runner, a sandboxed `security find-generic-password` couldn't read the probe item+ ("does not exist").+- But that runner's keychain isn't a person's login or iCloud keychain, so this is untested on a+ real Mac.+- Without Seatbelt (the default), a shell command you approve can still read Claude's+ "Claude Code-credentials" item.++**Checked on CI's Mac** (`.github/workflows/mac-local.yml`, `scripts/mac_local_probe.sh`): the unit+tests run on macOS; the real Claude Code reads kwnt's settings (its debug log reports the deny+rules); sandbox-runtime, which Claude's Bash sandbox is built on, gets the same sections and has+to block reads and writes of the denied places, still allow an ordinary home file, and block an+unlisted domain; and the job reports whether a sandboxed `security find-generic-password` reads a+test Keychain item. No Claude sign-in exists on CI, so no real turn runs there.+## Who refreshes a sign-inWhile the setting is on, the broker is the only thing that refreshes a bot's own Claude sign-in@@ -141,5 +194,7 @@ this computer.- `src/db/isolated_folders.rs`: the record of folders isolated replies used.- `src/server/isolated_folders_routes.rs`: the person's list and Forget(`release-080/forget-folder-contract.md`).+- `src/drivers/mac_local.rs`: the Mac hardening for Claude turns on this computer; its CI check is+ `.github/workflows/mac-local.yml` with `scripts/mac_local_probe.sh`.- `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/scripts/mac_local_probe.sh b/scripts/mac_local_probe.shnew file mode 100755index 00000000..37dc4a13--- /dev/null+++ b/scripts/mac_local_probe.sh@@ -0,0 +1,188 @@+#!/bin/bash+# 0.8.0 079-mac-local-hardening, run by .github/workflows/mac-local.yml on GitHub's macOS runner (the+# only Mac CI has). It takes the exact settings kwnt gives Claude on this computer on a Mac (written+# by the ignored test drivers::mac_local::tests::write_settings_for_the_mac_ci_probe, Seatbelt on)+# and checks three things:+#+# 1. The real Claude Code (CLAUDE_VERSION) accepts them: its --debug log says it added the deny+# rules. No Claude sign-in exists here, so no model turn runs.+# 2. Seatbelt enforces the sandbox half: the same filesystem/network sections are handed to+# sandbox-runtime (srt, the library Claude's own Bash sandbox is built on), and reads/writes of+# the denied places must fail while an ordinary file in the home folder still works.+# 3. The Keychain: whether a sandboxed `security find-generic-password` still gets a secret. This+# is reported, not enforced: denyRead of ~/Library/Keychains only stops reading the files.+#+# Usage: scripts/mac_local_probe.sh <kwnt lib test binary>+# Needs: node >= 22.12 and npm on PATH, macOS. Writes a summary to $GITHUB_STEP_SUMMARY when set.+set -uo pipefail++BIN="$1"+CLAUDE_VERSION="${CLAUDE_VERSION:-2.1.316}"+SRT_VERSION="${SRT_VERSION:-0.0.81}"+T="${RUNNER_TEMP:-$(mktemp -d)}/mac-local-probe"+REAL_HOME="$HOME"+H="$T/home"+# Inside the home, as ~/.kwnt is: writes outside the home already fail, so only here does the+# write check on kwnt's start files test their own rule+D="$H/.kwnt"+SUMMARY="${GITHUB_STEP_SUMMARY:-/dev/null}"+fails=0++rm -rf "$T" && mkdir -p "$T"+note() { echo "$*"; echo "$*" >> "$SUMMARY"; }+pass() { note "- PASS: $*"; }+fail() { note "- FAIL: $*"; echo "::error::$*"; fails=$((fails + 1)); }++note "## Mac local hardening probe (macOS $(sw_vers -productVersion), $(uname -m))"++# A stand-in home and data folder with something to steal in each denied place+mkdir -p "$H/.claude" "$H/.codex" "$H/.grok" "$H/Library/Keychains" "$H/work" "$D/profiles/p1" \+ "$D/backups" "$D/mcp" "$D/run/mcp-cwd/t1" "$D/laya" "$D/bin"+echo SECRET-claude > "$H/.claude/kwnt-probe-secret.txt"+echo SECRET-shm > "$D/kwnt.db-shm"+echo SECRET-backup > "$D/backups/kwnt-1.db"+echo SECRET-mcp > "$D/mcp/claude-1.json"+echo SECRET-run > "$D/run/mcp-cwd/t1/x"+# What kwnt loads or runs at its next start: readable, not writable+echo start-config > "$D/config.toml"+echo start-laya > "$D/laya/serve.py"+echo start-bin > "$D/bin/uv"+echo SECRET-codex > "$H/.codex/auth.json"+echo SECRET-grok > "$H/.grok/user-settings.json"+echo SECRET-keychain-file > "$H/Library/Keychains/probe.keychain-db"+echo SECRET-token > "$D/api-token"+echo SECRET-db > "$D/kwnt.db"+echo SECRET-profile > "$D/profiles/p1/.credentials.json"+echo ok > "$H/work/ok.txt"++settings_for() { # <home> <out> [data folder, default $D]+ env HOME="$1" KWNT_DATA_DIR="${3:-$D}" KWNT_MAC_SETTINGS_OUT="$2" \+ "$BIN" --ignored --exact drivers::mac_local::tests::write_settings_for_the_mac_ci_probe -q > "$2.log" 2>&1 \+ || { cat "$2.log"; return 1; }+}+settings_for "$H" "$T/settings.json" || { fail "couldn't write kwnt's settings"; exit 1; }+note ""+note "### kwnt's settings for a Mac turn (Seatbelt on)"+python3 -c 'import json,sys; s=json.load(open(sys.argv[1])); print(len(s["permissions"]["deny"]), "deny rules;", "sandbox.denyRead:", s["sandbox"]["filesystem"]["denyRead"])' "$T/settings.json" | tee -a "$SUMMARY"+if python3 -c 'import json,sys; sys.exit(json.load(open(sys.argv[1])).get("autoMemoryEnabled") is not False)' "$T/settings.json"; then+ pass "autoMemoryEnabled is false"+else+ fail "autoMemoryEnabled isn't false"+fi++# --- 1. The real Claude Code reads them ------------------------------------------------------+note ""+note "### 1. Claude Code $CLAUDE_VERSION accepts them"+npm install --silent --no-audit --no-fund --prefix "$T/cc" "@anthropic-ai/claude-code@$CLAUDE_VERSION" > "$T/cc.log" 2>&1 || { cat "$T/cc.log"; fail "npm install claude-code"; }+CLAUDE="$T/cc/node_modules/.bin/claude"+if [ -x "$CLAUDE" ]; then+ # No sign-in: Claude loads its settings, then fails to reach the model. 90 s at most.+ env -i HOME="$H" PATH="$(dirname "$(command -v node)"):/usr/bin:/bin" \+ perl -e 'alarm 90; exec @ARGV' "$CLAUDE" --debug --settings "$(cat "$T/settings.json")" -p hi < /dev/null > "$T/claude.out" 2>&1+ echo "claude exit $? (expected to fail: not signed in)"+ LOG=$(ls -t "$H/.claude/debug/"* 2>/dev/null | head -1)+ want=$(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["permissions"]["deny"]))' "$T/settings.json")+ if [ -n "$LOG" ] && grep -q "Adding $want deny rule(s) to destination 'flagSettings'" "$LOG"; then+ pass "Claude's debug log: \"Adding $want deny rule(s) to destination 'flagSettings'\""+ else+ fail "Claude didn't report adding $want deny rules from --settings"+ [ -n "$LOG" ] && grep -i "settings\|deny\|invalid" "$LOG" | head -20+ head -40 "$T/claude.out"+ fi+ if [ -n "$LOG" ]; then+ note "Claude's sandbox lines (informational):"+ { grep -i "sandbox" "$LOG" | head -15 | sed 's/^/ /'; } | tee -a "$SUMMARY"+ fi+else+ fail "claude not installed"+fi++# --- 2. Seatbelt enforces the sandbox half (sandbox-runtime) ---------------------------------+note ""+note "### 2. Seatbelt (sandbox-runtime $SRT_VERSION) enforces the same sections"+npm install --silent --no-audit --no-fund --prefix "$T/srt" "@anthropic-ai/sandbox-runtime@$SRT_VERSION" > "$T/srt.log" 2>&1 || { cat "$T/srt.log"; fail "npm install sandbox-runtime"; }+SRT="$T/srt/node_modules/.bin/srt"+srt_settings() { # <kwnt settings> <out>: Claude's sandbox.filesystem/network use srt's own format+ python3 -c 'import json,sys; s=json.load(open(sys.argv[1]))["sandbox"]; json.dump({"filesystem": s["filesystem"], "network": dict(s["network"], deniedDomains=[])}, open(sys.argv[2], "w"), indent=1)' "$1" "$2"+}+in_sandbox() { # <srt settings> <home> <command...>: runs it, output in $T/out+ local f="$1" home="$2"; shift 2+ (cd "$home" && env HOME="$home" perl -e 'alarm 60; exec @ARGV' "$SRT" --settings "$f" "$@") > "$T/out" 2>&1+}+if [ -x "$SRT" ]; then+ # After step 1, which ran Claude in this home and let it write its own ~/.claude.json+ echo '{"primaryApiKey": "SECRET-claude-json"}' > "$H/.claude.json"+ srt_settings "$T/settings.json" "$T/srt.json"+ in_sandbox "$T/srt.json" "$H" cat "$H/work/ok.txt"+ if [ $? -eq 0 ] && grep -qx ok "$T/out"; then pass "an ordinary file in the home folder is still readable"; else fail "the sandbox didn't run an allowed read: $(head -5 "$T/out")"; fi+ for f in "$H/.claude/kwnt-probe-secret.txt" "$H/.claude.json" "$H/.codex/auth.json" "$H/.grok/user-settings.json" \+ "$H/Library/Keychains/probe.keychain-db" "$D/api-token" "$D/kwnt.db" "$D/kwnt.db-shm" \+ "$D/profiles/p1/.credentials.json" "$D/backups/kwnt-1.db" "$D/mcp/claude-1.json" "$D/run/mcp-cwd/t1/x"; do+ in_sandbox "$T/srt.json" "$H" cat "$f"+ rc=$?+ if [ $rc -ne 0 ] && ! grep -q SECRET "$T/out"; then pass "read denied: ${f#$T/}"; else fail "read NOT denied: ${f#$T/} (exit $rc)"; fi+ done+ in_sandbox "$T/srt.json" "$H" sh -c "echo planted > '$H/.claude/settings.json'"+ if [ ! -e "$H/.claude/settings.json" ]; then pass "write denied: home/.claude/settings.json"; else fail "write NOT denied: home/.claude/settings.json"; fi+ for f in "$D/config.toml" "$D/laya/serve.py" "$D/bin/uv"; do+ in_sandbox "$T/srt.json" "$H" cat "$f"+ if [ $? -eq 0 ] && grep -q "^start-" "$T/out"; then pass "readable: ${f#$T/}"; else fail "kwnt's start file NOT readable: ${f#$T/}"; fi+ before=$(cat "$f")+ in_sandbox "$T/srt.json" "$H" sh -c "echo planted > '$f'"+ if [ "$(cat "$f")" = "$before" ]; then pass "write denied: ${f#$T/}"; else fail "write NOT denied: ${f#$T/}"; fi+ done+ mkdir -p "$D/workspace"+ in_sandbox "$T/srt.json" "$H" sh -c "echo new > '$D/workspace/new.txt'"+ if [ -e "$D/workspace/new.txt" ]; then pass "a write elsewhere in the data folder still works"; else fail "a write in data/workspace failed: $(head -5 "$T/out")"; fi+ in_sandbox "$T/srt.json" "$H" sh -c "echo planted > '$D/bin/new-tool'"+ if [ ! -e "$D/bin/new-tool" ]; then pass "a new file in data/bin is denied"; else fail "a new file in data/bin was NOT denied"; fi+ # The data folder named through a link: Seatbelt matches real paths, so the resolved spelling+ # has to be in the settings too+ ln -s "$D" "$T/data-link"+ if settings_for "$H" "$T/settings-link.json" "$T/data-link"; then+ srt_settings "$T/settings-link.json" "$T/srt-link.json"+ in_sandbox "$T/srt-link.json" "$H" cat "$D/api-token"+ rc=$?+ if [ $rc -ne 0 ] && ! grep -q SECRET "$T/out"; then pass "read denied through a linked data folder: data/api-token"; else fail "read NOT denied through a linked data folder (exit $rc)"; fi+ else+ fail "couldn't write kwnt's settings for a linked data folder"+ fi+ in_sandbox "$T/srt.json" "$H" sh -c "echo new > '$H/work/new.txt'"+ if [ -e "$H/work/new.txt" ]; then pass "a write in the home folder still works"; else fail "a write in the home folder failed: $(head -5 "$T/out")"; fi+ in_sandbox "$T/srt.json" "$H" curl -sS -m 15 -o /dev/null https://example.com+ rc=$?+ if [ $rc -ne 0 ]; then pass "network to an unlisted domain blocked (curl exit $rc; in Claude this would ask)"; else fail "network to example.com NOT blocked"; fi+else+ fail "srt not installed"+fi++# --- 3. The Keychain (reported, not enforced) --------------------------------------------------+note ""+note "### 3. Keychain through the security service (reported only)"+KC_SERVICE="kwnt-ci-probe-$$"+if [ -x "$SRT" ] && security add-generic-password -a kwnt-ci -s "$KC_SERVICE" -w "probe-value-$$" -U > /dev/null 2>&1; then+ outside=$(security find-generic-password -s "$KC_SERVICE" -w 2>/dev/null)+ settings_for "$REAL_HOME" "$T/settings-real.json" && srt_settings "$T/settings-real.json" "$T/srt-real.json"+ login_kc=$(ls "$REAL_HOME"/Library/Keychains/login.keychain-db 2>/dev/null | head -1)+ if [ -n "$login_kc" ]; then+ in_sandbox "$T/srt-real.json" "$REAL_HOME" cat "$login_kc"+ if [ $? -ne 0 ]; then pass "reading the login keychain file is denied"; else fail "reading the login keychain file NOT denied"; fi+ fi+ in_sandbox "$T/srt-real.json" "$REAL_HOME" security find-generic-password -s "$KC_SERVICE" -w+ inside=$(cat "$T/out")+ if [ "$outside" != "probe-value-$$" ]; then+ note "- UNKNOWN: the probe item couldn't be read even outside the sandbox"+ elif printf '%s' "$inside" | grep -q "probe-value-$$"; then+ note "- NOT PROTECTED: a sandboxed \`security find-generic-password\` read a Keychain item (the Seatbelt profile allows the securityd service). Claude keeps its sign-in in the Keychain as \"Claude Code-credentials\"."+ echo "::warning::Keychain items are readable from inside the sandbox via the security service"+ else+ note "- BLOCKED: a sandboxed \`security find-generic-password\` got nothing: $(head -3 "$T/out")"+ fi+ security delete-generic-password -s "$KC_SERVICE" > /dev/null 2>&1 || true+else+ note "- UNKNOWN: couldn't add a probe item to this runner's Keychain"+fi++note ""+note "Result: $fails failure(s)"+exit $((fails > 0))diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex a9029e63..9a85771c 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -675,6 +675,26 @@ impl CliDriver {self.grok_home = Some(dir);self}++ /// Arguments for a turn on this computer (not in the VM): the profile's overrides and, for+ /// Claude on a Mac, the local hardening ([`super::mac_local`]), as one `--settings` object.+ fn local_settings_args(&self, is_mac: bool) -> Vec<String> {+ let mut args = self.profile_env.as_ref().map(|e| e.args.clone()).unwrap_or_default();+ if !super::mac_local::applies(is_mac, &self.tool_kind, false) {+ return args;+ }+ let profile_home = self.profile_env.as_ref().and_then(|e| {+ e.set.iter().find(|(k, _)| k == "CLAUDE_CONFIG_DIR").map(|(_, v)| std::path::PathBuf::from(v))+ });+ let Some(places) = super::mac_local::Places::here(profile_home) else {+ tracing::warn!("no home folder: Claude runs without the Mac hardening");+ return args;+ };+ let seatbelt = super::mac_local::seatbelt_on(std::env::var(super::mac_local::SEATBELT_ENV).ok().as_deref());+ let sock = std::env::var("SSH_AUTH_SOCK").ok();+ super::mac_local::merge_settings_arg(&mut args, super::mac_local::settings(&places, seatbelt, sock.as_deref()));+ args+ }}/// Longest stderr tail kept from a grok run.@@ -1749,10 +1769,12 @@ impl Driver for CliDriver {// The container's claude, its own home and a stand-in credential; the profile's// home and this computer's settings never reach itcmd = t.wrap(&cmd);- } else if let Some(env) = &self.profile_env {- env.apply(&mut 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 options- cmd.args(&env.args);+ cmd.args(self.local_settings_args(cfg!(target_os = "macos")));}// codex's reply comes from its -o file; its stdout carries the `--json` steps@@ -2548,6 +2570,58 @@ endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\n}}+ /// 079-mac-local-hardening: on a Mac, a Claude turn on this computer gets the deny rules+ /// in the same `--settings` as its profile's overrides; Codex, Grok and Linux get nothing new+ #[test]+ fn a_mac_claude_turn_gets_one_settings_with_the_hardening() {+ let profile = tempfile::tempdir().unwrap();+ let one = |kind: &str, with_profile: bool, mac: bool| {+ let mut d = CliDriver::new(Some("/bin/true".into()), Some(kind.into()));+ if with_profile {+ d = d.with_profile_home(crate::profiles::Engine::Claude, profile.path().to_path_buf());+ }+ d.local_settings_args(mac)+ };+ let settings_of = |args: &[String]| -> serde_json::Value {+ assert_eq!(args.iter().filter(|a| *a == "--settings").count(), 1, "{args:?}");+ let i = args.iter().position(|a| a == "--settings").unwrap();+ serde_json::from_str(&args[i + 1]).unwrap()+ };+ let v = settings_of(&one("claude", true, true));+ assert!(v["env"].is_object(), "the profile's overrides stay: {v}");+ let deny: Vec<String> = serde_json::from_value(v["permissions"]["deny"].clone()).unwrap();+ let home = dirs::home_dir().unwrap();+ let want = format!("Read(/{}/**)", home.join(".claude").display());+ assert!(deny.contains(&want), "{want} not in {deny:?}");+ let want = format!("Read(/{}/**)", profile.path().display());+ assert!(deny.contains(&want), "the profile's home: {want} not in {deny:?}");+ // Without a profile: the hardening alone+ let v = settings_of(&one("claude", false, true));+ assert!(v.get("env").is_none() && v["permissions"]["deny"].is_array(), "{v}");+ // Not a Mac, or not Claude: exactly what was there before+ assert_eq!(one("claude", false, false), Vec::<String>::new());+ let before = crate::profiles::CliEnv::for_home(crate::profiles::Engine::Claude, profile.path()).args;+ assert_eq!(one("claude", true, false), before);+ assert_eq!(one("codex", false, true), Vec::<String>::new());+ assert_eq!(one("grok", false, true), Vec::<String>::new());+ }++ /// The flag reaches the CLI: on macOS the fake claude sees one `--settings` with the deny+ /// rules; elsewhere it sees none (no profile)+ #[tokio::test]+ async fn the_hardening_reaches_claudes_command_line_on_a_mac_only() {+ let fake = Fake::new("claude", &format!("{RECORD}\necho '{CLAUDE_RESULT}'"));+ fake.run(turn(false)).await.unwrap();+ let argv = fake.argv();+ let settings: Vec<&String> = argv.windows(2).filter(|w| w[0] == "--settings").map(|w| &w[1]).collect();+ if cfg!(target_os = "macos") {+ assert_eq!(settings.len(), 1, "{argv:?}");+ assert!(settings[0].contains("\"deny\"") && settings[0].contains(".claude/**"), "{argv:?}");+ } else {+ assert!(settings.is_empty(), "{argv:?}");+ }+ }+const CLAUDE_INIT_EMPTY: &str = r#"{"type":"system","subtype":"init","tools":[],"mcp_servers":[],"skills":[],"slash_commands":[]}"#;const CLAUDE_RESULT: &str = r#"{"type":"result","subtype":"success","is_error":false,"num_turns":1,"result":"The card."}"#;diff --git a/src/drivers/mac_local.rs b/src/drivers/mac_local.rsnew file mode 100644index 00000000..7207831c--- /dev/null+++ b/src/drivers/mac_local.rs@@ -0,0 +1,495 @@+//! Hardening for Claude turns in Mac "local" mode (0.8.0 F, item 079-mac-local-hardening;+//! agents-in-vm design.md Q6). Without the VM, Claude runs on the Mac itself, so a bot talked into+//! it by a web page, a file or another bot could `cat` a sign-in or plant a hook in+//! `~/.claude/settings.json`. This adds one `--settings` layer that:+//!+//! - denies Claude's file tools (Read, Grep, Glob, Edit, Write) the sign-in folders and kwnt's+//! secrets (`Read(…)` and `Edit(…)` deny rules), and denies them changes to what kwnt loads or+//! runs at its next start (`config.toml`, `laya/`, `bin/`: `Edit(…)` only). **Without+//! `KWNT_MAC_SEATBELT` that is all**: the rules cover Claude's file tools only, and a shell+//! command the person approves can still read these places and Keychain items;+//! - with `KWNT_MAC_SEATBELT=1`, turns on Claude's own Seatbelt sandbox for Bash with the same+//! paths in `sandbox.filesystem.denyRead` and `denyWrite`, so `cat ~/.claude/.credentials.json`+//! or a script reading the Keychain *files* fails at the OS level. Keychain items reached+//! through macOS's security service (`security find-generic-password`) are not proven safe: on+//! CI's Mac runner a sandboxed lookup couldn't read the probe item, but that runner's keychain+//! isn't a person's login or iCloud keychain, so it's untested on a real Mac+//! (`.github/workflows/mac-local.yml`);+//! - turns off Claude's auto memory (`autoMemoryEnabled: false`): it writes inside the denied+//! `~/.claude` (or the profile's home), so every try would fail or ask;+//! - keeps kwnt in charge of every command: `autoAllowBashIfSandboxed: false` (a sandboxed+//! command still asks kwnt, as today) and `allowUnsandboxedCommands: false` (the bot can't opt+//! a command out of the sandbox).+//!+//! What it does **not** do (design.md Q6): the Claude process itself still reads its own sign-in+//! and the Keychain, as it must to run. This protects against a tricked bot's *tools*, not+//! against the CLI. The VM ("Run Claude inside the VM") is the protection for that.+//!+//! Writes stay as broad as today (`allowWrite: ["~"]`, plus Claude's own denyWrite list for shell+//! start-up files and `~/.claude`).+//!+//! **The Seatbelt half is opt-in for now** (`KWNT_MAC_SEATBELT=1`); the deny rules for the file+//! tools are always on. With the sandbox on, Bash's network goes through Claude's proxy, which asks+//! before each new domain (kwnt shows that as an approval card; `localhost` and `127.0.0.1`, kwnt's+//! own API, are allowed), and Unix sockets other than `$SSH_AUTH_SOCK` are blocked (Docker). Writes+//! outside the home folder fail. None+//! of that can be tried without a real Mac (CI has no signed-in Claude), so it stays off until it+//! has been tried on one.++use serde_json::{json, Map, Value};+use std::path::{Path, PathBuf};+use std::sync::RwLock;++/// Turns the Seatbelt sandbox on when `1`, `on`, `true` or `yes`. The deny rules apply either way.+pub const SEATBELT_ENV: &str = "KWNT_MAC_SEATBELT";++/// The running kwnt's data folder (`config.data_dir`: `--data-dir`, config.toml's `data_dir`,+/// `KWNT_DATA_DIR` or `~/.kwnt`), set by [`crate::serve::run`]. Replaceable, not a `OnceLock`:+/// the Mac app can start the server again in the same process.+static DATA_DIR: RwLock<Option<PathBuf>> = RwLock::new(None);++/// Records the data folder the server runs on, so every rule names the folder actually in use.+pub fn set_data_dir(dir: &Path) {+ let dir = std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf());+ if let Ok(mut d) = DATA_DIR.write() {+ *d = Some(dir);+ }+}++/// The data folder for the rules: the running server's ([`set_data_dir`]) first; without a server+/// (the CI probe, a test) `KWNT_DATA_DIR`, else `~/.kwnt`, as [`crate::config::Config::load`] does.+fn data_dir_for(running: Option<PathBuf>, env: Option<std::ffi::OsString>) -> PathBuf {+ running+ .or_else(|| env.filter(|d| !d.is_empty()).map(PathBuf::from))+ .unwrap_or_else(crate::config::default_data_dir)+}++/// One denied place: an absolute Mac path, a folder (`dir`) or a file, and whether reading it is+/// denied too (`read`) or only changing it (kwnt's own config and the programs it starts).+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Denied {+ pub path: String,+ pub dir: bool,+ pub read: bool,+}++/// The places a bot's tools never read or write, for one turn.+#[derive(Debug, Clone, PartialEq)]+pub struct Places {+ pub home: PathBuf,+ pub data_dir: PathBuf,+ /// The profile's own sign-in home (`CLAUDE_CONFIG_DIR`), when the turn runs on one.+ pub profile_home: Option<PathBuf>,+}++impl Places {+ /// This computer's: `$HOME`, the running kwnt's data folder (see [`data_dir_for`]) and the+ /// profile's home. `None` without a home folder.+ pub fn here(profile_home: Option<PathBuf>) -> Option<Self> {+ let home = dirs::home_dir()?;+ let running = DATA_DIR.read().ok().and_then(|d| d.clone());+ let data_dir = data_dir_for(running, std::env::var_os("KWNT_DATA_DIR"));+ Some(Self { home, data_dir, profile_home })+ }++ /// The places to deny, absolute, without repeats. Mac paths, joined with `/` as strings:+ /// `Path::join` would use `\` when this is compiled for Windows (CI's rust (windows) runs+ /// these tests), and the rules are only ever read on a Mac. Where a place (or the folder it+ /// is in) is reached through a link, its resolved spelling is listed too: Seatbelt matches+ /// real paths, so `/var/…` alone wouldn't cover `/private/var/…`.+ pub fn denied(&self) -> Vec<Denied> {+ let h = mac_path(&self.home);+ let d = mac_path(&self.data_dir);+ let secret = |path: String, dir: bool| Denied { path, dir, read: true };+ let no_edit = |path: String, dir: bool| Denied { path, dir, read: false };+ let mut list: Vec<Denied> = vec![+ secret(mac_join(&h, ".claude"), true),+ // Claude's primaryApiKey and MCP servers' env and headers+ secret(mac_join(&h, ".claude.json"), false),+ secret(mac_join(&h, ".codex"), true),+ secret(mac_join(&h, ".grok"), true),+ // The login and other keychains' files. Reaching the Keychain through its service+ // (`security find-generic-password`) is Seatbelt's mach-lookup rule, not this one+ secret(mac_join(&h, "Library/Keychains"), true),+ secret(mac_join(&d, "profiles"), true),+ secret(mac_join(&d, crate::sandbox::credentials::VAULT_DIR), true),+ secret(mac_join(&d, crate::sandbox::credentials::KEY_FILE), false),+ secret(mac_join(&d, "api-token"), false),+ secret(mac_join(&d, "kwnt.db"), false),+ secret(mac_join(&d, "kwnt.db-wal"), false),+ secret(mac_join(&d, "kwnt.db-shm"), false),+ // Copies of the database, with its API keys and OAuth tokens (db/spaces.rs)+ secret(mac_join(&d, "backups"), true),+ // Each turn's claude-<uuid>.json, with MCP headers and env (mcp/cli_config.rs)+ secret(mac_join(&d, "mcp"), true),+ // run/mcp-cwd/<turn token> (server/mcp_runtime.rs)+ secret(mac_join(&d, "run"), true),+ // What kwnt loads or runs at its next start: readable, never changed by a bot+ no_edit(mac_join(&d, "config.toml"), false),+ no_edit(mac_join(&d, "laya"), true),+ no_edit(mac_join(&d, "bin"), true),+ ];+ // The CLIs' own homes when moved with their variables (absolute Mac paths only)+ for var in ["CLAUDE_CONFIG_DIR", "CODEX_HOME", "GROK_HOME"] {+ if let Some(p) = std::env::var_os(var).filter(|v| !v.is_empty()) {+ let p = mac_path(Path::new(&p));+ if p.starts_with('/') {+ list.push(secret(p, true));+ }+ }+ }+ if let Some(p) = &self.profile_home {+ list.push(secret(mac_path(p), true));+ }+ // Only a Mac reads these rules; elsewhere a resolved path wouldn't be a Mac path+ if cfg!(unix) {+ let resolved: Vec<Denied> = list+ .iter()+ .filter_map(|x| resolved(&x.path).map(|path| Denied { path, ..x.clone() }))+ .collect();+ list.extend(resolved);+ }+ let mut out: Vec<Denied> = Vec::new();+ for x in list {+ match out.iter_mut().find(|y| y.path == x.path) {+ Some(y) => y.read |= x.read,+ None => out.push(x),+ }+ }+ out+ }+}++/// `p`'s spelling with links resolved, when it differs: the nearest part of it that exists is+/// resolved and the rest appended (a denied file need not exist yet). `None` when nothing+/// resolves differently.+fn resolved(p: &str) -> Option<String> {+ let mut base = Path::new(p);+ let mut rest: Vec<String> = Vec::new();+ let real = loop {+ if let Ok(r) = std::fs::canonicalize(base) {+ break mac_path(&r);+ }+ rest.push(base.file_name()?.to_str()?.to_string());+ base = base.parent()?;+ };+ let full = rest.iter().rev().fold(real, |acc, c| mac_join(&acc, c));+ (full.starts_with('/') && full != p).then_some(full)+}++/// A path as a Mac path string, without a trailing `/` (but `/` itself stays `/`).+fn mac_path(p: &Path) -> String {+ let s = p.to_string_lossy();+ let t = s.trim_end_matches('/');+ if t.is_empty() && s.starts_with('/') {+ "/".into()+ } else {+ t.into()+ }+}++/// `base/rel` with `/`, whatever OS this is compiled for.+fn mac_join(base: &str, rel: &str) -> String {+ format!("{}/{rel}", base.trim_end_matches('/'))+}++/// Whether a turn gets [`settings`]: Claude, on a Mac, on this computer (not in the VM).+pub fn applies(is_mac: bool, tool_kind: &str, isolated: bool) -> bool {+ is_mac && tool_kind == "claude" && !isolated+}++/// Whether the Seatbelt half is on, given `KWNT_MAC_SEATBELT`'s value (opt-in, see the module doc).+pub fn seatbelt_on(env: Option<&str>) -> bool {+ matches!(env.map(|v| v.trim().to_ascii_lowercase()).as_deref(), Some("1" | "on" | "true" | "yes"))+}++/// A permission-rule path: `//abs/path` is absolute in Claude's rule syntax (a single `/` would be+/// relative to the settings file).+fn rule_path(p: &str, dir: bool) -> String {+ let s = p.trim_end_matches('/');+ if dir {+ format!("/{s}/**")+ } else {+ format!("/{s}")+ }+}++/// The `--settings` object for one turn. `ssh_auth_sock`: the agent socket Bash may still reach+/// (git over ssh) when the sandbox is on.+pub fn settings(places: &Places, seatbelt: bool, ssh_auth_sock: Option<&str>) -> Value {+ let denied = places.denied();+ let mut deny = Vec::new();+ for x in denied.iter().filter(|x| x.read) {+ deny.push(Value::from(format!("Read({})", rule_path(&x.path, x.dir))));+ }+ for x in &denied {+ deny.push(Value::from(format!("Edit({})", rule_path(&x.path, x.dir))));+ }+ let mut out = Map::new();+ out.insert("permissions".into(), json!({ "deny": deny }));+ // Auto memory writes under <claude home>/projects/*/memory, inside the denied ~/.claude (or+ // the profile's home): every try would fail or ask+ out.insert("autoMemoryEnabled".into(), Value::Bool(false));+ if seatbelt {+ let read: Vec<Value> = denied.iter().filter(|x| x.read).map(|x| Value::from(x.path.as_str())).collect();+ let write: Vec<Value> = denied.iter().map(|x| Value::from(x.path.as_str())).collect();+ out.insert(+ "sandbox".into(),+ json!({+ "enabled": true,+ // A Mac always has Seatbelt; if it can't start, Claude warns and Bash runs as+ // today rather than every turn failing+ "failIfUnavailable": false,+ "autoAllowBashIfSandboxed": false,+ "allowUnsandboxedCommands": false,+ "filesystem": {+ "denyRead": read,+ "denyWrite": write,+ "allowWrite": ["~"],+ },+ "network": {+ // kwnt's own API, which the bot's tools block tells it to call with curl+ "allowedDomains": ["localhost", "127.0.0.1"],+ "allowUnixSockets": ssh_auth_sock.filter(|s| s.starts_with('/')).into_iter().collect::<Vec<_>>(),+ },+ }),+ );+ }+ Value::Object(out)+}++/// Merges `extra` into the `--settings` JSON already in `args` (a profile's env overrides), or+/// appends `--settings extra`. Claude reads one `--settings`, so they must be one object.+pub fn merge_settings_arg(args: &mut Vec<String>, extra: Value) {+ if let Some(i) = args.iter().position(|a| a == "--settings") {+ if let Some(Ok(Value::Object(mut have))) = args.get(i + 1).map(|v| serde_json::from_str::<Value>(v)) {+ if let Value::Object(add) = extra {+ for (k, v) in add {+ have.insert(k, v);+ }+ }+ args[i + 1] = Value::Object(have).to_string();+ return;+ }+ }+ args.push("--settings".into());+ args.push(extra.to_string());+}++#[cfg(test)]+mod tests {+ use super::*;++ fn places() -> Places {+ Places { home: "/Users/o".into(), data_dir: "/Users/o/.kwnt".into(), profile_home: Some("/Users/o/.kwnt/profiles/p1".into()) }+ }++ fn strs(v: &Value) -> Vec<String> {+ v.as_array().unwrap().iter().map(|x| x.as_str().unwrap().to_string()).collect()+ }++ #[test]+ fn only_claude_on_a_mac_outside_the_vm() {+ assert!(applies(true, "claude", false));+ assert!(!applies(true, "claude", true), "the VM has its own walls");+ assert!(!applies(false, "claude", false), "Seatbelt is macOS only");+ for other in ["codex", "grok", "gemini"] {+ assert!(!applies(true, other, false), "{other}");+ }+ }++ #[test]+ fn the_sign_ins_and_kwnts_secrets_are_denied_to_tools_and_bash() {+ let s = settings(&places(), true, Some("/private/tmp/launchd-1/Listeners"));+ let deny = strs(&s["permissions"]["deny"]);+ for want in [+ "Read(//Users/o/.claude/**)",+ "Read(//Users/o/.codex/**)",+ "Read(//Users/o/.grok/**)",+ "Read(//Users/o/Library/Keychains/**)",+ "Read(//Users/o/.kwnt/profiles/**)",+ "Read(//Users/o/.kwnt/kwnt-vault/**)",+ "Read(//Users/o/.kwnt/kwnt-vault.key)",+ "Read(//Users/o/.kwnt/api-token)",+ "Read(//Users/o/.kwnt/kwnt.db)",+ "Read(//Users/o/.kwnt/kwnt.db-wal)",+ "Read(//Users/o/.kwnt/kwnt.db-shm)",+ "Read(//Users/o/.claude.json)",+ "Read(//Users/o/.kwnt/backups/**)",+ "Read(//Users/o/.kwnt/mcp/**)",+ "Read(//Users/o/.kwnt/run/**)",+ "Edit(//Users/o/.claude/**)",+ "Edit(//Users/o/.claude.json)",+ "Edit(//Users/o/.kwnt/api-token)",+ "Edit(//Users/o/.kwnt/backups/**)",+ ] {+ assert!(deny.contains(&want.to_string()), "{want} missing from {deny:?}");+ }+ // The profile's home sits inside profiles/ here, but is listed too (it may live elsewhere)+ assert!(deny.contains(&"Read(//Users/o/.kwnt/profiles/p1/**)".to_string()));+ let sb = &s["sandbox"];+ assert_eq!(sb["enabled"], true);+ assert_eq!(sb["autoAllowBashIfSandboxed"], false, "kwnt still decides every command");+ assert_eq!(sb["allowUnsandboxedCommands"], false, "a bot can't take a command out of the sandbox");+ assert_eq!(sb["failIfUnavailable"], false);+ let read = strs(&sb["filesystem"]["denyRead"]);+ for want in [+ "/Users/o/.claude",+ "/Users/o/.claude.json",+ "/Users/o/.codex",+ "/Users/o/.grok",+ "/Users/o/Library/Keychains",+ "/Users/o/.kwnt/kwnt-vault.key",+ "/Users/o/.kwnt/kwnt.db-shm",+ "/Users/o/.kwnt/backups",+ "/Users/o/.kwnt/mcp",+ "/Users/o/.kwnt/run",+ ] {+ assert!(read.contains(&want.to_string()), "{want} missing from {read:?}");+ }+ // Everything unreadable is unwritable too+ let write = strs(&sb["filesystem"]["denyWrite"]);+ for p in &read {+ assert!(write.contains(p), "{p} readable-denied but writable: {write:?}");+ }+ assert_eq!(sb["filesystem"]["allowWrite"], json!(["~"]), "writes stay as broad as today");+ // The bot's own folder and kwnt's other files aren't touched+ assert!(!read.iter().any(|p| p == "/Users/o/.kwnt" || p == "/Users/o"), "{read:?}");+ assert_eq!(sb["network"]["allowedDomains"], json!(["localhost", "127.0.0.1"]), "kwnt's own API needs no card");+ assert_eq!(sb["network"]["allowUnixSockets"], json!(["/private/tmp/launchd-1/Listeners"]), "git over ssh keeps its agent");+ let s = settings(&places(), true, None);+ assert_eq!(s["sandbox"]["network"]["allowUnixSockets"], json!([]));+ }++ #[test]+ fn the_seatbelt_half_is_opt_in_and_the_rules_apply_either_way() {+ for on in ["1", "on", "TRUE", " yes "] {+ assert!(seatbelt_on(Some(on)), "{on}");+ }+ for off in [None, Some("0"), Some("off"), Some(""), Some("maybe")] {+ assert!(!seatbelt_on(off), "{off:?}");+ }+ let s = settings(&places(), false, None);+ assert!(s.get("sandbox").is_none());+ assert!(!strs(&s["permissions"]["deny"]).is_empty());+ }++ #[test]+ fn one_settings_object_with_a_profiles_overrides() {+ let mut args = vec!["--settings".to_string(), json!({ "env": { "ANTHROPIC_BASE_URL": "" } }).to_string()];+ merge_settings_arg(&mut args, settings(&places(), true, None));+ assert_eq!(args.iter().filter(|a| *a == "--settings").count(), 1, "{args:?}");+ let v: Value = serde_json::from_str(&args[1]).unwrap();+ assert_eq!(v["env"]["ANTHROPIC_BASE_URL"], "", "the profile's overrides stay");+ assert_eq!(v["sandbox"]["enabled"], true);+ // No profile: appended+ let mut args = vec!["-p".to_string(), "hi".to_string()];+ merge_settings_arg(&mut args, json!({ "permissions": {} }));+ assert_eq!(args[2], "--settings");+ }++ #[test]+ fn paths_become_absolute_rules() {+ assert_eq!(rule_path("/Users/o/.claude/", true), "//Users/o/.claude/**");+ assert_eq!(rule_path("/Users/o/.kwnt/api-token", false), "//Users/o/.kwnt/api-token");+ }++ #[test]+ fn the_rules_use_mac_slashes_whatever_os_builds_them() {+ assert_eq!(mac_join("/Users/o/", ".claude"), "/Users/o/.claude");+ assert_eq!(mac_join("/", "x"), "/x");+ assert_eq!(mac_path(Path::new("/Users/o/.kwnt/")), "/Users/o/.kwnt");+ assert_eq!(mac_path(Path::new("/")), "/");+ let s = settings(&places(), true, None);+ let all = strs(&s["permissions"]["deny"]).into_iter().chain(strs(&s["sandbox"]["filesystem"]["denyRead"]));+ for r in all {+ assert!(!r.contains('\\'), "{r}");+ }+ }++ #[test]+ fn kwnts_start_files_are_readable_but_never_changed() {+ let s = settings(&places(), true, None);+ let deny = strs(&s["permissions"]["deny"]);+ let read = strs(&s["sandbox"]["filesystem"]["denyRead"]);+ let write = strs(&s["sandbox"]["filesystem"]["denyWrite"]);+ for (path, rule) in [+ ("/Users/o/.kwnt/config.toml", "/Users/o/.kwnt/config.toml"),+ ("/Users/o/.kwnt/laya", "/Users/o/.kwnt/laya/**"),+ ("/Users/o/.kwnt/bin", "/Users/o/.kwnt/bin/**"),+ ] {+ assert!(deny.contains(&format!("Edit(/{rule})")), "Edit {rule} missing from {deny:?}");+ assert!(!deny.contains(&format!("Read(/{rule})")), "{rule} must stay readable: {deny:?}");+ assert!(write.contains(&path.to_string()), "{path} missing from denyWrite {write:?}");+ assert!(!read.contains(&path.to_string()), "{path} must stay readable in Bash: {read:?}");+ }+ }++ #[test]+ fn auto_memory_is_off_because_its_folder_is_denied() {+ for seatbelt in [false, true] {+ assert_eq!(settings(&places(), seatbelt, None)["autoMemoryEnabled"], json!(false), "seatbelt {seatbelt}");+ }+ }++ #[test]+ fn the_rules_name_the_running_servers_data_folder() {+ // A data folder from config.toml (or --data-dir), not from the environment+ let config: crate::config::Config = toml::from_str("data_dir = \"/Volumes/ext/kwnt\"").unwrap();+ let env = Some(std::ffi::OsString::from("/Users/o/.kwnt"));+ assert_eq!(data_dir_for(Some(config.data_dir.clone()), env.clone()), PathBuf::from("/Volumes/ext/kwnt"));+ // Without a running server: KWNT_DATA_DIR, else ~/.kwnt+ assert_eq!(data_dir_for(None, env), PathBuf::from("/Users/o/.kwnt"));+ assert_eq!(data_dir_for(None, Some("".into())), crate::config::default_data_dir());+ let p = Places { home: "/Users/o".into(), data_dir: config.data_dir, profile_home: None };+ let deny = strs(&settings(&p, false, None)["permissions"]["deny"]);+ for want in ["Read(//Volumes/ext/kwnt/api-token)", "Read(//Volumes/ext/kwnt/kwnt.db)", "Read(//Volumes/ext/kwnt/profiles/**)"] {+ assert!(deny.contains(&want.to_string()), "{want} missing from {deny:?}");+ }+ assert!(!deny.iter().any(|r| r.contains("/Users/o/.kwnt/")), "{deny:?}");+ // What serve::run records is what a turn's rules use+ let dir = tempfile::tempdir().unwrap();+ set_data_dir(dir.path());+ assert_eq!(Places::here(None).unwrap().data_dir, std::path::absolute(dir.path()).unwrap());+ }++ #[cfg(unix)]+ #[test]+ fn a_linked_folder_is_denied_by_its_resolved_spelling_too() {+ let t = tempfile::tempdir().unwrap();+ let real = t.path().join("real-data");+ std::fs::create_dir_all(real.join("profiles")).unwrap();+ std::fs::write(real.join("api-token"), "x").unwrap();+ let link = t.path().join("data-link");+ std::os::unix::fs::symlink(&real, &link).unwrap();+ let p = Places { home: t.path().join("home"), data_dir: link.clone(), profile_home: None };+ let denied = p.denied();+ let real = mac_path(&std::fs::canonicalize(&real).unwrap());+ let link = mac_path(&link);+ let find = |path: String| denied.iter().find(|x| x.path == path).cloned();+ for (name, dir, read) in [("api-token", false, true), ("profiles", true, true), ("kwnt.db-shm", false, true), ("config.toml", false, false)] {+ let want = Denied { path: format!("{real}/{name}"), dir, read };+ assert_eq!(find(want.path.clone()), Some(want), "resolved {name}");+ assert!(find(format!("{link}/{name}")).is_some(), "as written: {name}");+ }+ // Nothing listed twice; places not reached through a link aren't doubled+ let mut paths: Vec<&String> = denied.iter().map(|x| &x.path).collect();+ paths.sort();+ paths.dedup();+ assert_eq!(paths.len(), denied.len());+ assert_eq!(resolved("/"), None);+ }++ /// Not a check: `.github/workflows/mac-local.yml` runs it on the macOS runner to get the exact+ /// settings this computer's turn would get (Seatbelt on), then hands them to the real Claude+ /// and to sandbox-runtime's Seatbelt to see what's enforced there.+ #[test]+ #[ignore = "writes KWNT_MAC_SETTINGS_OUT for the mac-local CI probe"]+ fn write_settings_for_the_mac_ci_probe() {+ let out = std::env::var_os("KWNT_MAC_SETTINGS_OUT").expect("KWNT_MAC_SETTINGS_OUT");+ let places = Places::here(None).expect("a home folder");+ let sock = std::env::var("SSH_AUTH_SOCK").ok();+ let s = settings(&places, true, sock.as_deref());+ std::fs::write(out, serde_json::to_vec_pretty(&s).unwrap()).unwrap();+ }+}diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex c077424f..7b1d5ebe 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -6,6 +6,7 @@ pub mod custom;pub mod engines;pub mod events;pub mod grok;+pub mod mac_local;#[cfg(windows)]pub(crate) mod win_job;diff --git a/src/serve.rs b/src/serve.rsindex 5ad650b6..22b64e44 100644--- a/src/serve.rs+++ b/src/serve.rs@@ -27,6 +27,8 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(let _ = std::fs::create_dir_all(&config.data_dir);crate::fsx::restrict_to_user(&config.data_dir);}+ // Claude turns on a Mac deny this folder's secrets to the bot's tools: name the one in use+ crate::drivers::mac_local::set_data_dir(&config.data_dir);let db = Database::init(&config.data_dir).await?;restrict_data_dir(&config.data_dir);let tools = ToolRunner::new(config.data_dir.join("workspace"));