Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test: cover the IP walk, SSRF ranges, import caps and log redaction
Yudhi Armyndhariscca17224d705
diff --git a/src/common/security/chat-scope.spec.ts b/src/common/security/chat-scope.spec.tsindex 82a0c3c35..5093ca21b 100644--- a/src/common/security/chat-scope.spec.ts+++ b/src/common/security/chat-scope.spec.ts@@ -95,6 +95,18 @@ describe('chat-scope', () => {expect(await buildExpandedChatScope([`${LID}@lid`])).toEqual(buildChatScope([`${LID}@lid`]));});+ it('drops an item that carries no chat id from a fenced list', () => {+ const scope = buildChatScope([`${PHONE}@c.us`]);+ const items: Array<{ id: string | null | undefined }> = [{ id: null }, { id: undefined }, { id: `${PHONE}@c.us` }];+ expect(filterByChatScope(scope, items, item => item.id)).toEqual([{ id: `${PHONE}@c.us` }]);+ });++ it('expands a mapped lid to both phone dialects in the filter scope', async () => {+ const scope = await buildExpandedChatScope([`${LID}@lid`], batch);+ expect(scope?.allowed.has(`${PHONE}@c.us`)).toBe(true);+ expect(scope?.allowed.has(`${PHONE}@s.whatsapp.net`)).toBe(true);+ });+it('filters a list to the fenced chats, leaving an unrestricted key untouched', async () => {const rows = [{ id: '[email protected]' }, { id: '[email protected]' }, { id: `${PHONE}@c.us` }];const scope = await buildExpandedChatScope(['[email protected]'], batch);diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.tsindex 83bfff4eb..e18425fcf 100644--- a/src/common/security/ssrf-guard.spec.ts+++ b/src/common/security/ssrf-guard.spec.ts@@ -36,6 +36,10 @@ describe('isBlockedAddress', () => {['192.168.1.1', 'RFC1918 192.168/16'],['169.254.169.254', 'link-local / cloud metadata'],['100.64.0.1', 'CGNAT 100.64/10'],+ ['192.0.0.8', 'IETF protocol assignments 192.0.0.0/24'],+ ['198.19.255.255', 'benchmarking 198.18.0.0/15, upper end'],+ ['224.0.0.1', 'IPv4 multicast 224.0.0.0/4'],+ ['255.255.255.255', 'reserved 240.0.0.0/4, broadcast'],['0.0.0.0', 'unspecified'],['::1', 'IPv6 loopback'],['fc00::1', 'IPv6 ULA fc00::/7'],@@ -471,7 +475,7 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {const init = {method: 'POST',body: 'payload',- headers: { authorization: 'Bearer secret', 'x-custom': 'keep' },+ headers: { authorization: 'Bearer secret', cookie: 'sid=abc', 'x-custom': 'keep' },};await withSafeFetch('https://api.example.com/upload', init, use, { followRedirects: true });@@ -483,6 +487,7 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {expect(hop2.method).toBe('GET');expect(hop2.body).toBeUndefined();expect(hop2.headers?.get('authorization')).toBeNull();+ expect(hop2.headers?.get('cookie')).toBeNull();expect(hop2.headers?.get('x-custom')).toBe('keep');});diff --git a/src/common/services/logger.service.spec.ts b/src/common/services/logger.service.spec.tsindex 97a68831a..09b725327 100644--- a/src/common/services/logger.service.spec.ts+++ b/src/common/services/logger.service.spec.ts@@ -77,6 +77,41 @@ describe('LoggerService', () => {expect(output.userId).toBe('u1');});+ it.each([+ 'passwd',+ 'secret',+ 'token',+ 'accessToken',+ 'authorization',+ 'credentials',+ 'apiPepper',+ 'privateKey',+ 'private-key',+ 'api-key',+ 'api_key',+ ])('redacts the value under the key %s', key => {+ logger.log('auth', { [key]: 'value-1', visible: 'v' });++ const output = getLogOutput(consoleSpy) as unknown as Record<string, unknown>;+ expect(output[key]).toBe('[REDACTED]');+ expect(output.visible).toBe('v');+ });++ it('redacts secret-named keys inside arrays of objects', () => {+ logger.log('cfg', {+ instances: [+ { name: 'a', secret: 's1' },+ { name: 'b', token: 't1' },+ ],+ });++ const output = getLogOutput(consoleSpy) as unknown as { instances: Array<Record<string, string>> };+ expect(output.instances).toEqual([+ { name: 'a', secret: '[REDACTED]' },+ { name: 'b', token: '[REDACTED]' },+ ]);+ });+it('redacts secret-named keys nested inside the metadata', () => {logger.log('cfg', { config: { redisPassword: 'p', host: 'h' } });diff --git a/src/common/storage/orphan-sweep.spec.ts b/src/common/storage/orphan-sweep.spec.tsnew file mode 100644index 000000000..cfd7c3309--- /dev/null+++ b/src/common/storage/orphan-sweep.spec.ts@@ -0,0 +1,96 @@+import { sweepOrphanedFiles } from './orphan-sweep';++describe('sweepOrphanedFiles', () => {+ const PREFIX = 'status/';++ function fixture(initial: string[]) {+ let keys = initial;+ const deleted: string[] = [];+ const deleteFile = jest.fn((key: string): Promise<void> => {+ deleted.push(key);+ return Promise.resolve();+ });+ const storage = {+ iterateFiles: async function* (): AsyncGenerator<string> {+ await Promise.resolve();+ for (const key of keys) yield key;+ },+ deleteFile,+ };+ return {+ deleted,+ deleteFile,+ set: (next: string[]) => {+ keys = next;+ },+ sweep: (+ overrides: Partial<Parameters<typeof sweepOrphanedFiles>[0]> & {+ firstSeenAt: Map<string, number>;+ now: number;+ },+ ) =>+ sweepOrphanedFiles({+ storage,+ prefix: PREFIX,+ graceMs: 500,+ referencedAmong: () => Promise.resolve(new Set<string | undefined>()),+ onDeleteFailed: jest.fn(),+ ...overrides,+ }),+ };+ }++ it('never touches a file outside the prefix it owns', async () => {+ const f = fixture(['status/a.jpg', 'chat-media/b.jpg']);+ const removed = await f.sweep({ firstSeenAt: new Map(), now: 1000, graceMs: 0 });+ expect(removed).toBe(1);+ expect(f.deleted).toEqual(['status/a.jpg']);+ });++ it('deletes an unreferenced file only after the grace window has run from its first sighting', async () => {+ const f = fixture(['status/a.jpg']);+ const firstSeenAt = new Map<string, number>();+ expect(await f.sweep({ firstSeenAt, now: 1000 })).toBe(0);+ expect(firstSeenAt.get('status/a.jpg')).toBe(1000);+ expect(await f.sweep({ firstSeenAt, now: 1499 })).toBe(0);+ expect(await f.sweep({ firstSeenAt, now: 1500 })).toBe(1);+ expect(f.deleted).toEqual(['status/a.jpg']);+ expect(firstSeenAt.size).toBe(0);+ });++ it('drops the bookkeeping of a file that disappeared or became referenced between passes', async () => {+ const f = fixture(['status/gone.jpg', 'status/claimed.jpg']);+ const firstSeenAt = new Map<string, number>();+ await f.sweep({ firstSeenAt, now: 1000 });+ expect([...firstSeenAt.keys()].sort()).toEqual(['status/claimed.jpg', 'status/gone.jpg']);++ f.set(['status/claimed.jpg']);+ await f.sweep({+ firstSeenAt,+ now: 1100,+ referencedAmong: () => Promise.resolve(new Set<string | undefined>(['status/claimed.jpg'])),+ });+ expect(firstSeenAt.size).toBe(0);+ });++ it('reports a failed delete and retries the file on a later pass', async () => {+ const f = fixture(['status/a.jpg']);+ f.deleteFile.mockRejectedValueOnce(new Error('EBUSY'));+ const onDeleteFailed = jest.fn();+ const firstSeenAt = new Map<string, number>();+ await f.sweep({ firstSeenAt, now: 1000, graceMs: 0, onDeleteFailed });+ expect(onDeleteFailed).toHaveBeenCalledWith('status/a.jpg', expect.any(Error));+ expect(firstSeenAt.has('status/a.jpg')).toBe(true);+ expect(await f.sweep({ firstSeenAt, now: 1001, graceMs: 0, onDeleteFailed })).toBe(1);+ });++ it('asks which keys are referenced in chunks of the size it was given', async () => {+ const f = fixture(['status/1', 'status/2', 'status/3', 'status/4', 'status/5']);+ const referencedAmong = jest.fn((keys: string[]) => {+ void keys;+ return Promise.resolve(new Set<string | undefined>());+ });+ await f.sweep({ firstSeenAt: new Map(), now: 1000, chunkSize: 2, referencedAmong });+ expect(referencedAmong.mock.calls.map(([keys]) => keys.length)).toEqual([2, 2, 1]);+ });+});diff --git a/src/common/storage/storage-transfer.spec.ts b/src/common/storage/storage-transfer.spec.tsindex edbbee057..df0c2aa8e 100644--- a/src/common/storage/storage-transfer.spec.ts+++ b/src/common/storage/storage-transfer.spec.ts@@ -372,6 +372,49 @@ describe('createExportStream and the per-entry import cap', () => {});});+describe('the per-entry import cap boundary', () => {+ const importOne = async (cap: string, size: number) => {+ const prev = process.env.STORAGE_IMPORT_MAX_BYTES;+ process.env.STORAGE_IMPORT_MAX_BYTES = cap;+ const pack = tar.pack();+ pack.entry({ name: 'only.bin' }, Buffer.alloc(size, 0x61));+ pack.finalize();+ try {+ return await importFromStream(pack.pipe(createGzip()), () => Promise.resolve(), makeLogger() as never).catch(+ (err: unknown) => err,+ );+ } finally {+ if (prev === undefined) delete process.env.STORAGE_IMPORT_MAX_BYTES;+ else process.env.STORAGE_IMPORT_MAX_BYTES = prev;+ }+ };++ it('imports an entry of exactly the cap and aborts on one byte more', async () => {+ expect(await importOne('10', 10)).toEqual({ imported: 1, failed: 0 });+ const over = await importOne('10', 11);+ expect(over).toBeInstanceOf(Error);+ expect((over as Error).message).toMatch(/10-byte per-entry cap \(STORAGE_IMPORT_MAX_BYTES\)/);+ });+});++describe('createExportStream and the entry-count limit this deployment lowered', () => {+ it('warns above the lower limit, though the shipped default would not', async () => {+ const prev = process.env.STORAGE_IMPORT_MAX_ENTRIES;+ process.env.STORAGE_IMPORT_MAX_ENTRIES = '2';+ const logger = makeLogger();+ try {+ const { openFile } = trackingOpener();+ const output = await createExportStream(() => Promise.resolve(files.slice(0, 3)), openFile, logger as never);+ await new Promise<void>(resolve => output.on('end', resolve).resume());+ } finally {+ if (prev === undefined) delete process.env.STORAGE_IMPORT_MAX_ENTRIES;+ else process.env.STORAGE_IMPORT_MAX_ENTRIES = prev;+ }+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('above the import limit of 2'));+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('Raise STORAGE_IMPORT_MAX_ENTRIES'));+ });+});+// docs/14, .env.example and the upgrade notes state these figures, and an operator sizes an import// against them: a drifted default changes what an import is allowed to extract without a word.describe('storage import caps', () => {diff --git a/src/common/storage/storage.service.spec.ts b/src/common/storage/storage.service.spec.tsindex 7304d010b..ce2e2f14c 100644--- a/src/common/storage/storage.service.spec.ts+++ b/src/common/storage/storage.service.spec.ts@@ -146,6 +146,16 @@ describe('StorageService put/getFile containment is backend-agnostic', () => {fs.rmSync(baseDir, { recursive: true, force: true });});++ it('deleteFile rejects an unsafe key before reaching the S3 backend', async () => {+ const { service, baseDir } = makeLocalService();+ const sendMock = s3Stub(service);++ await expect(service.deleteFile('../evil')).rejects.toThrow(/unsafe storage key/);+ expect(sendMock).not.toHaveBeenCalled();++ fs.rmSync(baseDir, { recursive: true, force: true });+ });});describe('StorageService.openFile (the export read path)', () => {diff --git a/src/common/utils/ip.spec.ts b/src/common/utils/ip.spec.tsindex 86fe6c995..899dbeab4 100644--- a/src/common/utils/ip.spec.ts+++ b/src/common/utils/ip.spec.ts@@ -132,4 +132,12 @@ describe('resolveClientIp', () => {it('skips a trusted hop that carries a port', () => {expect(resolveClientIp(req('10.0.0.2', '198.51.100.20, 10.0.0.9:8080'), ['10.0.0.0/8'])).toBe('198.51.100.20');});++ it('walks X-Forwarded-For from the right, so an address the client wrote on the left is never chosen', () => {+ // The client sent `203.0.113.99`; the trusted proxy appended the address it actually saw.+ expect(resolveClientIp(req('10.0.0.2', '203.0.113.99, 198.51.100.7'), ['10.0.0.0/8'])).toBe('198.51.100.7');+ expect(resolveClientIp(req('10.0.0.2', '203.0.113.99, 198.51.100.7, 10.0.0.9'), ['10.0.0.0/8'])).toBe(+ '198.51.100.7',+ );+ });});diff --git a/src/common/utils/template-render.spec.ts b/src/common/utils/template-render.spec.tsindex 9ce50cf83..bacf1792e 100644--- a/src/common/utils/template-render.spec.ts+++ b/src/common/utils/template-render.spec.ts@@ -17,6 +17,12 @@ describe('renderTemplate', () => {it('leaves an unknown placeholder literal', () => {expect(renderTemplate('Hi {{name}}', {})).toBe('Hi {{name}}');});++ it('never renders a member of Object.prototype for a name with no variable of its own', () => {+ expect(renderTemplate('{{constructor}} {{toString}} {{__proto__}}', {})).toBe(+ '{{constructor}} {{toString}} {{__proto__}}',+ );+ });});describe('legacy single-brace {name} (deprecated, still supported)', () => {diff --git a/src/common/validation/max-code-points.spec.ts b/src/common/validation/max-code-points.spec.tsindex 258ea7981..8dd22e091 100644--- a/src/common/validation/max-code-points.spec.ts+++ b/src/common/validation/max-code-points.spec.ts@@ -35,4 +35,12 @@ describe('varchar-backed fields are bounded in code points', () => {await expect(through('a'.repeat(room))).resolves.toMatchObject({ [field]: wrap('a'.repeat(room)) });await expect(through('a'.repeat(room + 1))).rejects.toBeInstanceOf(BadRequestException);});++ it('counts an astral character once, not as the two UTF-16 units it takes', async () => {+ const robot = String.fromCodePoint(0x1f916);+ const through = (name: string): Promise<unknown> =>+ pipe.transform({ replyText: 'hi', name }, { type: 'body', metatype: CreateAutomationRuleDto });+ await expect(through(robot.repeat(100))).resolves.toMatchObject({ name: robot.repeat(100) });+ await expect(through(robot.repeat(101))).rejects.toBeInstanceOf(BadRequestException);+ });});diff --git a/src/config/load-env.spec.ts b/src/config/load-env.spec.tsindex 28e9a313d..99e08da89 100644--- a/src/config/load-env.spec.ts+++ b/src/config/load-env.spec.ts@@ -48,6 +48,18 @@ describe('loadEnvironment', () => {}});+ it('lets a dashboard-saved engine apply over the blank value a stock compose forwards', () => {+ process.env.ENGINE_TYPE = '';+ makeTempCwd({ 'data/.env.generated': 'ENGINE_TYPE=baileys\n' });++ runLoader();++ expect(process.env.ENGINE_TYPE).toBe('baileys');+ // Not pinned: the host supplied nothing, so the Infrastructure page offers the setting for edit.+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ expect((require('./env-precedence') as typeof import('./env-precedence')).isEnvPinned('ENGINE_TYPE')).toBe(false);+ });+it('loads REDIS_HOST from a .env file so it reaches the webhook worker connection', () => {delete process.env.REDIS_HOST;makeTempCwd({ '.env': 'REDIS_HOST=redis.internal\n', 'data/.env.generated': '' });diff --git a/src/core/hooks/hook-results.spec.ts b/src/core/hooks/hook-results.spec.tsnew file mode 100644index 000000000..5845d5810--- /dev/null+++ b/src/core/hooks/hook-results.spec.ts@@ -0,0 +1,22 @@+import { isMessagePayload, isWebhookBeforeResult } from './hook-results';++describe('hook result checks', () => {+ it('accepts a message payload only when it carries both a string id and a string chatId', () => {+ expect(isMessagePayload({ id: 'm', chatId: '[email protected]' })).toBe(true);+ expect(isMessagePayload({ id: 'm' })).toBe(false);+ expect(isMessagePayload({ chatId: '[email protected]' })).toBe(false);+ expect(isMessagePayload({ id: 1, chatId: '[email protected]' })).toBe(false);+ expect(isMessagePayload({ id: 'm', chatId: 2 })).toBe(false);+ expect(isMessagePayload(null)).toBe(false);+ expect(isMessagePayload(['m', 'c'])).toBe(false);+ expect(isMessagePayload('m')).toBe(false);+ });++ it('accepts a webhook:before result only when it carries an object payload', () => {+ expect(isWebhookBeforeResult({ payload: { a: 1 } })).toBe(true);+ expect(isWebhookBeforeResult({ payload: null })).toBe(false);+ expect(isWebhookBeforeResult({ payload: [1] })).toBe(false);+ expect(isWebhookBeforeResult({})).toBe(false);+ expect(isWebhookBeforeResult(null)).toBe(false);+ });+});