Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(auth): refuse an API key expiry that does not parse as a date

Yudhi Armyndharis7db24c18b80d
diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.ts
index ade46433e..058ac729d 100644
--- a/src/modules/auth/auth.service.spec.ts
+++ b/src/modules/auth/auth.service.spec.ts
@@ -5,7 +5,13 @@ jest.mock('fs', () => ({ __esModule: true, ...jest.requireActual<typeof import('
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository, type QueryDeepPartialEntity } from 'typeorm';
-import { UnauthorizedException, NotFoundException, ConflictException, ForbiddenException } from '@nestjs/common';
+import {
+ BadRequestException,
+ UnauthorizedException,
+ NotFoundException,
+ ConflictException,
+ ForbiddenException,
+} from '@nestjs/common';
import { createHash, createHmac } from 'crypto';
import * as fs from 'fs';
import { AuthService, resolveSeedApiKey, bannerKeyLine, UnresolvedApiKeyException } from './auth.service';
@@ -295,6 +301,15 @@ describe('AuthService', () => {
const expectedHash = hashKey(result.rawKey);
expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ keyHash: expectedHash }));
});
+
+ // ISO 8601 week, ordinal and basic forms pass @IsDateString but are an Invalid Date to `new Date`,
+ // which was stored as NaN and read back as an expiry that never arrives.
+ it.each(['2020-W01-1', '2026-274', '20261001T101010Z'])('refuses an unparseable expiresAt %s', async expiresAt => {
+ (repository.create as jest.Mock).mockImplementation((dto: Partial<ApiKey>) => ({ ...dto, id: 'uuid-new' }));
+
+ await expect(service.createApiKey({ name: 'tmp', expiresAt })).rejects.toThrow(BadRequestException);
+ expect(repository.save).not.toHaveBeenCalled();
+ });
});
// ── findAll / findOne ─────────────────────────────────────────────
@@ -384,6 +399,20 @@ describe('AuthService', () => {
).rejects.toThrow(/last active admin/i);
expect(committedWrites).toHaveLength(0); // neither write landed
});
+
+ it.each([ApiKeyRole.OPERATOR, ApiKeyRole.ADMIN])(
+ 'refuses an unparseable expiresAt on a %s key without writing it',
+ async role => {
+ setupKeys([
+ createMockApiKey({ id: 'uuid-1', role }),
+ createMockApiKey({ id: 'uuid-2', role: ApiKeyRole.ADMIN }),
+ ]);
+
+ await expect(service.update('uuid-1', { expiresAt: '2026-W40-1' })).rejects.toThrow(BadRequestException);
+ expect(committedWrites).toHaveLength(0);
+ expect((await service.findOne('uuid-1')).expiresAt).toBeNull();
+ },
+ );
});
// ── delete / revoke ───────────────────────────────────────────────
@@ -852,6 +881,14 @@ describe('AuthService', () => {
await expect(service.validateApiKey('expired')).rejects.toThrow('API key has expired');
});
+ it('refuses a key whose stored expiry does not parse as a date', async () => {
+ // Older releases stored an unparseable expiry as an Invalid Date; it must not mean "never expires".
+ const key = createMockApiKey({ expiresAt: new Date('2020-W01-1'), keyHash: hashKey('bad-expiry') });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+
+ await expect(service.validateApiKey('bad-expiry')).rejects.toThrow('API key has expired');
+ });
+
it('answers 403, not 401, when the IP is not allowed', async () => {
const key = createMockApiKey({
allowedIps: ['10.0.0.1'],
diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts
index c031dc5e2..612acf737 100644
--- a/src/modules/auth/auth.service.ts
+++ b/src/modules/auth/auth.service.ts
@@ -1,4 +1,5 @@
import {
+ BadRequestException,
ConflictException,
ForbiddenException,
Injectable,
@@ -209,7 +210,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
allowedIps: dto.allowedIps || null,
allowedSessions: normalizeScopeList(dto.allowedSessions),
allowedChats: normalizeChatAllowList(dto.allowedChats),
- expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null,
+ expiresAt: dto.expiresAt ? AuthService.parseExpiry(dto.expiresAt) : null,
});
const saved = await this.apiKeyRepository.save(apiKey);
@@ -246,7 +247,8 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
(dto.role !== undefined && dto.role !== ApiKeyRole.ADMIN) ||
(normalizeScopeList(dto.allowedSessions)?.length ?? 0) > 0 ||
(normalizeChatAllowList(dto.allowedChats)?.length ?? 0) > 0;
- const setsExpiry = dto.expiresAt !== undefined && dto.expiresAt !== null;
+ const expiry = dto.expiresAt ? AuthService.parseExpiry(dto.expiresAt) : null;
+ const setsExpiry = expiry !== null;
const removesOrSchedulesLastAdmin = stripsAdmin || setsExpiry;
// Capture the authorization-relevant fields BEFORE applying the change. Only a change to role,
@@ -268,7 +270,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
if (dto.allowedIps !== undefined) patch.allowedIps = dto.allowedIps;
if (dto.allowedSessions !== undefined) patch.allowedSessions = normalizeScopeList(dto.allowedSessions);
if (dto.allowedChats !== undefined) patch.allowedChats = normalizeChatAllowList(dto.allowedChats);
- if (dto.expiresAt !== undefined) patch.expiresAt = dto.expiresAt ? new Date(dto.expiresAt) : null;
+ if (dto.expiresAt !== undefined) patch.expiresAt = expiry;
let saved: ApiKey;
if (removesOrSchedulesLastAdmin && apiKey.role === ApiKeyRole.ADMIN) {
@@ -280,7 +282,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
const result = await this.withLastAdminGuard(
this.apiKeyRepository.createQueryBuilder().update(ApiKey).set(patch),
id,
- setsExpiry && !stripsAdmin ? new Date(dto.expiresAt as string) : undefined,
+ stripsAdmin ? undefined : (expiry ?? undefined),
).execute();
await this.assertMutationApplied(id, result.affected);
// The row's post-write state, for the eviction comparison below.
@@ -350,6 +352,17 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
return saved;
}
+ /**
+ * @IsDateString accepts every ISO 8601 form, but `new Date` parses only some of them: a week
+ * ('2026-W40-1'), ordinal ('2026-274') or basic ('20261001T101010Z') date is an Invalid Date, which
+ * would be stored as NaN and never compare as expired. Refuse it instead.
+ */
+ private static parseExpiry(value: string): Date {
+ const at = new Date(value);
+ if (Number.isNaN(at.getTime())) throw new BadRequestException('expiresAt is not a parseable date');
+ return at;
+ }
+
/**
* "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
@@ -515,7 +528,9 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
throw new UnauthorizedException('API key is revoked');
}
- if (apiKey.expiresAt && apiKey.expiresAt < new Date()) {
+ // Negated so a stored expiry that hydrates to an Invalid Date (every comparison false) counts as
+ // expired rather than never expiring.
+ if (apiKey.expiresAt && !(apiKey.expiresAt >= new Date())) {
throw new UnauthorizedException('API key has expired');
}