refactor(audit): audit log writes through AuditLogRepository

This commit is contained in:
jubnl
2026-09-22 12:34:49 +02:00
parent b8e7dbccc6
commit c2da9d62f7
29 changed files with 308 additions and 80 deletions
@@ -0,0 +1,64 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { createUser } from '../../../helpers/factories';
import { AuditLog } from '../../../../src/db/entities/AuditLog.entity';
import type { AuditLogRepository } from '../../../../src/db/repositories/AuditLog.repository';
import { DB_TIMESTAMP_RE } from '../../../../src/db/types';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let auditLog: AuditLogRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
auditLog = t.repo(AuditLog) as AuditLogRepository;
});
beforeEach(() => { resetTestDb(testDb); t.clear(); });
afterAll(async () => { await t.close(); testDb.close(); });
describe('AuditLogRepository', () => {
it('AUDITREPO-001: insert writes the legacy column set, matching the SELECT * row exactly', async () => {
const { user } = createUser(testDb);
await auditLog.insertEntry({ user_id: user.id, action: 'trip.create', resource: 'trip', details: '{"title":"Rome"}', ip: '1.2.3.4' });
const row = testDb.prepare('SELECT * FROM audit_log').get() as { id: number; created_at: string };
expect(row).toStrictEqual({
id: row.id,
created_at: row.created_at,
user_id: user.id,
action: 'trip.create',
resource: 'trip',
details: '{"title":"Rome"}',
ip: '1.2.3.4',
});
});
it('AUDITREPO-002: created_at is left to the column default, as text, in the YYYY-MM-DD HH:MM:SS shape', async () => {
const { user } = createUser(testDb);
await auditLog.insertEntry({ user_id: user.id, action: 'user.login', resource: null, details: null, ip: null });
const stored = testDb.prepare('SELECT created_at, typeof(created_at) AS kind FROM audit_log').get() as { created_at: string; kind: string };
expect(stored.kind).toBe('text');
expect(stored.created_at).toMatch(DB_TIMESTAMP_RE);
});
it('AUDITREPO-003: a null user writes a null user_id twin, not a foreign-key value', async () => {
await auditLog.insertEntry({ user_id: null, action: 'user.login', resource: null, details: null, ip: null });
const row = testDb.prepare('SELECT user_id FROM audit_log').get() as { user_id: number | null };
expect(row.user_id).toBeNull();
});
it('AUDITREPO-004: null resource/details/ip are stored as NULL, not the string "null"', async () => {
const { user } = createUser(testDb);
await auditLog.insertEntry({ user_id: user.id, action: 'user.login', resource: null, details: null, ip: null });
const row = testDb.prepare('SELECT resource, details, ip FROM audit_log').get();
expect(row).toEqual({ resource: null, details: null, ip: null });
});
it('AUDITREPO-005: resolves without returning a value — no id or row is read back', async () => {
const { user } = createUser(testDb);
await expect(
auditLog.insertEntry({ user_id: user.id, action: 'user.login', resource: null, details: null, ip: null }),
).resolves.toBeUndefined();
});
});
+31 -32
View File
@@ -1,32 +1,15 @@
/**
* Unit tests for the DI-native audit domain — AUDIT-SVC-001 through
* AUDIT-SVC-017 (001–007 are the getClientIp cases moved 1:1 from the legacy
* AUDIT-SVC-019 (001–007 are the getClientIp cases moved 1:1 from the legacy
* tests/unit/services/auditLog.test.ts, which had no case IDs — the IDs are
* introduced with the move; 008–014 cover writeAudit over a real in-memory
* SQLite DB, which the legacy suite never exercised; 015–017 pin the
* audit.bridge delegation). The logger module is mocked (it replaces the old
* suite's fs mock: the import-time mkdir lives there now, and mocking it lets
* the exact log-line formats be asserted).
* introduced with the move; 008–014, 018, 019 cover writeAudit over a real
* in-memory SQLite DB through AuditLogRepository/UsersRepository, which the
* legacy suite never exercised). The logger module is mocked (it replaces the
* old suite's fs mock: the import-time mkdir lives there now, and mocking it
* lets the exact log-line formats be asserted).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
@@ -36,27 +19,44 @@ vi.mock('../../../src/nest/audit/audit-log.logger', () => ({
}));
import type { Request } from 'express';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
import { Users } from '../../../src/db/entities/Users.entity';
import type { AuditLogRepository } from '../../../src/db/repositories/AuditLog.repository';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
import { AuditService } from '../../../src/nest/audit/audit.service';
import { getClientIp } from '../../../src/nest/audit/client-ip';
import { logInfo, logDebug, logError } from '../../../src/nest/audit/audit-log.logger';
const svc = new AuditService(new DatabaseService(testDb));
const testDb = new Database(':memory:');
testDb.exec('PRAGMA journal_mode = WAL');
testDb.exec('PRAGMA foreign_keys = ON');
testDb.exec('PRAGMA busy_timeout = 5000');
beforeAll(() => {
let t: TestOrm;
let auditLogRepo: AuditLogRepository;
let svc: AuditService;
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
t = await createTestOrm(testDb);
auditLogRepo = t.repo(AuditLog) as AuditLogRepository;
svc = new AuditService(auditLogRepo, t.repo(Users) as UsersRepository);
});
beforeEach(() => {
vi.clearAllMocks();
testDb.prepare('DELETE FROM audit_log').run();
testDb.prepare('DELETE FROM users').run();
t.clear();
});
afterAll(() => {
afterAll(async () => {
await t.close();
testDb.close();
});
@@ -111,7 +111,7 @@ describe('getClientIp', () => {
});
});
// ── writeAudit (real DB) ──────────────────────────────────────────────────────
// ── writeAudit (real DB, through the repositories) ────────────────────────────
function seedUser(id: number, email: string): void {
testDb.prepare(
@@ -180,10 +180,10 @@ describe('writeAudit', () => {
});
it('AUDIT-SVC-013: never throws — a failed insert reduces to a logError line', async () => {
testDb.prepare('ALTER TABLE audit_log RENAME TO audit_log_gone').run();
const spy = vi.spyOn(auditLogRepo, 'insertEntry').mockRejectedValueOnce(new Error('insert failed'));
await expect(svc.writeAudit({ userId: 1, action: 'user.login' })).resolves.not.toThrow();
expect(logError).toHaveBeenCalledWith(expect.stringMatching(/^Audit write failed: /));
testDb.prepare('ALTER TABLE audit_log_gone RENAME TO audit_log').run();
expect(logError).toHaveBeenCalledWith('Audit write failed: insert failed');
spy.mockRestore();
});
it('AUDIT-SVC-018: settings.api_keys_update names the changed keys and nothing else (#1939)', async () => {
@@ -212,4 +212,3 @@ describe('writeAudit', () => {
expect(logInfo).toHaveBeenLastCalledWith('a@b.c logged in ip=1.1.1.1');
});
});
+14 -3
View File
@@ -65,12 +65,19 @@ import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { getMcpSafeUrl } from '../../../src/app-config';
import { ADDON_IDS } from '../../../src/addons';
import { MAX_PENDING_CODES, sweepPendingCodes } from '../../../src/nest/oauth/oauth.pending-codes';
import { createTestOrm } from '../../helpers/test-orm';
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
import type { AuditLogRepository } from '../../../src/db/repositories/AuditLog.repository';
import { Users } from '../../../src/db/entities/Users.entity';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
const dbs = new DatabaseService(testDb);
// Stubbed rather than real: every case drives the MCP gate through this one
// flag, exactly as the addons.bridge mock did before the fold.
const addonsStub = { isAddonEnabled } as unknown as AddonsService;
const svc = new OauthService(dbs, addonsStub, new AuditService(dbs));
let svc: OauthService;
let auditLogRepo: AuditLogRepository;
let usersRepo: UsersRepository;
// Legacy free-function names delegating to the service, so the moved cases below
// read exactly as they did before the fold. Arrow wrappers rather than `.bind`:
@@ -95,9 +102,13 @@ const saveConsent = (...args: Parameters<OauthService['saveConsent']>) => svc.sa
const getConsent = (...args: Parameters<OauthService['getConsent']>) => svc.getConsent(...args);
const isConsentSufficient = (...args: Parameters<OauthService['isConsentSufficient']>) => svc.isConsentSufficient(...args);
beforeAll(() => {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
const t = await createTestOrm(testDb);
auditLogRepo = t.repo(AuditLog) as AuditLogRepository;
usersRepo = t.repo(Users) as UsersRepository;
svc = new OauthService(dbs, addonsStub, new AuditService(auditLogRepo, usersRepo));
});
beforeEach(() => {
@@ -1285,7 +1296,7 @@ describe('module-scoped OAuth state', () => {
codeChallengeMethod: 'S256',
})!;
const secondInstance = new OauthService(dbs, addonsStub, new AuditService(dbs));
const secondInstance = new OauthService(dbs, addonsStub, new AuditService(auditLogRepo, usersRepo));
expect(secondInstance.consumeAuthCode(code)?.userId).toBe(42);
});
});
@@ -28,6 +28,11 @@ import { runMigrations } from '../../../src/db/migrations';
import { createUser } from '../../helpers/factories';
import { PluginUserSettingsService } from '../../../src/nest/plugins/plugin-user-settings.service';
import { parseManifest, ManifestError } from '../../../src/nest/plugins/install/manifest';
import { createTestOrm } from '../../helpers/test-orm';
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
import type { AuditLogRepository } from '../../../src/db/repositories/AuditLog.repository';
import { Users } from '../../../src/db/entities/Users.entity';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
/** The host-side settings reads, over the same connection the test seeded. */
const userSettings = () => new PluginUserSettingsService(new DatabaseService(dbConn));
@@ -126,7 +131,13 @@ describe('a plugin channel label is bounded by the host', () => {
VALUES ('loud', 'Loud', 'active', 1, '1.0.0', '[]', '[]', ?, '{}')`,
).run(JSON.stringify({ notificationChannel: { title: '🎉'.repeat(5) + 'A'.repeat(500) } }));
const rt = new PluginRuntimeService(new DatabaseService(dbConn), new AuditService(new DatabaseService(dbConn)), new AddonsService(new DatabaseService(dbConn)), userSettings());
const t = await createTestOrm(dbConn);
const rt = new PluginRuntimeService(
new DatabaseService(dbConn),
new AuditService(t.repo(AuditLog) as AuditLogRepository, t.repo(Users) as UsersRepository),
new AddonsService(new DatabaseService(dbConn)),
userSettings(),
);
// Stand the plugin up as a granted, active notificationChannel provider.
(rt as unknown as { supervisor: { running: Map<string, unknown> } }).supervisor.running.set('loud', {
id: 'loud', status: 'active', hooks: ['notificationChannel'], granted: new Set(['hook:notification-channel']),
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';
// Avoid any real DNS/network from the SSRF guard during saveSettings and the probe.
vi.mock('../../../src/utils/ssrfGuard', () => ({
@@ -12,15 +12,25 @@ import { AirtrailService } from '../../../src/nest/integrations/airtrail.service
import type { AirtrailClient } from '../../../src/nest/integrations/airtrail.client';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { AuditService } from '../../../src/nest/audit/audit.service';
import { createTestOrm } from '../../helpers/test-orm';
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
import type { AuditLogRepository } from '../../../src/db/repositories/AuditLog.repository';
import { Users } from '../../../src/db/entities/Users.entity';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
// The probe is the only call that would leave the process, so the client is a
// stub; the credential handling around it runs against the real row.
const listFlights = vi.fn();
const svc = new AirtrailService(
new DatabaseService(db),
new AuditService(new DatabaseService(db)),
{ listFlights } as unknown as AirtrailClient,
);
let svc: AirtrailService;
beforeAll(async () => {
const t = await createTestOrm(db);
svc = new AirtrailService(
new DatabaseService(db),
new AuditService(t.repo(AuditLog) as AuditLogRepository, t.repo(Users) as UsersRepository),
{ listFlights } as unknown as AirtrailClient,
);
});
const MASK = '••••••••';
@@ -1,4 +1,4 @@
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect, vi, beforeAll } from 'vitest';
// Avoid any real DNS/network from the SSRF guard during saveSettings.
vi.mock('../../../src/utils/ssrfGuard', () => ({
@@ -12,17 +12,30 @@ import { AirtrailService } from '../../../src/nest/integrations/airtrail.service
import { AirtrailClient } from '../../../src/nest/integrations/airtrail.client';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { AuditService } from '../../../src/nest/database/../audit/audit.service';
import { createTestOrm } from '../../helpers/test-orm';
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
import type { AuditLogRepository } from '../../../src/db/repositories/AuditLog.repository';
import { Users } from '../../../src/db/entities/Users.entity';
import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
// The free functions became methods with the airtrail fold; same SQL, same
// behaviour, one instance over the same db handle.
const svc = new AirtrailService(
new DatabaseService(db),
new AuditService(new DatabaseService(db)),
new AirtrailClient(),
);
const getConnectionSettings = (...args: Parameters<AirtrailService['getConnectionSettings']>) => svc.getConnectionSettings(...args);
const isAirtrailWriteEnabled = (...args: Parameters<AirtrailService['isAirtrailWriteEnabled']>) => svc.isAirtrailWriteEnabled(...args);
const saveSettings = (...args: Parameters<AirtrailService['saveSettings']>) => svc.saveSettings(...args);
let svc: AirtrailService;
let getConnectionSettings: (...args: Parameters<AirtrailService['getConnectionSettings']>) => ReturnType<AirtrailService['getConnectionSettings']>;
let isAirtrailWriteEnabled: (...args: Parameters<AirtrailService['isAirtrailWriteEnabled']>) => ReturnType<AirtrailService['isAirtrailWriteEnabled']>;
let saveSettings: (...args: Parameters<AirtrailService['saveSettings']>) => ReturnType<AirtrailService['saveSettings']>;
beforeAll(async () => {
const t = await createTestOrm(db);
svc = new AirtrailService(
new DatabaseService(db),
new AuditService(t.repo(AuditLog) as AuditLogRepository, t.repo(Users) as UsersRepository),
new AirtrailClient(),
);
getConnectionSettings = (...args) => svc.getConnectionSettings(...args);
isAirtrailWriteEnabled = (...args) => svc.isAirtrailWriteEnabled(...args);
saveSettings = (...args) => svc.saveSettings(...args);
});
describe('airtrail writeback opt-in persistence (#1240)', () => {
it('defaults the writeback opt-in to off for a new user', async () => {