Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test(dashboard): cover the API client's sign-out on an unusable key
Yudhi Armyndharis844e28c9b433
diff --git a/dashboard/src/services/api.test.ts b/dashboard/src/services/api.test.tsnew file mode 100644index 000000000..99bd401b7--- /dev/null+++ b/dashboard/src/services/api.test.ts@@ -0,0 +1,70 @@+// The API client's handling of a response that proves the stored key unusable. A 401, or a 403 because+// the key's allowedIps refuse this client, must sign the dashboard out; a role 403 must not, or every+// page an operator cannot open would log them out.+import '../test-helpers/register-hooks.ts';+import { test, before, beforeEach } from 'node:test';+import assert from 'node:assert/strict';++let sessionApi: (typeof import('./api.ts'))['sessionApi'];+const navigations: string[] = [];++before(async () => {+ const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');+ await installJsdomGlobals();+ // jsdom's location.assign cannot be spied on (it is unforgeable) and does not navigate anyway.+ Object.defineProperty(globalThis, 'window', {+ value: { location: { assign: (url: string) => navigations.push(url) } },+ configurable: true,+ writable: true,+ });+ ({ sessionApi } = await import('./api.ts'));+});++beforeEach(() => {+ navigations.length = 0;+ sessionStorage.setItem('openwa_api_key', 'stored-key');+});++function answer(status: number, message: string): void {+ globalThis.fetch = (() =>+ Promise.resolve(+ new Response(JSON.stringify({ statusCode: status, message }), {+ status,+ headers: { 'Content-Type': 'application/json' },+ }),+ )) as typeof fetch;+}++const settled = (promise: Promise<unknown>): Promise<boolean> =>+ Promise.race([+ promise.then(+ () => true,+ () => true,+ ),+ new Promise<boolean>(resolve => setTimeout(() => resolve(false), 20)),+ ]);++for (const [status, message] of [+ [401, 'Invalid API key'],+ [403, 'IP address not allowed'],+ [403, 'Client IP could not be determined'],+] as const) {+ test(`a ${status} "${message}" clears the key and returns to login`, async () => {+ answer(status, message);+ const call = sessionApi.list();+ assert.equal(await settled(call), false, 'the call settled, so its caller would render the failure');+ assert.equal(sessionStorage.getItem('openwa_api_key'), null);+ assert.deepEqual(navigations, ['/']);+ });+}++test('a role 403 keeps the key and rejects with the status', async () => {+ answer(403, 'Insufficient permissions. Required: operator');+ await assert.rejects(sessionApi.list(), (err: Error & { status?: number }) => {+ assert.equal(err.status, 403);+ assert.equal(err.message, 'Insufficient permissions. Required: operator');+ return true;+ });+ assert.equal(sessionStorage.getItem('openwa_api_key'), 'stored-key');+ assert.deepEqual(navigations, []);+});