Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(auth): guard key revoke, delete and scoping on the live row

Yudhi Armyndharis9fa5e0564fae
diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.ts
index 058ac729d..969749634 100644
--- a/src/modules/auth/auth.service.spec.ts
+++ b/src/modules/auth/auth.service.spec.ts
@@ -419,13 +419,11 @@ describe('AuthService', () => {
describe('delete', () => {
it('should remove the API key from DB', async () => {
- const key = createMockApiKey();
- (repository.findOne as jest.Mock).mockResolvedValue(key);
- (repository.remove as jest.Mock).mockResolvedValue(key);
+ setupKeys([createMockApiKey()]);
await service.delete('uuid-1');
- expect(repository.remove).toHaveBeenCalledWith(key);
+ await expect(service.findOne('uuid-1')).rejects.toThrow(NotFoundException);
});
it('should throw NotFoundException for non-existent key', async () => {
@@ -440,13 +438,11 @@ describe('AuthService', () => {
.spyOn((service as unknown as { moduleRef: { get: (...a: unknown[]) => unknown } }).moduleRef, 'get')
.mockReturnValue({ evictApiKey });
- const key = createMockApiKey();
- (repository.findOne as jest.Mock).mockResolvedValue(key);
- (repository.remove as jest.Mock).mockResolvedValue(key);
+ setupKeys([createMockApiKey()]);
await service.delete('uuid-1');
- expect(repository.remove).toHaveBeenCalledWith(key);
+ await expect(service.findOne('uuid-1')).rejects.toThrow(NotFoundException);
expect(evictApiKey).toHaveBeenCalledWith('uuid-1', 'deleted');
});
@@ -583,7 +579,7 @@ describe('AuthService', () => {
await expect(service.findOne('admin-b')).rejects.toThrow(NotFoundException);
});
- it('runs non-admin mutations and benign admin updates on unguarded statements', async () => {
+ it('lets the guard pass non-admin mutations and runs a benign admin update unguarded', async () => {
setupKeys([
createMockApiKey({ id: 'op-del', role: ApiKeyRole.OPERATOR }),
createMockApiKey({ id: 'op-rev', role: ApiKeyRole.OPERATOR }),
@@ -596,11 +592,15 @@ describe('AuthService', () => {
await service.update('op-demote', { role: ApiKeyRole.VIEWER }); // demote of a non-admin
await service.update('adm-1', { name: 'renamed' }); // benign update of an admin
- // The last-admin guard is bound via andWhere; none of these statements carries it — the
- // benign admin rename runs unguarded even though the target IS a usable admin, because a
- // non-stripping patch cannot strand the system.
- expect(committedWrites).toHaveLength(3); // revoke + demote + rename (the delete removes the row)
- expect(committedWrites.every(w => !w.guarded)).toBe(true);
+ // Delete, revoke and demote carry the guard whatever role the pre-read saw, and it passes on
+ // a row that is not a usable admin. The benign admin rename runs unguarded even though the
+ // target IS a usable admin, because a non-stripping patch cannot strand the system.
+ expect(committedWrites.map(w => [w.mode, w.guarded])).toEqual([
+ ['delete', true],
+ ['update', true],
+ ['update', true],
+ ['update', false],
+ ]);
await expect(service.findOne('op-del')).rejects.toThrow(NotFoundException);
expect((await service.findOne('op-rev')).isActive).toBe(false);
});
@@ -638,6 +638,33 @@ describe('AuthService', () => {
expect(result.name).toBe('renamed-by-peer'); // the concurrent rename survives the revoke
expect((await service.findOne('op-1')).name).toBe('renamed-by-peer');
});
+
+ // The pre-read saw an operator, but a concurrent promotion (and the delete of the old admin) has
+ // committed by the time the write runs: the target is now the last usable admin, and the guard
+ // must judge that live row rather than the stale role.
+ describe('a target promoted to the last usable admin after the pre-read', () => {
+ beforeEach(() => {
+ setupKeys([createMockApiKey({ id: 'key-b', role: ApiKeyRole.ADMIN })]);
+ (repository.findOne as jest.Mock).mockResolvedValueOnce(
+ createMockApiKey({ id: 'key-b', role: ApiKeyRole.OPERATOR }), // stale pre-read
+ );
+ });
+
+ it('refuses to scope it', async () => {
+ await expect(service.update('key-b', { allowedSessions: ['s1'] })).rejects.toThrow(ConflictException);
+ expect(committedWrites).toHaveLength(0);
+ });
+
+ it('refuses to revoke it', async () => {
+ await expect(service.revoke('key-b')).rejects.toThrow(ConflictException);
+ expect(committedWrites).toHaveLength(0);
+ });
+
+ it('refuses to delete it', async () => {
+ await expect(service.delete('key-b')).rejects.toThrow(ConflictException);
+ await expect(service.findOne('key-b')).resolves.toBeDefined();
+ });
+ });
});
// ── last-admin invariant vs session-scoped admins ─────────────────
@@ -1049,9 +1076,7 @@ describe('AuthService', () => {
});
it('revoke removes the bootstrap key file when it still holds the revoked key', async () => {
- const key = createMockApiKey({ isActive: true }); // keyHash matches hashKey('test-key')
- (repository.findOne as jest.Mock).mockResolvedValue(key);
- (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));
+ setupKeys([createMockApiKey({ isActive: true })]); // keyHash matches hashKey('test-key')
existsSpy.mockReturnValue(true);
readSpy.mockReturnValue('test-key\n');
@@ -1061,9 +1086,7 @@ describe('AuthService', () => {
});
it('revoke leaves the file alone when it holds a different (still live) key', async () => {
- const key = createMockApiKey({ isActive: true });
- (repository.findOne as jest.Mock).mockResolvedValue(key);
- (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));
+ setupKeys([createMockApiKey({ isActive: true })]);
existsSpy.mockReturnValue(true);
readSpy.mockReturnValue('another-key');
@@ -1073,9 +1096,7 @@ describe('AuthService', () => {
});
it('delete removes the bootstrap key file when it still holds the deleted key', async () => {
- const key = createMockApiKey();
- (repository.findOne as jest.Mock).mockResolvedValue(key);
- (repository.remove as jest.Mock).mockResolvedValue(key);
+ setupKeys([createMockApiKey()]);
existsSpy.mockReturnValue(true);
readSpy.mockReturnValue('test-key');
@@ -1085,9 +1106,7 @@ describe('AuthService', () => {
});
it('tolerates a missing file on revoke (nothing to clean up)', async () => {
- const key = createMockApiKey({ isActive: true });
- (repository.findOne as jest.Mock).mockResolvedValue(key);
- (repository.save as jest.Mock).mockImplementation(k => Promise.resolve(k));
+ setupKeys([createMockApiKey({ isActive: true })]);
existsSpy.mockReturnValue(false);
await service.revoke('uuid-1');
diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts
index 612acf737..bf3091528 100644
--- a/src/modules/auth/auth.service.ts
+++ b/src/modules/auth/auth.service.ts
@@ -273,10 +273,10 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
if (dto.expiresAt !== undefined) patch.expiresAt = expiry;
let saved: ApiKey;
- if (removesOrSchedulesLastAdmin && apiKey.role === ApiKeyRole.ADMIN) {
- // The guard's predicate is the target's ROLE, not its usability snapshot: usability also
- // depends on isActive/expiry/scope, which the guarded statement itself evaluates against live
- // row state. A non-admin target genuinely cannot strand the system, so it stays lock-free.
+ if (removesOrSchedulesLastAdmin) {
+ // Guarded whatever role the pre-read saw: a concurrent promotion can make the target the last
+ // usable admin before this write lands, and only the statement itself sees the live row. On a
+ // row that is not a usable admin the guard passes, so non-admin keys are unaffected.
// An expiry pushed later on a key that already expires cannot bring a lockout closer, so the
// guard lets it through on its own; alongside a demotion or scoping it is guarded as usual.
const result = await this.withLastAdminGuard(
@@ -305,16 +305,12 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
async delete(id: string): Promise<void> {
const apiKey = await this.findOne(id);
- if (apiKey.role === ApiKeyRole.ADMIN) {
- const result = await this.withLastAdminGuard(
- this.apiKeyRepository.createQueryBuilder().delete().from(ApiKey),
- id,
- ).execute();
- await this.assertMutationApplied(id, result.affected);
- } else {
- // A non-admin target cannot strand the system — no guard needed.
- await this.apiKeyRepository.remove(apiKey);
- }
+ // Guarded whatever role the pre-read saw, so the statement judges the live row (see update).
+ const result = await this.withLastAdminGuard(
+ this.apiKeyRepository.createQueryBuilder().delete().from(ApiKey),
+ id,
+ ).execute();
+ await this.assertMutationApplied(id, result.affected);
// Drop any un-flushed usage accumulator so a deleted key leaves nothing behind in the Map.
this.usageTracker.forget(id);
this.removeBootstrapKeyFileIfMatching(apiKey);
@@ -328,19 +324,13 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
async revoke(id: string): Promise<ApiKey> {
const apiKey = await this.findOne(id);
- let saved: ApiKey;
- if (apiKey.role === ApiKeyRole.ADMIN) {
- const result = await this.withLastAdminGuard(
- this.apiKeyRepository.createQueryBuilder().update(ApiKey).set({ isActive: false }),
- id,
- ).execute();
- await this.assertMutationApplied(id, result.affected);
- saved = await this.findOne(id);
- } else {
- // A non-admin target cannot strand the system — no guard needed.
- await this.applyUnguardedUpdate({ isActive: false }, id);
- saved = await this.findOne(id);
- }
+ // Guarded whatever role the pre-read saw, so the statement judges the live row (see update).
+ const result = await this.withLastAdminGuard(
+ this.apiKeyRepository.createQueryBuilder().update(ApiKey).set({ isActive: false }),
+ id,
+ ).execute();
+ await this.assertMutationApplied(id, result.affected);
+ const saved = await this.findOne(id);
// A revoked key fails validation before its next flush, so its accumulator would orphan —
// drop it here.
this.usageTracker.forget(id);
@@ -450,7 +440,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
/**
* Apply a single-row UPDATE with no last-admin guard — the caller has established the target
- * cannot strand the system (non-admin target, or a non-stripping patch). The SET list is only
+ * cannot strand the system (a patch that neither strips nor expires a key). The SET list is only
* the patch itself: saving the pre-read ENTITY instead would write every column from that
* snapshot, resurrecting a revoke or demote that committed between the read and the write (a
* rename writing isActive: true back over a concurrent false, for instance). There is no guard