Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(storage): fail fast on an unwritable media storage root (#1066)

Yudhi Armyndharisb6a1114ba303
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 194fdafc5..72a182626 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **A media storage root the app cannot write to is now caught at boot, with an error that says what
+ to change.** The check ran on the wrong question: `StorageService` created the root only when it did
+ not already exist, so a root that existed but belonged to another user sailed through startup and
+ failed much later, on the first media write — surfacing as a bare `EACCES` from `mkdir` deep inside
+ status ingestion, naming neither the setting at fault nor the file that set it.
+ Startup now probes writability, and refuses to start with the value of
+ `STORAGE_LOCAL_PATH`, the absolute path it resolved to, and the uid the process is running as. (#1065)
+
+ One value self-heals instead of stopping the boot. `./uploads` was never an operator's choice:
+ `GET /infra/status` read a config key that never existed and returned it as the storage path on every
+ request in v0.2.0–v0.7.3, so any save on the dashboard's Infrastructure page in that window wrote
+ `STORAGE_LOCAL_PATH=./uploads` into `data/.env.generated` — which lives on the data volume and
+ outlives every upgrade. #472 fixed the endpoint; nothing migrated the stored value. An **unwritable**
+ `./uploads` is therefore treated as damage this project caused and is moved to `./data/media` with a
+ warning. A **writable** one is left exactly as it is, so a bare-metal install already serving media
+ from that directory is never relocated out from under it.
+
+ Installs carrying this value have been losing media quietly, not loudly: until v0.13.0 the image
+ chowned all of `/app`, so writes to `/app/uploads` succeeded — into the container's ephemeral layer,
+ outside the mounted volume, discarded on every container recreate. v0.13.0 narrowed that chown to
+ `./data`, which is what finally turned a silent loss into a visible error.
+
## [0.13.0] - 2026-08-03
### Added
diff --git a/src/config/storage-root.spec.ts b/src/config/storage-root.spec.ts
new file mode 100644
index 000000000..d5ecc1a0e
--- /dev/null
+++ b/src/config/storage-root.spec.ts
@@ -0,0 +1,90 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { DEFAULT_STORAGE_ROOT, isStorageRootWritable, resolveStorageRoot } from './storage-root';
+
+describe('resolveStorageRoot', () => {
+ const writableAlways = (): boolean => true;
+ const writableNever = (): boolean => false;
+
+ it('returns the configured root unchanged when it is writable', () => {
+ expect(resolveStorageRoot({ configured: './data/media', isWritable: writableAlways })).toBe('./data/media');
+ });
+
+ it('returns the default when nothing is configured', () => {
+ expect(resolveStorageRoot({ configured: undefined, isWritable: writableAlways })).toBe(DEFAULT_STORAGE_ROOT);
+ });
+
+ it('leaves a WRITABLE ./uploads alone — a healthy bare-metal install must not be relocated', () => {
+ expect(resolveStorageRoot({ configured: './uploads', isWritable: writableAlways })).toBe('./uploads');
+ });
+
+ it('migrates an UNWRITABLE ./uploads fossil to the default and warns', () => {
+ const warnings: string[] = [];
+ const effective = resolveStorageRoot({
+ configured: './uploads',
+ isWritable: (p: string): boolean => p !== './uploads',
+ logger: { warn: (m: string): void => void warnings.push(m) },
+ });
+
+ expect(effective).toBe(DEFAULT_STORAGE_ROOT);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain('STORAGE_LOCAL_PATH');
+ expect(warnings[0]).toContain('./uploads');
+ });
+
+ it('migrates the bare "uploads" spelling too — path.join normalises ./uploads to it', () => {
+ expect(resolveStorageRoot({ configured: 'uploads', isWritable: (p: string): boolean => p !== 'uploads' })).toBe(
+ DEFAULT_STORAGE_ROOT,
+ );
+ });
+
+ it('throws an actionable error naming STORAGE_LOCAL_PATH when a non-fossil root is unwritable', () => {
+ expect(() => resolveStorageRoot({ configured: '/mnt/readonly', isWritable: writableNever })).toThrow(
+ /STORAGE_LOCAL_PATH/,
+ );
+ expect(() => resolveStorageRoot({ configured: '/mnt/readonly', isWritable: writableNever })).toThrow(
+ /\/mnt\/readonly/,
+ );
+ });
+
+ it('throws rather than silently continuing when the fossil AND the migration target are both unwritable', () => {
+ expect(() => resolveStorageRoot({ configured: './uploads', isWritable: writableNever })).toThrow(
+ /STORAGE_LOCAL_PATH/,
+ );
+ });
+});
+
+describe('isStorageRootWritable', () => {
+ let tmp: string;
+
+ beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'openwa-storage-root-'));
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ });
+
+ it('creates a missing root and reports it writable', () => {
+ const root = path.join(tmp, 'media');
+
+ expect(isStorageRootWritable(root)).toBe(true);
+ expect(fs.existsSync(root)).toBe(true);
+ });
+
+ it('reports an EXISTING but unwritable root as not writable (the #1065 case existsSync misses)', () => {
+ // Running as root bypasses permission bits entirely, so the negative case is unprovable there.
+ if (typeof process.getuid === 'function' && process.getuid() === 0) return;
+
+ const root = path.join(tmp, 'locked');
+ fs.mkdirSync(root);
+ fs.chmodSync(root, 0o555);
+
+ try {
+ expect(isStorageRootWritable(root)).toBe(false);
+ } finally {
+ fs.chmodSync(root, 0o755);
+ }
+ });
+});
diff --git a/src/config/storage-root.ts b/src/config/storage-root.ts
new file mode 100644
index 000000000..4d047aaa8
--- /dev/null
+++ b/src/config/storage-root.ts
@@ -0,0 +1,86 @@
+import * as fs from 'fs';
+import * as path from 'path';
+
+/** Storage root used when STORAGE_LOCAL_PATH is unset. Mirrors configuration.ts's `storage.localPath`. */
+export const DEFAULT_STORAGE_ROOT = './data/media';
+
+/**
+ * Storage roots no operator ever chose: `GET /infra/status` read a config key that never existed
+ * (`storage.path`) and returned this fallback on every request in v0.2.0–v0.7.3, so any dashboard
+ * Infrastructure save in that window persisted it to `data/.env.generated` — which lives on the data
+ * volume and survives every upgrade (#472 fixed the endpoint, nothing migrated the stored value).
+ *
+ * Both spellings are listed because `path.join` normalises `./uploads` to `uploads`, so the value can
+ * be observed either way depending on which layer wrote it.
+ */
+const FOSSIL_STORAGE_ROOTS = new Set(['./uploads', 'uploads']);
+
+/** Minimal logger surface (satisfied by createLogger()'s result). */
+export interface StorageRootLogger {
+ warn: (message: string) => void;
+}
+
+export interface StorageRootOptions {
+ /** Raw STORAGE_LOCAL_PATH. Blank/undefined falls back to {@link DEFAULT_STORAGE_ROOT}. */
+ configured?: string;
+ /** Injectable for tests; defaults to the real filesystem probe. */
+ isWritable?: (root: string) => boolean;
+ logger?: StorageRootLogger;
+}
+
+/**
+ * Whether the storage root can actually be written to, creating it when missing.
+ *
+ * This deliberately probes WRITABILITY, not existence. StorageService's own boot check is
+ * `if (!existsSync(root)) mkdirSync(root)` — which is a silent no-op for a root that exists but is
+ * owned by another user, so the failure only surfaces later, on the first media write (#1065).
+ */
+export function isStorageRootWritable(root: string): boolean {
+ try {
+ fs.mkdirSync(root, { recursive: true });
+ fs.accessSync(root, fs.constants.W_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Resolve the effective storage root, failing fast when it is unusable.
+ *
+ * A writable root is returned untouched — including a writable `./uploads`, so a bare-metal install
+ * that has been happily using it is never relocated out from under its existing media. Only an
+ * unwritable fossil is migrated onto the default, which is the case that cannot be anything but
+ * broken: in the official image `/app` is root-owned (v0.13.0 narrowed the build's chown from `/app`
+ * to `./data`), so `./uploads` resolves outside the mounted data volume and cannot be created.
+ *
+ * Any other unwritable root throws — a misconfiguration the operator must see and fix, not something
+ * to paper over with a silent fallback. That is how this class of bug stayed invisible for so long:
+ * before v0.13.0 the same fossil silently succeeded into the container's ephemeral layer, and every
+ * status/chat media file written there was discarded on the next container recreate.
+ */
+export function resolveStorageRoot(options: StorageRootOptions): string {
+ const isWritable = options.isWritable ?? isStorageRootWritable;
+ const configured = options.configured?.trim() || DEFAULT_STORAGE_ROOT;
+
+ if (isWritable(configured)) return configured;
+
+ if (FOSSIL_STORAGE_ROOTS.has(configured) && isWritable(DEFAULT_STORAGE_ROOT)) {
+ options.logger?.warn(
+ `STORAGE_LOCAL_PATH='${configured}' is not writable and is a known-bad value written by a bug in ` +
+ `OpenWA v0.2.0–v0.7.3 (#472); falling back to '${DEFAULT_STORAGE_ROOT}'. Remove the STORAGE_LOCAL_PATH ` +
+ `line from data/.env.generated to silence this warning. Any media previously written to ` +
+ `'${configured}' was outside the data volume and is not recoverable.`,
+ );
+ return DEFAULT_STORAGE_ROOT;
+ }
+
+ throw new Error(
+ `Refusing to start: the media storage root is not writable.\n` +
+ ` STORAGE_LOCAL_PATH = ${configured}\n` +
+ ` resolved to = ${path.resolve(configured)}\n` +
+ ` running as uid = ${typeof process.getuid === 'function' ? process.getuid() : 'n/a'}\n` +
+ `Point STORAGE_LOCAL_PATH at a directory the app can write to (in Docker, keep it inside the ` +
+ `mounted data volume — e.g. ${DEFAULT_STORAGE_ROOT}).`,
+ );
+}
diff --git a/src/main.ts b/src/main.ts
index 1897ce2b4..00e3aa0d0 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -13,6 +13,7 @@ import { LoggerService, LogLevel, createLogger } from './common/services/logger.
import { createSwaggerConfig, exemptPublicOperations } from './config/swagger.config';
import { registerUncaughtExceptionMonitor, registerUnhandledRejectionHandler } from './config/process-error-monitor';
import { runBootstrapOrExit } from './config/bootstrap-fatal';
+import { resolveStorageRoot } from './config/storage-root';
import { applyHttpTimeouts, HttpTimeoutConfig, HttpTimeoutSink } from './config/http-timeouts';
import { createInflightBodyBudget, resolveInflightBodyBudgetBytes } from './config/inflight-body-budget';
import { applyGlobalValidation } from './config/app-validation';
@@ -85,6 +86,15 @@ async function bootstrap() {
);
}
+ // Fail fast on a media storage root the app cannot write to, BEFORE Nest builds the module graph:
+ // StorageService only checks that the root EXISTS, so a root owned by another user passes boot and
+ // fails later on the first media write instead (#1065). Runs ahead of NestFactory.create so
+ // configuration.ts reads the resolved value.
+ process.env.STORAGE_LOCAL_PATH = resolveStorageRoot({
+ configured: process.env.STORAGE_LOCAL_PATH,
+ logger: bootstrapLogger,
+ });
+
// Disable Nest's default body parser so we can set an explicit size cap below.
const app = await NestFactory.create(AppModule, { bodyParser: false });
appInstance = app;