Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): quote saved config values the next boot would misread

Yudhi Armyndharis835df28d5fa7
diff --git a/src/modules/infra/generated-env.ts b/src/modules/infra/generated-env.ts
index 6f4135b5e..95983b808 100644
--- a/src/modules/infra/generated-env.ts
+++ b/src/modules/infra/generated-env.ts
@@ -28,3 +28,14 @@ export function readGeneratedEnv(): Record<string, string> {
const envPath = generatedEnvPath();
return fs.existsSync(envPath) ? dotenv.parse(fs.readFileSync(envPath, 'utf8')) : {};
}
+
+/**
+ * `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.
+ */
+export function encodeGeneratedEnvValue(key: string, value: string): string | undefined {
+ return [value, `'${value}'`, `"${value}"`, `\`${value}\``].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 9744de16d..e9d109b6f 100644
--- a/src/modules/infra/infra-config.controller.spec.ts
+++ b/src/modules/infra/infra-config.controller.spec.ts
@@ -260,6 +260,45 @@ describe('InfraConfigController.saveConfig rejects values that would inject extr
});
});
+describe('InfraConfigController.saveConfig writes values the next boot reads back unchanged', () => {
+ const newController = () => new InfraConfigController({} as never, {} as never, {} as never);
+
+ function 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);
+ 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=')),
+ parsed: jest.requireActual<typeof import('dotenv')>('dotenv').parse(content).DATABASE_PASSWORD,
+ };
+ }
+
+ // dotenv reads an unquoted `#` as a comment and trims outer quotes and whitespace, so a raw
+ // `KEY=value` line would boot with a different secret than the one saved.
+ it.each(['S3cr#tPass', ' spaced ', "'quoted'", '"dq"', 'p\\nq', `it's#`, `a'b"c#`])(
+ 'round-trips %j through dotenv',
+ password => {
+ expect(savedPassword(password).parsed).toBe(password);
+ },
+ );
+
+ it('keeps a value that needs no quoting bare', () => {
+ expect(savedPassword('Str0ng!Passw0rd').line).toBe('DATABASE_PASSWORD=Str0ng!Passw0rd');
+ });
+
+ it('refuses a value no dotenv form can carry, writing nothing', () => {
+ (fs.existsSync as jest.Mock).mockReturnValue(false);
+ (fs.writeFileSync as jest.Mock).mockClear();
+ expect(() =>
+ newController().saveConfig({
+ database: { type: 'postgres', builtIn: false, host: 'db', password: `a'b"c\`d#` },
+ } as never),
+ ).toThrow(BadRequestException);
+ expect(fs.writeFileSync as jest.Mock).not.toHaveBeenCalled();
+ });
+});
+
describe('InfraConfigController.saveConfig engine selection (persist ENGINE_TYPE — Infrastructure tile)', () => {
const engineFactory = {
getAvailableEngines: () => [{ id: 'whatsapp-web.js' }, { id: 'baileys' }],
diff --git a/src/modules/infra/infra-config.controller.ts b/src/modules/infra/infra-config.controller.ts
index b2c482d0c..06623bba3 100644
--- a/src/modules/infra/infra-config.controller.ts
+++ b/src/modules/infra/infra-config.controller.ts
@@ -27,7 +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 { generatedEnvPath, readGeneratedEnv } from './generated-env';
+import { encodeGeneratedEnvValue, generatedEnvPath, readGeneratedEnv } from './generated-env';
import {
applyDatabaseSection,
applyEngineSection,
@@ -333,7 +333,17 @@ export class InfraConfigController {
private persistGeneratedEnv(envPath: string, merged: Record<string, string>): void {
const body = Object.keys(merged)
.sort()
- .map(key => `${key}=${merged[key]}`);
+ .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 contents = [
'# OpenWA Configuration',
`# Generated at ${new Date().toISOString()}`,