Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(auth): increment the API key usage count instead of overwriting it

Yudhi Armyndharisa6eb45ee0cd3
diff --git a/src/modules/auth/api-key-usage-tracker.service.ts b/src/modules/auth/api-key-usage-tracker.service.ts
index 24b8ad372..271cae98a 100644
--- a/src/modules/auth/api-key-usage-tracker.service.ts
+++ b/src/modules/auth/api-key-usage-tracker.service.ts
@@ -58,14 +58,17 @@ export class ApiKeyUsageTracker {
// 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.
- // Worse for a DELETED key: revocation is a hard `remove()`, so `save()` finds no row for the
+ // Worse for a DELETED key: deletion is a hard `remove()`, so `save()` finds no row for the
// primary key and INSERTs it back, hash included — the credential authenticates again. An
// `update()` by id affects zero rows instead. `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.
+ // The count is an increment, never the value this request loaded plus the delta: two requests
+ // that loaded the same stale row at a window boundary both write, and an absolute value from
+ // the second would overwrite the uses the first one persisted. `pending` is a local integer.
await this.apiKeyRepository.update(
{ id: apiKey.id },
- { lastUsedAt: apiKey.lastUsedAt, usageCount: apiKey.usageCount },
+ { lastUsedAt: apiKey.lastUsedAt, usageCount: () => `"usageCount" + ${pending}` },
);
} catch (error) {
// Lost-update safe: a failed windowed write must not drop the accumulated increments —
diff --git a/src/modules/auth/api-key-usage-write-scope.spec.ts b/src/modules/auth/api-key-usage-write-scope.spec.ts
index 35f6e80f5..4b8851885 100644
--- a/src/modules/auth/api-key-usage-write-scope.spec.ts
+++ b/src/modules/auth/api-key-usage-write-scope.spec.ts
@@ -1,5 +1,7 @@
+import 'reflect-metadata';
import { readFileSync, readdirSync } from 'fs';
import { join, relative, sep } from 'path';
+import { DataSource } from 'typeorm';
import { ApiKeyUsageTracker } from './api-key-usage-tracker.service';
import { ApiKey, ApiKeyRole } from './entities/api-key.entity';
@@ -10,11 +12,11 @@ import { ApiKey, ApiKeyRole } from './entities/api-key.entity';
* `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. Revocation is a hard delete,
+ * windowed write is silently reverted by an advisory statistics update. Deletion is a hard delete,
* so the same write on a removed key is an INSERT rather than an UPDATE: the credential comes back
* with its original hash and authenticates again.
*
- * `forget()` is called by revoke() before its deactivating save and closes the window for a key with
+ * `forget()` is called by revoke() and delete() after their write 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.
*
@@ -122,7 +124,8 @@ describe('API-key usage write scope', () => {
// rather than writing NULL, so an undefined here is not a wipe — it is a write that silently
// updates nothing but `updatedAt`, and the statistics stop advancing with no error to notice.
expect(written.lastUsedAt).toBeInstanceOf(Date);
- expect(typeof written.usageCount).toBe('number');
+ // The count is a SQL increment expression, not a value.
+ expect(typeof written.usageCount).toBe('function');
});
it('aims the write at the row it loaded and no other', async () => {
@@ -162,6 +165,39 @@ describe('API-key usage write scope', () => {
});
});
+describe('API-key usage count at a window boundary', () => {
+ let ds: DataSource;
+
+ beforeAll(async () => {
+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [ApiKey], synchronize: true });
+ await ds.initialize();
+ });
+
+ afterAll(async () => {
+ await ds.destroy();
+ });
+
+ it('keeps every counted use when two requests holding the same stale row both write', async () => {
+ const repo = ds.getRepository(ApiKey);
+ const { id } = await repo.save(
+ repo.create({ name: 'k', keyPrefix: 'kp', keyHash: 'window', role: ApiKeyRole.OPERATOR, usageCount: 0 }),
+ );
+ const tracker = new ApiKeyUsageTracker(repo);
+
+ // Ten uses inside the window stay pending.
+ await repo.update({ id }, { lastUsedAt: new Date(Date.now() - 1_000) });
+ for (let i = 0; i < 10; i++) await tracker.record(await repo.findOneByOrFail({ id }));
+
+ // The window passes; two requests load the same row before either windowed write lands.
+ await repo.update({ id }, { lastUsedAt: new Date(Date.now() - 120_000) });
+ const first = await repo.findOneByOrFail({ id });
+ const second = await repo.findOneByOrFail({ id });
+ await Promise.all([tracker.record(first), tracker.record(second)]);
+
+ expect((await repo.findOneByOrFail({ id })).usageCount).toBe(12);
+ });
+});
+
/**
* Structural guard for the entrypoint dimension of the same bug.
*
diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.ts
index 2dd32145f..6c07cef35 100644
--- a/src/modules/auth/auth.service.spec.ts
+++ b/src/modules/auth/auth.service.spec.ts
@@ -770,7 +770,8 @@ describe('AuthService', () => {
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);
+ // An increment by this request's delta, not the loaded value plus it.
+ expect((patch.usageCount as () => string)()).toBe('"usageCount" + 1');
expect(repository.save).not.toHaveBeenCalled();
});
@@ -919,7 +920,7 @@ describe('AuthService', () => {
// failed delta plus this request's increment — nothing is lost.
await service.validateApiKey(rawKey);
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
+ expect((writes[1][1].usageCount as () => string)()).toBe('"usageCount" + 2'); // failed delta 1 + this request 1
// The successful retry drained the accumulator — nothing left for the shutdown flush.
await service.onModuleDestroy();