Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(plugins): stop a sparse instance inheriting the sibling tenant's config

Yudhi Armyndharis2b52e3046a72
diff --git a/src/core/plugins/ingress-instance-config.spec.ts b/src/core/plugins/ingress-instance-config.spec.ts
index 54043e08e..811e0ee32 100644
--- a/src/core/plugins/ingress-instance-config.spec.ts
+++ b/src/core/plugins/ingress-instance-config.spec.ts
@@ -90,6 +90,7 @@ function makeBridge(opts: {
getPluginInstanceService: () => ({
resolve: (pluginId: string, instanceId: string) =>
Promise.resolve(opts.rows.find(r => r.pluginId === pluginId && r.instanceId === instanceId) ?? null),
+ list: (pluginId: string) => Promise.resolve(opts.rows.filter(r => r.pluginId === pluginId)),
}),
} as unknown as PluginHostServices;
@@ -139,6 +140,65 @@ describe('ingress dispatch resolves config per INSTANCE, not per session scope',
expect(calls[0].config).toEqual({ apiToken: 'token-B' });
});
+ /**
+ * Layering the row on top corrects only the keys the row DEFINES. Every key it leaves unset falls
+ * through to the layer underneath — and for two instances sharing a scope that layer is not a
+ * schema default, it is the other tenant's projected config. So a sparse row, which is the normal
+ * shape when an instance relies on a plugin default, still received the sibling's live value.
+ *
+ * The scope slice cannot be attributed to an instance once siblings exist, so it is not consulted
+ * there at all. With a single instance on the scope it still applies: that slice is either that
+ * instance's own projection or the operator's deliberate per-session override.
+ */
+ it('does not hand a sparse instance the sibling tenant value for a key it left unset', async () => {
+ const a = instanceRow('acct-a', { apiToken: 'token-A', endpoint: 'https://a.example' }, SHARED_SCOPE);
+ const b = instanceRow('acct-b', { apiToken: 'token-B' }, SHARED_SCOPE); // relies on the default
+ const { bridge, calls } = makeBridge({
+ rows: [a, b],
+ baseConfig: { endpoint: 'https://default.example' },
+ // acct-a was provisioned last, so the scope slice carries ITS endpoint.
+ sessionConfig: { [SHARED_SCOPE]: { apiToken: 'token-A', endpoint: 'https://a.example' } },
+ });
+
+ await bridge.dispatchWebhookForInstance(job('acct-b'));
+
+ expect(calls[0].config).toEqual({ apiToken: 'token-B', endpoint: 'https://default.example' });
+ });
+
+ // Negative twin: with no sibling the slice IS attributable, so an operator's per-session override
+ // must keep applying — dropping it everywhere would break the surface it exists for.
+ it('still applies the per-session override when one instance binds the scope', async () => {
+ const a = instanceRow('acct-a', { apiToken: 'token-A' }, SHARED_SCOPE);
+ const { bridge, calls } = makeBridge({
+ rows: [a],
+ baseConfig: { endpoint: 'https://default.example' },
+ sessionConfig: { [SHARED_SCOPE]: { endpoint: 'https://operator.example' } },
+ });
+
+ await bridge.dispatchWebhookForInstance(job('acct-a'));
+
+ expect(calls[0].config).toEqual({ apiToken: 'token-A', endpoint: 'https://operator.example' });
+ });
+
+ /**
+ * A DISABLED sibling is not a tenant receiving deliveries, so it cannot be the one the slice was
+ * projected for in any way that matters — counting it would drop the operator's override for a
+ * deployment that has only one live instance.
+ */
+ it('a disabled sibling does not make the scope unattributable', async () => {
+ const a = instanceRow('acct-a', { apiToken: 'token-A' }, SHARED_SCOPE);
+ const retired = { ...instanceRow('acct-b', { apiToken: 'token-B' }, SHARED_SCOPE), enabled: false };
+ const { bridge, calls } = makeBridge({
+ rows: [a, retired],
+ baseConfig: { endpoint: 'https://default.example' },
+ sessionConfig: { [SHARED_SCOPE]: { endpoint: 'https://operator.example' } },
+ });
+
+ await bridge.dispatchWebhookForInstance(job('acct-a'));
+
+ expect(calls[0].config).toEqual({ apiToken: 'token-A', endpoint: 'https://operator.example' });
+ });
+
it('keeps plugin-level defaults underneath the instance override', async () => {
const a = instanceRow('acct-a', { apiToken: 'token-A' }, SHARED_SCOPE);
const { bridge, calls } = makeBridge({
diff --git a/src/core/plugins/plugin-activation.ts b/src/core/plugins/plugin-activation.ts
index 7ade1c0a1..5151a24d0 100644
--- a/src/core/plugins/plugin-activation.ts
+++ b/src/core/plugins/plugin-activation.ts
@@ -35,20 +35,18 @@ function deepMerge(base: Record<string, unknown>, override: Record<string, unkno
}
/**
- * Resolve the config a plugin sees for a given session: the per-session override (if any) deep-merged
- * over the base ('*') config, so an override only changes the keys it specifies (at any depth) and
- * inherits the rest from the base — a sparse override can't drop a base key (e.g. a nested secret) it
- * didn't touch. A global plugin and a non-session-attributed event (no sessionId) get the base
- * unchanged. Returns a fresh object on merge; never mutates the inputs.
- */
-/**
- * Layer one integration instance's own config over whatever the session-scoped resolution produced.
+ * Layer one integration instance's own config over whatever resolution produced.
*
* Provisioning projects each instance's config into the scope-keyed store, so two enabled instances
* sharing a session scope collapse onto one key and the later write wins. The scope therefore cannot
* say WHOSE credentials a delivery must run with; only the instance row can. Applied last so it beats
* both the base config and an operator's per-session override, and deep-merged so a sparse instance
- * config still inherits schema defaults and any key it did not set.
+ * config keeps the keys it did not set.
+ *
+ * This merge alone does NOT isolate two instances: it corrects the keys the row defines, and every
+ * key the row leaves unset still resolves from the layer underneath. Whether that layer can be
+ * attributed to this instance is the caller's decision — `PluginSandboxBridge` withholds the
+ * scope slice once siblings exist, for exactly that reason.
*/
export function resolveInstanceConfig(
resolved: Record<string, unknown>,
@@ -57,6 +55,13 @@ export function resolveInstanceConfig(
return instanceConfig ? deepMerge(resolved, instanceConfig) : resolved;
}
+/**
+ * Resolve the config a plugin sees for a given session: the per-session override (if any) deep-merged
+ * over the base ('*') config, so an override only changes the keys it specifies (at any depth) and
+ * inherits the rest from the base — a sparse override can't drop a base key (e.g. a nested secret) it
+ * didn't touch. A global plugin and a non-session-attributed event (no sessionId) get the base
+ * unchanged. Returns a fresh object on merge; never mutates the inputs.
+ */
export function resolvePluginConfig(
base: Record<string, unknown>,
sessionConfig: Record<string, Record<string, unknown>> | undefined,
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index 1b980b15e..7377fbd00 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -707,7 +707,13 @@ describe('PluginLoaderService — enable-failure hook cleanup', () => {
describe('PluginLoaderService.dispatchWebhookForInstance config delivery', () => {
it('delivers the instance-session-resolved config to the sandbox host', async () => {
- const fakeInstanceService = { resolve: jest.fn().mockResolvedValue({ sessionScope: 'sess-1' }) };
+ // `list` is part of the real service and the dispatch path consults it to decide whether the
+ // scope-keyed slice can be attributed to this instance. One enabled instance on the scope, so
+ // the slice IS attributable and the per-session override below must still apply.
+ const fakeInstanceService = {
+ resolve: jest.fn().mockResolvedValue({ sessionScope: 'sess-1' }),
+ list: jest.fn().mockResolvedValue([{ instanceId: 'acct1', enabled: true, sessionScope: 'sess-1' }]),
+ };
const configService = { get: jest.fn().mockReturnValue(undefined) } as unknown as ConfigService;
const pluginStorage = {
getPluginEntry: jest.fn().mockReturnValue(undefined),
diff --git a/src/core/plugins/plugin-sandbox-bridge.ts b/src/core/plugins/plugin-sandbox-bridge.ts
index 8d4a3ba09..25694f431 100644
--- a/src/core/plugins/plugin-sandbox-bridge.ts
+++ b/src/core/plugins/plugin-sandbox-bridge.ts
@@ -199,14 +199,27 @@ export class PluginSandboxBridge {
// last — applying it on top would hand a delivery the other tenant's credentials again. The
// override still decides every key the instance does not define, and still decides everything on
// the hook path. To change an instance's own config, use the instance route.
+ // The scope slice is consulted only while it can be ATTRIBUTED to this instance. Layering the row
+ // on top corrects the keys the row defines; every key it leaves unset — the normal shape when an
+ // instance relies on a plugin default — falls through to that slice, which for two instances
+ // sharing a scope holds the other tenant's projected value. So a sparse row was still handed a
+ // sibling's live endpoint or token.
+ //
+ // KNOWN RESIDUE: a WILDCARD instance is projected into the BASE config instead
+ // (scope-binding.service.ts, `updatePluginConfig`), and that merge is not separable per instance
+ // by design — its own comment says so. Attribution there needs the projection re-keyed by
+ // instance, which is a storage change, not a resolution one.
+ const scopeIsAttributable = await this.scopeHasAtMostOneInstance(d.pluginId, instance?.sessionScope ?? undefined);
const config = plugin
? resolveInstanceConfig(
- resolvePluginConfig(
- plugin.config,
- plugin.sessionConfig,
- instance?.sessionScope ?? undefined,
- plugin.manifest.sessionScoped !== false,
- ),
+ scopeIsAttributable
+ ? resolvePluginConfig(
+ plugin.config,
+ plugin.sessionConfig,
+ instance?.sessionScope ?? undefined,
+ plugin.manifest.sessionScoped !== false,
+ )
+ : plugin.config,
instance?.config,
)
: undefined;
@@ -229,6 +242,35 @@ export class PluginSandboxBridge {
}
}
+ /**
+ * Whether the scope-keyed config slice can be attributed to the instance being dispatched.
+ *
+ * Provisioning projects each instance's config into that slice keyed by SCOPE, so with siblings it
+ * holds whichever was written last and says nothing about whose delivery this is. With one enabled
+ * instance it is either that instance's own projection or an operator's deliberate per-session
+ * override — both of which must keep applying, so a single-instance deployment is unchanged.
+ *
+ * A lookup failure is treated as NOT attributable: the instance's own config still applies, and the
+ * cost of being wrong that way is a missing default rather than another tenant's credential.
+ */
+ private async scopeHasAtMostOneInstance(pluginId: string, scope: string | undefined): Promise<boolean> {
+ if (!scope) return false;
+ try {
+ const rows = await this.hostServices.getPluginInstanceService().list(pluginId);
+ return rows.filter(row => row.enabled && row.sessionScope === scope).length <= 1;
+ } catch (error) {
+ // Logged rather than swallowed: this drops the operator's per-session override for the
+ // deliveries it affects, and a silent config change is exactly what made the original
+ // collapse hard to see.
+ this.logger.warn('Could not count instances on the scope; withholding the per-session config slice', {
+ pluginId,
+ scope,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return false;
+ }
+ }
+
/**
* Untrusted enable: load the plugin in an isolated worker and drive its lifecycle there. Capability
* calls and hooks round-trip to the host, which enforces permission + session scope. A failure