Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): keep a stored selection that the environment pins

Yudhi Armyndharis751ab4590c78
diff --git a/dashboard/src/hooks/useInfraConfigForm.test.ts b/dashboard/src/hooks/useInfraConfigForm.test.ts
index 716565bef..e692c9a5c 100644
--- a/dashboard/src/hooks/useInfraConfigForm.test.ts
+++ b/dashboard/src/hooks/useInfraConfigForm.test.ts
@@ -315,3 +315,43 @@ test('a stored pool size outside the field range is saved as stored', () => {
assert.equal(result.current.buildSavePayload().database?.poolSize, 100);
});
+
+// /config reports a pinned selection as the effective value, so the form shows the pin. Sending it back would write the
+// pin over the stored choice and drop the stored settings of the other mode; untouched, it is left out.
+const PINNED_SELECTIONS: InfraStatus = { ...RUNNING, envPinned: ['DATABASE_TYPE', 'STORAGE_TYPE', 'REDIS_ENABLED'] };
+
+test('a selection the environment pins is left out of a save until the operator changes it', () => {
+ const { result } = renderForm({ status: PINNED_SELECTIONS, saved: SAVED });
+
+ const { database, redis, storage } = result.current.buildSavePayload();
+
+ assert.deepEqual([database?.type, redis?.enabled, storage?.type], [undefined, undefined, undefined]);
+ // The rest of each section still goes out.
+ assert.deepEqual([database?.host, redis?.host, storage?.s3Bucket], ['pg.internal', 'redis.internal', 'media']);
+});
+
+test('a pinned selection the operator changes is sent, and an unpinned one always is', () => {
+ const { result } = renderForm({ status: PINNED_SELECTIONS, saved: SAVED });
+
+ rtl.act(() => {
+ result.current.updateDbConfig('type', 'sqlite');
+ result.current.updateStorageConfig('type', 'local');
+ result.current.setRedisEnabled(false);
+ });
+ const changed = result.current.buildSavePayload();
+ assert.deepEqual([changed.database?.type, changed.redis?.enabled, changed.storage?.type], ['sqlite', false, 'local']);
+
+ const unpinned = renderForm({ status: RUNNING, saved: SAVED }).result.current.buildSavePayload();
+ assert.deepEqual(
+ [unpinned.database?.type, unpinned.redis?.enabled, unpinned.storage?.type],
+ ['postgres', true, 's3'],
+ );
+});
+
+test('one pinned selection is left out without the others', () => {
+ const { result } = renderForm({ status: { ...RUNNING, envPinned: ['STORAGE_TYPE'] }, saved: SAVED });
+
+ const { database, redis, storage } = result.current.buildSavePayload();
+
+ assert.deepEqual([database?.type, redis?.enabled, storage?.type], ['postgres', true, undefined]);
+});
diff --git a/dashboard/src/hooks/useInfraConfigForm.ts b/dashboard/src/hooks/useInfraConfigForm.ts
index de710106d..de62592cf 100644
--- a/dashboard/src/hooks/useInfraConfigForm.ts
+++ b/dashboard/src/hooks/useInfraConfigForm.ts
@@ -137,6 +137,11 @@ export function useInfraConfigForm(
// their selection (#735).
const engineHydrated = useRef(false);
const engineTouched = useRef(false);
+ // The database type, storage type and Redis switch the operator has changed here. Until then a value the
+ // environment pins is the pin, not a choice, and a save leaves it out (see buildSavePayload).
+ const dbTypeTouched = useRef(false);
+ const storageTypeTouched = useRef(false);
+ const redisEnabledTouched = useRef(false);
/** Whether engineConfig.type reflects a real value (seeded from the saved config or user-picked)
* rather than the useState default — the save payload omits `type` when it doesn't. */
@@ -211,12 +216,16 @@ export function useInfraConfigForm(
setEngineConfig(prev => (prev.type === seed ? prev : { ...prev, type: seed }));
}, [savedConfig]);
- const updateDbConfig = (key: keyof DatabaseConfig, value: string | number | boolean) =>
+ const updateDbConfig = (key: keyof DatabaseConfig, value: string | number | boolean) => {
+ if (key === 'type') dbTypeTouched.current = true;
setDbConfig(prev => ({ ...prev, [key]: value }));
+ };
const updateRedisConfig = (key: keyof RedisConfig, value: string | boolean) =>
setRedisConfig(prev => ({ ...prev, [key]: value }));
- const updateStorageConfig = (key: keyof StorageConfig, value: string | boolean) =>
+ const updateStorageConfig = (key: keyof StorageConfig, value: string | boolean) => {
+ if (key === 'type') storageTypeTouched.current = true;
setStorageConfig(prev => ({ ...prev, [key]: value }));
+ };
const updateEngineConfig = (key: keyof EngineConfig, value: string | boolean) => {
if (key === 'type') engineTouched.current = true;
setEngineConfig(prev => ({ ...prev, [key]: value }));
@@ -224,32 +233,44 @@ export function useInfraConfigForm(
// Disabling Redis also disables the queue, since queue processing depends on it.
const setRedisEnabled = (enabled: boolean) => {
+ redisEnabledTouched.current = true;
setRedisEnabledState(enabled);
if (!enabled) setQueueEnabled(false);
};
const setRedisConnected = (connected: boolean) => setRedisConfig(prev => ({ ...prev, connected }));
+ // /config reports the EFFECTIVE selection, so under a pin the form shows the pinned value. Sending it back would
+ // write the pin into data/.env.generated over the stored choice, which unsetting the variable was supposed to
+ // reveal (#1082), and drop the stored settings of the mode it replaces. Untouched, it is left out, and the
+ // gateway keeps the stored selection. Read at save time, like the engine pin below.
+ const pinnedSeed = (key: string, touched: { current: boolean }) =>
+ !touched.current && !!infraStatus?.envPinned?.includes(key);
+
const buildSavePayload = (): SaveConfigPayload => ({
// A bundled container never receives a typed password (the field is hidden once built-in is on,
// but a value typed before the toggle survives in state). '' means "unchanged" on the backend.
// An emptied pool size is NaN, which JSON writes as null and the backend refuses: leave it out.
database: {
...dbConfig,
+ type: pinnedSeed('DATABASE_TYPE', dbTypeTouched) ? undefined : dbConfig.type,
password: dbConfig.builtIn ? '' : dbConfig.password,
poolSize: Number.isInteger(dbConfig.poolSize) ? dbConfig.poolSize : undefined,
},
// `connected` is runtime-only status, not persisted configuration. Keep it out of the
// whitelisted backend DTO so a valid dashboard save cannot be rejected as an unknown field.
redis: {
- enabled: redisEnabled,
+ enabled: pinnedSeed('REDIS_ENABLED', redisEnabledTouched) ? undefined : redisEnabled,
builtIn: redisConfig.builtIn,
host: redisConfig.host,
port: redisConfig.port,
password: redisConfig.builtIn ? '' : redisConfig.password,
},
queue: { enabled: queueEnabled },
- storage: { ...storageConfig },
+ storage: {
+ ...storageConfig,
+ type: pinnedSeed('STORAGE_TYPE', storageTypeTouched) ? undefined : storageConfig.type,
+ },
// Only send `type` once we actually know it — either the radio seeded from /config or the
// operator picked one. If /config never resolved, engineConfig.type still holds its useState
// default, and sending that would persist ENGINE_TYPE and silently flip the engine on the next
diff --git a/dashboard/src/pages/Infrastructure.test.ts b/dashboard/src/pages/Infrastructure.test.ts
index f298cd841..6d4e03fe6 100644
--- a/dashboard/src/pages/Infrastructure.test.ts
+++ b/dashboard/src/pages/Infrastructure.test.ts
@@ -1628,6 +1628,50 @@ test('the engine radio seeds from the effective engine when ENGINE_TYPE is pinne
);
});
+// The same for the database type, the storage type and the Redis switch: /config reports a pinned value as the
+// effective one, and sending it back would write the pin over the stored choice and drop that mode's settings.
+test('saving while the selections are pinned leaves them out so the stored choices survive', async () => {
+ const { screen, waitFor, fireEvent } = rtl;
+ resetFetchCalls();
+ overrides = { status: { ...INFRA_STATUS, envPinned: ['DATABASE_TYPE', 'REDIS_ENABLED', 'STORAGE_TYPE'] } };
+ const { container } = renderInfrastructure();
+
+ await screen.findByText('Database Configuration');
+ await awaitConfigHydrated(container);
+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));
+
+ await waitFor(() => assert.ok(findFetchCall('PUT', '/api/infra/config'), 'expected a PUT to /infra/config'));
+ const body = findFetchCall('PUT', '/api/infra/config')!.body as {
+ database: Record<string, unknown>;
+ redis: Record<string, unknown>;
+ storage: Record<string, unknown>;
+ };
+ assert.deepEqual(['type' in body.database, 'enabled' in body.redis, 'type' in body.storage], [false, false, false]);
+ assert.equal(body.database.username, 'openwa_admin', 'the rest of the section still goes out');
+});
+
+test('a pinned selection the operator changes is saved', async () => {
+ const { screen, waitFor, fireEvent } = rtl;
+ resetFetchCalls();
+ overrides = { status: { ...INFRA_STATUS, envPinned: ['DATABASE_TYPE', 'REDIS_ENABLED', 'STORAGE_TYPE'] } };
+ const { container } = renderInfrastructure();
+
+ await screen.findByText('Database Configuration');
+ await awaitConfigHydrated(container);
+ fireEvent.click(container.querySelectorAll<HTMLInputElement>('input[name="dbType"]')[0]);
+ fireEvent.click(container.querySelectorAll<HTMLInputElement>('input[name="storageType"]')[1]);
+ fireEvent.click(toggleInput(container, 'Enable Redis'));
+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));
+
+ await waitFor(() => assert.ok(findFetchCall('PUT', '/api/infra/config'), 'expected a PUT to /infra/config'));
+ const body = findFetchCall('PUT', '/api/infra/config')!.body as {
+ database: { type?: string };
+ redis: { enabled?: boolean };
+ storage: { type?: string };
+ };
+ assert.deepEqual([body.database.type, body.redis.enabled, body.storage.type], ['sqlite', true, 's3']);
+});
+
test('saving while ENGINE_TYPE is pinned omits engine.type so the stored choice survives', async () => {
const { screen, waitFor, fireEvent } = rtl;
resetFetchCalls();
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index aa856069d..de2d3abb8 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -696,7 +696,8 @@ export interface SavedConfig {
export interface SaveConfigPayload {
database?: {
- type: 'sqlite' | 'postgres';
+ // Absent keeps the stored selection; the form leaves out a type the environment pins.
+ type?: 'sqlite' | 'postgres';
builtIn?: boolean;
host?: string;
port?: string;
@@ -719,7 +720,7 @@ export interface SaveConfigPayload {
enabled?: boolean;
};
storage?: {
- type: 'local' | 's3';
+ type?: 'local' | 's3';
builtIn?: boolean;
localPath?: string;
s3Bucket?: string;
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 7a2682882..da3dd03d7 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 `database` is present | enum | `sqlite` drops stale postgres keys; `postgres` writes connection keys |
+| `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.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 `storage` is present | enum | `local` drops stale S3 keys; `s3` drops `STORAGE_LOCAL_PATH` |
+| `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.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 |
@@ -5745,7 +5745,7 @@ Merge-save infrastructure config to `data/.env.generated` (a `0600` secret file)
Write/IO errors are caught and returned as HTTP `200` with `{ "saved": false, "envPath": "", "profiles": [], "message": "Failed to save configuration: …" }`. DTO validation, an unknown engine type, an invalid `database.schema`, CR/LF injection, a value that cannot be stored so that it reads back unchanged, and a merged config the production boot guard would reject (an empty or default `DATABASE_PASSWORD` or S3 key on an external datastore, or a placeholder `REDIS_PASSWORD`; message starts `Refusing to save a configuration that would be rejected at production boot.`), and a local `storage.localPath` the app cannot create or write (message starts `Refusing to save the storage path`; the next start would refuse to boot on it, and a path pinned by the host environment or the project `.env` is not judged, as the boot never reads the submitted one) are real HTTP `400` responses, and nothing is written. `profiles` lists newly-required Docker profiles.
-**Errors:** `400` unknown/mistyped body field, missing nested `database.type`/`storage.type`, unknown
+**Errors:** `400` unknown/mistyped body field, a `database.type`/`storage.type` left out with none stored or pinned, unknown
`engine.type`, invalid `database.schema`, CR-LF in a value, a value that cannot round-trip through the
env file, a config the production boot secret guard would reject, or a local
`storage.localPath` the app cannot create or write · `401` · `403`
diff --git a/openapi.json b/openapi.json
index 20d67ecbc..0f005157d 100644
--- a/openapi.json
+++ b/openapi.json
@@ -22477,7 +22477,8 @@
"enum": [
"sqlite",
"postgres"
- ]
+ ],
+ "description": "Absent keeps the stored selection, which the rest of the section then applies to."
},
"builtIn": {
"type": "boolean"
@@ -22509,10 +22510,7 @@
"sslRejectUnauthorized": {
"type": "boolean"
}
- },
- "required": [
- "type"
- ]
+ }
},
"RedisConfigDto": {
"type": "object",
@@ -22550,7 +22548,8 @@
"enum": [
"local",
"s3"
- ]
+ ],
+ "description": "Absent keeps the stored selection, which the rest of the section then applies to."
},
"builtIn": {
"type": "boolean"
@@ -22573,10 +22572,7 @@
"s3Endpoint": {
"type": "string"
}
- },
- "required": [
- "type"
- ]
+ }
},
"EngineConfigDto": {
"type": "object",
diff --git a/src/modules/infra/config-sections.ts b/src/modules/infra/config-sections.ts
index 70a902fb9..9975faee7 100644
--- a/src/modules/infra/config-sections.ts
+++ b/src/modules/infra/config-sections.ts
@@ -32,6 +32,24 @@ function portValue(label: string, value: string): string {
return port;
}
+// 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.
+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));
+ if (type === undefined) {
+ throw new BadRequestException(`${section}.type must be one of the following values: ${allowed.join(', ')}`);
+ }
+ return type as T;
+}
+
// Database. NOTE: these keys must match what src/config/configuration.ts reads.
export function applyDatabaseSection(
database: DatabaseConfigDto,
@@ -39,7 +57,8 @@ export function applyDatabaseSection(
ctx: ConfigSectionContext,
): void {
const { updates, staleKeys, profiles } = ctx;
- updates.DATABASE_TYPE = database.type || 'sqlite';
+ const type = sectionType('database', 'DATABASE_TYPE', database.type, existing, ['sqlite', 'postgres']);
+ if (database.type) updates.DATABASE_TYPE = database.type;
if (database.builtIn !== undefined) {
updates.POSTGRES_BUILTIN = database.builtIn ? 'true' : 'false';
}
@@ -47,7 +66,7 @@ export function applyDatabaseSection(
// is inherited so a partial payload stays in the current mode instead of silently
// flipping to external.
const dbBuiltIn = database.builtIn ?? existing.POSTGRES_BUILTIN === 'true';
- if (database.type === 'postgres') {
+ if (type === 'postgres') {
if (dbBuiltIn) {
// Built-in PostgreSQL - use container name as host
updates.DATABASE_HOST = 'postgres';
@@ -173,11 +192,12 @@ export function applyStorageSection(
ctx: ConfigSectionContext,
): void {
const { updates, staleKeys, profiles } = ctx;
- updates.STORAGE_TYPE = storage.type || 'local';
+ const type = sectionType('storage', 'STORAGE_TYPE', storage.type, existing, ['local', 's3']);
+ if (storage.type) updates.STORAGE_TYPE = storage.type;
if (storage.builtIn !== undefined) {
updates.MINIO_BUILTIN = storage.builtIn ? 'true' : 'false';
}
- if (storage.type === 'local') {
+ if (type === 'local') {
// Switching to local: drop stale S3 keys, and reset the built-in flag with them —
// there is no bundled MinIO backing a local storage path.
updates.MINIO_BUILTIN = 'false';
@@ -188,7 +208,7 @@ export function applyStorageSection(
for (const k of ['S3_ENDPOINT', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY', 'S3_BUCKET', 'S3_REGION']) {
staleKeys.add(k);
}
- } else if (storage.type === 's3') {
+ } else {
staleKeys.add('STORAGE_LOCAL_PATH');
if (storage.builtIn === true) {
// Built-in MinIO - use container name as endpoint
diff --git a/src/modules/infra/dto/save-config.dto.spec.ts b/src/modules/infra/dto/save-config.dto.spec.ts
index 026b63e3e..31868677f 100644
--- a/src/modules/infra/dto/save-config.dto.spec.ts
+++ b/src/modules/infra/dto/save-config.dto.spec.ts
@@ -106,3 +106,20 @@ describe('SaveConfigDto sections refuse an array', () => {
},
);
});
+
+// A section without its type keeps the stored selection (applyDatabaseSection, applyStorageSection), so the page can
+// leave out a type the environment pins. A type that is sent is still held to the enum.
+describe('SaveConfigDto section types', () => {
+ it.each(['database', 'storage'])('%s may leave its type out', async section => {
+ const { errors } = await run({ [section]: { builtIn: false } });
+ expect(errors).toHaveLength(0);
+ });
+
+ it.each([
+ ['database', 'mysql'],
+ ['storage', 'ftp'],
+ ])('%s refuses a type outside the enum (%s)', async (section, type) => {
+ const { errors } = await run({ [section]: { type } });
+ expect(errors.map(e => e.property)).toEqual([section]);
+ });
+});
diff --git a/src/modules/infra/dto/save-config.dto.ts b/src/modules/infra/dto/save-config.dto.ts
index 95fe97b55..cbce01a9e 100644
--- a/src/modules/infra/dto/save-config.dto.ts
+++ b/src/modules/infra/dto/save-config.dto.ts
@@ -1,4 +1,4 @@
-import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
+import { ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsBoolean, IsIn, IsNumber, IsObject, IsOptional, IsString, ValidateNested } from 'class-validator';
import { ToStrictBoolean, ToStrictNumber, ToStrictString } from '../../../common/utils/strict-boolean';
@@ -16,9 +16,13 @@ import { ToStrictBoolean, ToStrictNumber, ToStrictString } from '../../../common
* are accepted; any other spelling is rejected 400.
*/
export class DatabaseConfigDto {
- @ApiProperty({ enum: ['sqlite', 'postgres'] })
+ @ApiPropertyOptional({
+ enum: ['sqlite', 'postgres'],
+ description: 'Absent keeps the stored selection, which the rest of the section then applies to.',
+ })
+ @IsOptional()
@IsIn(['sqlite', 'postgres'])
- type!: 'sqlite' | 'postgres';
+ type?: 'sqlite' | 'postgres';
@ApiPropertyOptional()
@ToStrictBoolean()
@@ -122,9 +126,13 @@ export class QueueConfigDto {
}
export class StorageConfigDto {
- @ApiProperty({ enum: ['local', 's3'] })
+ @ApiPropertyOptional({
+ enum: ['local', 's3'],
+ description: 'Absent keeps the stored selection, which the rest of the section then applies to.',
+ })
+ @IsOptional()
@IsIn(['local', 's3'])
- type!: 'local' | 's3';
+ type?: 'local' | 's3';
@ApiPropertyOptional()
@ToStrictBoolean()
diff --git a/src/modules/infra/infra-config.controller.spec.ts b/src/modules/infra/infra-config.controller.spec.ts
index 538e1e833..9b05d6214 100644
--- a/src/modules/infra/infra-config.controller.spec.ts
+++ b/src/modules/infra/infra-config.controller.spec.ts
@@ -830,6 +830,112 @@ describe('InfraConfigController.saveConfig per-key merge (partial payloads)', ()
expect(env).toContain('SESSION_DATA_PATH=./old-path');
expect(env).toContain('PUPPETEER_ARGS=--custom-flag');
});
+
+ // The page leaves out a type the environment pins while the operator has not touched it, so the pin is never
+ // written over the stored choice. The section then applies to the stored selection, and never rewrites it.
+ describe('a section without its type', () => {
+ const STORED_EXTERNAL =
+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=false\nDATABASE_HOST=db.example.com\nDATABASE_USERNAME=app\n' +
+ 'DATABASE_PASSWORD=Str0ng!Passw0rd\nDATABASE_NAME=appdb\nSTORAGE_TYPE=s3\nMINIO_BUILTIN=false\n' +
+ 'S3_ENDPOINT=https://s3.example.com\nS3_BUCKET=media\nS3_ACCESS_KEY_ID=ak-strong\nS3_SECRET_ACCESS_KEY=sk-strong\n';
+ const STORED_LOCAL = 'DATABASE_TYPE=sqlite\nPOSTGRES_BUILTIN=false\nSTORAGE_TYPE=local\nMINIO_BUILTIN=false\n';
+ let pinnedKeys: string[] = [];
+ const pin = (values: Record<string, string>) => {
+ Object.assign(process.env, values);
+ pinnedKeys = Object.keys(values);
+ recordPinnedEnvKeys(values);
+ };
+
+ afterEach(() => {
+ for (const key of pinnedKeys) delete process.env[key];
+ pinnedKeys = [];
+ recordPinnedEnvKeys({});
+ });
+
+ it('keeps a stored PostgreSQL and S3 choice and their settings under the opposite pins', () => {
+ pin({ DATABASE_TYPE: 'sqlite', STORAGE_TYPE: 'local' });
+
+ const env = written(
+ {
+ database: { builtIn: false, host: 'db.example.com', username: 'app', database: 'appdb' },
+ storage: {
+ builtIn: false,
+ localPath: './data/media',
+ s3Bucket: 'media',
+ s3Endpoint: 'https://s3.example.com',
+ },
+ },
+ STORED_EXTERNAL,
+ );
+
+ for (const line of STORED_EXTERNAL.trim().split('\n')) expect(env).toContain(line);
+ expect(env).not.toMatch(/^STORAGE_LOCAL_PATH=/m);
+ });
+
+ it('keeps a stored SQLite and local choice under the opposite pins, with no bundled container', () => {
+ pin({
+ DATABASE_TYPE: 'postgres',
+ DATABASE_PASSWORD: 'Str0ng!Passw0rd',
+ STORAGE_TYPE: 's3',
+ S3_ACCESS_KEY_ID: 'ak-strong',
+ S3_SECRET_ACCESS_KEY: 'sk-strong',
+ });
+ (fs.existsSync as jest.Mock).mockReturnValue(true);
+ (fs.readFileSync as jest.Mock).mockReturnValue(STORED_LOCAL);
+
+ const { profiles } = newController().saveConfig({
+ database: { builtIn: true, host: 'postgres' },
+ storage: { builtIn: true, s3Endpoint: 'http://minio:9000' },
+ });
+ const env = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>).at(-1)![1];
+
+ for (const line of STORED_LOCAL.trim().split('\n')) expect(env).toContain(line);
+ expect(env).not.toMatch(/^(DATABASE_HOST|S3_ENDPOINT)=/m);
+ expect(profiles).toEqual([]);
+ });
+
+ it('follows a pinned type without writing it when nothing is stored', () => {
+ pin({
+ DATABASE_TYPE: 'postgres',
+ DATABASE_PASSWORD: 'Str0ng!Passw0rd',
+ STORAGE_TYPE: 's3',
+ S3_ACCESS_KEY_ID: 'ak-strong',
+ S3_SECRET_ACCESS_KEY: 'sk-strong',
+ });
+
+ const env = written(
+ { database: { builtIn: false, host: 'db.example.com' }, storage: { builtIn: false, s3Bucket: 'media' } },
+ 'POSTGRES_BUILTIN=false\nSTORAGE_LOCAL_PATH=./data/media\n',
+ );
+
+ expect(env).toContain('DATABASE_HOST=db.example.com');
+ expect(env).toContain('S3_BUCKET=media');
+ expect(env).not.toMatch(/^(DATABASE_TYPE|STORAGE_TYPE|STORAGE_LOCAL_PATH)=/m);
+ });
+
+ it.each([
+ ['database', { database: { host: 'db.example.com' } }, /database\.type must be one of/],
+ ['storage', { storage: { s3Bucket: 'media' } }, /storage\.type must be one of/],
+ ])('is refused when no %s type is sent, stored or pinned', (_section, config, message) => {
+ (fs.existsSync as jest.Mock).mockReturnValue(true);
+ (fs.readFileSync as jest.Mock).mockReturnValue('DATABASE_TYPE=mysql\nSTORAGE_TYPE=ftp\n');
+ (fs.writeFileSync as jest.Mock).mockClear();
+
+ expect(() => newController().saveConfig(config as never)).toThrow(BadRequestException);
+ expect(() => newController().saveConfig(config as never)).toThrow(message);
+ expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();
+ });
+
+ it('still writes a type that is sent', () => {
+ pin({ DATABASE_TYPE: 'sqlite', STORAGE_TYPE: 'local' });
+
+ const env = written({ database: { type: 'sqlite' }, storage: { type: 'local' } }, STORED_EXTERNAL);
+
+ expect(env).toContain('DATABASE_TYPE=sqlite');
+ expect(env).toContain('STORAGE_TYPE=local');
+ expect(env).not.toMatch(/^DATABASE_HOST=/m);
+ });
+ });
});
describe('InfraConfigController.saveConfig built-in/external mode flips and the save-time secret guard', () => {