Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): check the saved config round-trips as a whole file

Yudhi Armyndharis96a5ebfcd9fd
diff --git a/src/modules/infra/generated-env.ts b/src/modules/infra/generated-env.ts
index 95983b808..9dbb4b1b7 100644
--- a/src/modules/infra/generated-env.ts
+++ b/src/modules/infra/generated-env.ts
@@ -33,9 +33,12 @@ export function readGeneratedEnv(): Record<string, string> {
* `value` in the form dotenv reads back unchanged, or `undefined` when no form does. dotenv takes an
* unquoted `#` as a comment and strips outer quotes and whitespace, so such a value is quoted; any
* other value stays bare, which keeps existing files and scripts/lib-env.sh (plain lines only) as-is.
+ * A leading quote is never left bare: it reads back on its own line, but in the whole file it opens a
+ * quoted value that a later line holding the same quote character closes.
*/
export function encodeGeneratedEnvValue(key: string, value: string): string | undefined {
- return [value, `'${value}'`, `"${value}"`, `\`${value}\``].find(
+ const quoted = [`'${value}'`, `"${value}"`, `\`${value}\``];
+ return (/^['"`]/.test(value) ? quoted : [value, ...quoted]).find(
form => dotenv.parse(`${key}=${form}`)[key] === value,
);
}
diff --git a/src/modules/infra/infra-config.controller.spec.ts b/src/modules/infra/infra-config.controller.spec.ts
index e9d109b6f..d7024570e 100644
--- a/src/modules/infra/infra-config.controller.spec.ts
+++ b/src/modules/infra/infra-config.controller.spec.ts
@@ -287,6 +287,37 @@ describe('InfraConfigController.saveConfig writes values the next boot reads bac
expect(savedPassword('Str0ng!Passw0rd').line).toBe('DATABASE_PASSWORD=Str0ng!Passw0rd');
});
+ // Each line reads back on its own, but the next boot parses the whole file, where a quote one value
+ // leaves open can run on to a later line that holds the same quote character.
+ function savedFile(databasePassword: string, redisPassword: string): string {
+ (fs.existsSync as jest.Mock).mockReturnValue(false);
+ (fs.writeFileSync as jest.Mock).mockClear();
+ newController().saveConfig({
+ database: { type: 'postgres', builtIn: false, host: 'db', 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];
+ }
+
+ it('keeps every key intact when a value opens a quote that a later line closes', () => {
+ const dotenv = jest.requireActual<typeof import('dotenv')>('dotenv');
+ const content = savedFile('"x7Kp', 'ab"#cd');
+ const whole = dotenv.parse(content);
+ const lineByLine = Object.assign({}, ...content.split('\n').map(line => dotenv.parse(line))) as Record<
+ string,
+ string
+ >;
+
+ expect(whole).toEqual(lineByLine);
+ expect(whole).toMatchObject({ DATABASE_TYPE: 'postgres', DATABASE_PASSWORD: '"x7Kp', REDIS_PASSWORD: 'ab"#cd' });
+ });
+
+ it('refuses a quoted value that a later line would extend, writing nothing', () => {
+ // `#x\` needs quoting, and its `\'` escapes the closing quote once a later line holds a `'#`.
+ expect(() => savedFile('#x\\', `a'#b`)).toThrow(/DATABASE_PASSWORD/);
+ expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();
+ });
+
it('refuses a value no dotenv form can carry, writing nothing', () => {
(fs.existsSync as jest.Mock).mockReturnValue(false);
(fs.writeFileSync as jest.Mock).mockClear();
diff --git a/src/modules/infra/infra-config.controller.ts b/src/modules/infra/infra-config.controller.ts
index 06623bba3..aeb31d6e0 100644
--- a/src/modules/infra/infra-config.controller.ts
+++ b/src/modules/infra/infra-config.controller.ts
@@ -27,6 +27,7 @@ import { assertNoDefaultSecretsInProduction } from '../../config/bootstrap-secur
import { BLANK_SHADOWED_ENV_KEYS, isEnvPinned, isOsProvidedEnv } from '../../config/env-precedence';
import * as fs from 'fs';
import * as path from 'path';
+import * as dotenv from 'dotenv';
import { encodeGeneratedEnvValue, generatedEnvPath, readGeneratedEnv } from './generated-env';
import {
applyDatabaseSection,
@@ -331,19 +332,18 @@ export class InfraConfigController {
}
private persistGeneratedEnv(envPath: string, merged: Record<string, string>): void {
- const body = Object.keys(merged)
- .sort()
- .map(key => {
- // Quoted where a raw line would read back differently (a `#` in a password would otherwise
- // truncate it on the next boot); refused, before anything is written, where no form can carry it.
- const encoded = encodeGeneratedEnvValue(key, merged[key]);
- if (encoded === undefined) {
- throw new BadRequestException(
- `Invalid configuration value for ${key}: it cannot be stored so that it reads back unchanged`,
- );
- }
- return `${key}=${encoded}`;
- });
+ const unreadable = (key: string) =>
+ new BadRequestException(
+ `Invalid configuration value for ${key}: it cannot be stored so that it reads back unchanged`,
+ );
+ const keys = Object.keys(merged).sort();
+ const body = keys.map(key => {
+ // Quoted where a raw line would read back differently (a `#` in a password would otherwise
+ // truncate it on the next boot); refused, before anything is written, where no form can carry it.
+ const encoded = encodeGeneratedEnvValue(key, merged[key]);
+ if (encoded === undefined) throw unreadable(key);
+ return `${key}=${encoded}`;
+ });
const contents = [
'# OpenWA Configuration',
`# Generated at ${new Date().toISOString()}`,
@@ -352,6 +352,11 @@ export class InfraConfigController {
...body,
'',
].join('\n');
+ // The next boot parses the file as a whole, where a quoted value can run on into a later line
+ // (a trailing `\'` escapes its own closing quote), so each line reading back alone is not enough.
+ const back = dotenv.parse(contents);
+ const drifted = keys.find(key => back[key] !== merged[key]);
+ if (drifted !== undefined) throw unreadable(drifted);
// Write to data/ so it persists across container restarts. Owner-only (0600): this file holds
// the DB/S3/Redis credentials, so it must not be world-readable between save and next restart.