Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(auth): give the bootstrap key file one owner and a redirect lever

Yudhi Armyndhariscfd0f65c2abd
diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts
index 5f1607e40..403a42616 100644
--- a/src/modules/auth/auth.service.ts
+++ b/src/modules/auth/auth.service.ts
@@ -10,20 +10,16 @@ import { ModuleRef } from '@nestjs/core';
import { InjectRepository } from '@nestjs/typeorm';
import { Equal, IsNull, MoreThan, Not, Repository } from 'typeorm';
import { randomBytes } from 'crypto';
-import { existsSync, readFileSync, unlinkSync } from 'fs';
-import { join } from 'path';
-import { writeSecretFile } from '../../common/utils/secret-file';
import { ipMatches } from '../../common/utils/ip';
import { hashApiKey } from './api-key-hash';
import { ApiKey, ApiKeyRole } from './entities/api-key.entity';
import { CreateApiKeyDto, UpdateApiKeyDto } from './dto';
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';
-const API_KEY_FILE = join(process.cwd(), 'data', '.api-key');
-
/**
* Resolves the API key to seed on first boot (when no keys exist yet).
* Precedence: an explicit `API_MASTER_KEY` always wins; otherwise a
@@ -92,7 +88,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
// Save raw key to file for startup script to read (owner-only — it's the raw admin key).
try {
- writeSecretFile(API_KEY_FILE, displayKey);
+ writeBootstrapKey(displayKey);
} catch (err) {
this.logger.warn('Could not save API key file', { error: String(err) });
}
@@ -139,14 +135,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
* Returns null when the file is absent, unreadable, empty, or stale.
*/
private async readLiveBootstrapKey(): Promise<string | null> {
- if (!existsSync(API_KEY_FILE)) return null;
- let rawKey: string;
- try {
- rawKey = readFileSync(API_KEY_FILE, 'utf-8').trim();
- } catch (error) {
- this.logger.warn(`Failed to read API key file: ${API_KEY_FILE}`, { error: String(error) });
- return null;
- }
+ const rawKey = readBootstrapKey(this.logger);
if (!rawKey) return null;
const stored = await this.apiKeyRepository.findOne({ where: { keyHash: this.hashKey(rawKey) } });
const live = Boolean(stored && stored.isActive && (!stored.expiresAt || stored.expiresAt > new Date()));
@@ -166,7 +155,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
return null;
}
}
- this.removeBootstrapKeyFile('it no longer resolves to an active key');
+ removeBootstrapKey('it no longer resolves to an active key', this.logger);
return null;
}
@@ -177,24 +166,9 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
* removing it cannot break first-boot seeding — seeding writes it only when no keys exist.
*/
private removeBootstrapKeyFileIfMatching(apiKey: ApiKey): void {
- try {
- if (!existsSync(API_KEY_FILE)) return;
- const fileKey = readFileSync(API_KEY_FILE, 'utf-8').trim();
- if (!fileKey || this.hashKey(fileKey) !== apiKey.keyHash) return;
- this.removeBootstrapKeyFile('its key was revoked or deleted');
- } catch (error) {
- this.logger.warn(`Failed to inspect API key file: ${API_KEY_FILE}`, { error: String(error) });
- }
- }
-
- private removeBootstrapKeyFile(reason: string): void {
- try {
- unlinkSync(API_KEY_FILE);
- this.logger.log(`Removed stale bootstrap API key file (${reason}): ${API_KEY_FILE}`);
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; // already gone
- this.logger.warn(`Failed to remove stale API key file: ${API_KEY_FILE}`, { error: String(error) });
- }
+ const fileKey = readBootstrapKey(this.logger);
+ if (!fileKey || this.hashKey(fileKey) !== apiKey.keyHash) return;
+ removeBootstrapKey('its key was revoked or deleted', this.logger);
}
private async seedApiKey(rawKey: string, name: string, role: ApiKeyRole): Promise<ApiKey> {
diff --git a/src/modules/auth/bootstrap-key-file.spec.ts b/src/modules/auth/bootstrap-key-file.spec.ts
new file mode 100644
index 000000000..d05650d99
--- /dev/null
+++ b/src/modules/auth/bootstrap-key-file.spec.ts
@@ -0,0 +1,88 @@
+import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { bootstrapKeyFilePath, readBootstrapKey, writeBootstrapKey, removeBootstrapKey } from './bootstrap-key-file';
+
+const logger = { log: jest.fn(), warn: jest.fn() };
+
+describe('bootstrap key file', () => {
+ let dir: string;
+ const original = process.env.BOOTSTRAP_KEY_FILE;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'owa-bootkey-'));
+ process.env.BOOTSTRAP_KEY_FILE = join(dir, '.api-key');
+ logger.log.mockClear();
+ logger.warn.mockClear();
+ });
+
+ afterEach(() => {
+ if (original === undefined) delete process.env.BOOTSTRAP_KEY_FILE;
+ else process.env.BOOTSTRAP_KEY_FILE = original;
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ describe('bootstrapKeyFilePath', () => {
+ it('honours BOOTSTRAP_KEY_FILE', () => {
+ expect(bootstrapKeyFilePath()).toBe(join(dir, '.api-key'));
+ });
+
+ it('falls back to data/.api-key under the working directory', () => {
+ delete process.env.BOOTSTRAP_KEY_FILE;
+
+ expect(bootstrapKeyFilePath()).toBe(join(process.cwd(), 'data', '.api-key'));
+ });
+
+ it('re-reads the env on every call, so a redirect set after import still takes effect', () => {
+ // This is the whole point: it used to be a module const evaluated at import from process.cwd(),
+ // so an e2e setup that redirects it could not — and an e2e boot rewrote the developer's file.
+ const moved = join(dir, 'moved.key');
+ process.env.BOOTSTRAP_KEY_FILE = moved;
+
+ expect(bootstrapKeyFilePath()).toBe(moved);
+ });
+ });
+
+ describe('readBootstrapKey', () => {
+ it('returns null when the file is absent', () => {
+ expect(readBootstrapKey(logger)).toBeNull();
+ });
+
+ it('returns null for an empty or whitespace-only file rather than a blank key', () => {
+ writeFileSync(join(dir, '.api-key'), ' \n');
+
+ expect(readBootstrapKey(logger)).toBeNull();
+ });
+
+ it('returns the trimmed key', () => {
+ writeFileSync(join(dir, '.api-key'), ' owa_k1_abc \n');
+
+ expect(readBootstrapKey(logger)).toBe('owa_k1_abc');
+ });
+ });
+
+ describe('writeBootstrapKey', () => {
+ it('writes to the resolved path', () => {
+ writeBootstrapKey('owa_k1_written');
+
+ expect(readFileSync(join(dir, '.api-key'), 'utf-8')).toContain('owa_k1_written');
+ });
+ });
+
+ describe('removeBootstrapKey', () => {
+ it('removes the file and says why', () => {
+ writeFileSync(join(dir, '.api-key'), 'owa_k1_abc');
+
+ removeBootstrapKey('its key was revoked or deleted', logger);
+
+ expect(existsSync(join(dir, '.api-key'))).toBe(false);
+ expect(logger.log).toHaveBeenCalledWith(expect.stringContaining('revoked or deleted'));
+ });
+
+ it('treats an already-absent file as success, not a failure to report', () => {
+ removeBootstrapKey('gone anyway', logger);
+
+ expect(logger.warn).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/modules/auth/bootstrap-key-file.ts b/src/modules/auth/bootstrap-key-file.ts
new file mode 100644
index 000000000..3188a509b
--- /dev/null
+++ b/src/modules/auth/bootstrap-key-file.ts
@@ -0,0 +1,53 @@
+import { existsSync, readFileSync, unlinkSync } from 'fs';
+import { join } from 'path';
+import { writeSecretFile } from '../../common/utils/secret-file';
+import type { LoggerService } from '../../common/services/logger.service';
+
+/**
+ * `data/.api-key` — the bootstrap key file.
+ *
+ * It is an operator convenience: the first-boot banner quotes it, and backup scripts read it. It is
+ * never read for seeding or for authentication, so removing it can never lock anyone out.
+ *
+ * The point of gathering the four file operations here is that the file is a single resource touched
+ * by two concerns that otherwise share nothing — first-boot seeding writes it, and admin key
+ * lifecycle unlinks it when the key it holds is revoked or deleted. As a module const reached from
+ * both, it was the coupling; as a resource with one owner, each concern asks for what it needs.
+ *
+ * The path resolves PER CALL, and honours `BOOTSTRAP_KEY_FILE`. Both matter: it used to be a const
+ * evaluated at import from `process.cwd()`, so nothing could redirect it — which is why an e2e boot
+ * (whose setup redirects both databases) still wrote and unlinked the developer's real repo-root
+ * `data/.api-key`.
+ */
+export function bootstrapKeyFilePath(): string {
+ return process.env.BOOTSTRAP_KEY_FILE || join(process.cwd(), 'data', '.api-key');
+}
+
+/** The raw key the file holds, or null when absent, unreadable or empty. Never throws. */
+export function readBootstrapKey(logger: Pick<LoggerService, 'warn'>): string | null {
+ const file = bootstrapKeyFilePath();
+ if (!existsSync(file)) return null;
+ try {
+ return readFileSync(file, 'utf-8').trim() || null;
+ } catch (error) {
+ logger.warn(`Failed to read API key file: ${file}`, { error: String(error) });
+ return null;
+ }
+}
+
+/** Write the key owner-only (0600) — it is a live credential until the operator rotates it. */
+export function writeBootstrapKey(displayKey: string): void {
+ writeSecretFile(bootstrapKeyFilePath(), displayKey);
+}
+
+/** Remove the file. Absent is success, not a failure — the caller's intent is "make it gone". */
+export function removeBootstrapKey(reason: string, logger: Pick<LoggerService, 'log' | 'warn'>): void {
+ const file = bootstrapKeyFilePath();
+ try {
+ unlinkSync(file);
+ logger.log(`Removed stale bootstrap API key file (${reason}): ${file}`);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; // already gone
+ logger.warn(`Failed to remove stale API key file: ${file}`, { error: String(error) });
+ }
+}
diff --git a/test/setup-e2e.ts b/test/setup-e2e.ts
index 11ab102eb..42a73c3dd 100644
--- a/test/setup-e2e.ts
+++ b/test/setup-e2e.ts
@@ -16,6 +16,12 @@ process.env.DATABASE_NAME = e2eDataDb;
const e2eMainDb = join(tmpdir(), `openwa-e2e-main-${process.pid}.sqlite`);
rmSync(e2eMainDb, { force: true });
process.env.MAIN_DATABASE_NAME = e2eMainDb;
+// The bootstrap key file is written on first boot (no keys yet — which every e2e run is) and unlinked
+// when that key is revoked or deleted. Without a lever it resolves under the repo root, so an e2e run
+// rewrote the DEVELOPER'S ./data/.api-key. Point it at the same throwaway temp dir as the databases.
+const e2eKeyFile = join(tmpdir(), `openwa-e2e-key-${process.pid}`);
+rmSync(e2eKeyFile, { force: true });
+process.env.BOOTSTRAP_KEY_FILE = e2eKeyFile;
process.env.QUEUE_ENABLED = 'false';
// Likewise force Redis off per suite: queue-on.e2e-spec.ts flips REDIS_ENABLED=true at module
// load and can't restore it when it self-skips, so without this reset later suites in the same