Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): constrain Docker container teardown to managed services (#534)

Yudhi Armyndharis2567299daec3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eb83be240..0d9449805 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Security
- **Hook re-entrancy is now blocked for sandboxed plugins too.** A plugin running in the worker-thread sandbox could re-fire the hook it was handling by issuing a capability call (for example, sending a message from within a `message:sending` handler), because the re-entrancy guard did not span the worker boundary — looping the event back into the plugin without bound. The host now runs each worker-initiated capability call inside the in-flight hook context, so such a re-fire is short-circuited exactly as it already was for in-process plugins. (#532)
+- **Docker container teardown is constrained to OpenWA-managed services.** The `POST /infra/restart` endpoint passed its `profilesToRemove` list straight to container removal, which resolved containers by a name substring — so an unrecognized or empty profile could stop and remove an unrelated container. Teardown is now restricted to the managed allowlist (`postgres`, `redis`, `minio`) and container resolution requires an exact `openwa-<service>` name match. (#534)
## [0.7.12] - 2026-06-29
diff --git a/src/modules/docker/docker.service.spec.ts b/src/modules/docker/docker.service.spec.ts
index 08896d9ff..90a334ae2 100644
--- a/src/modules/docker/docker.service.spec.ts
+++ b/src/modules/docker/docker.service.spec.ts
@@ -70,3 +70,45 @@ describe('DockerService.buildDockerOptions', () => {
});
});
});
+
+describe('DockerService.getContainerByService exact-name fallback', () => {
+ // Label lookup returns nothing → exercises the name fallback. The fallback must match the exact
+ // OpenWA-managed container name, never a substring (a substring — and especially the empty string —
+ // would let an arbitrary container be resolved and torn down).
+ function withFakeDocker(containers: Array<{ Id: string; Names: string[] }>) {
+ const service = new DockerService();
+ const listContainers = jest
+ .fn()
+ .mockResolvedValueOnce([]) // label-filtered lookup: no match
+ .mockResolvedValueOnce(containers); // fallback: all containers
+ const getContainer = jest.fn((id: string) => ({ id }));
+ Object.assign(service as unknown as Record<string, unknown>, {
+ docker: { listContainers, getContainer },
+ isAvailable: true,
+ });
+ return { service, getContainer };
+ }
+
+ it('does not resolve any container for an empty service name', async () => {
+ const { service, getContainer } = withFakeDocker([{ Id: 'abc', Names: ['/openwa-postgres'] }]);
+ expect(await service.getContainerByService('')).toBeNull();
+ expect(getContainer).not.toHaveBeenCalled();
+ });
+
+ it('does not resolve a container by substring of its name', async () => {
+ const { service, getContainer } = withFakeDocker([{ Id: 'abc', Names: ['/openwa-postgres-primary'] }]);
+ // 'postgres' is a substring of 'openwa-postgres-primary' but not the exact managed name.
+ expect(await service.getContainerByService('postgres')).toBeNull();
+ expect(getContainer).not.toHaveBeenCalled();
+ });
+
+ it('resolves the exact openwa-<service> container', async () => {
+ const { service, getContainer } = withFakeDocker([
+ { Id: 'p', Names: ['/openwa-postgres'] },
+ { Id: 'r', Names: ['/openwa-redis'] },
+ ]);
+ const result = await service.getContainerByService('redis');
+ expect(getContainer).toHaveBeenCalledWith('r');
+ expect(result).toEqual({ id: 'r' });
+ });
+});
diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.ts
index a322912d2..2c19d49b2 100644
--- a/src/modules/docker/docker.service.ts
+++ b/src/modules/docker/docker.service.ts
@@ -1,6 +1,12 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import Docker from 'dockerode';
+/**
+ * The only Docker profiles OpenWA manages (and may start/stop/remove). Used to bound teardown so a
+ * caller-supplied profile name can never reach removeService for an unrelated container.
+ */
+export const MANAGED_DOCKER_PROFILES: readonly string[] = ['postgres', 'redis', 'minio'];
+
interface ContainerInfo {
id: string;
name: string;
@@ -181,9 +187,11 @@ export class DockerService implements OnModuleInit {
return this.docker.getContainer(containers[0].Id);
}
- // Fallback: try by name
+ // Fallback: try by EXACT name (never a substring — a substring, and especially the empty
+ // string, would resolve an arbitrary container). OpenWA-managed containers are `openwa-<service>`.
+ const target = `openwa-${service}`;
const allContainers = await this.docker.listContainers({ all: true });
- const match = allContainers.find(c => c.Names?.some(n => n.includes(`openwa-${service}`) || n.includes(service)));
+ const match = allContainers.find(c => c.Names?.some(n => n === target || n === `/${target}`));
if (match) {
return this.docker.getContainer(match.Id);
diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.ts
index 4bf4c8a70..49f0187ff 100644
--- a/src/modules/infra/infra.controller.spec.ts
+++ b/src/modules/infra/infra.controller.spec.ts
@@ -784,3 +784,34 @@ describe('InfraController.exportStorage keeps the export import-able and sweeps
expect(await exists(result.download)).toBe(false);
});
});
+
+describe('InfraController.requestRestart constrains teardown to managed profiles', () => {
+ const buildController = (dockerService: Record<string, unknown>) =>
+ new InfraController(
+ { get: () => undefined } as never,
+ { isInitialized: true } as never,
+ { isInitialized: true } as never,
+ {} as never, // engineFactory
+ dockerService as never,
+ { isAvailable: () => Promise.resolve(false) } as never, // cacheService
+ { isS3Available: () => false, refreshS3Availability: () => Promise.resolve(false) } as never, // storageService
+ { shutdown: jest.fn() } as never, // shutdownService
+ );
+
+ it('removes only allowlisted profiles, never an unknown or empty entry', async () => {
+ const removeService = jest.fn().mockResolvedValue(true);
+ const controller = buildController({
+ isDockerAvailable: () => true,
+ removeService,
+ orchestrateProfiles: jest.fn().mockResolvedValue({}),
+ });
+
+ // '' (matches any container by substring) and 'evil' must be dropped; only managed profiles act.
+ await controller.requestRestart({ profilesToRemove: ['', 'evil', 'postgres', 'redis'] });
+
+ const removed = removeService.mock.calls.map(call => String((call as unknown[])[0])).sort();
+ expect(removed).toEqual(['postgres', 'redis']);
+ expect(removed).not.toContain('');
+ expect(removed).not.toContain('evil');
+ });
+});
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index 3ac162cae..1bfa52694 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -9,7 +9,7 @@ import { isPathWithin } from '../../common/utils/path-safety';
import { writeSecretFile } from '../../common/utils/secret-file';
import { EngineFactory } from '../../engine/engine.factory';
import { getEffectiveWebVersionInfo, resolveCurrentWebVersion } from '../../engine/wa-web-version';
-import { DockerService } from '../docker';
+import { DockerService, MANAGED_DOCKER_PROFILES } from '../docker';
import { CacheService } from '../../common/cache/cache.service';
import { StorageService } from '../../common/storage/storage.service';
import { ShutdownService } from '../../common/services/shutdown.service';
@@ -645,7 +645,15 @@ export class InfraController {
// otherwise tear down the very backend the app is running on. (Known minor limitation: switching
// away from a built-in backend and then reloading the page before restarting can leave the old
// container running until the next explicit change.)
- const toRemove = profilesToRemove.filter(p => !profiles.includes(p));
+ // Only ever tear down OpenWA-managed services. An arbitrary profile name (or the empty string)
+ // would otherwise reach removeService and, via container-name matching, could stop an unrelated
+ // container — so constrain teardown to the managed allowlist and drop anything else.
+ const requested = profilesToRemove.filter(p => !profiles.includes(p));
+ const toRemove = requested.filter(p => MANAGED_DOCKER_PROFILES.includes(p));
+ const ignored = requested.filter(p => !MANAGED_DOCKER_PROFILES.includes(p));
+ if (ignored.length > 0) {
+ this.logger.warn('Ignoring non-managed profiles in profilesToRemove', { ignored });
+ }
// First, remove containers for disabled services
if (toRemove.length > 0) {