Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): scope the API-key usage write to its own columns
Yudhi Armyndharis9076fa89d8d6
diff --git a/src/modules/auth/api-key-usage-tracker.service.ts b/src/modules/auth/api-key-usage-tracker.service.tsindex 05ad82ff3..6712a4483 100644--- a/src/modules/auth/api-key-usage-tracker.service.ts+++ b/src/modules/auth/api-key-usage-tracker.service.ts@@ -54,7 +54,17 @@ export class ApiKeyUsageTracker {}this.pending.delete(apiKey.id);try {- await this.apiKeyRepository.save(apiKey);+ // Write the usage columns ONLY. `apiKey` is the entity this request loaded at authentication+ // time, so persisting it whole writes every column back as it was then — including isActive,+ // role, allowedSessions, allowedIps and expiresAt. An administrator change committed between+ // that load and this windowed write would be reverted by an advisory statistics update.+ // `forget()` closes the window for a key holding only pending counters, but cannot reach an+ // entity a request handler is already holding. Same reasoning as flushPending() below, which+ // writes one column for the same reason.+ await this.apiKeyRepository.update(+ { id: apiKey.id },+ { lastUsedAt: apiKey.lastUsedAt, usageCount: apiKey.usageCount },+ );} catch (error) {// Lost-update safe: a failed windowed write must not drop the accumulated increments —// merge them back (accumulate, never overwrite, in case a concurrent path re-added adiff --git a/src/modules/auth/api-key-usage-write-scope.spec.ts b/src/modules/auth/api-key-usage-write-scope.spec.tsnew file mode 100644index 000000000..137e0af91--- /dev/null+++ b/src/modules/auth/api-key-usage-write-scope.spec.ts@@ -0,0 +1,187 @@+import { readFileSync, readdirSync } from 'fs';+import { join, relative, sep } from 'path';+import { ApiKeyUsageTracker } from './api-key-usage-tracker.service';+import { ApiKey, ApiKeyRole } from './entities/api-key.entity';++/**+ * The usage-stat write must carry usage state and nothing else.+ *+ * Authentication loads the whole key row and hands the entity to the usage tracker, which mutates+ * `lastUsedAt`/`usageCount` on it and persists on a 60s window. Persisting that entity WHOLE writes+ * every column back — including `isActive`, `role`, `allowedSessions`, `allowedIps` and `expiresAt`+ * as they were when the request began. An administrator change committed between the load and the+ * windowed write is silently reverted by an advisory statistics update.+ *+ * `forget()` is called by revoke() before its deactivating save and closes the window for a key with+ * only PENDING counters. It cannot reach an entity a request handler is already holding, which is the+ * case these tests pin.+ *+ * The shutdown path already writes correctly — `flushPending` uses an atomic column increment and its+ * own comment warns against "reloading the row and saving it back". These tests hold the hot path to+ * the same standard.+ */++function makeRow(overrides: Partial<ApiKey> = {}): ApiKey {+ return {+ id: 'key-1',+ name: 'Test Key',+ keyHash: 'hash',+ keyPrefix: 'prefix',+ role: ApiKeyRole.OPERATOR,+ allowedIps: null,+ allowedSessions: null,+ isActive: true,+ expiresAt: null,+ lastUsedAt: null,+ usageCount: 5,+ createdAt: new Date(),+ updatedAt: new Date(),+ ...overrides,+ };+}++/**+ * A repository standing in for one persisted row: `save` writes the whole entity over it, `update`+ * writes only the named columns. That asymmetry is the entire subject of these tests, so the double+ * models it rather than asserting on which method was called.+ */+function makeRepository(row: ApiKey) {+ return {+ save: jest.fn((entity: ApiKey) => {+ Object.assign(row, entity);+ return Promise.resolve(entity);+ }),+ update: jest.fn((_criteria: unknown, patch: Partial<ApiKey>) => {+ Object.assign(row, patch);+ return Promise.resolve({ affected: 1 });+ }),+ increment: jest.fn(() => Promise.resolve({ affected: 1 })),+ };+}++/** The columns the usage write is allowed to touch. */+const USAGE_COLUMNS = ['lastUsedAt', 'usageCount'];++describe('API-key usage write scope', () => {+ it('does not resurrect a key revoked while the request was in flight', async () => {+ const row = makeRow();+ const repository = makeRepository(row);+ const tracker = new ApiKeyUsageTracker(repository as never);++ // A request authenticates and the handler now holds its own copy of the row.+ const heldByRequest = { ...row };++ // An administrator revokes the key while that request is still in flight. forget() clears any+ // PENDING counter but cannot reach the entity above.+ row.isActive = false;+ tracker.forget(row.id);++ // The windowed usage write fires (lastUsedAt is null, so the window is due immediately).+ await tracker.record(heldByRequest);++ expect(row.isActive).toBe(false);+ });++ it('does not revert an authorisation narrowing committed while the request was in flight', async () => {+ const row = makeRow({ role: ApiKeyRole.ADMIN });+ const repository = makeRepository(row);+ const tracker = new ApiKeyUsageTracker(repository as never);++ const heldByRequest = { ...row };++ // Narrowed on every authorisation dimension at once.+ row.role = ApiKeyRole.VIEWER;+ row.allowedSessions = ['session-a'];+ row.allowedIps = ['10.0.0.1'];+ row.expiresAt = new Date('2020-01-01T00:00:00.000Z');++ await tracker.record(heldByRequest);++ expect(row.role).toBe(ApiKeyRole.VIEWER);+ expect(row.allowedSessions).toEqual(['session-a']);+ expect(row.allowedIps).toEqual(['10.0.0.1']);+ expect(row.expiresAt).toEqual(new Date('2020-01-01T00:00:00.000Z'));+ });++ it('persists exactly the two usage columns and no others', async () => {+ const row = makeRow();+ const repository = makeRepository(row);+ const tracker = new ApiKeyUsageTracker(repository as never);++ await tracker.record({ ...row });++ const updateCall = repository.update.mock.calls[0];+ const saveCall = repository.save.mock.calls[0];+ const written: Partial<ApiKey> = updateCall ? updateCall[1] : saveCall[0];++ expect(Object.keys(written).sort()).toEqual([...USAGE_COLUMNS].sort());+ // Neither column may arrive undefined: TypeORM's update() writes NULL for an undefined value.+ expect(written.lastUsedAt).toBeInstanceOf(Date);+ expect(typeof written.usageCount).toBe('number');+ });++ it('still returns the incremented counters on the entity the caller holds', async () => {+ const row = makeRow({ usageCount: 5 });+ const repository = makeRepository(row);+ const tracker = new ApiKeyUsageTracker(repository as never);++ const heldByRequest = { ...row };+ await tracker.record(heldByRequest);++ expect(heldByRequest.usageCount).toBe(6);+ expect(heldByRequest.lastUsedAt).toBeInstanceOf(Date);+ });++ it('keeps a failed usage write non-fatal', async () => {+ const row = makeRow();+ const repository = makeRepository(row);+ repository.update.mockRejectedValueOnce(new Error('db down'));+ repository.save.mockRejectedValueOnce(new Error('db down'));+ const tracker = new ApiKeyUsageTracker(repository as never);++ await expect(tracker.record({ ...row })).resolves.toBeUndefined();+ });+});++/**+ * Structural guard for the entrypoint dimension of the same bug.+ *+ * The defect lives in the usage write, which every authentication path reaches through+ * validateApiKey. An enumeration that misses an entrypoint produces a fix that looks complete and+ * leaves a path uncovered — the websocket re-validation in events.gateway.ts was missed exactly once+ * during analysis of this defect. This test fails when a new call site appears, so the next+ * enumeration cannot silently be short.+ */+describe('validateApiKey entrypoint coverage', () => {+ /** Every known caller, with the surface it authenticates. */+ const KNOWN_CALLERS = new Map<string, string>([+ ['core/agent-tools/tool-invoker.ts', 'agent tool invocation'],+ ['common/security/bull-board-auth.middleware.ts', 'queue dashboard middleware'],+ ['modules/auth/guards/api-key.guard.ts', 'REST route guard'],+ ['modules/events/events.gateway.ts', 'websocket connect and per-subscribe re-validation'],+ ]);++ /** Where validateApiKey is declared, which is not a caller. */+ const DEFINITION = 'modules/auth/auth.service.ts';++ function walk(dir: string, out: string[] = []): string[] {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) walk(full, out);+ else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.spec.ts')) out.push(full);+ }+ return out;+ }++ it('enumerates every caller of validateApiKey', () => {+ const srcRoot = join(__dirname, '..', '..');++ const callers = walk(srcRoot)+ .filter(file => /\bvalidateApiKey\s*\(/.test(readFileSync(file, 'utf8')))+ .map(file => relative(srcRoot, file).split(sep).join('/'))+ .filter(rel => rel !== DEFINITION)+ .sort();++ expect(callers).toEqual([...KNOWN_CALLERS.keys()].sort());+ });+});diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex c7dc7b809..01cf395ec 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -98,6 +98,7 @@ describe('AuthService', () => {findOne: jest.fn(),create: jest.fn(),save: jest.fn(),+ update: jest.fn(),remove: jest.fn(),increment: jest.fn(),};@@ -600,7 +601,7 @@ describe('AuthService', () => {const result = await service.validateApiKey(rawKey);- expect(repository.save).not.toHaveBeenCalled(); // throttled — no DB write this request+ expect(repository.update).not.toHaveBeenCalled(); // throttled — no DB write this requestexpect(result.usageCount).toBe(6); // but the count is still reflected in-memoryexpect(result.lastUsedAt).toBeDefined();});@@ -613,11 +614,17 @@ describe('AuthService', () => {usageCount: 5,});(repository.findOne as jest.Mock).mockResolvedValue(key);- (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });await service.validateApiKey(rawKey);- expect(repository.save).toHaveBeenCalled(); // persisted after the window+ // Scoped to the usage columns: persisting the whole entity here would write back the+ // authorisation state this request loaded, reverting any concurrent administrator change.+ const [criteria, patch] = (repository.update as jest.Mock).mock.calls[0] as [{ id: string }, Partial<ApiKey>];+ expect(criteria).toEqual({ id: key.id });+ expect(Object.keys(patch).sort()).toEqual(['lastUsedAt', 'usageCount']);+ expect(patch.usageCount).toBe(6);+ expect(repository.save).not.toHaveBeenCalled();});it('should throw UnauthorizedException for invalid key', async () => {@@ -702,16 +709,16 @@ describe('AuthService', () => {// ── usage-stat lost-update safety + shutdown flush ────────────────describe('usage-stat lost-update safety', () => {- it('keeps the accumulated delta when the windowed save fails, and the next flush carries it', async () => {+ it('keeps the accumulated delta when the windowed write fails, and the next flush carries it', async () => {const rawKey = 'flaky-key';// Fresh row per findOne, as TypeORM returns it (no identity map): the DB state never// reflects the failed write, so the delta must survive in the pending map.const freshRow = () =>createMockApiKey({ keyHash: hashKey(rawKey), lastUsedAt: new Date(Date.now() - 5 * 60_000), usageCount: 5 });(repository.findOne as jest.Mock).mockImplementation(() => Promise.resolve(freshRow()));- (repository.save as jest.Mock)+ (repository.update as jest.Mock).mockRejectedValueOnce(new Error('db write failed'))- .mockImplementation(k => Promise.resolve(k));+ .mockResolvedValue({ affected: 1 });// The windowed write fails: the request still succeeds (the key is valid) and the delta is kept.const first = await service.validateApiKey(rawKey);@@ -720,8 +727,8 @@ describe('AuthService', () => {// Still due on the next request (DB lastUsedAt was never written) → the retry persists the// failed delta plus this request's increment — nothing is lost.await service.validateApiKey(rawKey);- const saves = (repository.save as jest.Mock).mock.calls as Array<[ApiKey]>;- expect(saves[1][0].usageCount).toBe(7); // DB 5 + failed delta 1 + this request 1+ const writes = (repository.update as jest.Mock).mock.calls as Array<[unknown, Partial<ApiKey>]>;+ expect(writes[1][1].usageCount).toBe(7); // DB 5 + failed delta 1 + this request 1// The successful retry drained the accumulator — nothing left for the shutdown flush.await service.onModuleDestroy();@@ -738,7 +745,7 @@ describe('AuthService', () => {(repository.increment as jest.Mock).mockResolvedValue({ affected: 1 });await service.validateApiKey(rawKey); // inside the throttle window → coalesced, no DB write- expect(repository.save).not.toHaveBeenCalled();+ expect(repository.update).not.toHaveBeenCalled();await service.onModuleDestroy();expect(repository.increment).toHaveBeenCalledWith({ id: 'uuid-1' }, 'usageCount', 1);