Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(plugins): write a non-record log meta as one field

Yudhi Armyndharisd3e1ef0b75f1
diff --git a/src/core/plugins/plugin-capability-context.ts b/src/core/plugins/plugin-capability-context.ts
index 70785532e..3a60d5ce0 100644
--- a/src/core/plugins/plugin-capability-context.ts
+++ b/src/core/plugins/plugin-capability-context.ts
@@ -59,6 +59,14 @@ export function dispatchConversationMedia(
/** 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));
+/** A plugin's log meta as the fields of the line: a record as it is, nothing as no fields, anything else as one field. */
+const metaFields = (meta: unknown): Record<string, unknown> =>
+ meta === undefined || meta === null
+ ? {}
+ : typeof meta === 'object' && !Array.isArray(meta)
+ ? (meta as Record<string, unknown>)
+ : { meta };
+
/**
* The capability surface a plugin actually touches: ctx.messages, ctx.engine, ctx.net, ctx.storage,
* ctx.conversations, ctx.handover, ctx.mappings — and the gates in front of every one of them.
@@ -226,14 +234,14 @@ export class PluginCapabilityContext {
private buildPluginLogger(plugin: PluginInstance): PluginLogger {
return {
log: (message, meta) =>
- this.logger.log(`[${plugin.manifest.id}] ${message}`, { ...meta, pluginId: plugin.manifest.id }),
+ this.logger.log(`[${plugin.manifest.id}] ${message}`, { ...metaFields(meta), pluginId: plugin.manifest.id }),
debug: (message, meta) =>
- this.logger.debug(`[${plugin.manifest.id}] ${message}`, { ...meta, pluginId: plugin.manifest.id }),
+ this.logger.debug(`[${plugin.manifest.id}] ${message}`, { ...metaFields(meta), pluginId: plugin.manifest.id }),
warn: (message, meta) =>
- this.logger.warn(`[${plugin.manifest.id}] ${message}`, { ...meta, pluginId: plugin.manifest.id }),
+ this.logger.warn(`[${plugin.manifest.id}] ${message}`, { ...metaFields(meta), pluginId: plugin.manifest.id }),
error: (message, error, meta) =>
this.logger.error(`[${plugin.manifest.id}] ${message}`, error === undefined ? undefined : errorText(error), {
- ...meta,
+ ...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 02296559d..2138883d8 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 } from '../../common/services/logger.service';
+import { createLogger, LogFormat, LoggerService } from '../../common/services/logger.service';
describe('the logger a plugin gets', () => {
const manifest: PluginManifest = {
@@ -14,10 +14,10 @@ describe('the logger a plugin gets', () => {
main: 'index.js',
};
- const setup = () => {
+ const setup = (sink?: ReturnType<typeof createLogger>) => {
const host = { error: jest.fn(), log: jest.fn(), warn: jest.fn(), debug: jest.fn() };
const context = new PluginCapabilityContext(
- host as unknown as ReturnType<typeof createLogger>,
+ sink ?? (host as unknown as ReturnType<typeof createLogger>),
{} as PluginHostServices,
new HookManager(),
{ createPluginStorage: () => ({}) } as unknown as PluginStorageService,
@@ -41,6 +41,68 @@ describe('the logger a plugin gets', () => {
expect(host.error).toHaveBeenNthCalledWith(2, '[p1] upload failed', undefined, { sessionId: 's1', pluginId: 'p1' });
});
+ // The parameter is a record, but plugin code is not type checked: a string or an array given as the meta must not be
+ // spread into one field per character or per index.
+ describe('a meta that is not a record', () => {
+ // The meta a host logger call carried: the second argument, or the third of error().
+ const metaOf = (spy: jest.Mock, argument: 1 | 2): unknown => (spy.mock.calls as unknown[][])[0][argument];
+ const asRecord = (meta: unknown): Record<string, unknown> => meta as Record<string, unknown>;
+
+ it.each([
+ ['a string', 'abc'],
+ ['an array', [1, { token: 't' }]],
+ ['a number', 404],
+ ])('writes %s as one field', (_name, meta) => {
+ const { host, logger } = setup();
+
+ logger.log('m', asRecord(meta));
+ logger.debug('m', asRecord(meta));
+ logger.warn('m', asRecord(meta));
+ logger.error('m', undefined, asRecord(meta));
+
+ for (const written of [metaOf(host.log, 1), metaOf(host.debug, 1), metaOf(host.warn, 1), metaOf(host.error, 2)]) {
+ expect(written).toEqual({ meta, pluginId: 'p1' });
+ }
+ });
+
+ it.each([
+ ['undefined', undefined],
+ ['null', null],
+ ])('writes %s as no fields besides the plugin id', (_name, meta) => {
+ const { host, logger } = setup();
+
+ logger.warn('m', asRecord(meta));
+
+ expect(host.warn).toHaveBeenCalledWith('[p1] m', { pluginId: 'p1' });
+ expect(Object.keys(metaOf(host.warn, 1) as object)).toEqual(['pluginId']);
+ });
+
+ it('writes a string as one field of the line the logger prints', () => {
+ LoggerService.setLogFormat(LogFormat.JSON);
+ const warn = jest.spyOn(console, 'warn').mockImplementation();
+ try {
+ const { logger } = setup(createLogger('Plugins'));
+
+ logger.warn('failed', 'abc' as unknown as Record<string, unknown>);
+
+ const line = JSON.parse((warn.mock.calls as string[][])[0][0]) as Record<string, unknown>;
+ expect(line).toMatchObject({ message: '[p1] failed', meta: 'abc', pluginId: 'p1' });
+ expect(line).not.toHaveProperty('0');
+ } finally {
+ warn.mockRestore();
+ LoggerService.setLogFormat(null);
+ }
+ });
+
+ it('keeps the fields of a record as they are', () => {
+ const { host, logger } = setup();
+
+ logger.warn('m', { sessionId: 's1', nested: { a: 1 } });
+
+ expect(host.warn).toHaveBeenCalledWith('[p1] m', { sessionId: 's1', nested: { a: 1 }, pluginId: 'p1' });
+ });
+ });
+
it('passes the message of an Error, and the text of anything else, as the trace', () => {
const { host, logger } = setup();
diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
index 1600e7794..4cd88c2c1 100644
--- a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
@@ -738,6 +738,19 @@ describe('PluginLoaderService — sandbox log relay bounds', () => {
expect(logSpy).toHaveBeenNthCalledWith(2, '[p1] small', { n: 1, pluginId: 'p1' });
});
+ it('relays a worker log meta that is a string or an array as one field', async () => {
+ const loader = makeLoader();
+ seed(loader, { builtIn: false, instance: null });
+ await loader.enablePlugin('p1');
+ const logSpy = jest.spyOn(loggerOf(loader), 'log').mockImplementation(() => undefined);
+
+ loader.capturedOnLog!('log', 'string', 'abc' as unknown as Record<string, unknown>);
+ loader.capturedOnLog!('log', 'array', [1, 2] as unknown as Record<string, unknown>);
+
+ expect(logSpy).toHaveBeenNthCalledWith(1, '[p1] string', { meta: 'abc', pluginId: 'p1' });
+ expect(logSpy).toHaveBeenNthCalledWith(2, '[p1] array', { meta: [1, 2], pluginId: 'p1' });
+ });
+
it('keeps the error text of a worker error log whose meta is oversized or not serializable', async () => {
// logger.error's reason travels as meta.error, and the host error call gets no trace argument.
const loader = makeLoader();