Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(integration): secret redaction and instance scope teardown hardening (#593)
Yudhi Armyndharisd2bc9460a6f4
diff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.tsindex 7b69681c1..467f6930d 100644--- a/src/modules/integration/integration-instance.controller.spec.ts+++ b/src/modules/integration/integration-instance.controller.spec.ts@@ -79,6 +79,53 @@ describe('IntegrationInstanceController provisioning bridge', () => {expect(setPluginSessions).toHaveBeenCalledWith('chatwoot-adapter', []);});+ it('retires the "*" activation when a wildcard-scope instance is disabled and no other wildcard remains', async () => {+ const { loader, audit, setPluginSessions } = build();+ (loader.getPlugin as jest.Mock).mockReturnValue({+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },+ activeSessions: ['*'],+ });+ const base = { pluginId: 'chatwoot-adapter', instanceId: 'acct1', sessionScope: '*', config: {} };+ const instances = {+ resolve: jest.fn().mockResolvedValue({ ...base, enabled: true }),+ setEnabled: jest.fn().mockResolvedValue({ ...base, enabled: false }),+ update: jest.fn(),+ list: jest.fn().mockResolvedValue([{ ...base, enabled: false }]), // only this one, now disabled+ maskedView: (i: unknown) => i,+ } as unknown as PluginInstanceService;+ const controller = new IntegrationInstanceController(instances, loader, audit);++ await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });++ // Previously a no-op: a disabled wildcard instance kept firing on every session. Now '*' is retired.+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot-adapter', []);+ });++ it('keeps "*" active when another enabled wildcard instance remains', async () => {+ const { loader, audit, setPluginSessions } = build();+ (loader.getPlugin as jest.Mock).mockReturnValue({+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },+ activeSessions: ['*'],+ });+ const base = { pluginId: 'chatwoot-adapter', instanceId: 'acct1', sessionScope: '*', config: {} };+ const instances = {+ resolve: jest.fn().mockResolvedValue({ ...base, enabled: true }),+ setEnabled: jest.fn().mockResolvedValue({ ...base, enabled: false }),+ update: jest.fn(),+ list: jest.fn().mockResolvedValue([+ { ...base, enabled: false },+ { pluginId: 'chatwoot-adapter', instanceId: 'acct2', sessionScope: '*', config: {}, enabled: true },+ ]),+ maskedView: (i: unknown) => i,+ } as unknown as PluginInstanceService;+ const controller = new IntegrationInstanceController(instances, loader, audit);++ await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });++ // A second wildcard instance is still enabled → '*' must NOT be retired.+ expect(setPluginSessions).not.toHaveBeenCalledWith('chatwoot-adapter', []);+ });+it('tears down the OLD scope when the bound session changes (PATCH sessionScope)', async () => {const { loader, audit, setPluginSessionConfig } = build();(loader.getPlugin as jest.Mock).mockReturnValue({diff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.tsindex 170f786f1..1b3b6ef84 100644--- a/src/modules/integration/integration-instance.controller.ts+++ b/src/modules/integration/integration-instance.controller.ts@@ -47,7 +47,7 @@ export class IntegrationInstanceController {void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_CREATED, {metadata: { pluginId, instanceId: dto.instanceId },});- this.applyScopeBinding(pluginId, inst.sessionScope, inst.config ?? {}, inst.enabled);+ await this.applyScopeBinding(pluginId, inst.sessionScope, inst.config ?? {}, inst.enabled);return this.view(inst, routes, /* reveal */ true);} catch (err) {if (err instanceof InstanceExistsError) throw new ConflictException(err.message);@@ -94,14 +94,21 @@ export class IntegrationInstanceController {const previousScope = inst.sessionScope;if (dto.enabled !== undefined) inst = await this.instances.setEnabled(pluginId, instanceId, dto.enabled);if (dto.sessionScope !== undefined || dto.config !== undefined) {- inst = await this.instances.update(pluginId, instanceId, { sessionScope: dto.sessionScope, config: dto.config });+ inst = await this.instances.update(+ pluginId,+ instanceId,+ { sessionScope: dto.sessionScope, config: dto.config },+ this.schemaFor(pluginId),+ );}const updated = inst as PluginInstance;- // If the bound session changed, tear down the old scope so it stops firing with stale config.- if (previousScope && previousScope !== '*' && previousScope !== updated.sessionScope) {- this.applyScopeBinding(pluginId, previousScope, {}, false);+ // If the bound session changed, tear down the OLD scope (incl. a wildcard/null scope) so it stops+ // firing with stale config. The new scope is (re)bound right after; teardown runs first with the new+ // scope already persisted, so the wildcard retirement check sees the current state correctly.+ if (previousScope !== updated.sessionScope) {+ await this.applyScopeBinding(pluginId, previousScope, {}, false);}- this.applyScopeBinding(pluginId, updated.sessionScope, updated.config ?? {}, updated.enabled);+ await this.applyScopeBinding(pluginId, updated.sessionScope, updated.config ?? {}, updated.enabled);return this.view(updated, this.pluginRoutes(pluginId), false);}@@ -110,9 +117,11 @@ export class IntegrationInstanceController {async remove(@Param('pluginId') pluginId: string, @Param('instanceId') instanceId: string): Promise<void> {const inst = await this.instances.resolve(pluginId, instanceId);if (!inst) throw new NotFoundException('instance not found');- // Deactivate + clear the session config BEFORE deletion (needs the instance's scope).- this.applyScopeBinding(pluginId, inst.sessionScope, {}, false);+ const scope = inst.sessionScope;+ // Delete the row FIRST, then tear down its scope: for a wildcard/null scope the teardown lists the+ // remaining instances to decide whether to retire '*', and that check must not count this instance.await this.instances.remove(pluginId, instanceId);+ await this.applyScopeBinding(pluginId, scope, {}, false);void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_DELETED, { metadata: { pluginId, instanceId } });}@@ -133,6 +142,12 @@ export class IntegrationInstanceController {return this.loader.getPlugin(pluginId)?.manifest.ingress?.map(r => r.route) ?? [];}+ // The plugin's declarative config schema, used to restore masked secrets on update (undefined when the+ // plugin is unloaded — restoreSecretConfig then fails closed).+ private schemaFor(pluginId: string) {+ return this.loader.getPlugin(pluginId)?.manifest.configSchema;+ }+private view(inst: PluginInstance, routes: string[], reveal: boolean): InstanceView {const schema = this.loader.getPlugin(inst.pluginId)?.manifest.configSchema;const masked = reveal ? inst : this.instances.maskedView(inst, schema);@@ -156,19 +171,33 @@ export class IntegrationInstanceController {// disabled or removed instance must not keep firing). A concrete scope writes sessionConfig[scope] and// toggles that session in activeSessions; a null/'*' scope binds the base config + all sessions ('*').// Best-effort: provisioning must not fail because the plugin is momentarily unloaded.- private applyScopeBinding(+ private async applyScopeBinding(pluginId: string,scope: string | null,config: Record<string, unknown>,activate: boolean,- ): void {+ ): Promise<void> {try {if (!scope || scope === '*') {- // 'all sessions' → base config + activate ['*']. A base binding cannot be cleanly torn down- // (updatePluginConfig merges, so one instance's keys aren't separable) — deactivation is a no-op.+ // 'all sessions' → base config + activate ['*']. The merged base config cannot be cleanly torn+ // down (updatePluginConfig merges, so one instance's keys aren't separable), but the '*'+ // activation CAN be retired: on deactivate, drop '*' from activeSessions ONLY when no OTHER+ // enabled instance still binds a wildcard/null scope — otherwise disabling/deleting a wildcard+ // instance would leave the plugin firing on every session with stale config.if (activate) {this.loader.updatePluginConfig(pluginId, config);this.loader.setPluginSessions(pluginId, ['*']);+ return;+ }+ const anyWildcardLeft = (await this.instances.list(pluginId)).some(+ i => i.enabled && (!i.sessionScope || i.sessionScope === '*'),+ );+ if (!anyWildcardLeft) {+ const current = this.loader.getPlugin(pluginId)?.activeSessions ?? [];+ this.loader.setPluginSessions(+ pluginId,+ current.filter(s => s !== '*'),+ );}return;}diff --git a/src/modules/integration/plugin-instance.service.spec.ts b/src/modules/integration/plugin-instance.service.spec.tsindex bc8f52820..1ea201c7a 100644--- a/src/modules/integration/plugin-instance.service.spec.ts+++ b/src/modules/integration/plugin-instance.service.spec.ts@@ -72,6 +72,44 @@ describe('PluginInstanceService', () => {const gen = await service.create('chatwoot-adapter', 'a4', {});expect(gen.secret).toMatch(/^[0-9a-f]{64}$/);});++ it('masks a NESTED secret:true config field on masked reads (recursive redaction)', () => {+ const schema = {+ type: 'object',+ properties: {+ provider: {+ type: 'object',+ properties: { apiToken: { type: 'string', secret: true }, region: { type: 'string' } },+ },+ },+ } as PluginConfigSchema;+ const inst = {+ id: 'p:i',+ secret: 'x',+ config: { provider: { apiToken: 'live-token', region: 'us' } },+ } as unknown as PluginInstance;+ const config = service.maskedView(inst, schema).config as { provider: Record<string, unknown> };+ expect(config.provider.apiToken).toBe('***');+ expect(config.provider.region).toBe('us');+ });++ it('update restores a masked (sentinel) secret to the stored value instead of persisting "***"', async () => {+ const schema = {+ type: 'object',+ properties: { apiToken: { type: 'string', secret: true }, accountId: { type: 'number' } },+ } as PluginConfigSchema;+ await service.create('chatwoot', 'acct1', { config: { apiToken: 'real-token', accountId: 1 } });++ // Dashboard round-trips the masked config back with an edited non-secret field.+ const updated = await service.update(+ 'chatwoot',+ 'acct1',+ { config: { apiToken: '***', accountId: 2 } },+ schema,+ );++ expect(updated?.config).toEqual({ apiToken: 'real-token', accountId: 2 });+ });});describe('PluginInstanceService provisioning', () => {diff --git a/src/modules/integration/plugin-instance.service.ts b/src/modules/integration/plugin-instance.service.tsindex a70dba5e3..7f9145358 100644--- a/src/modules/integration/plugin-instance.service.ts+++ b/src/modules/integration/plugin-instance.service.ts@@ -4,8 +4,7 @@ import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { PluginInstance } from './entities/plugin-instance.entity';import type { PluginConfigSchema } from '../../core/plugins/plugin.interfaces';--const SECRET_MASK = '***';+import { redactSecretConfig, restoreSecretConfig, SECRET_SENTINEL } from '../plugins/redact-config';// A supplied ingress secret must be a real, guessing-resistant value; an empty/short one would make the// public HMAC forgeable. Absent => auto-generate. Trimmed so pasted whitespace can't slip a weak secret in.@@ -18,24 +17,6 @@ function normalizeSecret(supplied?: string): string {return s;}-// Mask every config value the plugin's schema marks `secret:true` (e.g. a Chatwoot apiToken) on operator-// reads — core does not otherwise redact instance `config`. Top-level fields only (the declarative-// configSchema is flat for secret credentials).-function redactSecrets(- config: Record<string, unknown> | null,- schema?: PluginConfigSchema,-): Record<string, unknown> | null {- if (!config) return config;- // Schema unavailable (plugin unloaded / failed to load) — we can't tell which fields are secret, so- // fail closed by masking every value rather than risk leaking a credential such as an API token.- if (!schema?.properties) return Object.fromEntries(Object.keys(config).map(key => [key, SECRET_MASK]));- const out: Record<string, unknown> = { ...config };- for (const [key, field] of Object.entries(schema.properties)) {- if (key in out && field.secret) out[key] = SECRET_MASK;- }- return out;-}-export class InstanceExistsError extends Error {constructor(pluginId: string, instanceId: string) {super(`instance ${instanceId} already exists for plugin ${pluginId}`);@@ -73,9 +54,14 @@ export class PluginInstanceService {}// Operator-facing view: never leak the raw secret, and mask any `secret:true` config field (e.g. a- // provider apiToken) per the plugin's configSchema. Reuses the redact-config sentinel convention.+ // provider apiToken) per the plugin's configSchema — recursively, at any depth, and fail-closed when+ // the schema is unavailable — by reusing the shared redactSecretConfig (single source of truth).maskedView(instance: PluginInstance, schema?: PluginConfigSchema): PluginInstance {- return { ...instance, secret: SECRET_MASK, config: redactSecrets(instance.config, schema) };+ return {+ ...instance,+ secret: SECRET_SENTINEL,+ config: instance.config == null ? instance.config : redactSecretConfig(instance.config, schema),+ };}async create(@@ -120,11 +106,17 @@ export class PluginInstanceService {pluginId: string,instanceId: string,patch: { sessionScope?: string; config?: Record<string, unknown> },+ schema?: PluginConfigSchema,): Promise<PluginInstance | null> {const inst = await this.resolve(pluginId, instanceId);if (!inst) return null;if (patch.sessionScope !== undefined) inst.sessionScope = patch.sessionScope || null;- if (patch.config !== undefined) inst.config = patch.config;+ if (patch.config !== undefined) {+ // The operator view masks secrets as the sentinel, so a round-tripped config carries '***' for+ // unchanged secrets. Restore the stored values instead of persisting the mask (which would corrupt+ // the credential); genuinely-new values are written as provided.+ inst.config = restoreSecretConfig(patch.config, inst.config ?? undefined, schema);+ }return this.repo.save(inst);}diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex dcfa7bbf5..5a79ff37a 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -6,6 +6,7 @@ import { BadRequestException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';import { PluginsService, isIngressCapable } from './plugins.service';+import { SECRET_SENTINEL } from './redact-config';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { PluginStorageService } from '../../core/plugins/plugin-storage.service';import { PluginStatus } from '../../core/plugins/plugin.interfaces';@@ -89,7 +90,9 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {const dto = await service.updatePackage('svc-plg', pkg({ version: '2.0.0' }));expect(dto.version).toBe('2.0.0');- expect(dto.config).toEqual({ apiKey: 'secret-123' }); // config survived the in-place update+ // Read view masks config for a schemaless plugin (fail-closed), but the stored value survived the update.+ expect(dto.config).toEqual({ apiKey: SECRET_SENTINEL });+ expect(loader.getPlugin('svc-plg')?.config).toEqual({ apiKey: 'secret-123' });expect(fs.existsSync(path.join(pluginsDir, 'svc-plg', 'index.js'))).toBe(true);expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false); // backup cleaned up});diff --git a/src/modules/plugins/redact-config.spec.ts b/src/modules/plugins/redact-config.spec.tsindex f85b30e61..a50b7c07c 100644--- a/src/modules/plugins/redact-config.spec.ts+++ b/src/modules/plugins/redact-config.spec.ts@@ -28,12 +28,18 @@ describe('redactSecretConfig', () => {expect(redactSecretConfig({ endpoint: 'https://x' }, schema)).toEqual({ endpoint: 'https://x' });});- it('returns a copy unchanged when there is no schema', () => {- const cfg = { apiKey: 's3cr3t' };+ it('fails closed and masks every value when there is no schema (cannot tell which fields are secret)', () => {+ const cfg = { apiKey: 's3cr3t', endpoint: 'https://x' };const out = redactSecretConfig(cfg, undefined);- expect(out).toEqual(cfg);+ expect(out).toEqual({ apiKey: SECRET_SENTINEL, endpoint: SECRET_SENTINEL });expect(out).not.toBe(cfg); // copy, not the same ref});++ it('round-trips a schemaless config: sentinel values restore the stored value, edited values persist', () => {+ const masked = redactSecretConfig({ apiKey: 's3cr3t', region: 'us' }, undefined);+ const restored = restoreSecretConfig({ ...masked, region: 'eu' }, { apiKey: 's3cr3t', region: 'us' }, undefined);+ expect(restored).toEqual({ apiKey: 's3cr3t', region: 'eu' });+ });});describe('restoreSecretConfig', () => {diff --git a/src/modules/plugins/redact-config.ts b/src/modules/plugins/redact-config.tsindex fe87ba25b..50b61fd64 100644--- a/src/modules/plugins/redact-config.ts+++ b/src/modules/plugins/redact-config.ts@@ -48,7 +48,15 @@ export function redactSecretConfig(schema?: PluginConfigSchema,): Record<string, unknown> {const out = { ...(config ?? {}) };- if (!schema?.properties) return out;+ // Fail CLOSED when the schema is unavailable (plugin unloaded / failed to load): we can't tell which+ // fields are secret, so mask every meaningful value rather than leak a credential. Returning the+ // config unchanged here would expose runtime-stored secrets on GET /plugins.+ if (!schema?.properties) {+ for (const key of Object.keys(out)) {+ if (isMeaningful(out[key])) out[key] = SECRET_SENTINEL;+ }+ return out;+ }return redactObject(out, schema.properties);}@@ -172,6 +180,19 @@ export function restoreSecretConfig(existing: Record<string, unknown> | undefined,schema?: PluginConfigSchema,): Record<string, unknown> {- if (!schema?.properties) return { ...incoming };+ // Symmetric fail-closed restore for the schemaless case: redactSecretConfig masks EVERY value to the+ // sentinel, so on write treat any sentinel value as "keep existing" (restore the stored value, or drop+ // the key when nothing is stored). Returning `incoming` as-is would persist the sentinel and corrupt+ // the stored config. Non-sentinel values (genuinely edited) are kept verbatim.+ if (!schema?.properties) {+ const out = { ...incoming };+ const ex = existing ?? {};+ for (const key of Object.keys(out)) {+ if (out[key] !== SECRET_SENTINEL) continue;+ if (isMeaningful(ex[key])) out[key] = ex[key];+ else delete out[key];+ }+ return out;+ }return restoreObject(incoming, existing, schema.properties);}