mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 15:17:30 +00:00
fix(server): fix the quirks preserved by the permissions and auditLog DI migrations
Permissions: stored levels are validated at load (corrupt/out-of-range rows fall back to the default consistently across all readers), the load-error swallow is narrowed to missing-table (anything else logs), and an all-skipped save no longer opens a transaction or flushes the cache. The module-scoped cache stays by design (shared DI+bridge invalidation), and the checkPermission 'admin' case stays — it is reachable (correct deny for non-admins on admin-level actions), not dead code. Audit: data/logs creation is lazy (no import-time disk side effect; the LOG_LEVEL freeze remains — tests/setup.ts timing contract), the log helpers gate on a real severity threshold (error < warn < info < debug; prod default 'info' unchanged), file-IO failures leave a console.error trace instead of vanishing in bare catches, and resolveUserEmail treats only null/undefined as anonymous so a real id 0 resolves via the DB.
This commit is contained in:
@@ -3,15 +3,20 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
/**
|
||||
* The server's rotating file logger — a plain, deliberately side-effectful
|
||||
* module, NOT an injectable. This is a documented parity exception to the
|
||||
* "importable without side effects" rule: index.ts lazy-requires it before any
|
||||
* Nest container exists (boot ordering), and tests/setup.ts relies on env
|
||||
* being read exactly once at first import (the LOG_LEVEL freeze below).
|
||||
* The server's rotating file logger — a plain module, NOT an injectable
|
||||
* (index.ts lazy-requires it before any Nest container exists). Directory
|
||||
* creation is lazy (first write), so importing the module has no disk side
|
||||
* effect; the LOG_LEVEL freeze below is the one deliberate import-time
|
||||
* behavior and is load-bearing for tests/setup.ts.
|
||||
*/
|
||||
|
||||
// Frozen at import on purpose (legacy timing; tests/setup.ts sets it pre-import).
|
||||
const LOG_LEVEL = (readEnv().app.logLevel || 'info').toLowerCase();
|
||||
// Severity threshold: a level logs only if it is at or above LOG_LEVEL's rank
|
||||
// (error < warn < info < debug). Unknown values fall back to 'info', matching
|
||||
// the legacy default.
|
||||
const LEVEL_RANKS: Record<string, number> = { error: 0, warn: 1, info: 2, debug: 3 };
|
||||
const LOG_THRESHOLD = LEVEL_RANKS[LOG_LEVEL] ?? LEVEL_RANKS.info;
|
||||
const MAX_LOG_SIZE = 10 * 1024 * 1024; // 10 MB
|
||||
const MAX_LOG_FILES = 5;
|
||||
|
||||
@@ -26,8 +31,18 @@ const C = {
|
||||
// ── File logger with rotation ─────────────────────────────────────────────
|
||||
|
||||
const logsDir = path.join(process.cwd(), 'data/logs');
|
||||
try { fs.mkdirSync(logsDir, { recursive: true }); } catch {}
|
||||
const logFilePath = path.join(logsDir, 'trek.log');
|
||||
let logsDirReady = false;
|
||||
|
||||
function ensureLogsDir(): void {
|
||||
if (logsDirReady) return;
|
||||
try {
|
||||
fs.mkdirSync(logsDir, { recursive: true });
|
||||
logsDirReady = true;
|
||||
} catch (e) {
|
||||
console.error(`[logger] could not create ${logsDir}: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
}
|
||||
|
||||
function rotateIfNeeded(): void {
|
||||
try {
|
||||
@@ -40,14 +55,19 @@ function rotateIfNeeded(): void {
|
||||
const dst = `${logFilePath}.${i}`;
|
||||
if (fs.existsSync(src)) fs.renameSync(src, dst);
|
||||
}
|
||||
} catch {}
|
||||
} catch (e) {
|
||||
console.error(`[logger] log rotation failed: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
}
|
||||
|
||||
function writeToFile(line: string): void {
|
||||
try {
|
||||
ensureLogsDir();
|
||||
rotateIfNeeded();
|
||||
fs.appendFileSync(logFilePath, line + '\n');
|
||||
} catch {}
|
||||
} catch (e) {
|
||||
console.error(`[logger] log file write failed: ${e instanceof Error ? e.message : e}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Public log helpers ────────────────────────────────────────────────────
|
||||
@@ -58,13 +78,14 @@ function formatTs(): string {
|
||||
}
|
||||
|
||||
export function logInfo(msg: string): void {
|
||||
if (LOG_THRESHOLD < LEVEL_RANKS.info) return;
|
||||
const ts = formatTs();
|
||||
console.log(`${C.blue}[INFO]${C.reset} ${ts} ${msg}`);
|
||||
writeToFile(`[INFO] ${ts} ${msg}`);
|
||||
}
|
||||
|
||||
export function logDebug(msg: string): void {
|
||||
if (LOG_LEVEL !== 'debug') return;
|
||||
if (LOG_THRESHOLD < LEVEL_RANKS.debug) return;
|
||||
const ts = formatTs();
|
||||
console.log(`${C.cyan}[DEBUG]${C.reset} ${ts} ${msg}`);
|
||||
writeToFile(`[DEBUG] ${ts} ${msg}`);
|
||||
@@ -77,6 +98,7 @@ export function logError(msg: string): void {
|
||||
}
|
||||
|
||||
export function logWarn(msg: string): void {
|
||||
if (LOG_THRESHOLD < LEVEL_RANKS.warn) return;
|
||||
const ts = formatTs();
|
||||
console.warn(`${C.yellow}[WARN]${C.reset} ${ts} ${msg}`);
|
||||
writeToFile(`[WARN] ${ts} ${msg}`);
|
||||
|
||||
@@ -49,7 +49,7 @@ export class AuditService {
|
||||
constructor(private readonly dbs: DatabaseService) {}
|
||||
|
||||
private resolveUserEmail(userId: number | null): string {
|
||||
if (!userId) return 'anonymous';
|
||||
if (userId == null) return 'anonymous';
|
||||
try {
|
||||
const row = this.dbs.get<{ email: string }>('SELECT email FROM users WHERE id = ?', userId);
|
||||
return row?.email || `uid:${userId}`;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { logError } from '../audit/audit-log.logger';
|
||||
|
||||
/**
|
||||
* Permission levels (hierarchical, higher includes lower):
|
||||
@@ -78,11 +79,21 @@ export class PermissionsService {
|
||||
);
|
||||
for (const row of rows) {
|
||||
const actionKey = row.key.replace('perm_', '');
|
||||
if (ACTIONS_MAP.has(actionKey)) {
|
||||
const action = ACTIONS_MAP.get(actionKey);
|
||||
// Only cache values the action actually allows: a corrupt/empty stored
|
||||
// level would otherwise deny in checkPermission while getAllPermissions
|
||||
// displays the default — ignoring it makes every reader fall back to
|
||||
// the default consistently.
|
||||
if (action && action.allowedLevels.includes(row.value as PermissionLevel)) {
|
||||
cache.set(actionKey, row.value as PermissionLevel);
|
||||
}
|
||||
}
|
||||
} catch { /* table might not exist yet during init */ }
|
||||
} catch (e) {
|
||||
// Missing table is expected during first-boot init; anything else is a
|
||||
// real DB failure that must not stay invisible (we still serve defaults).
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
if (!msg.includes('no such table')) logError(`Permissions load failed: ${msg}`);
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
|
||||
@@ -109,14 +120,20 @@ export class PermissionsService {
|
||||
|
||||
savePermissions(settings: Record<string, string>): { skipped: string[] } {
|
||||
const skipped: string[] = [];
|
||||
const valid: Array<[string, string]> = [];
|
||||
for (const [actionKey, level] of Object.entries(settings)) {
|
||||
const action = ACTIONS_MAP.get(actionKey);
|
||||
if (!action || !action.allowedLevels.includes(level as PermissionLevel)) {
|
||||
skipped.push(actionKey);
|
||||
continue;
|
||||
}
|
||||
valid.push([actionKey, level]);
|
||||
}
|
||||
// Nothing valid to write → no prepare, no transaction, no cache flush.
|
||||
if (valid.length === 0) return { skipped };
|
||||
const upsert = this.dbs.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)');
|
||||
this.dbs.transaction(() => {
|
||||
for (const [actionKey, level] of Object.entries(settings)) {
|
||||
const action = ACTIONS_MAP.get(actionKey);
|
||||
if (!action || !action.allowedLevels.includes(level as PermissionLevel)) {
|
||||
skipped.push(actionKey);
|
||||
continue;
|
||||
}
|
||||
for (const [actionKey, level] of valid) {
|
||||
upsert.run(`perm_${actionKey}`, level);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
/**
|
||||
* Unit tests for nest/audit/audit-log.logger — AUDIT-LOG-001 through
|
||||
* AUDIT-LOG-007. The logger is the deliberately side-effectful plain module
|
||||
* carved out of the legacy services/auditLog.ts (frozen LOG_LEVEL, import-time
|
||||
* mkdir, 10 MB × 5 rotation); it sits inside the src/nest/** coverage gate, so
|
||||
* its branches are pinned here with fs fully mocked.
|
||||
* AUDIT-LOG-009. The logger is the plain module carved out of the legacy
|
||||
* services/auditLog.ts; since the quirk-fix pass it has a real severity
|
||||
* threshold (error < warn < info < debug) against the import-frozen LOG_LEVEL,
|
||||
* lazy data/logs creation (no import-time mkdir), and console.error fallbacks
|
||||
* for file-IO failures. It sits inside the src/nest/** coverage gate, so its
|
||||
* branches are pinned here with fs fully mocked.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
@@ -30,47 +32,76 @@ beforeEach(() => {
|
||||
mocked.statSync.mockReturnValue({ size: 0 } as unknown as ReturnType<typeof fs.statSync>);
|
||||
});
|
||||
|
||||
describe('log levels + line format', () => {
|
||||
it('AUDIT-LOG-001: logInfo writes the ANSI console line and the plain file line', () => {
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
logInfo('hello');
|
||||
expect(log).toHaveBeenCalledTimes(1);
|
||||
const consoleLine = String(log.mock.calls[0][0]);
|
||||
expect(consoleLine.startsWith('\x1b[34m[INFO]\x1b[0m ')).toBe(true);
|
||||
expect(consoleLine).toMatch(/ \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} hello$/);
|
||||
expect(mocked.appendFileSync).toHaveBeenCalledTimes(1);
|
||||
expect(String(mocked.appendFileSync.mock.calls[0][1])).toMatch(/^\[INFO\] \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} hello\n$/);
|
||||
});
|
||||
// tests/setup.ts sets LOG_LEVEL=error before the first import, so the statically
|
||||
// imported helpers run at the most restrictive threshold; the fresh-import cases
|
||||
// below exercise the other levels.
|
||||
async function freshLogger(level: string) {
|
||||
vi.resetModules();
|
||||
vi.stubEnv('LOG_LEVEL', level);
|
||||
return import('../../../src/nest/audit/audit-log.logger');
|
||||
}
|
||||
|
||||
it('AUDIT-LOG-002: logError/logWarn use console.error/console.warn with their tags', () => {
|
||||
describe('severity threshold (frozen at import)', () => {
|
||||
it('AUDIT-LOG-001: at LOG_LEVEL=error only logError writes (console + file)', () => {
|
||||
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
logError('boom');
|
||||
logWarn('careful');
|
||||
expect(err.mock.calls[0][0]).toContain('[ERROR]');
|
||||
expect(warn.mock.calls[0][0]).toContain('[WARN]');
|
||||
expect(String(mocked.appendFileSync.mock.calls[0][1])).toMatch(/^\[ERROR\] /);
|
||||
expect(String(mocked.appendFileSync.mock.calls[1][1])).toMatch(/^\[WARN\] /);
|
||||
});
|
||||
|
||||
it('AUDIT-LOG-003: logDebug is gated by the import-frozen LOG_LEVEL (tests/setup.ts sets "error")', () => {
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
expect(LOG_LEVEL).toBe('error');
|
||||
logDebug('invisible');
|
||||
logInfo('nope');
|
||||
logWarn('nope');
|
||||
logDebug('nope');
|
||||
expect(log).not.toHaveBeenCalled();
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
expect(mocked.appendFileSync).not.toHaveBeenCalled();
|
||||
logError('boom');
|
||||
const consoleLine = String(err.mock.calls[0][0]);
|
||||
expect(consoleLine.startsWith('\x1b[31m[ERROR]\x1b[0m ')).toBe(true);
|
||||
expect(consoleLine).toMatch(/ \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} boom$/);
|
||||
expect(String(mocked.appendFileSync.mock.calls[0][1])).toMatch(/^\[ERROR\] \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} boom\n$/);
|
||||
});
|
||||
|
||||
it('AUDIT-LOG-004: the freeze happens at first import — a debug-env reimport logs debug lines', async () => {
|
||||
vi.resetModules();
|
||||
vi.stubEnv('LOG_LEVEL', 'debug');
|
||||
it('AUDIT-LOG-002: at LOG_LEVEL=debug every level logs with its tag', async () => {
|
||||
const fresh = await freshLogger('debug');
|
||||
try {
|
||||
const fresh = await import('../../../src/nest/audit/audit-log.logger');
|
||||
expect(fresh.LOG_LEVEL).toBe('debug');
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
fresh.logDebug('now visible');
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
fresh.logInfo('i');
|
||||
fresh.logDebug('d');
|
||||
fresh.logWarn('w');
|
||||
fresh.logError('e');
|
||||
expect(log.mock.calls.map((c) => String(c[0]).includes('[INFO]') || String(c[0]).includes('[DEBUG]'))).toEqual([true, true]);
|
||||
expect(String(warn.mock.calls[0][0])).toContain('[WARN]');
|
||||
expect(String(err.mock.calls[0][0])).toContain('[ERROR]');
|
||||
expect(mocked.appendFileSync).toHaveBeenCalledTimes(4);
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
}
|
||||
});
|
||||
|
||||
it('AUDIT-LOG-003: at the production default (info) info/warn log, debug does not', async () => {
|
||||
const fresh = await freshLogger('info');
|
||||
try {
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
fresh.logInfo('visible');
|
||||
fresh.logDebug('invisible');
|
||||
fresh.logWarn('visible');
|
||||
expect(log).toHaveBeenCalledTimes(1);
|
||||
expect(log.mock.calls[0][0]).toContain('[DEBUG]');
|
||||
expect(String(log.mock.calls[0][0])).toContain('[INFO]');
|
||||
expect(warn).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
}
|
||||
});
|
||||
|
||||
it('AUDIT-LOG-004: the freeze happens at first import — LOG_LEVEL reflects the env then', async () => {
|
||||
const fresh = await freshLogger('debug');
|
||||
try {
|
||||
expect(fresh.LOG_LEVEL).toBe('debug');
|
||||
expect(LOG_LEVEL).toBe('error'); // the static import stays frozen
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
@@ -78,12 +109,28 @@ describe('log levels + line format', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('rotation + resilience', () => {
|
||||
it('AUDIT-LOG-005: rotates trek.log through .1… in descending order once the cap is hit', () => {
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
describe('lazy logs dir + rotation + resilience', () => {
|
||||
it('AUDIT-LOG-005: data/logs is created lazily on the first write, not at import', async () => {
|
||||
const fresh = await freshLogger('info');
|
||||
try {
|
||||
mocked.mkdirSync.mockClear();
|
||||
expect(mocked.mkdirSync).not.toHaveBeenCalled();
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
fresh.logInfo('first write');
|
||||
expect(mocked.mkdirSync).toHaveBeenCalledTimes(1);
|
||||
fresh.logInfo('second write');
|
||||
expect(mocked.mkdirSync).toHaveBeenCalledTimes(1); // memoized
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
}
|
||||
});
|
||||
|
||||
it('AUDIT-LOG-006: rotates trek.log through .1… in descending order once the cap is hit', () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mocked.existsSync.mockReturnValue(true);
|
||||
mocked.statSync.mockReturnValue({ size: 10 * 1024 * 1024 } as unknown as ReturnType<typeof fs.statSync>);
|
||||
logInfo('rotate me');
|
||||
logError('rotate me');
|
||||
// MAX_LOG_FILES=5 → renames .3→.4, .2→.3, .1→.2, trek.log→.1 (descending).
|
||||
expect(mocked.renameSync).toHaveBeenCalledTimes(4);
|
||||
const dsts = mocked.renameSync.mock.calls.map((c) => String(c[1]));
|
||||
@@ -92,19 +139,30 @@ describe('rotation + resilience', () => {
|
||||
expect(String(mocked.renameSync.mock.calls[3][0]).endsWith('trek.log')).toBe(true);
|
||||
});
|
||||
|
||||
it('AUDIT-LOG-006: no rotation below the size cap', () => {
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
it('AUDIT-LOG-007: no rotation below the size cap', () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mocked.existsSync.mockReturnValue(true);
|
||||
mocked.statSync.mockReturnValue({ size: 10 } as unknown as ReturnType<typeof fs.statSync>);
|
||||
logInfo('small');
|
||||
logError('small');
|
||||
expect(mocked.renameSync).not.toHaveBeenCalled();
|
||||
expect(mocked.appendFileSync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('AUDIT-LOG-007: file-IO failures are swallowed (bare catch) — the console line still prints', () => {
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
it('AUDIT-LOG-008: file-write failures never throw and leave a console.error trace', () => {
|
||||
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mocked.appendFileSync.mockImplementation(() => { throw new Error('disk full'); });
|
||||
expect(() => logInfo('still up')).not.toThrow();
|
||||
expect(log).toHaveBeenCalledTimes(1);
|
||||
expect(() => logError('still up')).not.toThrow();
|
||||
// First call is the [ERROR] line itself, second is the fallback trace.
|
||||
expect(err).toHaveBeenCalledTimes(2);
|
||||
expect(String(err.mock.calls[1][0])).toBe('[logger] log file write failed: disk full');
|
||||
});
|
||||
|
||||
it('AUDIT-LOG-009: rotation failures are traced and the write still goes through', () => {
|
||||
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mocked.existsSync.mockReturnValue(true);
|
||||
mocked.statSync.mockImplementation(() => { throw new Error('stat broke'); });
|
||||
expect(() => logError('resilient')).not.toThrow();
|
||||
expect(String(err.mock.calls[1][0])).toBe('[logger] log rotation failed: stat broke');
|
||||
expect(mocked.appendFileSync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -134,16 +134,16 @@ describe('writeAudit', () => {
|
||||
expect(logDebug).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('AUDIT-SVC-010: unknown action keeps the raw key; unknown/zero/null userIds degrade', () => {
|
||||
it('AUDIT-SVC-010: unknown action keeps the raw key; empty-email/zero/null userIds resolve', () => {
|
||||
seedUser(1, 'a@b.c');
|
||||
svc.writeAudit({ userId: 1, action: 'custom.thing', ip: '9.9.9.9' });
|
||||
expect(logInfo).toHaveBeenLastCalledWith('a@b.c custom.thing ip=9.9.9.9');
|
||||
seedUser(42, ''); // falsy email → the `row?.email || uid:N` fallback
|
||||
svc.writeAudit({ userId: 42, action: 'user.login', ip: '9.9.9.9' });
|
||||
expect(logInfo).toHaveBeenLastCalledWith('uid:42 logged in ip=9.9.9.9');
|
||||
seedUser(0, 'zero@b.c'); // id 0 is falsy → audits as anonymous despite the real email
|
||||
seedUser(0, 'zero@b.c'); // since the quirk fix, a real id 0 resolves via the DB
|
||||
svc.writeAudit({ userId: 0, action: 'user.login', ip: '9.9.9.9' });
|
||||
expect(logInfo).toHaveBeenLastCalledWith('anonymous logged in ip=9.9.9.9');
|
||||
expect(logInfo).toHaveBeenLastCalledWith('zero@b.c logged in ip=9.9.9.9');
|
||||
svc.writeAudit({ userId: null, action: 'user.login', ip: '9.9.9.9' });
|
||||
expect(logInfo).toHaveBeenLastCalledWith('anonymous logged in ip=9.9.9.9');
|
||||
});
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
/**
|
||||
* Unit tests for the DI-native PermissionsService — PERM-SVC-001 through
|
||||
* PERM-SVC-020 (001–013 moved 1:1 from the legacy
|
||||
* PERM-SVC-023 (001–013 moved 1:1 from the legacy
|
||||
* tests/unit/services/permissions.test.ts, which had no case IDs — the IDs are
|
||||
* introduced with the move; 014–016 pin the cache semantics the real DB now
|
||||
* makes testable; 017–020 pin the permissions.bridge delegation and the
|
||||
* module-scoped cache shared across the DI and bridge instances). Uses a real
|
||||
* in-memory SQLite DB so the app_settings SQL is exercised faithfully.
|
||||
* module-scoped cache shared across the DI and bridge instances; 013 + 021–023
|
||||
* pin the quirk-fix pass: load-time level validation, the narrowed load-error
|
||||
* swallow, and the no-op-save early return). Uses a real in-memory SQLite DB
|
||||
* so the app_settings SQL is exercised faithfully.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
|
||||
|
||||
@@ -26,9 +28,19 @@ const { testDb, dbMock } = vi.hoisted(() => {
|
||||
});
|
||||
|
||||
vi.mock('../../../src/db/database', () => dbMock);
|
||||
// The service logs unexpected load failures via the plain audit logger.
|
||||
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import { createTables } from '../../../src/db/schema';
|
||||
import { runMigrations } from '../../../src/db/migrations';
|
||||
import { logError } from '../../../src/nest/audit/audit-log.logger';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import { PermissionsService, PERMISSION_ACTIONS } from '../../../src/nest/permissions/permissions.service';
|
||||
import {
|
||||
@@ -47,6 +59,7 @@ beforeAll(() => {
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
testDb.prepare("DELETE FROM app_settings WHERE key LIKE 'perm_%'").run();
|
||||
svc.invalidatePermissionsCache();
|
||||
});
|
||||
@@ -146,11 +159,55 @@ describe('savePermissions — invalid input is silently skipped', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkPermission — default case', () => {
|
||||
it('PERM-SVC-013: returns false when permission level is an unrecognized value', () => {
|
||||
describe('corrupt stored levels', () => {
|
||||
it('PERM-SVC-013: an unrecognized stored level is ignored — every reader falls back to the default', () => {
|
||||
testDb.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run('perm_trip_edit', 'unknown_level');
|
||||
testDb.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run('perm_trip_delete', '');
|
||||
svc.invalidatePermissionsCache();
|
||||
expect(svc.checkPermission('trip_edit', 'user', 10, 10, false)).toBe(false);
|
||||
// Since the quirk fix the corrupt rows never enter the cache, so
|
||||
// getPermissionLevel, getAllPermissions and checkPermission agree on the
|
||||
// default instead of the old display-default/deny-in-check split.
|
||||
expect(svc.getPermissionLevel('trip_edit')).toBe('trip_owner');
|
||||
expect(svc.getAllPermissions().trip_edit).toBe('trip_owner');
|
||||
expect(svc.checkPermission('trip_edit', 'user', 10, 10, false)).toBe(true); // owner passes the default
|
||||
expect(svc.checkPermission('trip_edit', 'user', 10, 20, true)).toBe(false); // member still denied
|
||||
expect(svc.getPermissionLevel('trip_delete')).toBe('trip_owner');
|
||||
});
|
||||
|
||||
it('PERM-SVC-021: a stored level outside the action\'s allowedLevels is ignored too', () => {
|
||||
// trip_edit only allows trip_owner/trip_member — a raw 'everybody' row must not widen it.
|
||||
testDb.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run('perm_trip_edit', 'everybody');
|
||||
svc.invalidatePermissionsCache();
|
||||
expect(svc.getPermissionLevel('trip_edit')).toBe('trip_owner');
|
||||
expect(svc.checkPermission('trip_edit', 'user', 10, 30, false)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('load failures', () => {
|
||||
it('PERM-SVC-022: a missing app_settings table stays silent and serves defaults; other DB failures are logged', () => {
|
||||
const bareDb = new Database(':memory:');
|
||||
const bareSvc = new PermissionsService(new DatabaseService(bareDb));
|
||||
bareSvc.invalidatePermissionsCache();
|
||||
expect(bareSvc.getPermissionLevel('trip_edit')).toBe('trip_owner');
|
||||
expect(logError).not.toHaveBeenCalled();
|
||||
// An unexpected failure (closed connection) must leave a trace.
|
||||
bareDb.close();
|
||||
bareSvc.invalidatePermissionsCache();
|
||||
expect(bareSvc.getPermissionLevel('trip_edit')).toBe('trip_owner');
|
||||
expect(logError).toHaveBeenCalledWith(expect.stringMatching(/^Permissions load failed: /));
|
||||
svc.invalidatePermissionsCache(); // don't leak the bare-DB cache to later tests
|
||||
});
|
||||
|
||||
it('PERM-SVC-023: an all-skipped save writes nothing and leaves the cache untouched', () => {
|
||||
expect(svc.getPermissionLevel('trip_edit')).toBe('trip_owner'); // prime the cache
|
||||
testDb.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run('perm_trip_edit', 'trip_member');
|
||||
const result = svc.savePermissions({ bogus: 'trip_member', trip_delete: 'trip_member' });
|
||||
expect(result.skipped).toEqual(['bogus', 'trip_delete']);
|
||||
// No valid entries → no transaction and no cache flush: the raw row above
|
||||
// stays invisible until an explicit invalidation.
|
||||
expect(svc.getPermissionLevel('trip_edit')).toBe('trip_owner');
|
||||
svc.invalidatePermissionsCache();
|
||||
expect(svc.getPermissionLevel('trip_edit')).toBe('trip_member');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user