mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 13:23:04 +00:00
fix(server): non-HTTP entrypoints run inside an ORM request context; permission loads fail closed on context errors
This commit is contained in:
@@ -91,7 +91,7 @@ export async function buildApp(): Promise<INestApplication> {
|
||||
// boot succeeds, the gateway logs as registered, every test passes, and no
|
||||
// browser can connect. Callers take the server from getHttpServer() below.
|
||||
boundHttpServer = nodeHttp.createServer(instance);
|
||||
app.useWebSocketAdapter(new TrekWsAdapter(boundHttpServer));
|
||||
app.useWebSocketAdapter(new TrekWsAdapter(boundHttpServer, orm));
|
||||
// ConfigModule.forRoot's load factories already ran inside NestFactory.create,
|
||||
// so the boot-stable snapshot is resolvable here, BEFORE app.init() — this is
|
||||
// the one bridge that lets the pre-init Express layer consume the validated
|
||||
|
||||
@@ -6,6 +6,12 @@ import { DEMO_PASS } from '../nest/common/demo';
|
||||
// touches the database happens inside the functions.
|
||||
import { saveBaseline, hasBaseline } from './demo-reset';
|
||||
|
||||
// D6 (task-2-review.md's controller ruling / non-HTTP caller table): this runs
|
||||
// from `runSchemaBootstrap` before `app.init()`, outside any request context, but
|
||||
// it is all raw `better-sqlite3` through the `db` param passed in — no
|
||||
// InjectRepository/global-EM read — so there is nothing to wrap yet. The domain
|
||||
// phase that gives demo seeding a repository read must wrap it in
|
||||
// withRequestContext then.
|
||||
function seedDemoData(db: Database.Database): { adminId: number; demoId: number } {
|
||||
const ADMIN_USER = readEnv().demo.adminUser;
|
||||
const ADMIN_EMAIL = readEnv().demo.adminEmailRaw || 'admin@trek.app';
|
||||
|
||||
@@ -283,6 +283,15 @@ export class McpRegistry {
|
||||
return this.accessPolicy(access, ctx);
|
||||
}
|
||||
|
||||
// D6: this callback is invoked from inside McpTransportController's @Post/@Get/
|
||||
// @Delete handlers (mcp-transport.controller.ts), which are ordinary Nest routes —
|
||||
// `@Public()` only exempts the auth guard, and the raw-body parser exemption in
|
||||
// bootstrap.ts only exempts Express's JSON/urlencoded parsers. Neither opts /mcp out
|
||||
// of `@mikro-orm/nestjs`'s per-request middleware (registerRequestContext, on by
|
||||
// default and not overridden in mikro-orm.config.ts), which forks the EntityManager
|
||||
// before any controller method runs. So a tool handler here already runs inside a
|
||||
// request context; do not wrap it in withRequestContext (task-2-review.md's
|
||||
// non-HTTP caller table confirms this path is already covered).
|
||||
private attachTool(
|
||||
registrar: LooseRegistrar,
|
||||
options: ToolOptions,
|
||||
|
||||
@@ -21,6 +21,9 @@ export class DemoResetJob implements OnApplicationBootstrap {
|
||||
|
||||
onApplicationBootstrap(): void {
|
||||
if (!this.registrar.isEnabled() || !this.runtimeEnv.isDemoMode()) return;
|
||||
// D6: resetDemoUser is all raw better-sqlite3 (see demo-reset.ts) — no
|
||||
// repository read today — but the tick already runs inside a request context
|
||||
// regardless, via CronRegistrarService's one wrapper around every onTick.
|
||||
this.registrar.register('demo-reset', '0 * * * *', () => void this.tick(), { timezone: 'none' });
|
||||
logInfo('Demo hourly reset scheduled');
|
||||
}
|
||||
|
||||
@@ -507,6 +507,11 @@ export async function restoreFromZip(storage: StorageService, zipPath: string):
|
||||
// still holds the pre-restore state. Any request using a cached
|
||||
// permission would decide against the wrong grants until the
|
||||
// next restart. Dropping the cache forces a fresh read.
|
||||
// D6: no repository read happens on this path today — invalidation is a
|
||||
// plain function, not a DB call — so no withRequestContext is owed here yet.
|
||||
// The domain phase that gives this restore path a repository read (Plan 3's
|
||||
// admin/backup cluster) must wrap it then; see task-2-review.md's non-HTTP
|
||||
// caller table.
|
||||
invalidatePermissionsCache();
|
||||
}
|
||||
|
||||
@@ -573,6 +578,8 @@ export async function restoreFromZip(storage: StorageService, zipPath: string):
|
||||
// stale anyway. Invalidating here too costs nothing and guarantees
|
||||
// we never serve cached permissions that don't match the DB state
|
||||
// we leave the process in after a failed restore.
|
||||
// D6: same no-repository-read note as the other invalidatePermissionsCache()
|
||||
// call above — nothing to wrap yet.
|
||||
try { invalidatePermissionsCache(); } catch { /* best-effort */ }
|
||||
throw err;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,11 @@ export class IdempotencyCleanupJob implements OnApplicationBootstrap {
|
||||
|
||||
onApplicationBootstrap(): void {
|
||||
if (!this.registrar.isEnabled()) return;
|
||||
// D6: `tick()` still reads/writes through raw `DatabaseService.prepare` (see
|
||||
// `purgeExpiredIdempotencyKeys`), but the tick itself already runs inside a
|
||||
// request context — CronRegistrarService.register wraps every job's onTick in
|
||||
// one place, so this needs no wrapper of its own even once it gains a
|
||||
// repository read.
|
||||
this.registrar.register('idempotency-cleanup', '0 3 * * *', () => this.tick());
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,8 @@ import { RealtimeService } from '../realtime/realtime.service';
|
||||
|
||||
/**
|
||||
* The impure MCP tool guards that used to live as plain functions in
|
||||
* src/mcp/tools/_shared.ts, reaching the db Proxy, permissions.bridge and the
|
||||
* src/mcp/tools/_shared.ts, reaching the db Proxy, a permissions.bridge
|
||||
* instance (no longer exists — see auth.service.ts:116) and the
|
||||
* src/websocket stub as module globals. The @McpController domain classes are
|
||||
* ordinary Nest providers, so they inject this instead. The pure result
|
||||
* helpers (noAccess/permissionDenied/adminRequired and the
|
||||
|
||||
@@ -3,12 +3,13 @@ import type { PermissionLevel } from './permissions.service';
|
||||
/**
|
||||
* The permissions cache — module state on purpose, in its own home (the
|
||||
* oauth.pending-codes.ts precedent) so every path that must see one shared
|
||||
* cache actually does: the container PermissionsService singleton, the
|
||||
* permissions.bridge instance the MCP _shared helper reaches, and the plain
|
||||
* backup restore path (backup.impl.ts), which is free functions by design and
|
||||
* has nothing to hang an injected service off. A restore rewrites
|
||||
* app_settings under the request path's feet; invalidating here is what keeps
|
||||
* every reader consistent afterwards.
|
||||
* cache actually does: the container PermissionsService singleton (the MCP
|
||||
* _shared helper reaches it through injection, not a separate bridge
|
||||
* instance — permissions.bridge no longer exists, see auth.service.ts:116),
|
||||
* and the plain backup restore path (backup.impl.ts), which is free
|
||||
* functions by design and has nothing to hang an injected service off. A
|
||||
* restore rewrites app_settings under the request path's feet; invalidating
|
||||
* here is what keeps every reader consistent afterwards.
|
||||
*/
|
||||
let cache: Map<string, PermissionLevel> | null = null;
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { ValidationError } from '@mikro-orm/core';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { logError } from '../audit/audit-log.logger';
|
||||
import { AppSettings } from '../../db/entities/AppSettings.entity';
|
||||
@@ -67,12 +68,13 @@ export const PERMISSION_ACTIONS: PermissionAction[] = [
|
||||
const ACTIONS_MAP = new Map(PERMISSION_ACTIONS.map(a => [a.key, a]));
|
||||
|
||||
// The in-memory cache is deliberately MODULE-scoped, not instance state, and
|
||||
// lives in ./permissions-cache: two service instances exist at runtime (the
|
||||
// container singleton and the permissions.bridge instance for
|
||||
// out-of-container consumers), and the backup restore path — plain functions,
|
||||
// no DI — must flush the same cache the request path reads. Both instances
|
||||
// wrap the same shared connection, so a single cache is also the correct
|
||||
// data shape.
|
||||
// lives in ./permissions-cache: the container's PermissionsService singleton
|
||||
// is not the only reader — the backup restore path (backup.impl.ts) is plain
|
||||
// functions, no DI, and must flush the same cache the request path reads.
|
||||
// Both reach the same shared connection, so a single cache is also the
|
||||
// correct data shape. (permissions.bridge, once a second out-of-container
|
||||
// instance, was replaced by injection — see auth.service.ts:116 — and no
|
||||
// longer exists.)
|
||||
|
||||
@Injectable()
|
||||
export class PermissionsService {
|
||||
@@ -88,6 +90,10 @@ export class PermissionsService {
|
||||
try {
|
||||
const rows = await this.appSettings.findByKeyPrefix('perm_');
|
||||
for (const row of rows) {
|
||||
// A typing artefact, not a parity change: AppSettingsRow types both
|
||||
// columns nullable, but `key` can never actually be null here (a NULL
|
||||
// key never matches `LIKE 'perm_%'`), and skipping a null `value` is
|
||||
// exactly the legacy `allowedLevels.includes(null) === false` skip.
|
||||
if (row.key == null || row.value == null) continue;
|
||||
const actionKey = row.key.replace('perm_', '');
|
||||
const action = ACTIONS_MAP.get(actionKey);
|
||||
@@ -100,6 +106,16 @@ export class PermissionsService {
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// A MikroORM ValidationError here (typically cannotUseGlobalContext) is not
|
||||
// a DB failure — it means this call reached the repository outside any
|
||||
// request context (D6: a non-HTTP entrypoint that isn't wrapped in
|
||||
// withRequestContext, or a bug in one that is). Serving defaults for that
|
||||
// is fail-OPEN: an admin who tightened a flag from its default gets the
|
||||
// looser default back, silently, for as long as the misuse persists
|
||||
// (task-2-review.md C3). A programming error rethrows instead of degrading;
|
||||
// the same rule applies to any later "log and serve defaults" branch this
|
||||
// plan adds (AddonsService's flag reads are Task 4's, not touched here).
|
||||
if (e instanceof ValidationError) throw e;
|
||||
// Under the legacy better-sqlite3 path a "no such table" error meant
|
||||
// first-boot init racing this read, before the table existed, and was
|
||||
// swallowed silently. Under the ORM, migrations run to completion in
|
||||
@@ -107,6 +123,10 @@ export class PermissionsService {
|
||||
// this service — there is no window left where app_settings can be
|
||||
// missing — so that message match is dropped and every failure here is
|
||||
// now a real, loggable DB error; defaults are still served either way.
|
||||
// One residual window this doesn't cover: backup.impl.ts's restore swaps
|
||||
// the database file under a live process, so a concurrent load can still
|
||||
// see a missing/mid-swap table and will now log here — behaviour
|
||||
// (defaults, uncached) is unchanged, so it is log noise only.
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
logError(`Permissions load failed: ${msg}`);
|
||||
// Serve defaults for THIS call, but do not install them: a half-built
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable, type OnApplicationBootstrap, type OnModuleDestroy } from '@nestjs/common';
|
||||
import semver from 'semver';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { pluginsEnabled } from './kill-switch';
|
||||
@@ -130,7 +131,9 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
|
||||
// plugin's ctx.plugins.call / ctx.events.emit resolve through callPlugin/
|
||||
// emitPluginEvent below (which own the dependency-edge authorization). The
|
||||
// arrow reads this.hostFactory lazily at spawn time, so the field-initializer
|
||||
// ordering (it runs before the constructor params are assigned) is safe.
|
||||
// ordering (it runs before the constructor params are assigned) is safe. `orm`
|
||||
// (D6, task-2-review.md C3) needs the same laziness — it is read once per RPC
|
||||
// dispatch, well after the constructor has run, not at field-init time.
|
||||
private readonly supervisor = new PluginSupervisor((id, granted) => {
|
||||
if (!this.hostFactory) throw new Error('PluginRpcHostFactory not provided — tests that activate plugins must pass one');
|
||||
return this.hostFactory.create(id, granted, this);
|
||||
@@ -158,7 +161,7 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
|
||||
void this.pruneErrorLog(id).catch(() => { /* retention is best-effort */ });
|
||||
} catch { /* DB unavailable — a log line must never crash the host */ }
|
||||
},
|
||||
});
|
||||
}, {}, () => this.orm);
|
||||
|
||||
// Filesystem watchers for dev-linked plugins (id -> watcher), so a rebuild of the
|
||||
// author's source auto-reloads. Empty unless dev-link is used.
|
||||
@@ -188,6 +191,12 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
|
||||
// test instance that exercises a transaction must pass one; setOperatorEgressHosts
|
||||
// refuses rather than writing outside a transaction (same shape as hostFactory).
|
||||
private readonly uow?: UnitOfWork,
|
||||
// D6 (task-2-review.md C3): the supervisor wraps every plugin RPC dispatch in a
|
||||
// request context built from this. Nest always injects it (MikroOrmCoreModule is
|
||||
// global); a hand-built test instance that dispatches through a real
|
||||
// PermissionsService/repository must pass one or those reads fail closed with
|
||||
// cannotUseGlobalContext instead of running.
|
||||
private readonly orm?: MikroORM,
|
||||
) {}
|
||||
|
||||
private get db() {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import fs from 'node:fs';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { fork, type ChildProcess } from 'node:child_process';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
import { readEnv } from '../../../app-config';
|
||||
import { resolveChildEntry, pluginCodeDir, pluginRealCodeDir, pluginPermissionArgs, ensurePluginModuleType } from '../paths';
|
||||
import { HOOK_PERMISSION, USER_DATA_PERMISSION, EVENTS_PERMISSION, type Envelope, type RpcError, type RpcRequest } from '../protocol/envelope';
|
||||
@@ -8,6 +9,7 @@ import type { PluginRpcHost } from '../host/rpc-host';
|
||||
import { scheduleJobs, stopJobs, type ScheduledJob } from '../host/plugin-jobs';
|
||||
import { SNAPSHOT_GRANT, type PluginEventMeta } from '../../../plugin-event-sink';
|
||||
import { RpcRateLimiter, DEFAULT_RPC_LIMIT, TokenBucket, DEFAULT_LOG_LIMIT } from '../host/rate-limit';
|
||||
import { withRequestContext } from '../../database/request-context';
|
||||
|
||||
export interface PluginRouteInfo {
|
||||
i: number;
|
||||
@@ -113,6 +115,16 @@ export class PluginSupervisor {
|
||||
private readonly createRpcHost: (id: string, granted: ReadonlySet<string>) => PluginRpcHost,
|
||||
private readonly hooks: SupervisorHooks = {},
|
||||
tuning: SupervisorTuning = {},
|
||||
// D6: every `ctx.*` call from a plugin child arrives over IPC, not an HTTP
|
||||
// request, so nothing has forked an EntityManager for it. A THUNK, not a value:
|
||||
// PluginRuntimeService's own `orm` field is not assigned yet when its `supervisor`
|
||||
// field initializer runs (constructor params are assigned after field
|
||||
// initializers — see that file's comment), so this is read lazily, once per
|
||||
// dispatch. Optional only so the hand-built doubles in
|
||||
// supervisor-lifecycle.test.ts / provider-hook-grant.test.ts /
|
||||
// event-subscriptions.test.ts (none of which reach a repository) don't need one;
|
||||
// PluginRuntimeService always passes the real MikroORM (OrmModule is global).
|
||||
private readonly resolveOrm?: () => { em: EntityManager } | undefined,
|
||||
) {
|
||||
this.tuning = { ...DEFAULTS, ...tuning };
|
||||
}
|
||||
@@ -550,7 +562,16 @@ export class PluginSupervisor {
|
||||
const inv = req.params as { _inv?: unknown } | undefined;
|
||||
const actingUserId = typeof inv?._inv === 'string' ? sup.invocations.get(inv._inv) : undefined;
|
||||
try {
|
||||
const res = await sup.rpcHost.dispatch(req, actingUserId);
|
||||
// The single choke point every plugin RPC passes through (D6): wrap it here,
|
||||
// not inside rpc-host.ts::dispatch, so the context also spans plugin-guards'
|
||||
// trip/permission reads and any *.rpc.ts handler's repository calls, not just
|
||||
// dispatch's own audit write. Without this, PermissionsService.checkPermission
|
||||
// ran outside any context, threw on a cold cache, and the catch served
|
||||
// defaults — fail-open on a tightened flag (task-2-review.md C3).
|
||||
const orm = this.resolveOrm?.();
|
||||
const res = orm
|
||||
? await withRequestContext(orm, () => sup.rpcHost.dispatch(req, actingUserId))
|
||||
: await sup.rpcHost.dispatch(req, actingUserId);
|
||||
sup.child?.send(res);
|
||||
} finally {
|
||||
sup.rpcLimiter.release();
|
||||
|
||||
@@ -4,9 +4,11 @@ import type { Server as HttpServer } from 'node:http';
|
||||
import type { MessageMappingProperties } from '@nestjs/websockets';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import type { Observable } from 'rxjs';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
import { readEnv } from '../../app-config';
|
||||
import { setServer, type TrekWebSocket } from './ws-state';
|
||||
import { logError } from '../audit/audit-log.logger';
|
||||
import { withRequestContext } from '../database/request-context';
|
||||
|
||||
// Per-connection message rate limiting. It lives in the adapter, not in the
|
||||
// gateway's handlers, because the original counted EVERY inbound frame before
|
||||
@@ -98,7 +100,15 @@ export class TrekWsAdapter extends WsAdapter {
|
||||
* server lands on the socket this process actually listens on. Given the app,
|
||||
* it would reach for Nest's own internal server, which buildApp never uses.
|
||||
*/
|
||||
constructor(httpServer: HttpServer) {
|
||||
constructor(
|
||||
httpServer: HttpServer,
|
||||
// D6 (task-2-review.md's controller ruling): a WS message handler has no HTTP
|
||||
// request behind it, so every `@SubscribeMessage` dispatch is wrapped here —
|
||||
// ONE wrapper at bindMessageHandlers below, not one per handler. Optional only
|
||||
// for trek-ws-adapter.test.ts, which never reaches a repository; bootstrap.ts
|
||||
// always passes the real MikroORM.
|
||||
private readonly orm?: { em: EntityManager },
|
||||
) {
|
||||
super(httpServer as unknown as INestApplicationContext);
|
||||
this.httpServerRef = httpServer;
|
||||
}
|
||||
@@ -203,7 +213,16 @@ export class TrekWsAdapter extends WsAdapter {
|
||||
|
||||
// The whole message is the payload: TREK's frames are flat, so `tripId`
|
||||
// sits beside `type` rather than under a `data` key.
|
||||
transform(handler.callback(message, socket)).subscribe({
|
||||
//
|
||||
// The context has to wrap the CALL, not just the subscribe(): an async
|
||||
// handler's body runs synchronously up to its first await the instant it is
|
||||
// invoked (before transform()/subscribe() ever run), and RequestContext.create
|
||||
// is AsyncLocalStorage.run — it only covers what executes inside this
|
||||
// synchronous frame, after which the async chain carries it on its own.
|
||||
const result = this.orm
|
||||
? withRequestContext(this.orm, () => handler.callback(message, socket))
|
||||
: handler.callback(message, socket);
|
||||
transform(result).subscribe({
|
||||
next: (response) => {
|
||||
if (response !== undefined && socket.readyState === 1) {
|
||||
socket.send(JSON.stringify(response));
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Injectable, type OnApplicationShutdown } from '@nestjs/common';
|
||||
import { Injectable, Optional, type OnApplicationShutdown } from '@nestjs/common';
|
||||
import { SchedulerRegistry } from '@nestjs/schedule';
|
||||
import { CronJob } from 'cron';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { readEnv } from '../../app-config';
|
||||
import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
import { withRequestContext } from '../database/request-context';
|
||||
|
||||
/**
|
||||
* The one way TREK code schedules a cron. Job providers register here from
|
||||
@@ -35,6 +37,18 @@ export class CronRegistrarService implements OnApplicationShutdown {
|
||||
constructor(
|
||||
private readonly registry: SchedulerRegistry,
|
||||
private readonly runtimeEnv: RuntimeEnvService,
|
||||
// D6 (task-2-review.md's controller ruling): a cron tick has no HTTP request
|
||||
// behind it, so every job's onTick is wrapped in a request context here — the
|
||||
// ONE place, rather than in each of the 14 `*.job.ts` providers. `@Optional()`
|
||||
// (not just a `?`, which is TS-only and does not tell Nest's DI the provider
|
||||
// may be absent) because SchedulingModule is deliberately NOT @Global (see
|
||||
// this module's own docstring): the e2e suites boot partial graphs — one
|
||||
// domain module + SchedulingModule, no MikroOrmModule.forRoot — so a hard
|
||||
// MikroORM dependency here would fail every one of them at compile(), the
|
||||
// same class of break `@InjectRepository` would cause. Production (buildApp)
|
||||
// always has it; a hand-built test instance that registers a job touching a
|
||||
// repository must pass one, same as the unit test doubles below.
|
||||
@Optional() private readonly orm?: MikroORM,
|
||||
) {}
|
||||
|
||||
/** False under NODE_ENV=test — the single gate keeping the suites timer-free. */
|
||||
@@ -56,7 +70,9 @@ export class CronRegistrarService implements OnApplicationShutdown {
|
||||
this.unregister(name);
|
||||
if (!this.isEnabled()) return false;
|
||||
const timeZone = opts?.timezone === 'none' ? undefined : readEnv().app.tz || 'UTC';
|
||||
const job = CronJob.from({ cronTime: expression, onTick, start: true, timeZone });
|
||||
const orm = this.orm;
|
||||
const wrappedTick = orm ? () => withRequestContext(orm, () => onTick()) : onTick;
|
||||
const job = CronJob.from({ cronTime: expression, onTick: wrappedTick, start: true, timeZone });
|
||||
this.registry.addCronJob(name, job);
|
||||
this.names.add(name);
|
||||
return true;
|
||||
|
||||
Reference in New Issue
Block a user