Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

fix(ci): replace e2e CLI-spawn tests with pure unit tests of the auth gate

Claude4cc5ca928455
diff --git a/v3/@claude-flow/cli/__tests__/mcp-http-nonloopback-auth-gate.test.ts b/v3/@claude-flow/cli/__tests__/mcp-http-nonloopback-auth-gate.test.ts
index 938d91d3c8..9bd354ef4b 100644
--- a/v3/@claude-flow/cli/__tests__/mcp-http-nonloopback-auth-gate.test.ts
+++ b/v3/@claude-flow/cli/__tests__/mcp-http-nonloopback-auth-gate.test.ts
@@ -15,135 +15,86 @@
// RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP=1. Default/loopback behavior (the
// common case, exercised by mcp-http-foreground-2984 and
// mcp-http-protocol-tools-2990) is unchanged.
-
-import { afterEach, describe, expect, it } from 'vitest';
-import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { isUnauthenticatedHttpAllowed } from '../src/mcp-server.js';
-
-const HERE = path.dirname(fileURLToPath(import.meta.url));
-const CLI = path.resolve(HERE, '..', 'bin', 'cli.js');
-// `bin/cli.js` is committed source and always present; what it actually
-// needs at runtime is the compiled `dist/src/index.js` it imports. This
-// repo's CI "Test Suite" job does not build @claude-flow/cli's own dist
-// (only @claude-flow/security and @claude-flow/cli-core get a targeted
-// build step there β€” see .github/workflows/ci.yml), so checking bin/cli.js
-// alone (the pattern mcp-http-foreground-2984/mcp-http-protocol-tools-2990
-// use) would report "built" when it isn't and fail every e2e spawn with
-// ERR_MODULE_NOT_FOUND. Check the real dependency instead and skip cleanly.
-const CLI_DIST_ENTRY = path.resolve(HERE, '..', 'dist', 'src', 'index.js');
-const CLI_BUILT = fs.existsSync(CLI) && fs.existsSync(CLI_DIST_ENTRY);
-const TEST_TMP = path.resolve(HERE, '..', '..', '..', '..', '.tmp-dream-2026-10-01', 'test-runtime');
-
-let child: ChildProcessWithoutNullStreams | undefined;
-
-afterEach(() => {
- if (child && child.exitCode === null && child.signalCode === null) {
- child.kill('SIGKILL');
- }
- child = undefined;
-});
-
-function waitForEither(
- proc: ChildProcessWithoutNullStreams,
- match: string,
- timeoutMs: number,
-): Promise<{ matched: boolean; exitCode: number | null; stdout: string; stderr: string }> {
- return new Promise((resolve) => {
- let stdout = '';
- let stderr = '';
- let settled = false;
- const finish = (matched: boolean, exitCode: number | null) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- resolve({ matched, exitCode, stdout, stderr });
- };
- const timer = setTimeout(() => finish(false, null), timeoutMs);
- proc.stdout.on('data', (chunk: Buffer) => {
- stdout += chunk.toString();
- if (stdout.includes(match)) finish(true, null);
- });
- proc.stderr.on('data', (chunk: Buffer) => {
- stderr += chunk.toString();
- if (stderr.includes(match)) finish(true, null);
- });
- proc.once('exit', (code) => finish(stdout.includes(match) || stderr.includes(match), code));
+//
+// These are pure, synchronous unit tests against the three exported
+// functions that make up the gate's full decision contract. An earlier
+// version of this file instead spawned the built CLI end-to-end
+// (node bin/cli.js mcp start ...), matching the pattern
+// mcp-http-foreground-2984.test.ts/mcp-http-protocol-tools-2990.test.ts use
+// β€” but this repo's CI "Test Suite" job never builds @claude-flow/cli's own
+// dist/ (only @claude-flow/security and @claude-flow/cli-core get a
+// targeted build step there, per .github/workflows/ci.yml), which is why
+// those two existing files are both already listed in
+// scripts/ci-test-baseline.txt as known-failing in CI. Rather than add a
+// third entry to that baseline (its own header: "Never add entries to make
+// a regression green"), this file tests the real exported decision logic
+// directly β€” no process spawn, no port bind, no build dependency β€” which
+// fully pins down the behavior these manual end-to-end checks verified
+// during development (see the PR/issue evidence: baseline-fails/
+// candidate-passes via git-stash, a live spawned server demonstrably
+// serving /health unauthenticated pre-fix and refusing to start post-fix).
+
+import { describe, expect, it } from 'vitest';
+import {
+ isLoopbackHost,
+ isUnauthenticatedHttpAllowed,
+ shouldRefuseUnauthenticatedHttp,
+} from '../src/mcp-server.js';
+
+describe('isLoopbackHost', () => {
+ it('is true for exactly the three recognized loopback spellings', () => {
+ expect(isLoopbackHost('localhost')).toBe(true);
+ expect(isLoopbackHost('127.0.0.1')).toBe(true);
+ expect(isLoopbackHost('::1')).toBe(true);
});
-}
-function spawnHttpCli(port: number, host: string, extraEnv: Record<string, string> = {}) {
- fs.mkdirSync(TEST_TMP, { recursive: true });
- return spawn('node', [CLI, 'mcp', 'start', '-t', 'http', '--host', host, '--port', String(port)], {
- env: {
- ...process.env,
- RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: undefined,
- RUFLO_DAEMON_AUTOSTART: '0',
- TEMP: TEST_TMP,
- TMP: TEST_TMP,
- ...extraEnv,
- },
- stdio: ['ignore', 'pipe', 'pipe'],
+ it('is false (fails closed) for anything not spelled exactly one of those three', () => {
+ expect(isLoopbackHost('0.0.0.0')).toBe(false);
+ expect(isLoopbackHost('::')).toBe(false);
+ expect(isLoopbackHost('192.168.1.5')).toBe(false);
+ // Case variants and bracketed forms are NOT normalized β€” conservative
+ // (fail-closed) direction: an operator relying on one of these would
+ // need the explicit opt-out, not a silent bypass of the gate.
+ expect(isLoopbackHost('LOCALHOST')).toBe(false);
+ expect(isLoopbackHost('[::1]')).toBe(false);
+ expect(isLoopbackHost('0:0:0:0:0:0:0:1')).toBe(false);
});
-}
+});
-describe('isUnauthenticatedHttpAllowed (unit)', () => {
+describe('isUnauthenticatedHttpAllowed', () => {
it('is false when unset', () => {
expect(isUnauthenticatedHttpAllowed({})).toBe(false);
});
+
it('is false for arbitrary truthy-looking strings', () => {
expect(isUnauthenticatedHttpAllowed({ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: 'yes' })).toBe(false);
expect(isUnauthenticatedHttpAllowed({ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '0' })).toBe(false);
expect(isUnauthenticatedHttpAllowed({ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: 'false' })).toBe(false);
});
+
it('is true only for the documented opt-out values', () => {
expect(isUnauthenticatedHttpAllowed({ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '1' })).toBe(true);
expect(isUnauthenticatedHttpAllowed({ RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: 'true' })).toBe(true);
});
});
-describe.skipIf(!CLI_BUILT)('MCP HTTP non-loopback authorization gate (end-to-end)', () => {
- it('refuses to start on a non-loopback host with no authorizer and no opt-out', async () => {
- const port = 38000 + Math.floor(Math.random() * 4000);
- child = spawnHttpCli(port, '0.0.0.0');
- const result = await waitForEither(child, 'RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP', 15_000);
-
- expect(result.matched).toBe(true);
- expect(result.stderr).toMatch(/Refusing to start the MCP HTTP server on non-loopback host/);
-
- // The port must never actually open β€” not just that an error was logged.
- await expect(
- fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(500) })
- ).rejects.toBeTruthy();
- }, 20_000);
-
- it('starts normally on a non-loopback host when the explicit opt-out is set', async () => {
- const port = 38000 + Math.floor(Math.random() * 4000);
- child = spawnHttpCli(port, '0.0.0.0', { RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '1' });
- const result = await waitForEither(child, 'MCP Server started', 20_000);
-
- expect(result.matched).toBe(true);
- expect(result.exitCode).toBeNull();
-
- const health = await fetch(`http://127.0.0.1:${port}/health`);
- expect(health.status).toBe(200);
- }, 25_000);
-
- it('still starts normally on a loopback host with no opt-out needed', async () => {
- // Uses 127.0.0.1 rather than the 'localhost' default to avoid this
- // sandbox's unrelated, pre-existing lack of IPv6 support (the
- // 'localhost' path additionally binds ::1 β€” see #2990's identical
- // EAFNOSUPPORT failure on this same host, independent of this candidate).
- const port = 38000 + Math.floor(Math.random() * 4000);
- child = spawnHttpCli(port, '127.0.0.1');
- const result = await waitForEither(child, 'MCP Server started', 20_000);
+describe('shouldRefuseUnauthenticatedHttp (the full startHttpServer gate)', () => {
+ it('refuses a non-loopback host with no opt-out β€” the vulnerability this candidate closes', () => {
+ expect(shouldRefuseUnauthenticatedHttp('0.0.0.0', {})).toBe(true);
+ });
- expect(result.matched).toBe(true);
- expect(result.exitCode).toBeNull();
+ it('allows a non-loopback host when the explicit opt-out is set', () => {
+ expect(
+ shouldRefuseUnauthenticatedHttp('0.0.0.0', { RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '1' }),
+ ).toBe(false);
+ });
- const health = await fetch(`http://127.0.0.1:${port}/health`);
- expect(health.status).toBe(200);
- }, 25_000);
+ it('allows every loopback host regardless of the opt-out β€” default behavior is unchanged', () => {
+ for (const host of ['localhost', '127.0.0.1', '::1']) {
+ expect(shouldRefuseUnauthenticatedHttp(host, {})).toBe(false);
+ expect(
+ shouldRefuseUnauthenticatedHttp(host, { RUFLO_MCP_ALLOW_UNAUTHENTICATED_HTTP: '1' }),
+ ).toBe(false);
+ }
+ });
});
diff --git a/v3/@claude-flow/cli/src/mcp-server.ts b/v3/@claude-flow/cli/src/mcp-server.ts
index a7c79e06f7..984bf5cc31 100644
--- a/v3/@claude-flow/cli/src/mcp-server.ts
+++ b/v3/@claude-flow/cli/src/mcp-server.ts
@@ -177,9 +177,16 @@ function processStartToken(pid: number): string | undefined {
/**
* Hosts treated as same-machine-only for MCP HTTP tool-call authorization
* purposes (see startHttpServer's non-loopback authorization gate below).
+ * Deliberately exact-string matching only (no DNS resolution) so anything
+ * not spelled exactly one of these three fails closed rather than open.
*/
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1']);
+/** Exported for tests β€” see LOOPBACK_HOSTS. */
+export function isLoopbackHost(host: string): boolean {
+ return LOOPBACK_HOSTS.has(host);
+}
+
/**
* Explicit, documented opt-out of the non-loopback authorization gate in
* startHttpServer(). Exported for tests.
@@ -189,6 +196,20 @@ export function isUnauthenticatedHttpAllowed(env: NodeJS.ProcessEnv = process.en
return v === '1' || v === 'true';
}
+/**
+ * The full startHttpServer() authorization gate, as a pure function:
+ * true means "refuse to start" (see the thrown error for why). Extracted
+ * so the exact decision contract (not just its two inputs individually) is
+ * directly unit-testable without spawning a process or binding a port.
+ * Exported for tests.
+ */
+export function shouldRefuseUnauthenticatedHttp(
+ host: string,
+ env: NodeJS.ProcessEnv = process.env,
+): boolean {
+ return !isLoopbackHost(host) && !isUnauthenticatedHttpAllowed(env);
+}
+
/**
* Default configuration
*/
@@ -965,9 +986,7 @@ export class MCPServerManager extends EventEmitter {
// Use one MCP server with two HTTP transports for the localhost default.
// Both loopback sockets therefore share sessions, tools, and notifications.
const dualLoopback = this.options.host === 'localhost';
- const isLoopbackHost = dualLoopback || LOOPBACK_HOSTS.has(this.options.host);
- const allowUnauthenticatedHttp = isUnauthenticatedHttpAllowed(process.env);
- if (!isLoopbackHost && !allowUnauthenticatedHttp) {
+ if (shouldRefuseUnauthenticatedHttp(this.options.host)) {
// No ToolAuthorizer is wired below: @claude-flow/mcp's tool-call
// authorization is fully opt-in (requireToolAuthorization/toolAuthorizer),
// so without this check every registered tool (memory_*, hooks_*,