Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(auth): refuse to strand admin access behind an expiring survivor

Yudhi Armyndharis0dbb81d02dc5
diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts
index 87edaa3c3..424b22a93 100644
--- a/src/modules/auth/auth.controller.ts
+++ b/src/modules/auth/auth.controller.ts
@@ -141,7 +141,10 @@ export class AuthController {
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Update API key (admin only)' })
@ApiResponse({ status: 200, description: 'The updated API key.', type: ApiKeyResponseDto })
- @ApiResponse({ status: 409, description: 'The change would remove the last usable admin key.' })
+ @ApiResponse({
+ status: 409,
+ description: 'The change would remove the last usable admin key: no other usable admin key lasts at least as long.',
+ })
async update(
@Param('id') id: string,
@Body() dto: UpdateApiKeyDto,
@@ -180,7 +183,10 @@ export class AuthController {
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Delete API key (admin only)' })
@ApiResponse({ status: 204, description: 'API key deleted' })
- @ApiResponse({ status: 409, description: 'The key is the last usable admin key.' })
+ @ApiResponse({
+ status: 409,
+ description: 'The key is the last usable admin key: no other usable admin key lasts at least as long.',
+ })
async delete(@Param('id') id: string, @Req() req: Request, @CurrentApiKey() actor?: ApiKey): Promise<void> {
const target = await this.authService.findOne(id);
await this.authService.delete(id);
@@ -195,7 +201,10 @@ export class AuthController {
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'Revoke API key (admin only)' })
@ApiResponse({ status: 200, description: 'The revoked API key (isActive now false).', type: ApiKeyResponseDto })
- @ApiResponse({ status: 409, description: 'The key is the last usable admin key.' })
+ @ApiResponse({
+ status: 409,
+ description: 'The key is the last usable admin key: no other usable admin key lasts at least as long.',
+ })
async revoke(
@Param('id') id: string,
@Req() req: Request,
diff --git a/src/modules/auth/auth.service.last-admin.spec.ts b/src/modules/auth/auth.service.last-admin.spec.ts
new file mode 100644
index 000000000..aff5cb923
--- /dev/null
+++ b/src/modules/auth/auth.service.last-admin.spec.ts
@@ -0,0 +1,86 @@
+import 'reflect-metadata';
+import { ConflictException } from '@nestjs/common';
+import { DataSource, Repository } from 'typeorm';
+import { ApiKey, ApiKeyRole } from './entities/api-key.entity';
+import { AuthService } from './auth.service';
+import { ApiKeyUsageTracker } from './api-key-usage-tracker.service';
+
+/**
+ * The last-admin guard against a REAL better-sqlite3 DataSource, for the part the in-memory double
+ * cannot show: how long the surviving admin lasts. A survivor that expires before the key being
+ * removed only postpones the lockout, so it must not let the removal through.
+ */
+describe('AuthService last-admin guard and expiring admins', () => {
+ let ds: DataSource;
+ let repo: Repository<ApiKey>;
+ let service: AuthService;
+ const inHours = (hours: number) => new Date(Date.now() + hours * 3_600_000);
+
+ beforeAll(async () => {
+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [ApiKey], synchronize: true });
+ await ds.initialize();
+ repo = ds.getRepository(ApiKey);
+ const tracker = { record: jest.fn(), forget: jest.fn() } as unknown as ApiKeyUsageTracker;
+ service = new AuthService(repo, tracker, { get: () => undefined } as never);
+ });
+
+ afterAll(async () => {
+ await ds.destroy();
+ });
+
+ beforeEach(async () => {
+ await repo.clear();
+ });
+
+ const admin = async (name: string, expiresAt: Date | null): Promise<string> =>
+ (
+ await repo.save(
+ repo.create({ name, keyPrefix: name, keyHash: name, role: ApiKeyRole.ADMIN, isActive: true, expiresAt }),
+ )
+ ).id;
+
+ it('refuses to remove or expire a non-expiring admin when the only other admin expires', async () => {
+ const a = await admin('a', null);
+ const b = await admin('b', inHours(1));
+
+ await expect(service.revoke(a)).rejects.toThrow(ConflictException);
+ await expect(service.delete(a)).rejects.toThrow(ConflictException);
+ await expect(service.update(a, { expiresAt: inHours(2).toISOString() })).rejects.toThrow(ConflictException);
+ expect(await repo.findOneByOrFail({ id: a })).toMatchObject({ isActive: true, expiresAt: null });
+
+ await expect(service.revoke(b)).resolves.toMatchObject({ isActive: false });
+ });
+
+ it('lets an expiring admin go when another admin lasts at least as long', async () => {
+ const old = await admin('old', inHours(1));
+ await admin('rotated', inHours(24 * 30));
+ await expect(service.revoke(old)).resolves.toMatchObject({ isActive: false });
+
+ await repo.clear();
+ const longer = await admin('longer', inHours(24 * 30));
+ await admin('shorter', inHours(1));
+ await expect(service.delete(longer)).rejects.toThrow(ConflictException);
+
+ await repo.clear();
+ const first = await admin('first', null);
+ await admin('second', null);
+ await expect(service.delete(first)).resolves.toBeUndefined();
+ });
+
+ it('lets an expiring admin have its expiry pushed later, but not a demotion alongside it', async () => {
+ const a = await admin('a', inHours(1));
+ const b = await admin('b', inHours(0.5));
+ await expect(service.update(a, { expiresAt: inHours(5).toISOString() })).resolves.toBeDefined();
+ await expect(service.update(a, { expiresAt: inHours(72).toISOString() })).resolves.toBeDefined();
+ await expect(service.update(a, { expiresAt: inHours(3).toISOString() })).rejects.toThrow(ConflictException);
+ await expect(service.update(b, { expiresAt: inHours(0.75).toISOString() })).resolves.toBeDefined();
+
+ await repo.clear();
+ const sole = await admin('sole', inHours(1));
+ await expect(service.update(sole, { expiresAt: inHours(5).toISOString() })).resolves.toBeDefined();
+ await expect(
+ service.update(sole, { expiresAt: inHours(10).toISOString(), role: ApiKeyRole.OPERATOR }),
+ ).rejects.toThrow(ConflictException);
+ expect(await repo.findOneByOrFail({ id: sole })).toMatchObject({ role: ApiKeyRole.ADMIN });
+ });
+});
diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.ts
index 6c07cef35..c077bf66e 100644
--- a/src/modules/auth/auth.service.spec.ts
+++ b/src/modules/auth/auth.service.spec.ts
@@ -210,7 +210,12 @@ describe('AuthService', () => {
const guardPasses =
!this.guarded ||
!isUsableAdminRow(target) ||
- [...keys.values()].some(k => k.id !== target.id && isUsableAdminRow(k));
+ [...keys.values()].some(
+ k =>
+ k.id !== target.id &&
+ isUsableAdminRow(k) &&
+ (!k.expiresAt || (!!target.expiresAt && k.expiresAt >= target.expiresAt)),
+ );
if (!guardPasses) return Promise.resolve({ affected: 0 });
if (this.mode === 'delete') keys.delete(this.targetId as string);
else Object.assign(target, this.patch ?? {});
diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts
index 2692cea00..008aa4530 100644
--- a/src/modules/auth/auth.service.ts
+++ b/src/modules/auth/auth.service.ts
@@ -241,11 +241,12 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
// Scoping the last unscoped admin (non-empty allowedSessions) strips key-management just as
// surely as demoting or expiring it: @RequireUnscopedKey would then 403 every lifecycle route.
- const removesOrSchedulesLastAdmin =
+ const stripsAdmin =
(dto.role !== undefined && dto.role !== ApiKeyRole.ADMIN) ||
- (dto.expiresAt !== undefined && dto.expiresAt !== null) ||
(normalizeScopeList(dto.allowedSessions)?.length ?? 0) > 0 ||
(normalizeChatAllowList(dto.allowedChats)?.length ?? 0) > 0;
+ const setsExpiry = dto.expiresAt !== undefined && dto.expiresAt !== null;
+ const removesOrSchedulesLastAdmin = stripsAdmin || setsExpiry;
// Capture the authorization-relevant fields BEFORE applying the change. Only a change to role,
// allowedIps, allowedSessions, allowedChats, or expiry can widen or restrict what an already-connected WebSocket
@@ -273,9 +274,12 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
// 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.
+ // 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(
this.apiKeyRepository.createQueryBuilder().update(ApiKey).set(patch),
id,
+ setsExpiry && !stripsAdmin ? new Date(dto.expiresAt as string) : undefined,
).execute();
await this.assertMutationApplied(id, result.affected);
// The row's post-write state, for the eviction comparison below.
@@ -369,31 +373,53 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
}
/**
- * The instant bound as :guardNow, formatted exactly as the SQLite driver persists datetime
+ * The instant bound as :guardNow (and :extendsTo), 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', ' ');
+ private static guardNowParam(at = new Date()): string {
+ return at.toISOString().slice(0, 23).replace('T', ' ');
}
+ /**
+ * The surviving admin must last at least as long as the target: never expiring, or expiring no
+ * earlier than a target that expires itself. A survivor due to expire first only postpones the
+ * lockout, so removing (or scheduling the expiry of) a non-expiring admin next to an expiring one
+ * is refused, while rotating to a key that outlives the old one still goes through. The target is
+ * the statement's own row, referenced by table name because the subquery aliases its row `other`.
+ */
+ private static readonly OUTLASTS_TARGET =
+ `("other"."expiresAt" IS NULL OR ` +
+ `("api_keys"."expiresAt" IS NOT NULL AND "other"."expiresAt" >= "api_keys"."expiresAt"))`;
+
/**
* 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
+ * ONLY when that row is not a usable admin, or another usable admin that outlasts it survives it
+ * (see OUTLASTS_TARGET), or, given `extendsTo`, that row already expires no later than 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 {
+ private withLastAdminGuard<T extends UpdateQueryBuilder<ApiKey> | DeleteQueryBuilder<ApiKey>>(
+ qb: T,
+ id: string,
+ extendsTo?: Date,
+ ): T {
+ const extension = extendsTo ? `("expiresAt" IS NOT NULL AND "expiresAt" <= :extendsTo) OR ` : '';
// 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')}))`,
+ `(NOT (${AuthService.usableAdminCondition('')}) OR ${extension}EXISTS (` +
+ `SELECT 1 FROM "api_keys" "other" WHERE "other"."id" <> :id AND ${AuthService.usableAdminCondition('other')} AND ` +
+ `${AuthService.OUTLASTS_TARGET}))`,
)
- .setParameters({ adminRole: ApiKeyRole.ADMIN, guardNow: AuthService.guardNowParam() }) as T;
+ .setParameters({
+ adminRole: ApiKeyRole.ADMIN,
+ guardNow: AuthService.guardNowParam(),
+ ...(extendsTo && { extendsTo: AuthService.guardNowParam(extendsTo) }),
+ }) as T;
}
/**
@@ -405,7 +431,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
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');
+ throw new ConflictException('Cannot remove the last active admin key: no other admin key lasts as long');
}
/**