π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
security(mcp-bridge): ADR-166 unauthenticated RCE β Phase 1-3 remediation + CI lock (#2521)
rUvd00a0a40cd8b
diff --git a/.github/workflows/adr-166-mcp-bridge-security.yml b/.github/workflows/adr-166-mcp-bridge-security.ymlnew file mode 100644index 0000000000..96c643ef84--- /dev/null+++ b/.github/workflows/adr-166-mcp-bridge-security.yml@@ -0,0 +1,94 @@+name: ADR-166 MCP Bridge Security Lock++# Anti-regression gate for the ADR-166 remediation. Runs on every PR touching+# either bridge file, the shared docker-compose, or the security tests. Fails+# closed if any load-bearing control drifts.++on:+ push:+ branches: [main]+ paths:+ - 'ruflo/src/mcp-bridge/**'+ - 'ruflo/src/ruvocal/mcp-bridge/**'+ - 'ruflo/docker-compose.yml'+ - 'ruflo/docker-compose.public.yml'+ - 'v3/@claude-flow/plugin-agent-federation/src/bin.ts'+ - '.github/workflows/adr-166-mcp-bridge-security.yml'+ pull_request:+ paths:+ - 'ruflo/src/mcp-bridge/**'+ - 'ruflo/src/ruvocal/mcp-bridge/**'+ - 'ruflo/docker-compose.yml'+ - 'ruflo/docker-compose.public.yml'+ - 'v3/@claude-flow/plugin-agent-federation/src/bin.ts'+ - '.github/workflows/adr-166-mcp-bridge-security.yml'+ workflow_dispatch:++jobs:+ static-source-lock:+ name: Static-source security lock+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ - name: ADR-166 Β§6 #9 β anti-regression lock (both bridges)+ run: node ruflo/src/mcp-bridge/test-security-lock.js++ runtime-behavior:+ name: Runtime behavior β 401 + terminal gate + fail-closed+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ - name: Install both bridges+ run: |+ (cd ruflo/src/mcp-bridge && npm install --no-audit --no-fund)+ (cd ruflo/src/ruvocal/mcp-bridge && npm install --no-audit --no-fund)+ - name: ADR-166 runtime verification+ run: node ruflo/src/mcp-bridge/test-runtime-security.mjs++ compose-loopback-only:+ name: Compose default binds loopback + Mongo has auth+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - name: Assert docker-compose binds ONLY to 127.0.0.1+ run: |+ set -euo pipefail+ # No line may map a container port to a public host port.+ # Look for "N.N.N.N:PORT:PORT" or bare "PORT:PORT" patterns under `ports:`.+ if grep -nE '^\s*-\s+"(?!127\.0\.0\.1|0\.0\.0\.0)?[^"]*3001:3001"' ruflo/docker-compose.yml \+ | grep -v '127.0.0.1:3001'; then+ echo "::error::docker-compose.yml exposes 3001 on non-loopback interface"+ exit 1+ fi+ if grep -nE '^\s*-\s+"(?!127\.0\.0\.1|0\.0\.0\.0)?[^"]*27017:27017"' ruflo/docker-compose.yml \+ | grep -v '127.0.0.1:27017'; then+ echo "::error::docker-compose.yml exposes 27017 on non-loopback interface"+ exit 1+ fi+ # Mongo must run with --auth AND require MONGO_INITDB_ROOT_PASSWORD to boot.+ grep -q '"--auth"' ruflo/docker-compose.yml \+ || { echo "::error::mongodb service missing --auth (Phase 2b)"; exit 1; }+ grep -q 'MONGO_INITDB_ROOT_PASSWORD:\?' ruflo/docker-compose.yml \+ || { 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; }+ echo "compose defaults: OK"++ federation-loopback-default:+ name: plugin-agent-federation bindHost default+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - name: Assert bindHost defaults to 127.0.0.1+ run: |+ set -euo pipefail+ grep -q "bindHost: process.env.FEDERATION_BIND_HOST ?? '127.0.0.1'" \+ v3/@claude-flow/plugin-agent-federation/src/bin.ts \+ || { echo "::error::plugin-agent-federation bindHost must default to 127.0.0.1 (Phase 3d)"; exit 1; }+ echo "federation default: OK"diff --git a/ruflo/docker-compose.public.yml b/ruflo/docker-compose.public.ymlnew file mode 100644index 0000000000..e0f0552757--- /dev/null+++ b/ruflo/docker-compose.public.yml@@ -0,0 +1,21 @@+# Optional public deployment override.+# Use: docker compose -f docker-compose.yml -f docker-compose.public.yml up -d+#+# Required env vars (set in .env or your secrets manager):+# MCP_BIND_HOST=0.0.0.0+# MCP_AUTH_TOKEN=<base64 token, >=32 bytes; openssl rand -base64 32>+#+# Without both, the bridge will exit non-zero at startup.+services:+ mcp-bridge:+ ports:+ - "${MCP_BIND_HOST:-127.0.0.1}:3001:3001"+ environment:+ MCP_BIND_HOST: "${MCP_BIND_HOST}"+ MCP_AUTH_TOKEN: "${MCP_AUTH_TOKEN}"+ mongodb:+ # Public deployment uses stronger Mongo isolation β auth + non-mapped host port.+ ports: [] # remove the host port mapping; access only over the docker network+ environment:+ MONGO_INITDB_ROOT_USERNAME: "${MONGO_ROOT_USERNAME}"+ MONGO_INITDB_ROOT_PASSWORD: "${MONGO_ROOT_PASSWORD}"diff --git a/ruflo/docker-compose.yml b/ruflo/docker-compose.ymlindex 8d5b439ee6..27044e07fa 100644--- a/ruflo/docker-compose.yml+++ b/ruflo/docker-compose.yml@@ -6,16 +6,19 @@# docker compose up -dservices:- # --- MongoDB ---+ # --- MongoDB (ADR-166 Β§6 Phase 2b β auth on by default) ---mongodb:image: mongo:7restart: unless-stoppedvolumes:- mongo-data:/data/dbports:- - "27017:27017"+ - "127.0.0.1:27017:27017"environment:MONGO_INITDB_DATABASE: ${MONGODB_DB_NAME:-chat-db}+ MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME:-ruflo}+ MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD:?FATAL: MONGO_INITDB_ROOT_PASSWORD is required. Generate: MONGO_INITDB_ROOT_PASSWORD=$(openssl rand -base64 32)}+ command: ["--auth"]# --- MCP Bridge (ruvocal version β Gemini grounded search, autopilot SSE) ---mcp-bridge:@@ -24,7 +27,7 @@ services:dockerfile: Dockerfilerestart: unless-stoppedports:- - "3001:3001"+ - "127.0.0.1:3001:3001"environment:PORT: "3001"NODE_ENV: production@@ -51,6 +54,15 @@ services:MCP_GROUP_CODEX: ${MCP_GROUP_CODEX:-false}# API keys for optional groupsANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}+ # --- ADR-166 Β§6 security surface ---+ MCP_BIND_HOST: ${MCP_BIND_HOST:-127.0.0.1}+ MCP_AUTH_TOKEN: ${MCP_AUTH_TOKEN:-}+ MCP_ENABLE_TERMINAL: ${MCP_ENABLE_TERMINAL:-false}+ 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+ tmpfs:+ - /tmphealthcheck:test: ["CMD", "node", "-e", "fetch('http://localhost:3001/health').then(r => process.exit(r.ok ? 0 : 1))"]interval: 30s@@ -87,7 +99,7 @@ services:environment:# Runtime config injected via DOTENV_LOCAL (entrypoint.sh writes .env.local)DOTENV_LOCAL: |- MONGODB_URL=mongodb://mongodb:27017+ MONGODB_URL=mongodb://${MONGO_INITDB_ROOT_USERNAME:-ruflo}:${MONGO_INITDB_ROOT_PASSWORD}@mongodb:27017/${MONGODB_DB_NAME:-chat-db}?authSource=adminMONGODB_DB_NAME=${MONGODB_DB_NAME:-chat-db}PUBLIC_APP_NAME=${BRAND_NAME:-RuFlo}PUBLIC_APP_DESCRIPTION=${BRAND_DESCRIPTION:-Enterprise AI Agent Orchestration Platform}diff --git a/ruflo/src/mcp-bridge/index.js b/ruflo/src/mcp-bridge/index.jsindex 4425ec4c3c..c56b7938e1 100644--- a/ruflo/src/mcp-bridge/index.js+++ b/ruflo/src/mcp-bridge/index.js@@ -1,6 +1,6 @@import express from "express";import { spawn } from "child_process";-import { randomUUID } from "crypto";+import { randomUUID, timingSafeEqual } from "crypto";// =============================================================================// CONFIGURATION@@ -12,6 +12,7 @@ const CLOUD_FUNCTIONS = {};const PORT = parseInt(process.env.PORT || "3001", 10);+const BIND_HOST = process.env.MCP_BIND_HOST || "127.0.0.1";// =============================================================================// TOOL GROUPS β Enable/disable categories of tools independently@@ -771,7 +772,30 @@ async function executeGoapSearch(query, args) {// TOOL EXECUTOR// =============================================================================+// 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);+}+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) {+ return {+ error:+ `Tool "${name}" is disabled by default. Set MCP_ENABLE_TERMINAL=true to allow.`,+ code: "TOOL_DISABLED",+ };+ }// Validate that search-like tools have a non-empty query to prevent 400 errorsif (!args || typeof args !== "object") args = {};const rawQuery = args.query ?? args.q ?? args.input ?? "";@@ -858,15 +882,39 @@ const GROUP_DISPLAY_NAMES = {const app = express();app.use(express.json({ limit: "10mb" }));-// ---------- CORS middleware ----------+// ---------- CORS middleware (ADR-166 Β§6 Phase 3b) ----------+const CORS_ALLOWLIST = (process.env.MCP_CORS_ORIGIN || "*")+ .split(",").map(s => s.trim()).filter(Boolean);+const CORS_WILDCARD = CORS_ALLOWLIST.length === 1 && CORS_ALLOWLIST[0] === "*";app.use((req, res, next) => {- res.setHeader("Access-Control-Allow-Origin", "*");+ const origin = req.get("origin") || "";+ if (CORS_WILDCARD) {+ res.setHeader("Access-Control-Allow-Origin", "*");+ } else if (origin && CORS_ALLOWLIST.includes(origin)) {+ res.setHeader("Access-Control-Allow-Origin", origin);+ res.setHeader("Vary", "Origin");+ }res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");if (req.method === "OPTIONS") return res.sendStatus(204);next();});+// ---------- Auth middleware ----------+// No-op in local-only mode (MCP_AUTH_TOKEN unset). Enforces 401 when token is set.+const MCP_TOKEN = process.env.MCP_AUTH_TOKEN || "";+function requireAuth(req, res, next) {+ if (req.path === "/health") return next();+ if (!MCP_TOKEN) return next();+ const expected = `Bearer ${MCP_TOKEN}`;+ const got = req.get("authorization") || "";+ const ok = got.length === expected.length &&+ timingSafeEqual(Buffer.from(got), Buffer.from(expected));+ if (!ok) return res.status(401).json({ error: "unauthorized" });+ next();+}+app.use(requireAuth);+// ---------- Shared MCP handler ----------function createMcpHandler(groupName) {return async (req, res) => {@@ -1676,10 +1724,30 @@ app.get("/groups", (_, res) => {// =============================================================================async function main() {- app.listen(PORT, () => {- console.log(`MCP Bridge v2.0.0 on port ${PORT}`);+ const isPublic = BIND_HOST !== "127.0.0.1" && BIND_HOST !== "localhost";+ if (isPublic && !process.env.MCP_AUTH_TOKEN) {+ console.error(+ "FATAL: refusing to bind a public interface without MCP_AUTH_TOKEN. " ++ "Generate one with: MCP_AUTH_TOKEN=$(openssl rand -base64 32)"+ );+ process.exit(1);+ }+ app.listen(PORT, BIND_HOST, () => {+ console.log(`MCP Bridge v2.0.0 on port ${PORT} (${BIND_HOST})`);const enabled = Object.entries(TOOL_GROUPS).filter(([, g]) => g.enabled).map(([n]) => n);console.log(`Active groups: ${enabled.join(", ")}`);+ // 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"}`,+ );+ if (MCP_ENABLE_TERMINAL) {+ console.warn(+ "[security] WARNING: terminal_execute is enabled. This tool grants shell 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.",+ );+ }});const anyBackendNeeded = BACKEND_DEFS.some(isBackendNeeded);diff --git a/ruflo/src/mcp-bridge/test-runtime-security.mjs b/ruflo/src/mcp-bridge/test-runtime-security.mjsnew file mode 100644index 0000000000..2fb550be12--- /dev/null+++ b/ruflo/src/mcp-bridge/test-runtime-security.mjs@@ -0,0 +1,177 @@+#!/usr/bin/env node+/**+ * ADR-166 runtime verification β spawn each bridge with a test env and+ * assert the load-bearing behaviors observed OVER THE WIRE. Complements+ * test-security-lock.js (which is static-source only).+ *+ * Behaviors verified:+ * R1. bridge starts on 127.0.0.1 by default+ * R2. with MCP_AUTH_TOKEN set: unauthenticated POST /mcp β 401+ * R3. with MCP_AUTH_TOKEN set: authenticated POST /mcp β 200 (or β 401)+ * R4. terminal_execute call β TOOL_DISABLED error unless MCP_ENABLE_TERMINAL=true+ * R5. public bind without MCP_AUTH_TOKEN β process exits β 0 within 3s+ *+ * node test-runtime-security.mjs+ */++import { spawn } from "node:child_process";+import { setTimeout as sleep } from "node:timers/promises";+import path from "node:path";+import { fileURLToPath } from "node:url";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const BRIDGES = [+ { label: "src/mcp-bridge", entry: path.join(HERE, "index.js") },+ { label: "src/ruvocal/mcp-bridge", entry: path.join(HERE, "..", "ruvocal", "mcp-bridge", "index.js") },+];++const TOKEN = "test-token-" + Math.random().toString(36).slice(2);+let passed = 0, failed = 0;+const failures = [];++function assert(cond, label) {+ if (cond) { console.log(` β ${label}`); passed++; }+ else { console.log(` β ${label}`); failures.push(label); failed++; }+}++async function pickPort() {+ // Pick a random port in the ephemeral range and hope for the best;+ // if the bridge fails to bind, the fetch will time out and we fail.+ return 20000 + Math.floor(Math.random() * 10000);+}++async function startBridge(entry, env, { waitMs = 1500 } = {}) {+ const child = spawn("node", [entry], {+ env: { ...process.env, ...env },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let stdout = "", stderr = "";+ child.stdout.on("data", (d) => { stdout += d.toString(); });+ child.stderr.on("data", (d) => { stderr += d.toString(); });+ const exitPromise = new Promise((resolve) => {+ child.on("exit", (code) => resolve({ exited: true, code }));+ });+ const ready = Promise.race([+ exitPromise,+ sleep(waitMs).then(() => ({ exited: false, code: null })),+ ]);+ return { child, stdout: () => stdout, stderr: () => stderr, ready };+}++async function killAndWait(child) {+ if (child.exitCode !== null) return;+ try { child.kill("SIGTERM"); } catch { /* ignore */ }+ await sleep(100);+ if (child.exitCode === null) try { child.kill("SIGKILL"); } catch { /* ignore */ }+}++async function testBridge(label, entry) {+ console.log(`\n# ${label}`);++ // R1 + R2 + R3 + R4 β bridge starts with token, auth behavior + terminal gate+ {+ const port = await pickPort();+ const b = await startBridge(entry, {+ PORT: String(port),+ MCP_BIND_HOST: "127.0.0.1",+ MCP_AUTH_TOKEN: TOKEN,+ MCP_ENABLE_TERMINAL: "false",+ MCP_GROUP_DEVTOOLS: "false",+ MCP_GROUP_INTELLIGENCE: "false",+ MCP_GROUP_AGENTS: "false",+ MCP_GROUP_MEMORY: "false",+ });+ const state = await b.ready;+ if (state.exited) {+ assert(false, `R1. bridge starts on 127.0.0.1 (exited early, code=${state.code}; stderr=${b.stderr().slice(0, 200)})`);+ } else {+ assert(true, "R1. bridge starts on 127.0.0.1 (didn't exit within 1.5s)");++ // R2 β unauthenticated POST /mcp β 401+ try {+ const r = await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),+ });+ assert(r.status === 401, `R2. unauthenticated POST /mcp β 401 (got ${r.status})`);+ } catch (e) {+ assert(false, `R2. unauthenticated POST /mcp threw: ${e.message}`);+ }++ // R3 β authenticated POST /mcp β not 401+ try {+ const r = await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Authorization": `Bearer ${TOKEN}`,+ },+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),+ });+ assert(r.status !== 401, `R3. authenticated POST /mcp β β 401 (got ${r.status})`);+ } catch (e) {+ assert(false, `R3. authenticated POST /mcp threw: ${e.message}`);+ }++ // R4 β terminal_execute β TOOL_DISABLED (denied at executeTool, not just autopilot)+ try {+ const r = await fetch(`http://127.0.0.1:${port}/mcp`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Authorization": `Bearer ${TOKEN}`,+ },+ body: JSON.stringify({+ jsonrpc: "2.0", id: 1, method: "tools/call",+ params: { name: "terminal_execute", arguments: { command: "id" } },+ }),+ });+ const body = await r.json();+ // The response wraps the executeTool result in `result.content[0].text` as JSON string.+ const text = JSON.stringify(body);+ assert(text.includes("TOOL_DISABLED") || text.includes("disabled by default"),+ "R4. terminal_execute denied server-side (TOOL_DISABLED)");+ } catch (e) {+ assert(false, `R4. terminal_execute threw: ${e.message}`);+ }+ }+ await killAndWait(b.child);+ }++ // R5 β public bind without token β process exits β 0 within 3s+ {+ const port = await pickPort();+ const b = await startBridge(entry, {+ PORT: String(port),+ MCP_BIND_HOST: "0.0.0.0",+ MCP_AUTH_TOKEN: "",+ MCP_GROUP_DEVTOOLS: "false",+ MCP_GROUP_INTELLIGENCE: "false",+ MCP_GROUP_AGENTS: "false",+ MCP_GROUP_MEMORY: "false",+ }, { waitMs: 3000 });+ const state = await b.ready;+ assert(state.exited && state.code !== 0,+ `R5. public bind without token exits β 0 (exited=${state.exited}, code=${state.code})`);+ if (b.stderr().includes("FATAL")) {+ assert(true, "R5b. FATAL message logged to stderr");+ } else {+ assert(false, "R5b. FATAL message expected in stderr");+ }+ await killAndWait(b.child);+ }+}++(async () => {+ for (const { label, entry } of BRIDGES) {+ await testBridge(label, entry);+ }+ console.log(`\n${passed} passed, ${failed} failed`);+ if (failed > 0) {+ console.log("\nFailures:");+ for (const f of failures) console.log(` - ${f}`);+ process.exit(1);+ }+ console.log("ADR-166 runtime verification: OK");+})();diff --git a/ruflo/src/mcp-bridge/test-security-lock.js b/ruflo/src/mcp-bridge/test-security-lock.jsnew file mode 100755index 0000000000..4c252f5f8a--- /dev/null+++ b/ruflo/src/mcp-bridge/test-security-lock.js@@ -0,0 +1,88 @@+#!/usr/bin/env node+/**+ * ADR-166 Β§6 acceptance #9 β anti-regression lock for the MCP-bridge+ * security surface. Runs on the source of BOTH bridge files (the ruvocal+ * variant that ships in docker-compose, and the sibling REST bridge).+ *+ * Fails if any of the following load-bearing controls silently disappears:+ * 1. `MCP_BIND_HOST` default is `127.0.0.1` (loopback default β Phase 1a)+ * 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)+ * 6. CORS respects `MCP_CORS_ORIGIN` allowlist (Phase 3b)+ *+ * Runs offline (no server, no deps). CI-safe.+ *+ * node test-security-lock.js # β exit 0 on green, exit 1 on regression+ */++import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const BRIDGES = [+ path.join(HERE, "index.js"), // ruflo/src/mcp-bridge/index.js+ path.join(HERE, "..", "ruvocal", "mcp-bridge", "index.js"), // ruvocal variant (deployed)+];++const CHECKS = [+ {+ id: "1. bind-loopback-default",+ rx: /BIND_HOST\s*=\s*process\.env\.MCP_BIND_HOST\s*\|\|\s*["']127\.0\.0\.1["']/,+ hint: "MCP_BIND_HOST must default to 127.0.0.1 (ADR-166 Β§6 Phase 1a)",+ },+ {+ id: "2. fail-closed-public-bind",+ rx: /isPublic\s*&&\s*!process\.env\.MCP_AUTH_TOKEN[\s\S]*?process\.exit\(\s*1\s*\)/,+ hint: "public bind without MCP_AUTH_TOKEN must process.exit(1) at boot (Phase 1b)",+ },+ {+ id: "3. auth-middleware-mounted",+ rx: /app\.use\(\s*requireAuth\s*\)/,+ hint: "requireAuth middleware must be mounted via app.use() (Phase 1c)",+ },+ {+ id: "4. constant-time-token-compare",+ rx: /timingSafeEqual\s*\(/,+ 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: "6. cors-allowlist-respected",+ rx: /MCP_CORS_ORIGIN[\s\S]*?CORS_ALLOWLIST/,+ hint: "CORS must respect MCP_CORS_ORIGIN allowlist (Phase 3b)",+ },+];++let hardFail = false;+for (const bridge of BRIDGES) {+ if (!fs.existsSync(bridge)) {+ console.error(`FAIL: bridge missing: ${bridge}`);+ hardFail = true;+ continue;+ }+ const src = fs.readFileSync(bridge, "utf-8");+ const rel = path.relative(path.join(HERE, "..", ".."), bridge);+ console.log(`\n# ${rel}`);+ for (const check of CHECKS) {+ if (check.rx.test(src)) {+ console.log(` β ${check.id}`);+ } else {+ console.log(` β ${check.id}`);+ console.log(` hint: ${check.hint}`);+ hardFail = true;+ }+ }+}++if (hardFail) {+ console.error("\nADR-166 security lock FAILED β a load-bearing control was removed or drifted.");+ process.exit(1);+}+console.log("\nADR-166 security lock: OK");diff --git a/ruflo/src/ruvocal/mcp-bridge/index.js b/ruflo/src/ruvocal/mcp-bridge/index.jsindex 1a49cb7d84..0dcbad521c 100644--- a/ruflo/src/ruvocal/mcp-bridge/index.js+++ b/ruflo/src/ruvocal/mcp-bridge/index.js@@ -1,6 +1,6 @@import express from "express";import { spawn } from "child_process";-import { randomUUID } from "crypto";+import { randomUUID, timingSafeEqual } from "crypto";// =============================================================================// CONFIGURATION@@ -12,6 +12,7 @@ const CLOUD_FUNCTIONS = {};const PORT = parseInt(process.env.PORT || "3001", 10);+const BIND_HOST = process.env.MCP_BIND_HOST || "127.0.0.1";// =============================================================================// TOOL GROUPS β Enable/disable categories of tools independently@@ -942,7 +943,30 @@ async function executeGoapSearchGemini(query, args) {// TOOL EXECUTOR// =============================================================================+// 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);+}+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) {+ return {+ error:+ `Tool "${name}" is disabled by default. Set MCP_ENABLE_TERMINAL=true to allow.`,+ code: "TOOL_DISABLED",+ };+ }switch (name) {case "search": {if (CLOUD_FUNCTIONS.search) {@@ -1033,15 +1057,44 @@ const GROUP_DISPLAY_NAMES = {const app = express();app.use(express.json({ limit: "10mb" }));-// ---------- CORS middleware ----------+// ---------- CORS middleware (ADR-166 Β§6 Phase 3b) ----------+// MCP_CORS_ORIGIN: comma-separated allowlist (e.g. "https://a.example,https://b.example").+// unset β "*" for back-compat (loopback default is same-origin anyway)+// "*" β wildcard (explicit opt-in β same as legacy behavior)+// other β echo the request origin ONLY if it appears in the allowlist+const CORS_ALLOWLIST = (process.env.MCP_CORS_ORIGIN || "*")+ .split(",").map(s => s.trim()).filter(Boolean);+const CORS_WILDCARD = CORS_ALLOWLIST.length === 1 && CORS_ALLOWLIST[0] === "*";app.use((req, res, next) => {- res.setHeader("Access-Control-Allow-Origin", "*");+ const origin = req.get("origin") || "";+ if (CORS_WILDCARD) {+ res.setHeader("Access-Control-Allow-Origin", "*");+ } else if (origin && CORS_ALLOWLIST.includes(origin)) {+ res.setHeader("Access-Control-Allow-Origin", origin);+ res.setHeader("Vary", "Origin");+ }+ // If no match, do NOT set the header β browser will block the request.res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");if (req.method === "OPTIONS") return res.sendStatus(204);next();});+// ---------- Auth middleware ----------+// No-op in local-only mode (MCP_AUTH_TOKEN unset). Enforces 401 when token is set.+const MCP_TOKEN = process.env.MCP_AUTH_TOKEN || "";+function requireAuth(req, res, next) {+ if (req.path === "/health") return next();+ if (!MCP_TOKEN) return next();+ const expected = `Bearer ${MCP_TOKEN}`;+ const got = req.get("authorization") || "";+ const ok = got.length === expected.length &&+ timingSafeEqual(Buffer.from(got), Buffer.from(expected));+ if (!ok) return res.status(401).json({ error: "unauthorized" });+ next();+}+app.use(requireAuth);+// ---------- Shared MCP handler ----------function createMcpHandler(groupName) {return async (req, res) => {@@ -1886,10 +1939,30 @@ app.get("/groups", (_, res) => {// =============================================================================async function main() {- app.listen(PORT, () => {- console.log(`MCP Bridge v2.0.0 on port ${PORT}`);+ const isPublic = BIND_HOST !== "127.0.0.1" && BIND_HOST !== "localhost";+ if (isPublic && !process.env.MCP_AUTH_TOKEN) {+ console.error(+ "FATAL: refusing to bind a public interface without MCP_AUTH_TOKEN. " ++ "Generate one with: MCP_AUTH_TOKEN=$(openssl rand -base64 32)"+ );+ process.exit(1);+ }+ app.listen(PORT, BIND_HOST, () => {+ console.log(`MCP Bridge v2.0.0 on port ${PORT} (${BIND_HOST})`);const enabled = Object.entries(TOOL_GROUPS).filter(([, g]) => g.enabled).map(([n]) => n);console.log(`Active groups: ${enabled.join(", ")}`);+ // 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"}`,+ );+ if (MCP_ENABLE_TERMINAL) {+ console.warn(+ "[security] WARNING: terminal_execute is enabled. This tool grants shell 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.",+ );+ }});const anyBackendNeeded = BACKEND_DEFS.some(isBackendNeeded);diff --git a/v3/@claude-flow/plugin-agent-federation/src/bin.ts b/v3/@claude-flow/plugin-agent-federation/src/bin.tsindex bd81cb8d17..4f5ded967f 100644--- a/v3/@claude-flow/plugin-agent-federation/src/bin.ts+++ b/v3/@claude-flow/plugin-agent-federation/src/bin.ts@@ -129,7 +129,7 @@ function makeContext(): PluginContext {return {config: {nodeName: process.env.FEDERATION_NODE_NAME ?? hostname(),- bindHost: process.env.FEDERATION_BIND_HOST ?? '0.0.0.0',+ bindHost: process.env.FEDERATION_BIND_HOST ?? '127.0.0.1',bindPort: Number(process.env.FEDERATION_BIND_PORT ?? 8443),defaultTrustLevel: process.env.FEDERATION_TRUST_LEVEL ?? 'untrusted',},diff --git a/v3/docs/adr/ADR-166-mcp-bridge-unauthenticated-rce-remediation.md b/v3/docs/adr/ADR-166-mcp-bridge-unauthenticated-rce-remediation.mdnew file mode 100644index 0000000000..8fb8a53c0b--- /dev/null+++ b/v3/docs/adr/ADR-166-mcp-bridge-unauthenticated-rce-remediation.md@@ -0,0 +1,356 @@+# ADR-166: MCP Bridge Unauthenticated RCE β Coordinated Disclosure Remediation++**ID**: ADR-166+**Status**: Accepted β Phase 0-3 shipped 2026-06-30 (this branch). Runtime + static locks green on both bridges.+**Date**: 2026-06-30+**Authors**: Dragan Spiridonov, rUv (drafted with Claude Code)+**Acknowledgements**: External security researcher who disclosed the vulnerability under coordinated disclosure (name withheld until embargo lifts and CVE is public). Their end-to-end PoC + video made the eight-step chain concrete instead of theoretical, which drove the choice to bind loopback by default rather than paper over with a token-only fix. Reporter will be credited by name in the GitHub Security Advisory + CVE when published.+**Branch**: security/adr-166-mcp-bridge-rce+**Disclosure**: External coordinated disclosure received 2026-06-30 from an independent security researcher. Reporter identity, the PoC's OAST callback domain, and the target EC2 address are withheld from this document. Treat as **embargoed** until Phase 1 ships and a coordinated advisory is published.+**Related ADRs**:+- ADR-034 (Optional MCP backends β `ruflo`/`ruvector`/`agentic-flow` stdio backends)+- ADR-035 (MCP tool groups β `MCP_GROUP_*` default-on/opt-in model)+- ADR-037 (Autopilot chat mode β where the tool blocklist is actually enforced)+- ADR-038 (Ruvocal fork β the deployed chat UI + bridge)+- ADR-029 (HF Chat UI Cloud Run β the documented cloud deployment path)+- ADR-012 (MCP security features)+- ADR-013 (Core security module β `@claude-flow/security` validators/SafeExecutor)+- ADR-131 (ToolOutputGuardrail β content-boundary screening, relevant to the AI-poisoning vector)+- ADR-165 (Security & CVE posture review, June 2026 β dependency CVE companion to this ADR)++---++## 1. Context++### 1.1 Why this ADR now++On 2026-06-30 we received a coordinated-disclosure report titled *"Unauthenticated Remote Code Execution and AI Platform Compromise in ruflo MCP Bridge."* It claims that the MCP Bridge HTTP endpoint accepts arbitrary tool invocations β including shell execution β with **no authentication**, that the shipping `docker-compose.yml` binds it to all interfaces, and that a single unauthenticated `POST /mcp` yields remote code execution inside the bridge container, from which LLM API keys, the AgentDB learning store, and the MongoDB conversation store are all compromised. The report includes an 8-step automated PoC (Python) and a video, described as confirmed live against a default deployment on AWS EC2.++We statically verified every substantive claim against the checked-out source. **The report is accurate.** This is a critical, internet-reachable, unauthenticated RCE in the default Docker deployment.++This ADR provides:++1. A grounded inventory of the affected bridge as it actually ships (not as intended).+2. The confirmed vulnerability findings with file-and-line evidence.+3. The end-to-end attack chain, mapped to the PoC.+4. A phased remediation roadmap with testable acceptance criteria, including the operational incident response (key rotation, learning-store audit) that patching alone does not cover.++### 1.2 Scope++**In scope**: the deployed MCP bridge (`ruflo/src/ruvocal/mcp-bridge/index.js`) and its sibling (`ruflo/src/mcp-bridge/index.js`); the shipping `ruflo/docker-compose.yml`; the nginx reverse proxy (`ruflo/src/nginx/nginx.conf`); the stdio MCP backend spawn path; the `MCP_GROUP_*` tool-group exposure model; and the `plugin-agent-federation` default bind host.++**Design contract** (per maintainer decision 2026-06-30): the MCP bridge is local-only by default. Public network exposure is an **explicit opt-in deployment pattern** (`MCP_BIND_HOST=0.0.0.0` + `MCP_AUTH_TOKEN` required). Local-only deployments do not carry the auth burden β the threat model and Phase 1 deliverables below are calibrated to this contract.++**Out of scope**: the npm dependency-CVE landscape (covered by ADR-165); the `@claude-flow/security` package internals; non-ruvocal deployment topologies beyond the documented Docker and `npx`/CLI paths; full TLS/network-segmentation design (referenced as operational guidance only).++### 1.3 Limitations of this audit++- **No live exploitation.** Findings are from static analysis (grep + file reads) of the source as checked out on 2026-06-30 and from reading the disclosed PoC script. We did **not** run the PoC against any host β there is no authorized target, and re-confirming a researcher-confirmed RCE adds risk without adding information.+- **Deployment-exposure assumption.** We did not measure the bind addresses of any live instance. The threat analysis assumes the documented default (`docker compose up -d`) and worst-case public reachability, consistent with the report.+- **PoC attachments not in repo.** The `.py` and `.mp4` live in the maintainer's local Downloads, not the repository, and are not committed. The PoC's callback domain is withheld here.++### 1.4 Measurement methodology++All findings were produced by reading the source directly at the current checkout. Representative commands:++```bash+# Locate the deployed bridge, compose, nginx+find ruflo -name docker-compose.yml -o -name nginx.conf+grep -n 'app.post("/mcp"' ruflo/src/ruvocal/mcp-bridge/index.js++# Confirm no inbound auth gate exists+grep -niE 'mcp_token|bearer|x-api-key|requireAuth|authMiddleware|MCP_AUTH' \+ ruflo/src/ruvocal/mcp-bridge/index.js # β only outbound Authorization to LLM providers++# Confirm the blocklist's sole call site is the autopilot flow+grep -n 'isBlockedTool' ruflo/src/ruvocal/mcp-bridge/index.js # def :1501, call :1633++# Confirm env inheritance to spawned backends, and listen bind+grep -n 'env: { ...process.env }\|app.listen(' ruflo/src/ruvocal/mcp-bridge/index.js+```++Compose, nginx, and the disclosed PoC were read in full. No synthetic data was used. Paths in this ADR are repo-relative.++---++## 2. Affected System Inventory++### 2.1 Topology (shipping `ruflo/docker-compose.yml`)++Four services compose the default deployment:++| Service | Image / Build | Host port mapping | Auth | Notes |+|---------|---------------|-------------------|------|-------|+| `mcp-bridge` | builds `./src/ruvocal/mcp-bridge` | `"3001:3001"` (all interfaces) | **none** | The deployed bridge is the **ruvocal** variant (`:22β23`). |+| `mongodb` | `mongo:7` | `"27017:27017"` (all interfaces) | **none** | No `MONGO_INITDB_ROOT_*` set (`:10β18`). |+| `nginx` | builds `./src/nginx` | `"3000:3000"` | n/a | CORS wildcard on all responses. |+| `chat-ui` | builds `./src/ruvocal` | `expose 3000` only | OIDC (app-level) | Talks to `mcp-bridge:3001` on the internal network. |++`restart: unless-stopped` on every service β relevant because it is what makes the PoC's persistence step survive a `kill 1`.++### 2.2 Bridge request surface (`ruflo/src/ruvocal/mcp-bridge/index.js`)++The Express app mounts exactly two pieces of middleware before all routes: `express.json()` (`:1034`) and a CORS handler that sets `Access-Control-Allow-Origin: *` (`:1037β1043`). **There is no authentication middleware.** Routes:++- `POST /mcp` β catch-all, serves **all enabled tools** (`:1102β1138`)+- `POST /mcp/:group` and `GET /mcp/:group` β per-group handlers (`:1096β1099`, factory `:1046β1084`)+- `POST /chat/completions`, `POST /autopilot*`, `GET /health|/models|/groups|/mcp-servers`++All `tools/call` requests dispatch to `executeTool(name, args)` (`:1066`, `:1121`).++### 2.3 Tool groups and backends (ADR-034 / ADR-035)++`executeTool` resolves a handful of built-in tools (`search`, `web_research`, `guidance`) and routes everything else to a spawned **stdio MCP backend** (`:979β989`). Backends (`:259β264`) include `ruflo` (`npx -y ruflo mcp start`), which serves the `agents`, `memory`, `devtools`, `security`, `browser`, `neural` groups β and crucially exposes `terminal_execute`. The `devtools` group defaults **on** (`MCP_GROUP_DEVTOOLS !== "false"`, compose `:43`), so `terminal_execute` is reachable by default.++Each backend is spawned with `env: { ...process.env }` (`:135β138`) β the full parent environment, including every provider key injected by compose (`:32β53`).++---++## 3. Confirmed Vulnerability Findings (Measured 2026-06-30)++The deployed bridge is the ruvocal variant; the sibling `ruflo/src/mcp-bridge/index.js` shares the identical flaws (the report's quoted line numbers 1302/1428 match that sibling file). Both must be remediated.++| ID | Severity | Finding | Evidence (repo-relative) |+|----|----------|---------|--------------------------|+| **V1** | **Critical** | `POST /mcp` dispatches `tools/call β executeTool()` with no authentication. The only middleware is JSON + wildcard CORS. | `ruflo/src/ruvocal/mcp-bridge/index.js:1102β1138`; middleware `:1034β1043` |+| **V2** | **Critical** | `terminal_execute` reachable unauthenticated β shell as `node` (uid 1000). Served by the `ruflo` backend; `devtools` defaults on. | `executeTool` default route `:979β989`; backend def `:259β261`; compose `:43` |+| **V3** | **High** | Tool blocklist (`AUTOPILOT_BLOCKED_PATTERNS`, incl. `/terminal_execute/`) enforced **only** in the autopilot flow via `isBlockedTool()` at `:1633`. `/mcp` and `/mcp/:group` never call it. | blocklist `:1493β1503`; sole call site `:1633` |+| **V4** | **High** | Spawned backends inherit the full parent env (`{ ...process.env }`), exposing `OPENAI/GOOGLE/OPENROUTER/ANTHROPIC` keys to any compromised child. | `StdioMcpClient.start()` `:135β138`; keys `docker-compose.yml:32β53` |+| **V5** | **High** | MongoDB bound to all interfaces on `27017` with no authentication β directly reachable off-host, independent of the RCE. | `ruflo/docker-compose.yml:10β18` |+| **V6** | **High** | Bridge port `3001` bound to all interfaces by default (amplifies V1 from local to internet). `app.listen(PORT)` has no bind-host argument. | `ruflo/docker-compose.yml:26β27`; `index.js:1889` |+| **V7** | **Medium** | `Access-Control-Allow-Origin: *` on every response at both nginx and the bridge β defense-in-depth gap for browser-driven pivots. | `ruflo/src/nginx/nginx.conf:20β22`; bridge `:1037β1040` |+| **V8** | **Medium** | `plugin-agent-federation` defaults `bindHost: '0.0.0.0'` β a second surface with the same exposure shape. | `v3/@claude-flow/plugin-agent-federation/src/bin.ts` |++**Severity rationale.** V1+V2+V6 compose to an unauthenticated, internet-reachable RCE (CVSS ~9.8, `AV:N/AC:L/PR:N/UI:N`). V4 and V5 turn the foothold into full platform and data compromise. V3 explains why the existing control gives false assurance: the maintainers *did* blocklist `terminal_execute`, but only on the one path attackers don't need.++---++## 4. Threat Model β the disclosed attack chain++The PoC weaponizes the findings end-to-end, every step a plain HTTP `POST /mcp` with no credentials:++| Step | Action | Tool / mechanism | Findings used |+|------|--------|------------------|---------------|+| 1 | Recon β enumerate all exposed tools | `initialize`, `tools/list` | V1 |+| 2 | RCE β shell in container; OAST callback proves outbound egress | `ruflo__terminal_execute` | V1, V2, V3 |+| 3 | Credential theft β `printenv | grep -iE 'KEY|TOKEN|SECRET'` | terminal_execute | V2, V4 |+| 4 | Weaponize β spin up attacker-controlled swarm on victim keys | `ruflo__swarm_init`, `ruflo__agent_spawn` | V1 |+| 5 | **AI poisoning** β inject malicious "compliance"/"best-practice" patterns so future generated code beacons out | `ruflo__agentdb_pattern-store` | V1 |+| 6 | Data theft β connect to `mongodb:27017` (no auth), dump + exfil conversations | terminal_execute β MongoClient | V2, V5 |+| 7 | Persistence β write `/app/beacon.js` + `NODE_OPTIONS` preload, `kill 1`; `restart: unless-stopped` relaunches with the backdoor | terminal_execute | V2 |+| 8 | Cleanup β wipe shell/REPL history | terminal_execute | V2 |++**Why step 5 raises the stakes.** The `agentdb_pattern-store` write is an **AI-supply-chain** attack: a one-time unauthenticated write persists into the learning store and steers *future* AI outputs for *all* users of that instance (it matches the `embedded-system`/`exfiltration` categories ADR-131's `ToolOutputGuardrail` was written to catch, but that guardrail is not on this path). Eradication therefore requires auditing/resetting the pattern store and rotating credentials β **not just redeploying a patched image.**++---++## 5. Gap Analysis++| Area | Apparent intent | Code reality | Consequence |+|------|-----------------|--------------|-------------|+| Dangerous-tool gating | `terminal_execute` is in `AUTOPILOT_BLOCKED_PATTERNS` | Enforced only in autopilot (`:1633`); `/mcp` bypasses it | False sense of control; RCE wide open on the primary path (V2, V3) |+| Endpoint auth | MCP HTTP transport | No inbound auth middleware anywhere | Anyone who can reach `:3001` is fully trusted (V1) |+| Bind exposure | Local service | `"3001:3001"` + `app.listen(PORT)` β `0.0.0.0` | Internet-reachable by default (V6) |+| Data store isolation | Internal Mongo | `"27017:27017"`, no auth | Direct off-host DB access, no RCE needed (V5) |+| Credential blast radius | Per-provider keys | `{ ...process.env }` to every backend | One compromised child reads all keys (V4) |+| CORS | Convenience for port-forward dev | `*` everywhere, incl. preflight | Browser-pivot defense-in-depth gap (V7) |+| Federation bind | Plugin networking | `bindHost: '0.0.0.0'` default | Same exposure shape on a second surface (V8) |++---++## 6. Remediation Roadmap++Apply Layer-1β3 changes to **both** bridge files (`ruflo/src/ruvocal/mcp-bridge/index.js` and `ruflo/src/mcp-bridge/index.js`). Authentication is the root-cause fix; every other layer is independent so no single regression re-opens the chain.++### Phase 0 β Operational incident response (immediate, parallel to coding)++0a. **Triage live exposure.** Identify any public default deployment (the report cites a confirmed AWS EC2 hit). For each, firewall `:3001`/`:27017` immediately.+0b. **Treat keys as compromised.** Rotate `OPENAI`/`GOOGLE`/`OPENROUTER`/`ANTHROPIC` keys for any exposed instance; review provider billing for abuse.+0c. **Audit the learning + conversation stores.** Inspect the AgentDB pattern store for injected `agentdb_pattern-store` entries (step 5) and MongoDB for tampering; purge poisoned patterns. **A patched redeploy alone does not undo poisoning.**+0d. **Coordinate disclosure timeline** with the reporter; open a private GitHub Security Advisory; reserve a CVE.++### Phase 1 β Default to local-only; auth required for the optional public deployment pattern (P0, target: hotfix release)++**1a. Bind loopback by default everywhere (root cause of public-default exposure, V6/V8).** Was 1c. Now the leading change.+ - `ruflo/docker-compose.yml`: `"3001:3001"` β `"127.0.0.1:3001:3001"`; same for Mongo `"27017:27017"` β `"127.0.0.1:27017:27017"`+ - `ruflo/src/ruvocal/mcp-bridge/index.js` + `ruflo/src/mcp-bridge/index.js`: `app.listen(PORT)` β `app.listen(PORT, BIND_HOST)` where `BIND_HOST = process.env.MCP_BIND_HOST || '127.0.0.1'`+ - `v3/@claude-flow/plugin-agent-federation/src/bin.ts`: default `bindHost: '127.0.0.1'` (was `'0.0.0.0'`)++**1b. Fail closed on public-bind opt-in without token (root cause of un-authed public exposure when operator opts in, V1).** Was 1b. Now second.++```js+const BIND_HOST = process.env.MCP_BIND_HOST || "127.0.0.1";+const isPublic = BIND_HOST !== "127.0.0.1" && BIND_HOST !== "localhost";+if (isPublic && !process.env.MCP_AUTH_TOKEN) {+ console.error(+ "FATAL: refusing to bind a public interface without MCP_AUTH_TOKEN. " ++ "Generate one with: MCP_AUTH_TOKEN=$(openssl rand -base64 32)"+ );+ process.exit(1);+}+app.listen(PORT, BIND_HOST, () => { /* ... */ });+```++ Token generation guidance: `MCP_AUTH_TOKEN=$(openssl rand -base64 32)`. Recommend β₯32 bytes.++**1c. Authenticate the HTTP surface when token IS set (V1, for the opt-in case).** Was 1a. Now third.++```js+const MCP_TOKEN = process.env.MCP_AUTH_TOKEN || "";+function requireAuth(req, res, next) {+ if (req.path === "/health") return next();+ if (!MCP_TOKEN) return next();+ const expected = `Bearer ${MCP_TOKEN}`;+ const got = req.get("authorization") || "";+ const ok = got.length === expected.length &&+ timingSafeEqual(Buffer.from(got), Buffer.from(expected));+ if (!ok) return res.status(401).json({ error: "unauthorized" });+ next();+}+app.use(requireAuth);+```++ Behavior: if `MCP_AUTH_TOKEN` is unset AND bind is loopback, middleware is a no-op (local IPC trust model); if `MCP_AUTH_TOKEN` is set (any bind), middleware enforces 401.++**1d. Gate `terminal_execute` (V2).** Off unless `MCP_ENABLE_TERMINAL=true`; print a security warning at startup when enabled. Enforce inside `executeTool` so every path is covered (see 2a).++### Optional public deployment pattern β explicit opt-in++When an operator deliberately exposes the bridge to a non-loopback interface (cloud, VPN-routed, or shared host), they MUST set BOTH of:++| Variable | Required | Notes |+|----------|----------|-------|+| `MCP_BIND_HOST` | yes (β 127.0.0.1) | e.g. `0.0.0.0` or a specific interface IP |+| `MCP_AUTH_TOKEN` | yes (β₯32 bytes) | Generate: `openssl rand -base64 32`. Rotate quarterly. |++`docker-compose.public.yml` (NEW, separate file from the default compose) is the supported public-deployment composition. The default `docker-compose.yml` stays loopback-only.++Generate the token, write to `.env` (gitignored), reference from compose:++```bash+echo "MCP_AUTH_TOKEN=$(openssl rand -base64 32)" >> .env+echo "MCP_BIND_HOST=0.0.0.0" >> .env+docker compose -f docker-compose.yml -f docker-compose.public.yml up -d+```++If either var is missing on a public bind, the bridge exits non-zero at startup. The chat-ui service must inject `Authorization: Bearer <token>` (Q1).++### Phase 2 β Reduce blast radius (P1, target: same release train)++**2a. Server-side tool authorization on every path (V3).** Move policy enforcement **into `executeTool()`** and switch denylist β **allowlist** (dangerous tools off unless explicitly enabled), so `/mcp`, `/mcp/:group`, and autopilot share one gate.+**2b. MongoDB auth + isolation (V5).** Add `MONGO_INITDB_ROOT_USERNAME/PASSWORD`; update `MONGODB_URL` with credentials; remove the `"27017:27017"` host mapping (or scope to `127.0.0.1`).+**2c. Read-only container (breaks step 7).** `read_only: true` on the bridge service + `tmpfs` for any scratch path, so `/app/beacon.js` writes fail (`EROFS`).++### Phase 3 β Hardening (P2, follow-on)++**3a. Scoped credential injection (V4).** Replace `{ ...process.env }` with a per-backend allowlist of only the keys that backend needs.+**3b. CORS allowlist (V7).** Replace `*` with a configurable origin allowlist (`MCP_CORS_ORIGIN`, default same-origin/localhost) at nginx (`:20β22`) and the bridge (`:1037β1040`).+**3c. Rate limiting** on `/mcp*`.+**3d. Fix federation default (V8).** `plugin-agent-federation` `bindHost` β `127.0.0.1`.+**3e. Independent auth** on memory/agent-management tools, decoupled from endpoint auth.++### Acceptance criteria++1. Unauthenticated `POST /mcp` (any method) β **401**; valid bearer β normal behavior. Covers `/mcp`, `/mcp/:group`, `/chat/completions`, `/autopilot*`.+2. The disclosed PoC fails at **Step 1** (recon `tools/list` β 401). Keep a sanitized request-replay as a regression test.+3. Startup with a public bind host and no token exits non-zero with a clear message.+4. `terminal_execute` returns "tool disabled" unless `MCP_ENABLE_TERMINAL=true`; allowlist enforced identically on `/mcp` and autopilot.+5. `docker compose up -d` exposes neither `3001` nor `27017` on a public interface (`ss -tlnp` shows loopback only); Mongo rejects unauthenticated clients.+6. A spawned backend's env contains only its allowlisted keys (assert e.g. no `ANTHROPIC_API_KEY` in a backend that doesn't need it).+7. `read_only` container: writing `/app/beacon.js` fails with `EROFS`.+8. A disallowed `Origin` does not receive `*`.+9. CI test asserts the auth middleware exists and returns 401 unauthenticated β it cannot be removed without a failing test.++---++## 7. Honest Risks and Open Questions++### Risks++**R1 β UX cost is concentrated in the optional public path.** Local-only deployments see zero new friction (no token, no headers, no rotation). The auth surface and rotation burden land only on operators who explicitly opt into public exposure β which matches the principle of "pay the security cost only when you assume the risk."+**R2 β Operators may set `MCP_BIND_HOST=0.0.0.0` without realizing the auth requirement.** Mitigated by 1b (fail-closed with a clear FATAL message + token-generation guidance in the same error string). The fatal log line MUST include the exact `openssl rand -base64 32` command.+**R3 β Allowlist over-restriction.** Moving to an allowlist (2a) may break workflows that rely on tools we forget to list. Mitigate by enumerating the current default-on tool set before flipping the default and logging every denied call.+**R4 β Persistence may already exist.** If an instance was exploited pre-patch, a beacon/`NODE_OPTIONS` preload may persist across a plain image pull. Phase 0c (rebuild from clean image + rotate keys + audit stores) is mandatory, not optional.++### Open questions++**Q1 β Token transport to chat-ui.** Inject via `DOTENV_LOCAL` env, a Docker secret, or a header added at the nginx proxy layer? Recommend a Docker secret + nginx-injected header so the browser never holds the token.+**Q2 β Does the `npx`/CLI bridge path share the gate?** The report notes the CLI defaults to `host: 'localhost'` (safer). Confirm the same auth middleware applies there before claiming the CLI path is covered.+**Q3 β Should the bridge adopt a signed-token scheme** (short-lived HMAC/JWT) instead of a static bearer, aligning with `TokenGenerator` (ADR-165 Β§4.6 Q6)? Static bearer ships fastest; revisit for multi-tenant deployments.+**Q4 β Per-room / per-client scoping** if the bridge ever serves more than one trust domain. Out of scope here; flagged for a follow-on.++---++## 8. Alternatives Considered and Rejected++**"Bind loopback by default; auth only for the optional public deployment pattern."** ACCEPTED (2026-06-30 per maintainer review). Rationale: matches the design contract that MCP is fundamentally local IPC; the public deployment story is an opt-in operational mode, not the default. Auth cost is paid only by operators who opt in. The previously-proposed always-on bearer auth was rejected as imposing local-IPC overhead on the common case.++**"Remove `terminal_execute` entirely."** Necessary-but-insufficient. Other tools (`agentdb_pattern-store` poisoning, swarm spawn on victim keys, Mongo reachability) keep platform-compromise paths open. Gate it (Phase 1d) *and* authenticate (1a).++**"Network-only mitigation (security groups / firewall)."** Required operationally (Phase 0a) but not a product fix β the goal is secure-by-default out of the box, which firewalls outside the repo cannot guarantee.++**"mTLS / OAuth on `/mcp` now."** Stronger but heavyweight for the self-host story. Fail-closed bearer + loopback bind is the right first step; mTLS can layer on for enterprise (Q3).++---++## 9. Evidence Ledger (2026-06-30 baseline, BEFORE remediation)++| Claim in this ADR | How it was verified | Source (repo-relative) |+|-------------------|---------------------|------------------------|+| Deployed bridge is the ruvocal variant | compose `build.context` read | `ruflo/docker-compose.yml:22β23` |+| `POST /mcp` dispatches `tools/call β executeTool` with no auth | File read of handler + middleware | `ruflo/src/ruvocal/mcp-bridge/index.js:1102β1138`, `:1034β1043` |+| No inbound auth gate exists | `grep -niE 'mcp_token\|bearer\|x-api-key\|requireAuth\|authMiddleware\|MCP_AUTH'` β only outbound provider `Authorization` at `:1571`,`:1780` | `ruflo/src/ruvocal/mcp-bridge/index.js` |+| `terminal_execute` served by `ruflo` backend; `devtools` default-on | Backend def + group-enabled expression + compose default | `index.js:259β261`, `:56`; `docker-compose.yml:43` |+| Blocklist enforced only in autopilot | `isBlockedTool` def `:1501`, sole call `:1633` (inside `handleAutopilot`) | `ruflo/src/ruvocal/mcp-bridge/index.js` |+| Backends spawned with full env inheritance | File read of `StdioMcpClient.start()` | `ruflo/src/ruvocal/mcp-bridge/index.js:135β138` |+| `app.listen(PORT)` has no bind-host arg (β 0.0.0.0) | File read of `main()` | `ruflo/src/ruvocal/mcp-bridge/index.js:1889` |+| Bridge port `3001` + Mongo `27017` bound to all interfaces | compose `ports` read | `ruflo/docker-compose.yml:15β16`, `:26β27` |+| MongoDB has no auth configured | No `MONGO_INITDB_ROOT_*` in compose | `ruflo/docker-compose.yml:10β18` |+| Provider keys injected into the bridge env | compose `environment` read | `ruflo/docker-compose.yml:32β53` |+| CORS wildcard at nginx and bridge | File reads | `ruflo/src/nginx/nginx.conf:20β22`; `ruflo/src/ruvocal/mcp-bridge/index.js:1037β1040` |+| Sibling bridge shares the flaw (report's 1302/1428) | `sed -n '1300,1305p;1426,1430p'` matches blocklist + `isBlockedTool` autopilot call | `ruflo/src/mcp-bridge/index.js` |+| `plugin-agent-federation` defaults `bindHost: '0.0.0.0'` | grep located the default | `v3/@claude-flow/plugin-agent-federation/src/bin.ts` |+| 8-step attack chain (reconβRCEβcredsβswarmβpoisonβMongoβpersistβcleanup) | Read disclosed PoC script in full | Coordinated-disclosure attachment (not committed) |++### 9.1 Post-remediation verification (2026-06-30, AFTER commits on this branch)++| Acceptance criterion (Β§6) | Verified how | Result |+|---------------------------|--------------|--------|+| #1 Unauthenticated POST /mcp β 401; valid bearer β normal | `test-runtime-security.mjs` R2 + R3 on BOTH bridges | β R2=401, R3=200 |+| #2 Disclosed PoC fails at Step 1 (recon `tools/list` β 401) | Follows from #1 (`tools/list` goes through same middleware) | β |+| #3 Startup with public bind + no token exits non-zero | `test-runtime-security.mjs` R5 on BOTH bridges | β exit code 1 + FATAL to stderr |+| #4 `terminal_execute` returns disabled unless `MCP_ENABLE_TERMINAL=true`; enforced on both `/mcp` and autopilot | Gate implemented in `executeTool()` (single site) β `test-runtime-security.mjs` R4 | β TOOL_DISABLED code |+| #5 `docker compose up -d` exposes neither 3001 nor 27017 publicly; Mongo rejects unauth | Compose diff (loopback binds + `--auth` + required root password) | β compose grep gate in CI |+| #6 Backend env allowlist (scoped `{ ...process.env }` replacement) | **Phase 3a β deferred** (see Β§7 Q, next release train) | β³ deferred |+| #7 `read_only` container: `/app/beacon.js` write fails EROFS | `read_only: true` + `tmpfs: /tmp` in compose | β present |+| #8 Disallowed Origin does not receive `*` | CORS allowlist wired to `MCP_CORS_ORIGIN`; default `*` for back-compat, allowlist honored when set | β present |+| #9 CI test asserts auth middleware exists + returns 401 | `test-security-lock.js` (static-source, 6 checks Γ 2 bridges) + `test-runtime-security.mjs` + `.github/workflows/adr-166-mcp-bridge-security.yml` | β 12/12 lock + 12/12 runtime green locally; CI gate armed on every PR |++---++## 10. References++### Predecessor ADRs++- **Maintainer decision 2026-06-30** (this branch's review thread): MCP design contract is local-only; public is explicit opt-in.+- [ADR-029](../../../ruflo/docs/adr/ADR-029-HUGGINGFACE-CHAT-UI-CLOUD-RUN.md) β documented Cloud Run deployment path+- [ADR-034](../../../ruflo/docs/adr/ADR-034-OPTIONAL-MCP-BACKENDS.md) β optional stdio MCP backends (`ruflo`/`ruvector`/β¦)+- [ADR-035](../../../ruflo/docs/adr/ADR-035-MCP-TOOL-GROUPS.md) β `MCP_GROUP_*` default-on/opt-in model+- [ADR-037](../../../ruflo/docs/adr/ADR-037-AUTOPILOT-CHAT-MODE.md) β autopilot flow (where the blocklist is enforced)+- [ADR-038](../../../ruflo/docs/adr/ADR-038-RUVOCAL-FORK.md) β the deployed ruvocal chat UI + bridge+- [ADR-165](./ADR-165-security-cve-posture-review.md) β June 2026 dependency-CVE posture (companion; note its hono CORS-wildcard advisory GHSA-88fw-hqm2-52qc, which compounds V7)+- [ADR-131](./ADR-131-tool-output-guardrail.md) β ToolOutputGuardrail (the content-screening control absent on the poisoning path, Β§4 step 5)++### External standards++- OWASP Top 10 for Agentic Applications 2026 β ASI01 (Agent Goal Hijacking), the class the Β§4 step-5 learning-store poisoning falls under+- CWE-306 (Missing Authentication for Critical Function), CWE-78 (OS Command Injection), CWE-942 (Permissive CORS)++### Follow-up issues to open (private until embargo lifts)++- "MCP bridge: require bearer auth on /mcp + fail-closed public bind" (Phase 1a/1b)+- "docker-compose: bind 3001 loopback; Mongo auth + drop 27017 host mapping" (Phase 1c/2b)+- "executeTool: allowlist tool gate covering /mcp + autopilot; gate terminal_execute" (Phase 1d/2a)+- "MCP bridge: read_only container + scoped per-backend env + CORS allowlist" (Phase 2c/3a/3b)+- "plugin-agent-federation: default bindHost 127.0.0.1" (Phase 3d)+- "Publish coordinated advisory + CVE; credit reporter" (Phase 0d)