Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(auth): stop an allowedSessions write landing as a widening

Yudhi Armyndharis23aba455fcf5
diff --git a/dashboard/src/components/SessionScopePicker.tsx b/dashboard/src/components/SessionScopePicker.tsx
index 44ae2c8fd..49f70993f 100644
--- a/dashboard/src/components/SessionScopePicker.tsx
+++ b/dashboard/src/components/SessionScopePicker.tsx
@@ -41,6 +41,16 @@ export function SessionScopePicker({ sessions, selectedIds, onChange, disabled }
{t('apiKeys.sessions.leaveAll')}
</button>
<p className="session-scope-hint">{t('apiKeys.sessions.hint')}</p>
+ {/*
+ An empty selection WIDENS the key to every session, which is the opposite of what
+ unticking the last box looks like it does. The explicit button above says so; reaching
+ the same state one checkbox at a time did not, so say it here the moment it is true.
+ */}
+ {rows.length > 0 && selectedIds.length === 0 && (
+ <p className="session-scope-widened" role="status">
+ {t('apiKeys.sessions.all')}
+ </p>
+ )}
{rows.length === 0 ? (
<p className="session-scope-empty">{t('apiKeys.sessions.empty')}</p>
) : (
diff --git a/dashboard/src/pages/ApiKeys.css b/dashboard/src/pages/ApiKeys.css
index 26af2c575..3aa8916e4 100644
--- a/dashboard/src/pages/ApiKeys.css
+++ b/dashboard/src/pages/ApiKeys.css
@@ -159,7 +159,8 @@
}
.api-keys-page .session-scope-hint,
-.api-keys-page .session-scope-empty {
+.api-keys-page .session-scope-empty,
+.api-keys-page .session-scope-widened {
margin: 0 0 0.75rem;
font-size: 0.8125rem;
font-weight: 400;
@@ -169,6 +170,12 @@
letter-spacing: normal;
}
+/* An empty selection grants every session, so it reads as a state rather than a hint. */
+.api-keys-page .session-scope-widened {
+ font-weight: 600;
+ color: var(--text-primary);
+}
+
.api-keys-page .session-scope-list {
list-style: none;
margin: 0;
diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts
index 72eb282ab..66e3ce058 100644
--- a/src/modules/auth/auth.service.ts
+++ b/src/modules/auth/auth.service.ts
@@ -49,6 +49,24 @@ export function bannerKeyLine(displayKey: string, isNewKey: boolean): string {
return `${displayKey.slice(0, 8)}… (full key in data/.api-key or the dashboard)`;
}
+/**
+ * Collapse an `allowedSessions` list to the two shapes the enforcement sites actually distinguish.
+ *
+ * The column is `simple-array`: TypeORM joins on write and splits on read, so `['']` is stored as
+ * `''` and read back as `[]`. Every site treats a zero-length list as "every session", so a write
+ * that looked like a scoping landed as a widening. The DTO validator now refuses such an entry at
+ * the boundary, and this is the second half: whatever reaches storage is either a non-empty list of
+ * real ids, or NULL.
+ *
+ * NULL rather than `[]` on purpose. Both already exist in the table for the same intent, and the
+ * published contract says an unscoped key omits the field, which only NULL produces.
+ */
+function normalizeScopeList(list: string[] | null | undefined): string[] | null {
+ if (list == null) return null;
+ const cleaned = list.map(entry => entry.trim()).filter(entry => entry.length > 0);
+ return cleaned.length > 0 ? cleaned : null;
+}
+
@Injectable()
export class AuthService implements OnModuleInit, OnModuleDestroy {
private readonly logger = createLogger('AuthService');
@@ -183,7 +201,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
keyPrefix,
role: dto.role || ApiKeyRole.OPERATOR,
allowedIps: dto.allowedIps || null,
- allowedSessions: dto.allowedSessions || null,
+ allowedSessions: normalizeScopeList(dto.allowedSessions),
expiresAt: dto.expiresAt ? new Date(dto.expiresAt) : null,
});
@@ -219,7 +237,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
const removesOrSchedulesLastAdmin =
(dto.role !== undefined && dto.role !== ApiKeyRole.ADMIN) ||
(dto.expiresAt !== undefined && dto.expiresAt !== null) ||
- (dto.allowedSessions !== undefined && dto.allowedSessions.length > 0);
+ (normalizeScopeList(dto.allowedSessions)?.length ?? 0) > 0;
// 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
@@ -237,7 +255,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
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.allowedSessions !== undefined) patch.allowedSessions = normalizeScopeList(dto.allowedSessions);
if (dto.expiresAt !== undefined) patch.expiresAt = dto.expiresAt ? new Date(dto.expiresAt) : null;
let saved: ApiKey;
@@ -260,7 +278,13 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
// 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);
+ // Normalize before comparing: a legacy row stored as '' reads back as [], which means the same
+ // as NULL at every enforcement site, so treating them as different would evict live sockets for a
+ // write that changed nothing.
+ const ordered = (v: string[] | null) => {
+ const normalized = normalizeScopeList(v);
+ return normalized ? [...normalized].sort() : null;
+ };
const authzChanged =
saved.role !== before.role ||
saved.expiresAt?.getTime() !== before.expiresAt?.getTime() ||
diff --git a/src/modules/auth/dto/api-key.dto.ts b/src/modules/auth/dto/api-key.dto.ts
index e1c4817fa..da1eb270a 100644
--- a/src/modules/auth/dto/api-key.dto.ts
+++ b/src/modules/auth/dto/api-key.dto.ts
@@ -1,7 +1,18 @@
-import { IsString, IsOptional, IsEnum, IsArray, IsDateString, MinLength, MaxLength, Validate } from 'class-validator';
+import {
+ IsString,
+ IsOptional,
+ IsEnum,
+ IsArray,
+ ArrayUnique,
+ IsDateString,
+ MinLength,
+ MaxLength,
+ Validate,
+} from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { ApiKeyRole } from '../entities/api-key.entity';
import { IsIpOrCidrConstraint } from './is-ip-or-cidr.validator';
+import { IsSessionIdConstraint } from './is-session-id.validator';
export class CreateApiKeyDto {
@ApiProperty({
@@ -42,6 +53,8 @@ export class CreateApiKeyDto {
@IsOptional()
@IsArray()
@IsString({ each: true })
+ @ArrayUnique()
+ @Validate(IsSessionIdConstraint, { each: true })
allowedSessions?: string[];
@ApiPropertyOptional({
@@ -131,6 +144,8 @@ export class UpdateApiKeyDto {
@IsOptional()
@IsArray()
@IsString({ each: true })
+ @ArrayUnique()
+ @Validate(IsSessionIdConstraint, { each: true })
allowedSessions?: string[];
@ApiPropertyOptional()
diff --git a/src/modules/auth/dto/is-session-id.validator.spec.ts b/src/modules/auth/dto/is-session-id.validator.spec.ts
new file mode 100644
index 000000000..bdf79f383
--- /dev/null
+++ b/src/modules/auth/dto/is-session-id.validator.spec.ts
@@ -0,0 +1,59 @@
+import { validate } from 'class-validator';
+import { plainToInstance } from 'class-transformer';
+import { isSessionId } from './is-session-id.validator';
+import { CreateApiKeyDto, UpdateApiKeyDto } from './api-key.dto';
+
+/**
+ * `allowedSessions` is stored in a `simple-array` column: TypeORM joins on write and splits on
+ * read. Two entry shapes therefore do not survive the round trip, and both fail OPEN.
+ *
+ * `['']` joins to `''`, reads back as `[]`, and every enforcement site treats a zero-length list as
+ * "every session" — so a request that looked like a scoping landed as a widening. An entry holding
+ * a comma comes back as two entries, so the stored allowlist is not the one that was sent.
+ */
+describe('isSessionId', () => {
+ it.each(['0a941dac-a965-45e7-b318-74ae8be134f0', 'legacy-id', 'a'])('accepts %p', value => {
+ expect(isSessionId(value)).toBe(true);
+ });
+
+ it.each([
+ ['', 'empty: joins to the same string as an unscoped key'],
+ [' ', 'whitespace only: trims to empty'],
+ [' id', 'leading space: never equals a stored id'],
+ ['id ', 'trailing space: never equals a stored id'],
+ ['a,b', 'comma: splits into two entries on read'],
+ ])('rejects %p (%s)', value => {
+ expect(isSessionId(value)).toBe(false);
+ });
+
+ it.each([undefined, null, 42, {}, []])('rejects the non-string %p', value => {
+ expect(isSessionId(value)).toBe(false);
+ });
+});
+
+describe('allowedSessions validation on the DTOs', () => {
+ const errorsFor = async (Dto: typeof CreateApiKeyDto | typeof UpdateApiKeyDto, allowedSessions: unknown) => {
+ const dto = plainToInstance(Dto, { name: 'k', allowedSessions });
+ const errors = await validate(dto, { whitelist: true });
+ return errors.filter(e => e.property === 'allowedSessions');
+ };
+
+ it.each([CreateApiKeyDto, UpdateApiKeyDto])('%p refuses the fail-open [""]', async Dto => {
+ expect(await errorsFor(Dto, [''])).not.toHaveLength(0);
+ });
+
+ it.each([CreateApiKeyDto, UpdateApiKeyDto])('%p refuses a comma-bearing entry', async Dto => {
+ expect(await errorsFor(Dto, ['a,b'])).not.toHaveLength(0);
+ });
+
+ it.each([CreateApiKeyDto, UpdateApiKeyDto])('%p refuses duplicates', async Dto => {
+ expect(await errorsFor(Dto, ['same', 'same'])).not.toHaveLength(0);
+ });
+
+ // The unscoped forms stay valid: they are the documented way to grant every session.
+ it.each([CreateApiKeyDto, UpdateApiKeyDto])('%p still accepts an empty list and a real id', async Dto => {
+ expect(await errorsFor(Dto, [])).toHaveLength(0);
+ expect(await errorsFor(Dto, ['0a941dac-a965-45e7-b318-74ae8be134f0'])).toHaveLength(0);
+ expect(await errorsFor(Dto, undefined)).toHaveLength(0);
+ });
+});
diff --git a/src/modules/auth/dto/is-session-id.validator.ts b/src/modules/auth/dto/is-session-id.validator.ts
new file mode 100644
index 000000000..02429c8a4
--- /dev/null
+++ b/src/modules/auth/dto/is-session-id.validator.ts
@@ -0,0 +1,32 @@
+import { ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';
+
+/**
+ * Whether a string can survive the round trip into `allowedSessions` and still mean what was sent.
+ *
+ * The column is `simple-array`, which TypeORM stores as a comma join and reads back with a comma
+ * split. Two shapes therefore do not survive it, and both fail OPEN rather than closed:
+ *
+ * - An empty or whitespace-only entry. `[""]` joins to `''`, reads back as `[]`, and every
+ * enforcement site treats a zero-length list as "every session". A request that looked like a
+ * scoping landed as a widening, which is the opposite of what the caller asked for.
+ * - An entry containing a comma. `["a,b"]` reads back as two entries, so the stored allowlist is
+ * not the one that was sent.
+ *
+ * Deliberately NOT a UUID rule, even though session ids are always server-generated UUIDs. A
+ * non-UUID entry fails CLOSED (it matches no session), so it is a usability wart rather than a
+ * security hole, while a UUID rule would reject an operator re-saving a key whose allowlist holds a
+ * legacy or imported id.
+ */
+export function isSessionId(value: unknown): boolean {
+ return typeof value === 'string' && value.trim() === value && value.length > 0 && !value.includes(',');
+}
+
+@ValidatorConstraint({ name: 'isSessionId', async: false })
+export class IsSessionIdConstraint implements ValidatorConstraintInterface {
+ validate(value: unknown): boolean {
+ return isSessionId(value);
+ }
+ defaultMessage(): string {
+ return 'each allowedSessions entry must be a non-empty session id with no surrounding whitespace and no comma';
+ }
+}