fix(server): non-HTTP entrypoints run inside an ORM request context; permission loads fail closed on context errors

This commit is contained in:
jubnl
2026-09-22 13:25:17 +02:00
parent 86c558cdd6
commit e9391a9ae1
23 changed files with 464 additions and 36 deletions
@@ -48,7 +48,6 @@ import { ADDON_IDS } from '../../../src/addons';
import { AirtrailClient, AirtrailRequestError, type AirtrailFlightRaw } from '../../../src/nest/integrations/airtrail.client';
import { AirtrailImportService } from '../../../src/nest/integrations/airtrail-import.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
// The permissions cache is module-scoped, so a write through any instance is
@@ -46,7 +46,6 @@ import { createMcpHarness, parseToolResult, type McpHarness } from '../../helper
import { ADDON_IDS } from '../../../src/addons';
import { addTripMember } from '../../helpers/factories';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { DEMO_EMAIL_PRIMARY } from '../../../src/nest/common/demo';
import { createTestUnitOfWork, createTestAppSettingsRepo } from '../../helpers/test-uow';
@@ -2,7 +2,6 @@ import { runMigrations } from '../../../src/db/migrations';
import { createTables } from '../../../src/db/schema';
import { invalidatePermissionsCache } from '../../../src/nest/permissions/permissions-cache';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { addTripMember, createDay, createTrip, createUser } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { resetTestDb } from '../../helpers/test-db';
@@ -40,7 +40,6 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, createDayAccommodation, createDayAssignment, addTripMember } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { AccommodationsService } from '../../../src/nest/accommodations/accommodations.service';
@@ -36,6 +36,9 @@ vi.mock('cron', () => ({
import { SchedulerRegistry } from '@nestjs/schedule';
import { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { Users } from '../../../src/db/entities/Users.entity';
function makeRegistrar(isTest: boolean) {
const registry = new SchedulerRegistry();
@@ -150,4 +153,54 @@ describe('CronRegistrarService', () => {
expect(registry.getCronJobs().size).toBe(0);
expect(registrar.jobCount).toBe(0);
});
describe('D6 request context (task-2-review.md C3 ruling)', () => {
// Global context disallowed on purpose — the production setting, like
// tests/unit/nest/database/request-context.test.ts — so a repository read
// with no wrapper around it genuinely throws, the way it would outside any
// HTTP request in production.
const testDb = createSnapshotTestDb();
let t: TestOrm;
beforeEach(async () => {
t = await createTestOrm(testDb, { allowGlobalContext: false });
});
afterEach(async () => {
await t.close();
});
it('CRONREG-010 — without MikroORM injected, a repository read inside onTick throws cannotUseGlobalContext', async () => {
const registry = new SchedulerRegistry();
const registrar = new CronRegistrarService(registry, { isTest: () => false } as RuntimeEnvService); // no orm arg
let caught: unknown;
registrar.register('job', '0 2 * * *', async () => {
try {
await t.orm.em.find(Users, {});
} catch (e) {
caught = e;
}
});
await h.jobs[0].onTick();
expect(caught).toBeInstanceOf(Error);
expect(String((caught as Error).message)).toMatch(/global (EntityManager|context)/i);
});
it('CRONREG-011 — with MikroORM injected, the SAME repository read inside onTick succeeds — the wrapper is load-bearing', async () => {
const registry = new SchedulerRegistry();
const registrar = new CronRegistrarService(registry, { isTest: () => false } as RuntimeEnvService, t.orm);
let result: unknown;
let caught: unknown;
registrar.register('job', '0 2 * * *', async () => {
try {
result = await t.orm.em.find(Users, {});
} catch (e) {
caught = e;
}
});
await h.jobs[0].onTick();
expect(caught).toBeUndefined();
expect(Array.isArray(result)).toBe(true);
});
});
});
@@ -17,6 +17,7 @@
* hand-rolled DatabaseService/all() stub.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
import { ValidationError } from '@mikro-orm/core';
// ── DB setup ──────────────────────────────────────────────────────────────────
@@ -239,6 +240,26 @@ describe('load failures', () => {
svc.invalidatePermissionsCache(); // don't leak this test's cache to later tests
});
it('PERM-SVC-025: a MikroORM ValidationError (context misuse) is a programming error and propagates, uncached — it does not get the "log and serve defaults" treatment', async () => {
// The concrete case this protects (task-2-review.md C3): checkPermission
// reached from a non-HTTP entrypoint outside any request context throws
// exactly this on a cold cache. Swallowing it and serving defaults was
// fail-open — an admin's tightened flag silently reverted to its looser
// default for as long as the misuse persisted. loadPermissions must rethrow
// instead of degrading.
const spy = vi
.spyOn(appSettings, 'findByKeyPrefix')
.mockRejectedValueOnce(ValidationError.cannotUseGlobalContext());
svc.invalidatePermissionsCache();
await expect(svc.getPermissionLevel('trip_edit')).rejects.toThrow(ValidationError);
expect(logError).not.toHaveBeenCalled();
expect(getPermissionsCache()).toBe(null);
spy.mockRestore();
svc.invalidatePermissionsCache();
});
it('PERM-SVC-023: an all-skipped save writes nothing and leaves the cache untouched', async () => {
expect(await 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');
+71 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
/**
* TrekWsAdapter: the wire protocol and the per-socket flood guard.
@@ -34,6 +34,12 @@ vi.mock('../../../src/app-config', async (importOriginal) => {
import { TrekWsAdapter } from '../../../src/nest/realtime/trek-ws.adapter';
import { getServer } from '../../../src/nest/realtime/ws-state';
import type { Server as HttpServer } from 'node:http';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestOrm } from '../../helpers/test-orm';
import { Users } from '../../../src/db/entities/Users.entity';
const testDb = createSnapshotTestDb();
afterAll(() => testDb.close());
type MessageListener = (buffer: Buffer) => void;
@@ -112,6 +118,70 @@ describe('TrekWsAdapter wire protocol', () => {
});
});
describe('TrekWsAdapter D6 request context (task-2-review.md C3 ruling)', () => {
// Global context disallowed on purpose — the production setting, like
// tests/unit/nest/database/request-context.test.ts — so a repository read
// with no wrapper around it genuinely throws, the way it would outside any
// HTTP request in production. A `@SubscribeMessage` handler has exactly that
// shape: dispatched from bindMessageHandlers below, not from an Express
// request, so nothing has forked an EntityManager for it unless the ONE
// wrapper there (not per-handler) does it.
it('WSAD-040: without MikroORM passed to the adapter, a repository read inside a handler throws cannotUseGlobalContext', async () => {
const t = await createTestOrm(testDb, { allowGlobalContext: false });
try {
let caught: unknown;
const ad = new TrekWsAdapter({} as HttpServer); // no orm
const socket = fakeSocket();
let captured: Promise<unknown> | undefined;
const capture = (v: unknown) => {
captured = v instanceof Promise ? v : Promise.resolve(v);
return { subscribe: () => {} } as never;
};
ad.bindMessageHandlers(
socket as never,
[{ message: 'join', callback: async () => {
try { await t.orm.em.find(Users, {}); } catch (e) { caught = e; }
} }] as never,
capture,
);
socket.emit('message', frame({ type: 'join', tripId: 1 }));
await captured;
expect(caught).toBeInstanceOf(Error);
expect(String((caught as Error).message)).toMatch(/global (EntityManager|context)/i);
} finally {
await t.close();
}
});
it('WSAD-041: with MikroORM passed to the adapter, the SAME repository read inside a handler succeeds — the wrapper is load-bearing', async () => {
const t = await createTestOrm(testDb, { allowGlobalContext: false });
try {
let result: unknown;
let caught: unknown;
const ad = new TrekWsAdapter({} as HttpServer, t.orm);
const socket = fakeSocket();
let captured: Promise<unknown> | undefined;
const capture = (v: unknown) => {
captured = v instanceof Promise ? v : Promise.resolve(v);
return { subscribe: () => {} } as never;
};
ad.bindMessageHandlers(
socket as never,
[{ message: 'join', callback: async () => {
try { result = await t.orm.em.find(Users, {}); } catch (e) { caught = e; }
} }] as never,
capture,
);
socket.emit('message', frame({ type: 'join', tripId: 1 }));
await captured;
expect(caught).toBeUndefined();
expect(Array.isArray(result)).toBe(true);
} finally {
await t.close();
}
});
});
describe('TrekWsAdapter flood guard', () => {
it('WSAD-010: counts EVERY frame, including the ones no handler wants', () => {
// The guard sits before parsing on purpose. Counting only the frames that
@@ -0,0 +1,132 @@
/**
* D6 regression (task-2-review.md C3): a plugin's `ctx.*` call arrives over a
* child-process `message` event, not an HTTP request, so nothing has forked an
* EntityManager for it. `PluginSupervisor.onMessage` (plugin-supervisor.ts:~553)
* is the single choke point every plugin RPC dispatch passes through, and it now
* wraps `sup.rpcHost.dispatch(...)` in `withRequestContext` there.
*
* The reviewer's probe, reproduced here through the REAL call chain
* (PluginSupervisor.onMessage → PluginGuards.canCreateAs →
* PermissionsService.checkPermission → AppSettingsRepository.findByKeyPrefix),
* not just `checkPermission` in isolation: with `perm_trip_create` tightened
* from its 'everybody' default to 'admin', a role-'user' actor's check must
* come back `false`. Before the fix (dispatch outside any context, and
* loadPermissions serving defaults on any error) it came back `true` — a
* fail-open security regression. After BOTH this round's fixes — the wrapper
* here, and `loadPermissions` rethrowing a MikroORM `ValidationError` instead
* of degrading (permissions.service.ts) — an unwrapped dispatch fails CLOSED
* (a HOST_ERROR envelope), never silently `true`.
*
* Global context is disallowed on purpose (`{ allowGlobalContext: false }`),
* like `tests/unit/nest/database/request-context.test.ts` — the production
* setting — NOT the `createTestOrm` default (`true`) that `test-uow.ts`'s
* shared helpers use to let ordinary unit tests call a repository with no
* request wrapper at all: that default would hide this exact bug.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createUser } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service';
import { PluginSupervisor } from '../../../src/nest/plugins/supervisor/plugin-supervisor';
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
import { RpcRateLimiter, DEFAULT_RPC_LIMIT } from '../../../src/nest/plugins/host/rate-limit';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
import type { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host';
import type { RpcRequest, RpcResponse, RpcError } from '../../../src/nest/plugins/protocol/envelope';
import type { EntityManager } from '@mikro-orm/core';
/** The slice of Supervisor's private `Supervised` shape a 'req' dispatch touches. */
interface DispatchEntry {
rpcHost: Pick<PluginRpcHost, 'dispatch'>;
child: { send: (msg: unknown) => void } | null;
rpcLimiter: RpcRateLimiter;
invocations: Map<string, number | undefined>;
}
/** `onMessage` is private; this is the narrowest structural view that reaches it
* without an `any` cast. */
interface SupervisorPrivate {
onMessage(sup: DispatchEntry, msg: RpcRequest): Promise<void>;
}
const testDb = createSnapshotTestDb();
let t: TestOrm;
let permissions: PermissionsService;
let guards: PluginGuards;
let userId: number;
beforeAll(async () => {
t = await createTestOrm(testDb, { allowGlobalContext: false });
const dbs = new DatabaseService(testDb);
permissions = new PermissionsService(t.repo(AppSettings) as AppSettingsRepository, new UnitOfWork(t.em));
guards = new PluginGuards(dbs, permissions, new AddonsService(dbs));
userId = createUser(testDb, { role: 'user' }).user.id;
// An admin has tightened trip_create from its 'everybody' default.
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('perm_trip_create', 'admin')").run();
});
afterAll(async () => {
await t.close();
testDb.close();
});
/**
* Wires one supervisor whose fake rpcHost.dispatch calls straight into
* PluginGuards.canCreateAs — the same chain the review traced
* (plugin-guards.service.ts:74,84 → PermissionsService.checkPermission) — and
* envelope-shapes the result exactly like the real PluginRpcHost.handle()
* catch (rpc-host.ts): a thrown error becomes a HOST_ERROR response, never an
* unhandled rejection. `resolveOrm` is the exact 4th constructor arg
* PluginRuntimeService passes in production (plugin-runtime.service.ts).
*/
function makeSupervisor(resolveOrm?: () => { em: EntityManager } | undefined) {
const sent: Array<RpcResponse | RpcError> = [];
const dispatch: PluginRpcHost['dispatch'] = async (req, actingUserId) => {
try {
const result = await guards.canCreateAs('trip_create', actingUserId as number);
return { k: 'res', id: req.id, ok: true, result };
} catch (e) {
return { k: 'res', id: req.id, ok: false, error: { code: 'HOST_ERROR', message: e instanceof Error ? e.message : String(e) } };
}
};
const createRpcHost = () => ({ dispatch }) as unknown as PluginRpcHost;
const supervisor = new PluginSupervisor(createRpcHost, {}, {}, resolveOrm) as unknown as SupervisorPrivate;
const sup: DispatchEntry = {
rpcHost: { dispatch },
child: { send: (msg) => sent.push(msg as RpcResponse | RpcError) },
rpcLimiter: new RpcRateLimiter(DEFAULT_RPC_LIMIT, Date.now()),
invocations: new Map([['inv-1', userId]]),
};
return { supervisor, sup, sent };
}
describe('PluginSupervisor request context (D6, C3)', () => {
it('CTX-PLUGIN-001: unwrapped, the RPC path fails CLOSED on a cold cache — never the old fail-open `true`', async () => {
permissions.invalidatePermissionsCache();
const { supervisor, sup, sent } = makeSupervisor(); // no resolveOrm — the bug's exact reproduction
await supervisor.onMessage(sup, { k: 'req', id: 'r1', method: 'trips.create', params: { _inv: 'inv-1' } });
expect(sent).toHaveLength(1);
const res = sent[0];
expect(res.ok).toBe(false);
if (res.ok === false) expect(res.error.message).toMatch(/global (EntityManager|context)/i);
});
it('CTX-PLUGIN-002: wrapped in withRequestContext, the same dispatch enforces the stored override — a "user" role is refused', async () => {
permissions.invalidatePermissionsCache();
const { supervisor, sup, sent } = makeSupervisor(() => t.orm);
await supervisor.onMessage(sup, { k: 'req', id: 'r2', method: 'trips.create', params: { _inv: 'inv-1' } });
expect(sent).toHaveLength(1);
const res = sent[0];
expect(res.ok).toBe(true);
if (res.ok) expect(res.result).toBe(false); // role 'user' against a stored 'admin' override
});
});