Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(security): prevent path traversal and enforce admin-only infra endpoints (#207)

Yudhi Armyndharis60ae387bac54
diff --git a/src/common/storage/storage.service.spec.ts b/src/common/storage/storage.service.spec.ts
new file mode 100644
index 000000000..cce9ef573
--- /dev/null
+++ b/src/common/storage/storage.service.spec.ts
@@ -0,0 +1,90 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import * as tar from 'tar-stream';
+import { createGzip } from 'zlib';
+import { Readable } from 'stream';
+import { ConfigService } from '@nestjs/config';
+
+// `archiver` v8 ships as ESM only, which ts-jest cannot parse when StorageService
+// is imported transitively. These tests never exercise the export path (which is
+// the only consumer of archiver), so a lightweight stub is sufficient.
+jest.mock('archiver', () => ({ default: jest.fn() }));
+
+import { StorageService } from './storage.service';
+
+/** Build an in-memory gzipped tar archive from the given entries. */
+function makeTarGz(entries: { name: string; data: string }[]): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ const pack = tar.pack();
+ let i = 0;
+ const writeNext = (): void => {
+ if (i >= entries.length) {
+ pack.finalize();
+ return;
+ }
+ const entry = entries[i++];
+ pack.entry({ name: entry.name }, Buffer.from(entry.data), err => (err ? reject(err) : writeNext()));
+ };
+ const gzip = createGzip();
+ const chunks: Buffer[] = [];
+ pack.pipe(gzip);
+ gzip.on('data', (c: Buffer) => chunks.push(c));
+ gzip.on('end', () => resolve(Buffer.concat(chunks)));
+ gzip.on('error', reject);
+ writeNext();
+ });
+}
+
+describe('StorageService (local) path traversal protection', () => {
+ let baseDir: string;
+ let localPath: string;
+ let service: StorageService;
+
+ beforeEach(() => {
+ baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-storage-'));
+ localPath = path.join(baseDir, 'media');
+ const configService = {
+ get: (key: string) => {
+ if (key === 'storage.type') return 'local';
+ if (key === 'storage.localPath') return localPath;
+ return undefined;
+ },
+ } as unknown as ConfigService;
+ service = new StorageService(configService);
+ });
+
+ afterEach(() => {
+ fs.rmSync(baseDir, { recursive: true, force: true });
+ });
+
+ it('writes a file within the storage root', async () => {
+ await service.putFile('sub/ok.txt', Buffer.from('hi'));
+ expect(fs.readFileSync(path.join(localPath, 'sub/ok.txt'), 'utf8')).toBe('hi');
+ });
+
+ it('rejects writing a file outside the storage root', async () => {
+ await expect(service.putFile('../escape.txt', Buffer.from('x'))).rejects.toThrow();
+ expect(fs.existsSync(path.join(baseDir, 'escape.txt'))).toBe(false);
+ });
+
+ it('rejects reading a file outside the storage root', async () => {
+ // A real file that exists OUTSIDE the storage root; without containment the
+ // service would happily read it via "..".
+ fs.writeFileSync(path.join(baseDir, 'secret.txt'), 'topsecret');
+ await expect(service.getFile('../secret.txt')).rejects.toThrow();
+ });
+
+ it('imports safe entries but refuses tar entries that escape the storage root', async () => {
+ const gz = await makeTarGz([
+ { name: 'safe.txt', data: 'good' },
+ { name: '../evil.txt', data: 'bad' },
+ ]);
+
+ const count = await service.importFromStream(Readable.from(gz));
+
+ expect(fs.readFileSync(path.join(localPath, 'safe.txt'), 'utf8')).toBe('good');
+ expect(fs.existsSync(path.join(baseDir, 'evil.txt'))).toBe(false);
+ expect(count).toBe(1);
+ });
+});
diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.ts
index 0170bb4a8..fdb95d4f6 100644
--- a/src/common/storage/storage.service.ts
+++ b/src/common/storage/storage.service.ts
@@ -15,6 +15,7 @@ import {
CreateBucketCommand,
} from '@aws-sdk/client-s3';
import { createLogger } from '../services/logger.service';
+import { isPathWithin } from '../utils/path-safety';
interface S3Config {
endpoint?: string;
@@ -247,11 +248,17 @@ export class StorageService {
}
private getLocalFile(filePath: string): Promise<Buffer> {
+ if (!isPathWithin(this.localPath, filePath)) {
+ throw new Error(`Refusing to read outside storage root: ${filePath}`);
+ }
const fullPath = path.join(this.localPath, filePath);
return Promise.resolve(fs.readFileSync(fullPath));
}
private putLocalFile(filePath: string, data: Buffer): Promise<void> {
+ if (!isPathWithin(this.localPath, filePath)) {
+ throw new Error(`Refusing to write outside storage root: ${filePath}`);
+ }
const fullPath = path.join(this.localPath, filePath);
const dir = path.dirname(fullPath);
diff --git a/src/common/utils/path-safety.spec.ts b/src/common/utils/path-safety.spec.ts
new file mode 100644
index 000000000..de83e937e
--- /dev/null
+++ b/src/common/utils/path-safety.spec.ts
@@ -0,0 +1,27 @@
+import * as path from 'path';
+import { isPathWithin } from './path-safety';
+
+describe('isPathWithin', () => {
+ const root = path.resolve('/srv/app/data');
+
+ it('allows a normal nested path', () => {
+ expect(isPathWithin(root, 'media/file.jpg')).toBe(true);
+ });
+
+ it('allows the root itself', () => {
+ expect(isPathWithin(root, '.')).toBe(true);
+ });
+
+ it('blocks parent traversal via ".."', () => {
+ expect(isPathWithin(root, '../../etc/passwd')).toBe(false);
+ });
+
+ it('blocks an absolute path outside the root', () => {
+ expect(isPathWithin(root, '/etc/passwd')).toBe(false);
+ });
+
+ it('blocks a sibling directory that shares the root prefix', () => {
+ // "/srv/app/data-evil" must NOT be considered inside "/srv/app/data"
+ expect(isPathWithin('/srv/app/data', '/srv/app/data-evil/x')).toBe(false);
+ });
+});
diff --git a/src/common/utils/path-safety.ts b/src/common/utils/path-safety.ts
new file mode 100644
index 000000000..ca816a958
--- /dev/null
+++ b/src/common/utils/path-safety.ts
@@ -0,0 +1,17 @@
+import * as path from 'path';
+
+/**
+ * Returns true if `target` resolves to a location inside (or equal to) `root`.
+ *
+ * Guards against path traversal: untrusted input such as tar archive entry
+ * names or user-supplied file paths can contain ".." or absolute paths that
+ * escape the intended directory. Both arguments are resolved to absolute paths
+ * before comparison, and the trailing separator check prevents a sibling
+ * directory that merely shares the root's prefix (e.g. "/data-evil" vs "/data")
+ * from being treated as inside the root.
+ */
+export function isPathWithin(root: string, target: string): boolean {
+ const resolvedRoot = path.resolve(root);
+ const resolvedTarget = path.resolve(resolvedRoot, target);
+ return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);
+}
diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.ts
new file mode 100644
index 000000000..a3d6a6bde
--- /dev/null
+++ b/src/modules/infra/infra.controller.spec.ts
@@ -0,0 +1,65 @@
+import { Reflector } from '@nestjs/core';
+import { BadRequestException } from '@nestjs/common';
+
+// StorageService (imported transitively by InfraController) pulls in `archiver`
+// v8, which is ESM-only and cannot be parsed by ts-jest. The controller logic
+// under test never touches archiver, so a lightweight stub is sufficient.
+jest.mock('archiver', () => ({ default: jest.fn() }));
+
+import { InfraController } from './infra.controller';
+import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';
+import { ApiKeyRole } from '../auth/entities/api-key.entity';
+
+describe('InfraController access control (Vuln 2)', () => {
+ const reflector = new Reflector();
+
+ // Every mutating or data-exfiltration endpoint must require the ADMIN role so
+ // that a low-privilege (VIEWER/OPERATOR) API key cannot wipe data, read
+ // secrets, change config, restart, or trigger storage import.
+ const adminOnly = [
+ 'saveConfig', // PUT /infra/config
+ 'requestRestart', // POST /infra/restart
+ 'exportData', // GET /infra/export-data (exposes webhook secrets)
+ 'importData', // POST /infra/import-data (DELETEs all rows)
+ 'exportStorage', // GET /infra/storage/export
+ 'importStorage', // POST /infra/storage/import
+ ] as const;
+
+ it.each(adminOnly)('%s requires the ADMIN role', method => {
+ const handler = InfraController.prototype[method as keyof InfraController] as object;
+ const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, handler);
+ expect(role).toBe(ApiKeyRole.ADMIN);
+ });
+
+ it('leaves read-only status open to any authenticated key', () => {
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- reading route metadata off the handler, not invoking it
+ const handler = InfraController.prototype.getStatus as object;
+ const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, handler);
+ expect(role).toBeUndefined();
+ });
+});
+
+describe('InfraController.importStorage filePath validation (Vuln 3)', () => {
+ function buildController(storage: Partial<{ importFromStream: jest.Mock; getCurrentStorageType: jest.Mock }>) {
+ return new InfraController(
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ storage as never,
+ {} as never,
+ );
+ }
+
+ it('rejects a filePath that escapes the data directory before touching the filesystem', async () => {
+ const storage = { importFromStream: jest.fn(), getCurrentStorageType: jest.fn(() => 'local') };
+ const controller = buildController(storage);
+
+ await expect(controller.importStorage({ filePath: '../../../../etc/passwd' })).rejects.toBeInstanceOf(
+ BadRequestException,
+ );
+ expect(storage.importFromStream).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index 4fe429041..dc3a56043 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -1,9 +1,11 @@
-import { Controller, Get, Put, Post, Body } from '@nestjs/common';
+import { Controller, Get, Put, Post, Body, BadRequestException } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import { DataSource } from 'typeorm';
import { InjectDataSource } from '@nestjs/typeorm';
-import { Public } from '../auth/decorators/auth.decorators';
+import { Public, RequireRole } from '../auth/decorators/auth.decorators';
+import { ApiKeyRole } from '../auth/entities/api-key.entity';
+import { isPathWithin } from '../../common/utils/path-safety';
import { EngineFactory } from '../../engine/engine.factory';
import { DockerService } from '../docker';
import { CacheService } from '../../common/cache/cache.service';
@@ -204,6 +206,7 @@ export class InfraController {
}
@Put('config')
+ @RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Save infrastructure configuration to .env file' })
@ApiResponse({ status: 200, description: 'Configuration saved' })
@ApiBody({ description: 'Configuration to save' })
@@ -335,6 +338,7 @@ export class InfraController {
}
}
@Post('restart')
+ @RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Request server restart with Docker orchestration' })
@ApiResponse({ status: 200, description: 'Server will restart with new profiles' })
async requestRestart(@Body() body?: { profiles?: string[]; profilesToRemove?: string[] }): Promise<{
@@ -436,6 +440,7 @@ export class InfraController {
}
@Get('export-data')
+ @RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Export all data from Data DB for migration' })
@ApiResponse({ status: 200, description: 'Exported data as JSON' })
async exportData(): Promise<{
@@ -483,6 +488,7 @@ export class InfraController {
}
@Post('import-data')
+ @RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Import data to Data DB (replaces existing data)' })
@ApiBody({
description: 'Exported data from export-data endpoint',
@@ -686,6 +692,7 @@ export class InfraController {
}
@Get('storage/export')
+ @RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Export all storage files as tar.gz' })
@ApiResponse({ status: 200, description: 'Tar.gz archive stream' })
async exportStorage(): Promise<{ message: string; download: string }> {
@@ -709,6 +716,7 @@ export class InfraController {
}
@Post('storage/import')
+ @RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Import storage files from tar.gz' })
@ApiBody({ description: 'Path to tar.gz file to import' })
@ApiResponse({ status: 200, description: 'Import result' })
@@ -717,8 +725,15 @@ export class InfraController {
): Promise<{ imported: boolean; count: number; storageType: string }> {
const { filePath } = body;
+ // `filePath` is fully caller-controlled. Restrict it to the app's data
+ // directory so it cannot point at arbitrary files on the host.
+ const dataDir = path.join(process.cwd(), 'data');
+ if (!filePath || !isPathWithin(dataDir, filePath)) {
+ throw new BadRequestException('filePath must reference a file inside the data directory');
+ }
+
if (!fs.existsSync(filePath)) {
- throw new Error(`File not found: ${filePath}`);
+ throw new BadRequestException(`File not found: ${filePath}`);
}
const readStream = fs.createReadStream(filePath);