fix(hooks): tighten a legacy log before rotating it

An existing 0664 log that was already at the cap was renamed to .1
before its mode was tightened, so the rotated copy stayed group/world
readable. Tighten the existing log first, and drop the post-open
fchmod that only reached the new active log.

Refs #3846
This commit is contained in:
Gaurav Dubey committed 2026-11-19 04:21:19 +00:00
1 parent 9e6272d5df
commit b427484d1e
2 files changed
+34 -9

No files matched your search

+8 -9
View File
@@ -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);
@@ -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-'));