Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(integration): retract a retired instance's secrets

Yudhi Armyndharis9df5eb9c322e
diff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.ts
index 7ab2b8f14..52b94e056 100644
--- a/src/modules/integration/integration-instance.controller.spec.ts
+++ b/src/modules/integration/integration-instance.controller.spec.ts
@@ -203,22 +203,23 @@ describe('IntegrationInstanceController provisioning bridge', () => {
properties: { apiToken: { type: 'string', secret: true }, baseUrl: { type: 'string' } },
},
};
- const row = (sessionScope: string | null, config: Record<string, unknown>) => ({
+ const row = (sessionScope: string | null, config: Record<string, unknown>, enabled = true) => ({
pluginId: 'chatwoot-adapter',
instanceId: 'acct1',
sessionScope,
config,
- enabled: true,
+ enabled,
});
- /** `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>) {
+ /** `before` is the row PATCH reads; `after` is what update() stores; `others` are the sibling rows. */
+ function patchWith(before: ReturnType<typeof row>, after: ReturnType<typeof row>, others: unknown[] = []) {
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]),
+ remove: jest.fn().mockResolvedValue(true),
+ list: jest.fn().mockResolvedValue([after, ...others]),
maskedView: (i: unknown) => i,
} as unknown as PluginInstanceService;
const controller = new IntegrationInstanceController(
@@ -230,6 +231,14 @@ describe('IntegrationInstanceController provisioning bridge', () => {
return { controller, updatePluginConfig, setPluginSessionConfig };
}
+ /** DELETE reads the row, removes it, then lists what is left: only `others`. */
+ function deleteWith(before: ReturnType<typeof row>, others: unknown[] = []) {
+ const built = patchWith(before, before, others);
+ const instances = (built.controller as unknown as { instances: { list: jest.Mock } }).instances;
+ instances.list.mockResolvedValue(others);
+ return built;
+ }
+
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' }),
@@ -263,16 +272,72 @@ describe('IntegrationInstanceController provisioning bridge', () => {
expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot-adapter', { baseUrl: 'https://crm' });
});
- it('leaves the base config alone when the instance moves out to a concrete session', async () => {
+ // The wildcard projection only merges, so whatever an instance projected stays in the base config after
+ // it stops contributing. Its secrets are taken back when it is disabled, deleted or moved off the scope.
+ const held = { apiToken: 'LEAKED', baseUrl: 'https://crm' };
+
+ it('is retracted when the instance moves out to a concrete session, which keeps it in its own slice', async () => {
const { controller, updatePluginConfig, setPluginSessionConfig } = patchWith(
- row(null, { apiToken: 'LEAKED', baseUrl: 'https://crm' }),
- row('sess-1', { baseUrl: 'https://crm' }),
+ row(null, held),
+ row('sess-1', held),
);
await controller.patch('chatwoot-adapter', 'acct1', { sessionScope: 'sess-1' });
- expect(updatePluginConfig).not.toHaveBeenCalled();
- expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', { baseUrl: 'https://crm' });
+ expect(updatePluginConfig).toHaveBeenCalledTimes(1);
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot-adapter', { apiToken: null });
+ expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-1', held);
+ });
+
+ it('is retracted when the instance is disabled', async () => {
+ const { controller, updatePluginConfig } = patchWith(row(null, held), row(null, held, false));
+
+ await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });
+
+ expect(updatePluginConfig).toHaveBeenCalledTimes(1);
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot-adapter', { apiToken: null });
+ });
+
+ it('is retracted when the instance is deleted', async () => {
+ const { controller, updatePluginConfig } = deleteWith(row('*', held));
+
+ await controller.remove('chatwoot-adapter', 'acct1');
+
+ expect(updatePluginConfig).toHaveBeenCalledTimes(1);
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot-adapter', { apiToken: null });
+ });
+
+ it('is handed back as the value another enabled wildcard instance still defines', async () => {
+ const sibling = { ...row(null, { apiToken: 'B-TOKEN' }), instanceId: 'acct2' };
+ const { controller, updatePluginConfig } = deleteWith(row(null, held), [sibling]);
+
+ await controller.remove('chatwoot-adapter', 'acct1');
+
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot-adapter', { apiToken: 'B-TOKEN' });
+ });
+
+ it('stays while the instance only moves between the spellings of the wildcard scope', async () => {
+ const { controller, updatePluginConfig } = patchWith(row(null, held), row('*', held));
+
+ await controller.patch('chatwoot-adapter', 'acct1', { sessionScope: '*' });
+
+ expect(updatePluginConfig).toHaveBeenCalledTimes(1);
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot-adapter', held);
+ });
+
+ it('is not retracted for an instance that was not contributing: disabled, or on a concrete session', async () => {
+ const disabled = patchWith(row(null, held, false), row(null, { baseUrl: 'https://crm' }, false));
+ await disabled.controller.patch('chatwoot-adapter', 'acct1', { config: { baseUrl: 'https://crm' } });
+ expect(disabled.updatePluginConfig).not.toHaveBeenCalled();
+
+ // Enabling it without the secret must not wipe a value the operator set on the plugin meanwhile.
+ const enabling = patchWith(row(null, held, false), row(null, { baseUrl: 'https://crm' }));
+ await enabling.controller.patch('chatwoot-adapter', 'acct1', { enabled: true });
+ expect(enabling.updatePluginConfig).toHaveBeenCalledWith('chatwoot-adapter', { baseUrl: 'https://crm' });
+
+ const concrete = deleteWith(row('sess-1', held));
+ await concrete.controller.remove('chatwoot-adapter', 'acct1');
+ expect(concrete.updatePluginConfig).not.toHaveBeenCalled();
});
});
diff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.ts
index 32866c246..65105c2ad 100644
--- a/src/modules/integration/integration-instance.controller.ts
+++ b/src/modules/integration/integration-instance.controller.ts
@@ -25,6 +25,17 @@ import { CreateInstanceDto, InstanceView, UpdateInstanceDto } from './dto/instan
import { sessionScopeVisible } from '../../common/security/session-scope';
import { ApiTags, ApiResponse } from '@nestjs/swagger';
+const isWildcardScope = (scope: string | null): boolean => !scope || scope === '*';
+
+/**
+ * What the instance has put into the plugin's base config: its config while it is enabled on the wildcard
+ * scope, nothing otherwise. That merged config is where a secret the instance stops contributing would stay
+ * behind (see ScopeBindingService.applyScopeBinding), and an instance that was not contributing, being
+ * disabled or on one session, left nothing there to take back.
+ */
+const contributedConfig = (inst: PluginInstance): Record<string, unknown> | undefined =>
+ inst.enabled && isWildcardScope(inst.sessionScope) ? (inst.config ?? undefined) : undefined;
+
// ADMIN-only provisioning surface for per-plugin instances (e.g. one Chatwoot account). Only plugins
// that declare an ingress route AND the webhook:ingress permission can have instances; everything
// else is rejected before touching persistence.
@@ -136,9 +147,7 @@ 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;
+ const previousConfig = contributedConfig(inst);
// 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) {
@@ -156,7 +165,11 @@ export class IntegrationInstanceController {
// 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.scopeBinding.applyScopeBinding(pluginId, previousScope, {}, false);
+ // A move between the spellings of the wildcard scope is re-bound right below: retracting here would
+ // only hand the running plugin a config without its secrets for the length of one call.
+ await this.scopeBinding.applyScopeBinding(pluginId, previousScope, {}, false, {
+ previousConfig: isWildcardScope(updated.sessionScope) ? undefined : previousConfig,
+ });
}
await this.scopeBinding.applyScopeBinding(pluginId, updated.sessionScope, updated.config ?? {}, updated.enabled, {
previousConfig,
@@ -184,7 +197,7 @@ export class IntegrationInstanceController {
// 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.scopeBinding.applyScopeBinding(pluginId, scope, {}, false);
+ await this.scopeBinding.applyScopeBinding(pluginId, scope, {}, false, { previousConfig: contributedConfig(inst) });
void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_DELETED, { metadata: { pluginId, instanceId } });
}
diff --git a/src/modules/integration/scope-binding.service.spec.ts b/src/modules/integration/scope-binding.service.spec.ts
index 735dcdddc..44da87f19 100644
--- a/src/modules/integration/scope-binding.service.spec.ts
+++ b/src/modules/integration/scope-binding.service.spec.ts
@@ -581,19 +581,20 @@ describe('ScopeBindingService.applyScopeBinding retracts a secret an instance no
function build() {
const updatePluginConfig = jest.fn();
const setPluginSessionConfig = jest.fn();
+ const setPluginSessions = jest.fn();
const loader = {
getPlugin: jest
.fn()
.mockReturnValue({ manifest: { id: 'chatwoot', configSchema: schema }, activeSessions: ['*'] }),
setPluginSessionConfig,
- setPluginSessions: jest.fn(),
+ setPluginSessions,
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 };
+ return { svc, list, updatePluginConfig, setPluginSessionConfig, setPluginSessions };
}
const sibling = (
@@ -648,6 +649,38 @@ describe('ScopeBindingService.applyScopeBinding retracts a secret an instance no
expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot', { baseUrl: 'https://crm', apiToken: 'C-TOKEN' });
});
+ it('retracts every secret the instance held when it is torn down, and ends the "*" activation as before', async () => {
+ const { svc, updatePluginConfig, setPluginSessions } = build();
+
+ await svc.applyScopeBinding('chatwoot', null, {}, false, {
+ previousConfig: { apiToken: 'LEAKED', baseUrl: 'https://crm', crm: { key: 'K', url: 'https://x' } },
+ });
+
+ expect(updatePluginConfig).toHaveBeenCalledTimes(1);
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot', { apiToken: null, crm: null });
+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot', []);
+ });
+
+ it('hands the base the value another enabled wildcard instance still defines when it is torn down', async () => {
+ const { svc, list, updatePluginConfig } = build();
+ list.mockResolvedValue([sibling('b', { apiToken: 'B-TOKEN' }), sibling('c', { baseUrl: 'https://c' })]);
+
+ await svc.applyScopeBinding('chatwoot', '*', {}, false, { previousConfig: { apiToken: 'LEAKED' } });
+
+ expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot', { apiToken: 'B-TOKEN' });
+ });
+
+ it('leaves the base config alone on a teardown that holds no secret, or that is given no previous config', async () => {
+ const { svc, list, updatePluginConfig } = build();
+
+ await svc.applyScopeBinding('chatwoot', null, {}, false, { previousConfig: { baseUrl: 'https://crm' } });
+ await svc.applyScopeBinding('chatwoot', null, {}, false, { previousConfig: null });
+ await svc.applyScopeBinding('chatwoot', null, {}, false);
+
+ expect(updatePluginConfig).not.toHaveBeenCalled();
+ expect(list).toHaveBeenCalledTimes(3); // only the '*' retirement check reads the siblings
+ });
+
it('only looks at siblings when a secret was removed', async () => {
const { svc, list, updatePluginConfig } = build();
diff --git a/src/modules/integration/scope-binding.service.ts b/src/modules/integration/scope-binding.service.ts
index a38dded22..b025fbc77 100644
--- a/src/modules/integration/scope-binding.service.ts
+++ b/src/modules/integration/scope-binding.service.ts
@@ -185,8 +185,9 @@ export class ScopeBindingService implements OnApplicationBootstrap {
* 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.
+ * `previousConfig` is what an enabled wildcard instance contributed to the base config before the change
+ * being applied. The base config merges, so a secret that the instance no longer defines (activation) or
+ * no longer contributes at all (teardown) would otherwise stay in it; see retractedSecrets.
*/
async applyScopeBinding(
pluginId: string,
@@ -210,6 +211,8 @@ export class ScopeBindingService implements OnApplicationBootstrap {
this.loader.setPluginSessions(pluginId, ['*']);
return;
}
+ const retracted = await this.retractedSecrets(pluginId, {}, opts.previousConfig);
+ if (Object.keys(retracted).length > 0) this.loader.updatePluginConfig(pluginId, retracted);
const rows = await this.instances.list(pluginId);
const anyWildcardLeft = rows.some(i => i.enabled && (!i.sessionScope || i.sessionScope === '*'));
if (!anyWildcardLeft) {
@@ -279,8 +282,9 @@ 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
+ * defines (none, for a teardown). The wildcard projection only merges, so on its own it cannot delete a
+ * key: a secret the operator revoked, or one of an instance that was disabled, deleted or moved off the
+ * wildcard scope, 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.