Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

hardening: prod secret guard, Postgres pool timeouts, API key pepper warning (#480)

Yudhi Armyndharis6f01fc9d6b5c
diff --git a/.env.example b/.env.example
index 90dd3fa58..477c35d6f 100644
--- a/.env.example
+++ b/.env.example
@@ -129,6 +129,10 @@ DATABASE_LOGGING=false
MAIN_DATABASE_SYNCHRONIZE=true
DATABASE_SSL=false # Set true for managed Postgres (Supabase, Heroku, Render, Railway)
DATABASE_SSL_REJECT_UNAUTHORIZED=true # Set false to allow self-signed certs (only when DATABASE_SSL=true)
+# Postgres pool/query timeouts (ms). Defaults are conservative; set any to 0 to disable.
+DATABASE_STATEMENT_TIMEOUT_MS=30000 # Aborts a single runtime query that runs longer (server-side; not applied to migrations)
+DATABASE_IDLE_TIMEOUT_MS=30000 # Closes idle pooled connections after this long
+DATABASE_CONNECTION_TIMEOUT_MS=10000 # Fails fast if a new connection can't be acquired in time
# =============================================================================
# REDIS / QUEUE (Phase 2)
@@ -234,6 +238,11 @@ API_MASTER_KEY=
# `dev-admin-key` instead. Ignored when API_MASTER_KEY is set.
# ALLOW_DEV_API_KEY=true
+# Optional server-side pepper for API-key hashing (HMAC-SHA256 instead of plain SHA-256).
+# Recommended in production. Note: setting or changing it invalidates all existing key hashes,
+# so re-issue keys after enabling. Leave unset to keep the current (unpeppered) behaviour.
+# API_KEY_PEPPER=
+
# =============================================================================
# DEVELOPER SETTINGS
# =============================================================================
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e4e643f7c..cdd91b26c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- CI now runs the dashboard unit tests, and re-runs the client-SDK suites when a server DTO or the engine interface changes (not only on SDK edits), so contract drift is caught at its source. (#478)
+- The Postgres connection pool now applies query/connection timeouts (`statement_timeout`, `idleTimeoutMillis`, `connectionTimeoutMillis`) on the runtime connection, so a stuck query or a saturated pool fails fast instead of hanging requests. The migration connection keeps idle/connection timeouts but never `statement_timeout`, so a long `CREATE INDEX` is not aborted. Env-tunable (`DATABASE_STATEMENT_TIMEOUT_MS`, `DATABASE_IDLE_TIMEOUT_MS`, `DATABASE_CONNECTION_TIMEOUT_MS`), conservative defaults, `0` disables; SQLite is unaffected. (#480)
### Fixed
@@ -30,6 +31,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The startup banner prints the full admin API key only when it is first created; on subsequent boots the key is masked, so the live credential is not re-written to the log pipeline on every restart. (#478)
- The production secret guard now rejects a placeholder `REDIS_PASSWORD` (e.g. `changeme`); an empty/unset password is still allowed so passwordless private-network Redis continues to boot. (#478)
- The published PHP SDK package no longer ships its test suite, PHPUnit config, or `composer.lock`. (#478)
+- The production weak-secret guard now also rejects the common defaults `123456`, `qwerty`, `root`, `test`, and `demo`. Matching stays an exact full-value comparison, so a strong secret that merely contains one of these words is not blocked. (#480)
+- The gateway now logs a startup warning when `API_KEY_PEPPER` is unset in production (stored API-key hashes then use plain SHA-256). Advisory only — enabling a pepper invalidates existing key hashes, so it stays opt-in and is never enforced. (#480)
## [0.7.5] - 2026-06-26
diff --git a/src/app.module.ts b/src/app.module.ts
index 1fce70fb0..3cee4ed07 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -161,6 +161,11 @@ if (dashboardServingEnabled && dashboardBuildPresent) {
retryDelay: 3000,
extra: {
max: configService.get<number>('dataDatabase.poolSize', 10),
+ // Runtime query/pool timeouts so a stuck query or saturated pool fails fast instead of
+ // hanging requests. statement_timeout is safe here (no migrations on this connection).
+ statement_timeout: configService.get<number>('dataDatabase.statementTimeoutMs', 30000),
+ idleTimeoutMillis: configService.get<number>('dataDatabase.idleTimeoutMs', 30000),
+ connectionTimeoutMillis: configService.get<number>('dataDatabase.connectionTimeoutMs', 10000),
},
};
}
diff --git a/src/config/bootstrap-security.spec.ts b/src/config/bootstrap-security.spec.ts
index 4302b2910..745ae6353 100644
--- a/src/config/bootstrap-security.spec.ts
+++ b/src/config/bootstrap-security.spec.ts
@@ -3,6 +3,7 @@ import {
isSwaggerEnabled,
resolveBodyLimit,
assertNoDefaultSecretsInProduction,
+ isApiKeyPepperMissingInProduction,
} from './bootstrap-security';
describe('resolveCorsPolicy', () => {
@@ -177,4 +178,53 @@ describe('assertNoDefaultSecretsInProduction', () => {
assertNoDefaultSecretsInProduction({ nodeEnv: 'production', databaseType: 'sqlite', databasePassword: 'openwa' }),
).not.toThrow();
});
+
+ it('refuses prod with common default passwords (123456, qwerty, root, test, demo)', () => {
+ for (const weak of ['123456', 'qwerty', 'root', 'test', 'demo']) {
+ expect(() => assertNoDefaultSecretsInProduction({ nodeEnv: 'production', apiMasterKey: weak })).toThrow(
+ /API_MASTER_KEY/,
+ );
+ }
+ });
+
+ it('matches blocklisted defaults case-insensitively', () => {
+ expect(() => assertNoDefaultSecretsInProduction({ nodeEnv: 'production', apiMasterKey: 'QWERTY' })).toThrow(
+ /API_MASTER_KEY/,
+ );
+ expect(() =>
+ assertNoDefaultSecretsInProduction({ nodeEnv: 'production', databaseType: 'postgres', databasePassword: 'Root' }),
+ ).toThrow(/DATABASE_PASSWORD/);
+ });
+
+ // Load-bearing invariant: the blocklist is an EXACT full-value match, never a substring scan, so
+ // adding short words (test/root/demo) must not reject a strong secret that merely contains one.
+ it('does not reject a strong secret that only contains a blocklisted word (exact match, not substring)', () => {
+ expect(() =>
+ assertNoDefaultSecretsInProduction({
+ nodeEnv: 'production',
+ databaseType: 'postgres',
+ databasePassword: 'my-test-key-9f3',
+ }),
+ ).not.toThrow();
+ expect(() =>
+ assertNoDefaultSecretsInProduction({ nodeEnv: 'production', apiMasterKey: 'root-pw-8821x' }),
+ ).not.toThrow();
+ });
+});
+
+describe('isApiKeyPepperMissingInProduction', () => {
+ it('is true in production when no pepper is set (incl. empty/whitespace)', () => {
+ expect(isApiKeyPepperMissingInProduction('production', undefined)).toBe(true);
+ expect(isApiKeyPepperMissingInProduction('production', '')).toBe(true);
+ expect(isApiKeyPepperMissingInProduction('production', ' ')).toBe(true);
+ });
+
+ it('is false in production when a pepper is set', () => {
+ expect(isApiKeyPepperMissingInProduction('production', 'a-real-server-pepper')).toBe(false);
+ });
+
+ it('is false outside production regardless of pepper (no dev warning noise)', () => {
+ expect(isApiKeyPepperMissingInProduction('development', undefined)).toBe(false);
+ expect(isApiKeyPepperMissingInProduction(undefined, undefined)).toBe(false);
+ });
});
diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.ts
index 52db1ef48..b1600797d 100644
--- a/src/config/bootstrap-security.ts
+++ b/src/config/bootstrap-security.ts
@@ -62,8 +62,22 @@ const FORBIDDEN_PROD_SECRETS = new Set([
'password',
'secret',
'admin',
+ '123456',
+ 'qwerty',
+ 'root',
+ 'test',
+ 'demo',
]);
+/**
+ * Whether to warn that API_KEY_PEPPER is unset in production. Without a pepper, stored API-key hashes
+ * fall back to plain SHA-256 (still functional). Advisory only — enabling a pepper re-hashes keys and
+ * invalidates existing ones (see api-key-hash.ts), so it stays opt-in and must never be enforced.
+ */
+export function isApiKeyPepperMissingInProduction(nodeEnv?: string, apiKeyPepper?: string): boolean {
+ return nodeEnv === 'production' && !apiKeyPepper?.trim();
+}
+
export interface SecretCheckEnv {
nodeEnv?: string;
databaseType?: string;
diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.ts
index b8d595506..c9c12f30b 100644
--- a/src/config/configuration.spec.ts
+++ b/src/config/configuration.spec.ts
@@ -62,6 +62,36 @@ describe('configuration — Puppeteer args delimiter', () => {
});
});
+describe('configuration — Postgres pool timeouts', () => {
+ const keys = ['DATABASE_STATEMENT_TIMEOUT_MS', 'DATABASE_IDLE_TIMEOUT_MS', 'DATABASE_CONNECTION_TIMEOUT_MS'];
+ const orig: Record<string, string | undefined> = {};
+ beforeEach(() => keys.forEach(k => (orig[k] = process.env[k])));
+ afterEach(() =>
+ keys.forEach(k => {
+ if (orig[k] === undefined) delete process.env[k];
+ else process.env[k] = orig[k];
+ }),
+ );
+
+ it('defaults to sane pool timeouts (30s statement, 30s idle, 10s connection)', () => {
+ keys.forEach(k => delete process.env[k]);
+ const cfg = configuration().dataDatabase;
+ expect(cfg.statementTimeoutMs).toBe(30000);
+ expect(cfg.idleTimeoutMs).toBe(30000);
+ expect(cfg.connectionTimeoutMs).toBe(10000);
+ });
+
+ it('honors env overrides (incl. 0 to disable a timeout)', () => {
+ process.env.DATABASE_STATEMENT_TIMEOUT_MS = '0';
+ process.env.DATABASE_IDLE_TIMEOUT_MS = '15000';
+ process.env.DATABASE_CONNECTION_TIMEOUT_MS = '2000';
+ const cfg = configuration().dataDatabase;
+ expect(cfg.statementTimeoutMs).toBe(0);
+ expect(cfg.idleTimeoutMs).toBe(15000);
+ expect(cfg.connectionTimeoutMs).toBe(2000);
+ });
+});
+
describe('configuration — plugin download cap is fail-safe', () => {
const orig = process.env.PLUGIN_DOWNLOAD_MAX_BYTES;
afterEach(() => {
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index b5d31f4a0..33f8fd9f1 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -52,6 +52,11 @@ export default () => ({
logging: process.env.DATABASE_LOGGING === 'true',
// Connection pooling (PostgreSQL)
poolSize: parseInt(process.env.DATABASE_POOL_SIZE || '10', 10),
+ // Pool/query timeouts (PostgreSQL). statement_timeout is server-side per query; idle/connection
+ // are pool-side. Set any to 0 to disable. Applied to the runtime connection only (see app.module).
+ statementTimeoutMs: parseInt(process.env.DATABASE_STATEMENT_TIMEOUT_MS || '30000', 10),
+ idleTimeoutMs: parseInt(process.env.DATABASE_IDLE_TIMEOUT_MS || '30000', 10),
+ connectionTimeoutMs: parseInt(process.env.DATABASE_CONNECTION_TIMEOUT_MS || '10000', 10),
// SSL configuration
ssl: process.env.DATABASE_SSL === 'true',
sslRejectUnauthorized: process.env.DATABASE_SSL_REJECT_UNAUTHORIZED !== 'false',
diff --git a/src/database/data-source.spec.ts b/src/database/data-source.spec.ts
index b145edf46..44603cc53 100644
--- a/src/database/data-source.spec.ts
+++ b/src/database/data-source.spec.ts
@@ -1,5 +1,5 @@
import { globSync } from 'glob';
-import dataDataSource from './data-source';
+import dataDataSource, { postgresDataSource } from './data-source';
// The data CLI DataSource manages the DATA connection's migrations (session/webhook/message/
// template/engine). It must NOT pull in the auth/audit entities — those belong to the always-SQLite
@@ -32,3 +32,19 @@ describe('data CLI DataSource', () => {
}
});
});
+
+// The migration CLI connection runs DDL (CREATE INDEX, unique backfills) that can legitimately take
+// minutes on a large table. It must carry pool/connection timeouts for resilience but MUST NOT carry a
+// server-side statement_timeout, or a long migration would be aborted mid-flight.
+describe('Postgres migration connection pool timeouts', () => {
+ const extra = postgresDataSource.options.extra as Record<string, number | undefined>;
+
+ it('sets idle and connection pool timeouts', () => {
+ expect(extra.idleTimeoutMillis).toBe(30000);
+ expect(extra.connectionTimeoutMillis).toBe(10000);
+ });
+
+ it('never sets statement_timeout (would abort long-running migrations)', () => {
+ expect(extra.statement_timeout).toBeUndefined();
+ });
+});
diff --git a/src/database/data-source.ts b/src/database/data-source.ts
index 3bb99d74d..b099e8674 100644
--- a/src/database/data-source.ts
+++ b/src/database/data-source.ts
@@ -27,7 +27,7 @@ const sqliteDataSource = new DataSource({
});
// PostgreSQL configuration
-const postgresDataSource = new DataSource({
+export const postgresDataSource = new DataSource({
type: 'postgres',
host: process.env.DATABASE_HOST || 'localhost',
port: parseInt(process.env.DATABASE_PORT || '5432', 10),
@@ -55,6 +55,10 @@ const postgresDataSource = new DataSource({
: false,
extra: {
max: parseInt(process.env.DATABASE_POOL_SIZE || '10', 10),
+ // Pool resilience only. NO statement_timeout here: this connection runs migrations, and a
+ // long CREATE INDEX / backfill must not be aborted mid-flight.
+ idleTimeoutMillis: parseInt(process.env.DATABASE_IDLE_TIMEOUT_MS || '30000', 10),
+ connectionTimeoutMillis: parseInt(process.env.DATABASE_CONNECTION_TIMEOUT_MS || '10000', 10),
},
});
diff --git a/src/main.ts b/src/main.ts
index 39ac59078..fa7dfa049 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -12,6 +12,7 @@ import {
isSwaggerEnabled,
resolveBodyLimit,
assertNoDefaultSecretsInProduction,
+ isApiKeyPepperMissingInProduction,
} from './config/bootstrap-security';
import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';
import { AuthService } from './modules/auth/auth.service';
@@ -127,6 +128,15 @@ async function bootstrap() {
redisPassword: process.env.REDIS_PASSWORD,
});
+ // Advisory (not enforced): without API_KEY_PEPPER, stored API-key hashes use plain SHA-256. Enabling
+ // a pepper re-hashes keys and invalidates existing ones, so we only nudge the operator (see api-key-hash.ts).
+ if (isApiKeyPepperMissingInProduction(process.env.NODE_ENV, process.env.API_KEY_PEPPER)) {
+ bootstrapLogger.warn(
+ 'API_KEY_PEPPER is not set in production: stored API-key hashes use plain SHA-256. ' +
+ 'Set API_KEY_PEPPER and re-issue keys to enable HMAC hashing.',
+ );
+ }
+
// Disable Nest's default body parser so we can set an explicit size cap below.
const app = await NestFactory.create(AppModule, { bodyParser: false });