Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(config): validate six numeric env knobs at boot

Yudhi Armyndharis0ee52fc868ed
diff --git a/.env.example b/.env.example
index 408290017..5ee260eae 100644
--- a/.env.example
+++ b/.env.example
@@ -369,6 +369,8 @@ DATABASE_SYNCHRONIZE=false # WARNING: Set false in production! (data DB
# REDIS_CONNECT_TIMEOUT_MS=5000
# REDIS_USERNAME=
# REDIS_PASSWORD=
+# Redis logical database for the cache (the queue uses the default database).
+# REDIS_CACHE_DB=1
# =============================================================================
# STORAGE
diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.ts
index 9d50dae7b..c75cc6be5 100644
--- a/src/config/configuration.spec.ts
+++ b/src/config/configuration.spec.ts
@@ -259,7 +259,7 @@ describe('configuration — webhook fan-out knobs are fail-safe', () => {
describe('configuration search namespace', () => {
// Save/restore the SEARCH_* env vars so a CI .env that sets them cannot flake the default-value
// assertions below (mirrors the mutate-and-restore pattern used for PLUGIN_DOWNLOAD_MAX_BYTES etc.).
- const keys = ['SEARCH_ENABLED', 'SEARCH_PROVIDER', 'SEARCH_LIMIT_MAX'];
+ const keys = ['SEARCH_ENABLED', 'SEARCH_PROVIDER'];
const orig: Record<string, string | undefined> = {};
beforeEach(() => keys.forEach(k => (orig[k] = process.env[k])));
afterEach(() =>
@@ -272,7 +272,7 @@ describe('configuration search namespace', () => {
it('exposes search defaults', () => {
keys.forEach(k => delete process.env[k]);
const cfg = configuration();
- expect(cfg.search).toEqual({ enabled: true, provider: 'auto', limitMax: 100 });
+ expect(cfg.search).toEqual({ enabled: true, provider: 'auto' });
});
});
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index 393a5026f..b831f3577 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -117,7 +117,6 @@ export default () => ({
search: {
enabled: process.env.SEARCH_ENABLED !== 'false',
provider: process.env.SEARCH_PROVIDER || 'auto',
- limitMax: Number(process.env.SEARCH_LIMIT_MAX) || 100,
},
// Dashboard statistics. The /stats aggregates run GROUP BY scans over the whole messages
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.ts
index ac0d0ac58..0d94c5cd0 100644
--- a/src/config/env.validation.spec.ts
+++ b/src/config/env.validation.spec.ts
@@ -541,6 +541,27 @@ describe('validateEnv', () => {
expect(() => validateEnv({ [key]: '3600000' })).not.toThrow();
});
+ // Each read fell back to the default on 0 or garbage, or passed a negative or fractional value on.
+ it.each(['SEARCH_LIMIT_MAX', 'INGRESS_MAX_ATTEMPTS', 'WEBHOOK_WORKER_CONCURRENCY', 'INGRESS_WORKER_CONCURRENCY'])(
+ 'rejects a non-positive or non-integer %s and accepts a plain count',
+ key => {
+ for (const bad of ['0', '-5', '2.5', 'abc', '5x']) {
+ expect(() => validateEnv({ [key]: bad })).toThrow(new RegExp(`${key} must be a positive integer`));
+ }
+ expect(() => validateEnv({ [key]: '7' })).not.toThrow();
+ expect(() => validateEnv({ [key]: '' })).not.toThrow();
+ expect(() => validateEnv({ [key]: ' ' })).not.toThrow();
+ },
+ );
+
+ it.each(['INGRESS_RETRY_DELAY_MS', 'REDIS_CACHE_DB'])('rejects a negative or non-integer %s and keeps 0', key => {
+ for (const bad of ['-1', '1.5', 'abc']) {
+ expect(() => validateEnv({ [key]: bad })).toThrow(new RegExp(`${key} must be a non-negative integer`));
+ }
+ expect(() => validateEnv({ [key]: '0' })).not.toThrow();
+ expect(() => validateEnv({ [key]: '' })).not.toThrow();
+ });
+
it('rejects a unit-suffixed CHAT_MEDIA_ARCHIVE_TTL_DAYS but keeps 0 (keep forever)', () => {
expect(() => validateEnv({ CHAT_MEDIA_ARCHIVE_TTL_DAYS: '30d' })).toThrow(/CHAT_MEDIA_ARCHIVE_TTL_DAYS/);
expect(() => validateEnv({ CHAT_MEDIA_ARCHIVE_TTL_DAYS: '0' })).not.toThrow();
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index 7deab92e2..1fd781a6d 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -220,6 +220,8 @@ export function validateEnv(config: EnvConfig): EnvConfig {
'EXPORT_INLINE_MEDIA_BUDGET_BYTES', // 0 = a data export carries no inline media at all
'MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES', // 0 = a message list carries no inline media at all
'CHAT_MEDIA_ARCHIVE_TTL_DAYS', // 0 = keep archived chat media forever
+ 'INGRESS_RETRY_DELAY_MS', // 0 = retry without backoff
+ 'REDIS_CACHE_DB',
]) {
checkNonNegativeInt(key);
}
@@ -337,6 +339,12 @@ export function validateEnv(config: EnvConfig): EnvConfig {
// the boot sweep delete every archive older than 24 ms, breaking export, restart, import.
'STORAGE_EXPORT_TTL_MS',
'STORAGE_EXPORT_SWEEP_MAX_AGE_MS',
+ // Each read fell back to its default on 0 or garbage, or passed a negative or fractional value on
+ // (SEARCH_LIMIT_MAX reached plugin search providers as-is).
+ 'SEARCH_LIMIT_MAX',
+ 'INGRESS_MAX_ATTEMPTS',
+ 'WEBHOOK_WORKER_CONCURRENCY',
+ 'INGRESS_WORKER_CONCURRENCY',
]) {
checkPositiveInt(key);
}
diff --git a/src/modules/integration/ingress-enqueue.service.spec.ts b/src/modules/integration/ingress-enqueue.service.spec.ts
index 5831cda52..9484610eb 100644
--- a/src/modules/integration/ingress-enqueue.service.spec.ts
+++ b/src/modules/integration/ingress-enqueue.service.spec.ts
@@ -243,6 +243,17 @@ describe('IngressEnqueueService', () => {
}
});
+ it.each(['1e1', '0x10', '0'])('falls back to 3 attempts for INGRESS_MAX_ATTEMPTS=%p', raw => {
+ const prevA = process.env.INGRESS_MAX_ATTEMPTS;
+ try {
+ process.env.INGRESS_MAX_ATTEMPTS = raw;
+ expect(resolveIngressJobOptions().attempts).toBe(3);
+ } finally {
+ if (prevA === undefined) delete process.env.INGRESS_MAX_ATTEMPTS;
+ else process.env.INGRESS_MAX_ATTEMPTS = prevA;
+ }
+ });
+
it('treats a blank INGRESS_RETRY_DELAY_MS as unset, not as 0', () => {
const prevD = process.env.INGRESS_RETRY_DELAY_MS;
try {
diff --git a/src/modules/integration/ingress-enqueue.service.ts b/src/modules/integration/ingress-enqueue.service.ts
index 1dacda95c..4d543c037 100644
--- a/src/modules/integration/ingress-enqueue.service.ts
+++ b/src/modules/integration/ingress-enqueue.service.ts
@@ -29,9 +29,8 @@ export type EnqueueOutcome = { outcome: 'queued' | 'dispatched' | 'failed'; erro
* INGRESS_RETRY_DELAY_MS); an invalid value falls back to the default.
*/
export function resolveIngressJobOptions(): { attempts: number; backoff: { type: 'exponential'; delay: number } } {
- const attempts = Number(process.env.INGRESS_MAX_ATTEMPTS);
return {
- attempts: Number.isInteger(attempts) && attempts >= 1 ? attempts : 3,
+ attempts: resolveNonNegativeIntEnv(process.env.INGRESS_MAX_ATTEMPTS, 0) || 3,
backoff: { type: 'exponential', delay: resolveNonNegativeIntEnv(process.env.INGRESS_RETRY_DELAY_MS, 5000) },
};
}
diff --git a/src/modules/queue/redis-connection.spec.ts b/src/modules/queue/redis-connection.spec.ts
index 26f11a817..2c0096478 100644
--- a/src/modules/queue/redis-connection.spec.ts
+++ b/src/modules/queue/redis-connection.spec.ts
@@ -1,4 +1,4 @@
-import { workerConnectionOptions, webhookWorkerConcurrency } from './redis-connection';
+import { ingressWorkerConcurrency, workerConnectionOptions, webhookWorkerConcurrency } from './redis-connection';
describe('workerConnectionOptions (webhook Worker connection)', () => {
const ORIGINAL_ENV = process.env;
@@ -68,4 +68,11 @@ describe('webhookWorkerConcurrency', () => {
process.env = { ...ORIGINAL_ENV, WEBHOOK_WORKER_CONCURRENCY: 'abc' };
expect(webhookWorkerConcurrency()).toBe(10);
});
+
+ it('does not read the leading digits of a unit-suffixed value', () => {
+ process.env = { ...ORIGINAL_ENV, WEBHOOK_WORKER_CONCURRENCY: '5abc' };
+ expect(webhookWorkerConcurrency()).toBe(10);
+ process.env = { ...ORIGINAL_ENV, INGRESS_WORKER_CONCURRENCY: '5abc' };
+ expect(ingressWorkerConcurrency()).toBe(10);
+ });
});
diff --git a/src/modules/queue/redis-connection.ts b/src/modules/queue/redis-connection.ts
index 1122208ad..f0357f32b 100644
--- a/src/modules/queue/redis-connection.ts
+++ b/src/modules/queue/redis-connection.ts
@@ -1,3 +1,5 @@
+import { resolveNonNegativeIntEnv } from '../../config/configuration';
+
/**
* BullMQ Redis connection options for the WEBHOOK queue's Worker.
*
@@ -47,8 +49,7 @@ const DEFAULT_WEBHOOK_WORKER_CONCURRENCY = 10;
* workerConnectionOptions above.)
*/
export function webhookWorkerConcurrency(): number {
- const parsed = parseInt(process.env.WEBHOOK_WORKER_CONCURRENCY || '', 10);
- return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_WEBHOOK_WORKER_CONCURRENCY;
+ return resolveNonNegativeIntEnv(process.env.WEBHOOK_WORKER_CONCURRENCY, 0) || DEFAULT_WEBHOOK_WORKER_CONCURRENCY;
}
/** Default number of ingress events the Worker processes in parallel. */
@@ -64,6 +65,5 @@ const DEFAULT_INGRESS_WORKER_CONCURRENCY = 10;
* non-positive/garbage value falls back to the default.
*/
export function ingressWorkerConcurrency(): number {
- const parsed = parseInt(process.env.INGRESS_WORKER_CONCURRENCY || '', 10);
- return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_INGRESS_WORKER_CONCURRENCY;
+ return resolveNonNegativeIntEnv(process.env.INGRESS_WORKER_CONCURRENCY, 0) || DEFAULT_INGRESS_WORKER_CONCURRENCY;
}
diff --git a/src/modules/search/search.constants.spec.ts b/src/modules/search/search.constants.spec.ts
new file mode 100644
index 000000000..3f36a6204
--- /dev/null
+++ b/src/modules/search/search.constants.spec.ts
@@ -0,0 +1,26 @@
+describe('SEARCH_LIMIT_MAX', () => {
+ const orig = process.env.SEARCH_LIMIT_MAX;
+ afterEach(() => {
+ if (orig === undefined) delete process.env.SEARCH_LIMIT_MAX;
+ else process.env.SEARCH_LIMIT_MAX = orig;
+ });
+
+ const load = (raw: string | undefined): number => {
+ if (raw === undefined) delete process.env.SEARCH_LIMIT_MAX;
+ else process.env.SEARCH_LIMIT_MAX = raw;
+ let value = 0;
+ jest.isolateModules(() => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ value = (require('./search.constants') as typeof import('./search.constants')).SEARCH_LIMIT_MAX;
+ });
+ return value;
+ };
+
+ it('honors a positive integer', () => {
+ expect(load('250')).toBe(250);
+ });
+
+ it.each([undefined, '', '0', '-5', '2.5', 'abc', '5x'])('falls back to 100 for %p', raw => {
+ expect(load(raw)).toBe(100);
+ });
+});
diff --git a/src/modules/search/search.constants.ts b/src/modules/search/search.constants.ts
index 168802776..be8419d4a 100644
--- a/src/modules/search/search.constants.ts
+++ b/src/modules/search/search.constants.ts
@@ -1,3 +1,5 @@
+import { resolveNonNegativeIntEnv } from '../../config/configuration';
+
/**
* Host-side /search pagination bounds. Applied in SearchService BEFORE delegating to any provider,
* so every backend (built-in DB full-text + plugin-backed) receives bounded pagination — a plugin
@@ -9,7 +11,7 @@
* SEARCH_OFFSET_MAX is a fixed deep-pagination guard (an offset this large is almost always a scan
* or abuse pattern), intentionally not env-driven to avoid expanding the config surface.
*/
-export const SEARCH_LIMIT_MAX = Number(process.env.SEARCH_LIMIT_MAX) || 100;
+export const SEARCH_LIMIT_MAX = resolveNonNegativeIntEnv(process.env.SEARCH_LIMIT_MAX, 100) || 100;
/** Generous upper bound on offset across every provider. */
export const SEARCH_OFFSET_MAX = 100_000;