Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(plugins): harden the plugin worker sandbox (scoped env + lifecycle timeouts) (#431)

Yudhi Armyndharisc4fb4bb18b2f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index da599f93c..33442a9c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,8 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Security
+
+- Untrusted (uploaded) plugins now run with a minimal, allowlisted worker environment instead of inheriting the host process environment, so a plugin can no longer read host secrets (database/Redis credentials, the API master key and pepper, `DOCKER_HOST`) out of `process.env`. (#431)
+
### Fixed
+- A sandboxed plugin whose `load`/`onEnable`/`onDisable` hangs no longer blocks the enable/disable request (and the request behind it) indefinitely — plugin lifecycle calls are now time-bounded, and a disable always tears the worker down even if `onDisable` fails, so a misbehaving plugin can't leak its worker thread. (#431)
- Sandboxed plugins now receive `onConfigChange` (config updates reach the worker instead of being silently ignored until disable + re-enable) and have their real `healthCheck` run — `GET /plugins/:id/health` previously always returned the default "healthy" for sandboxed plugins. (#430)
- Plugin `onDisable` now runs on graceful shutdown (`OnModuleDestroy`), so stateful plugins can flush buffers / close connections / persist state instead of losing in-flight work on every restart or deploy. (#430)
- A concurrent enable of the same plugin no longer double-runs `onEnable` or double-registers its hooks (a synchronous in-progress lock rejects the racing call). (#430)
diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
index 5395a5575..c4a21e283 100644
--- a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
@@ -66,7 +66,7 @@ describe('PluginLoaderService — sandbox tier routing', () => {
expect(loader.hosts).toHaveLength(1);
expect(loader.hosts[0].load).toHaveBeenCalled();
- expect(loader.hosts[0].runLifecycle).toHaveBeenCalledWith('onEnable');
+ expect(loader.hosts[0].runLifecycle).toHaveBeenCalledWith('onEnable', expect.any(Number));
const plugin = pluginOf(loader);
expect(plugin.status).toBe(PluginStatus.ENABLED);
expect(plugin.instance).toBeNull(); // the instance lives in the worker, never in-process
@@ -80,11 +80,26 @@ describe('PluginLoaderService — sandbox tier routing', () => {
await loader.disablePlugin('p1');
- expect(host.runLifecycle).toHaveBeenCalledWith('onDisable');
+ expect(host.runLifecycle).toHaveBeenCalledWith('onDisable', expect.any(Number));
expect(host.terminate).toHaveBeenCalled();
expect(pluginOf(loader).status).toBe(PluginStatus.DISABLED);
});
+ it('force-terminates the sandbox worker even when onDisable rejects (e.g. times out)', async () => {
+ const loader = makeLoader();
+ seed(loader, { builtIn: false, instance: null });
+ await loader.enablePlugin('p1');
+ const host = loader.hosts[0];
+ host.runLifecycle.mockRejectedValueOnce(new Error("plugin worker lifecycle 'onDisable' timed out after 30000ms"));
+
+ await loader.disablePlugin('p1'); // resolves: disable is a force-teardown, not blocked by onDisable
+
+ expect(host.terminate).toHaveBeenCalled(); // worker killed despite the onDisable failure
+ expect(pluginOf(loader).status).toBe(PluginStatus.DISABLED);
+ // the host must be dropped so a misbehaving plugin can't leak its worker thread
+ expect((loader as unknown as { sandboxHosts: Map<string, unknown> }).sandboxHosts.has('p1')).toBe(false);
+ });
+
it('enables a built-in plugin in-process (no sandbox worker spawned)', async () => {
const loader = makeLoader();
const onEnable = jest.fn().mockResolvedValue(undefined);
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index 888eaad9c..a1b282d3d 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -1,5 +1,5 @@
import * as path from 'path';
-import { resolvePluginMainPath } from './plugin-loader.service';
+import { resolvePluginMainPath, buildSandboxWorkerEnv } from './plugin-loader.service';
/** Regression lock: a plugin's manifest.main must not escape its plugin directory. */
describe('resolvePluginMainPath', () => {
@@ -25,6 +25,49 @@ describe('resolvePluginMainPath', () => {
});
});
+/**
+ * Untrusted plugins run in a worker thread; the worker must NOT inherit the host's secrets. The
+ * worker env is an allowlist, not a copy of process.env.
+ */
+describe('buildSandboxWorkerEnv', () => {
+ it('forwards only the allowlisted vars and drops host secrets', () => {
+ const env = buildSandboxWorkerEnv({
+ NODE_ENV: 'production',
+ TZ: 'UTC',
+ NODE_EXTRA_CA_CERTS: '/certs/ca.pem',
+ API_MASTER_KEY: 'super-secret',
+ API_KEY_PEPPER: 'pepper',
+ DATABASE_PASSWORD: 'dbpw',
+ DATABASE_URL: 'postgres://u:p@host/db',
+ REDIS_URL: 'redis://u:p@host',
+ DOCKER_HOST: 'tcp://0.0.0.0:2375',
+ });
+
+ expect(env.NODE_ENV).toBe('production');
+ expect(env.TZ).toBe('UTC');
+ expect(env.NODE_EXTRA_CA_CERTS).toBe('/certs/ca.pem');
+
+ // Host secrets must never reach an untrusted plugin.
+ expect(env.API_MASTER_KEY).toBeUndefined();
+ expect(env.API_KEY_PEPPER).toBeUndefined();
+ expect(env.DATABASE_PASSWORD).toBeUndefined();
+ expect(env.DATABASE_URL).toBeUndefined();
+ expect(env.REDIS_URL).toBeUndefined();
+ expect(env.DOCKER_HOST).toBeUndefined();
+ });
+
+ it('omits allowlisted keys that are unset rather than emitting undefined entries', () => {
+ const env = buildSandboxWorkerEnv({ NODE_ENV: 'development' });
+ expect(env.NODE_ENV).toBe('development');
+ expect('TZ' in env).toBe(false);
+ expect('NODE_EXTRA_CA_CERTS' in env).toBe(false);
+ });
+
+ it('defaults NODE_ENV to production when the host has none', () => {
+ expect(buildSandboxWorkerEnv({}).NODE_ENV).toBe('production');
+ });
+});
+
import * as fs from 'fs';
import * as os from 'os';
import { PluginLoaderService } from './plugin-loader.service';
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 816a88988..7a4118d8a 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -33,6 +33,20 @@ const SANDBOX_MAX_OLD_GEN_MB = 256;
const SANDBOX_HOOK_TIMEOUT_MS = 5000;
/** A sandboxed plugin's healthCheck must answer within this, else it's reported unhealthy (not hung). */
const SANDBOX_HEALTH_TIMEOUT_MS = 5000;
+/**
+ * A sandboxed plugin's load()/onLoad/onEnable/onDisable must complete within this, else the worker is
+ * torn down and the operation fails — a wedged lifecycle can't hang the enable/disable request (and
+ * the ADMIN HTTP call behind it) forever. Generous on purpose: a slow-but-valid onEnable that opens
+ * connections should still finish well under it.
+ */
+const SANDBOX_LIFECYCLE_TIMEOUT_MS = 30000;
+
+/**
+ * Host process.env keys an untrusted plugin worker is allowed to see. Everything else — secrets like
+ * API_MASTER_KEY, API_KEY_PEPPER, the DATABASE_/REDIS_ vars, DOCKER_HOST — is withheld. The worker is
+ * a thread, so it needs no PATH to start and require() resolves via module paths, not env.
+ */
+const SANDBOX_ENV_ALLOWLIST = ['NODE_ENV', 'NODE_EXTRA_CA_CERTS', 'TZ'] as const;
/**
* Resolve a plugin's `main` entry to an absolute path, asserting it stays inside
@@ -48,6 +62,20 @@ export function resolvePluginMainPath(pluginsDir: string, pluginId: string, main
return mainPath;
}
+/**
+ * Build the minimal, allowlisted env for an untrusted plugin worker so it never inherits host secrets.
+ * Only {@link SANDBOX_ENV_ALLOWLIST} keys are forwarded (unset keys are omitted, not emitted as
+ * `undefined`), and NODE_ENV defaults to 'production' when the host has none.
+ */
+export function buildSandboxWorkerEnv(source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
+ const env: NodeJS.ProcessEnv = {};
+ for (const key of SANDBOX_ENV_ALLOWLIST) {
+ if (source[key] !== undefined) env[key] = source[key];
+ }
+ env.NODE_ENV = source.NODE_ENV ?? 'production';
+ return env;
+}
+
@Injectable()
export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
private readonly logger = createLogger('PluginLoaderService');
@@ -286,8 +314,19 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
try {
const host = this.sandboxHosts.get(pluginId);
if (host) {
- await host.runLifecycle('onDisable');
- await host.terminate();
+ // Disable is a force-teardown: even if the plugin's onDisable hangs (now bounded) or throws,
+ // we still kill the worker and drop the reference, so a misbehaving plugin can never block a
+ // disable or leak its worker thread.
+ try {
+ await host.runLifecycle('onDisable', SANDBOX_LIFECYCLE_TIMEOUT_MS);
+ } catch (error) {
+ this.logger.warn(`Sandboxed plugin ${pluginId} onDisable failed during disable; terminating anyway`, {
+ pluginId,
+ action: 'sandbox_disable_lifecycle_failed',
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ await host.terminate().catch(() => undefined);
this.sandboxHosts.delete(pluginId);
} else {
const context = this.createPluginContext(plugin);
@@ -497,7 +536,12 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
): PluginWorkerHost {
const workerEntry = path.join(__dirname, 'sandbox', 'worker-bootstrap.js');
return new PluginWorkerHost(
- new WorkerThreadChannel({ workerEntry, maxOldGenerationSizeMb: SANDBOX_MAX_OLD_GEN_MB }),
+ new WorkerThreadChannel({
+ workerEntry,
+ maxOldGenerationSizeMb: SANDBOX_MAX_OLD_GEN_MB,
+ // Withhold host secrets: the worker gets a minimal allowlisted env, not a copy of process.env.
+ env: buildSandboxWorkerEnv(),
+ }),
capDispatcher,
onHookSubscribe,
onLog,
@@ -585,9 +629,9 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
);
this.sandboxHosts.set(pluginId, host);
try {
- await host.load(mainPath, { pluginId, config: plugin.config });
- await host.runLifecycle('onLoad');
- await host.runLifecycle('onEnable');
+ await host.load(mainPath, { pluginId, config: plugin.config }, SANDBOX_LIFECYCLE_TIMEOUT_MS);
+ await host.runLifecycle('onLoad', SANDBOX_LIFECYCLE_TIMEOUT_MS);
+ await host.runLifecycle('onEnable', SANDBOX_LIFECYCLE_TIMEOUT_MS);
} catch (error) {
this.sandboxHosts.delete(pluginId);
await host.terminate().catch(() => undefined);
diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
index 0d3f4d751..8d497072f 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.spec.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
@@ -294,4 +294,60 @@ describe('PluginWorkerHost', () => {
await expect(host.healthCheck(1000)).resolves.toMatchObject({ healthy: false });
});
});
+
+ describe('lifecycle timeouts', () => {
+ it('rejects load() when the worker never reports ready within the timeout', async () => {
+ jest.useFakeTimers();
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const pending = host.load('/p/index.js', undefined, 100);
+ jest.advanceTimersByTime(100);
+
+ await expect(pending).rejects.toThrow(/timed out/i);
+ jest.useRealTimers();
+ });
+
+ it('clears the load timer when ready arrives in time (no late rejection)', async () => {
+ jest.useFakeTimers();
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const pending = host.load('/p/index.js', undefined, 100);
+ ch.reply({ kind: 'ready' });
+ await expect(pending).resolves.toBeUndefined();
+
+ jest.advanceTimersByTime(1000); // timer must have been cleared; advancing has no effect
+ jest.useRealTimers();
+ });
+
+ it('rejects runLifecycle() when no result arrives within the timeout', async () => {
+ jest.useFakeTimers();
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+ void host.load('/p/index.js');
+ ch.reply({ kind: 'ready' });
+
+ const pending = host.runLifecycle('onEnable', 100);
+ jest.advanceTimersByTime(100);
+
+ await expect(pending).rejects.toThrow(/timed out/i);
+ jest.useRealTimers();
+ });
+
+ it('clears the lifecycle timer when the result arrives in time', async () => {
+ jest.useFakeTimers();
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+ void host.load('/p/index.js');
+ ch.reply({ kind: 'ready' });
+
+ const pending = host.runLifecycle('onEnable', 100);
+ ch.reply({ kind: 'lifecycle-result', id: lastLifecycle(ch).id, ok: true });
+ await expect(pending).resolves.toBeUndefined();
+
+ jest.advanceTimersByTime(1000); // no late rejection
+ jest.useRealTimers();
+ });
+ });
});
diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.ts
index d897ce608..f2755b060 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.ts
@@ -18,8 +18,15 @@ export class PluginWorkerHost {
private nextId = 1;
private ready = false;
private dead = false;
- private readyWaiters: Array<{ resolve: () => void; reject: (error: Error) => void }> = [];
- private readonly pending = new Map<number, { resolve: () => void; reject: (error: Error) => void }>();
+ private readyWaiters: Array<{
+ resolve: () => void;
+ reject: (error: Error) => void;
+ timer?: ReturnType<typeof setTimeout>;
+ }> = [];
+ private readonly pending = new Map<
+ number,
+ { resolve: () => void; reject: (error: Error) => void; timer?: ReturnType<typeof setTimeout> }
+ >();
private readonly hookPending = new Map<
number,
{ resolve: (result: { continue: boolean; data?: unknown }) => void; timer: ReturnType<typeof setTimeout> }
@@ -76,22 +83,51 @@ export class PluginWorkerHost {
});
}
- /** Load the plugin module in the worker; resolves once it reports `ready`, rejects if it errors. */
- load(mainPath: string, context?: SandboxStaticContext): Promise<void> {
+ /**
+ * Load the plugin module in the worker; resolves once it reports `ready`, rejects if it errors.
+ * When `timeoutMs` is given, a worker that never reports ready rejects the call (the caller then
+ * tears the worker down) so a wedged module load can't hang enable forever.
+ */
+ load(mainPath: string, context?: SandboxStaticContext, timeoutMs?: number): Promise<void> {
return new Promise((resolve, reject) => {
if (this.dead) return reject(new Error('plugin worker is no longer running'));
if (this.ready) return resolve();
- this.readyWaiters.push({ resolve, reject });
+ const waiter: { resolve: () => void; reject: (error: Error) => void; timer?: ReturnType<typeof setTimeout> } = {
+ resolve,
+ reject,
+ };
+ if (timeoutMs !== undefined) {
+ waiter.timer = setTimeout(() => {
+ const index = this.readyWaiters.indexOf(waiter);
+ if (index !== -1) this.readyWaiters.splice(index, 1);
+ reject(new Error(`plugin worker load timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+ }
+ this.readyWaiters.push(waiter);
this.channel.postMessage(context ? { kind: 'load', mainPath, context } : { kind: 'load', mainPath });
});
}
- /** Invoke a plugin lifecycle method in the worker; resolves/rejects on the correlated result. */
- runLifecycle(method: PluginLifecycleMethod): Promise<void> {
+ /**
+ * Invoke a plugin lifecycle method in the worker; resolves/rejects on the correlated result.
+ * When `timeoutMs` is given, a method that never replies rejects the call so a wedged
+ * onLoad/onEnable/onDisable can't hang the enable/disable request indefinitely.
+ */
+ runLifecycle(method: PluginLifecycleMethod, timeoutMs?: number): Promise<void> {
return new Promise((resolve, reject) => {
if (this.dead) return reject(new Error('plugin worker is no longer running'));
const id = this.nextId++;
- this.pending.set(id, { resolve, reject });
+ const entry: { resolve: () => void; reject: (error: Error) => void; timer?: ReturnType<typeof setTimeout> } = {
+ resolve,
+ reject,
+ };
+ if (timeoutMs !== undefined) {
+ entry.timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new Error(`plugin worker lifecycle '${method}' timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+ }
+ this.pending.set(id, entry);
this.channel.postMessage({ kind: 'lifecycle', id, method });
});
}
@@ -128,17 +164,24 @@ export class PluginWorkerHost {
switch (message.kind) {
case 'ready':
this.ready = true;
- this.drain(this.readyWaiters, w => w.resolve());
+ this.drain(this.readyWaiters, w => {
+ if (w.timer) clearTimeout(w.timer);
+ w.resolve();
+ });
break;
case 'error': {
const error = new Error(message.error);
- this.drain(this.readyWaiters, w => w.reject(error));
+ this.drain(this.readyWaiters, w => {
+ if (w.timer) clearTimeout(w.timer);
+ w.reject(error);
+ });
break;
}
case 'lifecycle-result': {
const waiter = this.pending.get(message.id);
if (!waiter) return;
this.pending.delete(message.id);
+ if (waiter.timer) clearTimeout(waiter.timer);
if (message.ok) waiter.resolve();
else waiter.reject(new Error(message.error));
break;
@@ -194,8 +237,14 @@ export class PluginWorkerHost {
private handleExit(code: number): void {
this.dead = true;
const error = new Error(`plugin worker exited unexpectedly (code ${code})`);
- this.drain(this.readyWaiters, w => w.reject(error));
- this.pending.forEach(waiter => waiter.reject(error));
+ this.drain(this.readyWaiters, w => {
+ if (w.timer) clearTimeout(w.timer);
+ w.reject(error);
+ });
+ this.pending.forEach(waiter => {
+ if (waiter.timer) clearTimeout(waiter.timer);
+ waiter.reject(error);
+ });
this.pending.clear();
this.healthPending.forEach(({ resolve, timer }) => {
clearTimeout(timer);