diff --git a/.github/actions/diff/publish-status.sh b/.github/actions/diff/publish-status.sh index a6ae4891..b1bb4f25 100644 --- a/.github/actions/diff/publish-status.sh +++ b/.github/actions/diff/publish-status.sh @@ -51,13 +51,13 @@ git fetch origin rugsnare/status --depth=1 2>/dev/null || true if git show origin/rugsnare/status:status.json >/dev/null 2>&1; then EXISTING_RAW=$(git show origin/rugsnare/status:status.json) EXISTING=$(printf '%s' "$EXISTING_RAW" | node -e " - const d = JSON.parse(require('fs').readFileSync('/dev/stdin', 'utf8')); + const d = JSON.parse(require('fs').readFileSync(0, 'utf8')); // compare everything except timestamp/runId (they change every run) delete d.timestamp; delete d.runId; console.log(JSON.stringify(d)); " 2>/dev/null || echo "{}") NEW=$(printf '%s' "$STATUS_JSON" | node -e " - const d = JSON.parse(require('fs').readFileSync('/dev/stdin', 'utf8')); + const d = JSON.parse(require('fs').readFileSync(0, 'utf8')); delete d.timestamp; delete d.runId; console.log(JSON.stringify(d)); ") @@ -67,13 +67,25 @@ if git show origin/rugsnare/status:status.json >/dev/null 2>&1; then fi # ISO-8601 UTC timestamps compare correctly as strings EXISTING_TS=$(printf '%s' "$EXISTING_RAW" | node -e " - const d = JSON.parse(require('fs').readFileSync('/dev/stdin', 'utf8')); + const d = JSON.parse(require('fs').readFileSync(0, 'utf8')); console.log(typeof d.timestamp === 'string' ? d.timestamp : ''); " 2>/dev/null || echo "") if [ -n "$EXISTING_TS" ] && [ "$EXISTING_TS" \> "$TIMESTAMP" ]; then echo "::notice::Status branch already has a newer run ($EXISTING_TS > $TIMESTAMP) - skipping stale re-run" exit 0 fi + # T-039 F-4: runId is the authoritative recency signal - a re-run of an OLD + # run finishes later (newer timestamp) but must never overwrite the status + # of a newer run. Existing runId >= ours -> skip. + EXISTING_RUN=$(printf '%s' "$EXISTING_RAW" | node -e " + const d = JSON.parse(require('fs').readFileSync(0, 'utf8')); + console.log(Number.isFinite(Number(d.runId)) ? String(Number(d.runId)) : ''); + " 2>/dev/null || echo "") + OUR_RUN=$(node -e "console.log(Number.isFinite(Number(process.env.GITHUB_RUN_ID)) ? String(Number(process.env.GITHUB_RUN_ID)) : '')" 2>/dev/null || echo "") + if [ -n "$EXISTING_RUN" ] && [ -n "$OUR_RUN" ] && [ "$EXISTING_RUN" -ge "$OUR_RUN" ]; then + echo "::notice::Status branch already has run $EXISTING_RUN >= our $OUR_RUN - skipping stale re-run" + exit 0 + fi fi # Write to a temp branch: single-file orphan commit, force-pushed diff --git a/product/package.json b/product/package.json index f8c47b97..1a162e3e 100644 --- a/product/package.json +++ b/product/package.json @@ -21,8 +21,8 @@ "supply-chain", "ci" ], "scripts": { - "test": "node --test test/security-canary.test.js test/security-runtime.test.js test/runtime-mode.test.js test/runtime-integrity.test.js test/core.test.js test/proxy.test.js test/proxy-http.test.js test/rpc-edge.test.js test/rpc-http.test.js test/auth.test.js test/results.test.js test/keccak.test.js test/onchain.test.js test/shadow.test.js test/advisory.test.js test/prompts.test.js test/policies.test.js test/canary.test.js test/canary-replay.test.js test/canary-http.test.js test/receipts.test.js test/mcp-server.test.js test/chameleon.test.js test/v041.test.js test/wrap.test.js test/v05.test.js test/adhoc-url.test.js test/doctor.test.js test/events.test.js test/config.test.js test/scan-e2e.test.js test/approve.test.js test/sarif.test.js test/audit.test.js test/vault.test.js test/budgets.test.js test/pins-sig.test.js test/review28.test.js test/undeclared.test.js test/skills-pin.test.js test/version.test.js test/history.test.js test/history-web.test.js test/gradation.test.js test/skills-advisory.test.js test/pinv11.test.js", - "prepack": "node --test test/security-canary.test.js test/security-runtime.test.js test/runtime-mode.test.js test/runtime-integrity.test.js test/core.test.js test/proxy.test.js test/proxy-http.test.js test/rpc-edge.test.js test/rpc-http.test.js test/auth.test.js test/results.test.js test/keccak.test.js test/onchain.test.js test/shadow.test.js test/advisory.test.js test/prompts.test.js test/policies.test.js test/canary.test.js test/canary-replay.test.js test/canary-http.test.js test/receipts.test.js test/mcp-server.test.js test/chameleon.test.js test/v041.test.js test/wrap.test.js test/v05.test.js test/adhoc-url.test.js test/doctor.test.js test/events.test.js test/config.test.js test/scan-e2e.test.js test/approve.test.js test/sarif.test.js test/audit.test.js test/vault.test.js test/budgets.test.js test/pins-sig.test.js test/review28.test.js test/undeclared.test.js test/skills-pin.test.js test/version.test.js test/history.test.js test/history-web.test.js test/gradation.test.js test/skills-advisory.test.js test/pinv11.test.js" + "test": "node --test test/security-canary.test.js test/security-runtime.test.js test/runtime-mode.test.js test/runtime-integrity.test.js test/core.test.js test/proxy.test.js test/proxy-http.test.js test/rpc-edge.test.js test/rpc-http.test.js test/auth.test.js test/results.test.js test/keccak.test.js test/onchain.test.js test/shadow.test.js test/advisory.test.js test/prompts.test.js test/policies.test.js test/canary.test.js test/canary-replay.test.js test/canary-http.test.js test/receipts.test.js test/mcp-server.test.js test/chameleon.test.js test/v041.test.js test/wrap.test.js test/v05.test.js test/adhoc-url.test.js test/doctor.test.js test/events.test.js test/config.test.js test/scan-e2e.test.js test/approve.test.js test/sarif.test.js test/audit.test.js test/vault.test.js test/budgets.test.js test/pins-sig.test.js test/review28.test.js test/undeclared.test.js test/publish-status.test.js test/skills-pin.test.js test/version.test.js test/history.test.js test/history-web.test.js test/gradation.test.js test/skills-advisory.test.js test/pinv11.test.js", + "prepack": "node --test test/security-canary.test.js test/security-runtime.test.js test/runtime-mode.test.js test/runtime-integrity.test.js test/core.test.js test/proxy.test.js test/proxy-http.test.js test/rpc-edge.test.js test/rpc-http.test.js test/auth.test.js test/results.test.js test/keccak.test.js test/onchain.test.js test/shadow.test.js test/advisory.test.js test/prompts.test.js test/policies.test.js test/canary.test.js test/canary-replay.test.js test/canary-http.test.js test/receipts.test.js test/mcp-server.test.js test/chameleon.test.js test/v041.test.js test/wrap.test.js test/v05.test.js test/adhoc-url.test.js test/doctor.test.js test/events.test.js test/config.test.js test/scan-e2e.test.js test/approve.test.js test/sarif.test.js test/audit.test.js test/vault.test.js test/budgets.test.js test/pins-sig.test.js test/review28.test.js test/undeclared.test.js test/publish-status.test.js test/skills-pin.test.js test/version.test.js test/history.test.js test/history-web.test.js test/gradation.test.js test/skills-advisory.test.js test/pinv11.test.js" } } diff --git a/product/src/pins.js b/product/src/pins.js index 8a133080..e7c19919 100644 --- a/product/src/pins.js +++ b/product/src/pins.js @@ -260,7 +260,8 @@ export function detectShadows(pins) { export function pinTool(serverPin, tool, hash, { approved = true, reason = 'scan' } = {}) { const now = new Date().toISOString(); - const existing = serverPin.tools[tool.name]; + // own-property only (T-039 F-2): proto names must not surface phantom entries + const existing = Object.hasOwn(serverPin.tools, tool.name) ? serverPin.tools[tool.name] : undefined; // PIN-SPEC v1.1 byte-stability: a ROUTINE SCAN that sees the SAME contract // of an ALREADY-APPROVED tool must not touch the entry - pinnedAt churn // would change pins.json bytes on every re-scan and break third-party @@ -303,7 +304,9 @@ export function pinTool(serverPin, tool, hash, { approved = true, reason = 'scan pinnedAt: now, approved, }; - return serverPin.tools[tool.name]; + // own-property lookups only (T-039 F-2): 'constructor'/'toString' names + // must never resolve through Object.prototype as phantom pins + return Object.hasOwn(serverPin.tools, tool.name) ? serverPin.tools[tool.name] : undefined; } /** @@ -778,7 +781,9 @@ export function detectPaywallIntroduction(oldDescription, newDescription) { export function compareTools(serverPin, liveTools, toolHashFn) { const result = []; for (const tool of liveTools) { - const pin = serverPin.tools[tool.name]; + // own-property only (T-039 F-2): 'constructor' et al. must compare as + // absent (NEW), never as a phantom inherited pin + const pin = Object.hasOwn(serverPin.tools, tool.name) ? serverPin.tools[tool.name] : undefined; const hash = toolHashFn(tool); if (!pin) result.push({ tool: tool.name, status: 'NEW', hash, description: tool.description ?? '' }); else if (pin.hash !== hash) { diff --git a/product/src/proxy-http.js b/product/src/proxy-http.js index 81f0fdfe..aaeb1814 100644 --- a/product/src/proxy-http.js +++ b/product/src/proxy-http.js @@ -160,6 +160,20 @@ export function createHttpProxy({ name, targetUrl, authConfig = {}, mode = 'obse * Create the local HTTP server that the MCP client connects to. */ const server = http.createServer((clientReq, clientRes) => { + // CSRF guard (T-039 F-3): a browser page must not be able to drive the + // local proxy. Same-origin loopback only; non-browser clients send no + // Origin header at all and are unaffected. + const origin = clientReq.headers.origin; + if (origin) { + const localPort = clientReq.socket.localPort; + const allowed = new Set([`http://localhost:${localPort}`, `http://127.0.0.1:${localPort}`]); + if (!allowed.has(origin)) { + logEvent({ kind: 'cross-origin-reject', server: name, origin: String(origin).slice(0, 100) }, cwd); + clientRes.writeHead(403, { 'content-type': 'application/json' }); + clientRes.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32000, message: '[RUGSNARE] Cross-origin requests are not permitted.' } })); + return; + } + } if (clientReq.method === 'GET') { // Health check / SSE endpoint - just 200 clientRes.writeHead(200, { 'content-type': 'text/event-stream' }); @@ -173,16 +187,28 @@ export function createHttpProxy({ name, targetUrl, authConfig = {}, mode = 'obse try { const msg = JSON.parse(body); + // JSON-RPC batch (T-039 F-1): the per-message gates never see inside + // an array - reject outright in enforce, forward with a log in observe. + if (Array.isArray(msg)) { + if (mode === 'enforce') { + logEvent({ kind: 'batch-reject', server: name, entries: msg.length }, cwd); + clientRes.writeHead(200, { 'content-type': 'application/json' }); + clientRes.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: '[RUGSNARE] JSON-RPC batch requests are not supported in enforce mode.' } })); + return; + } + logEvent({ kind: 'batch-forward', server: name, entries: msg.length }, cwd); + } + // Call policies + loop detector - same enforcement as the stdio proxy. // A blocked call is answered directly to the client; the remote never sees it. if (msg.method === 'tools/call' && msg.params) { - // Fail-closed for unknown-in-session names (REVIEW T-031 / T-034): - // before the first tools/list there is no allowed-cache, so in - // enforce a call to a name not in the pin is unknown - block it. + // Fail-closed for unknown-in-session names (REVIEW T-031 / T-034); + // T-039 F-2: own-property lookups only - proto names must not + // resolve through Object.prototype. if (mode === 'enforce' && ( quarantinedTools.has(msg.params.name) - || serverPin.tools[msg.params.name]?.approved === false - || (!hasSeenToolsList && serverPin.tools[msg.params.name] === undefined) + || (Object.hasOwn(serverPin.tools, msg.params.name) && serverPin.tools[msg.params.name].approved === false) + || (!hasSeenToolsList && !Object.hasOwn(serverPin.tools, msg.params.name)) )) { logEvent({ kind: 'quarantine-call-block', server: name, tool: msg.params.name, ...(hasSeenToolsList ? {} : { note: 'call before first tools/list; name not in pin (fail-closed)' }) }, cwd); clientRes.writeHead(200, { 'content-type': 'application/json' }); @@ -206,7 +232,8 @@ export function createHttpProxy({ name, targetUrl, authConfig = {}, mode = 'obse } } - const toolPin = serverPin.tools[msg.params.name]; + // own-property only (T-039 F-2): proto names must not resolve + const toolPin = Object.hasOwn(serverPin.tools, msg.params.name) ? serverPin.tools[msg.params.name] : undefined; const policyResult = evaluateCall( { toolName: msg.params.name, arguments: msg.params.arguments, description: toolPin?.description ?? '' }, activePolicies diff --git a/product/src/proxy.js b/product/src/proxy.js index 53e90381..ad2df3e3 100644 --- a/product/src/proxy.js +++ b/product/src/proxy.js @@ -94,16 +94,30 @@ export function createProxy({ name, server, streams, mode = 'observe', config, c return; } try { + // JSON-RPC batch (array of messages) is an enforcement blind spot + // (T-039 F-1): the per-message gates below never see inside it, so an + // unapproved tool could ride a batch. Reject batches outright in + // enforce; forward (with a log line) in observe. + if (Array.isArray(msg)) { + if (mode === 'enforce') { + writeOut(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: '[RUGSNARE] JSON-RPC batch requests are not supported in enforce mode.' } })); + logEvent({ kind: 'batch-reject', server: name, entries: msg.length }, cwd); + return; + } + logEvent({ kind: 'batch-forward', server: name, entries: msg.length }, cwd); + } if (msg.method === 'tools/call' && msg.params) { // Fail-closed for unknown-in-session names (REVIEW T-031 / T-034): // before the first tools/list there is no allowed-cache, so in enforce // a call to a name that is not even in the pin is unknown - block it. // Pinned (approved) tools still pass; after the first list the normal // quarantine/undeclared logic takes over. + // T-039 F-2: own-property lookups only - 'constructor'/'toString'/ + // '__proto__' must not resolve through Object.prototype. if (mode === 'enforce' && ( quarantinedTools.has(msg.params.name) - || serverPin.tools[msg.params.name]?.approved === false - || (!hasSeenToolsList && serverPin.tools[msg.params.name] === undefined) + || (Object.hasOwn(serverPin.tools, msg.params.name) && serverPin.tools[msg.params.name].approved === false) + || (!hasSeenToolsList && !Object.hasOwn(serverPin.tools, msg.params.name)) )) { writeOut(JSON.stringify({ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message: '[RUGSNARE] Tool is quarantined or has not been approved.' } })); logEvent({ kind: 'quarantine-call-block', server: name, tool: msg.params.name, ...(hasSeenToolsList ? {} : { note: 'call before first tools/list; name not in pin (fail-closed)' }) }, cwd); @@ -164,7 +178,9 @@ export function createProxy({ name, server, streams, mode = 'observe', config, c } // Policy evaluation: check arguments against rules - const toolPin = serverPin.tools[msg.params.name]; + // (own-property lookup only - a proto name must not resolve to + // Object.prototype members as a phantom "pin") + const toolPin = Object.hasOwn(serverPin.tools, msg.params.name) ? serverPin.tools[msg.params.name] : undefined; const policyResult = evaluateCall( { toolName: msg.params.name, arguments: msg.params.arguments, description: toolPin?.description ?? '' }, activePolicies diff --git a/product/src/skills-pin.js b/product/src/skills-pin.js index d1ac633d..c63bb6f8 100644 --- a/product/src/skills-pin.js +++ b/product/src/skills-pin.js @@ -201,7 +201,9 @@ export function pinAllSkills(pins, cwd = process.cwd(), home = os.homedir(), { p let pinnedCount = 0; for (const skill of skills) { const key = `${skill.app}/${skill.scope}/${skill.relative}`; - const existing = pins.skills[key]; + // own-property only (T-039 F-2 discipline): never resolve through + // Object.prototype even for adversarial key shapes + const existing = Object.hasOwn(pins.skills, key) ? pins.skills[key] : undefined; const entry = pinSkillFile(skill, cwd); // ยง7 byte-stability: a scan that sees the SAME content must not touch // the entry - pinnedAt churn changes pins.json bytes on every re-scan diff --git a/product/test/publish-status.test.js b/product/test/publish-status.test.js new file mode 100644 index 00000000..bf4555f7 --- /dev/null +++ b/product/test/publish-status.test.js @@ -0,0 +1,78 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { execFileSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +// T-039 F-4: the runId guard in publish-status.sh. A re-run of an OLD CI run +// finishes with a NEWER wall-clock timestamp than the status already on the +// branch - the timestamp guard alone would let it overwrite a newer run's +// verdict. runId is the authoritative recency signal: existing >= ours -> skip. +// +// The simulation builds a local bare "origin" with a rugsnare/status branch +// (runId 200, verdict drift), then runs the real script as runId 100 - the +// skip path exits 0 BEFORE any push, so no network is touched. + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const SCRIPT = path.join(HERE, '..', '..', '.github', 'actions', 'diff', 'publish-status.sh'); + +function git(cwd, args) { + return execFileSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', '-c', 'commit.gpgsign=false', ...args], { cwd, encoding: 'utf8', windowsHide: true }); +} + +function runScript(args, env, cwd) { + try { + const out = execFileSync('bash', [SCRIPT, ...args], { cwd, encoding: 'utf8', timeout: 60000, env: { ...process.env, ...env }, windowsHide: true }); + return { code: 0, out }; + } catch (e) { + return { code: e.status ?? 1, out: (e.stdout || '') + (e.stderr || '') }; + } +} + +test('T-039 F-4: stale re-run (older runId) never overwrites a newer status', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rugsnare-pubstatus-')); + try { + const bare = path.join(root, 'remote.git'); + const work = path.join(root, 'work'); + git(root, ['init', '--bare', bare]); + git(root, ['clone', bare, work]); + + // seed a commit on the default branch + fs.writeFileSync(path.join(work, 'seed.txt'), 'seed'); + git(work, ['add', '.']); + git(work, ['commit', '-m', 'seed']); + const mainBranch = git(work, ['rev-parse', '--abbrev-ref', 'HEAD']).trim(); + + // create rugsnare/status holding runId 200 (drift) with an OLD timestamp + git(work, ['checkout', '--orphan', 'rugsnare/status']); + git(work, ['rm', '-rf', '--quiet', '.']); + fs.writeFileSync(path.join(work, 'status.json'), JSON.stringify({ + verdict: 'drift', findings: 3, config: '.mcp.json', timestamp: '2026-11-01T00:00:00Z', + runId: '200', repo: 'x/y', branch: mainBranch, summary: 'DRIFT DETECTED: 3 finding(s)', + })); + git(work, ['add', 'status.json']); + git(work, ['commit', '-m', 'status seed']); + git(work, ['push', 'origin', 'rugsnare/status']); + git(work, ['checkout', mainBranch]); + + // act: the script runs as re-run of runId 100 (older), fresh timestamp, + // different verdict (clean) so the unchanged-dedup cannot fire first + const older = runScript(['clean', '0', '.mcp.json'], { GITHUB_RUN_ID: '100', GITHUB_REPOSITORY: 'x/y', GITHUB_REF_NAME: mainBranch }, work); + assert.equal(older.code, 0, `script must exit 0 on the skip path\n${older.out}`); + assert.match(older.out, /run 200 >= our 100/, 'runId guard fires for the stale re-run'); + + // the status branch is untouched + const still = JSON.parse(git(work, ['show', 'origin/rugsnare/status:status.json'])); + assert.equal(still.runId, '200', 'status branch still holds run 200'); + assert.equal(still.verdict, 'drift', 'drift verdict NOT overwritten by the stale clean re-run'); + + // same-run re-execution is also a skip (>=, not >) + const same = runScript(['clean', '0', '.mcp.json'], { GITHUB_RUN_ID: '200', GITHUB_REPOSITORY: 'x/y', GITHUB_REF_NAME: mainBranch }, work); + assert.equal(same.code, 0); + assert.match(same.out, /run 200 >= our 200/, 'same runId skipped too'); + } finally { + try { fs.rmSync(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 }); } catch { /* Windows */ } + } +}); diff --git a/product/test/undeclared.test.js b/product/test/undeclared.test.js index 23f49b12..05ce407c 100644 --- a/product/test/undeclared.test.js +++ b/product/test/undeclared.test.js @@ -129,6 +129,55 @@ test('stdio enforce: NEW tool call BEFORE tools/list is blocked (fail-closed); p } }); +// ---- T-039 security fixes ---------------------------------------------------- + +const PINNED_STORE = (tools) => JSON.stringify({ version: 1, servers: { svc: { tools } } }); +function pinFixture(dir, tools) { + fs.mkdirSync(path.join(dir, '.rugsnare'), { recursive: true }); + fs.writeFileSync(path.join(dir, '.rugsnare', 'pins.json'), PINNED_STORE(tools)); +} + +test('T-039 F-1 stdio: JSON-RPC batch rejected in enforce, nothing forwarded', () => { + const { dir, cleanup } = tmpCwd(); + try { + pinFixture(dir, { approved_tool: { hash: 'h', approved: true } }); + const h = stdioHarness({ cwd: dir, mode: 'enforce' }); + // batch: one innocent call + one call to an unpinned name, before any tools/list + h.streams.clientIn.write(JSON.stringify([ + { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'approved_tool', arguments: {} } }, + { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'shadow_tool', arguments: {} } }, + ]) + '\n'); + const out = h.out.join('\n'); + assert.match(out, /JSON-RPC batch requests are not supported in enforce mode/, 'batch rejected with -32600 message'); + assert.equal(h.serverSide.join('').includes('shadow_tool'), false, 'batch NOT forwarded to the server'); + assert.equal(h.serverSide.join('').includes('approved_tool'), false, 'whole batch dropped, not just the bad entry'); + assert.ok(readEvents(dir).some((e) => e.kind === 'batch-reject'), 'batch-reject event recorded'); + } finally { + cleanup(); + } +}); + +test('T-039 F-2 stdio: prototype names (constructor/toString) are blocked pre-list, pinned passes', () => { + const { dir, cleanup } = tmpCwd(); + try { + pinFixture(dir, { approved_tool: { hash: 'h', approved: true } }); + const h = stdioHarness({ cwd: dir, mode: 'enforce' }); + // no tools/list: pre-list fail-closed must treat proto names as unknown + h.call(1, 'constructor'); + h.call(2, 'toString'); + h.call(3, '__proto__'); + assert.equal(h.serverSide.join('').includes('constructor'), false, 'constructor NOT forwarded'); + assert.equal(h.serverSide.join('').includes('toString'), false, 'toString NOT forwarded'); + assert.equal(h.serverSide.join('').includes('__proto__'), false, '__proto__ NOT forwarded'); + const blocked = h.out.filter((s) => s.includes('"error"')).length; + assert.equal(blocked, 3, 'all three proto names blocked'); + h.call(4, 'approved_tool'); + assert.ok(h.serverSide.join('').includes('approved_tool'), 'pinned tool still passes'); + } finally { + cleanup(); + } +}); + // ---- HTTP proxy --------------------------------------------------------------- function mockRemote() { @@ -279,3 +328,89 @@ test('HTTP enforce: call BEFORE tools/list to an unpinned name is blocked (fail- await new Promise((r) => remote.server.close(r)); } }); + +// ---- T-039 security fixes, HTTP half ---- + +test('T-039 F-1/F-2 HTTP: batch rejected in enforce; proto name blocked pre-list', async () => { + const { dir, cleanup } = tmpCwd(); + const remote = await mockRemote(); + try { + pinFixture(dir, { discover: { hash: 'h', approved: true }, raw: { hash: 'h', approved: true } }); + const proxy = createHttpProxy({ name: 'svc', targetUrl: `http://127.0.0.1:${remote.port}`, mode: 'enforce', cwd: dir }); + const port = await new Promise((resolve) => proxy.server.listen(0, '127.0.0.1', () => resolve(proxy.server.address().port))); + const origWrite = process.stderr.write.bind(process.stderr); + process.stderr.write = () => true; + try { + await rpc(port, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 't', version: '1' } }); + // no tools/list yet + + // batch carrying an unpinned call: whole array must be rejected + const batch = await new Promise((resolve, reject) => { + const req = http.request({ host: '127.0.0.1', port, method: 'POST', headers: { 'content-type': 'application/json' } }, (res) => { + let body = ''; + res.on('data', (c) => { body += c; }); + res.on('end', () => resolve(JSON.parse(body))); + }); + req.on('error', reject); + req.end(JSON.stringify([ + { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'discover', arguments: {} } }, + { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'shadow_tool', arguments: {} } }, + ])); + }); + assert.ok(batch.error, 'batch rejected'); + assert.match(batch.error.message, /batch requests are not supported in enforce mode/); + assert.ok(!remote.state.callsReceived.includes('discover'), 'nothing from the batch reached the remote'); + assert.ok(readEvents(dir).some((e) => e.kind === 'batch-reject'), 'batch-reject event'); + + // proto name pre-list: blocked, not resolved through Object.prototype + const proto = await rpc(port, 'tools/call', { name: 'constructor', arguments: {} }); + assert.ok(proto.error, 'proto name blocked'); + assert.match(proto.error.message, /quarantined or has not been approved/); + assert.ok(!remote.state.callsReceived.includes('constructor'), 'proto name never forwarded'); + } finally { + process.stderr.write = origWrite; + await new Promise((r) => proxy.server.close(r)); + } + } finally { + cleanup(); + await new Promise((r) => remote.server.close(r)); + } +}); + +test('T-039 F-3 HTTP: foreign Origin gets 403, loopback Origin passes', async () => { + const { dir, cleanup } = tmpCwd(); + const remote = await mockRemote(); + try { + const proxy = createHttpProxy({ name: 'svc', targetUrl: `http://127.0.0.1:${remote.port}`, mode: 'observe', cwd: dir }); + const port = await new Promise((resolve) => proxy.server.listen(0, '127.0.0.1', () => resolve(proxy.server.address().port))); + const post = (headers) => new Promise((resolve) => { + const req = http.request({ host: '127.0.0.1', port, method: 'POST', headers: { 'content-type': 'application/json', ...headers } }, (res) => { + let body = ''; + res.on('data', (c) => { body += c; }); + res.on('end', () => resolve({ status: res.statusCode, body })); + }); + req.on('error', () => resolve({ status: 0, body: '' })); + req.end(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' })); + }); + try { + const evil = await post({ origin: 'https://evil.example' }); + assert.equal(evil.status, 403, 'foreign Origin rejected'); + assert.match(evil.body, /Cross-origin requests are not permitted/); + assert.ok(!remote.state.declaredTools.length || true, 'sanity'); + assert.ok(readEvents(dir).some((e) => e.kind === 'cross-origin-reject'), 'cross-origin-reject event'); + + // no Origin header (regular MCP client): unaffected + const noOrigin = await post({}); + assert.equal(noOrigin.status, 200, 'no-Origin request passes'); + + // exact loopback origin: allowed + const loopback = await post({ origin: `http://localhost:${port}` }); + assert.equal(loopback.status, 200, 'loopback Origin passes'); + } finally { + await new Promise((r) => proxy.server.close(r)); + } + } finally { + cleanup(); + await new Promise((r) => remote.server.close(r)); + } +});