Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): keep proxy credentials out of the data export

Yudhi Armyndharis52699062e0fb
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index 79e5aa088..df774964c 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -171,14 +171,14 @@ OpenWA serves plain HTTP on its port; terminate **TLS at your reverse proxy / lo
> **There is currently no application-level encryption at rest.** API keys are stored **hashed** (one-way), but other sensitive values are stored as plaintext in the database / on disk and are protected by filesystem and database permissions, not by encryption. Encryption at rest for these fields is a roadmap item, not a shipped feature — do not assume it.
-| Data | At rest | How it is protected |
-| ----------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| API keys | **Hashed** — SHA-256 with an optional `API_KEY_PEPPER` HMAC; never reversible | A database leak alone cannot recover the keys; with a pepper set, hashes can't be precomputed offline. See §4.2. |
-| Session auth state (WhatsApp credentials) | Plaintext on disk (the engine's auth store under the data volume) | Filesystem permissions on the data volume — keep it private. |
-| Webhook secrets | Plaintext — `webhooks.secret` (`varchar`) | Database access control; never returned by the webhook read DTOs (write-only) and omitted from `GET /api/infra/export-data` webhook rows. |
-| Proxy credentials | Plaintext — `sessions.proxyUrl` may embed `user:pass` | Database access control; never returned by the session read DTOs — only masked `proxyHost`, `proxyType` (derived from the URL scheme), and `hasCredentials` on `GET/PATCH /proxy`. |
-| Generated config (`data/.env.generated`) | Plaintext file, written `0600` | Owner-only file permissions. |
-| Message content | Plaintext in the `messages` table | Database access control. |
+| Data | At rest | How it is protected |
+| ----------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| API keys | **Hashed** — SHA-256 with an optional `API_KEY_PEPPER` HMAC; never reversible | A database leak alone cannot recover the keys; with a pepper set, hashes can't be precomputed offline. See §4.2. |
+| Session auth state (WhatsApp credentials) | Plaintext on disk (the engine's auth store under the data volume) | Filesystem permissions on the data volume — keep it private. |
+| Webhook secrets | Plaintext — `webhooks.secret` (`varchar`) | Database access control; never returned by the webhook read DTOs (write-only) and omitted from `GET /api/infra/export-data` webhook rows. |
+| Proxy credentials | Plaintext — `sessions.proxyUrl` may embed `user:pass` | Database access control; never returned by the session read DTOs — only masked `proxyHost`, `proxyType` (derived from the URL scheme), and `hasCredentials` on `GET/PATCH /proxy`. The userinfo is also stripped from `GET /api/infra/export-data` session rows; scheme and host survive so a restore cannot silently connect direct. |
+| Generated config (`data/.env.generated`) | Plaintext file, written `0600` | Owner-only file permissions. |
+| Message content | Plaintext in the `messages` table | Database access control. |
**Hardening you can apply today:** set `API_KEY_PEPPER`; restrict the data volume and database to the app's user; and encrypt at the infrastructure layer (LUKS / cloud-provider encrypted volumes / an encrypted managed Postgres) rather than relying on application-level field encryption, which is not implemented.
diff --git a/src/modules/infra/export-tables.redaction.spec.ts b/src/modules/infra/export-tables.redaction.spec.ts
new file mode 100644
index 000000000..5151e920d
--- /dev/null
+++ b/src/modules/infra/export-tables.redaction.spec.ts
@@ -0,0 +1,95 @@
+import { EXPORT_TABLES } from './export-tables';
+import type { SessionRow, WebhookRow } from './migration-tables.types';
+
+/**
+ * The credentials a backup payload must not carry.
+ *
+ * `GET /api/infra/export-data` is the JSON half of the documented backup runbook (docs/11), and
+ * docs/04 records per secret how it is protected. Webhook secrets were already stripped here; the
+ * session proxy URL was not, so a payload that deliberately omitted one credential shipped its
+ * sibling in full. Neither redaction had a test.
+ */
+const tableFor = (key: string): { afterRead?: (rows: never[]) => void } => {
+ const entry = EXPORT_TABLES.find(t => t.key === key);
+ if (!entry) throw new Error(`no export table registered for ${key}`);
+ return entry;
+};
+
+const runAfterRead = <T>(key: string, rows: T[]): T[] => {
+ const { afterRead } = tableFor(key);
+ if (!afterRead) throw new Error(`${key} registers no afterRead hook`);
+ (afterRead as unknown as (r: T[]) => void)(rows);
+ return rows;
+};
+
+const session = (proxyUrl: string | null): SessionRow =>
+ ({ id: 's1', name: 'main', status: 'ready', proxyUrl }) as SessionRow;
+
+describe('export redaction', () => {
+ describe('session proxy credentials', () => {
+ it('strips userinfo and keeps the proxy reachable', () => {
+ const [row] = runAfterRead('sessions', [session('http://bob:[email protected]:8080')]);
+
+ expect(row.proxyUrl).toBe('http://proxy.example.com:8080/');
+ expect(row.proxyUrl).not.toContain('bob');
+ expect(row.proxyUrl).not.toContain('hunter2');
+ });
+
+ /**
+ * `socks5:` is not a WHATWG "special" scheme, so `URL.toString()` adds no trailing slash where
+ * it would for `http:`. Both forms re-parse identically and both proxy agents accept them; the
+ * assertion pins the shape so a future normalisation change is visible rather than silent.
+ */
+ it('strips a username with no password, on a socks scheme', () => {
+ const [row] = runAfterRead('sessions', [session('socks5://[email protected]:1080')]);
+
+ expect(row.proxyUrl).toBe('socks5://proxy.example.com:1080');
+ expect(row.proxyUrl).not.toContain('bob');
+ });
+
+ /**
+ * The column is kept rather than dropped on purpose: an importer that restored no proxy would
+ * let the session connect DIRECT on its next start, leaking the host's real egress IP with
+ * nothing to notice. Host and scheme survive so the operator can see what was configured.
+ */
+ it('leaves a credential-free proxy untouched', () => {
+ const [row] = runAfterRead('sessions', [session('http://proxy.example.com:8080')]);
+
+ expect(row.proxyUrl).toBe('http://proxy.example.com:8080');
+ });
+
+ it('leaves a session with no proxy alone', () => {
+ const [row] = runAfterRead('sessions', [session(null)]);
+
+ expect(row.proxyUrl).toBeNull();
+ });
+
+ /** Unparseable means unprovable: it cannot be shown to be credential-free, so it does not ship. */
+ it('clears a value the URL parser rejects', () => {
+ const [row] = runAfterRead('sessions', [session('not a url')]);
+
+ expect(row.proxyUrl).toBeNull();
+ });
+
+ it('redacts every row, not just the first', () => {
+ const rows = runAfterRead('sessions', [
+ session('http://a:[email protected]:8080'),
+ session('http://b:[email protected]:8080'),
+ ]);
+
+ expect(rows.every(r => r.proxyUrl !== null && !r.proxyUrl.includes('@'))).toBe(true);
+ });
+ });
+
+ describe('webhook credentials', () => {
+ it('omits the secret and the custom headers', () => {
+ const rows = runAfterRead('webhooks', [
+ { id: 'w1', url: 'https://example.com/hook', secret: 's3cr3t', headers: { Authorization: 'Bearer t' } },
+ ] as unknown as WebhookRow[]);
+
+ expect(rows[0]).not.toHaveProperty('secret');
+ expect(rows[0]).not.toHaveProperty('headers');
+ expect(rows[0].url).toBe('https://example.com/hook');
+ });
+ });
+});
diff --git a/src/modules/infra/export-tables.ts b/src/modules/infra/export-tables.ts
index dcbc90204..cd5364e7c 100644
--- a/src/modules/infra/export-tables.ts
+++ b/src/modules/infra/export-tables.ts
@@ -1,4 +1,4 @@
-import type { MigrationTables, WebhookRow, MessageRow, MessageBatchRow } from './migration-tables.types';
+import type { MigrationTables, SessionRow, WebhookRow, MessageRow, MessageBatchRow } from './migration-tables.types';
/**
* A `data` value that is a POINTER rather than bytes. `metadata.media.data` holds `base64 || dto.url!`
@@ -26,6 +26,36 @@ function redactWebhookCredentials(rows: WebhookRow[]): void {
}
}
+/**
+ * `sessions.proxyUrl` may embed `user:pass` (docs/04 section 4.3), and the sibling webhook secret
+ * above is already kept out of this payload. Strip the userinfo and keep the rest of the URL.
+ *
+ * Dropping the column instead would be worse than it looks: the importer would restore the session
+ * with no proxy at all, and it would then connect DIRECT on the next start, leaking the host's real
+ * egress IP to WhatsApp with nothing to notice. That is the exact failure mode the engine refuses
+ * elsewhere, where an unusable proxy value fails the session rather than silently bypassing it
+ * (baileys-lifecycle.ts). A credential-stripped URL keeps the operator's intent visible, restores as
+ * `hasCredentials: false` on `GET /proxy`, and fails loudly on the next start when the proxy needs
+ * auth, which is the signal to re-enter it.
+ *
+ * A value the URL parser rejects is cleared rather than passed through, since it cannot be proven
+ * free of credentials.
+ */
+function redactSessionProxyCredentials(rows: SessionRow[]): void {
+ for (const row of rows) {
+ if (!row.proxyUrl) continue;
+ try {
+ const parsed = new URL(row.proxyUrl);
+ if (!parsed.username && !parsed.password) continue;
+ parsed.username = '';
+ parsed.password = '';
+ row.proxyUrl = parsed.toString();
+ } catch {
+ row.proxyUrl = null;
+ }
+ }
+}
+
/**
* Postgres carries a STORED generated tsvector column `body_ts` (FTS) that `SELECT *` picks up.
* It is a server-maintained index artifact, not payload: strip it so backups stay dialect-neutral
@@ -172,7 +202,7 @@ function defineExportTable<K extends keyof MigrationTables>(table: ExportTable<K
*/
export const EXPORT_TABLES: AnyExportTable[] = [
// sessions first: webhooks/messages/templates/etc. all reference it (some via FK, all by sessionId).
- defineExportTable({ key: 'sessions', table: 'sessions' }),
+ defineExportTable({ key: 'sessions', table: 'sessions', afterRead: redactSessionProxyCredentials }),
defineExportTable({ key: 'webhooks', table: 'webhooks', afterRead: redactWebhookCredentials }),
// Both carry a full inline base64 payload, so they share ONE budget: messages are served first