Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): write nothing of a section pinned to the other selection
Yudhi Armyndharis47323114bc19
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex da3dd03d7..444c53854 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5676,7 +5676,7 @@ Merge-save infrastructure config to `data/.env.generated` (a `0600` secret file)| Field | Type | Required | Constraints | Description || ----------------------------------------------------- | ------------------------ | ------------------------ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || `database` | object | No | — | DB section (see nested) |-| `database.type` | `'sqlite' \| 'postgres'` | If none stored or pinned | enum | `sqlite` drops stale postgres keys; `postgres` writes connection keys. Absent keeps the stored selection (else the one the environment pins) and writes none |+| `database.type` | `'sqlite' \| 'postgres'` | If none stored or pinned | enum | `sqlite` drops stale postgres keys; `postgres` writes connection keys. Absent keeps the stored selection (else the pinned one); a pin of the other skips the section || `database.builtIn` | boolean | No | — | When `true`+postgres, pins host `postgres`, port `5432`, user and database `openwa` and schema `public`, and pushes the `postgres` Docker profile || `database.host` / `.port` / `.username` / `.database` | string | No | `port` is a string | External postgres connection (defaults `localhost`/`5432`/`postgres`/`openwa`) || `database.schema` | string | No | lower-case, no `pg_` prefix (else 400) | Postgres schema, saved as `POSTGRES_SCHEMA`; an empty value writes `public` (also forced to `public` when switching to the built-in DB) |@@ -5688,7 +5688,7 @@ Merge-save infrastructure config to `data/.env.generated` (a `0600` secret file)| `redis.host` / `.port` | string | No | `port` is a string | Defaults `localhost`/`6379` || `redis.password` | string | No | secret | Empty keeps existing || `queue.enabled` | boolean | No | — | Writes `QUEUE_ENABLED` |-| `storage.type` | `'local' \| 's3'` | If none stored or pinned | enum | `local` drops stale S3 keys; `s3` drops `STORAGE_LOCAL_PATH`. Absent keeps the stored selection (else the one the environment pins) and writes none |+| `storage.type` | `'local' \| 's3'` | If none stored or pinned | enum | `local` drops stale S3 keys; `s3` drops `STORAGE_LOCAL_PATH`. Absent keeps the stored selection (else the pinned one); a pin of the other skips the section || `storage.builtIn` | boolean | No | — | `true`+s3 uses bundled MinIO defaults + pushes `minio` profile || `storage.localPath` | string | No | — | Default `./data/media` || `storage.s3Bucket` / `.s3Region` / `.s3Endpoint` | string | No | — | External S3 |diff --git a/openapi.json b/openapi.jsonindex 0f005157d..ba6b89c25 100644--- a/openapi.json+++ b/openapi.json@@ -22478,7 +22478,7 @@"sqlite","postgres"],- "description": "Absent keeps the stored selection, which the rest of the section then applies to."+ "description": "Absent keeps the stored selection, which the rest of the section then applies to. While the environment pins another selection than the stored one, a section without it writes nothing."},"builtIn": {"type": "boolean"@@ -22549,7 +22549,7 @@"local","s3"],- "description": "Absent keeps the stored selection, which the rest of the section then applies to."+ "description": "Absent keeps the stored selection, which the rest of the section then applies to. While the environment pins another selection than the stored one, a section without it writes nothing."},"builtIn": {"type": "boolean"diff --git a/src/modules/infra/config-sections.ts b/src/modules/infra/config-sections.tsindex b122ced77..d14cc4414 100644--- a/src/modules/infra/config-sections.ts+++ b/src/modules/infra/config-sections.ts@@ -33,21 +33,27 @@ function portValue(label: string, value: string): string {}// The selection a section applies to: the one sent, else the stored one, else the one the environment pins. Only a-// sent one is written, so a save that leaves it out (the page does for a type the environment pins) never writes a-// selection over the stored choice. With none of the three the section cannot be read, and is refused.+// sent one is written, so a save that leaves it out (the page does for a pinned type in a card left untouched) never+// writes a selection over the stored choice. When the environment pins another selection than the stored one, the+// section's fields belong to neither boot: applied to the stored mode they reach the pinned boot now (a PostgreSQL+// DATABASE_NAME refuses a SQLite boot), applied to the pinned mode they reach the stored one once the pin is+// removed. Nothing of the section is written then (null). With no selection at all it cannot be read, and is refused.function sectionType<T extends string>(section: string,key: string,sent: T | undefined,existing: Record<string, string>,allowed: readonly T[],-): T {- const type =- sent ?? [existing[key], isEnvPinned(key) ? process.env[key] : undefined].find(v => allowed.includes(v as T));+): T | null {+ if (sent) return sent;+ const stored = allowed.find(v => v === existing[key]);+ const pinned = isEnvPinned(key) ? allowed.find(v => v === process.env[key]) : undefined;+ if (stored && pinned && stored !== pinned) return null;+ const type = stored ?? pinned;if (type === undefined) {throw new BadRequestException(`${section}.type must be one of the following values: ${allowed.join(', ')}`);}- return type as T;+ return type;}// Database. NOTE: these keys must match what src/config/configuration.ts reads.@@ -58,6 +64,7 @@ export function applyDatabaseSection(): void {const { updates, staleKeys, profiles } = ctx;const type = sectionType('database', 'DATABASE_TYPE', database.type, existing, ['sqlite', 'postgres']);+ if (type === null) return;if (database.type) updates.DATABASE_TYPE = database.type;if (database.builtIn !== undefined) {updates.POSTGRES_BUILTIN = database.builtIn ? 'true' : 'false';@@ -195,6 +202,7 @@ export function applyStorageSection(): void {const { updates, staleKeys, profiles } = ctx;const type = sectionType('storage', 'STORAGE_TYPE', storage.type, existing, ['local', 's3']);+ if (type === null) return;if (storage.type) updates.STORAGE_TYPE = storage.type;if (storage.builtIn !== undefined) {updates.MINIO_BUILTIN = storage.builtIn ? 'true' : 'false';diff --git a/src/modules/infra/dto/save-config.dto.ts b/src/modules/infra/dto/save-config.dto.tsindex cbce01a9e..0280c2dbd 100644--- a/src/modules/infra/dto/save-config.dto.ts+++ b/src/modules/infra/dto/save-config.dto.ts@@ -18,7 +18,9 @@ import { ToStrictBoolean, ToStrictNumber, ToStrictString } from '../../../commonexport class DatabaseConfigDto {@ApiPropertyOptional({enum: ['sqlite', 'postgres'],- description: 'Absent keeps the stored selection, which the rest of the section then applies to.',+ description:+ 'Absent keeps the stored selection, which the rest of the section then applies to. While the environment pins ' ++ 'another selection than the stored one, a section without it writes nothing.',})@IsOptional()@IsIn(['sqlite', 'postgres'])@@ -128,7 +130,9 @@ export class QueueConfigDto {export class StorageConfigDto {@ApiPropertyOptional({enum: ['local', 's3'],- description: 'Absent keeps the stored selection, which the rest of the section then applies to.',+ description:+ 'Absent keeps the stored selection, which the rest of the section then applies to. While the environment pins ' ++ 'another selection than the stored one, a section without it writes nothing.',})@IsOptional()@IsIn(['local', 's3'])diff --git a/src/modules/infra/infra-config.controller.spec.ts b/src/modules/infra/infra-config.controller.spec.tsindex 9cafa8da7..36138eb6a 100644--- a/src/modules/infra/infra-config.controller.spec.ts+++ b/src/modules/infra/infra-config.controller.spec.ts@@ -34,6 +34,7 @@ import { SaveConfigDto } from './dto/save-config.dto';import { AuditAction } from '../audit/entities/audit-log.entity';import { recordOsEnvKeys, recordPinnedEnvKeys } from '../../config/env-precedence';import { resolveStorageRoot } from '../../config/storage-root';+import { validateEnv } from '../../config/env.validation';import {EXPECTED_MODE,FILE_STATES,@@ -852,6 +853,26 @@ describe('InfraConfigController.saveConfig per-key merge (partial payloads)', ()recordPinnedEnvKeys({});});+ // The page sends every field of a card, seeded with defaults for keys nothing stores. Applied to the stored+ // PostgreSQL while SQLite is pinned, that writes DATABASE_NAME=openwa, a bare name the pinned SQLite boot refuses.+ it('writes nothing of a section whose pinned selection differs from the stored one', () => {+ pin({ DATABASE_TYPE: 'sqlite', STORAGE_TYPE: 'local' });+ const stored = STORED_EXTERNAL.replace('DATABASE_NAME=appdb\n', '');++ const env = written(+ {+ database: { builtIn: false, host: 'db.example.com', port: '5432', database: 'openwa', poolSize: 10 },+ storage: { builtIn: false, localPath: './data/media', s3Region: 'ap-southeast-1' },+ },+ stored,+ );++ expect(env).not.toMatch(/^(DATABASE_NAME|DATABASE_PORT|DATABASE_POOL_SIZE|S3_REGION|STORAGE_LOCAL_PATH)=/m);+ for (const line of stored.trim().split('\n')) expect(env).toContain(line);+ const parsed = jest.requireActual<typeof import('dotenv')>('dotenv').parse(env);+ expect(() => validateEnv({ ...parsed, DATABASE_TYPE: 'sqlite', STORAGE_TYPE: 'local' })).not.toThrow();+ });+it('keeps a stored PostgreSQL and S3 choice and their settings under the opposite pins', () => {pin({ DATABASE_TYPE: 'sqlite', STORAGE_TYPE: 'local' });@@ -926,6 +947,25 @@ describe('InfraConfigController.saveConfig per-key merge (partial payloads)', ()expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();});+ it('applies a section whose pinned selection is the stored one', () => {+ pin({ DATABASE_TYPE: 'postgres', STORAGE_TYPE: 's3' });++ const env = written({ database: { poolSize: 25 }, storage: { s3Bucket: 'media-2' } }, STORED_EXTERNAL);++ expect(env).toContain('DATABASE_POOL_SIZE=25');+ expect(env).toContain('S3_BUCKET=media-2');+ });++ it('applies a section to the stored selection when nothing pins one', () => {+ const env = written(+ { database: { host: 'db.example.com' }, storage: { localPath: './data/media-2' } },+ 'DATABASE_TYPE=sqlite\nPOSTGRES_BUILTIN=false\nSTORAGE_TYPE=local\nSTORAGE_LOCAL_PATH=./data/media\n',+ );++ expect(env).toContain('STORAGE_LOCAL_PATH=./data/media-2');+ expect(env).not.toMatch(/^DATABASE_HOST=/m);+ });+it('still writes a type that is sent', () => {pin({ DATABASE_TYPE: 'sqlite', STORAGE_TYPE: 'local' });