Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(plugins): never throw from a plugin's logger on what it passes

Yudhi Armyndharis81768344f0f0
diff --git a/src/common/services/logger.service.ts b/src/common/services/logger.service.ts
index 83d4a443b..fc72c0a30 100644
--- a/src/common/services/logger.service.ts
+++ b/src/common/services/logger.service.ts
@@ -218,7 +218,7 @@ export function redactSecrets(value: unknown, options: RedactOptions = {}): unkn
}
/** Written in place of a message or trace that cannot be read. */
-const UNPRINTABLE = '[Unprintable]';
+export const UNPRINTABLE = '[Unprintable]';
/**
* What a value that could not be turned into JSON is written as: a primitive as it prints, anything else not at all.
diff --git a/src/core/plugins/plugin-capability-context.ts b/src/core/plugins/plugin-capability-context.ts
index 6d3ef646a..5382118d9 100644
--- a/src/core/plugins/plugin-capability-context.ts
+++ b/src/core/plugins/plugin-capability-context.ts
@@ -5,7 +5,7 @@ import type { LidMappingStore } from '../../engine/identity/lid-mapping-store.se
import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import { toNeutralJid } from '../../engine/identity/wa-id';
import { ConversationMappingConflict } from '../../modules/integration/conversation-mapping.service';
-import { createLogger } from '../../common/services/logger.service';
+import { createLogger, UNPRINTABLE } from '../../common/services/logger.service';
import { isPluginActiveForSession, resolvePluginConfig } from './plugin-activation';
import { effectiveNetAllow, isNetHostAllowed, performPluginFetch } from './plugin-net';
import { buildConversationSendFacade, type ConversationMediaType } from './conversation-send-facade';
@@ -56,20 +56,45 @@ export function dispatchConversationMedia(
}
}
+// Plugin code can pass anything to its logger, and reading a value can throw (a Proxy trap, a getter, a toString): what
+// cannot be read is written as a marker, never thrown into the plugin.
+
+/** The text of a plugin's log message: what String gives for it (a Symbol included), or the marker. */
+const messageText = (message: unknown): string => {
+ try {
+ return String(message);
+ } catch {
+ return UNPRINTABLE;
+ }
+};
+
/** The trace for a plugin's ctx.logger.error: an Error's message, or the text of whatever else was passed. */
-const errorText = (error: unknown): string => (error instanceof Error ? error.message : String(error));
+const errorText = (error: unknown): string => {
+ try {
+ return error instanceof Error ? error.message : String(error);
+ } catch {
+ return UNPRINTABLE;
+ }
+};
/** A prototype that is the root of a chain (Object.prototype of any realm, or none): what a plain record has. */
const isRootPrototype = (prototype: object | null): boolean =>
prototype === null || Object.getPrototypeOf(prototype) === null;
-/** A plugin's log meta as the fields of the line: a plain record as it is, nothing as no fields, else as one field. */
-const metaFields = (meta: unknown): Record<string, unknown> =>
- meta === undefined || meta === null
- ? {}
- : typeof meta === 'object' && isRootPrototype(Object.getPrototypeOf(meta) as object | null)
- ? (meta as Record<string, unknown>)
- : { meta };
+/**
+ * A plugin's log meta as the fields of the line: a plain record as it is, nothing as no fields, else as one field. An
+ * object whose prototype cannot be read (a Proxy whose getPrototypeOf trap throws, or a revoked one) is taken as a
+ * record, as spreading it took it: the logger copies it by its own properties or writes it as [Unreadable].
+ */
+const metaFields = (meta: unknown): Record<string, unknown> => {
+ if (meta === undefined || meta === null) return {};
+ if (typeof meta !== 'object') return { meta };
+ try {
+ return isRootPrototype(Object.getPrototypeOf(meta) as object | null) ? (meta as Record<string, unknown>) : { meta };
+ } catch {
+ return meta as Record<string, unknown>;
+ }
+};
/**
* The capability surface a plugin actually touches: ctx.messages, ctx.engine, ctx.net, ctx.storage,
@@ -239,14 +264,20 @@ export class PluginCapabilityContext {
private buildPluginLogger(plugin: PluginInstance): PluginLogger {
return {
log: (message, meta) =>
- this.logger.log(`[${plugin.manifest.id}] ${message}`, metaFields(meta), { pluginId: plugin.manifest.id }),
+ this.logger.log(`[${plugin.manifest.id}] ${messageText(message)}`, metaFields(meta), {
+ pluginId: plugin.manifest.id,
+ }),
debug: (message, meta) =>
- this.logger.debug(`[${plugin.manifest.id}] ${message}`, metaFields(meta), { pluginId: plugin.manifest.id }),
+ this.logger.debug(`[${plugin.manifest.id}] ${messageText(message)}`, metaFields(meta), {
+ pluginId: plugin.manifest.id,
+ }),
warn: (message, meta) =>
- this.logger.warn(`[${plugin.manifest.id}] ${message}`, metaFields(meta), { pluginId: plugin.manifest.id }),
+ this.logger.warn(`[${plugin.manifest.id}] ${messageText(message)}`, metaFields(meta), {
+ pluginId: plugin.manifest.id,
+ }),
error: (message, error, meta) =>
this.logger.error(
- `[${plugin.manifest.id}] ${message}`,
+ `[${plugin.manifest.id}] ${messageText(message)}`,
error === undefined ? undefined : errorText(error),
metaFields(meta),
{ pluginId: plugin.manifest.id },
diff --git a/src/core/plugins/plugin-capability-logger.spec.ts b/src/core/plugins/plugin-capability-logger.spec.ts
index 5abb6a9fe..98bf79b6d 100644
--- a/src/core/plugins/plugin-capability-logger.spec.ts
+++ b/src/core/plugins/plugin-capability-logger.spec.ts
@@ -3,7 +3,7 @@ import { PluginCapabilityContext } from './plugin-capability-context';
import { PluginHostServices } from './plugin-host-services';
import { PluginStorageService } from './plugin-storage.service';
import { PluginInstance, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';
-import { createLogger, LogFormat, LoggerService } from '../../common/services/logger.service';
+import { createLogger, LogFormat, LoggerService, LogLevel } from '../../common/services/logger.service';
describe('the logger a plugin gets', () => {
const manifest: PluginManifest = {
@@ -214,6 +214,79 @@ describe('the logger a plugin gets', () => {
});
});
+ // Plugin code is not type checked and can pass anything: no argument may make the call throw into the plugin, and
+ // every line keeps the plugin id.
+ describe('an argument that throws when it is read', () => {
+ const trap = (): never => {
+ throw new Error('trap');
+ };
+ const revoked = (target: object): object => {
+ const { proxy, revoke } = Proxy.revocable(target, {});
+ revoke();
+ return proxy;
+ };
+ // The lines of the nine calls below, in the order they were made, whatever console method each went to.
+ const written = (make: () => unknown): Record<string, unknown>[] => {
+ LoggerService.setLogFormat(LogFormat.JSON);
+ LoggerService.setLogLevel(LogLevel.DEBUG);
+ const lines: Record<string, unknown>[] = [];
+ const spies = [jest.spyOn(console, 'log'), jest.spyOn(console, 'warn'), jest.spyOn(console, 'error')];
+ for (const spy of spies)
+ spy.mockImplementation((line: string) => lines.push(JSON.parse(line) as Record<string, unknown>));
+ try {
+ const { logger } = setup(createLogger('Plugins'));
+ const meta = (): Record<string, unknown> => make() as Record<string, unknown>;
+ logger.log(make() as string);
+ logger.debug(make() as string);
+ logger.warn(make() as string);
+ logger.error(make() as string);
+ logger.error('m', make());
+ logger.log('m', meta());
+ logger.debug('m', meta());
+ logger.warn('m', meta());
+ logger.error('m', undefined, meta());
+ return lines;
+ } finally {
+ for (const spy of spies) spy.mockRestore();
+ LoggerService.setLogFormat(null);
+ LoggerService.setLogLevel(LogLevel.INFO);
+ }
+ };
+
+ it.each([
+ ['a Proxy whose getPrototypeOf trap throws', (): unknown => new Proxy({ a: 1 }, { getPrototypeOf: trap })],
+ ['a Proxy whose get trap throws', (): unknown => new Proxy({ a: 1 }, { get: trap })],
+ ['a Proxy whose ownKeys trap throws', (): unknown => new Proxy({ a: 1 }, { ownKeys: trap })],
+ ['a revoked Proxy', (): unknown => revoked({ a: 1 })],
+ ['a revoked Proxy of an array', (): unknown => revoked([1])],
+ ['an object whose toString throws', (): unknown => ({ toString: trap, valueOf: trap })],
+ ['an object without a prototype', (): unknown => Object.create(null) as object],
+ ['a Symbol', (): unknown => Symbol('s')],
+ [
+ 'an Error whose message getter throws',
+ (): unknown => Object.defineProperty(new Error('x'), 'message', { get: trap }),
+ ],
+ [
+ 'an Error behind a Proxy whose getPrototypeOf trap throws',
+ (): unknown => new Proxy(new Error('x'), { getPrototypeOf: trap }),
+ ],
+ ])('writes every line with the plugin id when the message, error or meta is %s', (_name, make) => {
+ const all = written(make);
+
+ expect(all).toHaveLength(9);
+ for (const line of all) expect(line).toMatchObject({ pluginId: 'p1' });
+ });
+
+ it('writes what it can read: the text String gives, the marker for the rest, a Proxy meta by its own properties', () => {
+ expect(written(() => Symbol('s'))[0]).toMatchObject({ message: '[p1] Symbol(s)' });
+ expect(written(() => Object.create(null) as object)[0]).toMatchObject({ message: '[p1] [Unprintable]' });
+ const message = Object.defineProperty(new Error('x'), 'message', { get: trap });
+ expect(written(() => message)[4]).toMatchObject({ message: '[p1] m', trace: '[Unprintable]' });
+ expect(written(() => new Proxy({ a: 1 }, { getPrototypeOf: trap }))[5]).toMatchObject({ a: 1, pluginId: 'p1' });
+ expect(written(() => revoked({ a: 1 }))[5]).toMatchObject({ metadata: '[Unreadable]', pluginId: 'p1' });
+ });
+ });
+
it('passes the message of an Error, and the text of anything else, as the trace', () => {
const { host, logger } = setup();