From e89f4c3ece4f672a413ec369e1a1c06418ac73e7 Mon Sep 17 00:00:00 2001 From: Lily Shen <115414357+lilyshen0722@users.noreply.github.com> Date: Thu, 1 Oct 2026 10:13:37 -0700 Subject: [PATCH] fix(cli): keep Claude broker tokens out of env Route Commonly token placeholders in Claude HTTP MCP headers through a headersHelper. The helper reads the per-spawn 0600 credential file on each invocation; Claude can refresh it on its documented 401/403 retry without exposing the token in Claude or MCP child environments. Add coverage for HTTP and streamable HTTP headers, mixed stdio/HTTP declarations, token-free Claude env/config, and a rotated file across one 401 retry. Update the environment test that asserted the old token-in-env behavior. Bump the CLI package version to 0.1.84 for the source-version guard. Written by sprint-impl, a Commonly agent. Pod thread: https://commonly.me/v2/pods/6a692a1be833c668acdb84cf#message-76155. --- ...dapters.claude.credential-channel.test.mjs | 117 ++++++++++++++---- .../adapters.claude.environment.test.mjs | 8 +- cli/package-lock.json | 4 +- cli/package.json | 2 +- cli/src/lib/adapters/claude.js | 101 +++++++++++++-- 5 files changed, 188 insertions(+), 44 deletions(-) diff --git a/cli/__tests__/adapters.claude.credential-channel.test.mjs b/cli/__tests__/adapters.claude.credential-channel.test.mjs index bbb289fd1a..a4305a61f5 100644 --- a/cli/__tests__/adapters.claude.credential-channel.test.mjs +++ b/cli/__tests__/adapters.claude.credential-channel.test.mjs @@ -18,6 +18,7 @@ */ import { jest } from '@jest/globals'; +import { execFileSync } from 'node:child_process'; import { EventEmitter } from 'events'; import os from 'os'; import path from 'path'; @@ -69,7 +70,7 @@ const fakeChild = ({ stdout = '', code = 0 } = {}) => { return proc; }; -const captureImpl = () => { +const captureImpl = ({ onSpawn } = {}) => { const calls = []; const impl = (cmd, args, opts) => { const i = args.indexOf('--mcp-config'); @@ -77,8 +78,10 @@ const captureImpl = () => { const config = configPath ? JSON.parse(fs.readFileSync(configPath, 'utf8')) : null; const declared = config?.mcpServers?.commonly?.env || {}; const fileVar = declared.COMMONLY_TOKEN_FILE; - const resolved = fileVar && opts.env?.['COMMONLY_TOKEN_FILE']; - calls.push({ + const hasHeadersHelper = Object.values(config?.mcpServers || {}) + .some((entry) => typeof entry.headersHelper === 'string'); + const resolved = (fileVar || hasHeadersHelper) && opts.env?.['COMMONLY_TOKEN_FILE']; + const call = { cmd, args, env: opts.env, @@ -89,7 +92,9 @@ const captureImpl = () => { tokenInEnv: opts.env?.['COMMONLY_AGENT_TOKEN'], fileText: resolved && fs.existsSync(resolved) ? fs.readFileSync(resolved, 'utf8') : null, fileMode: resolved && fs.existsSync(resolved) ? fs.statSync(resolved).mode & 0o777 : null, - }); + }; + calls.push(call); + if (onSpawn) onSpawn(call); return fakeChild({ stdout: 'ok', code: 0 }); }; return { calls, impl }; @@ -210,10 +215,10 @@ describe('claude: the seat credential arrives as a path, never as a value (TASK- }); }); -describe('claude: the carve-out for a reference the rewrite cannot move (TASK-082/TASK-083)', () => { - const spawnWithImpl = async (mcp) => { +describe('claude: HTTP token headers use the per-spawn credential file (TASK-228)', () => { + const spawnWithImpl = async (mcp, onSpawn) => { const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'kai-claude-carve-')); - const { calls, impl } = captureImpl(); + const { calls, impl } = captureImpl({ onSpawn }); let warned = []; const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); try { @@ -235,27 +240,84 @@ describe('claude: the carve-out for a reference the rewrite cannot move (TASK-08 return { call: calls[0], warned }; }; - test('a header reference keeps the value in the environment, and the seat is told', async () => { - // Measured shape, and the reason this carve-out exists at all: an HTTP entry - // hands claude a header string to substitute. There is no file channel for a - // bearer header, so refusing would take the broker away from every seat that - // has one. The value is supplied, and the warning names the trade. + const runHeadersHelper = (call, serverName = 'github-grant') => { + const command = call.config.mcpServers[serverName].headersHelper; + return JSON.parse(execFileSync('/bin/sh', ['-c', command], { + encoding: 'utf8', + env: call.env, + })); + }; + + test('a broker header uses a helper and keeps the token out of Claude env and MCP config', async () => { + let headers; const { call, warned } = await spawnWithImpl([{ + name: 'github-grant', + transport: 'http', + url: 'https://api.commonly.me/api/mcp/grants/grant-live', + headers: { + Authorization: 'Bearer ${COMMONLY_AGENT_TOKEN}', + 'X-Commonly-Instance': 'prod', + }, + }], (spawnCall) => { headers = runHeadersHelper(spawnCall); }); + const entry = call.config.mcpServers['github-grant']; + expect(call.tokenInEnv).toBeUndefined(); + expect(Object.keys(call.env)).not.toContain('COMMONLY_AGENT_TOKEN'); + expect(call.env.COMMONLY_TOKEN_FILE).toBe(call.resolvedFile); + expect(entry.headers).toEqual({ 'X-Commonly-Instance': 'prod' }); + expect(entry.headersHelper).toContain(path.dirname(call.configPath)); + expect(JSON.stringify(call.config)).not.toContain('${COMMONLY_AGENT_TOKEN}'); + expect(JSON.stringify(call.config)).not.toContain(TOKEN); + expect(warned.join('\n')).not.toMatch(/COMMONLY_AGENT_TOKEN/); + expect(headers).toEqual({ Authorization: `Bearer ${TOKEN}` }); + }); + + test('a 401 retry reruns the helper and reads a rotated token during one spawn', async () => { + const rotated = 'cm_agent_'.padEnd(73, 'R'); + const headers = []; + const statuses = []; + await spawnWithImpl([{ name: 'github-grant', transport: 'http', url: 'https://api.commonly.me/api/mcp/grants/grant-live', headers: { Authorization: 'Bearer ${COMMONLY_AGENT_TOKEN}' }, - }]); - expect(call.tokenInEnv).toBe(TOKEN); - expect(call.config.mcpServers['github-grant'].headers.Authorization).toBe('Bearer ${COMMONLY_AGENT_TOKEN}'); - // The value kept is THIS spawn's credential, not whatever the launcher - // exported: those are different strings, so the carve-out cannot pass by - // inheriting the bootstrap variable. - expect(call.tokenInEnv).not.toBe(LAUNCHER_TOKEN); - expect(warned.join('\n')).toMatch(/Put the credential on the entry's env to get the file channel/); + }], (call) => { + const fakeBroker = (requestHeaders) => { + if (requestHeaders.Authorization === `Bearer ${rotated}`) return 200; + if (requestHeaders.Authorization === `Bearer ${TOKEN}`) return 401; + return 500; + }; + headers.push(runHeadersHelper(call)); + // Model Claude's documented auth retry: the connection's existing + // headers get one stale-token response, then the helper runs again. + statuses.push(fakeBroker(headers[0])); + fs.writeFileSync(call.resolvedFile, rotated, { mode: 0o600 }); + fs.chmodSync(call.resolvedFile, 0o600); + headers.push(runHeadersHelper(call)); + statuses.push(fakeBroker(headers[1])); + }); + expect(headers).toEqual([ + { Authorization: `Bearer ${TOKEN}` }, + { Authorization: `Bearer ${rotated}` }, + ]); + expect(statuses).toEqual([401, 200]); }); - test('an embedded reference in an env value also keeps the value', async () => { + test('streamable HTTP headers use the helper while unrelated HTTP headers stay static', async () => { + let headers; + const { call } = await spawnWithImpl([{ + name: 'github-grant', + transport: 'streamable-http', + url: 'https://api.commonly.me/api/mcp/grants/grant-live', + headers: { + Authorization: 'Bearer ${COMMONLY_AGENT_TOKEN}', + 'X-Commonly-Instance': 'prod', + }, + }], (spawnCall) => { headers = runHeadersHelper(spawnCall); }); + expect(call.config.mcpServers['github-grant'].headers).toEqual({ 'X-Commonly-Instance': 'prod' }); + expect(headers).toEqual({ Authorization: `Bearer ${TOKEN}` }); + }); + + test('an embedded reference in an env value remains on the literal expansion path', async () => { const { call } = await spawnWithImpl([{ name: 'commonly', transport: 'stdio', @@ -266,7 +328,8 @@ describe('claude: the carve-out for a reference the rewrite cannot move (TASK-08 expect(call.declared.NOTE).toBe('prefix-${COMMONLY_AGENT_TOKEN}'); }); - test('both channels at once: the env entry moves to the file, the header still needs the value', async () => { + test('stdio and HTTP credential declarations both use the file, never the Claude env', async () => { + let headers; const { call } = await spawnWithImpl([ { name: 'commonly', @@ -280,11 +343,13 @@ describe('claude: the carve-out for a reference the rewrite cannot move (TASK-08 url: 'https://api.commonly.me/api/mcp/grants/grant-live', headers: { Authorization: 'Bearer ${COMMONLY_AGENT_TOKEN}' }, }, - ]); - // Our own server stops depending on the value even in the spawn that still - // needs it for the header — the two decisions are per declaration. + ], (spawnCall) => { headers = runHeadersHelper(spawnCall); }); + // The stdio child reads the file through its env declaration; the HTTP + // connection's helper reads that same per-spawn file when Claude invokes it. expect(call.declared.COMMONLY_TOKEN_FILE).toBe('${COMMONLY_TOKEN_FILE}'); expect(call.declared.COMMONLY_AGENT_TOKEN).toBeUndefined(); - expect(call.tokenInEnv).toBe(TOKEN); + expect(call.tokenInEnv).toBeUndefined(); + expect(call.env.COMMONLY_TOKEN_FILE).toBe(call.resolvedFile); + expect(headers).toEqual({ Authorization: `Bearer ${TOKEN}` }); }); }); diff --git a/cli/__tests__/adapters.claude.environment.test.mjs b/cli/__tests__/adapters.claude.environment.test.mjs index a1791c23f0..bea3ade788 100644 --- a/cli/__tests__/adapters.claude.environment.test.mjs +++ b/cli/__tests__/adapters.claude.environment.test.mjs @@ -715,7 +715,7 @@ describe('claude adapter — ctx.environment', () => { expect(calls[0].opts.env.COMMONLY_API_URL).toBe('https://api-dev.commonly.me'); }); - test('projected broker headers stay placeholder-based while the token is supplied to Claude', async () => { + test('projected broker headers use a helper while the token stays out of Claude env', async () => { const { impl, calls } = makeSpawnImpl(); await claude.spawn('hi', { sessionId: null, @@ -734,9 +734,11 @@ describe('claude adapter — ctx.environment', () => { const server = calls[0].config.mcpServers['github-grant']; expect(server.url).toBe('https://api.commonly.me/api/mcp/grants/grant-live'); - expect(server.headers.Authorization).toBe('Bearer ${COMMONLY_AGENT_TOKEN}'); + expect(server.headers).toBeUndefined(); + expect(typeof server.headersHelper).toBe('string'); expect(JSON.stringify(calls[0].config)).not.toContain('cm_agent_test'); - expect(calls[0].opts.env.COMMONLY_AGENT_TOKEN).toBe('cm_agent_test'); + expect(calls[0].opts.env.COMMONLY_AGENT_TOKEN).toBeUndefined(); + expect(calls[0].opts.env.COMMONLY_TOKEN_FILE).toMatch(/\/token$/); }); test('${COMMONLY_INSTANCE_URL} alias is supplied to native expansion', async () => { diff --git a/cli/package-lock.json b/cli/package-lock.json index a4b63e541b..bb7468ebcf 100644 --- a/cli/package-lock.json +++ b/cli/package-lock.json @@ -1,12 +1,12 @@ { "name": "@commonlyai/cli", - "version": "0.1.83", + "version": "0.1.84", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@commonlyai/cli", - "version": "0.1.83", + "version": "0.1.84", "license": "Apache-2.0", "dependencies": { "commander": "^12.0.0" diff --git a/cli/package.json b/cli/package.json index 677bfea6c8..64478d0777 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@commonlyai/cli", - "version": "0.1.83", + "version": "0.1.84", "license": "Apache-2.0", "description": "The Commonly CLI — connect agents, manage pods, iterate fast", "type": "module", diff --git a/cli/src/lib/adapters/claude.js b/cli/src/lib/adapters/claude.js index e4639f268e..2e32a36de8 100644 --- a/cli/src/lib/adapters/claude.js +++ b/cli/src/lib/adapters/claude.js @@ -91,6 +91,22 @@ const DEFAULT_TIMEOUT_MS = (() => { })(); const buildPrompt = buildMemoryPreamble; +const RUNTIME_CREDENTIAL_PLACEHOLDER = '${COMMONLY_AGENT_TOKEN}'; + +const QUOTE_SHELL_ARGUMENT = (value) => `'${String(value).replaceAll("'", "'\\''")}'`; + +const HEADER_TOKEN_HELPER_SOURCE = `import { readFileSync } from 'node:fs'; + +const credentialFile = process.env.${CREDENTIAL_FILE_VAR}; +if (!credentialFile) throw new Error('missing ${CREDENTIAL_FILE_VAR}'); +const token = readFileSync(credentialFile, 'utf8').trim(); +if (!token) throw new Error('empty ${CREDENTIAL_FILE_VAR}'); +const templates = JSON.parse(readFileSync(process.argv[2], 'utf8')); +const headers = Object.fromEntries( + Object.entries(templates).map(([name, parts]) => [name, parts.join(token)]), +); +process.stdout.write(JSON.stringify(headers) + '\\n'); +`; const PUBLIC_DENIED_TOOLS = [ 'WebSearch', @@ -290,9 +306,9 @@ const runClaude = ({ cmd, args, cwd, env, timeoutMs, credentials = [], spawnImpl // Keep Commonly placeholders in the MCP JSON and expose their values only in // Claude's per-spawn environment. Claude Code natively expands ${VAR} in MCP -// command/args/env/url/headers fields. Substituting here used to materialize the raw -// cm_agent_* bearer token in a transient JSON file, which made the token -// readable to any co-confined child allowed to read that config directory. +// command/args/env/url/header fields. Token-bearing HTTP headers are routed +// through headersHelper below, because a literal expansion would put the +// credential in Claude's environment and every MCP child's environment. // // Recognised placeholders: // ${COMMONLY_TOKEN_FILE} — the PATH of this spawn's credential file @@ -324,20 +340,67 @@ const buildMcpExpansionEnv = (mcpConfig, ctx) => { // added only when the value is non-empty AND the declaration still references // it — and `serialized` is the config AFTER the credential rewrite, which is // what moves the default declaration off this value and onto the file. A - // reference the rewrite cannot move (args, url, headers, or a string that - // merely contains the placeholder) keeps the value for that spawn, because - // claude substitutes those literally and there is no file channel for them. - // That is the measured carve-out, and createMcpConfig warns when it applies - // so the seat still carrying the value is named rather than assumed fixed. + // reference that cannot use the file channel (args, url, unsupported or + // non-HTTP headers, or a string that merely contains the placeholder) keeps + // the value for that spawn. createMcpConfig warns when this carve-out applies. COMMONLY_AGENT_TOKEN: ctx.runtimeToken || '', }; const output = {}; for (const [key, value] of Object.entries(values)) { - if (value && serialized.includes(`\${${key}}`)) output[key] = value; + const referenced = serialized.includes(`\${${key}}`) + || (key === CREDENTIAL_FILE_VAR && ctx.headersHelperUsesCredentialFile === true); + if (value && referenced) output[key] = value; } return output; }; +const isHttpTransport = (server) => { + const transport = String(server?.transport || server?.type || '').trim().toLowerCase(); + return transport === 'http' || transport === 'streamable-http'; +}; + +const getTokenHeaderTemplates = (server) => { + if (!isHttpTransport(server) || !server.headers || typeof server.headers !== 'object') return null; + const templates = Object.fromEntries( + Object.entries(server.headers) + .filter(([, value]) => typeof value === 'string' && value.includes(RUNTIME_CREDENTIAL_PLACEHOLDER)) + .map(([name, value]) => [name, value.split(RUNTIME_CREDENTIAL_PLACEHOLDER)]), + ); + return Object.keys(templates).length > 0 ? templates : null; +}; + +const writePrivateFile = async (path, contents) => { + await writeFile(path, contents, { encoding: 'utf8', mode: 0o600 }); + await chmod(path, 0o600); +}; + +// Claude's headersHelper is invoked when an HTTP connection is established and +// again after an authentication retry. Keep the token out of its config and +// environment: the helper reads the current per-spawn file on every invocation. +const createTokenHeaderHelpers = async (mcpServers, dir) => { + const servers = mcpServers + .map((server, index) => ({ server, index, templates: getTokenHeaderTemplates(server) })) + .filter((item) => item.templates); + if (servers.length === 0) return new Map(); + + const scriptPath = join(dir, 'headers-helper.mjs'); + await writePrivateFile(scriptPath, HEADER_TOKEN_HELPER_SOURCE); + const helpers = new Map(); + for (const { server, index, templates } of servers) { + const templatesPath = join(dir, `headers-${index}.json`); + await writePrivateFile(templatesPath, JSON.stringify(templates)); + helpers.set(server.name, { + command: [ + QUOTE_SHELL_ARGUMENT(process.execPath), + QUOTE_SHELL_ARGUMENT(scriptPath), + QUOTE_SHELL_ARGUMENT(templatesPath), + ].join(' '), + headerNames: Object.keys(templates), + }); + } + return helpers; +}; + const buildMcpConfig = (mcpServers, ctx = {}) => { // Shape: `{ mcpServers: { : { ... } } }` — the standard MCP client // config, which claude's `--mcp-config` reads directly. @@ -368,7 +431,13 @@ const buildMcpConfig = (mcpServers, ctx = {}) => { label: 'claude', }).env; } - if (server.headers) entry.headers = { ...server.headers }; + const headerHelper = ctx.dynamicHeaderHelpers?.get(server.name); + if (server.headers) { + const headers = { ...server.headers }; + for (const headerName of headerHelper?.headerNames || []) delete headers[headerName]; + if (Object.keys(headers).length > 0 || !headerHelper) entry.headers = headers; + } + if (headerHelper) entry.headersHelper = headerHelper.command; mcpServersMap[server.name] = entry; } return { mcpServers: mcpServersMap }; @@ -390,7 +459,14 @@ const createMcpConfig = async (mcpServers, ctx = {}) => { // config — no second lifecycle to get wrong — and so it is inside the one // non-workspace path the Seatbelt profile admits. credential = writeCredentialFile(ctx.runtimeToken, { agentName: ctx.agentName || 'agent', root: dir }); - const config = buildMcpConfig(mcpServers, { ...ctx, credentialFile: credential?.path || null }); + const dynamicHeaderHelpers = credential?.path + ? await createTokenHeaderHelpers(mcpServers, dir) + : new Map(); + const config = buildMcpConfig(mcpServers, { + ...ctx, + credentialFile: credential?.path || null, + dynamicHeaderHelpers, + }); await writeFile( file, JSON.stringify(config, null, 2), @@ -402,12 +478,13 @@ const createMcpConfig = async (mcpServers, ctx = {}) => { const expansionEnv = buildMcpExpansionEnv(config, { ...ctx, credentialFile: credential?.path || null, + headersHelperUsesCredentialFile: dynamicHeaderHelpers.size > 0, }); if (expansionEnv[CREDENTIAL_KEY]) { // eslint-disable-next-line no-console console.warn( `[claude] this declaration references ${CREDENTIAL_KEY} in a field claude ` - + 'substitutes literally (args, url, headers, or a larger string), so the ' + + 'substitutes literally (args, url, unsupported headers, or a larger string), so the ' + "value stays in claude's environment for this spawn and every MCP child " + `inherits it. Put the credential on the entry's env to get the file channel.`, );