Audit: GET_LOCK-Ergebnis vor Eintrag prüfen #1

Open
flessinb wants to merge 1 commit from codex/nightbot-2026-09-30 into main
2 changed files with 33 additions and 1 deletions
Showing only changes of commit 51089b2249 - Show all commits

View file

@ -36,7 +36,8 @@ export async function audit(e: AuditInput, conn?: PoolConnection): Promise<void>
const c = conn ?? (await pool.getConnection()); const c = conn ?? (await pool.getConnection());
try { try {
if (own) await c.beginTransaction(); if (own) await c.beginTransaction();
await c.query('SELECT GET_LOCK(?, 10)', ['kc_audit_chain']); const [locks] = await c.query<import('mysql2').RowDataPacket[]>('SELECT GET_LOCK(?, 10) AS acquired', ['kc_audit_chain']);
if (Number(locks[0]?.acquired) !== 1) throw new Error('Audit lock unavailable');
const last = await one<{ hash: string } & import('mysql2').RowDataPacket>('SELECT hash FROM audit_events ORDER BY id DESC LIMIT 1', [], c); const last = await one<{ hash: string } & import('mysql2').RowDataPacket>('SELECT hash FROM audit_events ORDER BY id DESC LIMIT 1', [], c);
const prev = last?.hash ?? '0'.repeat(64); const prev = last?.hash ?? '0'.repeat(64);
const ts = new Date(); const ts = new Date();

View file

@ -0,0 +1,31 @@
import { describe, expect, it, vi } from 'vitest';
const connection = vi.hoisted(() => ({
beginTransaction: vi.fn(),
query: vi.fn(),
execute: vi.fn(),
commit: vi.fn(),
rollback: vi.fn(),
release: vi.fn(),
}));
vi.mock('../src/db.js', () => ({
pool: { getConnection: vi.fn(async () => connection) },
one: vi.fn(),
query: vi.fn(),
}));
import { audit } from '../src/audit.js';
describe('audit advisory lock', () => {
it.each([0, null])('does not append an event when GET_LOCK returns %s', async (acquired) => {
vi.clearAllMocks();
connection.query.mockResolvedValueOnce([[{ acquired }]]).mockResolvedValueOnce([[{ released: null }]]);
await expect(audit({ actorType: 'system', action: 'test.lock' })).rejects.toThrow('Audit lock unavailable');
expect(connection.execute).not.toHaveBeenCalled();
expect(connection.commit).not.toHaveBeenCalled();
expect(connection.rollback).toHaveBeenCalledOnce();
expect(connection.release).toHaveBeenCalledOnce();
});
});