diff --git a/scripts/hooks/post-bash-command-log.js b/scripts/hooks/post-bash-command-log.js index dffbba6de..606c608d2 100644 --- a/scripts/hooks/post-bash-command-log.js +++ b/scripts/hooks/post-bash-command-log.js @@ -207,6 +207,12 @@ function appendLine(filePath, line) { } catch { // No log yet. } + // Logs written by earlier versions were group/world readable. Tighten an + // existing log before it can be rotated, so the `.1` copy is private too. + // Windows has no POSIX permission bits to tighten. + if (stat && stat.isFile() && process.platform !== 'win32' && (stat.mode & 0o077) !== 0) { + fs.chmodSync(filePath, LOG_FILE_MODE); + } if (stat && stat.isFile() && stat.size > 0 && stat.size + Buffer.byteLength(data) > LOG_MAX_BYTES) { try { fs.renameSync(filePath, `${filePath}.1`); @@ -216,17 +222,10 @@ function appendLine(filePath, line) { } } + // The mode only applies when this call creates the file; an existing log + // was tightened above. const fd = fs.openSync(filePath, 'a', LOG_FILE_MODE); try { - // The mode above only applies when the file is created. Logs written by - // earlier versions were group/world readable, so tighten them here. - // Windows has no POSIX permission bits to tighten. - if (process.platform !== 'win32') { - const current = fs.fstatSync(fd); - if (current.isFile() && (current.mode & 0o077) !== 0) { - fs.fchmodSync(fd, LOG_FILE_MODE); - } - } fs.writeSync(fd, data); } finally { fs.closeSync(fd); diff --git a/tests/scripts/post-bash-command-log.test.js b/tests/scripts/post-bash-command-log.test.js index 71be45a20..7c1fc1166 100644 --- a/tests/scripts/post-bash-command-log.test.js +++ b/tests/scripts/post-bash-command-log.test.js @@ -445,6 +445,32 @@ if ( passed++; else failed++; +if ( + test('a legacy group/world-readable log at the cap rotates to a private .1 (#3846)', () => { + if (!checkModes) return; + const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-bash-log-')); + const logFile = path.join(homeDir, '.claude', 'bash-commands.log'); + + try { + fs.mkdirSync(path.dirname(logFile), { recursive: true }); + fs.writeFileSync(logFile, '[legacy] history\n'); + fs.truncateSync(logFile, LOG_MAX_BYTES); + fs.chmodSync(logFile, 0o664); + + const result = runHook('audit', { tool_input: { command: 'echo next' } }, homeDir); + assert.strictEqual(result.status, 0, result.stdout + result.stderr); + + assert.ok(fs.readFileSync(`${logFile}.1`, 'utf8').startsWith('[legacy] history\n')); + assert.strictEqual(fs.statSync(`${logFile}.1`).mode & 0o777, 0o600); + assert.strictEqual(fs.statSync(logFile).mode & 0o777, 0o600); + } finally { + fs.rmSync(homeDir, { recursive: true, force: true }); + } + }) +) + passed++; +else failed++; + if ( test('a failed rotation still records the command (#3846)', () => { const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-bash-log-'));