Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(identity): grant no lid alias when the table read fails
Yudhi Armyndharis75a613e73f94
diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.tsindex f9196ec8e..ab44e32c2 100644--- a/src/engine/identity/lid-mapping-store.service.ts+++ b/src/engine/identity/lid-mapping-store.service.ts@@ -233,14 +233,14 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {* forward cache, and nothing phone-keyed ever warms it, so a mapping past the preload cap or* evicted by the LRU would stay invisible to a phone filter for good. For callers that can await* (the message and status filters, the handover gate, the API-key chat fence). Same rule as- * {@link lidsForPhonesPersisted}; a read error falls back to the cache alone.+ * {@link lidsForPhonesPersisted}; a read error grants no aliases.*/async findLidsForPhone(phone: string): Promise<string[]> {try {return (await this.readLidsForPhones([phone]))[phone];} catch (err) {this.logger.warn(`Could not read lids for a phone: ${err instanceof Error ? err.message : String(err)}`);- return this.lidsForPhone(phone).filter(lid => !this.unreported.has(lid));+ return [];}}@@ -252,18 +252,16 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {async phonesForLidsPersisted(lids: string[]): Promise<Record<string, string | null>> {const out: Record<string, string | null> = {};if (lids.length === 0) return out;- // The mirror is only the fallback for a failed table read, so it is read without getCached:- // that warms every miss with a findOne of its own, one per lid ahead of the batched query below.- for (const lid of lids) out[lid] = this.unreported.has(lid) ? null : (this.lidToPhone.get(lid) ?? null);+ // A chunk the table could not answer grants nothing: the display mirror never authorizes an alias.+ for (const lid of lids) out[lid] = null;try {for (const batch of chunk(lids)) {const rows = await this.repo.find({ where: { lid: In(batch) } });- for (const lid of batch) out[lid] = null;// The table WINS: a stale cached negative must not shadow a mapping another node persisted.for (const row of rows) out[row.lid] = this.rowPhone(row.lid, row.phone, row.isReported);}} catch {- // The table may not exist yet (migration pending); the mirror is the best available answer.+ // The table may not exist yet (migration pending); the chunks read before the failure stand.}return out;}@@ -273,10 +271,7 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {try {return await this.readLidsForPhones(phones);} catch {- // The table may not exist yet (migration pending); the cache is the best available answer.- return Object.fromEntries(- phones.map(phone => [phone, this.lidsForPhone(phone).filter(lid => !this.unreported.has(lid))]),- );+ return Object.fromEntries(phones.map(phone => [phone, []]));}}@@ -311,7 +306,7 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {/*** Forward lookup for callers that can await: the API-key chat fence and every chat-bound read* behind it (message history and media, the quoted body, status and handover filters). The table- * answers first, the in-memory mirror only when the read fails. The mirror alone is+ * answers authoritatively; a failed read grants no aliases. The mirror alone is* not enough: it is LRU-evicted at `LID_MAPPING_CACHE_MAX`, and nothing refreshes it when another* node re-maps a lid in the shared table, so a cache-first answer could resolve the same lid to* a phone the fence no longer sees, and a read behind the fence would serve that other chat. The@@ -327,7 +322,7 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {} catch (err) {this.logger.warn(`Could not read the phone for a lid: ${err instanceof Error ? err.message : String(err)}`);}- return this.unreported.has(lid) ? null : (this.getCached(lid) ?? null);+ return null;}/**diff --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.tsindex a231a66ce..1648c217a 100644--- a/src/engine/identity/lid-mapping-store.spec.ts+++ b/src/engine/identity/lid-mapping-store.spec.ts@@ -209,7 +209,7 @@ describe('LidMappingStoreService — LRU cap', () => {expect(store.getCached('lid-b')).toBe('620002'); // the table read did not evict the resident entry});- it('skips a table row this process has since re-mapped, and falls back to the cache on a read error', async () => {+ it('skips a locally superseded row and refuses cached aliases on a read error', async () => {const repo = makeFakeRepo([{ lid: '111', phone: '628999' }]);const store = await newStore(repo);jest.spyOn((store as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => {});@@ -218,7 +218,7 @@ describe('LidMappingStoreService — LRU cap', () => {expect(await store.findLidsForPhone('628999')).toEqual([]);repo.find.mockRejectedValueOnce(new Error('connection lost'));- expect(await store.findLidsForPhone('628000')).toEqual(['111']);+ expect(await store.findLidsForPhone('628000')).toEqual([]);});it('finds a phone by lid from the table on a cache miss, without indexing the row', async () => {@@ -711,11 +711,28 @@ describe('LidMappingStoreService — deterministic persisted lookups (authorizatexpect(repo.findOne).toHaveBeenCalledWith({ where: { lid: '111' } });});- it('findPhoneForLid answers from the cache when the table read fails', async () => {+ it('findPhoneForLid refuses aliases when the table read fails', async () => {const repo = makeFakeRepo([{ lid: '111', phone: '628999' }]);const store = await newStore(repo);repo.findOne.mockRejectedValueOnce(new Error('connection lost'));- expect(await store.findPhoneForLid('111@lid')).toBe('628999');+ expect(await store.findPhoneForLid('111@lid')).toBeNull();+ expect(store.getCached('111')).toBe('628999');+ });++ it('the chat fence admits no alias while the table cannot be read, only the id as granted', async () => {+ const repo = makeFakeRepo([{ lid: '111', phone: '628999' }]);+ const store = await newStore(repo);+ jest.spyOn((store as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => {});+ repo.findOne.mockRejectedValue(new Error('connection lost'));+ repo.find.mockRejectedValue(new Error('connection lost'));+ const fence = new ChatScopeService(store);+ expect(store.getCached('111')).toBe('628999');+ expect(await fence.allows({ allowedChats: ['[email protected]'] }, '111@lid')).toBe(false);+ expect(await fence.allows({ allowedChats: ['111@lid'] }, '[email protected]')).toBe(false);+ expect(await fence.allows({ allowedChats: ['111@lid'] }, '111@lid')).toBe(true);+ expect(await fence.allows({ allowedChats: ['[email protected]'] }, '[email protected]')).toBe(true);+ const listed = await fence.scopeForFilter({ allowedChats: ['[email protected]'] });+ expect([...(listed?.allowed ?? [])].sort()).toEqual(['[email protected]', '[email protected]']);});it('findPhoneForLid reads the table for a lid evicted from the LRU cache', async () => {@@ -866,11 +883,39 @@ describe('LidMappingStoreService — deterministic persisted lookups (authorizatexpect(await store.lidsForPhonesPersisted([])).toEqual({});// The null-phone row is skipped rather than indexed under a null key.expect((await store.lidsForPhonesPersisted(['628999']))['628999']).toEqual(['111']);- // A read error falls back to the cache, which the preload filled.+ // Display cache entries cannot authorize aliases when the table is unavailable.repo.find.mockRejectedValueOnce(new Error('no such table'));- expect(await store.phonesForLidsPersisted(['111'])).toEqual({ 111: '628999' });+ expect(await store.phonesForLidsPersisted(['111'])).toEqual({ 111: null });repo.find.mockRejectedValueOnce(new Error('no such table'));- expect(await store.lidsForPhonesPersisted(['628999'])).toEqual({ 628999: ['111'] });+ expect(await store.lidsForPhonesPersisted(['628999'])).toEqual({ 628999: [] });+ });++ it('does not use cached aliases for a failed forward query chunk', async () => {+ const lids = Array.from({ length: 501 }, (_, i) => String(900000 + i));+ const repo = makeFakeRepo(lids.map(lid => ({ lid, phone: `62${lid}` })));+ const store = await newStore(repo);+ const read = repo.find.getMockImplementation()!;+ repo.find.mockImplementationOnce(read).mockRejectedValueOnce(new Error('connection lost'));++ const result = await store.phonesForLidsPersisted(lids);++ expect(result[lids[0]]).toBe(`62${lids[0]}`);+ expect(result[lids[499]]).toBe(`62${lids[499]}`);+ expect(result[lids[500]]).toBeNull();+ expect(store.getCached(lids[500])).toBe(`62${lids[500]}`);+ });++ it('does not restore cached aliases when a reverse query chunk fails', async () => {+ const phones = Array.from({ length: 501 }, (_, i) => String(62900000 + i));+ const repo = makeFakeRepo(phones.map((phone, i) => ({ lid: String(900000 + i), phone })));+ const store = await newStore(repo);+ const read = repo.find.getMockImplementation()!;+ repo.find.mockImplementationOnce(read).mockRejectedValueOnce(new Error('connection lost'));++ const result = await store.lidsForPhonesPersisted(phones);++ expect(result[phones[0]]).toEqual([]);+ expect(result[phones[500]]).toEqual([]);});it('drops a cached lid that another node has re-mapped to a different phone', async () => {@@ -1042,11 +1087,11 @@ describe('LidMappingStoreService — deterministic persisted lookups (authorizatexpect(await store.findPhoneForLid('222@lid')).toBe('628999');});- it('findLidsForPhone falls back to the cache when the table read throws', async () => {+ it('findLidsForPhone refuses aliases when the table read throws', async () => {const repo = makeFakeRepo([{ lid: '111', phone: '628999' }]);const store = await newStore(repo);repo.find.mockRejectedValueOnce(new Error('no such table'));- expect(await store.findLidsForPhone('628999')).toEqual(['111']);+ expect(await store.findLidsForPhone('628999')).toEqual([]);});});@@ -1919,7 +1964,10 @@ describe('LidMappingStoreService: a negative result on the shared table', () =>release();await expect(older).resolves.toBe(true);expect(store.resolveLid('111@lid')).toBe('628111');+ expect(await store.findPhoneForLid('111@lid')).toBe('628111');jest.spyOn(repo, 'findOne').mockRejectedValueOnce(new Error('connection lost'));+ expect(await store.findPhoneForLid('111@lid')).toBeNull();+ expect(store.resolveLid('111@lid')).toBe('628111');expect(await store.findPhoneForLid('111@lid')).toBe('628111');expect(warn).toHaveBeenCalledTimes(1);warn.mockClear();