diff --git a/.github/workflows/adr-166-mcp-bridge-security.yml b/.github/workflows/adr-166-mcp-bridge-security.yml index c6def55735..b512b76a86 100644 --- a/.github/workflows/adr-166-mcp-bridge-security.yml +++ b/.github/workflows/adr-166-mcp-bridge-security.yml @@ -54,6 +54,8 @@ jobs: run: node ruflo/src/mcp-bridge/test-runtime-security.mjs - name: Local-only browser guard (#4226) on both bridges run: node ruflo/src/mcp-bridge/test-local-browser-guard.mjs + - name: Capability policy on both bridges (stub backends + stub model) + run: node ruflo/src/mcp-bridge/test-tool-policy.mjs compose-loopback-only: name: Compose default binds loopback + Mongo has auth @@ -82,6 +84,15 @@ jobs: || { echo "::error::MONGO_INITDB_ROOT_PASSWORD must be a required variable (:? syntax)"; exit 1; } grep -q 'read_only: true' ruflo/docker-compose.yml \ || { echo "::error::bridge service must be read_only: true (Phase 2c)"; exit 1; } + # Every published host port must be bound to loopback. The chat UI has + # no sign-in of its own; remote access goes through an authenticated + # proxy, not a port published on every interface. + bad=$(awk '/^[[:space:]]*ports:/{p=1;next} p&&/^[[:space:]]*-[[:space:]]/{print;next} {p=0}' ruflo/docker-compose.yml \ + | grep -vE '^[[:space:]]*-[[:space:]]+"127\.0\.0\.1:' || true) + if [ -n "$bad" ]; then + echo "::error::docker-compose.yml publishes a port on a non-loopback interface: $bad" + exit 1 + fi echo "compose defaults: OK" federation-loopback-default: diff --git a/ruflo/docker-compose.yml b/ruflo/docker-compose.yml index 0c1afb1960..439abe8449 100644 --- a/ruflo/docker-compose.yml +++ b/ruflo/docker-compose.yml @@ -64,6 +64,10 @@ services: MCP_BIND_HOST: ${MCP_BIND_HOST:-0.0.0.0} MCP_AUTH_TOKEN: "${MCP_AUTH_TOKEN:?MCP_AUTH_TOKEN is required. Generate one with: openssl rand -hex 32}" MCP_ENABLE_TERMINAL: ${MCP_ENABLE_TERMINAL:-false} + # Tools are offered by reviewed capability (src/mcp-bridge/tool-policy.js); + # unknown tools are denied. Read, state and search tools are on by default. + # Opt into more with a comma list: network, file, shell. + MCP_ALLOW_CAPABILITIES: ${MCP_ALLOW_CAPABILITIES:-} MCP_CORS_ORIGIN: ${MCP_CORS_ORIGIN:-*} # ADR-166 §6 Phase 2c — read-only rootfs breaks the PoC's /app/beacon.js write. read_only: true @@ -81,8 +85,15 @@ services: context: ./src/nginx dockerfile: Dockerfile restart: unless-stopped + # Local-only by default. The chat UI has no sign-in of its own, and the + # bridge's MCP_AUTH_TOKEN authenticates the app, not the person using the + # browser, so publishing this port on every interface would hand the app + # and its API to anyone who can reach the host. + # For remote access, put an HTTPS proxy that requires sign-in in front of + # every route (app, API and streaming) on this compose network, and remove + # this host port mapping so nothing can go around the proxy. ports: - - "3000:3000" + - "127.0.0.1:3000:3000" depends_on: - chat-ui - mcp-bridge diff --git a/ruflo/src/mcp-bridge/Dockerfile b/ruflo/src/mcp-bridge/Dockerfile index 7fd0a9a2c2..3ec52de09d 100644 --- a/ruflo/src/mcp-bridge/Dockerfile +++ b/ruflo/src/mcp-bridge/Dockerfile @@ -18,6 +18,7 @@ RUN npm install -g @openai/codex || true COPY index.js ./ COPY mcp-stdio-kernel.js ./ COPY url-guard.js ./ +COPY tool-policy.js ./ # Create writable directories for MCP backends (ruflo, ruvector, agentic-flow) # These tools write state/tasks/memory to the working directory at runtime diff --git a/ruflo/src/mcp-bridge/index.js b/ruflo/src/mcp-bridge/index.js index f3d83fc7e2..5b676285aa 100644 --- a/ruflo/src/mcp-bridge/index.js +++ b/ruflo/src/mcp-bridge/index.js @@ -2,6 +2,11 @@ import express from "express"; import { spawn } from "child_process"; import { randomUUID, timingSafeEqual } from "crypto"; import { assertPublicUrl } from "./url-guard.js"; +import { createToolPolicy } from "./tool-policy.js"; + +// Capability allowlist (tool-policy.js). Decides which tools are listed and +// callable; anything it does not know is denied. +const toolPolicy = createToolPolicy(process.env); // ============================================================================= // CONFIGURATION @@ -318,6 +323,9 @@ function getActiveTools() { for (const [backendName, client] of mcpBackends) { const accepted = filterToolsByGroups(client.tools, backendName); for (const t of accepted) { + // A tool the policy does not allow is never listed, so it cannot be + // resolved by executeTool either. + if (!toolPolicy.allows(backendName, t._originalName)) continue; filtered.push({ ...t, name: `${backendName}__${t._originalName}` }); } } @@ -343,7 +351,18 @@ async function initBackends() { ); allBackendTools = getActiveTools(); - console.log(`MCP backends: ${mcpBackends.size} active, ${allBackendTools.length} tools (filtered by groups)`); + console.log(`MCP backends: ${mcpBackends.size} active, ${allBackendTools.length} tools (filtered by groups and capability policy)`); + const withheld = {}; + for (const [backendName, client] of mcpBackends) { + for (const t of filterToolsByGroups(client.tools, backendName)) { + if (toolPolicy.allows(backendName, t._originalName)) continue; + const why = toolPolicy.reason(backendName, t._originalName); + withheld[why] = (withheld[why] || 0) + 1; + } + } + if (Object.keys(withheld).length > 0) { + console.log(`Capability policy withheld tools: ${JSON.stringify(withheld)} (allowed: ${toolPolicy.allowed.join(", ")})`); + } } process.on("SIGTERM", () => { for (const [, c] of mcpBackends) c.stop(); process.exit(0); }); @@ -353,7 +372,7 @@ process.on("SIGINT", () => { for (const [, c] of mcpBackends) c.stop(); process. // BUILT-IN TOOLS (core group — always on) // ============================================================================= -const BUILTIN_TOOLS = [ +const BUILTIN_TOOL_DEFS = [ { name: "search", description: "Search your knowledge base for relevant information.", @@ -398,6 +417,7 @@ const BUILTIN_TOOLS = [ }, }, ]; +const BUILTIN_TOOLS = BUILTIN_TOOL_DEFS.filter(t => toolPolicy.allowsBuiltin(t.name)); // ============================================================================= // GUIDANCE ENGINE — AI-facing instruction system @@ -781,25 +801,23 @@ async function executeGoapSearch(query, args) { // ADR-166 §6 Phase 1d + 2a — server-side tool gate. // Enforced HERE (not just in the autopilot handler) so /mcp, /mcp/:group, -// autopilot, and any future path share ONE denial gate. Was the missing -// link that made the disclosed unauthenticated-RCE chain reach shell. -const DANGEROUS_TOOLS = Object.freeze(new Set([ - "terminal_execute", - "ruflo__terminal_execute", - "devtools__terminal_execute", -])); -function isTerminalTool(name) { - return DANGEROUS_TOOLS.has(name) || /terminal_execute/i.test(name); +// autopilot, and any future path share ONE denial gate. The decision is the +// capability policy's (tool-policy.js): a built-in must be allowed by it, and a +// backend tool must be in the policy-filtered list from getActiveTools(). A +// tool it does not know is refused here, before any backend sees the call. +function isToolPermitted(name) { + if (typeof name !== "string") return false; + if (BUILTIN_TOOL_DEFS.some(t => t.name === name)) return toolPolicy.allowsBuiltin(name); + return getActiveTools().some(t => t.name === name); } -const MCP_ENABLE_TERMINAL = process.env.MCP_ENABLE_TERMINAL === "true"; async function executeTool(name, args) { - // Deny dangerous tools unless the operator explicitly opted in. - // Enforced on every path (not just autopilot) — root cause of ADR-166 V2/V3. - if (isTerminalTool(name) && !MCP_ENABLE_TERMINAL) { + // Deny every tool the capability policy does not allow, on every path. + // Root cause of ADR-166 V2/V3; the policy replaced a name-pattern check. + if (!isToolPermitted(name)) { return { error: - `Tool "${name}" is disabled by default. Set MCP_ENABLE_TERMINAL=true to allow.`, + `Tool "${name}" is not available. Unknown tools are denied, and tools that run commands, touch files or reach the network need the operator to allow that capability (MCP_ALLOW_CAPABILITIES).`, code: "TOOL_DISABLED", }; } @@ -1421,7 +1439,6 @@ const AUTOPILOT_BLOCKED_PATTERNS = [ /^security_delete/, /^browser_fill$/, /^browser_click$/, - /terminal_execute/, ]; function isBlockedTool(name) { @@ -1820,11 +1837,12 @@ async function main() { // ADR-166 §6 — startup posture banner console.log( `[security] bind=${BIND_HOST} auth=${process.env.MCP_AUTH_TOKEN ? "bearer" : "off (local-only)"} ` + - `terminal=${MCP_ENABLE_TERMINAL ? "ENABLED (⚠ opt-in)" : "disabled"}`, + `capabilities=${toolPolicy.allowed.join(",")}`, ); - if (MCP_ENABLE_TERMINAL) { + const risky = toolPolicy.allowed.filter(c => ["network", "file", "shell"].includes(c)); + if (risky.length > 0) { console.warn( - "[security] WARNING: terminal_execute is enabled. This tool grants shell access " + + `[security] WARNING: ${risky.join(", ")} tools are enabled. They grant command, file or network access ` + "inside the bridge container to any client the auth layer accepts. Ensure " + "MCP_AUTH_TOKEN is set on any non-loopback bind. See ADR-166 §6 Phase 1d.", ); diff --git a/ruflo/src/mcp-bridge/test-security-lock.js b/ruflo/src/mcp-bridge/test-security-lock.js index 3d74bd5e11..bedab0970a 100755 --- a/ruflo/src/mcp-bridge/test-security-lock.js +++ b/ruflo/src/mcp-bridge/test-security-lock.js @@ -9,7 +9,7 @@ * 2. Public bind without `MCP_AUTH_TOKEN` calls `process.exit(1)` at boot (Phase 1b) * 3. `requireAuth` middleware exists and is mounted with `app.use(requireAuth)` (Phase 1c) * 4. `requireAuth` uses `timingSafeEqual` (constant-time compare) - * 5. `executeTool` denies terminal_execute unless `MCP_ENABLE_TERMINAL === "true"` (Phase 1d + 2a) + * 5. `executeTool` refuses any tool the capability policy (tool-policy.js) does not allow (Phase 1d + 2a) * 6. CORS respects `MCP_CORS_ORIGIN` allowlist (Phase 3b) * 9. Both production images use the supported Node 24 LTS line (#2847) * @@ -54,9 +54,9 @@ const CHECKS = [ hint: "auth compare must use timingSafeEqual (Phase 1c)", }, { - id: "5. terminal-gate-server-side", - rx: /MCP_ENABLE_TERMINAL[\s\S]*?executeTool[\s\S]*?TOOL_DISABLED|executeTool[\s\S]*?MCP_ENABLE_TERMINAL[\s\S]*?TOOL_DISABLED/, - hint: "terminal_execute must be denied at executeTool unless MCP_ENABLE_TERMINAL=true (Phase 1d + 2a)", + id: "5. capability-gate-server-side", + rx: /import\s*\{\s*createToolPolicy\s*\}\s*from\s*["']\.\/tool-policy\.js["'][\s\S]*?if \(!toolPolicy\.allows\(backendName, t\._originalName\)\) continue;[\s\S]*?async function executeTool\(name, args\) \{\s*\/\/[^\n]*\n\s*\/\/[^\n]*\n\s*if \(!isToolPermitted\(name\)\) \{[\s\S]*?TOOL_DISABLED/, + hint: "executeTool must refuse, as its first step, any tool the capability policy does not allow, and getActiveTools must filter by it (Phase 1d + 2a)", }, { id: "6. cors-allowlist-respected", @@ -123,6 +123,13 @@ for (const dockerfile of DOCKERFILES) { const source = fs.readFileSync(dockerfile, "utf-8"); const rel = path.relative(path.join(HERE, "..", ".."), dockerfile); console.log(`\n# ${rel}`); + if (/^COPY\s+tool-policy\.js\s/m.test(source)) { + console.log(" ✓ 14. image-includes-tool-policy"); + } else { + console.log(" ✗ 14. image-includes-tool-policy"); + console.log(" hint: the image must COPY tool-policy.js or the bridge fails to start"); + hardFail = true; + } if (/^COPY\s+url-guard\.js\s/m.test(source)) { console.log(" ✓ 13. image-includes-url-guard"); } else { diff --git a/ruflo/src/mcp-bridge/test-stub-backend.mjs b/ruflo/src/mcp-bridge/test-stub-backend.mjs new file mode 100644 index 0000000000..58c410e466 --- /dev/null +++ b/ruflo/src/mcp-bridge/test-stub-backend.mjs @@ -0,0 +1,37 @@ +#!/usr/bin/env node +// Stub MCP stdio backend for test-tool-policy.mjs. The test puts it on PATH as +// `npx` and `claude`, so the bridge spawns it in place of the real backends. +// It offers a fixed tool list per backend and appends every tools/call it +// receives to STUB_LOG, so the test can prove what reached a backend. +import fs from "node:fs"; +import path from "node:path"; +import { createInterface } from "node:readline"; + +const argv = process.argv.slice(2); +const invokedAs = path.basename(process.env.STUB_INVOKED_AS || ""); +const backend = invokedAs === "claude" ? "claude" + : argv.includes("ruvector") ? "ruvector" + : argv.includes("ruflo") ? "ruflo" + : "other"; + +const TOOLS = { + ruflo: ["task_list", "memory_search", "terminal_execute", "github_repo_analyze", "memory_brand_new_tool"], + ruvector: ["hooks_stats", "hooks_rag_context", "hooks_brand_new_tool"], + claude: ["Bash", "Read"], + other: [], +}; + +const reply = (id, result) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n"); + +createInterface({ input: process.stdin, terminal: false }).on("line", (line) => { + let msg; + try { msg = JSON.parse(line); } catch { return; } + if (msg.method === "initialize") { + reply(msg.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: `stub-${backend}`, version: "0" } }); + } else if (msg.method === "tools/list") { + reply(msg.id, { tools: TOOLS[backend].map((name) => ({ name, description: `stub ${name}`, inputSchema: { type: "object", properties: {} } })) }); + } else if (msg.method === "tools/call") { + fs.appendFileSync(process.env.STUB_LOG, `${backend}:${msg.params?.name}\n`); + reply(msg.id, { content: [{ type: "text", text: `stub ${backend} ran ${msg.params?.name}` }] }); + } +}); diff --git a/ruflo/src/mcp-bridge/test-stub-provider.mjs b/ruflo/src/mcp-bridge/test-stub-provider.mjs new file mode 100644 index 0000000000..0f85f3601a --- /dev/null +++ b/ruflo/src/mcp-bridge/test-stub-provider.mjs @@ -0,0 +1,27 @@ +// Preloaded into the bridge by test-tool-policy.mjs (node --import). Replaces +// fetch for the OpenAI chat endpoint with a stub model: on the first turn it +// asks for every tool named in STUB_PROVIDER_CALLS, on the next it answers in +// text. It records the tool names the bridge offered in STUB_PROVIDER_LOG. +import fs from "node:fs"; + +const realFetch = globalThis.fetch; +globalThis.fetch = async (input, init) => { + const url = typeof input === "string" ? input : input?.url; + if (url !== "https://api.openai.com/v1/chat/completions") return realFetch(input, init); + const body = JSON.parse(init?.body || "{}"); + const offered = (body.tools || []).map((t) => t.function?.name); + fs.appendFileSync(process.env.STUB_PROVIDER_LOG, JSON.stringify({ offered }) + "\n"); + const answered = (body.messages || []).some((m) => m.role === "tool"); + const message = answered + ? { role: "assistant", content: "done" } + : { + role: "assistant", + content: null, + tool_calls: process.env.STUB_PROVIDER_CALLS.split(",").map((name, i) => ({ + id: `call_${i}`, type: "function", function: { name, arguments: "{}" }, + })), + }; + return new Response(JSON.stringify({ choices: [{ message, finish_reason: answered ? "stop" : "tool_calls" }] }), { + status: 200, headers: { "Content-Type": "application/json" }, + }); +}; diff --git a/ruflo/src/mcp-bridge/test-tool-policy.mjs b/ruflo/src/mcp-bridge/test-tool-policy.mjs new file mode 100644 index 0000000000..1b8f5d61d2 --- /dev/null +++ b/ruflo/src/mcp-bridge/test-tool-policy.mjs @@ -0,0 +1,192 @@ +#!/usr/bin/env node +/** + * Capability policy, verified over the wire on BOTH bridges. + * + * Each bridge is started with stub backends on PATH (test-stub-backend.mjs as + * `npx` and `claude`) and a stub model preloaded (test-stub-provider.mjs). The + * stub backends log every tools/call they receive, so the test can prove that + * a denied call never reached a backend, whichever path it came in on: + * POST /mcp, POST /mcp/ (including the wrong group) and autopilot. + * + * P1. the two copies of tool-policy.js are byte-identical + * P2. denied tools are not listed: shell, unknown, Claude Code (wildcard group) + * P3. denied calls return TOOL_DISABLED on every endpoint + * P4. autopilot does not offer denied tools to the model and refuses them + * P5. approved read-only tools still reach the backend, once per call + * P6. nothing else reached any backend + * P7. MCP_ENABLE_TERMINAL=true still lets an operator opt into shell tools, + * while unknown and unreviewed tools stay hidden + * + * node test-tool-policy.mjs + */ + +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; +import { fileURLToPath } from "node:url"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const RUVOCAL = path.join(HERE, "..", "ruvocal", "mcp-bridge"); +const BRIDGES = [ + { label: "src/mcp-bridge", entry: path.join(HERE, "index.js") }, + { label: "src/ruvocal/mcp-bridge", entry: path.join(RUVOCAL, "index.js") }, +]; +const TOKEN = "policy-test-" + Math.random().toString(36).slice(2); + +const ALLOWED = ["ruflo__task_list", "ruvector__hooks_stats"]; +const DENIED = [ + "ruflo__terminal_execute", // shell, by name + "ruflo__memory_search", // file + "ruflo__github_repo_analyze", // shell, no "terminal" in its name + "ruflo__memory_brand_new_tool", // unknown, inside an enabled prefix + "ruvector__hooks_rag_context", // shell in ruvector + "ruvector__hooks_brand_new_tool", + "claude__Bash", // Claude Code group (no prefixes = wildcard) + "claude__Read", + "terminal_execute", // bare name +]; + +let passed = 0, failed = 0; +function assert(cond, label) { + if (cond) { console.log(` ✓ ${label}`); passed++; } + else { console.log(` ✗ ${label}`); failed++; } +} + +const work = fs.mkdtempSync(path.join(os.tmpdir(), "tool-policy-")); +const bin = path.join(work, "bin"); +fs.mkdirSync(bin); +for (const name of ["npx", "claude"]) { + const file = path.join(bin, name); + fs.writeFileSync(file, `#!/bin/sh\nSTUB_INVOKED_AS=${name} exec "${process.execPath}" "${path.join(HERE, "test-stub-backend.mjs")}" "$@"\n`); + fs.chmodSync(file, 0o755); +} + +async function rpc(port, route, method, params) { + const r = await fetch(`http://127.0.0.1:${port}${route}`, { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), + }); + return r.json(); +} +const listNames = async (port, route) => ((await rpc(port, route, "tools/list", {})).result?.tools || []).map((t) => t.name); + +async function startBridge(entry, extraEnv, tag) { + const port = 20000 + Math.floor(Math.random() * 10000); + const stubLog = path.join(work, `${tag}-backend.log`); + const providerLog = path.join(work, `${tag}-provider.log`); + fs.writeFileSync(stubLog, ""); + fs.writeFileSync(providerLog, ""); + const child = spawn(process.execPath, ["--import", path.join(HERE, "test-stub-provider.mjs"), entry], { + env: { + ...process.env, + PATH: `${bin}${path.delimiter}${process.env.PATH}`, + PORT: String(port), + MCP_BIND_HOST: "127.0.0.1", + MCP_AUTH_TOKEN: TOKEN, + MCP_ENABLE_TERMINAL: "false", + MCP_ALLOW_CAPABILITIES: "", + MCP_GROUP_CLAUDE_CODE: "true", + OPENAI_API_KEY: "stub", + AUTOPILOT_COOLDOWN: "0", + STUB_LOG: stubLog, + STUB_PROVIDER_LOG: providerLog, + STUB_PROVIDER_CALLS: [...DENIED, ...ALLOWED].join(","), + ...extraEnv, + }, + stdio: ["ignore", "pipe", "pipe"], + }); + let output = ""; + child.stdout.on("data", (d) => { output += d; }); + child.stderr.on("data", (d) => { output += d; }); + const deadline = Date.now() + 20000; + while (Date.now() < deadline) { + await sleep(250); + try { + const names = await listNames(port, "/mcp"); + if (names.includes("ruflo__task_list") && names.includes("ruvector__hooks_stats")) { + return { child, port, stubLog, providerLog, output: () => output }; + } + } catch { /* not up yet */ } + } + child.kill("SIGKILL"); + throw new Error(`bridge did not load stub backends:\n${output.slice(-2000)}`); +} + +const backendCalls = (log) => fs.readFileSync(log, "utf8").split("\n").filter(Boolean); +const textOf = (body) => JSON.stringify(body); + +async function defaultPolicy(entry, tag) { + const b = await startBridge(entry, {}, tag); + try { + const listed = await listNames(b.port, "/mcp"); + for (const name of ALLOWED) assert(listed.includes(name), `P2. ${name} is listed`); + for (const name of DENIED) assert(!listed.includes(name), `P2. ${name} is not listed`); + assert((await listNames(b.port, "/mcp/claude-code")).length === 0, "P2. /mcp/claude-code lists nothing"); + const devtools = await listNames(b.port, "/mcp/devtools"); + assert(!devtools.some((n) => DENIED.includes(n)), "P2. /mcp/devtools lists no denied tool"); + + for (const route of ["/mcp", "/mcp/core", "/mcp/devtools", "/mcp/claude-code"]) { + for (const name of DENIED) { + const body = await rpc(b.port, route, "tools/call", { name, arguments: { command: "id" } }); + assert(textOf(body).includes("TOOL_DISABLED"), `P3. ${route} refuses ${name}`); + } + } + for (const name of ALLOWED) { + const body = await rpc(b.port, "/mcp", "tools/call", { name, arguments: {} }); + assert(textOf(body).includes(`ran ${name.split("__")[1]}`), `P5. ${name} reaches its backend`); + } + + const r = await fetch(`http://127.0.0.1:${b.port}/chat/completions`, { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}`, "x-autopilot": "true" }, + body: JSON.stringify({ model: "gpt-4o", messages: [{ role: "user", content: "go" }] }), + }); + const events = await r.text(); + const offered = fs.readFileSync(b.providerLog, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l).offered); + assert(offered.length > 0, "P4. autopilot called the stub model"); + assert(offered.every((names) => !names.some((n) => DENIED.includes(n))), "P4. autopilot offered no denied tool"); + assert(offered.every((names) => ALLOWED.every((n) => names.includes(n))), "P4. autopilot offered the approved tools"); + // Autopilot streams a 120-character summary, so match the start of the refusal. + const refusals = (events.match(/is not available/g) || []).length; + assert(refusals === DENIED.length, `P4. autopilot refused each denied call (${refusals}/${DENIED.length})`); + + const calls = backendCalls(b.stubLog); + const expected = ["ruflo:task_list", "ruflo:task_list", "ruvector:hooks_stats", "ruvector:hooks_stats"]; + assert(JSON.stringify([...calls].sort()) === JSON.stringify(expected), + `P5/P6. backends saw only the approved calls, once per request (saw: ${calls.join(", ") || "none"})`); + } finally { + b.child.kill("SIGKILL"); + } +} + +async function terminalOptIn(entry, tag) { + const b = await startBridge(entry, { MCP_ENABLE_TERMINAL: "true" }, tag); + try { + const listed = await listNames(b.port, "/mcp"); + assert(listed.includes("ruflo__terminal_execute"), "P7. opt-in lists ruflo__terminal_execute"); + for (const name of ["ruflo__memory_brand_new_tool", "ruvector__hooks_brand_new_tool", "claude__Bash"]) { + assert(!listed.includes(name), `P7. opt-in still hides ${name}`); + } + await rpc(b.port, "/mcp", "tools/call", { name: "ruflo__terminal_execute", arguments: {} }); + assert(backendCalls(b.stubLog).includes("ruflo:terminal_execute"), "P7. opted-in shell call reaches the backend"); + } finally { + b.child.kill("SIGKILL"); + } +} + +console.log("\n# tool-policy.js copies"); +assert(fs.readFileSync(path.join(HERE, "tool-policy.js"), "utf8") === fs.readFileSync(path.join(RUVOCAL, "tool-policy.js"), "utf8"), + "P1. both bridges ship the same tool-policy.js"); + +for (const [i, { label, entry }] of BRIDGES.entries()) { + console.log(`\n# ${label}`); + await defaultPolicy(entry, `b${i}-default`); + await terminalOptIn(entry, `b${i}-terminal`); +} + +fs.rmSync(work, { recursive: true, force: true }); +console.log(`\n${passed} passed, ${failed} failed`); +process.exit(failed === 0 ? 0 : 1); diff --git a/ruflo/src/mcp-bridge/tool-policy.js b/ruflo/src/mcp-bridge/tool-policy.js new file mode 100644 index 0000000000..18d13e8461 --- /dev/null +++ b/ruflo/src/mcp-bridge/tool-policy.js @@ -0,0 +1,348 @@ +// Tool capability policy for the MCP bridges. +// +// One reviewed allowlist assigns a capability to every tool the bridge may +// offer. The bridge asks this module when it builds its tool list, so a tool +// that is denied is neither listed nor callable, and a denied call is refused +// before anything is sent to a backend. +// +// Unknown tools are denied. A tool is known only if its backend and exact +// name appear in BACKEND_TOOL_CAPABILITIES below. A name that merely looks +// harmless, or a new tool a backend adds in a later release, gets no +// capability and stays hidden until someone traces its handler and adds it. +// +// This file is shared by ruflo/src/mcp-bridge and ruflo/src/ruvocal/mcp-bridge. +// The two copies must be byte-identical; test-tool-policy.mjs checks that. +// +// Capabilities, least to most dangerous: +// read no side effects; reads the backend's own state +// state writes only the backend's own data store, at paths the caller +// cannot choose +// search the bridge's built-in search, sent to operator-configured endpoints +// network outbound requests the caller can direct +// file reads or writes filesystem paths the caller can influence +// shell runs processes or code +// +// read, state and search are allowed by default. Operators opt into the rest +// with MCP_ALLOW_CAPABILITIES (comma list, e.g. "network,file"). +// MCP_ENABLE_TERMINAL=true remains an alias for allowing "shell". + +export const CAPABILITIES = Object.freeze(["read", "state", "search", "network", "file", "shell"]); +const DEFAULT_ALLOWED = Object.freeze(["read", "state", "search"]); + +export const BUILTIN_CAPABILITIES = Object.freeze({ + search: "search", + web_research: "search", + guidance: "read", +}); + +// Traced against ruflo 3.82.0 and ruvector 0.3.29 (2026-12-02). Only tools in +// groups that are enabled by default were reviewed. Tools from the opt-in +// groups (security, browser, neural, agentic-flow, gemini) and from Claude +// Code have no entry, so they stay hidden even when their group is enabled. +// Each entry was assigned by reading the tool's handler code. +// +// Judgement calls, so a later reviewer can revisit them: +// - Downloading the fixed embedding model on first use is not "network": the +// caller cannot direct it. Tools whose only outbound request is that download +// are "state". +// - ruflo memory_* tools that accept a database path are "file". +// - A fixed `node -e` header probe (graph-edge-writer) still spawns a process. +// The tools the review traced to it are "shell"; other tools that open the +// memory database may reach the same harmless probe. +// - No config_* tool has an entry: config_set, config_import and config_reset +// change settings, such as the model endpoint, that other tools act on, and +// the read tools are held back until their output has been reviewed. +// - swarm_shutdown is "file": it runs agent_terminate's cleanup, which deletes +// a memory branch path recorded when the agent was spawned. +export const BACKEND_TOOL_CAPABILITIES = Object.freeze({ + ruflo: Object.freeze({ + "agent_execute": "network", + "agent_health": "read", + "agent_list": "read", + "agent_logs": "read", + "agent_pool": "state", + "agent_spawn": "file", + "agent_status": "read", + "agent_terminate": "file", + "agent_update": "state", + "agentdb_batch": "state", + "agentdb_causal-edge": "shell", + "agentdb_causal-edge-delete": "state", + "agentdb_causal-node-delete": "state", + "agentdb_consolidate": "state", + "agentdb_context-synthesize": "state", + "agentdb_controllers": "state", + "agentdb_episode-delete": "state", + "agentdb_episode-get": "state", + "agentdb_episode-list": "state", + "agentdb_episode-recall": "state", + "agentdb_episode-update": "state", + "agentdb_feedback": "state", + "agentdb_graph-pathfinder": "shell", + "agentdb_graph-query": "shell", + "agentdb_health": "state", + "agentdb_hierarchical-delete": "state", + "agentdb_hierarchical-get": "state", + "agentdb_hierarchical-list": "state", + "agentdb_hierarchical-recall": "state", + "agentdb_hierarchical-stats": "state", + "agentdb_hierarchical-store": "state", + "agentdb_pattern-list": "state", + "agentdb_pattern-search": "state", + "agentdb_pattern-store": "state", + "agentdb_route": "state", + "agentdb_semantic-route": "state", + "agentdb_session-end": "state", + "agentdb_session-start": "state", + "agentdb_skill-get": "state", + "agentdb_skill-list": "state", + "analyze_diff": "shell", + "analyze_diff-classify": "shell", + "analyze_diff-reviewers": "shell", + "analyze_diff-risk": "shell", + "analyze_diff-stats": "shell", + "analyze_file-risk": "read", + "coordination_consensus": "state", + "coordination_load_balance": "state", + "coordination_metrics": "read", + "coordination_node": "state", + "coordination_orchestrate": "state", + "coordination_sync": "state", + "coordination_topology": "state", + "embeddings_compare": "state", + "embeddings_generate": "state", + "embeddings_hyperbolic": "read", + "embeddings_init": "state", + "embeddings_neural": "state", + "embeddings_rabitq_build": "state", + "embeddings_rabitq_search": "state", + "embeddings_rabitq_status": "read", + "embeddings_search": "state", + "embeddings_status": "state", + "github_issue_track": "shell", + "github_metrics": "shell", + "github_pr_manage": "shell", + "github_repo_analyze": "shell", + "github_workflow": "shell", + "hive-mind_broadcast": "state", + "hive-mind_consensus": "state", + "hive-mind_init": "state", + "hive-mind_join": "state", + "hive-mind_leave": "state", + "hive-mind_memory": "state", + "hive-mind_optimize-memory": "state", + "hive-mind_shutdown": "state", + "hive-mind_spawn": "state", + "hive-mind_status": "read", + "hooks_build-agents": "file", + "hooks_codemod": "file", + "hooks_coverage-gaps": "file", + "hooks_coverage-route": "file", + "hooks_coverage-suggest": "file", + "hooks_explain": "read", + "hooks_fast-apply": "file", + "hooks_init": "read", + "hooks_intelligence": "state", + "hooks_intelligence-reset": "state", + "hooks_intelligence_attention": "state", + "hooks_intelligence_learn": "state", + "hooks_intelligence_pattern-search": "state", + "hooks_intelligence_pattern-store": "state", + "hooks_intelligence_stats": "read", + "hooks_intelligence_trajectory-end": "state", + "hooks_intelligence_trajectory-start": "state", + "hooks_intelligence_trajectory-step": "shell", + "hooks_intelligence_unified-stats": "read", + "hooks_intelligence_verified-ingest": "shell", + "hooks_list": "read", + "hooks_metrics": "read", + "hooks_model-outcome": "state", + "hooks_model-route": "state", + "hooks_model-stats": "read", + "hooks_model-verify": "state", + "hooks_notify": "read", + "hooks_post-command": "state", + "hooks_post-edit": "state", + "hooks_post-task": "shell", + "hooks_pre-command": "read", + "hooks_pre-edit": "read", + "hooks_pre-task": "file", + "hooks_pretrain": "file", + "hooks_route": "state", + "hooks_session-end": "state", + "hooks_session-restore": "read", + "hooks_session-start": "shell", + "hooks_task-completed": "state", + "hooks_teammate-idle": "read", + "hooks_transfer": "file", + "hooks_worker-cancel": "state", + "hooks_worker-detect": "state", + "hooks_worker-dispatch": "shell", + "hooks_worker-list": "read", + "hooks_worker-status": "read", + "memory_bridge_status": "state", + "memory_cleanup": "state", + "memory_compress": "state", + "memory_delete": "file", + "memory_detailed-stats": "state", + "memory_export": "file", + "memory_import": "file", + "memory_import_claude": "shell", + "memory_list": "file", + "memory_list_scopes": "file", + "memory_migrate": "state", + "memory_retrieve": "file", + "memory_search": "file", + "memory_search_unified": "state", + "memory_stats": "file", + "memory_store": "file", + "performance_benchmark": "state", + "performance_bottleneck": "state", + "performance_metrics": "read", + "performance_optimize": "state", + "performance_profile": "state", + "performance_report": "state", + "progress_check": "read", + "progress_summary": "read", + "progress_sync": "state", + "progress_watch": "read", + "session_current": "read", + "session_delete": "state", + "session_export": "file", + "session_import": "file", + "session_info": "read", + "session_list": "read", + "session_restore": "state", + "session_save": "state", + "swarm_health": "state", + "swarm_init": "state", + "swarm_pheromone_status": "state", + "swarm_pheromone_update": "state", + "swarm_shutdown": "file", + "swarm_status": "state", + "system_health": "state", + "system_info": "read", + "system_metrics": "state", + "system_reset": "state", + "system_status": "read", + "task_assign": "state", + "task_cancel": "state", + "task_complete": "state", + "task_create": "state", + "task_list": "read", + "task_retry": "state", + "task_status": "read", + "task_summary": "read", + "task_update": "state", + "terminal_close": "state", + "terminal_create": "shell", + "terminal_execute": "shell", + "terminal_history": "read", + "terminal_list": "read", + "workflow_cancel": "state", + "workflow_create": "state", + "workflow_delete": "state", + "workflow_execute": "network", + "workflow_list": "read", + "workflow_pause": "state", + "workflow_resume": "network", + "workflow_run": "state", + "workflow_status": "read", + "workflow_stop": "state", + "workflow_template": "state", + "workflow_validate": "file", + }), + ruvector: Object.freeze({ + "hooks_algorithms_list": "read", + "hooks_ast_analyze": "shell", + "hooks_ast_complexity": "shell", + "hooks_attention_info": "read", + "hooks_batch_learn": "state", + "hooks_build_agents": "shell", + "hooks_capabilities": "read", + "hooks_coedit_record": "state", + "hooks_coedit_suggest": "read", + "hooks_compress": "state", + "hooks_compress_get": "read", + "hooks_compress_stats": "read", + "hooks_compress_store": "state", + "hooks_coverage_route": "shell", + "hooks_coverage_suggest": "shell", + "hooks_diff_analyze": "shell", + "hooks_diff_classify": "shell", + "hooks_diff_similar": "shell", + "hooks_doctor": "shell", + "hooks_error_record": "state", + "hooks_error_suggest": "read", + "hooks_export": "read", + "hooks_force_learn": "state", + "hooks_forget": "state", + "hooks_git_churn": "shell", + "hooks_gnn_info": "read", + "hooks_graph_cluster": "shell", + "hooks_graph_mincut": "shell", + "hooks_import": "state", + "hooks_init": "shell", + "hooks_learn": "state", + "hooks_learning_config": "state", + "hooks_learning_stats": "read", + "hooks_learning_update": "state", + "hooks_memory_get": "read", + "hooks_memory_list": "read", + "hooks_memory_update": "state", + "hooks_pretrain": "shell", + "hooks_rag_context": "shell", + "hooks_recall": "read", + "hooks_remember": "state", + "hooks_route": "read", + "hooks_route_enhanced": "file", + "hooks_security_scan": "shell", + "hooks_stats": "read", + "hooks_subscribe_snapshot": "read", + "hooks_suggest_context": "read", + "hooks_swarm_recommend": "read", + "hooks_trajectory_begin": "state", + "hooks_trajectory_end": "state", + "hooks_trajectory_step": "state", + "hooks_verify": "shell", + "hooks_watch_status": "read", + }), +}); + +const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key); + +export function allowedCapabilities(env = {}) { + const allowed = new Set(DEFAULT_ALLOWED); + const extra = typeof env.MCP_ALLOW_CAPABILITIES === "string" ? env.MCP_ALLOW_CAPABILITIES : ""; + for (const raw of extra.split(",")) { + const capability = raw.trim().toLowerCase(); + if (CAPABILITIES.includes(capability)) allowed.add(capability); + } + if (env.MCP_ENABLE_TERMINAL === "true") allowed.add("shell"); + return allowed; +} + +export function capabilityOf(backend, toolName) { + if (typeof backend !== "string" || typeof toolName !== "string") return null; + if (!hasOwn(BACKEND_TOOL_CAPABILITIES, backend)) return null; + const table = BACKEND_TOOL_CAPABILITIES[backend]; + return hasOwn(table, toolName) ? table[toolName] : null; +} + +export function builtinCapabilityOf(toolName) { + return typeof toolName === "string" && hasOwn(BUILTIN_CAPABILITIES, toolName) + ? BUILTIN_CAPABILITIES[toolName] + : null; +} + +export function createToolPolicy(env = {}) { + const allowed = allowedCapabilities(env); + const permits = (capability) => capability !== null && allowed.has(capability); + return Object.freeze({ + allowed: Object.freeze([...allowed]), + allowsBuiltin: (toolName) => permits(builtinCapabilityOf(toolName)), + allows: (backend, toolName) => permits(capabilityOf(backend, toolName)), + // Why a tool is withheld, for logs: "unreviewed" or the capability it needs. + reason: (backend, toolName) => capabilityOf(backend, toolName) ?? "unreviewed", + }); +} diff --git a/ruflo/src/nginx/nginx.conf b/ruflo/src/nginx/nginx.conf index 112107bd17..4838627851 100644 --- a/ruflo/src/nginx/nginx.conf +++ b/ruflo/src/nginx/nginx.conf @@ -46,7 +46,9 @@ http { location / { proxy_pass http://chat-ui:3000; proxy_http_version 1.1; - proxy_set_header Host $host; + # $http_host keeps the port, so the chat UI's origin check matches + # what the browser sends (e.g. 127.0.0.1:3000). + proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; diff --git a/ruflo/src/ruvocal/mcp-bridge/Dockerfile b/ruflo/src/ruvocal/mcp-bridge/Dockerfile index 7fd0a9a2c2..3ec52de09d 100644 --- a/ruflo/src/ruvocal/mcp-bridge/Dockerfile +++ b/ruflo/src/ruvocal/mcp-bridge/Dockerfile @@ -18,6 +18,7 @@ RUN npm install -g @openai/codex || true COPY index.js ./ COPY mcp-stdio-kernel.js ./ COPY url-guard.js ./ +COPY tool-policy.js ./ # Create writable directories for MCP backends (ruflo, ruvector, agentic-flow) # These tools write state/tasks/memory to the working directory at runtime diff --git a/ruflo/src/ruvocal/mcp-bridge/index.js b/ruflo/src/ruvocal/mcp-bridge/index.js index b79c16ddc2..e692f48f4c 100644 --- a/ruflo/src/ruvocal/mcp-bridge/index.js +++ b/ruflo/src/ruvocal/mcp-bridge/index.js @@ -2,6 +2,11 @@ import express from "express"; import { spawn } from "child_process"; import { randomUUID, timingSafeEqual } from "crypto"; import { assertPublicUrl } from "./url-guard.js"; +import { createToolPolicy } from "./tool-policy.js"; + +// Capability allowlist (tool-policy.js). Decides which tools are listed and +// callable; anything it does not know is denied. +const toolPolicy = createToolPolicy(process.env); // ============================================================================= // CONFIGURATION @@ -323,6 +328,9 @@ function getActiveTools() { for (const [backendName, client] of mcpBackends) { const accepted = filterToolsByGroups(client.tools, backendName); for (const t of accepted) { + // A tool the policy does not allow is never listed, so it cannot be + // resolved by executeTool either. + if (!toolPolicy.allows(backendName, t._originalName)) continue; filtered.push({ ...t, name: `${backendName}__${t._originalName}` }); } } @@ -348,7 +356,18 @@ async function initBackends() { ); allBackendTools = getActiveTools(); - console.log(`MCP backends: ${mcpBackends.size} active, ${allBackendTools.length} tools (filtered by groups)`); + console.log(`MCP backends: ${mcpBackends.size} active, ${allBackendTools.length} tools (filtered by groups and capability policy)`); + const withheld = {}; + for (const [backendName, client] of mcpBackends) { + for (const t of filterToolsByGroups(client.tools, backendName)) { + if (toolPolicy.allows(backendName, t._originalName)) continue; + const why = toolPolicy.reason(backendName, t._originalName); + withheld[why] = (withheld[why] || 0) + 1; + } + } + if (Object.keys(withheld).length > 0) { + console.log(`Capability policy withheld tools: ${JSON.stringify(withheld)} (allowed: ${toolPolicy.allowed.join(", ")})`); + } } process.on("SIGTERM", () => { for (const [, c] of mcpBackends) c.stop(); process.exit(0); }); @@ -358,7 +377,7 @@ process.on("SIGINT", () => { for (const [, c] of mcpBackends) c.stop(); process. // BUILT-IN TOOLS (core group — always on) // ============================================================================= -const BUILTIN_TOOLS = [ +const BUILTIN_TOOL_DEFS = [ { name: "search", description: "Search your knowledge base for relevant information.", @@ -403,6 +422,7 @@ const BUILTIN_TOOLS = [ }, }, ]; +const BUILTIN_TOOLS = BUILTIN_TOOL_DEFS.filter(t => toolPolicy.allowsBuiltin(t.name)); // ============================================================================= // GUIDANCE ENGINE — AI-facing instruction system @@ -952,25 +972,23 @@ async function executeGoapSearchGemini(query, args) { // ADR-166 §6 Phase 1d + 2a — server-side tool gate. // Enforced HERE (not just in the autopilot handler) so /mcp, /mcp/:group, -// autopilot, and any future path share ONE denial gate. Was the missing -// link that made the disclosed unauthenticated-RCE chain reach shell. -const DANGEROUS_TOOLS = Object.freeze(new Set([ - "terminal_execute", - "ruflo__terminal_execute", - "devtools__terminal_execute", -])); -function isTerminalTool(name) { - return DANGEROUS_TOOLS.has(name) || /terminal_execute/i.test(name); +// autopilot, and any future path share ONE denial gate. The decision is the +// capability policy's (tool-policy.js): a built-in must be allowed by it, and a +// backend tool must be in the policy-filtered list from getActiveTools(). A +// tool it does not know is refused here, before any backend sees the call. +function isToolPermitted(name) { + if (typeof name !== "string") return false; + if (BUILTIN_TOOL_DEFS.some(t => t.name === name)) return toolPolicy.allowsBuiltin(name); + return getActiveTools().some(t => t.name === name); } -const MCP_ENABLE_TERMINAL = process.env.MCP_ENABLE_TERMINAL === "true"; async function executeTool(name, args) { - // Deny dangerous tools unless the operator explicitly opted in. - // Enforced on every path (not just autopilot) — root cause of ADR-166 V2/V3. - if (isTerminalTool(name) && !MCP_ENABLE_TERMINAL) { + // Deny every tool the capability policy does not allow, on every path. + // Root cause of ADR-166 V2/V3; the policy replaced a name-pattern check. + if (!isToolPermitted(name)) { return { error: - `Tool "${name}" is disabled by default. Set MCP_ENABLE_TERMINAL=true to allow.`, + `Tool "${name}" is not available. Unknown tools are denied, and tools that run commands, touch files or reach the network need the operator to allow that capability (MCP_ALLOW_CAPABILITIES).`, code: "TOOL_DISABLED", }; } @@ -1617,7 +1635,6 @@ const AUTOPILOT_BLOCKED_PATTERNS = [ /^security_delete/, /^browser_fill$/, /^browser_click$/, - /terminal_execute/, ]; function isBlockedTool(name) { @@ -2035,11 +2052,12 @@ async function main() { // ADR-166 §6 — startup posture banner (helps operators see the security state at boot) console.log( `[security] bind=${BIND_HOST} auth=${process.env.MCP_AUTH_TOKEN ? "bearer" : "off (local-only)"} ` + - `terminal=${MCP_ENABLE_TERMINAL ? "ENABLED (⚠ opt-in)" : "disabled"}`, + `capabilities=${toolPolicy.allowed.join(",")}`, ); - if (MCP_ENABLE_TERMINAL) { + const risky = toolPolicy.allowed.filter(c => ["network", "file", "shell"].includes(c)); + if (risky.length > 0) { console.warn( - "[security] WARNING: terminal_execute is enabled. This tool grants shell access " + + `[security] WARNING: ${risky.join(", ")} tools are enabled. They grant command, file or network access ` + "inside the bridge container to any client the auth layer accepts. Ensure " + "MCP_AUTH_TOKEN is set on any non-loopback bind. See ADR-166 §6 Phase 1d.", ); diff --git a/ruflo/src/ruvocal/mcp-bridge/tool-policy.js b/ruflo/src/ruvocal/mcp-bridge/tool-policy.js new file mode 100644 index 0000000000..18d13e8461 --- /dev/null +++ b/ruflo/src/ruvocal/mcp-bridge/tool-policy.js @@ -0,0 +1,348 @@ +// Tool capability policy for the MCP bridges. +// +// One reviewed allowlist assigns a capability to every tool the bridge may +// offer. The bridge asks this module when it builds its tool list, so a tool +// that is denied is neither listed nor callable, and a denied call is refused +// before anything is sent to a backend. +// +// Unknown tools are denied. A tool is known only if its backend and exact +// name appear in BACKEND_TOOL_CAPABILITIES below. A name that merely looks +// harmless, or a new tool a backend adds in a later release, gets no +// capability and stays hidden until someone traces its handler and adds it. +// +// This file is shared by ruflo/src/mcp-bridge and ruflo/src/ruvocal/mcp-bridge. +// The two copies must be byte-identical; test-tool-policy.mjs checks that. +// +// Capabilities, least to most dangerous: +// read no side effects; reads the backend's own state +// state writes only the backend's own data store, at paths the caller +// cannot choose +// search the bridge's built-in search, sent to operator-configured endpoints +// network outbound requests the caller can direct +// file reads or writes filesystem paths the caller can influence +// shell runs processes or code +// +// read, state and search are allowed by default. Operators opt into the rest +// with MCP_ALLOW_CAPABILITIES (comma list, e.g. "network,file"). +// MCP_ENABLE_TERMINAL=true remains an alias for allowing "shell". + +export const CAPABILITIES = Object.freeze(["read", "state", "search", "network", "file", "shell"]); +const DEFAULT_ALLOWED = Object.freeze(["read", "state", "search"]); + +export const BUILTIN_CAPABILITIES = Object.freeze({ + search: "search", + web_research: "search", + guidance: "read", +}); + +// Traced against ruflo 3.82.0 and ruvector 0.3.29 (2026-12-02). Only tools in +// groups that are enabled by default were reviewed. Tools from the opt-in +// groups (security, browser, neural, agentic-flow, gemini) and from Claude +// Code have no entry, so they stay hidden even when their group is enabled. +// Each entry was assigned by reading the tool's handler code. +// +// Judgement calls, so a later reviewer can revisit them: +// - Downloading the fixed embedding model on first use is not "network": the +// caller cannot direct it. Tools whose only outbound request is that download +// are "state". +// - ruflo memory_* tools that accept a database path are "file". +// - A fixed `node -e` header probe (graph-edge-writer) still spawns a process. +// The tools the review traced to it are "shell"; other tools that open the +// memory database may reach the same harmless probe. +// - No config_* tool has an entry: config_set, config_import and config_reset +// change settings, such as the model endpoint, that other tools act on, and +// the read tools are held back until their output has been reviewed. +// - swarm_shutdown is "file": it runs agent_terminate's cleanup, which deletes +// a memory branch path recorded when the agent was spawned. +export const BACKEND_TOOL_CAPABILITIES = Object.freeze({ + ruflo: Object.freeze({ + "agent_execute": "network", + "agent_health": "read", + "agent_list": "read", + "agent_logs": "read", + "agent_pool": "state", + "agent_spawn": "file", + "agent_status": "read", + "agent_terminate": "file", + "agent_update": "state", + "agentdb_batch": "state", + "agentdb_causal-edge": "shell", + "agentdb_causal-edge-delete": "state", + "agentdb_causal-node-delete": "state", + "agentdb_consolidate": "state", + "agentdb_context-synthesize": "state", + "agentdb_controllers": "state", + "agentdb_episode-delete": "state", + "agentdb_episode-get": "state", + "agentdb_episode-list": "state", + "agentdb_episode-recall": "state", + "agentdb_episode-update": "state", + "agentdb_feedback": "state", + "agentdb_graph-pathfinder": "shell", + "agentdb_graph-query": "shell", + "agentdb_health": "state", + "agentdb_hierarchical-delete": "state", + "agentdb_hierarchical-get": "state", + "agentdb_hierarchical-list": "state", + "agentdb_hierarchical-recall": "state", + "agentdb_hierarchical-stats": "state", + "agentdb_hierarchical-store": "state", + "agentdb_pattern-list": "state", + "agentdb_pattern-search": "state", + "agentdb_pattern-store": "state", + "agentdb_route": "state", + "agentdb_semantic-route": "state", + "agentdb_session-end": "state", + "agentdb_session-start": "state", + "agentdb_skill-get": "state", + "agentdb_skill-list": "state", + "analyze_diff": "shell", + "analyze_diff-classify": "shell", + "analyze_diff-reviewers": "shell", + "analyze_diff-risk": "shell", + "analyze_diff-stats": "shell", + "analyze_file-risk": "read", + "coordination_consensus": "state", + "coordination_load_balance": "state", + "coordination_metrics": "read", + "coordination_node": "state", + "coordination_orchestrate": "state", + "coordination_sync": "state", + "coordination_topology": "state", + "embeddings_compare": "state", + "embeddings_generate": "state", + "embeddings_hyperbolic": "read", + "embeddings_init": "state", + "embeddings_neural": "state", + "embeddings_rabitq_build": "state", + "embeddings_rabitq_search": "state", + "embeddings_rabitq_status": "read", + "embeddings_search": "state", + "embeddings_status": "state", + "github_issue_track": "shell", + "github_metrics": "shell", + "github_pr_manage": "shell", + "github_repo_analyze": "shell", + "github_workflow": "shell", + "hive-mind_broadcast": "state", + "hive-mind_consensus": "state", + "hive-mind_init": "state", + "hive-mind_join": "state", + "hive-mind_leave": "state", + "hive-mind_memory": "state", + "hive-mind_optimize-memory": "state", + "hive-mind_shutdown": "state", + "hive-mind_spawn": "state", + "hive-mind_status": "read", + "hooks_build-agents": "file", + "hooks_codemod": "file", + "hooks_coverage-gaps": "file", + "hooks_coverage-route": "file", + "hooks_coverage-suggest": "file", + "hooks_explain": "read", + "hooks_fast-apply": "file", + "hooks_init": "read", + "hooks_intelligence": "state", + "hooks_intelligence-reset": "state", + "hooks_intelligence_attention": "state", + "hooks_intelligence_learn": "state", + "hooks_intelligence_pattern-search": "state", + "hooks_intelligence_pattern-store": "state", + "hooks_intelligence_stats": "read", + "hooks_intelligence_trajectory-end": "state", + "hooks_intelligence_trajectory-start": "state", + "hooks_intelligence_trajectory-step": "shell", + "hooks_intelligence_unified-stats": "read", + "hooks_intelligence_verified-ingest": "shell", + "hooks_list": "read", + "hooks_metrics": "read", + "hooks_model-outcome": "state", + "hooks_model-route": "state", + "hooks_model-stats": "read", + "hooks_model-verify": "state", + "hooks_notify": "read", + "hooks_post-command": "state", + "hooks_post-edit": "state", + "hooks_post-task": "shell", + "hooks_pre-command": "read", + "hooks_pre-edit": "read", + "hooks_pre-task": "file", + "hooks_pretrain": "file", + "hooks_route": "state", + "hooks_session-end": "state", + "hooks_session-restore": "read", + "hooks_session-start": "shell", + "hooks_task-completed": "state", + "hooks_teammate-idle": "read", + "hooks_transfer": "file", + "hooks_worker-cancel": "state", + "hooks_worker-detect": "state", + "hooks_worker-dispatch": "shell", + "hooks_worker-list": "read", + "hooks_worker-status": "read", + "memory_bridge_status": "state", + "memory_cleanup": "state", + "memory_compress": "state", + "memory_delete": "file", + "memory_detailed-stats": "state", + "memory_export": "file", + "memory_import": "file", + "memory_import_claude": "shell", + "memory_list": "file", + "memory_list_scopes": "file", + "memory_migrate": "state", + "memory_retrieve": "file", + "memory_search": "file", + "memory_search_unified": "state", + "memory_stats": "file", + "memory_store": "file", + "performance_benchmark": "state", + "performance_bottleneck": "state", + "performance_metrics": "read", + "performance_optimize": "state", + "performance_profile": "state", + "performance_report": "state", + "progress_check": "read", + "progress_summary": "read", + "progress_sync": "state", + "progress_watch": "read", + "session_current": "read", + "session_delete": "state", + "session_export": "file", + "session_import": "file", + "session_info": "read", + "session_list": "read", + "session_restore": "state", + "session_save": "state", + "swarm_health": "state", + "swarm_init": "state", + "swarm_pheromone_status": "state", + "swarm_pheromone_update": "state", + "swarm_shutdown": "file", + "swarm_status": "state", + "system_health": "state", + "system_info": "read", + "system_metrics": "state", + "system_reset": "state", + "system_status": "read", + "task_assign": "state", + "task_cancel": "state", + "task_complete": "state", + "task_create": "state", + "task_list": "read", + "task_retry": "state", + "task_status": "read", + "task_summary": "read", + "task_update": "state", + "terminal_close": "state", + "terminal_create": "shell", + "terminal_execute": "shell", + "terminal_history": "read", + "terminal_list": "read", + "workflow_cancel": "state", + "workflow_create": "state", + "workflow_delete": "state", + "workflow_execute": "network", + "workflow_list": "read", + "workflow_pause": "state", + "workflow_resume": "network", + "workflow_run": "state", + "workflow_status": "read", + "workflow_stop": "state", + "workflow_template": "state", + "workflow_validate": "file", + }), + ruvector: Object.freeze({ + "hooks_algorithms_list": "read", + "hooks_ast_analyze": "shell", + "hooks_ast_complexity": "shell", + "hooks_attention_info": "read", + "hooks_batch_learn": "state", + "hooks_build_agents": "shell", + "hooks_capabilities": "read", + "hooks_coedit_record": "state", + "hooks_coedit_suggest": "read", + "hooks_compress": "state", + "hooks_compress_get": "read", + "hooks_compress_stats": "read", + "hooks_compress_store": "state", + "hooks_coverage_route": "shell", + "hooks_coverage_suggest": "shell", + "hooks_diff_analyze": "shell", + "hooks_diff_classify": "shell", + "hooks_diff_similar": "shell", + "hooks_doctor": "shell", + "hooks_error_record": "state", + "hooks_error_suggest": "read", + "hooks_export": "read", + "hooks_force_learn": "state", + "hooks_forget": "state", + "hooks_git_churn": "shell", + "hooks_gnn_info": "read", + "hooks_graph_cluster": "shell", + "hooks_graph_mincut": "shell", + "hooks_import": "state", + "hooks_init": "shell", + "hooks_learn": "state", + "hooks_learning_config": "state", + "hooks_learning_stats": "read", + "hooks_learning_update": "state", + "hooks_memory_get": "read", + "hooks_memory_list": "read", + "hooks_memory_update": "state", + "hooks_pretrain": "shell", + "hooks_rag_context": "shell", + "hooks_recall": "read", + "hooks_remember": "state", + "hooks_route": "read", + "hooks_route_enhanced": "file", + "hooks_security_scan": "shell", + "hooks_stats": "read", + "hooks_subscribe_snapshot": "read", + "hooks_suggest_context": "read", + "hooks_swarm_recommend": "read", + "hooks_trajectory_begin": "state", + "hooks_trajectory_end": "state", + "hooks_trajectory_step": "state", + "hooks_verify": "shell", + "hooks_watch_status": "read", + }), +}); + +const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key); + +export function allowedCapabilities(env = {}) { + const allowed = new Set(DEFAULT_ALLOWED); + const extra = typeof env.MCP_ALLOW_CAPABILITIES === "string" ? env.MCP_ALLOW_CAPABILITIES : ""; + for (const raw of extra.split(",")) { + const capability = raw.trim().toLowerCase(); + if (CAPABILITIES.includes(capability)) allowed.add(capability); + } + if (env.MCP_ENABLE_TERMINAL === "true") allowed.add("shell"); + return allowed; +} + +export function capabilityOf(backend, toolName) { + if (typeof backend !== "string" || typeof toolName !== "string") return null; + if (!hasOwn(BACKEND_TOOL_CAPABILITIES, backend)) return null; + const table = BACKEND_TOOL_CAPABILITIES[backend]; + return hasOwn(table, toolName) ? table[toolName] : null; +} + +export function builtinCapabilityOf(toolName) { + return typeof toolName === "string" && hasOwn(BUILTIN_CAPABILITIES, toolName) + ? BUILTIN_CAPABILITIES[toolName] + : null; +} + +export function createToolPolicy(env = {}) { + const allowed = allowedCapabilities(env); + const permits = (capability) => capability !== null && allowed.has(capability); + return Object.freeze({ + allowed: Object.freeze([...allowed]), + allowsBuiltin: (toolName) => permits(builtinCapabilityOf(toolName)), + allows: (backend, toolName) => permits(capabilityOf(backend, toolName)), + // Why a tool is withheld, for logs: "unreviewed" or the capability it needs. + reason: (backend, toolName) => capabilityOf(backend, toolName) ?? "unreviewed", + }); +} diff --git a/ruflo/src/scripts/package-rvf.sh b/ruflo/src/scripts/package-rvf.sh index 5e87b087e5..2207a5e836 100755 --- a/ruflo/src/scripts/package-rvf.sh +++ b/ruflo/src/scripts/package-rvf.sh @@ -81,6 +81,7 @@ tar czf "$OUTPUT" \ mcp-bridge/Dockerfile \ chat-ui/Dockerfile \ mcp-bridge/url-guard.js \ + mcp-bridge/tool-policy.js \ chat-ui/static/ \ mcp-bridge/mcp-stdio-kernel.js \ mcp-bridge/test-harness.js \