Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(integration): stop boot scope reconciliation from clobbering operator-set sessions (#1035)
Yudhi Armyndharisc5d2142b2f96
diff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.tsindex 1977f561e..e6c5810b2 100644--- a/src/modules/integration/integration-instance.controller.spec.ts+++ b/src/modules/integration/integration-instance.controller.spec.ts@@ -5,8 +5,13 @@ import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { AuditService } from '../audit/audit.service';import { ScopeBindingService } from './scope-binding.service';+import { SessionService } from '../session/session.service';import { ApiKey } from '../auth/entities/api-key.entity';+// ScopeBindingService reads session rows only for its boot-time "this scope matches no session"+// warning; provisioning never reaches it, so these tests hand it a resolving stub.+const sessions = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as SessionService;+// The provisioning bridge is what makes a minted instance's config reach the ingress worker: on// create/patch it mirrors the instance config into the plugin's per-session config and activates the// bound session; on delete it clears both. dispatchWebhookForInstance then resolves it as ctx.config.@@ -50,7 +55,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.create('chatwoot-adapter', {@@ -86,7 +91,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });@@ -114,7 +119,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });@@ -144,7 +149,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });@@ -182,7 +187,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.patch('chatwoot-adapter', 'acct1', { sessionScope: 'sess-2' });@@ -213,7 +218,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });@@ -250,7 +255,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.remove('chatwoot-adapter', 'acct1');@@ -281,7 +286,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.remove('chatwoot-adapter', 'acct1');@@ -323,7 +328,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.patch('chatwoot-adapter', 'acct1', { sessionScope: 'sess-2' });@@ -354,7 +359,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.patch('chatwoot-adapter', 'acct1', { enabled: false });@@ -393,7 +398,7 @@ describe('IntegrationInstanceController provisioning bridge', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);await controller.create('chatwoot-adapter', {@@ -432,7 +437,7 @@ describe('IntegrationInstanceController session-scope fence', () => {svc,loader,audit,- new ScopeBindingService(svc, loader, audit),+ new ScopeBindingService(svc, loader, audit, sessions),);return { controller, svc };}@@ -622,7 +627,7 @@ describe('IntegrationInstanceController reveal masking', () => {instances,loader,audit,- new ScopeBindingService(instances, loader, audit),+ new ScopeBindingService(instances, loader, audit, sessions),);return { controller };}@@ -712,7 +717,7 @@ describe('IntegrationInstanceController update audit', () => {instances,loader,audit as unknown as AuditService,- new ScopeBindingService(instances, loader, audit as unknown as AuditService),+ new ScopeBindingService(instances, loader, audit as unknown as AuditService, sessions),);return { controller, audit, instances };}diff --git a/src/modules/integration/scope-binding.service.spec.ts b/src/modules/integration/scope-binding.service.spec.tsindex 62a3912a5..55e555331 100644--- a/src/modules/integration/scope-binding.service.spec.ts+++ b/src/modules/integration/scope-binding.service.spec.ts@@ -1,28 +1,43 @@+import { NotFoundException } from '@nestjs/common';import { ScopeBindingService } from './scope-binding.service';import { PluginInstanceService } from './plugin-instance.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { AuditService } from '../audit/audit.service';+import { SessionService } from '../session/session.service';// The boot-time reconciler re-derives each ENABLED instance's runtime scope binding from the persisted// plugin_instances rows, so a binding lost at provisioning time (plugin momentarily unloaded) is// restored on the next boot without an operator re-PATCH.describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {- function build(loaded = true) {+ // `activeSessions` seeds what the loader restored from registry.json — i.e. the state a prior+ // PUT /api/plugins/:id/sessions persisted, which the boot reconciler must not undo.+ function build(loaded = true, activeSessions: string[] = []) {const setPluginSessionConfig = jest.fn();const setPluginSessions = jest.fn();const updatePluginConfig = jest.fn();const loader = {- getPlugin: jest.fn().mockReturnValue(loaded ? { manifest: { id: 'chatwoot' }, activeSessions: [] } : undefined),+ getPlugin: jest.fn().mockReturnValue(loaded ? { manifest: { id: 'chatwoot' }, activeSessions } : undefined),setPluginSessionConfig,setPluginSessions,updatePluginConfig,} as unknown as PluginLoaderService;const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;- return { loader, audit, setPluginSessionConfig, setPluginSessions, updatePluginConfig };+ // Default: every bound scope resolves to a real session row, so the missing-session warning stays+ // quiet unless a test asks for it (SessionService.findOne throws NotFoundException for a gone row).+ const sessions = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as SessionService;+ return { loader, audit, sessions, setPluginSessionConfig, setPluginSessions, updatePluginConfig };}+ /** The service's own logger, for asserting the boot-time missing-session warning. */+ const loggerOf = (svc: ScopeBindingService): { warn: jest.Mock } =>+ (svc as unknown as { logger: { warn: jest.Mock } }).logger;++ /** The session list written by the nth setPluginSessions call, as an order-insensitive set. */+ const sessionsWritten = (mock: jest.Mock, call = 0): Set<string> =>+ new Set((mock.mock.calls[call] as [string, string[]])[1]);+it('restores an enabled concrete-scope instance (sessionConfig + activeSessions) on boot', async () => {- const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();+ const { loader, audit, sessions, setPluginSessionConfig, setPluginSessions } = build();const instances = {listAll: jest.fn()@@ -32,14 +47,66 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {list: jest.fn().mockResolvedValue([]),} as unknown as PluginInstanceService;- await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();+ await new ScopeBindingService(instances, loader, audit, sessions).onApplicationBootstrap();expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot', 'sess-1', { baseUrl: 'x' });expect(setPluginSessions).toHaveBeenCalledWith('chatwoot', ['sess-1']);});+ // Regression (live 0.12.1 host): an operator had put both plugins on ["*"] via+ // PUT /api/plugins/:id/sessions; it read back and persisted correctly. After a restart the boot+ // reconciler re-derived activeSessions from each instance row's concrete sessionScope and dropped+ // the '*' — binding both plugins to a session id that no longer existed, i.e. to nothing. Nothing+ // warned: the row still read `enabled`, hooks stayed registered, healthCheck stayed green, and the+ // plugins silently received no events. Boot RESTORES bindings, so it must only ever add.+ it('keeps an operator-set "*" when reconciling a concrete-scope instance on boot', async () => {+ const { loader, audit, sessions, setPluginSessions } = build(true, ['*']);+ const instances = {+ listAll: jest+ .fn()+ .mockResolvedValue([+ { pluginId: 'chatwoot', instanceId: 'a', sessionScope: 'sess-1', config: {}, enabled: true },+ ]),+ // No siblings: this must pass on the additive boot path alone, NOT on the wildcard-sibling+ // preservation guard, which would mask the bug here.+ list: jest.fn().mockResolvedValue([]),+ } as unknown as PluginInstanceService;++ await new ScopeBindingService(instances, loader, audit, sessions).onApplicationBootstrap();++ expect(setPluginSessions).toHaveBeenCalledTimes(1);+ expect(sessionsWritten(setPluginSessions)).toEqual(new Set(['*', 'sess-1']));+ });++ it('does not drop an unrelated already-active concrete session when reconciling on boot', async () => {+ const { loader, audit, sessions, setPluginSessions } = build(true, ['sess-other']);+ const instances = {+ listAll: jest+ .fn()+ .mockResolvedValue([+ { pluginId: 'chatwoot', instanceId: 'a', sessionScope: 'sess-1', config: {}, enabled: true },+ ]),+ list: jest.fn().mockResolvedValue([]),+ } as unknown as PluginInstanceService;++ await new ScopeBindingService(instances, loader, audit, sessions).onApplicationBootstrap();++ expect(sessionsWritten(setPluginSessions)).toEqual(new Set(['sess-other', 'sess-1']));+ });++ // The counterpart to the regression test above: provisioning IS a decision (the operator just+ // narrowed this plugin to one session), so that path must keep retiring '*' exactly as before.+ it('still retires "*" on a provisioning-time concrete activation (non-boot path unchanged)', async () => {+ const { loader, audit, sessions, setPluginSessions } = build(true, ['*']);+ const instances = { list: jest.fn().mockResolvedValue([]) } as unknown as PluginInstanceService;++ await new ScopeBindingService(instances, loader, audit, sessions).applyScopeBinding('chatwoot', 'sess-1', {}, true);++ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot', ['sess-1']);+ });+it('restores an enabled wildcard/null-scope instance as base config + ["*"]', async () => {- const { loader, audit, updatePluginConfig, setPluginSessions } = build();+ const { loader, audit, sessions, updatePluginConfig, setPluginSessions } = build();const instances = {listAll: jest.fn()@@ -48,14 +115,14 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {]),} as unknown as PluginInstanceService;- await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();+ await new ScopeBindingService(instances, loader, audit, sessions).onApplicationBootstrap();expect(updatePluginConfig).toHaveBeenCalledWith('chatwoot', { token: 't' });expect(setPluginSessions).toHaveBeenCalledWith('chatwoot', ['*']);});it('does NOT activate a disabled instance (honors the real enabled flag, never force-activates)', async () => {- const { loader, audit, setPluginSessionConfig, setPluginSessions } = build();+ const { loader, audit, sessions, setPluginSessionConfig, setPluginSessions } = build();const instances = {listAll: jest.fn()@@ -64,32 +131,103 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {]),} as unknown as PluginInstanceService;- await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();+ await new ScopeBindingService(instances, loader, audit, sessions).onApplicationBootstrap();expect(setPluginSessionConfig).not.toHaveBeenCalled();expect(setPluginSessions).not.toHaveBeenCalled();});it('skips an instance whose plugin is not loaded', async () => {- const { loader, audit, setPluginSessions } = build(/* loaded */ false);+ const { loader, audit, sessions, setPluginSessions } = build(/* loaded */ false);const instances = {listAll: jest.fn().mockResolvedValue([{ pluginId: 'ghost', instanceId: 'a', sessionScope: 'sess-1', config: {}, enabled: true }]),} as unknown as PluginInstanceService;- await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();+ await new ScopeBindingService(instances, loader, audit, sessions).onApplicationBootstrap();expect(setPluginSessions).not.toHaveBeenCalled();});it('does not throw when listing instances fails (reconciliation is best-effort)', async () => {- const { loader, audit } = build();+ const { loader, audit, sessions } = build();const instances = {listAll: jest.fn().mockRejectedValue(new Error('db down')),} as unknown as PluginInstanceService;- await expect(new ScopeBindingService(instances, loader, audit).onApplicationBootstrap()).resolves.toBeUndefined();+ await expect(+ new ScopeBindingService(instances, loader, audit, sessions).onApplicationBootstrap(),+ ).resolves.toBeUndefined();+ });++ // A scope pointing at a deleted session binds the plugin to nothing, and every other signal an+ // operator can read (instance `enabled`, plugin `status`, healthCheck) stays green — so the log line+ // is the only place the inertness can surface.+ it('warns when an enabled instance is bound to a session that no longer exists', async () => {+ const { loader, audit, setPluginSessions } = build();+ const instances = {+ listAll: jest+ .fn()+ .mockResolvedValue([+ { pluginId: 'chatwoot', instanceId: 'main', sessionScope: 'gone-sess', config: {}, enabled: true },+ ]),+ list: jest.fn().mockResolvedValue([]),+ } as unknown as PluginInstanceService;+ const sessions = {+ findOne: jest.fn().mockRejectedValue(new NotFoundException("Session with id 'gone-sess' not found")),+ } as unknown as SessionService;++ const svc = new ScopeBindingService(instances, loader, audit, sessions);+ const warn = jest.spyOn(loggerOf(svc), 'warn').mockImplementation(() => undefined);+ await svc.onApplicationBootstrap();++ expect(warn).toHaveBeenCalledTimes(1);+ const [message] = warn.mock.calls[0] as [string, Record<string, unknown>];+ expect(message).toContain('chatwoot');+ expect(message).toContain('main');+ expect(message).toContain('gone-sess');+ // Warning only — the binding is still applied (the session id may be recreated).+ expect(setPluginSessions).toHaveBeenCalledWith('chatwoot', ['gone-sess']);+ });++ it('does not warn when the bound session exists', async () => {+ const { loader, audit, sessions } = build();+ const instances = {+ listAll: jest+ .fn()+ .mockResolvedValue([+ { pluginId: 'chatwoot', instanceId: 'main', sessionScope: 'sess-1', config: {}, enabled: true },+ ]),+ list: jest.fn().mockResolvedValue([]),+ } as unknown as PluginInstanceService;++ const svc = new ScopeBindingService(instances, loader, audit, sessions);+ const warn = jest.spyOn(loggerOf(svc), 'warn').mockImplementation(() => undefined);+ await svc.onApplicationBootstrap();++ expect(warn).not.toHaveBeenCalled();+ });++ // A DB hiccup is not evidence the session is gone: reporting one as missing would send an operator+ // hunting a scope that is in fact fine.+ it('stays quiet when the session lookup fails for a reason other than a missing row', async () => {+ const { loader, audit } = build();+ const instances = {+ listAll: jest+ .fn()+ .mockResolvedValue([+ { pluginId: 'chatwoot', instanceId: 'main', sessionScope: 'sess-1', config: {}, enabled: true },+ ]),+ list: jest.fn().mockResolvedValue([]),+ } as unknown as PluginInstanceService;+ const sessions = { findOne: jest.fn().mockRejectedValue(new Error('db down')) } as unknown as SessionService;++ const svc = new ScopeBindingService(instances, loader, audit, sessions);+ const warn = jest.spyOn(loggerOf(svc), 'warn').mockImplementation(() => undefined);+ await expect(svc.onApplicationBootstrap()).resolves.toBeUndefined();++ expect(warn).not.toHaveBeenCalled();});it('ends at ["*"] for a plugin with a wildcard + concrete instance regardless of DB row order (order-independent)', async () => {@@ -106,6 +244,7 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {updatePluginConfig: jest.fn(),} as unknown as PluginLoaderService;const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;+ const sessionRows = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as SessionService;const wildcard = { pluginId: 'chatwoot', instanceId: 'wild', sessionScope: null, config: {}, enabled: true };const concrete = { pluginId: 'chatwoot', instanceId: 'conc', sessionScope: 'sess-1', config: {}, enabled: true };@@ -119,7 +258,7 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {listAll: jest.fn().mockResolvedValue(rowOrder),list: jest.fn().mockResolvedValue([]),} as unknown as PluginInstanceService;- await new ScopeBindingService(instances, loader, audit).onApplicationBootstrap();+ await new ScopeBindingService(instances, loader, audit, sessionRows).onApplicationBootstrap();// The wildcard activation must survive in both row orders ('*' subsumes the concrete scope).expect(plugin.activeSessions).toContain('*');}diff --git a/src/modules/integration/scope-binding.service.ts b/src/modules/integration/scope-binding.service.tsindex c1a1fb639..1d46e42ce 100644--- a/src/modules/integration/scope-binding.service.ts+++ b/src/modules/integration/scope-binding.service.ts@@ -1,7 +1,8 @@-import { Injectable, OnApplicationBootstrap } from '@nestjs/common';+import { Injectable, NotFoundException, OnApplicationBootstrap } from '@nestjs/common';import { AuditAction } from '../audit/entities/audit-log.entity';import { AuditService } from '../audit/audit.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { SessionService } from '../session/session.service';import { PluginInstanceService } from './plugin-instance.service';import { PluginInstance } from './entities/plugin-instance.entity';import { createLogger } from '../../common/services/logger.service';@@ -21,6 +22,7 @@ export class ScopeBindingService implements OnApplicationBootstrap {private readonly instances: PluginInstanceService,private readonly loader: PluginLoaderService,private readonly audit: AuditService,+ private readonly sessions: SessionService,) {}/**@@ -64,7 +66,8 @@ export class ScopeBindingService implements OnApplicationBootstrap {if (!inst.enabled) continue;// Skip instances whose plugin isn't loaded — applyScopeBinding would only no-op/log for them.if (!this.loader.getPlugin(inst.pluginId)) continue;- await this.applyScopeBinding(inst.pluginId, inst.sessionScope, inst.config ?? {}, true);+ await this.applyScopeBinding(inst.pluginId, inst.sessionScope, inst.config ?? {}, true, { additive: true });+ await this.warnIfScopeHasNoSession(inst);count++;}@@ -76,6 +79,37 @@ export class ScopeBindingService implements OnApplicationBootstrap {}}+ /**+ * Warn when a just-reconciled instance binds a concrete scope no session row matches — a session the+ * operator deleted, or a scope typed/copied wrong. The plugin is then activated for nothing: the+ * dispatch gate never matches that id, so it receives no events, while every signal an operator can+ * read stays reassuring (the instance row says `enabled`, the plugin's status says `enabled`, hooks+ * are registered and healthCheck is green). This log line is the only place that inertness surfaces.+ *+ * Diagnostic only — it never skips or alters the binding: the id may be recreated (an import or a+ * re-provision can restore the same session id), in which case the restored binding is exactly right.+ */+ private async warnIfScopeHasNoSession(inst: PluginInstance): Promise<void> {+ if (!inst.sessionScope || inst.sessionScope === '*') return;+ try {+ await this.sessions.findOne(inst.sessionScope);+ } catch (err) {+ // findOne throws NotFoundException only for a genuinely missing row. Any other failure (a DB+ // hiccup mid-boot) is not evidence the session is gone, and reporting it as gone would send an+ // operator hunting a binding that is in fact fine — so stay quiet rather than cry wolf.+ if (!(err instanceof NotFoundException)) return;+ this.logger.warn(+ `Plugin instance ${inst.pluginId}:${inst.instanceId} is bound to session '${inst.sessionScope}', which does not exist — it will receive no events until that session is restored or the instance is re-scoped`,+ {+ action: 'scope_binding_session_missing',+ pluginId: inst.pluginId,+ instanceId: inst.instanceId,+ sessionScope: inst.sessionScope,+ },+ );+ }+ }+/*** Bind an instance's config to the plugin's runtime so an ingress handler resolves it as ctx.config* (see PluginLoaderService.dispatchWebhookForInstance) and activate the session — iff `activate` (a@@ -85,12 +119,22 @@ export class ScopeBindingService implements OnApplicationBootstrap {* session + sessionConfig survive while a sibling binds the same scope, and '*' survives while a* sibling binds a wildcard/null scope.* Best-effort: provisioning must not fail because the plugin is momentarily unloaded.+ *+ * `additive` is for the boot reconciler, which RESTORES bindings rather than deciding them. Retiring+ * '*' on a concrete activation is a provisioning-time decision — the operator just narrowed this+ * plugin to one session, so it should stop firing on all of them. At boot there is no such new+ * decision to apply: activeSessions (restored from registry.json) already encodes the outcome of+ * every prior decision, including an explicit PUT /api/plugins/:id/sessions. Re-deriving it from the+ * 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.*/async applyScopeBinding(pluginId: string,scope: string | null,config: Record<string, unknown>,activate: boolean,+ opts: { additive?: boolean } = {},): Promise<void> {try {if (!scope || scope === '*') {@@ -129,7 +173,9 @@ export class ScopeBindingService implements OnApplicationBootstrap {}this.loader.setPluginSessionConfig(pluginId, scope, activate ? config : {});const current = this.loader.getPlugin(pluginId)?.activeSessions ?? [];- const set = new Set(current.filter(s => s !== '*'));+ // Provisioning retires '*' (this instance narrows the plugin to one session); the additive boot+ // path keeps the restored set whole, so an operator's PUT /plugins/:id/sessions survives a restart.+ const set = new Set(opts.additive ? current : current.filter(s => s !== '*'));if (activate) set.add(scope);else set.delete(scope);// Preserve '*' while an enabled wildcard/null sibling still binds all sessions ('*' subsumes