Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(integration): stop instance writes overwriting concurrent changes

Yudhi Armyndharisfedbaaa896ed
diff --git a/src/modules/integration/plugin-instance.service.spec.ts b/src/modules/integration/plugin-instance.service.spec.ts
index 302a0f34a..98fa90c3a 100644
--- a/src/modules/integration/plugin-instance.service.spec.ts
+++ b/src/modules/integration/plugin-instance.service.spec.ts
@@ -151,11 +151,14 @@ describe('PluginInstanceService provisioning', () => {
expect(rotated.secret).not.toBe(created.secret);
});
- it('update patches enabled/scope/config in one save; remove deletes', async () => {
+ it('update patches enabled/scope/config in one write; remove deletes', async () => {
await service.create('chatwoot', 'acct1', { sessionScope: 'a' });
- const save = jest.spyOn(ds.getRepository(PluginInstance), 'save');
+ const repo = ds.getRepository(PluginInstance);
+ const write = jest.spyOn(repo, 'update');
+ const save = jest.spyOn(repo, 'save');
const patched = await service.update('chatwoot', 'acct1', { enabled: false, sessionScope: 'b', config: { k: 1 } });
- expect(save).toHaveBeenCalledTimes(1);
+ expect(write).toHaveBeenCalledTimes(1);
+ expect(save).not.toHaveBeenCalled();
expect(patched?.enabled).toBe(false);
expect(patched?.sessionScope).toBe('b');
expect(patched?.config).toEqual({ k: 1 });
@@ -165,6 +168,77 @@ describe('PluginInstanceService provisioning', () => {
expect(await service.remove('chatwoot', 'acct1')).toBe(false);
});
+ it('update and regenerateSecret return the stored updatedAt, not the one read before the write', async () => {
+ await service.create('chatwoot', 'acct1', {});
+ const backdate = () => ds.query(`UPDATE plugin_instances SET "updatedAt" = '2000-01-01 00:00:00'`);
+
+ await backdate();
+ const patched = await service.update('chatwoot', 'acct1', { enabled: false });
+ const afterPatch = await service.resolve('chatwoot', 'acct1');
+ expect(afterPatch?.updatedAt.getUTCFullYear()).not.toBe(2000);
+ expect(patched?.updatedAt).toEqual(afterPatch?.updatedAt);
+
+ await backdate();
+ const rotated = await service.regenerateSecret('chatwoot', 'acct1');
+ const afterRotate = await service.resolve('chatwoot', 'acct1');
+ expect(rotated.updatedAt).toEqual(afterRotate?.updatedAt);
+ expect(rotated.secret).toBe(afterRotate?.secret);
+ });
+
+ it('answers a concurrent duplicate create with InstanceExistsError and keeps the first secret', async () => {
+ const results = await Promise.allSettled([
+ service.create('chatwoot', 'acct1', { secret: 'first-secret-16chars' }),
+ service.create('chatwoot', 'acct1', { secret: 'second-secret-16chars' }),
+ ]);
+ const created = results.filter(r => r.status === 'fulfilled');
+ const rejected = results.filter(r => r.status === 'rejected');
+ expect(created).toHaveLength(1);
+ expect(rejected).toHaveLength(1);
+ expect(rejected[0].reason).toBeInstanceOf(InstanceExistsError);
+ const winner = created[0].value;
+ expect((await service.resolve('chatwoot', 'acct1'))?.secret).toBe(winner.secret);
+ });
+
+ it('mint returns the stored row when a concurrent mint inserted it first', async () => {
+ const [a, b] = await Promise.all([service.mint('chatwoot', 'acct1', {}), service.mint('chatwoot', 'acct1', {})]);
+ expect(a.secret).toBe(b.secret);
+ expect((await service.resolve('chatwoot', 'acct1'))?.secret).toBe(a.secret);
+ });
+
+ // update() reads the row before it writes; a DELETE or a secret rotation can land in between.
+ it('update does not re-insert a row deleted after it was read', async () => {
+ await service.create('chatwoot', 'acct1', {});
+ const stale = await service.resolve('chatwoot', 'acct1');
+ await service.remove('chatwoot', 'acct1');
+ jest.spyOn(service, 'resolve').mockResolvedValueOnce(stale);
+
+ expect(await service.update('chatwoot', 'acct1', { enabled: false })).toBeNull();
+ expect(await service.resolve('chatwoot', 'acct1')).toBeNull();
+ });
+
+ it('update does not revert a secret rotated after it was read', async () => {
+ await service.create('chatwoot', 'acct1', {});
+ const stale = await service.resolve('chatwoot', 'acct1');
+ const rotated = await service.regenerateSecret('chatwoot', 'acct1');
+ jest.spyOn(service, 'resolve').mockResolvedValueOnce(stale);
+
+ await service.update('chatwoot', 'acct1', { enabled: false });
+
+ const stored = await service.resolve('chatwoot', 'acct1');
+ expect(stored?.secret).toBe(rotated.secret);
+ expect(stored?.enabled).toBe(false);
+ });
+
+ it('regenerateSecret does not re-insert a row deleted after it was read', async () => {
+ await service.create('chatwoot', 'acct1', {});
+ const stale = await service.resolve('chatwoot', 'acct1');
+ await service.remove('chatwoot', 'acct1');
+ jest.spyOn(service, 'resolve').mockResolvedValueOnce(stale);
+
+ await expect(service.regenerateSecret('chatwoot', 'acct1')).rejects.toThrow(/not found/);
+ expect(await service.resolve('chatwoot', 'acct1')).toBeNull();
+ });
+
it('normalizes an empty sessionScope to null (all-sessions) on mint/create/update, never a literal ""', async () => {
// '' would break outbound send (falsy sessionId) and be unrecoverable from the UI; store null instead.
const minted = await service.mint('chatwoot', 'm1', { sessionScope: '' });
diff --git a/src/modules/integration/plugin-instance.service.ts b/src/modules/integration/plugin-instance.service.ts
index 5f60745fc..5587bec9c 100644
--- a/src/modules/integration/plugin-instance.service.ts
+++ b/src/modules/integration/plugin-instance.service.ts
@@ -1,8 +1,9 @@
import { randomBytes } from 'node:crypto';
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { Repository } from 'typeorm';
+import { QueryDeepPartialEntity, Repository } from 'typeorm';
import { PluginInstance } from './entities/plugin-instance.entity';
+import { isUniqueViolation } from '../../common/utils/db-errors';
import type { PluginConfigSchema } from '../../core/plugins/plugin.interfaces';
import { redactSecretConfig, restoreSecretConfig, SECRET_SENTINEL } from '../plugins/redact-config';
// Type-only: the module binds this class to PLUGIN_INSTANCE_PORT with a `useExisting` alias, which
@@ -36,11 +37,22 @@ export class PluginInstanceService implements PluginInstancePort {
instanceId: string,
opts: { sessionScope?: string; verifyToken?: string; secret?: string; config?: Record<string, unknown> },
): Promise<PluginInstance> {
- const id = `${pluginId}:${instanceId}`;
- const existing = await this.repo.findOne({ where: { id } });
+ const existing = await this.resolve(pluginId, instanceId);
if (existing) return existing;
+ return (
+ (await this.insert(pluginId, instanceId, opts)) ?? ((await this.resolve(pluginId, instanceId)) as PluginInstance)
+ );
+ }
+
+ // A plain INSERT, never save(): with the primary key set, save() re-selects and turns a concurrent
+ // duplicate into an UPDATE that overwrites the first row's secret. Null when the id already exists.
+ private async insert(
+ pluginId: string,
+ instanceId: string,
+ opts: { sessionScope?: string; verifyToken?: string; secret?: string; config?: Record<string, unknown> },
+ ): Promise<PluginInstance | null> {
const inst = this.repo.create({
- id,
+ id: `${pluginId}:${instanceId}`,
pluginId,
instanceId,
sessionScope: opts.sessionScope || null,
@@ -49,7 +61,13 @@ export class PluginInstanceService implements PluginInstancePort {
config: opts.config ?? null,
enabled: true,
});
- return this.repo.save(inst);
+ try {
+ await this.repo.insert(inst as QueryDeepPartialEntity<PluginInstance>);
+ } catch (err) {
+ if (isUniqueViolation(err)) return null;
+ throw err;
+ }
+ return inst;
}
resolve(pluginId: string, instanceId: string): Promise<PluginInstance | null> {
@@ -72,19 +90,10 @@ export class PluginInstanceService implements PluginInstancePort {
instanceId: string,
opts: { sessionScope?: string; verifyToken?: string; secret?: string; config?: Record<string, unknown> },
): Promise<PluginInstance> {
- const id = `${pluginId}:${instanceId}`;
- if (await this.repo.findOne({ where: { id } })) throw new InstanceExistsError(pluginId, instanceId);
- const inst = this.repo.create({
- id,
- pluginId,
- instanceId,
- sessionScope: opts.sessionScope || null,
- secret: normalizeSecret(opts.secret),
- verifyToken: opts.verifyToken || randomBytes(16).toString('hex'),
- config: opts.config ?? null,
- enabled: true,
- });
- return this.repo.save(inst);
+ if (await this.resolve(pluginId, instanceId)) throw new InstanceExistsError(pluginId, instanceId);
+ const inst = await this.insert(pluginId, instanceId, opts);
+ if (!inst) throw new InstanceExistsError(pluginId, instanceId);
+ return inst;
}
list(pluginId: string): Promise<PluginInstance[]> {
@@ -96,11 +105,17 @@ export class PluginInstanceService implements PluginInstancePort {
return this.repo.find();
}
+ // update() and regenerateSecret() write only the columns they change, and only to a row that still
+ // exists: a whole-row save() would re-insert a row deleted meanwhile, or write back a stale secret
+ // over a concurrent rotation. Both re-read the row after the write so the result carries the fresh
+ // updatedAt the database stamped.
async regenerateSecret(pluginId: string, instanceId: string): Promise<PluginInstance> {
const inst = await this.resolve(pluginId, instanceId);
- if (!inst) throw new Error(`instance ${instanceId} not found for plugin ${pluginId}`);
- inst.secret = randomBytes(32).toString('hex');
- return this.repo.save(inst);
+ const secret = randomBytes(32).toString('hex');
+ const written = inst ? (await this.repo.update({ id: inst.id }, { secret })).affected : 0;
+ const stored = written ? await this.resolve(pluginId, instanceId) : null;
+ if (!stored) throw new Error(`instance ${instanceId} not found for plugin ${pluginId}`);
+ return stored;
}
async update(
@@ -111,15 +126,18 @@ export class PluginInstanceService implements PluginInstancePort {
): Promise<PluginInstance | null> {
const inst = await this.resolve(pluginId, instanceId);
if (!inst) return null;
- if (patch.enabled !== undefined) inst.enabled = patch.enabled;
- if (patch.sessionScope !== undefined) inst.sessionScope = patch.sessionScope || null;
+ const changes: Partial<Pick<PluginInstance, 'enabled' | 'sessionScope' | 'config'>> = {};
+ if (patch.enabled !== undefined) changes.enabled = patch.enabled;
+ if (patch.sessionScope !== undefined) changes.sessionScope = patch.sessionScope || null;
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);
+ changes.config = restoreSecretConfig(patch.config, inst.config ?? undefined, schema);
}
- return this.repo.save(inst);
+ if (Object.keys(changes).length === 0) return inst;
+ const { affected } = await this.repo.update({ id: inst.id }, changes as QueryDeepPartialEntity<PluginInstance>);
+ return affected ? this.resolve(pluginId, instanceId) : null;
}
async remove(pluginId: string, instanceId: string): Promise<boolean> {