Audit pass via Phase C dogfooding (security-auditor @ Agy/Gemini reviewing our own safe_tools.rs) surfaced 5 real bugs. All fixed. ## Gemini findings (5 real bugs) [#1 HIGH] FAIL-OPEN on missing config/hook Before: missing policy-chain.toml → "passing through" warning; missing hook script → "skipped" warning. Misconfig silently disabled enforcement. After: both paths FAIL-CLOSED with clear error surfaced to caller. Tests/dev can opt in to pass-through via KEI_POLICY_CHAIN_OPTIONAL=1. [#2 HIGH] Path traversal in kei_edit/kei_write Before: no validation; attacker could pass file_path=/etc/passwd or $HOME/.ssh/authorized_keys. After: validate_path() rejects '..' segments, system dirs (/etc/, /usr/, /System/, /var/, /root/), and dotfile-secret dirs (~/.ssh/, ~/.aws/, ~/.gnupg/, ~/.config/gcloud/). Override via KEI_ALLOWED_ROOTS for explicit single-root confinement. [#3 HIGH] CLAUDECODE/GROKCODE env bypass Behavior unchanged — this guard is a perf/UX optimization to avoid double-firing hooks when called from inside Claude/Grok (which already ran their own PreToolUse). Documented explicitly as NOT a security boundary: attacker controlling parent env already owns the invocation. Module header gains a DESIGN NOTE making this load-bearing. [#4 MED] std::fs in async context Before: handle_edit/handle_write used std::fs::{read_to_string,write}, which block the tokio worker thread. Pathological paths like /dev/random would freeze a worker indefinitely. After: tokio::fs::{read_to_string,write}.await — async I/O, worker stays responsive. [#5 MED] kill_on_drop only kills immediate child Before: timeout in kei_bash drops the Child handle; tokio's kill_on_drop SIGKILLs only the shell. Grandchildren (e.g., 'sleep 1000 &') orphaned. After: Unix-only: spawn child in its own process group (Command::process_group(0)), and on timeout libc::kill(-pid, SIGKILL) to take down the whole group. New libc dep on Unix. ## Copilot doc fix Doc claimed "kei-mcp exposes 4 built-in tools" without saying spawn_agent lives in tools.rs while kei_bash/edit/write live in safe_tools.rs. Validator agent flagged this as FALSE/MISLEADING. Now the doc spells out the two-file structure + adds a v0.41 hardening summary. ## claude/grok subprocess permissions Cross-CLI audit demo revealed that 'claude -p' and 'grok --print' returned empty when invoked headless with a real audit task — they need explicit permission flags to use Read/Grep tools in non-interactive mode. Added: claude: --permission-mode=bypassPermissions grok: --always-approve agy: --dangerously-skip-permissions Override via KEI_AGENT_PERMISSIVE=0 to keep strict default. Re-verified: claude+grok both echo SMOKE-OK-V41 with the flag. ## Verification cargo test -p kei-mcp --release → 3/3 pass MCP JSON-RPC smoke (all 7): - tools/list shows 4 built-ins ✓ - kei_bash blocks RULE 0.1 push ✓ - kei_bash passes 'echo OK' ✓ - kei_write rejects /etc/passwd ✓ - kei_write rejects ../ traversal ✓ - kei_write rejects ~/.ssh/* ✓ - missing policy-chain → FAIL-CLOSED with clear error ✓ - KEI_POLICY_CHAIN_OPTIONAL=1 → opt-in pass-through ✓
7 KiB
Cross-CLI policy enforcement
Same safety rules. Any LLM CLI. Three honesty tiers.
KeiSeiKit's safety hooks (no-github-push, safety-guard, destructive-guard,
citation-verify, numeric-claims-guard) originally fired only inside Claude
Code's PreToolUse pipeline. Phase C extends enforcement to other CLIs —
but the strength of enforcement depends on what each CLI permits.
The 3-tier honesty model
| Tier | What it means | CLIs |
|---|---|---|
| TIER 1 — full native | Tool-call enforcement at the CLI's own hook layer. Same as Claude. | claude, grok |
| TIER 2 — MCP-wrapped | Native shell disabled at launch; agent forced to use our policy-gated kei_bash/kei_edit/kei_write MCP tools. |
copilot |
| TIER 3 — advisory | CLI can't disable native shell; we register kei-mcp and instruct the agent to prefer kei_* tools, but enforcement is prompt-level only. |
agy, kimi |
For patent-sensitive or production-PR work — stick to TIER 1 (claude or grok).
How to wire
One command sets up enforcement for whichever CLIs you have installed:
kei mcp-wire # detect + wire all installed CLIs
kei mcp-wire grok # wire one CLI
kei mcp-wire --dry-run # preview config changes without writing
kei mcp-wire --list # show enforcement tier per CLI
The orchestrator is idempotent — running twice produces the same config.
What kei mcp-wire writes
claude (TIER 1 — already enforced)
No-op. Native PreToolUse hooks already gate every tool call. kei mcp-wire claude
prints the optional mcpServers snippet you can add to
~/.claude/settings.json if you want claude to also see spawn_agent for
sub-agent dispatch.
grok (TIER 1 — port our hooks)
Writes ~/.grok/settings.json hooks.PreToolUse block:
Bashmatcher →no-github-push.sh+safety-guard.sh+destructive-guard.shEditmatcher →citation-verify.sh+numeric-claims-guard.shWritematcher →citation-verify.sh+numeric-claims-guard.sh
Plus registers kei-mcp with GROKCODE=1 env (so kei-mcp's policy chain skips
duplicate enforcement when invoked via Grok — your native hooks already fired).
xAI's Grok uses the same JSON input contract as Claude Code's PreToolUse, so our hook scripts run unchanged. Identical enforcement to claude.
copilot (TIER 2 — disable native shell, force MCP)
Writes ~/.copilot/mcp-config.json registering kei-mcp. To activate enforcement,
launch copilot with --excluded-tools='shell':
alias copilot='copilot --excluded-tools=shell'
The agent will have NO native shell tool, only kei-mcp's kei_bash —
which runs the policy chain before execution. kei_edit / kei_write
similarly gate file mutations.
agy / kimi (TIER 3 — advisory)
Writes their MCP config (~/.gemini/config/mcp_config.json for agy,
~/.kimi/mcp.json for kimi) registering kei-mcp.
The honest part: these CLIs do NOT have a way to disable their native
shell. The agent CAN reach for native bash regardless of what we tell it.
The system prompt nudges it toward kei_bash, but a determined or careless
agent can bypass.
For patent-sensitive work — don't use agy or kimi as orchestrator. Use them for analysis / brainstorming / no-side-effect tasks only.
Internals
policy-chain.toml (SSoT)
One file declares which hooks gate which tool, for all CLIs that go through the MCP layer:
# ~/.claude/hooks/_lib/policy-chain.toml
[bash]
chain = ["no-github-push.sh", "safety-guard.sh", "destructive-guard.sh"]
[edit]
chain = ["citation-verify.sh", "numeric-claims-guard.sh"]
[write]
chain = ["citation-verify.sh", "numeric-claims-guard.sh"]
To add a hook: append its basename. The hook script must already exist in
~/.claude/hooks/ and follow the standard PreToolUse contract (read JSON
on stdin with .tool_name + .tool_input, return exit 0 = pass / 2 = block).
kei-mcp built-in tools
kei-mcp (Rust MCP server at _primitives/_rust/kei-mcp/) exposes 4
built-in tools across two source files (both bypass the atom-discovery
loop in handlers/tools.rs):
In handlers/tools.rs:
spawn_agent(name, task, on?)— invokes a KeiSeiKit agent on any backend
In handlers/safe_tools.rs (Phase C, v0.40+):
kei_bash(command, cwd?)— runs[bash]chain → executeskei_edit(file_path, old_string, new_string)— runs[edit]chain → editskei_write(file_path, content)— runs[write]chain → writes
The chain runs against the same hook scripts Claude uses; identical input shape, identical decisions. On block, the hook's stderr surfaces as the MCP error message so the calling agent sees exactly why.
v0.41 hardening (post-audit fixes):
- Fail-CLOSED on missing config — if
policy-chain.tomlis absent the chain refuses to run (was: silent pass-through). Tests / dev can opt in viaKEI_POLICY_CHAIN_OPTIONAL=1env. - Fail-CLOSED on missing hook script — if a hook declared in the chain is not on disk the call fails (was: warn-and-skip).
- Path-traversal guard on
kei_edit/kei_write— rejects..segments,/etc/,/usr/,/System/,/var/,/root/, plus$HOME/{.ssh,.aws,.gnupg,.config/gcloud}/recursively. Override viaKEI_ALLOWED_ROOTS=':'-separated-absolute-paths. - Async file I/O —
kei_edit/kei_writenow usetokio::fsso a pathological file (/dev/randometc.) cannot block a tokio worker. - Process-group kill on timeout —
kei_bashputs its child shell in its own process group; on timeout the entire group iskillpg(SIGKILL)'d so grandchildren don't orphan (Unix-only; no-op on Windows).
Double-enforcement guard
If kei-mcp is invoked from a process where $CLAUDECODE=1 or $GROKCODE=1,
it SKIPS its hook chain — the CLI's native hooks already fired. This is set
automatically by kei mcp-wire claude / kei mcp-wire grok. On copilot /
agy / kimi the env is unset → chain runs.
Verification
# All 4 built-ins must list:
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
| kei-mcp | jq -r '.result.capabilities'
# Block test (kei_bash refuses forbidden command):
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"kei_bash","arguments":{"command":"git push https://github.com/x/y.git main"}}}' \
| kei-mcp 2>&1 | grep "RULE 0.1" # expects: BLOCK — RULE 0.1 NO GITHUB PUSH
# Pass test:
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"kei_bash","arguments":{"command":"echo OK"}}}' \
| kei-mcp | tail -1 | jq -r '.result.content[0].text' # expects: OK
Related
- Multi-CLI agent invocation — DNA-resolved agent dispatch
kei-mcpsource:_primitives/_rust/kei-mcp/src/handlers/safe_tools.rs- Policy SSoT:
hooks/_lib/policy-chain.toml - Wire scripts:
scripts/kei-mcp-wire*.sh