diff --git a/scripts/hooks/governance-capture.js b/scripts/hooks/governance-capture.js index 5f75baeaf..781dbab09 100644 --- a/scripts/hooks/governance-capture.js +++ b/scripts/hooks/governance-capture.js @@ -20,6 +20,7 @@ const crypto = require('crypto'); const { isElevatedPowerShellCommand } = require('../lib/powershell-destructive-command'); +const { getToolResultText } = require('./hook-input'); const MAX_STDIN = 1024 * 1024; let destructiveCommandClassifier = null; @@ -165,7 +166,7 @@ function emitGovernanceEvent(event) { /** * Analyze a hook input payload and return governance events to capture. * - * @param {Object} input - Parsed hook input (tool_name, tool_input, tool_output) + * @param {Object} input - Parsed hook input (tool_name, tool_input, tool_response) * @param {Object} [context] - Additional context (sessionId, hookPhase) * @returns {Array} Array of governance event objects */ @@ -177,7 +178,7 @@ function analyzeForGovernanceEvents(input, context = {}) { ? 'PowerShell' : normalizedToolName === 'bash' ? 'Bash' : rawToolName; const toolInput = input.tool_input || {}; - const toolOutput = typeof input.tool_output === 'string' ? input.tool_output : ''; + const toolOutput = getToolResultText(input); const sessionId = context.sessionId || null; const hookPhase = context.hookPhase || 'unknown'; diff --git a/scripts/hooks/hook-input.js b/scripts/hooks/hook-input.js index 66fcfe19e..262938fc6 100644 --- a/scripts/hooks/hook-input.js +++ b/scripts/hooks/hook-input.js @@ -146,9 +146,32 @@ function readStdinRaw(stream = process.stdin, options = {}) { }); } +/** + * The result a PostToolUse payload carries for its tool. Claude Code sends it as + * `tool_response`, which for Bash is an object with `stdout` and `stderr`; the + * Cursor adapter and older callers send `tool_output`, a string or `{ output }`. + */ +function getToolResult(input) { + return input?.tool_response ?? input?.tool_output; +} + +/** + * The text of that result: a string as it is, an adapted `output`, or the + * `stdout` and `stderr` of a Bash result. An empty string when it has no text. + */ +function getToolResultText(input) { + const result = getToolResult(input); + if (typeof result === 'string') return result; + if (!result || typeof result !== 'object') return ''; + if (typeof result.output === 'string') return result.output; + return [result.stdout, result.stderr].filter(part => typeof part === 'string' && part !== '').join('\n'); +} + module.exports = { DEFAULT_MAX_STDIN, DEFAULT_STDIN_IDLE_TIMEOUT_MS, + getToolResult, + getToolResultText, readStdinRaw, resolveMaxStdin, resolveStdinIdleTimeout diff --git a/scripts/hooks/post-bash-pr-created.js b/scripts/hooks/post-bash-pr-created.js index b18dad539..a83ca18b7 100755 --- a/scripts/hooks/post-bash-pr-created.js +++ b/scripts/hooks/post-bash-pr-created.js @@ -2,6 +2,7 @@ 'use strict'; const MAX_STDIN = 1024 * 1024; +const { getToolResultText } = require('./hook-input'); let raw = ''; function run(rawInput) { @@ -10,7 +11,7 @@ function run(rawInput) { const cmd = String(input.tool_input?.command || ''); if (/\bgh\s+pr\s+create\b/.test(cmd)) { - const out = String(input.tool_output?.output || ''); + const out = getToolResultText(input); const match = out.match(/https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+/); if (match) { const prUrl = match[0]; diff --git a/scripts/hooks/session-activity-tracker.js b/scripts/hooks/session-activity-tracker.js index a9dc21a95..1ac8efd7c 100644 --- a/scripts/hooks/session-activity-tracker.js +++ b/scripts/hooks/session-activity-tracker.js @@ -29,17 +29,52 @@ const FILE_PATH_KEYS = new Set([ 'new_file_path', ]); +// A name that carries a credential word anywhere (`AWS_SECRET_ACCESS_KEY`, +// `DOCKER_AUTH_CONFIG`, Docker's `"auth":`), but not `max_tokens`, `tokenizer` +// or `author`. +const CREDENTIAL_WORD = /secret|token(?!s|iz)|passw(?:or)?d|api[_-]?key|access[_-]?key|private[_-]?key|credential|auth\b|auth[_-]?config/i; +// A whole name and its separator. A name starts only where a run of name +// characters starts, so each run is scanned once and long output stays linear +// however long the name is. +const ASSIGNMENT = /(?`; + copied = valueStart + value[0].length; + ASSIGNMENT.lastIndex = copied; + } + return redacted + text.slice(copied); +} + function redactSecrets(value) { - return String(value || '') + // The credential values cover what governance-capture detects, since tool + // output such as `cat .env` lands in these summaries too. + return redactCredentialValues(String(value || '') .replace(/\n/g, ' ') .replace(/--token[= ][^ ]*/g, '--token=') .replace(/Authorization:[: ]*[^ ]*[: ]*[^ ]*/gi, 'Authorization:') .replace(/\bAKIA[A-Z0-9]{16}\b/g, '') .replace(/\bASIA[A-Z0-9]{16}\b/g, '') - .replace(/password[= ][^ ]*/gi, 'password=') - .replace(/\bghp_[A-Za-z0-9_]+\b/g, '') - .replace(/\bgho_[A-Za-z0-9_]+\b/g, '') - .replace(/\bghs_[A-Za-z0-9_]+\b/g, '') + .replace(/password[= ][^ ]*/gi, 'password=')) + .replace(/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, '') + .replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----.*/g, '') + .replace(/\bgh[pousr]_[A-Za-z0-9_]+\b/g, '') .replace(/\bgithub_pat_[A-Za-z0-9_]+\b/g, ''); } @@ -545,20 +580,34 @@ function summarizeInput(toolName, toolInput, filePaths) { return truncateSummary(toolName); } +// Activity history keeps tool output text only from the adapter's `tool_output`, a +// string, number, boolean or `{ output }`, and redacts it. A structured result is never +// serialized, since an encoding nested in it escapes the redaction patterns. function summarizeOutput(toolOutput) { - if (toolOutput === null || toolOutput === undefined) { - return ''; + if (['string', 'number', 'boolean'].includes(typeof toolOutput)) { + return truncateSummary(String(toolOutput)); } - if (typeof toolOutput === 'string') { - return truncateSummary(toolOutput); - } - - if (typeof toolOutput === 'object' && typeof toolOutput.output === 'string') { + if (toolOutput && typeof toolOutput === 'object' && typeof toolOutput.output === 'string') { return truncateSummary(toolOutput.output); } - return truncateSummary(JSON.stringify(toolOutput)); + return ''; +} + +// Of Claude Code's `tool_response`, only the sizes and flags of a Bash result +// ({ stdout, stderr, interrupted, isImage }) are kept. None of them holds output. +function summarizeToolResponse(response) { + if (!response || typeof response !== 'object') { + return ''; + } + + const parts = ['stdout', 'stderr'] + .filter(field => typeof response[field] === 'string') + .map(field => `${field}: ${response[field].length} chars`); + if (response.interrupted === true) parts.push('interrupted'); + if (response.isImage === true) parts.push('image'); + return parts.join(', '); } function buildActivityRow(input, env = process.env) { @@ -601,7 +650,9 @@ function buildActivityRow(input, env = process.env) { tool_name: toolName, input_summary: summarizeInput(toolName, toolInput, filePaths), input_params_json: sanitizeInputParams(toolInput), - output_summary: summarizeOutput(input?.tool_output), + output_summary: input?.tool_response === undefined + ? summarizeOutput(input?.tool_output) + : summarizeToolResponse(input.tool_response), duration_ms: 0, file_paths: filePaths, file_events: fileEvents, diff --git a/tests/hooks/governance-capture.test.js b/tests/hooks/governance-capture.test.js index 7d40ebe78..aefa64423 100644 --- a/tests/hooks/governance-capture.test.js +++ b/tests/hooks/governance-capture.test.js @@ -142,6 +142,18 @@ async function runTests() { assert.strictEqual(secretEvent.payload.severity, 'critical'); })) passed += 1; else failed += 1; + if (await test('analyzeForGovernanceEvents detects secrets in a Bash result Claude Code sends as tool_response', async () => { + const events = analyzeForGovernanceEvents({ + tool_name: 'Bash', + tool_input: { command: 'cat .env' }, + tool_response: { stdout: 'AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE\n', stderr: '', interrupted: false, isImage: false }, + }); + + const secretEvent = events.find(e => e.eventType === 'secret_detected'); + assert.ok(secretEvent, 'Expected a secret_detected event'); + assert.strictEqual(secretEvent.payload.location, 'output'); + })) passed += 1; else failed += 1; + if (await test('analyzeForGovernanceEvents detects approval-required commands', async () => { const events = analyzeForGovernanceEvents({ tool_name: 'Bash', diff --git a/tests/hooks/hook-input.test.js b/tests/hooks/hook-input.test.js index a9d7799bb..a45294859 100644 --- a/tests/hooks/hook-input.test.js +++ b/tests/hooks/hook-input.test.js @@ -10,6 +10,8 @@ const { spawn } = require('child_process'); const { PassThrough } = require('stream'); const { DEFAULT_STDIN_IDLE_TIMEOUT_MS, + getToolResult, + getToolResultText, readStdinRaw, resolveStdinIdleTimeout } = require('../../scripts/hooks/hook-input'); @@ -194,6 +196,27 @@ async function runTests() { passed++; else failed++; + if ( + await test('reads the tool result from Claude Code and from adapted payloads', async () => { + // Claude Code sends tool_response; Bash results carry stdout and stderr. + const bash = { stdout: 'out', stderr: 'err', interrupted: false, isImage: false }; + assert.strictEqual(getToolResult({ tool_response: bash }), bash); + assert.strictEqual(getToolResultText({ tool_response: bash }), 'out\nerr'); + assert.strictEqual(getToolResultText({ tool_response: { stdout: 'out', stderr: '' } }), 'out'); + assert.strictEqual(getToolResultText({ tool_response: 'plain' }), 'plain'); + // The Cursor adapter and older payloads send tool_output. + assert.strictEqual(getToolResultText({ tool_output: { output: 'adapted' } }), 'adapted'); + assert.strictEqual(getToolResultText({ tool_output: 'legacy' }), 'legacy'); + assert.strictEqual(getToolResultText({ tool_response: { stdout: 'new' }, tool_output: 'old' }), 'new'); + // A result without text, or no result at all. + assert.strictEqual(getToolResultText({ tool_response: { filePath: '/tmp/a.txt', type: 'create' } }), ''); + assert.strictEqual(getToolResultText({}), ''); + assert.strictEqual(getToolResultText(null), ''); + }) + ) + passed++; + else failed++; + if ( await test('held-open stream with no input settles as truncated after the idle deadline', async () => { const { resultPromise } = readFromHeldOpenStream([]); diff --git a/tests/hooks/post-bash-hooks.test.js b/tests/hooks/post-bash-hooks.test.js index eb6e2a167..798cfcc89 100644 --- a/tests/hooks/post-bash-hooks.test.js +++ b/tests/hooks/post-bash-hooks.test.js @@ -130,6 +130,19 @@ if (test('stderr contains PR URL when gh pr create output has PR URL', () => { assert.ok(result.stderr.includes('gh pr review 42'), 'stderr should contain review command'); })) passed++; else failed++; +if (test('stderr contains PR URL when Claude Code sends the Bash result as tool_response', () => { + const input = JSON.stringify({ + hook_event_name: 'PostToolUse', + tool_name: 'Bash', + tool_input: { command: 'gh pr create --fill' }, + tool_response: { stdout: 'https://github.com/owner/repo/pull/42\n', stderr: '', interrupted: false, isImage: false } + }); + const result = runScript(prCreatedScript, input); + assert.strictEqual(result.status, 0, 'Should exit with code 0'); + assert.ok(result.stderr.includes('[Hook] PR created: https://github.com/owner/repo/pull/42'), `stderr should contain PR URL, got: ${result.stderr}`); + assert.ok(result.stderr.includes('gh pr review 42 --repo owner/repo'), 'stderr should contain review command'); +})) passed++; else failed++; + if (test('stderr contains correct repo in review command', () => { const input = JSON.stringify({ tool_input: { command: 'gh pr create' }, diff --git a/tests/hooks/session-activity-tracker-output.test.js b/tests/hooks/session-activity-tracker-output.test.js new file mode 100644 index 000000000..ea622be21 --- /dev/null +++ b/tests/hooks/session-activity-tracker-output.test.js @@ -0,0 +1,176 @@ +/** + * Tests for what session-activity-tracker.js keeps of a tool's output. + */ + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +const script = path.join( + __dirname, + '..', + '..', + 'scripts', + 'hooks', + 'session-activity-tracker.js' +); +const { buildActivityRow, summarizeOutput } = require(script); + +function test(name, fn) { + try { + fn(); + console.log(` ✓ ${name}`); + return true; + } catch (err) { + console.log(` ✗ ${name}`); + console.log(` Error: ${err.message}`); + return false; + } +} + +function makeTempDir() { + return fs.mkdtempSync(path.join(os.tmpdir(), 'session-activity-tracker-test-')); +} + +function withTempHome(homeDir) { + return { + HOME: homeDir, + USERPROFILE: homeDir, + }; +} + +// session-activity-tracker.js appends to ~/.claude/metrics/tool-usage.jsonl, so +// runs get an empty home instead of the developer's real one unless a test +// passes withTempHome(). +const ISOLATED_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'session-activity-home-')); +const ISOLATED_HOME_ENV = { HOME: ISOLATED_HOME, USERPROFILE: ISOLATED_HOME }; +process.on('exit', () => fs.rmSync(ISOLATED_HOME, { recursive: true, force: true })); + +function runScript(input, envOverrides = {}, options = {}) { + const inputStr = typeof input === 'string' ? input : JSON.stringify(input); + const result = spawnSync('node', [script], { + encoding: 'utf8', + input: inputStr, + timeout: 10000, + env: { + ...process.env, ...ISOLATED_HOME_ENV, + ECC_SESSION_ID: '', CLAUDE_SESSION_ID: '', + ...envOverrides, + }, + cwd: options.cwd, + }); + return { code: result.status || 0, stdout: result.stdout || '', stderr: result.stderr || '' }; +} + +function readMetricRows(homeDir) { + const metricsFile = path.join(homeDir, '.claude', 'metrics', 'tool-usage.jsonl'); + return fs.readFileSync(metricsFile, 'utf8') + .trim() + .split(/\r?\n/) + .filter(Boolean) + .map(line => JSON.parse(line)); +} + +function runTests() { + console.log('\n=== Testing session-activity-tracker.js output summaries ===\n'); + + let passed = 0; + let failed = 0; + + (test('summarizes tool output with credentials redacted', () => { + assert.strictEqual(summarizeOutput({ stdout: 'out', stderr: '' }), ''); + assert.strictEqual(summarizeOutput(`token ghp_${'A'.repeat(20)}`), 'token '); + // Claude Code sends the result as tool_response, for Bash { stdout, stderr, ... }: + // only its sizes and flags are kept. + const bashRow = buildActivityRow( + { + hook_event_name: 'PostToolUse', + session_id: 'sess-1', + tool_name: 'Bash', + tool_input: { command: 'npm test' }, + tool_response: { stdout: '12 passing\n', stderr: 'warn: slow\n', interrupted: false, isImage: false }, + }, + {} + ); + assert.strictEqual(bashRow.output_summary, 'stdout: 11 chars, stderr: 11 chars'); + // Output such as `cat .env` lands here too, so the secrets governance-capture + // detects are redacted as well. + assert.strictEqual(summarizeOutput('api_key = "example-secret-value"\n'), 'api_key = '); + assert.strictEqual(summarizeOutput('OPENAI_API_KEY=sk-abc123def456\nDEBUG=1'), 'OPENAI_API_KEY= DEBUG=1'); + assert.strictEqual(summarizeOutput('AWS_SECRET_ACCESS_KEY=example-secret-value'), 'AWS_SECRET_ACCESS_KEY='); + assert.strictEqual(summarizeOutput('DOCKER_AUTH_CONFIG={"auths":{"registry":{}}}'), 'DOCKER_AUTH_CONFIG='); + assert.strictEqual(summarizeOutput('DOCKER_AUTH_CONFIG={"auths": {"registry": {"auth": "dXNlcjpwYXNz"}}}'), 'DOCKER_AUTH_CONFIG='); + assert.strictEqual(summarizeOutput('{"auths":{"registry":{"auth":"dXNlcjpwYXNz"}}}'), '{"auths":{"registry":{"auth":}}}'); + assert.strictEqual(summarizeOutput('auth_method=oidc author=Jane'), 'auth_method=oidc author=Jane'); + assert.strictEqual(summarizeOutput('{"token": "abc.def", "user": "bob"}'), '{"token": , "user": "bob"}'); + const jwt = ['eyJ' + 'a'.repeat(12), 'eyJ' + 'b'.repeat(12), 'c'.repeat(12)].join('.'); + assert.strictEqual(summarizeOutput(`Bearer ${jwt} done`), 'Bearer done'); + assert.strictEqual(summarizeOutput('-----BEGIN RSA PRIVATE KEY-----\nMIIE...'), ''); + assert.strictEqual(summarizeOutput(`ghu_${'C'.repeat(36)}`), ''); + assert.strictEqual(summarizeOutput('Unexpected tokens: 0, max_tokens=4096, tokenizer=bpe, author=Jane'), 'Unexpected tokens: 0, max_tokens=4096, tokenizer=bpe, author=Jane'); + // A bare value after a quoted JSON key ends at the next field, and a quoted one + // may hold escaped quotes. + assert.strictEqual(summarizeOutput('{"token":null,"status":"failed","exit_code":1}'), '{"token":,"status":"failed","exit_code":1}'); + assert.strictEqual(summarizeOutput('{"api_key":"part1\\" part2"}'), '{"api_key":}'); + // Any other bare value runs to the next space: a comma can be part of it. + assert.strictEqual(summarizeOutput('CLIENT_SECRET=alpha,beta DEBUG=1'), 'CLIENT_SECRET= DEBUG=1'); + assert.strictEqual(summarizeOutput('client_secret: alpha,beta'), 'client_secret: '); + // The whole name is checked, however long. + const longName = `API_KEY_${'A'.repeat(65)}`; + assert.strictEqual(summarizeOutput(`${longName}=example-secret-value`), `${longName}=`); + assert.strictEqual(summarizeOutput(`${'A'.repeat(100)}_SECRET=example-secret-value`), `${'A'.repeat(100)}_SECRET=`); + // Separator-heavy output stays linear: unbounded name parts took seconds here. + for (const output of ['a.'.repeat(64000), 'secret'.repeat(21000), 'x.secret:'.repeat(14000), '"a":'.repeat(32000)]) { + const started = Date.now(); + summarizeOutput(output); + assert.ok(Date.now() - started < 2000, `Redacting ${output.length} characters should stay within its time budget`); + } + }) ? passed++ : failed++); + + (test('saves no part of a structured tool result in activity history', () => { + const tmpHome = makeTempDir(); + const marker = 'S3CR3T-MARK'; + const env = { ...withTempHome(tmpHome), CLAUDE_HOOK_EVENT_NAME: 'PostToolUse', ECC_SESSION_ID: 'sess-privacy' }; + const bashOutput = [ + `{"token": "${marker}-direct"}`, + JSON.stringify(JSON.stringify({ token: `${marker}-escaped` })), + `Authorization: Bearer ${marker}-header`, + `"Authorization": "Bearer ${marker}-quoted"`, + `API_TOKEN=${marker}\\ escaped-space`, + ].join('\n'); + const payloads = [ + { tool_name: 'Bash', tool_input: { command: 'cat .env' }, tool_response: { stdout: bashOutput, stderr: '', interrupted: false, isImage: false } }, + { + tool_name: 'mcp__example__fetch', + tool_input: {}, + tool_response: { + content: [{ type: 'text', text: JSON.stringify({ api_key: `${marker}-nested` }) }], + headers: { Authorization: `Bearer ${marker}-field` }, + raw: JSON.stringify(JSON.stringify(`password=${marker}-double`)), + }, + }, + { tool_name: 'Read', tool_input: { file_path: 'README.md' }, tool_output: { output: 'adapted result text' } }, + ]; + for (const payload of payloads) { + assert.strictEqual(runScript(payload, env).code, 0); + } + + const saved = fs.readFileSync(path.join(tmpHome, '.claude', 'metrics', 'tool-usage.jsonl'), 'utf8'); + assert.ok(!saved.includes(marker), `activity history kept a credential fragment: ${saved}`); + const rows = readMetricRows(tmpHome); + assert.deepStrictEqual(rows.map(row => row.output_summary), [ + `stdout: ${bashOutput.length} chars, stderr: 0 chars`, + '', + 'adapted result text', + ]); + + fs.rmSync(tmpHome, { recursive: true, force: true }); + }) ? passed++ : failed++); + + console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); + process.exit(failed > 0 ? 1 : 0); +} + +runTests(); diff --git a/tests/hooks/session-activity-tracker.test.js b/tests/hooks/session-activity-tracker.test.js index d56110535..9f4d3d31f 100644 --- a/tests/hooks/session-activity-tracker.test.js +++ b/tests/hooks/session-activity-tracker.test.js @@ -564,7 +564,8 @@ function runTests() { assert.strictEqual(summarizeOutput(null), ''); assert.strictEqual(summarizeOutput(undefined), ''); assert.strictEqual(summarizeOutput('hello\nworld'), 'hello world'); - assert.strictEqual(summarizeOutput({ ok: true }), '{"ok":true}'); + // A structured result is not serialized: nested encodings would escape redaction. + assert.strictEqual(summarizeOutput({ ok: true }), ''); }) ? passed++ : failed++); (test('extracts file paths from nested arrays while filtering duplicates and remote URIs', () => {