Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(plugins): record plugin changes in the audit log

Yudhi Armyndharis54a9abcf986a
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index f7e88c9f8..15d7856f3 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -556,7 +556,8 @@ app.use(helmet({
> (updates carry before/after authorization state), rejected authentication, session lifecycle
> (including disconnects caused by WhatsApp unlinking the device, account restrictions and their
> lifting, and refused rebinds), integration-instance creation, update, secret rotation, deletion,
-> redrive, and scope-binding bridge failures, webhook delivery-failure redrive batches, send-pacing refusals (sampled) and breaker trips, the
+> redrive, and scope-binding bridge failures, plugin install, update, uninstall, enable, disable, configuration and session
+> activation, webhook delivery-failure redrive batches, send-pacing refusals (sampled) and breaker trips, the
> infra operations (config save, restart request, data export/import, storage export/import),
> WebSocket rate-limit violations (sampled — see §4.6), and Bull Board queue mutations. Enum
> members for API-key use, session connected, message sends, and webhook lifecycle are explicitly
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index c0a37016a..4c2d10bf8 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -658,7 +658,9 @@ batch), rate-limit enforcement (`rate_limit_exceeded`, sampled to at
most one row per subject+kind per minute), the queue dashboard (`queue_board_mutated`), integration
plugin instances (`integration_instance_created`, `integration_instance_updated`,
`integration_instance_secret_regenerated`, `integration_instance_deleted`,
-`integration_instance_redriven`), and ADMIN-only infrastructure operations (`infra_config_saved`,
+`integration_instance_redriven`), plugin management (`plugin_installed`, `plugin_updated`, `plugin_uninstalled`,
+`plugin_enabled`, `plugin_disabled`, `plugin_config_updated`, `plugin_sessions_updated`; metadata carries the plugin
+id, version, the host of the requested download URL and config field names, never config values), and ADMIN-only infrastructure operations (`infra_config_saved`,
`infra_restart_requested`, `infra_data_exported`, `infra_data_imported`, `infra_storage_exported`,
`infra_storage_imported`).
diff --git a/openapi.json b/openapi.json
index 9b4c00d7b..bb2eac722 100644
--- a/openapi.json
+++ b/openapi.json
@@ -91,6 +91,13 @@
"integration_instance_secret_regenerated",
"integration_instance_deleted",
"integration_instance_redriven",
+ "plugin_installed",
+ "plugin_updated",
+ "plugin_uninstalled",
+ "plugin_enabled",
+ "plugin_disabled",
+ "plugin_config_updated",
+ "plugin_sessions_updated",
"infra_config_saved",
"infra_restart_requested",
"infra_data_exported",
diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.ts
index 9edb97788..e19678150 100644
--- a/src/modules/audit/entities/audit-log.entity.ts
+++ b/src/modules/audit/entities/audit-log.entity.ts
@@ -64,6 +64,15 @@ export enum AuditAction {
INTEGRATION_INSTANCE_DELETED = 'integration_instance_deleted',
INTEGRATION_INSTANCE_REDRIVEN = 'integration_instance_redriven',
+ // Plugin management (ADMIN-only: a plugin is third-party code that runs in the gateway process).
+ PLUGIN_INSTALLED = 'plugin_installed',
+ PLUGIN_UPDATED = 'plugin_updated',
+ PLUGIN_UNINSTALLED = 'plugin_uninstalled',
+ PLUGIN_ENABLED = 'plugin_enabled',
+ PLUGIN_DISABLED = 'plugin_disabled',
+ PLUGIN_CONFIG_UPDATED = 'plugin_config_updated',
+ PLUGIN_SESSIONS_UPDATED = 'plugin_sessions_updated',
+
// Infrastructure events (ADMIN-only operations on the infra module: credential-bearing config
// mutation, server restart / Docker orchestration, and full-DB / storage export+import).
INFRA_CONFIG_SAVED = 'infra_config_saved',
diff --git a/src/modules/plugins/plugins.controller.audit.spec.ts b/src/modules/plugins/plugins.controller.audit.spec.ts
new file mode 100644
index 000000000..7f3ac213a
--- /dev/null
+++ b/src/modules/plugins/plugins.controller.audit.spec.ts
@@ -0,0 +1,119 @@
+import { PluginsController } from './plugins.controller';
+import type { PluginsService } from './plugins.service';
+import type { AuditService } from '../audit/audit.service';
+import { AuditAction } from '../audit/entities/audit-log.entity';
+
+/**
+ * A plugin is third-party code that runs in the gateway process, so every successful mutation of one
+ * leaves an audit row naming the plugin (the acting key and IP are stamped from the request context).
+ */
+describe('PluginsController audit trail', () => {
+ const plugin = { id: 'relay', version: '1.2.3' };
+ const done = { success: true, message: 'ok' };
+ let service: Record<string, jest.Mock>;
+ let logInfo: jest.Mock;
+ let controller: PluginsController;
+
+ beforeEach(() => {
+ service = {
+ installPackage: jest.fn().mockResolvedValue(plugin),
+ installFromUrl: jest.fn().mockResolvedValue(plugin),
+ updateFromUrl: jest.fn().mockResolvedValue(plugin),
+ enable: jest.fn().mockResolvedValue(done),
+ disable: jest.fn().mockResolvedValue(done),
+ uninstall: jest.fn().mockResolvedValue(done),
+ updateConfig: jest.fn().mockReturnValue(done),
+ updateSessionConfig: jest.fn().mockReturnValue(done),
+ updateSessions: jest.fn().mockReturnValue(plugin),
+ };
+ logInfo = jest.fn().mockResolvedValue(null);
+ controller = new PluginsController(service as unknown as PluginsService, { logInfo } as unknown as AuditService);
+ });
+
+ it('records an upload install with the plugin id and version', async () => {
+ await controller.install({ buffer: Buffer.from('zip') });
+
+ expect(logInfo).toHaveBeenCalledWith(AuditAction.PLUGIN_INSTALLED, {
+ sessionId: undefined,
+ metadata: { pluginId: 'relay', version: '1.2.3', source: 'upload' },
+ });
+ });
+
+ it('records a URL install with the download host only, never the path, credentials or query', async () => {
+ await controller.installFromUrl({ url: 'https://user:[email protected]:8443/relay.zip?token=abc' });
+
+ const [action, context] = logInfo.mock.calls[0] as [AuditAction, { metadata: Record<string, unknown> }];
+ expect(action).toBe(AuditAction.PLUGIN_INSTALLED);
+ expect(context.metadata).toEqual({ pluginId: 'relay', version: '1.2.3', source: 'plugins.example.com:8443' });
+ expect(JSON.stringify(context)).not.toMatch(/secret|token/);
+ });
+
+ it('records an in-place update with the version it ended on', async () => {
+ await controller.update('relay', { url: 'https://plugins.example.com/relay.zip' });
+
+ expect(logInfo).toHaveBeenCalledWith(AuditAction.PLUGIN_UPDATED, {
+ sessionId: undefined,
+ metadata: { pluginId: 'relay', version: '1.2.3', source: 'plugins.example.com' },
+ });
+ });
+
+ it.each([
+ ['enable', AuditAction.PLUGIN_ENABLED],
+ ['disable', AuditAction.PLUGIN_DISABLED],
+ ['uninstall', AuditAction.PLUGIN_UNINSTALLED],
+ ] as const)('records %s', async (method, action) => {
+ await controller[method]('relay');
+
+ expect(logInfo).toHaveBeenCalledWith(action, { sessionId: undefined, metadata: { pluginId: 'relay' } });
+ });
+
+ it('records a configuration change by field name, never by value', () => {
+ controller.updateConfig('relay', { config: { apiKey: 'sk-live-123', baseUrl: 'https://crm.example.com' } });
+
+ const [action, context] = logInfo.mock.calls[0] as [AuditAction, { metadata: Record<string, unknown> }];
+ expect(action).toBe(AuditAction.PLUGIN_CONFIG_UPDATED);
+ expect(context.metadata).toEqual({ pluginId: 'relay', fields: ['apiKey', 'baseUrl'] });
+ expect(JSON.stringify(context)).not.toContain('sk-live-123');
+ });
+
+ it('attributes a per-session configuration change to its session', () => {
+ controller.updateSessionConfig('relay', 'sess-1', { config: { baseUrl: 'https://crm.example.com' } });
+
+ expect(logInfo).toHaveBeenCalledWith(AuditAction.PLUGIN_CONFIG_UPDATED, {
+ sessionId: 'sess-1',
+ metadata: { pluginId: 'relay', fields: ['baseUrl'] },
+ });
+ });
+
+ it('records which sessions a plugin was activated for', () => {
+ controller.updateSessions('relay', { sessions: ['sess-1', 'sess-2'] });
+
+ expect(logInfo).toHaveBeenCalledWith(AuditAction.PLUGIN_SESSIONS_UPDATED, {
+ sessionId: undefined,
+ metadata: { pluginId: 'relay', sessions: ['sess-1', 'sess-2'] },
+ });
+ });
+
+ it('writes no row for a call that did not change anything', async () => {
+ service.enable.mockResolvedValueOnce({ success: false, message: 'could not start' });
+ service.uninstall.mockRejectedValueOnce(new Error('built-in'));
+
+ await controller.enable('relay');
+ await expect(controller.uninstall('relay')).rejects.toThrow('built-in');
+
+ expect(logInfo).not.toHaveBeenCalled();
+ });
+
+ // The service answers a refused configuration change with 200 and success false (a masked secret list it
+ // cannot restore, for one), so the audit row has to follow the outcome and not the call.
+ it('writes no row for a configuration change the service refused', () => {
+ const refused = { success: false, message: 'could not restore the masked secret' };
+ service.updateConfig.mockReturnValueOnce(refused);
+ service.updateSessionConfig.mockReturnValueOnce(refused);
+
+ controller.updateConfig('relay', { config: { apiKeys: ['********'] } });
+ controller.updateSessionConfig('relay', 'sess-1', { config: { apiKeys: ['********'] } });
+
+ expect(logInfo).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.ts
index cbe3544d2..32bddd497 100644
--- a/src/modules/plugins/plugins.controller.ts
+++ b/src/modules/plugins/plugins.controller.ts
@@ -27,6 +27,8 @@ import {
import type { CatalogPlugin } from './catalog';
import { RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
+import { AuditService } from '../audit/audit.service';
+import { AuditAction } from '../audit/entities/audit-log.entity';
/** Max accepted upload size for a plugin package (compressed). */
const MAX_PLUGIN_UPLOAD_BYTES = 5 * 1024 * 1024;
@@ -43,7 +45,28 @@ const RESTORING_CONFLICT = 'The plugin is still being restored after startup; re
// another tenant's activation by sending its own session or []), and `updateSessionConfig` is
// already covered by the guard through its own :sessionId route param.
export class PluginsController {
- constructor(private readonly pluginsService: PluginsService) {}
+ constructor(
+ private readonly pluginsService: PluginsService,
+ private readonly audit: AuditService,
+ ) {}
+
+ /**
+ * One audit row per successful plugin mutation. Plugins run in the gateway process, so which key
+ * installed, enabled or reconfigured one is the first thing an investigation needs. Ids, versions and
+ * config FIELD NAMES only: a config can carry credentials, and audit metadata is not a credential store.
+ */
+ private record(action: AuditAction, pluginId: string, extra: Record<string, unknown> = {}, sessionId?: string): void {
+ void this.audit.logInfo(action, { sessionId, metadata: { pluginId, ...extra } });
+ }
+
+ /** Host of a download URL: enough to tell where code came from, without a credential or token in the query. */
+ private static sourceHost(url: string): string {
+ try {
+ return new URL(url).host;
+ } catch {
+ return 'unknown';
+ }
+ }
@Get()
@RequireRole(ApiKeyRole.ADMIN)
@@ -75,7 +98,9 @@ export class PluginsController {
@ApiResponse({ status: 409, description: 'Plugin already installed' })
@ApiResponse({ status: 413, description: 'Package exceeds the 5 MB upload limit' })
async install(@UploadedFile() file: { buffer?: Buffer }): Promise<PluginDto> {
- return this.pluginsService.installPackage(file);
+ const plugin = await this.pluginsService.installPackage(file);
+ this.record(AuditAction.PLUGIN_INSTALLED, plugin.id, { version: plugin.version, source: 'upload' });
+ return plugin;
}
@Post('install-url')
@@ -89,7 +114,12 @@ export class PluginsController {
description: 'Plugin already installed, or the plugin is still being restored after startup; retry shortly',
})
async installFromUrl(@Body() dto: InstallFromUrlDto): Promise<PluginDto> {
- return await this.pluginsService.installFromUrl(dto.url);
+ const plugin = await this.pluginsService.installFromUrl(dto.url);
+ this.record(AuditAction.PLUGIN_INSTALLED, plugin.id, {
+ version: plugin.version,
+ source: PluginsController.sourceHost(dto.url),
+ });
+ return plugin;
}
// Declared before `:id` so `GET /plugins/catalog` is not captured by the `:id` route.
@@ -122,7 +152,9 @@ export class PluginsController {
@ApiResponse({ status: 404, description: 'Plugin not found' })
@ApiResponse({ status: 409, description: RESTORING_CONFLICT })
async enable(@Param('id') id: string): Promise<{ success: boolean; message: string }> {
- return await this.pluginsService.enable(id);
+ const result = await this.pluginsService.enable(id);
+ if (result.success) this.record(AuditAction.PLUGIN_ENABLED, id);
+ return result;
}
@Post(':id/disable')
@@ -134,7 +166,9 @@ export class PluginsController {
@ApiResponse({ status: 404, description: 'Plugin not found' })
@ApiResponse({ status: 409, description: RESTORING_CONFLICT })
async disable(@Param('id') id: string): Promise<{ success: boolean; message: string }> {
- return await this.pluginsService.disable(id);
+ const result = await this.pluginsService.disable(id);
+ if (result.success) this.record(AuditAction.PLUGIN_DISABLED, id);
+ return result;
}
@Put(':id/config')
@@ -145,7 +179,11 @@ export class PluginsController {
@ApiResponse({ status: 400, description: 'Validation failed, or the body carries a field the DTO does not declare.' })
@ApiResponse({ status: 404, description: 'Plugin not found' })
updateConfig(@Param('id') id: string, @Body() configDto: PluginConfigDto): { success: boolean; message: string } {
- return this.pluginsService.updateConfig(id, configDto.config);
+ const result = this.pluginsService.updateConfig(id, configDto.config);
+ // The service answers a refused change with 200 and success false, so a row is written only for one applied.
+ if (result.success)
+ this.record(AuditAction.PLUGIN_CONFIG_UPDATED, id, { fields: Object.keys(configDto.config ?? {}) });
+ return result;
}
// The dashboard fetches this WITH the API key and injects the body as an opaque-origin sandboxed
@@ -181,7 +219,11 @@ export class PluginsController {
@Param('sessionId') sessionId: string,
@Body() configDto: PluginConfigDto,
): { success: boolean; message: string } {
- return this.pluginsService.updateSessionConfig(id, sessionId, configDto.config);
+ const result = this.pluginsService.updateSessionConfig(id, sessionId, configDto.config);
+ if (result.success) {
+ this.record(AuditAction.PLUGIN_CONFIG_UPDATED, id, { fields: Object.keys(configDto.config ?? {}) }, sessionId);
+ }
+ return result;
}
@Put(':id/sessions')
@@ -200,7 +242,9 @@ export class PluginsController {
// This is a full-replacement PUT (setPluginSessions overwrites the entire activeSessions array),
// so a scoped key must never reach it: sending [] or its own session would delete every other
// tenant's activation. The @RequireUnscopedKey fence above enforces that before the handler runs.
- return this.pluginsService.updateSessions(id, dto.sessions);
+ const plugin = this.pluginsService.updateSessions(id, dto.sessions);
+ this.record(AuditAction.PLUGIN_SESSIONS_UPDATED, id, { sessions: dto.sessions });
+ return plugin;
}
@Post(':id/update')
@@ -216,7 +260,12 @@ export class PluginsController {
description: 'Gateway shutting down; the previous version was kept',
})
async update(@Param('id') id: string, @Body() dto: InstallFromUrlDto): Promise<PluginDto> {
- return await this.pluginsService.updateFromUrl(id, dto.url);
+ const plugin = await this.pluginsService.updateFromUrl(id, dto.url);
+ this.record(AuditAction.PLUGIN_UPDATED, id, {
+ version: plugin.version,
+ source: PluginsController.sourceHost(dto.url),
+ });
+ return plugin;
}
@Delete(':id')
@@ -228,7 +277,9 @@ export class PluginsController {
@ApiResponse({ status: 404, description: 'Plugin not found' })
@ApiResponse({ status: 409, description: RESTORING_CONFLICT })
async uninstall(@Param('id') id: string): Promise<{ success: boolean; message: string }> {
- return await this.pluginsService.uninstall(id);
+ const result = await this.pluginsService.uninstall(id);
+ this.record(AuditAction.PLUGIN_UNINSTALLED, id);
+ return result;
}
@Get(':id/health')