Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(auth): move the last-admin guard into the mutation statement

Yudhi Armyndharis6547d99e7092
diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.ts
index 01cf395ec..3a92acce7 100644
--- a/src/modules/auth/auth.service.spec.ts
+++ b/src/modules/auth/auth.service.spec.ts
@@ -4,7 +4,7 @@ jest.mock('fs', () => ({ __esModule: true, ...jest.requireActual<typeof import('
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
-import { FindOperator, Repository } from 'typeorm';
+import { Repository } from 'typeorm';
import { UnauthorizedException, NotFoundException, ConflictException } from '@nestjs/common';
import { createHash, createHmac } from 'crypto';
import * as fs from 'fs';
@@ -90,6 +90,12 @@ describe('bannerKeyLine (startup banner key masking)', () => {
describe('AuthService', () => {
let service: AuthService;
let repository: jest.Mocked<Partial<Repository<ApiKey>>>;
+ /** In-memory stand-in for the api_keys table, shared by the findOne/remove/save mocks and the
+ * guarded-statement double below. */
+ let keys: Map<string, ApiKey>;
+ /** Guarded statements whose write committed (affected = 1), newest last — for assertions on what
+ * actually landed. */
+ let committedGuardedWrites: Array<{ mode: 'update' | 'delete'; patch?: Record<string, unknown> }>;
beforeEach(async () => {
repository = {
@@ -101,7 +107,9 @@ describe('AuthService', () => {
update: jest.fn(),
remove: jest.fn(),
increment: jest.fn(),
+ createQueryBuilder: jest.fn(),
};
+ setupKeys([]);
const module: TestingModule = await Test.createTestingModule({
providers: [
@@ -120,24 +128,18 @@ describe('AuthService', () => {
// ── last-admin guard test double ──────────────────────────────────
/**
- * In-memory stand-in for the api_keys table: findOne()/count()/save()/remove() backed by a Map.
- * count() HONORS the where-clause — the last-admin guard's query filters on role/isActive/
- * expiresAt AND session scope, so a mock that ignores the predicate (e.g. reporting a fixed
- * set size) would let a session-scoped admin count as a surviving key manager and the
- * allowedSessions filter would never actually be exercised. Interleaving is driven purely by
- * promise resolution order, so concurrency scenarios stay deterministic regardless of which
- * request runs its critical section first.
+ * In-memory stand-in for the api_keys table: findOne()/save()/remove() and the query-builder
+ * double below are all backed by the same Map. The last-admin guard now lives inside the guarded
+ * SQL statement itself, so the double's execute() evaluates the guard and performs the write as
+ * ONE synchronous step — mirroring the single atomic statement, so concurrency scenarios stay
+ * deterministic (statements interleave only before or after that step, never inside it).
*/
function setupKeys(seed: ApiKey[]): void {
- const keys = new Map(seed.map(k => [k.id, k]));
+ keys = new Map(seed.map(k => [k.id, k]));
+ committedGuardedWrites = [];
(repository.findOne as jest.Mock).mockImplementation((options: { where: { id: string } }) =>
Promise.resolve(keys.get(options.where.id) ?? null),
);
- (repository.count as jest.Mock).mockImplementation((options?: { where?: Array<Record<string, unknown>> }) =>
- Promise.resolve(
- [...keys.values()].filter(k => (options?.where ?? []).some(branch => matchesWhere(k, branch))).length,
- ),
- );
(repository.remove as jest.Mock).mockImplementation((key: ApiKey) => {
keys.delete(key.id);
return Promise.resolve(key);
@@ -146,42 +148,65 @@ describe('AuthService', () => {
keys.set(key.id, key);
return Promise.resolve(key);
});
+ (repository.createQueryBuilder as jest.Mock).mockImplementation(() => {
+ const qb = {
+ mode: 'update' as 'update' | 'delete',
+ patch: undefined as Record<string, unknown> | undefined,
+ targetId: undefined as string | undefined,
+ update() {
+ this.mode = 'update';
+ return this;
+ },
+ delete() {
+ this.mode = 'delete';
+ return this;
+ },
+ from() {
+ return this;
+ },
+ set(patch: Record<string, unknown>) {
+ this.patch = patch;
+ return this;
+ },
+ where(_fragment: string, params: { id: string }) {
+ this.targetId = params.id;
+ return this;
+ },
+ andWhere() {
+ return this;
+ },
+ setParameters() {
+ return this;
+ },
+ async execute(): Promise<{ affected: number }> {
+ const target = keys.get(this.targetId as string);
+ if (!target) return { affected: 0 };
+ const guardPasses =
+ !isUsableAdminRow(target) || [...keys.values()].some(k => k.id !== target.id && isUsableAdminRow(k));
+ if (!guardPasses) return { affected: 0 };
+ if (this.mode === 'delete') keys.delete(this.targetId as string);
+ else Object.assign(target, this.patch ?? {});
+ committedGuardedWrites.push({ mode: this.mode, patch: this.patch });
+ return { affected: 1 };
+ },
+ };
+ return qb;
+ });
}
- function setupLiveAdmins(...ids: string[]): void {
- setupKeys(ids.map(id => createMockApiKey({ id, role: ApiKeyRole.ADMIN })));
- }
-
- /** OR semantics across the where array; AND across the fields of a single branch. */
- function matchesWhere(key: ApiKey, branch: Record<string, unknown>): boolean {
- return Object.entries(branch).every(([field, condition]) => matchesCondition(dbColumnValue(key, field), condition));
- }
-
- /** Mirror the simple-array columns' stored shape: null stays null, an array is stored as a CSV. */
- function dbColumnValue(key: ApiKey, field: string): unknown {
- const value = (key as unknown as Record<string, unknown>)[field];
- if ((field === 'allowedSessions' || field === 'allowedIps') && Array.isArray(value)) return value.join(',');
- return value;
+ /** JS mirror of the guard's "usable admin" row predicate (the SQL definition lives in the
+ * service): an active, unexpired ADMIN key with no session scope. */
+ function isUsableAdminRow(key: ApiKey): boolean {
+ return (
+ key.role === ApiKeyRole.ADMIN &&
+ key.isActive &&
+ (!key.expiresAt || key.expiresAt.getTime() > Date.now()) &&
+ (!key.allowedSessions || key.allowedSessions.length === 0)
+ );
}
- function matchesCondition(value: unknown, condition: unknown): boolean {
- if (condition instanceof FindOperator) {
- switch (condition.type) {
- case 'not':
- return !matchesCondition(value, condition.value);
- case 'isNull':
- return value === null || value === undefined;
- case 'moreThan':
- return (
- value instanceof Date && condition.value instanceof Date && value.getTime() > condition.value.getTime()
- );
- case 'equal':
- return value === condition.value;
- default:
- throw new Error(`unsupported FindOperator in count mock: ${String(condition.type)}`);
- }
- }
- return value === condition;
+ function setupLiveAdmins(...ids: string[]): void {
+ setupKeys(ids.map(id => createMockApiKey({ id, role: ApiKeyRole.ADMIN })));
}
// ── createApiKey ──────────────────────────────────────────────────
@@ -315,7 +340,6 @@ describe('AuthService', () => {
it('rejects demoting or expiring the last usable admin', async () => {
const key = createMockApiKey({ role: ApiKeyRole.ADMIN });
(repository.findOne as jest.Mock).mockResolvedValue(key);
- (repository.count as jest.Mock).mockResolvedValue(0);
await expect(service.update('uuid-1', { role: ApiKeyRole.OPERATOR })).rejects.toThrow(/last active admin/i);
await expect(
@@ -361,14 +385,18 @@ describe('AuthService', () => {
});
it('rejects deleting the last usable admin but allows it when another usable admin exists', async () => {
- const key = createMockApiKey({ role: ApiKeyRole.ADMIN });
- (repository.findOne as jest.Mock).mockResolvedValue(key);
- (repository.remove as jest.Mock).mockResolvedValue(key);
- (repository.count as jest.Mock).mockResolvedValueOnce(0).mockResolvedValueOnce(1);
+ setupKeys([createMockApiKey({ id: 'uuid-1', role: ApiKeyRole.ADMIN })]);
await expect(service.delete('uuid-1')).rejects.toThrow(/last active admin/i);
+
+ setupKeys([
+ createMockApiKey({ id: 'uuid-1', role: ApiKeyRole.ADMIN }),
+ createMockApiKey({ id: 'uuid-2', role: ApiKeyRole.ADMIN }),
+ ]);
+
await expect(service.delete('uuid-1')).resolves.toBeUndefined();
- expect(repository.remove).toHaveBeenCalledTimes(1);
+ await expect(service.findOne('uuid-1')).rejects.toThrow(NotFoundException); // one delete committed
+ await expect(service.findOne('uuid-2')).resolves.toBeDefined(); // the survivor is intact
});
});
@@ -418,7 +446,6 @@ describe('AuthService', () => {
it('rejects revoking the last usable admin', async () => {
const key = createMockApiKey({ role: ApiKeyRole.ADMIN, isActive: true });
(repository.findOne as jest.Mock).mockResolvedValue(key);
- (repository.count as jest.Mock).mockResolvedValue(0);
await expect(service.revoke('uuid-1')).rejects.toThrow(/last active admin/i);
expect(repository.save).not.toHaveBeenCalled();
@@ -437,13 +464,15 @@ describe('AuthService', () => {
it('rejects exactly one of two concurrent deletes against the last two admins', async () => {
setupLiveAdmins('admin-a', 'admin-b');
- // Without serialization both counts run before either remove commits and both deletes pass.
+ // Without statement-level guard+write, both checks run before either delete commits and both
+ // pass.
const results = await Promise.allSettled([service.delete('admin-a'), service.delete('admin-b')]);
const { succeeded, conflicts } = outcomes(results);
expect(succeeded).toHaveLength(1);
expect(conflicts).toHaveLength(1);
- expect(repository.remove).toHaveBeenCalledTimes(1); // one admin survives — no lockout
+ const survivors = await Promise.allSettled([service.findOne('admin-a'), service.findOne('admin-b')]);
+ expect(survivors.filter(r => r.status === 'fulfilled')).toHaveLength(1); // one admin survives — no lockout
});
it('rejects exactly one of a concurrent demote and revoke against the last two admins', async () => {
@@ -458,10 +487,13 @@ describe('AuthService', () => {
expect(succeeded).toHaveLength(1);
expect(conflicts).toHaveLength(1);
// The loser's write never happened: exactly one capability-stripping write in total.
- const strippingSaves = (repository.save as jest.Mock).mock.calls.filter(
- ([key]: [ApiKey]) => key.role !== ApiKeyRole.ADMIN || key.isActive === false,
+ const strippingWrites = committedGuardedWrites.filter(
+ w =>
+ w.mode === 'delete' ||
+ (w.patch?.role !== undefined && w.patch.role !== ApiKeyRole.ADMIN) ||
+ w.patch?.isActive === false,
);
- expect((repository.remove as jest.Mock).mock.calls.length + strippingSaves.length).toBe(1);
+ expect(strippingWrites).toHaveLength(1);
});
it('lets concurrent deletes proceed when another usable admin remains', async () => {
@@ -472,28 +504,24 @@ describe('AuthService', () => {
const { succeeded, conflicts } = outcomes(results);
expect(succeeded).toHaveLength(2);
expect(conflicts).toHaveLength(0);
- expect(repository.remove).toHaveBeenCalledTimes(2);
+ await expect(service.findOne('admin-a')).rejects.toThrow(NotFoundException);
+ await expect(service.findOne('admin-b')).rejects.toThrow(NotFoundException);
});
- it('keeps non-admin mutations and benign admin updates off the mutex (no contention)', async () => {
- const lockRun = jest.spyOn(
- (service as unknown as { adminCapabilityLock: { run: (...args: unknown[]) => unknown } }).adminCapabilityLock,
- 'run',
- );
- const operatorKey = createMockApiKey({ id: 'op-1', role: ApiKeyRole.OPERATOR });
- const adminKey = createMockApiKey({ id: 'adm-1', role: ApiKeyRole.ADMIN });
- (repository.findOne as jest.Mock).mockImplementation((options: { where: { id: string } }) =>
- Promise.resolve(options.where.id === 'op-1' ? operatorKey : adminKey),
- );
- (repository.remove as jest.Mock).mockImplementation((key: ApiKey) => Promise.resolve(key));
- (repository.save as jest.Mock).mockImplementation((key: ApiKey) => Promise.resolve(key));
+ it('keeps non-admin mutations and benign admin updates off the guarded statement', async () => {
+ setupKeys([
+ createMockApiKey({ id: 'op-del', role: ApiKeyRole.OPERATOR }),
+ createMockApiKey({ id: 'op-rev', role: ApiKeyRole.OPERATOR }),
+ createMockApiKey({ id: 'op-demote', role: ApiKeyRole.OPERATOR }),
+ createMockApiKey({ id: 'adm-1', role: ApiKeyRole.ADMIN }),
+ ]);
- await service.delete('op-1'); // non-admin delete
- await service.revoke('op-1'); // non-admin revoke
- await service.update('op-1', { role: ApiKeyRole.VIEWER }); // demote of a non-admin
+ await service.delete('op-del'); // non-admin delete
+ await service.revoke('op-rev'); // non-admin revoke
+ 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
- expect(lockRun).not.toHaveBeenCalled();
+ expect(repository.createQueryBuilder).not.toHaveBeenCalled();
});
});
@@ -543,7 +571,8 @@ describe('AuthService', () => {
setupKeys([unscopedAdmin('admin-a'), scopedAdmin('admin-scoped')]);
await expect(service.delete('admin-scoped')).resolves.toBeUndefined();
- expect(repository.remove).toHaveBeenCalledTimes(1);
+ await expect(service.findOne('admin-scoped')).rejects.toThrow(NotFoundException);
+ await expect(service.findOne('admin-a')).resolves.toBeDefined();
});
it('allows stripping an unscoped admin when another unscoped admin remains', async () => {
@@ -552,17 +581,18 @@ describe('AuthService', () => {
await expect(service.update('admin-a', { allowedSessions: ['sess-9'] })).resolves.toBeDefined();
});
- it('re-reads the target inside the critical section instead of trusting the pre-lock snapshot', async () => {
- // The pre-lock read sees a usable admin; a concurrent (already serialized) mutation demoted
- // it before this request's section ran. The fresh read must win — no spurious conflict.
- const stale = createMockApiKey({ id: 'admin-a', role: ApiKeyRole.ADMIN });
- const fresh = createMockApiKey({ id: 'admin-a', role: ApiKeyRole.OPERATOR });
- (repository.findOne as jest.Mock).mockResolvedValueOnce(stale).mockResolvedValue(fresh);
- (repository.count as jest.Mock).mockResolvedValue(0);
- (repository.remove as jest.Mock).mockImplementation((key: ApiKey) => Promise.resolve(key));
+ it('evaluates the guard against the row’s live state, not the pre-read snapshot', async () => {
+ // The pre-read sees a usable admin; by the time the guarded statement runs, a concurrent
+ // mutation has already demoted it. The guard reads the row's CURRENT state inside the
+ // statement (the table double below), so there is no spurious conflict — the delete goes
+ // through and the demoted key is gone.
+ setupKeys([createMockApiKey({ id: 'admin-a', role: ApiKeyRole.OPERATOR })]);
+ (repository.findOne as jest.Mock).mockResolvedValueOnce(
+ createMockApiKey({ id: 'admin-a', role: ApiKeyRole.ADMIN }), // stale pre-read
+ );
await expect(service.delete('admin-a')).resolves.toBeUndefined();
- expect(repository.remove).toHaveBeenCalledWith(fresh);
+ await expect(service.findOne('admin-a')).rejects.toThrow(NotFoundException);
});
});
diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts
index c66a14799..cf1e9b215 100644
--- a/src/modules/auth/auth.service.ts
+++ b/src/modules/auth/auth.service.ts
@@ -8,7 +8,7 @@ import {
} from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { InjectRepository } from '@nestjs/typeorm';
-import { Equal, IsNull, MoreThan, Not, Repository } from 'typeorm';
+import { Repository, UpdateQueryBuilder, DeleteQueryBuilder, type QueryDeepPartialEntity } from 'typeorm';
import { randomBytes } from 'crypto';
import { ipMatches } from '../../common/utils/ip';
import { hashApiKey } from './api-key-hash';
@@ -18,7 +18,6 @@ import { createLogger } from '../../common/services/logger.service';
import { readBootstrapKey, removeBootstrapKey, writeBootstrapKey } from './bootstrap-key-file';
import { ApiKeyUsageTracker } from './api-key-usage-tracker.service';
import { EventsGateway, type ApiKeyEvictionReason } from '../events/events.gateway';
-import { KeyedAsyncLock } from '../integration/ordering-lock';
/**
* Resolves the API key to seed on first boot (when no keys exist yet).
@@ -54,19 +53,6 @@ export function bannerKeyLine(displayKey: string, isNewKey: boolean): string {
export class AuthService implements OnModuleInit, OnModuleDestroy {
private readonly logger = createLogger('AuthService');
- /**
- * Serializes every last-usable-admin check with the mutation it guards, in ONE critical section.
- * The check is check-then-act across awaits: without serialization, two concurrent requests that
- * demote/delete/revoke the last two admins both pass the check before either writes — leaving zero
- * usable admins, a total management lockout (the boot seed only fires on an EMPTY table, not on
- * zero admins). The guarded invariant is global ("count of OTHER usable admins"), so the lock key
- * must be a single global key too: keying per target key id would serialize nothing — the racing
- * requests target DIFFERENT keys. An in-process mutex is sufficient under the single-process
- * deployment contract.
- */
- private readonly adminCapabilityLock = new KeyedAsyncLock();
- private static readonly ADMIN_CAPABILITY_LOCK_KEY = 'admin-capability';
-
constructor(
@InjectRepository(ApiKey, 'main')
private readonly apiKeyRepository: Repository<ApiKey>,
@@ -235,81 +221,71 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
(dto.expiresAt !== undefined && dto.expiresAt !== null) ||
(dto.allowedSessions !== undefined && dto.allowedSessions.length > 0);
- const applyAndSave = async (): Promise<ApiKey> => {
- // Re-read the target inside the critical section: the pre-lock snapshot can be stale — a
- // concurrent serialized mutation may already have changed this key's usability — so the
- // last-admin check and the write both run against fresh state.
- const target = await this.findOne(id);
- if (removesOrSchedulesLastAdmin) {
- await this.assertNotLastUsableAdmin(target);
- }
-
- // Capture the authorization-relevant fields BEFORE applying the change. Only a change to role,
- // allowedIps, allowedSessions, or expiry can widen or restrict what an already-connected WebSocket
- // socket may see, so only those trigger eviction of live /events sockets — a benign rename must
- // NOT disconnect clients. REST enforces the new state immediately; without eviction a live socket
- // keeps streaming events for sessions/IPs the key just lost until it resubscribes or drops.
- const before = {
- role: target.role,
- allowedIps: target.allowedIps,
- allowedSessions: target.allowedSessions,
- expiresAt: target.expiresAt,
- };
-
- if (dto.name) target.name = dto.name;
- if (dto.role) target.role = dto.role;
- if (dto.allowedIps !== undefined) target.allowedIps = dto.allowedIps;
- if (dto.allowedSessions !== undefined) target.allowedSessions = dto.allowedSessions;
- if (dto.expiresAt !== undefined) target.expiresAt = dto.expiresAt ? new Date(dto.expiresAt) : null;
-
- const saved = await this.apiKeyRepository.save(target);
-
- // Compare membership, not order: a pure reorder of allowedIps/allowedSessions is a no-op for the
- // .includes()-based enforcement, so sort before stringify to avoid a spurious eviction on a reorder.
- const ordered = (v: string[] | null) => (v ? [...v].sort() : v);
- const authzChanged =
- saved.role !== before.role ||
- saved.expiresAt?.getTime() !== before.expiresAt?.getTime() ||
- JSON.stringify(ordered(saved.allowedIps)) !== JSON.stringify(ordered(before.allowedIps)) ||
- JSON.stringify(ordered(saved.allowedSessions)) !== JSON.stringify(ordered(before.allowedSessions));
- if (authzChanged) {
- this.evictActiveSockets(id, 'authorization_changed');
- }
- return saved;
+ // Capture the authorization-relevant fields BEFORE applying the change. Only a change to role,
+ // allowedIps, allowedSessions, or expiry can widen or restrict what an already-connected WebSocket
+ // socket may see, so only those trigger eviction of live /events sockets — a benign rename must
+ // NOT disconnect clients. REST enforces the new state immediately; without eviction a live socket
+ // keeps streaming events for sessions/IPs the key just lost until it resubscribes or drops.
+ const before = {
+ role: apiKey.role,
+ allowedIps: apiKey.allowedIps,
+ allowedSessions: apiKey.allowedSessions,
+ expiresAt: apiKey.expiresAt,
};
- // Run check+write inside the shared critical section ONLY when this update can strip the last
- // usable admin; every other update (rename, promotion, non-admin keys) stays lock-free.
- // The predicate is the target's ROLE, not its usability: usability also depends on isActive,
- // expiry and scope, any of which a concurrent serialized mutation may have just changed. Reading
- // that from the pre-lock snapshot would let a target that only LOOKS unusable skip the lock and
- // run its check unserialized — the very race the lock exists to close. Role is the stable,
- // conservative key: it over-locks a little (an already-revoked admin) and never under-locks.
- return removesOrSchedulesLastAdmin && apiKey.role === ApiKeyRole.ADMIN
- ? this.adminCapabilityLock.run(AuthService.ADMIN_CAPABILITY_LOCK_KEY, applyAndSave)
- : applyAndSave();
+ const patch: QueryDeepPartialEntity<ApiKey> = {};
+ if (dto.name) patch.name = dto.name;
+ if (dto.role) patch.role = dto.role;
+ if (dto.allowedIps !== undefined) patch.allowedIps = dto.allowedIps;
+ if (dto.allowedSessions !== undefined) patch.allowedSessions = dto.allowedSessions;
+ if (dto.expiresAt !== undefined) patch.expiresAt = dto.expiresAt ? new Date(dto.expiresAt) : null;
+
+ 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.
+ const result = await this.withLastAdminGuard(
+ this.apiKeyRepository.createQueryBuilder().update(ApiKey).set(patch),
+ id,
+ ).execute();
+ await this.assertMutationApplied(id, result.affected);
+ // The row's post-write state, for the eviction comparison below.
+ saved = await this.findOne(id);
+ } else {
+ Object.assign(apiKey, patch);
+ saved = await this.apiKeyRepository.save(apiKey);
+ }
+
+ // Compare membership, not order: a pure reorder of allowedIps/allowedSessions is a no-op for the
+ // .includes()-based enforcement, so sort before stringify to avoid a spurious eviction on a reorder.
+ const ordered = (v: string[] | null) => (v ? [...v].sort() : v);
+ const authzChanged =
+ saved.role !== before.role ||
+ saved.expiresAt?.getTime() !== before.expiresAt?.getTime() ||
+ JSON.stringify(ordered(saved.allowedIps)) !== JSON.stringify(ordered(before.allowedIps)) ||
+ JSON.stringify(ordered(saved.allowedSessions)) !== JSON.stringify(ordered(before.allowedSessions));
+ if (authzChanged) {
+ this.evictActiveSockets(id, 'authorization_changed');
+ }
+ return saved;
}
async delete(id: string): Promise<void> {
const apiKey = await this.findOne(id);
- const removeKey = async (): Promise<void> => {
- // Re-read inside the critical section (same staleness hazard as update()): never run the
- // last-admin check against the pre-lock snapshot.
- const target = await this.findOne(id);
- await this.assertNotLastUsableAdmin(target);
- // Drop any un-flushed usage accumulator so a deleted key leaves nothing behind in the Map.
- this.usageTracker.forget(id);
- await this.apiKeyRepository.remove(target);
- this.removeBootstrapKeyFileIfMatching(target);
- };
- // Lock on the ROLE, not on the pre-lock usability snapshot: isActive/expiry/scope can change
- // under a concurrent serialized mutation, so a target that merely looks unusable here must not
- // skip the critical section. A non-admin target genuinely cannot strand the system.
if (apiKey.role === ApiKeyRole.ADMIN) {
- await this.adminCapabilityLock.run(AuthService.ADMIN_CAPABILITY_LOCK_KEY, removeKey);
+ const result = await this.withLastAdminGuard(
+ this.apiKeyRepository.createQueryBuilder().delete().from(ApiKey),
+ id,
+ ).execute();
+ await this.assertMutationApplied(id, result.affected);
} else {
- await removeKey();
+ // A non-admin target cannot strand the system — no guard needed.
+ await this.apiKeyRepository.remove(apiKey);
}
+ // Drop any un-flushed usage accumulator so a deleted key leaves nothing behind in the Map.
+ this.usageTracker.forget(id);
+ this.removeBootstrapKeyFileIfMatching(apiKey);
this.evictActiveSockets(id, 'deleted');
this.logger.log(`API key deleted: ${apiKey.name}`, {
keyId: id,
@@ -319,23 +295,22 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
async revoke(id: string): Promise<ApiKey> {
const apiKey = await this.findOne(id);
- const revokeKey = async (): Promise<ApiKey> => {
- // Re-read inside the critical section (same staleness hazard as update()).
- const target = await this.findOne(id);
- await this.assertNotLastUsableAdmin(target);
- // A revoked key fails validation before its next flush, so its accumulator would orphan —
- // drop it here.
- this.usageTracker.forget(id);
- target.isActive = false;
- const saved = await this.apiKeyRepository.save(target);
- this.removeBootstrapKeyFileIfMatching(target);
- return saved;
- };
- // Same reasoning as delete(): the lock predicate is the stable role, not a snapshot of usability.
- const saved =
- apiKey.role === ApiKeyRole.ADMIN
- ? await this.adminCapabilityLock.run(AuthService.ADMIN_CAPABILITY_LOCK_KEY, revokeKey)
- : await revokeKey();
+ 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 {
+ apiKey.isActive = false;
+ saved = await this.apiKeyRepository.save(apiKey);
+ }
+ // A revoked key fails validation before its next flush, so its accumulator would orphan —
+ // drop it here.
+ this.usageTracker.forget(id);
+ this.removeBootstrapKeyFileIfMatching(apiKey);
// Kick any WebSocket connections already authenticated with this key: without this, a revoked
// key keeps receiving events on already-subscribed sockets until they happen to disconnect.
this.evictActiveSockets(id, 'revoked');
@@ -343,52 +318,65 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
}
/**
- * "Usable admin" for the last-admin invariant: an active, unexpired ADMIN key with NO session
- * scope. The key-lifecycle routes are fenced behind @RequireUnscopedKey (AuthController), so a
- * session-scoped admin can authenticate but can never manage keys — counting it as a surviving
- * admin would bless the removal of the last key that actually can, a permanent management
- * lockout with no in-band recovery (the boot seed only fires on an EMPTY table, not on zero
- * unscoped admins).
+ * "Usable admin" — the SQL-level subject of the last-admin invariant: an active, unexpired ADMIN
+ * key with NO session scope. The key-lifecycle routes are fenced behind @RequireUnscopedKey
+ * (AuthController), so a session-scoped admin can authenticate but can never manage keys —
+ * counting it as a surviving admin would bless the removal of the last key that actually can, a
+ * permanent management lockout with no in-band recovery (the boot seed only fires on an EMPTY
+ * table, not on zero unscoped admins). The simple-array column stores an empty array as '' (rows
+ * updated with allowedSessions: [] hold exactly that), so "no session scope" is NULL or ''.
+ * Dates are stored as UTC "YYYY-MM-DD HH:mm:ss.SSS" strings, so :guardNow is bound in that exact
+ * format (see guardNowParam) and the string comparison is chronological. Parameterized by column
+ * prefix so one definition serves both the row being mutated (bare) and the EXISTS subquery's
+ * `other` row.
*/
- private static isUsableAdmin(key: ApiKey, now = new Date()): boolean {
+ private static usableAdminCondition(prefix: string): string {
+ const col = (name: string) => (prefix ? `"${prefix}"."${name}"` : `"${name}"`);
return (
- key.role === ApiKeyRole.ADMIN &&
- key.isActive &&
- (!key.expiresAt || key.expiresAt > now) &&
- (!key.allowedSessions || key.allowedSessions.length === 0)
+ `${col('role')} = :adminRole AND ${col('isActive')} = 1 AND ` +
+ `(${col('expiresAt')} IS NULL OR ${col('expiresAt')} > :guardNow) AND ` +
+ `(${col('allowedSessions')} = '' OR ${col('allowedSessions')} IS NULL)`
);
}
- private async assertNotLastUsableAdmin(target: ApiKey): Promise<void> {
- const now = new Date();
- if (!AuthService.isUsableAdmin(target, now)) return;
-
- // Match isUsableAdmin at the SQL level: only UNSCOPED admins count. The simple-array column
- // stores an empty array as '' (rows updated with allowedSessions: [] hold exactly that), so
- // "no session scope" is NULL or '' — IsNull() alone would miss the '' rows.
- const otherUsableAdmins = await this.apiKeyRepository.count({
- where: [
- { id: Not(target.id), role: ApiKeyRole.ADMIN, isActive: true, expiresAt: IsNull(), allowedSessions: IsNull() },
- { id: Not(target.id), role: ApiKeyRole.ADMIN, isActive: true, expiresAt: IsNull(), allowedSessions: Equal('') },
- {
- id: Not(target.id),
- role: ApiKeyRole.ADMIN,
- isActive: true,
- expiresAt: MoreThan(now),
- allowedSessions: IsNull(),
- },
- {
- id: Not(target.id),
- role: ApiKeyRole.ADMIN,
- isActive: true,
- expiresAt: MoreThan(now),
- allowedSessions: Equal(''),
- },
- ],
- });
- if (otherUsableAdmins === 0) {
- throw new ConflictException('Cannot remove the last active admin key');
- }
+ /**
+ * The instant bound as :guardNow, formatted exactly as the SQLite driver persists datetime
+ * columns (UTC "YYYY-MM-DD HH:mm:ss.SSS" — what AbstractSqliteDriver writes for a Date), so the
+ * guard's comparison against stored expiresAt values is chronological.
+ */
+ private static guardNowParam(): string {
+ return new Date().toISOString().slice(0, 23).replace('T', ' ');
+ }
+
+ /**
+ * Bind the last-admin guard onto a single-row UPDATE/DELETE: the statement touches its target row
+ * ONLY when that row is not a usable admin, or another usable admin survives it. The guard runs
+ * inside the same statement as the write, so the database serializes concurrent last-admin
+ * mutations — including across processes sharing this database. The disjunct is parenthesized
+ * explicitly: without the outer parens, `id = :id AND NOT (…) OR EXISTS (…)` would parse as
+ * `(id = :id AND NOT …) OR EXISTS (…)` and the EXISTS branch would escape the row scope.
+ */
+ private withLastAdminGuard<T extends UpdateQueryBuilder<ApiKey> | DeleteQueryBuilder<ApiKey>>(qb: T, id: string): T {
+ // Cast: the chained this-types collapse to the union across a generic receiver.
+ return qb
+ .where('"id" = :id', { id })
+ .andWhere(
+ `(NOT (${AuthService.usableAdminCondition('')}) OR EXISTS (` +
+ `SELECT 1 FROM "api_keys" "other" WHERE "other"."id" <> :id AND ${AuthService.usableAdminCondition('other')}))`,
+ )
+ .setParameters({ adminRole: ApiKeyRole.ADMIN, guardNow: AuthService.guardNowParam() }) as T;
+ }
+
+ /**
+ * A guarded statement that affected zero rows either hit the guard (the target was the last
+ * usable admin) or lost a race with a concurrent delete (the row is gone). Distinguish by
+ * re-reading: findOne raises the same NotFoundException it does anywhere else, and a row that
+ * still exists was refused by the guard.
+ */
+ private async assertMutationApplied(id: string, affected: number | null | undefined): Promise<void> {
+ if (affected) return;
+ await this.findOne(id);
+ throw new ConflictException('Cannot remove the last active admin key');
}
/**