Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(integration): retract a removed secret from the base config

Yudhi Armyndharis4ad9fa62e825
diff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.ts
index 0d7956359..7ab2b8f14 100644
--- a/src/modules/integration/integration-instance.controller.spec.ts
+++ b/src/modules/integration/integration-instance.controller.spec.ts
@@ -193,6 +193,89 @@ describe('IntegrationInstanceController provisioning bridge', () => {
expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-2', { baseUrl: 'https://y' }); // new bound
});
+ describe('a secret removed from a wildcard instance', () => {
+ const manifest = {
+ id: 'chatwoot-adapter',
+ ingress: [{ route: 'chatwoot' }],
+ permissions: ['webhook:ingress'],
+ configSchema: {
+ type: 'object',
+ properties: { apiToken: { type: 'string', secret: true }, baseUrl: { type: 'string' } },
+ },
+ };
+ const row = (sessionScope: string | null, config: Record<string, unknown>) => ({
+ pluginId: 'chatwoot-adapter',
+ instanceId: 'acct1',
+ sessionScope,
+ config,
+ enabled: true,
+ });
+
+ /** `before` is the row PATCH reads; `after` is what update() stores once the null secret is dropped. */
+ function patchWith(before: ReturnType<typeof row>, after: ReturnType<typeof row>) {
+ const { loader, audit, updatePluginConfig, setPluginSessionConfig } = build();
+ (loader.getPlugin as jest.Mock).mockReturnValue({ manifest, activeSessions: ['*'] });
+ const instances = {
+ resolve: jest.fn().mockResolvedValue(before),
+ update: jest.fn().mockResolvedValue(after),
+ list: jest.fn().mockResolvedValue([after]),
+ maskedView: (i: unknown) => i,
+ } as unknown as PluginInstanceService;
+ const controller = new IntegrationInstanceController(
+ instances,
+ loader,
+ audit,
+ new ScopeBindingService(instances, loader, audit, sessions),
+ );
+ return { controller, updatePluginConfig, setPluginSessionConfig };
+ }
+
+ it('is retracted from the plugin base config, where the earlier projection left it', async () => {
+ const { controller, updatePluginConfig } = patchWith(
+ row(null, { apiToken: 'LEAKED', baseUrl: 'https://crm' }),
+ row(null, { baseUrl: 'https://crm' }),
+ );
+
+ await controller.patch('chatwoot-adapter', 'acct1', { config: { apiToken: null, baseUrl: 'https://crm' } });
+
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot-adapter', { baseUrl: 'https://crm', apiToken: null });
+ });
+
+ it('is also retracted when the config is replaced without it', async () => {
+ const { controller, updatePluginConfig } = patchWith(
+ row('*', { apiToken: 'LEAKED', baseUrl: 'https://crm' }),
+ row('*', { baseUrl: 'https://crm' }),
+ );
+
+ await controller.patch('chatwoot-adapter', 'acct1', { config: { baseUrl: 'https://crm' } });
+
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot-adapter', { baseUrl: 'https://crm', apiToken: null });
+ });
+
+ it('leaves the base config alone when the instance moves in from a concrete session', async () => {
+ const { controller, updatePluginConfig } = patchWith(
+ row('sess-1', { apiToken: 'SLICE-ONLY', baseUrl: 'https://crm' }),
+ row(null, { baseUrl: 'https://crm' }),
+ );
+
+ await controller.patch('chatwoot-adapter', 'acct1', { sessionScope: null });
+
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot-adapter', { baseUrl: 'https://crm' });
+ });
+
+ it('leaves the base config alone when the instance moves out to a concrete session', async () => {
+ const { controller, updatePluginConfig, setPluginSessionConfig } = patchWith(
+ row(null, { apiToken: 'LEAKED', baseUrl: 'https://crm' }),
+ row('sess-1', { baseUrl: 'https://crm' }),
+ );
+
+ await controller.patch('chatwoot-adapter', 'acct1', { sessionScope: 'sess-1' });
+
+ expect(updatePluginConfig).not.toHaveBeenCalled();
+ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', { baseUrl: 'https://crm' });
+ });
+ });
+
it('returns a bound instance to all sessions on PATCH sessionScope:null', async () => {
const { loader, audit, setPluginSessionConfig, setPluginSessions, updatePluginConfig } = build();
(loader.getPlugin as jest.Mock).mockReturnValue({
diff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.ts
index f78f953db..32866c246 100644
--- a/src/modules/integration/integration-instance.controller.ts
+++ b/src/modules/integration/integration-instance.controller.ts
@@ -136,6 +136,9 @@ export class IntegrationInstanceController {
let inst: PluginInstance | null = await this.resolveVisible(pluginId, instanceId, apiKey);
if (dto.sessionScope !== undefined) this.assertScopeWritable(apiKey, dto.sessionScope);
const previousScope = inst.sessionScope;
+ // Only a wildcard instance projected its config into the plugin's base config, where a secret it no
+ // longer defines would stay behind (see ScopeBindingService.applyScopeBinding).
+ const previousConfig = !previousScope || previousScope === '*' ? inst.config : undefined;
// One update() writes every field in a single save. Restoring the masked config can refuse the
// PATCH with a 400 before that save, so a rejected body changes nothing, `enabled` included.
if (dto.enabled !== undefined || dto.sessionScope !== undefined || dto.config !== undefined) {
@@ -155,7 +158,9 @@ export class IntegrationInstanceController {
if (previousScope !== updated.sessionScope) {
await this.scopeBinding.applyScopeBinding(pluginId, previousScope, {}, false);
}
- await this.scopeBinding.applyScopeBinding(pluginId, updated.sessionScope, updated.config ?? {}, updated.enabled);
+ await this.scopeBinding.applyScopeBinding(pluginId, updated.sessionScope, updated.config ?? {}, updated.enabled, {
+ previousConfig,
+ });
// Audit the successful update with the CHANGED FIELD NAMES only — never the values: a config patch
// can carry credentials, and audit metadata is not a credential store.
const updatedFields = (['enabled', 'sessionScope', 'config'] as const).filter(f => dto[f] !== undefined);
diff --git a/src/modules/integration/scope-binding.service.spec.ts b/src/modules/integration/scope-binding.service.spec.ts
index 6ff1bdfa5..735dcdddc 100644
--- a/src/modules/integration/scope-binding.service.spec.ts
+++ b/src/modules/integration/scope-binding.service.spec.ts
@@ -560,3 +560,115 @@ describe('ScopeBindingService.resyncAfterImport', () => {
await expect(service.resyncAfterImport([])).rejects.toThrow('db down');
});
});
+
+/**
+ * A wildcard instance is projected into the plugin's BASE config, and that write merges, so it cannot
+ * delete a key. A secret the instance no longer defines (the operator revoked it) stayed in the base
+ * config, in registry.json and in every hook and ingress delivery's config, while the instance row and
+ * its GET already showed it gone.
+ */
+describe('ScopeBindingService.applyScopeBinding retracts a secret an instance no longer defines', () => {
+ const schema = {
+ type: 'object',
+ properties: {
+ apiToken: { type: 'string', secret: true },
+ baseUrl: { type: 'string' },
+ replyDelayMs: { type: 'number' },
+ crm: { type: 'object', properties: { key: { type: 'string', secret: true }, url: { type: 'string' } } },
+ },
+ };
+
+ function build() {
+ const updatePluginConfig = jest.fn();
+ const setPluginSessionConfig = jest.fn();
+ const loader = {
+ getPlugin: jest
+ .fn()
+ .mockReturnValue({ manifest: { id: 'chatwoot', configSchema: schema }, activeSessions: ['*'] }),
+ setPluginSessionConfig,
+ setPluginSessions: jest.fn(),
+ updatePluginConfig,
+ } as unknown as PluginLoaderService;
+ const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;
+ const sessions = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as Repository<Session>;
+ const list = jest.fn().mockResolvedValue([]);
+ const svc = new ScopeBindingService({ list } as unknown as PluginInstanceService, loader, audit, sessions);
+ return { svc, list, updatePluginConfig, setPluginSessionConfig };
+ }
+
+ const sibling = (
+ instanceId: string,
+ config: Record<string, unknown>,
+ enabled = true,
+ sessionScope: string | null = null,
+ ) => ({
+ pluginId: 'chatwoot',
+ instanceId,
+ sessionScope,
+ config,
+ enabled,
+ });
+
+ it('writes null for the removed secret together with the rest of the instance config', async () => {
+ const { svc, updatePluginConfig } = build();
+
+ await svc.applyScopeBinding('chatwoot', null, { baseUrl: 'https://crm' }, true, {
+ previousConfig: { apiToken: 'LEAKED', baseUrl: 'https://crm' },
+ });
+
+ expect(updatePluginConfig).toHaveBeenCalledTimes(1);
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot', { baseUrl: 'https://crm', apiToken: null });
+ });
+
+ it('retracts a secret nested under a key the instance dropped, and leaves a plain key alone', async () => {
+ const { svc, updatePluginConfig } = build();
+
+ await svc.applyScopeBinding('chatwoot', '*', { baseUrl: 'https://crm' }, true, {
+ previousConfig: { baseUrl: 'https://crm', replyDelayMs: 5, crm: { key: 'K', url: 'https://x' } },
+ });
+
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot', { baseUrl: 'https://crm', crm: null });
+ });
+
+ it('hands the base the value another enabled wildcard instance still defines, not the removed one', async () => {
+ const { svc, list, updatePluginConfig } = build();
+ list.mockResolvedValue([
+ sibling('a', { baseUrl: 'https://crm' }),
+ sibling('b', { apiToken: 'B-OLD' }),
+ sibling('c', { apiToken: 'C-TOKEN' }),
+ sibling('d', { apiToken: 'D-DISABLED' }, false),
+ sibling('e', { apiToken: 'E-CONCRETE' }, true, 'sess-1'),
+ ]);
+
+ await svc.applyScopeBinding('chatwoot', null, { baseUrl: 'https://crm' }, true, {
+ previousConfig: { apiToken: 'LEAKED', baseUrl: 'https://crm' },
+ });
+
+ // The last wildcard instance by id wins, as it does when boot reconciliation replays them.
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot', { baseUrl: 'https://crm', apiToken: 'C-TOKEN' });
+ });
+
+ it('only looks at siblings when a secret was removed', async () => {
+ const { svc, list, updatePluginConfig } = build();
+
+ await svc.applyScopeBinding('chatwoot', null, { apiToken: 'NEW' }, true, {
+ previousConfig: { apiToken: 'OLD' },
+ });
+ await svc.applyScopeBinding('chatwoot', null, { baseUrl: 'https://crm' }, true);
+
+ expect(list).not.toHaveBeenCalled();
+ expect(updatePluginConfig).toHaveBeenNthCalledWith(1, 'chatwoot', { apiToken: 'NEW' });
+ expect(updatePluginConfig).toHaveBeenNthCalledWith(2, 'chatwoot', { baseUrl: 'https://crm' });
+ });
+
+ it('never touches the base config for a concrete scope, whose slice is replaced whole', async () => {
+ const { svc, updatePluginConfig, setPluginSessionConfig } = build();
+
+ await svc.applyScopeBinding('chatwoot', 'sess-1', { baseUrl: 'https://crm' }, true, {
+ previousConfig: { apiToken: 'LEAKED', baseUrl: 'https://crm' },
+ });
+
+ expect(updatePluginConfig).not.toHaveBeenCalled();
+ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot', 'sess-1', { baseUrl: 'https://crm' });
+ });
+});
diff --git a/src/modules/integration/scope-binding.service.ts b/src/modules/integration/scope-binding.service.ts
index f81985d56..a38dded22 100644
--- a/src/modules/integration/scope-binding.service.ts
+++ b/src/modules/integration/scope-binding.service.ts
@@ -7,8 +7,16 @@ import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
import { Session } from '../session/entities/session.entity';
import { PluginInstanceService } from './plugin-instance.service';
import { PluginInstance } from './entities/plugin-instance.entity';
+import type { PluginConfigField } from '../../core/plugins/plugin.interfaces';
import { createLogger } from '../../common/services/logger.service';
+/** Whether a config field is a secret, or holds one at any depth. */
+const holdsSecret = (field: PluginConfigField | undefined): boolean =>
+ !!field &&
+ (field.secret === true || Object.values(field.properties ?? {}).some(holdsSecret) || holdsSecret(field.items));
+
+const isDefined = (value: unknown): boolean => value != null && value !== '';
+
/**
* Owns the provisioning bridge that makes a persisted plugin instance's config reach the ingress
* worker: it mirrors the instance config into the plugin's per-session config and toggles the bound
@@ -176,13 +184,16 @@ export class ScopeBindingService implements OnApplicationBootstrap {
* instance row would silently overwrite that operator choice — and bind the plugin to the row's
* scope even when that session has since been deleted, leaving it activated for nothing. So the boot
* path only ever ADDS the row's scope; it removes nothing.
+ *
+ * `previousConfig` is what a wildcard instance held before the change being applied. The base config
+ * merges, so a secret that config no longer defines would otherwise stay in it; see retractedSecrets.
*/
async applyScopeBinding(
pluginId: string,
scope: string | null,
config: Record<string, unknown>,
activate: boolean,
- opts: { additive?: boolean } = {},
+ opts: { additive?: boolean; previousConfig?: Record<string, unknown> | null } = {},
): Promise<void> {
try {
if (!scope || scope === '*') {
@@ -192,7 +203,10 @@ export class ScopeBindingService implements OnApplicationBootstrap {
// 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.updatePluginConfig(pluginId, {
+ ...(await this.retractedSecrets(pluginId, config, opts.previousConfig)),
+ ...config,
+ });
this.loader.setPluginSessions(pluginId, ['*']);
return;
}
@@ -262,4 +276,31 @@ export class ScopeBindingService implements OnApplicationBootstrap {
});
}
}
+
+ /**
+ * What to write over the base config to take back the secrets `previous` held and `config` no longer
+ * defines. The wildcard projection only merges, so on its own it cannot delete a key: a secret the
+ * operator revoked would stay in the base config, in registry.json and in the config of every hook and
+ * ingress delivery. Each is written as the value another enabled wildcard instance still defines (the
+ * last by id, as boot reconciliation replays them), else as null, which is how a removed top-level
+ * secret is stored there. Siblings are read only when a secret was actually removed.
+ */
+ private async retractedSecrets(
+ pluginId: string,
+ config: Record<string, unknown>,
+ previous: Record<string, unknown> | null | undefined,
+ ): Promise<Record<string, unknown>> {
+ const before = previous ?? {};
+ const properties = this.loader.getPlugin(pluginId)?.manifest.configSchema?.properties ?? {};
+ const removed = Object.keys(before).filter(
+ key => holdsSecret(properties[key]) && isDefined(before[key]) && !isDefined(config[key]),
+ );
+ if (removed.length === 0) return {};
+ const siblings = (await this.instances.list(pluginId))
+ .filter(row => row.enabled && (!row.sessionScope || row.sessionScope === '*'))
+ .sort((a, b) => String(a.instanceId).localeCompare(String(b.instanceId)));
+ return Object.fromEntries(
+ removed.map(key => [key, siblings.findLast(row => isDefined(row.config?.[key]))?.config?.[key] ?? null]),
+ );
+ }
}