diff --git a/api/index.ts b/api/index.ts index edad487..178db11 100644 --- a/api/index.ts +++ b/api/index.ts @@ -1,5 +1,8 @@ import log from '@data-fair/lib-node/log.js' import { start, stop } from './src/server.ts' +import { installUncaughtErrorsHandler } from '@data-fair/catalogs-shared/plugin-guard.ts' + +installUncaughtErrorsHandler() start().then(() => {}, err => { log.error('failure while starting the service', { code: 'start-process', err }) diff --git a/api/src/catalogs/service.ts b/api/src/catalogs/service.ts index 13a82f7..ff231ea 100644 --- a/api/src/catalogs/service.ts +++ b/api/src/catalogs/service.ts @@ -66,6 +66,7 @@ export const prepareCatalog = async (catalog: Catalog) => { secrets: decipherSecrets(catalog.secrets, config.cipherPassword) }) } catch (error: any) { + if (error.status >= 500) throw error throw httpError(400, `Invalid configuration: ${error.message || 'Unknown error'}`) } diff --git a/api/src/plugins/service.ts b/api/src/plugins/service.ts index c419ef3..bbb6255 100644 --- a/api/src/plugins/service.ts +++ b/api/src/plugins/service.ts @@ -5,10 +5,13 @@ import fs from 'fs-extra' import { httpError } from '@data-fair/lib-express' import { ensureArtefact } from '@data-fair/lib-node-registry' import { importPluginModule } from '@data-fair/catalogs-shared/plugin-load.ts' +import { guardPlugin } from '@data-fair/catalogs-shared/plugin-guard.ts' import config, { registryCacheDir } from '#config' fs.ensureDirSync(registryCacheDir) +const pluginCallTimeout = 60 * 1000 + /** Minimal account shape forwarded to the registry for access control. */ export type PluginAccount = { type: 'user' | 'organization', id: string, department?: string } @@ -55,5 +58,5 @@ export const getPlugin = async ( // For compatibility with older plugins if (plugin.listResources && !plugin.list) plugin.list = plugin.listResources - return { plugin, pkg } + return { plugin: guardPlugin(plugin, artefactId, { timeout: pluginCallTimeout }), pkg } } diff --git a/shared/plugin-guard.ts b/shared/plugin-guard.ts new file mode 100644 index 0000000..a1b20da --- /dev/null +++ b/shared/plugin-guard.ts @@ -0,0 +1,91 @@ +import type CatalogPlugin from '@data-fair/types-catalogs' +import { AsyncLocalStorage } from 'node:async_hooks' +import log from '@data-fair/lib-node/log.js' + +type PluginCall = { plugin: string, method: string, settled: boolean, fail: (err: unknown) => void } + +const pluginStorage = new AsyncLocalStorage() +const pendingCalls = new Set() + +const maxPluginErrors = 10 +const pluginErrorsWindow = 10 * 60 * 1000 +const pluginErrorDates = new Map() + +const isThenable = (value: unknown): value is PromiseLike => + typeof (value as PromiseLike | null)?.then === 'function' + +const callPlugin = (plugin: string, method: string, timeout: number | undefined, run: () => unknown) => { + let fail: (err: unknown) => void = () => {} + const failed = new Promise((_resolve, reject) => { fail = reject }) + failed.catch(() => {}) + const call: PluginCall = { plugin, method, settled: false, fail } + const settle = () => { + call.settled = true + pendingCalls.delete(call) + } + + pendingCalls.add(call) + let result: unknown + try { + result = pluginStorage.run(call, run) + } catch (err) { + settle() + throw err + } + if (!isThenable(result)) { + settle() + return result + } + + const timer = timeout + ? setTimeout(() => { + log.warn('a plugin call timed out', { code: 'plugin-call-timeout', plugin, pluginMethod: method, timeout }) + fail(Object.assign(new Error(`the plugin ${plugin} did not answer ${method} in ${timeout / 1000}s`), { status: 504, expose: true })) + }, timeout) + : undefined + return Promise.race([result, failed]).finally(() => { + clearTimeout(timer) + settle() + }) +} + +export const guardPlugin = (plugin: CatalogPlugin, pluginId: string, opts: { timeout?: number } = {}): CatalogPlugin => { + const guarded: Record = { ...plugin } + for (const [key, value] of Object.entries(plugin) as [string, unknown][]) { + if (typeof value !== 'function') continue + guarded[key] = (...args: unknown[]) => callPlugin(pluginId, key, opts.timeout, () => (value as (...args: unknown[]) => unknown).apply(plugin, args)) + } + return guarded as unknown as CatalogPlugin +} + +export const outsidePlugin = (fn: () => T): T => pluginStorage.exit(fn) + +export const installUncaughtErrorsHandler = () => { + process.on('uncaughtException', (err, origin) => { + const call = pluginStorage.getStore() + if (!call) { + log.error('uncaught error, shutting down', { code: 'uncaught-error', origin, err }) + process.exit(1) + } + + const failedCalls = call.settled ? [...pendingCalls].filter(c => c.plugin === call.plugin) : [call] + log.error('uncaught error in a plugin', { + code: 'plugin-uncaught-error', + plugin: call.plugin, + pluginMethod: call.method, + afterCallSettled: call.settled, + failedCalls: failedCalls.length, + origin, + err + }) + for (const failedCall of failedCalls) failedCall.fail(err) + + const now = Date.now() + const dates = [...(pluginErrorDates.get(call.plugin) ?? []).filter(date => date > now - pluginErrorsWindow), now] + pluginErrorDates.set(call.plugin, dates) + if (dates.length >= maxPluginErrors) { + log.error('too many uncaught errors in a plugin, shutting down', { code: 'plugin-uncaught-errors-limit', plugin: call.plugin, count: dates.length }) + process.exit(1) + } + }) +} diff --git a/tests/features/shared/plugin-guard.unit.spec.ts b/tests/features/shared/plugin-guard.unit.spec.ts new file mode 100644 index 0000000..97a8c73 --- /dev/null +++ b/tests/features/shared/plugin-guard.unit.spec.ts @@ -0,0 +1,104 @@ +import { test, expect } from '@playwright/test' +import { spawnSync } from 'node:child_process' +import path from 'node:path' + +const guardPath = path.resolve(import.meta.dirname, '../../../shared/plugin-guard.ts') + +const runScript = (body: string) => { + const script = ` +import { EventEmitter } from 'node:events' +import { guardPlugin, outsidePlugin, installUncaughtErrorsHandler } from ${JSON.stringify(guardPath)} +installUncaughtErrorsHandler() +const resetError = () => Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }) +const emitLater = () => setTimeout(() => new EventEmitter().emit('error', resetError()), 10) +let sharedConnection +const plugin = guardPlugin({ + metadata: { title: 'test' }, + async list () { emitLater(); return { count: 0, results: [] } }, + async getResource () { Promise.reject(new Error('forgotten rejection')); return {} }, + prepare () { emitLater(); return new Promise(() => {}) }, + publishDataset () { return new Promise(() => {}) }, + async openConnection () { + sharedConnection = new EventEmitter() + setTimeout(() => sharedConnection.emit('error', resetError()), 30) + }, + useConnection () { return new Promise(() => {}) }, + hostCallback (cb) { cb(); return new Promise(() => {}) }, + assertConfigValid () { throw new Error('invalid config') } +}, 'test-plugin', { timeout: 100 }) +${body} +setTimeout(() => { console.log('ALIVE'); process.exit(0) }, 200) +` + return spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', env: { ...process.env, NODE_ENV: 'production' } }) +} + +test.describe('plugin guard', () => { + test('an error event nobody listens to in a plugin call does not stop the process', () => { + const res = runScript('await plugin.list({})') + expect(res.stdout).toContain('ALIVE') + expect(res.stdout).toContain('"code":"plugin-uncaught-error"') + expect(res.stdout).toContain('"plugin":"test-plugin"') + expect(res.status).toBe(0) + }) + + test('an unhandled rejection in a plugin call does not stop the process', () => { + const res = runScript('await plugin.getResource({})') + expect(res.stdout).toContain('ALIVE') + expect(res.stdout).toContain('"origin":"unhandledRejection"') + expect(res.status).toBe(0) + }) + + test('a pending plugin call rejects with the uncaught error it raised', () => { + const res = runScript('await plugin.prepare({}).catch(err => console.log("REJECTED=" + err.code))') + expect(res.stdout).toContain('REJECTED=ECONNRESET') + expect(res.stdout).toContain('"pluginMethod":"prepare"') + expect(res.stdout).toContain('ALIVE') + }) + + test('a plugin call that never settles rejects after the timeout', () => { + const res = runScript('await plugin.publishDataset({}).catch(err => console.log("REJECTED=" + err.status + " " + err.message))') + expect(res.stdout).toContain('REJECTED=504 the plugin test-plugin did not answer publishDataset in 0.1s') + }) + + test('an error on a resource created by a settled call fails the pending calls of the same plugin', () => { + const res = runScript(` +await plugin.openConnection() +await plugin.useConnection().catch(err => console.log('REJECTED=' + err.code))`) + expect(res.stdout).toContain('REJECTED=ECONNRESET') + expect(res.stdout).toContain('"afterCallSettled":true') + expect(res.stdout).toContain('ALIVE') + }) + + test('an error from a host callback run outside of the plugin context still stops the process', () => { + const res = runScript('plugin.hostCallback(() => outsidePlugin(emitLater))') + expect(res.stdout).not.toContain('ALIVE') + expect(res.stdout).toContain('"code":"uncaught-error"') + expect(res.status).toBe(1) + }) + + test('10 uncaught errors of one plugin stop the process', () => { + const res = runScript('for (let i = 0; i < 9; i++) plugin.list({}); setTimeout(() => console.log("NINE_OK"), 50); setTimeout(() => plugin.list({}), 100)') + expect(res.stdout).toContain('NINE_OK') + expect(res.stdout).toContain('"plugin":"test-plugin","count":10') + expect(res.stdout).not.toContain('ALIVE') + expect(res.stdout).toContain('"code":"plugin-uncaught-errors-limit"') + expect(res.status).toBe(1) + }) + + test('a synchronous throw is returned unchanged', () => { + const res = runScript('try { plugin.assertConfigValid({}) } catch (err) { console.log("THROWN=" + err.message) }') + expect(res.stdout).toContain('THROWN=invalid config') + }) + + test('keeps the plugin metadata', () => { + const res = runScript('console.log("TITLE=" + plugin.metadata.title)') + expect(res.stdout).toContain('TITLE=test') + }) + + test('an uncaught error outside of a plugin call still stops the process', () => { + const res = runScript('emitLater()') + expect(res.stdout).not.toContain('ALIVE') + expect(res.stdout).toContain('"code":"uncaught-error"') + expect(res.status).toBe(1) + }) +}) diff --git a/worker/index.ts b/worker/index.ts index 52f43cc..a76c41e 100644 --- a/worker/index.ts +++ b/worker/index.ts @@ -1,5 +1,8 @@ import log from '@data-fair/lib-node/log.js' import { start, stop } from './src/worker.ts' +import { installUncaughtErrorsHandler } from '@data-fair/catalogs-shared/plugin-guard.ts' + +installUncaughtErrorsHandler() start().then(() => log.info('worker loop is running'), err => { log.error('failure while starting the worker', { code: 'start-process', err }) diff --git a/worker/src/lib/logs.ts b/worker/src/lib/logs.ts index 127d97f..554e7c1 100644 --- a/worker/src/lib/logs.ts +++ b/worker/src/lib/logs.ts @@ -3,6 +3,7 @@ import type { Import, Publication } from '#api/types' import mongo from '#mongo' import { emit as wsEmit } from '@data-fair/lib-node/ws-emitter.js' +import { outsidePlugin } from '@data-fair/catalogs-shared/plugin-guard.ts' type TaskKey = 'import' | 'publication' type Task = Import | Publication @@ -14,11 +15,11 @@ type Task = Import | Publication export default (task: Task, type: TaskKey): LogFunctions => { const collection = type === 'import' ? mongo.imports : mongo.publications - const pushLog = async (log: Omit) => { + const pushLog = (log: Omit) => outsidePlugin(async () => { const logWithDate = { ...log, date: new Date().toISOString() } as Log await collection.updateOne({ _id: task._id }, { $push: { logs: logWithDate } }) await wsEmit(`${type}/${task._id}/logs`, logWithDate) - } + }) return { info: async (msg, extra) => await pushLog({ type: 'info', msg, extra } as Omit), @@ -26,11 +27,11 @@ export default (task: Task, type: TaskKey): LogFunctions => { error: async (msg, extra) => await pushLog({ type: 'error', msg, extra } as Omit), step: async (msg) => await pushLog({ type: 'step', msg } as Omit), task: async (key, msg, total) => await pushLog({ type: 'task', msg, key, progress: 0, total } as Omit), - progress: async (taskKey, progress, total) => { + progress: (taskKey, progress, total) => outsidePlugin(async () => { const progressDate = new Date().toISOString() await collection.updateOne({ _id: task._id, logs: { $elemMatch: { type: 'task', key: taskKey } } }, { $set: { 'logs.$.progress': progress, 'logs.$.total': total, 'logs.$.progressDate': progressDate } }) await wsEmit(`${type}/${task._id}/logs`, { type: 'task', key: taskKey, progressDate, progress, total }) - } + }) } } diff --git a/worker/src/worker.ts b/worker/src/worker.ts index a2bfb2d..40b4f91 100644 --- a/worker/src/worker.ts +++ b/worker/src/worker.ts @@ -10,6 +10,7 @@ import eventsQueue from '@data-fair/lib-node/events-queue.js' import upgradeScripts from '@data-fair/lib-node/upgrade-scripts.js' import { ensureArtefact } from '@data-fair/lib-node-registry' import { importPluginModule } from '@data-fair/catalogs-shared/plugin-load.ts' +import { guardPlugin } from '@data-fair/catalogs-shared/plugin-guard.ts' import { getNextImportDate } from '@data-fair/catalogs-shared/cron.ts' import importTask from './lib/import.ts' import publicationTask from './lib/publication.ts' @@ -150,6 +151,7 @@ async function iter (task: Task, type: typeof types[number]) { const mod = await importPluginModule<{ default: CatalogPlugin }>(ensured.path) plugin = mod.default if (plugin.listResources && !plugin.list) plugin.list = plugin.listResources + plugin = guardPlugin(plugin, catalog.plugin) } catch (e: any) { const status = e.status ?? e.statusCode ?? e.response?.status const msg = (status === 404 || status === 403)