Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(infra): emit audit-log entries for sensitive infrastructure operations (#883)

Yudhi Armyndharis89de0b086bcb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2416df9fe..e25defd8f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
"Deutsch" in the language switcher. All 689 translation keys are covered, so German users get a
fully localized UI instead of the English fallback. Thanks @rjsebening.
+- **Audit-log coverage for sensitive infrastructure operations.** The admin-only infrastructure
+ endpoints that save configuration, restart the server, and export/import the full database or
+ stored media now record an audit-log entry — attributing the operation to the calling API key and
+ client IP, with non-sensitive context only (section names, row counts; secret values are never
+ logged). Previously these operations, several of which expose or replace credential-bearing data,
+ left no audit trail. The audit-vocabulary coverage gate is extended to these actions, so a future
+ infrastructure operation cannot ship without one.
+
### Fixed
- **Session scoping on the audit-log and webhook delivery-failure list endpoints.** `GET /api/audit`
diff --git a/openapi.json b/openapi.json
index 8048c758a..ca60c2ec6 100644
--- a/openapi.json
+++ b/openapi.json
@@ -34,7 +34,13 @@
"integration_instance_created",
"integration_instance_updated",
"integration_instance_secret_regenerated",
- "integration_instance_deleted"
+ "integration_instance_deleted",
+ "infra_config_saved",
+ "infra_restart_requested",
+ "infra_data_exported",
+ "infra_data_imported",
+ "infra_storage_exported",
+ "infra_storage_imported"
],
"type": "string"
}
diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.ts
index 4a2084966..7ff8395da 100644
--- a/src/modules/audit/entities/audit-log.entity.ts
+++ b/src/modules/audit/entities/audit-log.entity.ts
@@ -34,6 +34,15 @@ export enum AuditAction {
INTEGRATION_INSTANCE_UPDATED = 'integration_instance_updated',
INTEGRATION_INSTANCE_SECRET_REGENERATED = 'integration_instance_secret_regenerated',
INTEGRATION_INSTANCE_DELETED = 'integration_instance_deleted',
+
+ // 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',
+ INFRA_RESTART_REQUESTED = 'infra_restart_requested',
+ INFRA_DATA_EXPORTED = 'infra_data_exported',
+ INFRA_DATA_IMPORTED = 'infra_data_imported',
+ INFRA_STORAGE_EXPORTED = 'infra_storage_exported',
+ INFRA_STORAGE_IMPORTED = 'infra_storage_imported',
}
export enum AuditSeverity {
diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.ts
index f74f2f8f8..5c3b968c8 100644
--- a/src/modules/infra/infra.controller.spec.ts
+++ b/src/modules/infra/infra.controller.spec.ts
@@ -43,6 +43,7 @@ import { ConversationMapping } from '../integration/entities/conversation-mappin
import { IngressEvent } from '../integration/entities/ingress-event.entity';
import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';
import { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';
+import { AuditAction } from '../audit/entities/audit-log.entity';
describe('InfraController access control (Vuln 2)', () => {
const reflector = new Reflector();
@@ -1110,3 +1111,194 @@ describe('InfraController.requestRestart constrains teardown to managed profiles
expect(removed).not.toContain('evil');
});
});
+
+// C002: the infra module exposed sensitive ADMIN operations (credential config write, restart/Docker
+// orchestration, full-DB + storage export/import) with no audit trail. Each now emits an AuditAction.
+describe('InfraController C002 audit trail (light-dependency handlers)', () => {
+ const makeAudit = (): { logInfo: jest.Mock } => ({ logInfo: jest.fn().mockResolvedValue(null) });
+
+ // Positional constructor: (config, mainDs, dataDs, engineFactory, dockerService, cacheService,
+ // storageService, shutdownService, webhookQueue?, auditService?). auditService is the last @Optional arg.
+ const build = (
+ audit: { logInfo: jest.Mock },
+ overrides: Partial<{
+ config: unknown;
+ dataDs: unknown;
+ engineFactory: unknown;
+ dockerService: unknown;
+ storageService: unknown;
+ shutdownService: unknown;
+ }> = {},
+ ): InfraController =>
+ new InfraController(
+ (overrides.config ?? {}) as never,
+ {} as never,
+ (overrides.dataDs ?? {}) as never,
+ (overrides.engineFactory ?? {}) as never,
+ (overrides.dockerService ?? {}) as never,
+ {} as never,
+ (overrides.storageService ?? {}) as never,
+ (overrides.shutdownService ?? {}) as never,
+ undefined as never,
+ audit as never,
+ );
+
+ it('saveConfig emits INFRA_CONFIG_SAVED without leaking secret values into the metadata', () => {
+ const audit = makeAudit();
+ build(audit).saveConfig({ database: { type: 'postgres', host: 'db', password: 'topsecret' } } as never);
+ expect(audit.logInfo).toHaveBeenCalledTimes(1);
+ const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { sections: string[] } }]>;
+ const [action, ctx] = calls[0];
+ expect(action).toBe(AuditAction.INFRA_CONFIG_SAVED);
+ expect(ctx.metadata.sections).toContain('database');
+ // Only section names + profiles are recorded — never a secret value.
+ expect(JSON.stringify(ctx)).not.toContain('topsecret');
+ });
+
+ it('saveConfig does NOT emit when the payload is rejected (unknown engine)', () => {
+ const audit = makeAudit();
+ const controller = build(audit, { engineFactory: { getAvailableEngines: () => [{ id: 'baileys' }] } });
+ expect(() => controller.saveConfig({ engine: { type: 'bogus' } })).toThrow(BadRequestException);
+ expect(audit.logInfo).not.toHaveBeenCalled();
+ });
+
+ it('requestRestart emits INFRA_RESTART_REQUESTED with the requested profiles', async () => {
+ const audit = makeAudit();
+ const controller = build(audit, {
+ config: { get: () => undefined },
+ dockerService: { isDockerAvailable: () => false },
+ shutdownService: { shutdown: jest.fn() },
+ });
+ await controller.requestRestart({ profiles: ['postgres'], profilesToRemove: [] });
+ const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { profiles: string[] } }]>;
+ expect(calls[0][0]).toBe(AuditAction.INFRA_RESTART_REQUESTED);
+ expect(calls[0][1].metadata.profiles).toEqual(['postgres']);
+ });
+
+ it('exportData emits INFRA_DATA_EXPORTED with per-table counts', async () => {
+ const audit = makeAudit();
+ const controller = build(audit, {
+ config: { get: (k: string, d?: unknown) => (k === 'dataDatabase.type' ? 'sqlite' : d) },
+ dataDs: { query: jest.fn().mockResolvedValue([]) },
+ });
+ await controller.exportData();
+ const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { counts: { sessions: number } } }]>;
+ expect(calls[0][0]).toBe(AuditAction.INFRA_DATA_EXPORTED);
+ expect(calls[0][1].metadata.counts.sessions).toBe(0);
+ });
+
+ it('importStorage emits INFRA_STORAGE_IMPORTED with the imported file count', async () => {
+ const audit = makeAudit();
+ const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('/srv/openwa');
+ (fs.existsSync as jest.Mock).mockImplementation((p: string) => p === '/srv/openwa/data/exports/x.tar.gz');
+ try {
+ const storageService = { importFromStream: jest.fn().mockResolvedValue(5), getCurrentStorageType: () => 'local' };
+ await build(audit, { storageService }).importStorage({ filePath: 'data/exports/x.tar.gz' });
+ const calls = audit.logInfo.mock.calls as Array<
+ [AuditAction, { metadata: { count: number; storageType: string } }]
+ >;
+ expect(calls[0][0]).toBe(AuditAction.INFRA_STORAGE_IMPORTED);
+ expect(calls[0][1].metadata).toEqual({ count: 5, storageType: 'local' });
+ } finally {
+ cwdSpy.mockRestore();
+ (fs.existsSync as jest.Mock).mockReturnValue(false);
+ }
+ });
+
+ it('exportStorage emits INFRA_STORAGE_EXPORTED', async () => {
+ const audit = makeAudit();
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-audit-'));
+ const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(cwd);
+ process.env.STORAGE_EXPORT_TTL_MS = '30';
+ try {
+ const storageService = { createExportStream: jest.fn().mockResolvedValue(Readable.from([Buffer.from('x')])) };
+ await build(audit, { storageService }).exportStorage();
+ const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { download: string } }]>;
+ expect(calls[0][0]).toBe(AuditAction.INFRA_STORAGE_EXPORTED);
+ expect(typeof calls[0][1].metadata.download).toBe('string');
+ } finally {
+ cwdSpy.mockRestore();
+ fs.rmSync(cwd, { recursive: true, force: true });
+ delete process.env.STORAGE_EXPORT_TTL_MS;
+ }
+ });
+});
+
+describe('InfraController C002 audit trail — import emits only on a committed restore', () => {
+ let ds: DataSource;
+ const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };
+ const build = (audit: { logInfo: jest.Mock }): InfraController =>
+ new InfraController(
+ cfg as never,
+ {} as never,
+ ds,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ undefined as never,
+ audit as never,
+ );
+
+ beforeEach(async () => {
+ ds = new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [
+ Session,
+ Webhook,
+ Message,
+ MessageBatch,
+ PluginInstance,
+ ConversationMapping,
+ IngressEvent,
+ WebhookDeliveryFailure,
+ IntegrationDeliveryFailure,
+ ],
+ synchronize: true,
+ });
+ await ds.initialize();
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ const seedSession = (id: string) =>
+ ds.getRepository(Session).save(
+ ds.getRepository(Session).create({
+ id,
+ name: `session-${id}`,
+ status: SessionStatus.READY,
+ phone: null,
+ pushName: null,
+ config: {},
+ proxyUrl: null,
+ proxyType: null,
+ connectedAt: null,
+ lastActiveAt: null,
+ }),
+ );
+
+ it('emits INFRA_DATA_EXPORTED then INFRA_DATA_IMPORTED across a successful round-trip', async () => {
+ await seedSession('s1');
+ const audit = { logInfo: jest.fn().mockResolvedValue(null) };
+ const controller = build(audit);
+ const dump = await controller.exportData();
+ const res = await controller.importData({ tables: dump.tables });
+ expect(res.imported).toBe(true);
+ const actions = (audit.logInfo.mock.calls as Array<[AuditAction, unknown]>).map(c => c[0]);
+ expect(actions).toContain(AuditAction.INFRA_DATA_EXPORTED);
+ expect(actions).toContain(AuditAction.INFRA_DATA_IMPORTED);
+ });
+
+ it('does NOT emit INFRA_DATA_IMPORTED when an empty backup is refused (no data changed)', async () => {
+ await seedSession('s1');
+ const audit = { logInfo: jest.fn().mockResolvedValue(null) };
+ const res = await build(audit).importData({ tables: {} });
+ expect(res.imported).toBe(false);
+ const actions = (audit.logInfo.mock.calls as Array<[AuditAction, unknown]>).map(c => c[0]);
+ expect(actions).not.toContain(AuditAction.INFRA_DATA_IMPORTED);
+ });
+});
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index 2a3e66728..db6b92830 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -31,6 +31,8 @@ import { StorageService } from '../../common/storage/storage.service';
import { ShutdownService } from '../../common/services/shutdown.service';
import { createLogger } from '../../common/services/logger.service';
import { isMissingTableError } from '../../common/utils/db-errors';
+import { AuditService } from '../audit/audit.service';
+import { AuditAction } from '../audit/entities/audit-log.entity';
import { ImportStorageDto } from './dto/import-storage.dto';
import * as fs from 'fs';
import * as path from 'path';
@@ -487,6 +489,12 @@ export class InfraController {
@Optional()
@InjectQueue(QUEUE_NAMES.WEBHOOK)
private readonly webhookQueue?: Queue,
+ // Best-effort audit emission for the sensitive infra operations below. Injected @Optional and
+ // appended last so it never shifts the existing positional args: the running app always provides
+ // the @Global AuditService, while the direct-construction unit tests omit it — the `?.` at each
+ // call site then makes emission a no-op there instead of forcing every test to wire a mock.
+ @Optional()
+ private readonly auditService?: AuditService,
) {}
/** Bound the DB liveness probe so a hung connection can't stall the status read. */
@@ -904,6 +912,13 @@ export class InfraController {
writeSecretFile(envPath, contents);
this.logger.log('Configuration saved', { envPath });
+ // Audit the credential-bearing env mutation. Fire-and-forget (not awaited) so saveConfig stays
+ // synchronous — its validation rejections must remain synchronous throws the tests assert via
+ // `.toThrow`. Only section names + Docker profiles are recorded; secret values are never logged.
+ void this.auditService?.logInfo(AuditAction.INFRA_CONFIG_SAVED, {
+ metadata: { sections: Object.keys(config ?? {}), profiles },
+ });
+
const profileMsg = profiles.length > 0 ? ` Docker profiles required: ${profiles.join(', ')}.` : '';
return {
@@ -1015,6 +1030,12 @@ export class InfraController {
}
}
+ // Record the operational action (Docker orchestration + scheduled restart) BEFORE starting the
+ // shutdown, awaited so the row is persisted even as the process goes down.
+ await this.auditService?.logInfo(AuditAction.INFRA_RESTART_REQUESTED, {
+ metadata: { profiles, profilesToRemove },
+ });
+
// Schedule graceful shutdown after the configurable bounded grace (SHUTDOWN_DELAY_MS,
// default 3s) — readiness reports 503 during the window so traffic drains first.
void this.shutdownService.shutdown();
@@ -1156,6 +1177,26 @@ export class InfraController {
this.logger.debug('integration_delivery_failures table not available for export', { error: String(error) });
}
+ const counts = {
+ sessions: sessions.length,
+ webhooks: webhooks.length,
+ messages: messages.length,
+ messageBatches: messageBatches.length,
+ templates: templates.length,
+ baileysStoredMessages: baileysStoredMessages.length,
+ lidMappings: lidMappings.length,
+ pluginInstances: pluginInstances.length,
+ conversationMappings: conversationMappings.length,
+ ingressEvents: ingressEvents.length,
+ webhookDeliveryFailures: webhookDeliveryFailures.length,
+ integrationDeliveryFailures: integrationDeliveryFailures.length,
+ };
+
+ // Audit the full-DB export: this payload carries webhook + plugin-instance secrets, so WHO pulled
+ // a dump (and the per-table row counts) is exactly the trail C002 was missing. Data itself is never
+ // logged — only counts.
+ await this.auditService?.logInfo(AuditAction.INFRA_DATA_EXPORTED, { metadata: { counts } });
+
return {
exportedAt: new Date().toISOString(),
dataDbType: this.configService.get<string>('dataDatabase.type', 'sqlite'),
@@ -1173,20 +1214,7 @@ export class InfraController {
webhookDeliveryFailures,
integrationDeliveryFailures,
},
- counts: {
- sessions: sessions.length,
- webhooks: webhooks.length,
- messages: messages.length,
- messageBatches: messageBatches.length,
- templates: templates.length,
- baileysStoredMessages: baileysStoredMessages.length,
- lidMappings: lidMappings.length,
- pluginInstances: pluginInstances.length,
- conversationMappings: conversationMappings.length,
- ingressEvents: ingressEvents.length,
- webhookDeliveryFailures: webhookDeliveryFailures.length,
- integrationDeliveryFailures: integrationDeliveryFailures.length,
- },
+ counts,
};
}
@@ -1676,6 +1704,13 @@ export class InfraController {
}
await queryRunner.commitTransaction();
+
+ // Audit the destructive replace-all restore, only on the committed-success path (the rollback /
+ // refused-empty branches above return without emitting, since no data actually changed).
+ await this.auditService?.logInfo(AuditAction.INFRA_DATA_IMPORTED, {
+ metadata: { counts, warnings: warnings.length },
+ });
+
return { imported: true, counts, warnings };
} catch (error) {
await queryRunner.rollbackTransaction();
@@ -1742,12 +1777,17 @@ export class InfraController {
fs.promises.unlink(exportPath).catch(() => undefined);
}, ttlMs).unref();
+ // cwd-relative rather than an absolute host path: doesn't leak the filesystem layout, and the
+ // import round-trip still works because importStorage's existsSync/createReadStream resolve a
+ // relative filePath against the same cwd this was made relative to.
+ const download = path.relative(process.cwd(), exportPath);
+
+ // Audit the bulk media-export (all stored files leave the box as one archive).
+ await this.auditService?.logInfo(AuditAction.INFRA_STORAGE_EXPORTED, { metadata: { download } });
+
return {
message: 'Storage export completed',
- // cwd-relative rather than an absolute host path: doesn't leak the filesystem layout, and the
- // import round-trip still works because importStorage's existsSync/createReadStream resolve a
- // relative filePath against the same cwd this was made relative to.
- download: path.relative(process.cwd(), exportPath),
+ download,
};
}
@@ -1778,11 +1818,17 @@ export class InfraController {
const readStream = fs.createReadStream(resolved);
const count = await this.storageService.importFromStream(readStream);
+ const storageType = this.storageService.getCurrentStorageType();
+
+ // Audit the bulk media-import (files written into the active storage backend).
+ await this.auditService?.logInfo(AuditAction.INFRA_STORAGE_IMPORTED, {
+ metadata: { count, storageType },
+ });
return {
imported: true,
count,
- storageType: this.storageService.getCurrentStorageType(),
+ storageType,
};
}
}