Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): run boot validation on the config being saved
Yudhi Armyndharis5ff1d09735fa
diff --git a/src/modules/infra/bundled-host-decisions.spec.ts b/src/modules/infra/bundled-host-decisions.spec.tsindex 6ef17b014..d9f370dbc 100644--- a/src/modules/infra/bundled-host-decisions.spec.ts+++ b/src/modules/infra/bundled-host-decisions.spec.ts@@ -5,6 +5,7 @@ jest.mock('fs', () => {return {...actual,writeFileSync: jest.fn(),+ renameSync: jest.fn(),chmodSync: jest.fn(),existsSync: jest.fn().mockReturnValue(false),readFileSync: jest.fn().mockReturnValue(''),@@ -18,7 +19,13 @@ jest.mock('../../config/storage-root', () => {import { InfraConfigController } from './infra-config.controller';import { InfraStatusController } from './infra-status.controller';import { hostPinnedElsewhere } from '../docker';-import { recordPinnedEnvKeys } from '../../config/env-precedence';+import {+ BLANK_SHADOWED_ENV_KEYS,+ clearBlankEnv,+ isEnvPinned,+ recordOsEnvKeys,+ recordPinnedEnvKeys,+} from '../../config/env-precedence';import { HOST_SPELLINGS, SERVICES, SERVICE_NAMES, type ServiceName } from '../../../test/fixtures/builtin-mode-cases';// Every decision that asks whether a host is the bundled container, for every spelling of the shared table, with the@@ -72,17 +79,35 @@ const label = (c: Case) => `${c.service} ${JSON.stringify(c.host)} ${c.position}let pinnedKeys: string[] = [];let fileText = '';+let environment: NodeJS.ProcessEnv;++beforeEach(() => {+ environment = { ...process.env };+ for (const key of Object.keys(process.env)) {+ if (/^(DATABASE_|POSTGRES_|REDIS_|STORAGE_|S3_|MINIO_|QUEUE_|CACHE_|ENGINE_TYPE$)/.test(key))+ delete process.env[key];+ }+});function arrange(c: Case, stored = ''): void {const spec = SERVICES[c.service];// A pinned host must outrank the file's, so the file holds a host of the other kind.const fileHost = c.position === 'file' ? c.host : c.reach ? spec.externalHost : spec.bundledHost;- const lines = [`${spec.selection}=${spec.selected}`, `${spec.host}=${fileHost}`];+ // Unrelated stored database fields still belong to a complete PostgreSQL connection.+ const lines = [+ 'DATABASE_TYPE=postgres',+ 'DATABASE_HOST=db.external.example',+ 'DATABASE_USERNAME=openwa',+ `${spec.selection}=${spec.selected}`,+ `${spec.host}=${fileHost}`,+ ];if (c.flag !== 'absent') lines.push(`${spec.flag}=${c.flag}`);fileText = `${lines.join('\n')}\n${STORED_SECRETS}${stored}`;const pins: Record<string, string> = { ...SECRETS, ...(c.position === 'pinned' ? { [spec.host]: c.host } : {}) };Object.assign(process.env, pins);pinnedKeys = Object.keys(pins);+ // Credentials are OS-supplied; the case's host pin is a project .env assignment, including a real blank.+ recordOsEnvKeys(SECRETS);recordPinnedEnvKeys(pins);(fs.existsSync as jest.Mock).mockReturnValue(true);(fs.readFileSync as jest.Mock).mockReturnValue(fileText);@@ -92,6 +117,11 @@ function arrange(c: Case, stored = ''): void {afterEach(() => {for (const key of pinnedKeys) delete process.env[key];pinnedKeys = [];+ for (const key of Object.keys(process.env)) {+ if (!(key in environment)) delete process.env[key];+ }+ Object.assign(process.env, environment);+ recordOsEnvKeys(process.env);recordPinnedEnvKeys({});(fs.existsSync as jest.Mock).mockReturnValue(false);(fs.readFileSync as jest.Mock).mockReturnValue('');@@ -149,6 +179,7 @@ describe.each(cases.map(c => [label(c), c] as const))('%s', (_label, c) => {// The host the next boot dials reaches the container exactly when this case's host does: a pinned one outranks a// file host of the other kind, and a file host is read as is.const reached = c.reach;+ const blankProjectDatabaseHost = c.service === 'database' && c.position === 'pinned' && c.host.trim() === '';it('may start the container unless a pin names another server', async () => {arrange(c);@@ -189,11 +220,16 @@ describe.each(cases.map(c => [label(c), c] as const))('%s', (_label, c) => {if (c.service !== 'redis') {it('keeps the stored credentials of a built-in save only when the bundled container already uses them', () => {arrange(c);- const env = saved(+ const payload =c.service === 'database'? { database: { type: 'postgres', builtIn: true } }- : { storage: { type: 's3', builtIn: true } },- );+ : { storage: { type: 's3', builtIn: true } };+ if (blankProjectDatabaseHost) {+ expect(() => saved(payload)).toThrow(/DATABASE_HOST is required/);+ expect(fs.writeFileSync).not.toHaveBeenCalled();+ return;+ }+ const env = saved(payload);const keep = c.position === 'pinned' || reached;if (c.service === 'database') expect(env.DATABASE_PASSWORD).toBe(keep ? 'StoredPw789!' : 'openwa');else@@ -206,11 +242,16 @@ describe.each(cases.map(c => [label(c), c] as const))('%s', (_label, c) => {if (c.service !== 'redis') {it('keeps the stored user, database and schema, or bucket and region, of a built-in save only when the bundled container already serves them', () => {arrange(c, STORED_VALUES);- const env = saved(+ const payload =c.service === 'database'? { database: { type: 'postgres', builtIn: true } }- : { storage: { type: 's3', builtIn: true } },- );+ : { storage: { type: 's3', builtIn: true } };+ if (blankProjectDatabaseHost) {+ expect(() => saved(payload)).toThrow(/DATABASE_HOST is required/);+ expect(fs.writeFileSync).not.toHaveBeenCalled();+ return;+ }+ const env = saved(payload);if (c.service === 'database')expect([env.DATABASE_USERNAME, env.DATABASE_NAME, env.POSTGRES_SCHEMA]).toEqual(reached ? ['app', 'appdb', 'tenant'] : ['openwa', 'openwa', 'public'],@@ -227,6 +268,11 @@ describe.each(cases.map(c => [label(c), c] as const))('%s', (_label, c) => {: c.service === 'redis'? { redis: { enabled: true, host: c.host, port: '6379' }, queue: { enabled: false } }: { storage: { type: 's3', s3Endpoint: c.host, s3Region: 'us-east-1' } };+ if (blankProjectDatabaseHost) {+ expect(() => saved(section)).toThrow(/DATABASE_HOST is required/);+ expect(fs.writeFileSync).not.toHaveBeenCalled();+ return;+ }const env = saved(section);expect(env[spec.flag]).toBe(c.flag === 'absent' ? undefined : c.flag);const sentHost = c.service === 'storage' ? c.host || undefined : c.host.trim() || 'localhost';@@ -234,3 +280,18 @@ describe.each(cases.map(c => [label(c), c] as const))('%s', (_label, c) => {expect(env[spec.host]).toBe(storedBundled ? spec.bundledHost : sentHost);});});++it.each(['', ' \t ', '\r'])('lets a blank OS database host %j use the valid generated host', blank => {+ arrange({ service: 'database', host: blank, reach: false, position: 'pinned', flag: 'false' });+ const hostEnvironment: NodeJS.ProcessEnv = { ...SECRETS, DATABASE_HOST: blank };+ clearBlankEnv(hostEnvironment, BLANK_SHADOWED_ENV_KEYS);+ delete process.env.DATABASE_HOST;+ Object.assign(process.env, hostEnvironment);+ recordOsEnvKeys(hostEnvironment);+ recordPinnedEnvKeys(hostEnvironment);++ expect(isEnvPinned('DATABASE_HOST')).toBe(false);+ const env = saved({ queue: { enabled: false } });+ expect(env.DATABASE_HOST).toBe('postgres');+ expect(env.QUEUE_ENABLED).toBe('false');+});diff --git a/src/modules/infra/infra-config.controller.spec.ts b/src/modules/infra/infra-config.controller.spec.tsindex 294963375..ed2f277b6 100644--- a/src/modules/infra/infra-config.controller.spec.ts+++ b/src/modules/infra/infra-config.controller.spec.ts@@ -69,11 +69,26 @@ const hostEnvSaved = HOST_ENV.map(k => [k, process.env[k]] as const);beforeAll(() => HOST_ENV.forEach(k => delete process.env[k]));afterAll(() => hostEnvSaved.forEach(([k, v]) => (process.env[k] = v)));+// These helpers exercise individual settings on an otherwise complete PostgreSQL configuration.+function completeDatabaseFixture(config: unknown, existing = ''): SaveConfigDto {+ const payload = config as SaveConfigDto;+ if (payload.database?.type !== 'postgres' || payload.database.builtIn === true) return payload;+ const saved = jest.requireActual<typeof import('dotenv')>('dotenv').parse(existing);+ return {+ ...payload,+ database: {+ ...(!saved.DATABASE_HOST && !process.env.DATABASE_HOST ? { host: 'localhost' } : {}),+ ...(!saved.DATABASE_USERNAME && !process.env.DATABASE_USERNAME ? { username: 'postgres' } : {}),+ ...payload.database,+ },+ };+}+describe('InfraConfigController.saveConfig SSL reject-unauthorized', () => {function writtenEnv(config: unknown): string {const spy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);const controller = new InfraConfigController({} as never, {} as never, {} as never);- controller.saveConfig(config as never);+ controller.saveConfig(completeDatabaseFixture(config));const content = spy.mock.calls[0][1] as string;spy.mockRestore();return content;@@ -272,7 +287,7 @@ describe('InfraConfigController PostgreSQL schema (POSTGRES_SCHEMA)', () => {(fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);(fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');(fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(config as never);+ newController().saveConfig(completeDatabaseFixture(config, existing));const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];(fs.existsSync as jest.Mock).mockReturnValue(false);(fs.readFileSync as jest.Mock).mockReturnValue('');@@ -345,7 +360,9 @@ describe('InfraConfigController.saveConfig writes the generated env owner-only',it('persists data/.env.generated with mode 0600, not world-readable', () => {const writeSpy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => undefined);const controller = new InfraConfigController({} as never, {} as never, {} as never);- controller.saveConfig({ database: { type: 'postgres', sslEnabled: true, password: 'pw' } } as never);+ controller.saveConfig({+ database: { type: 'postgres', host: 'db', username: 'app', sslEnabled: true, password: 'pw' },+ } as never);const opts = writeSpy.mock.calls[0][2];expect(opts).toEqual({ mode: 0o600 });writeSpy.mockRestore();@@ -359,7 +376,7 @@ describe('InfraConfigController.saveConfig env-name correctness and merge (#226)(fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);(fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');(fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(config as never);+ newController().saveConfig(completeDatabaseFixture(config, existing));const calls = (fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>;const content = calls[0][1];// Reset to defaults so later tests start from "no prior config".@@ -475,7 +492,9 @@ describe('InfraConfigController.saveConfig writes values the next boot reads bacfunction savedPassword(password: string): { line: string | undefined; parsed: string | undefined } {(fs.existsSync as jest.Mock).mockReturnValue(false);(fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig({ database: { type: 'postgres', builtIn: false, host: 'db', password } } as never);+ newController().saveConfig({+ database: { type: 'postgres', builtIn: false, host: 'db', username: 'app', password },+ } as never);const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];return {line: content.split('\n').find(l => l.startsWith('DATABASE_PASSWORD=')),@@ -502,7 +521,7 @@ describe('InfraConfigController.saveConfig writes values the next boot reads bac(fs.existsSync as jest.Mock).mockReturnValue(false);(fs.writeFileSync as jest.Mock).mockClear();newController().saveConfig({- database: { type: 'postgres', builtIn: false, host: 'db', password: databasePassword },+ database: { type: 'postgres', builtIn: false, host: 'db', username: 'app', password: databasePassword },redis: { enabled: true, builtIn: false, host: 'cache', password: redisPassword },} as never);return ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];@@ -549,7 +568,7 @@ describe('InfraConfigController.saveConfig engine selection (persist ENGINE_TYPE(fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);(fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');(fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(config as never);+ newController().saveConfig(completeDatabaseFixture(config, existing));const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];(fs.existsSync as jest.Mock).mockReturnValue(false);(fs.readFileSync as jest.Mock).mockReturnValue('');@@ -832,7 +851,7 @@ describe('InfraConfigController.saveConfig per-key merge (partial payloads)', ()(fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);(fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');(fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(config as never);+ newController().saveConfig(completeDatabaseFixture(config, existing));const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];(fs.existsSync as jest.Mock).mockReturnValue(false);(fs.readFileSync as jest.Mock).mockReturnValue('');@@ -974,7 +993,7 @@ describe('InfraConfigController.saveConfig per-key merge (partial payloads)', ()});it('keeps a stored PostgreSQL and S3 choice and their settings under the opposite pins', () => {- pin({ DATABASE_TYPE: 'sqlite', STORAGE_TYPE: 'local' });+ pin({ DATABASE_TYPE: 'sqlite', DATABASE_NAME: './data/pinned.sqlite', STORAGE_TYPE: 'local' });const env = written({@@ -996,6 +1015,8 @@ describe('InfraConfigController.saveConfig per-key merge (partial payloads)', ()it('keeps a stored SQLite and local choice under the opposite pins, with no bundled container', () => {pin({DATABASE_TYPE: 'postgres',+ DATABASE_HOST: 'db.pinned.example',+ DATABASE_USERNAME: 'app',DATABASE_PASSWORD: 'Str0ng!Passw0rd',STORAGE_TYPE: 's3',S3_ACCESS_KEY_ID: 'ak-strong',@@ -1018,6 +1039,8 @@ describe('InfraConfigController.saveConfig per-key merge (partial payloads)', ()it('follows a pinned type without writing it when nothing is stored', () => {pin({DATABASE_TYPE: 'postgres',+ DATABASE_HOST: 'db.pinned.example',+ DATABASE_USERNAME: 'app',DATABASE_PASSWORD: 'Str0ng!Passw0rd',STORAGE_TYPE: 's3',S3_ACCESS_KEY_ID: 'ak-strong',@@ -1292,7 +1315,7 @@ describe('InfraConfigController.saveConfig built-in/external mode flips and the(fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);(fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');(fs.writeFileSync as jest.Mock).mockClear();- newController().saveConfig(config as never);+ newController().saveConfig(completeDatabaseFixture(config, existing));const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];(fs.existsSync as jest.Mock).mockReturnValue(false);(fs.readFileSync as jest.Mock).mockReturnValue('');@@ -1896,15 +1919,26 @@ describe('InfraConfigController.saveConfig built-in/external mode flips and the];const switchBack = (running: Record<string, string>) => {Object.assign(process.env, running);- const env = jest- .requireActual<typeof import('dotenv')>('dotenv')- .parse(- written(- { database: { type: 'postgres', builtIn: true }, storage: { type: 's3', builtIn: true } },- SWITCHED,- ),- );- return Object.fromEntries(KEYS.map(key => [key, env[key]]));+ // These runtime values came from the generated file, so they are not host overrides of the new save.+ const precedence =+ jest.requireActual<typeof import('../../config/env-precedence')>('../../config/env-precedence');+ const wasOsProvided = precedence.isOsProvidedEnv;+ const source = jest+ .spyOn(precedence, 'isOsProvidedEnv')+ .mockImplementation(key => !Object.prototype.hasOwnProperty.call(running, key) && wasOsProvided(key));+ try {+ const env = jest+ .requireActual<typeof import('dotenv')>('dotenv')+ .parse(+ written(+ { database: { type: 'postgres', builtIn: true }, storage: { type: 's3', builtIn: true } },+ SWITCHED,+ ),+ );+ return Object.fromEntries(KEYS.map(key => [key, env[key]]));+ } finally {+ source.mockRestore();+ }};// Nothing is pinned: the running process holds the values its boot loaded from the file.afterEach(() => {@@ -1957,7 +1991,12 @@ describe('InfraConfigController.saveConfig built-in/external mode flips and the});it('writes the bundled ones while the running process uses SQLite and local storage', () => {- const env = switchBack({ ...RUNNING, DATABASE_TYPE: 'sqlite', STORAGE_TYPE: 'local' });+ const env = switchBack({+ ...RUNNING,+ DATABASE_TYPE: 'sqlite',+ DATABASE_NAME: './data/running.sqlite',+ STORAGE_TYPE: 'local',+ });expect([env.DATABASE_NAME, env.DATABASE_PASSWORD, env.S3_BUCKET, env.S3_ACCESS_KEY_ID]).toEqual(['openwa','openwa',@@ -2177,6 +2216,7 @@ describe('InfraConfigController.saveConfig persists strictly-coerced form booleatype: 'postgres',builtIn: 'false',host: 'db.example.com',+ username: 'app',password: 'unit-test-pw',sslEnabled: 'true',sslRejectUnauthorized: 'false',@@ -2772,7 +2812,7 @@ describe('InfraConfigController.requestRestart constrains teardown to managed pr] as const)('%s switched off from the page', (service, payload) => {it('is stopped by the restart that follows the save', async () => {const saved = [- 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_PASSWORD=openwa',+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=true\nDATABASE_HOST=postgres\nDATABASE_USERNAME=openwa\nDATABASE_PASSWORD=openwa','REDIS_ENABLED=true\nREDIS_BUILTIN=true\nREDIS_HOST=redis\nREDIS_PORT=6379\nQUEUE_ENABLED=true','STORAGE_TYPE=s3\nMINIO_BUILTIN=true\nS3_ENDPOINT=http://minio:9000\nS3_ACCESS_KEY_ID=minioadmin','S3_SECRET_ACCESS_KEY=minioadmin\n',@@ -2931,7 +2971,9 @@ describe('InfraConfigController audit trail (light-dependency handlers)', () =>it('saveConfig emits INFRA_CONFIG_SAVED without leaking secret values into the metadata', () => {const audit = makeAudit();- build(audit).saveConfig({ database: { type: 'postgres', host: 'db', password: 'topsecret' } } as never);+ build(audit).saveConfig({+ database: { type: 'postgres', host: 'db', username: 'app', password: 'topsecret' },+ } as never);expect(audit.logInfo).toHaveBeenCalledTimes(1);const calls = audit.logInfo.mock.calls as Array<[AuditAction, { metadata: { sections: string[] } }]>;const [action, ctx] = calls[0];diff --git a/src/modules/infra/infra-config.controller.ts b/src/modules/infra/infra-config.controller.tsindex b77c1cf29..1826bfd49 100644--- a/src/modules/infra/infra-config.controller.ts+++ b/src/modules/infra/infra-config.controller.ts@@ -30,6 +30,7 @@ import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { SaveConfigDto } from './dto/save-config.dto';import { assertNoDefaultSecretsInProduction } from '../../config/bootstrap-security';+import { validateEnv } from '../../config/env.validation';import { BLANK_SHADOWED_ENV_KEYS, isEnvPinned, isOsProvidedEnv } from '../../config/env-precedence';import { resolveStorageRoot } from '../../config/storage-root';import { randomUUID } from 'crypto';@@ -212,6 +213,7 @@ export class InfraConfigController {this.assertNoLineBreakValues(updates);const merged = this.mergeWithExisting(existing, ctx);this.assertProductionBootable(merged);+ this.assertBootValidates(merged);this.assertStorageRootWritable(updates, merged);this.persistGeneratedEnv(envPath, merged);this.auditConfigSaved(config, profiles);@@ -347,6 +349,19 @@ export class InfraConfigController {}}+ // The environment validation the next boot runs (env.validation.ts), applied to the same view of the merged result.+ // Without it a save the dashboard accepts, a PostgreSQL selection with no host or a pool size that is not a plain+ // integer, crash-loops the instance and the dashboard that could undo it.+ private assertBootValidates(merged: Record<string, string>): void {+ const bootValue = this.bootValueReader(merged);+ try {+ validateEnv(Object.fromEntries(Object.keys({ ...process.env, ...merged }).map(key => [key, bootValue(key)])));+ } catch (error) {+ const detail = error instanceof Error ? error.message : String(error);+ throw new BadRequestException(`Refusing to save a configuration that fails boot validation. ${detail}`);+ }+ }+// A storage path the app cannot create or write is refused by the next boot before Nest builds, which// crash-loops the instance with the dashboard that could undo the save down. Only a path this save// names is judged, and only when the boot will read it: a value the host or the project .env pinsdiff --git a/src/modules/infra/infra-config.persistence.spec.ts b/src/modules/infra/infra-config.persistence.spec.tsindex cdbdbb24f..c172a142b 100644--- a/src/modules/infra/infra-config.persistence.spec.ts+++ b/src/modules/infra/infra-config.persistence.spec.ts@@ -1,7 +1,7 @@import * as fs from 'fs';import * as os from 'os';import * as path from 'path';-import { ValidationPipe } from '@nestjs/common';+import { BadRequestException, ValidationPipe } from '@nestjs/common';import { GLOBAL_VALIDATION_OPTIONS } from '../../config/app-validation';import { recordOsEnvKeys, recordPinnedEnvKeys } from '../../config/env-precedence';import { SaveConfigDto } from './dto/save-config.dto';@@ -138,3 +138,44 @@ it('creates and replaces the overlay owner-only', async () => {if (process.platform !== 'win32') expect(actualFs.statSync(file).mode & 0o777).toBe(0o600);expect(dotenv.parse(actualFs.readFileSync(file)).PUPPETEER_HEADLESS).toBe('true');});++const invalidBootCases: Array<{+ name: string;+ stored: Record<string, string>;+ pins: Record<string, string>;+ body: unknown;+}> = [+ {+ name: 'missing PostgreSQL host and user',+ stored: {},+ pins: {},+ body: { database: { type: 'postgres', password: 'DummyPassword123456' } },+ },+ {+ name: 'a PostgreSQL bare name under a SQLite type pin',+ stored: {},+ pins: { DATABASE_TYPE: 'sqlite' },+ body: { database: { type: 'postgres', builtIn: true } },+ },+ { name: 'an exponent-form pool size', stored: database, pins: {}, body: { database: { poolSize: 1e21 } } },+];+for (const example of invalidBootCases) {+ it(`refuses ${example.name} before persisting`, async () => {+ seed(example.stored);+ Object.assign(process.env, example.pins);+ recordPinnedEnvKeys(example.pins);+ const before = actualFs.readFileSync(file);+ const input = await admitted(example.body, SaveConfigDto);+ expect(() => build().controller.saveConfig(input)).toThrow(BadRequestException);+ expect(actualFs.readFileSync(file)).toEqual(before);+ expect(actualFs.readdirSync(path.dirname(file))).toEqual(['.env.generated']);+ });+}++it('accepts a valid partial PostgreSQL change and preserves an absent pool value', async () => {+ seed({ ...database, DATABASE_POOL_SIZE: '17' });+ expect((await save({ database: { poolSize: null } })).saved).toBe(true);+ expect(dotenv.parse(actualFs.readFileSync(file)).DATABASE_POOL_SIZE).toBe('17');+ expect((await save({ database: { poolSize: 18 } })).saved).toBe(true);+ expect(dotenv.parse(actualFs.readFileSync(file)).DATABASE_POOL_SIZE).toBe('18');+});