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
@@ -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();