Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(docker): tighten the socket-proxy ACL and make profile removal semantics honest (#934)

Yudhi Armyndharis0775e39a6a41
diff --git a/README.md b/README.md
index c7ccbdce2..7b1920579 100644
--- a/README.md
+++ b/README.md
@@ -199,7 +199,7 @@ The production stack never exposes `/var/run/docker.sock` directly to the applic
openwa-api ──TCP 2375──▶ docker-proxy ──unix──▶ /var/run/docker.sock
```
-Only the operations needed for container orchestration are enabled (`CONTAINERS`, `IMAGES`, `VOLUMES`, `INFO`, `PING`, `POST`, `DELETE`). The application connects via the `DOCKER_HOST=tcp://docker-proxy:2375` environment variable, which `DockerService` detects automatically.
+Only the operations needed for container orchestration are enabled (`CONTAINERS`, `IMAGES`, `VOLUMES`, `INFO`, `PING`, plus the `POST` method switch). The application connects via the `DOCKER_HOST=tcp://docker-proxy:2375` environment variable, which `DockerService` detects automatically. Note this is an operational gateway, not a fine-grained privilege boundary: with `POST` enabled the proxy admits every method to the enabled paths and cannot scope container-create payloads, so a compromised API container would be host-root-equivalent — see `SECURITY.md` for the full threat model, mitigations, and how to disable the proxy if you don't use the built-in datastore orchestration.
### Non-root Container Execution
diff --git a/SECURITY.md b/SECURITY.md
index 20d72feef..fab9de4ec 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -40,11 +40,39 @@ Please include, where possible:
OpenWA already ships several hardening measures: API-key auth with roles
(ADMIN / OPERATOR / VIEWER), optional outbound webhook SSRF protection, a production
CORS policy (wildcard origins refused in production), request body-size limits, a
-least-privilege Docker socket-proxy with a non-root container, and path-containment
-checks on storage import/export.
+non-root application container, path-containment checks on storage import/export,
+and a Docker socket-proxy as the sole gateway to the Docker daemon.
When exposing OpenWA, please review the security-relevant configuration documented in
the README and `docs/` — in particular `CORS_ORIGINS`, `ALLOW_DEV_API_KEY`,
`ENABLE_SWAGGER`, `WEBHOOK_SSRF_PROTECT`, `BODY_SIZE_LIMIT`, and the Docker proxy setup.
Never expose the dashboard/API to the public internet with the development API key
enabled.
+
+### Docker socket proxy — scope and residual risk
+
+The application container never mounts `/var/run/docker.sock`; it reaches the daemon
+only through the bundled `docker-proxy` sidecar (pinned `tecnativa/docker-socket-proxy`),
+which listens solely on an internal Compose network that no other container joins.
+The proxy enables only the endpoint families the built-in datastore orchestration
+needs (`CONTAINERS`, `IMAGES`, `VOLUMES`, `INFO`, `PING`) plus its single `POST`
+method switch.
+
+This is **not** a fine-grained privilege boundary, and we deliberately do not claim
+it as one:
+
+- The proxy's method gate is all-or-nothing (`deny unless METH_GET || env(POST)`):
+ with `POST` enabled, every HTTP method — including `DELETE` — is admitted to the
+ enabled paths. Its `DELETE` env flag is dead config and is no longer set.
+- The proxy cannot scope container-create payloads (image, bind mounts, privileges).
+ A compromised API container could therefore create a container with a host
+ bind-mount, which is host-root-equivalent.
+
+Mitigations in place: the proxy is unreachable except from `openwa-api` (dedicated
+`internal: true` network), the orchestration endpoints require an ADMIN-role API key,
+teardown is allowlisted to the three managed profiles (`postgres`, `redis`, `minio`),
+and OpenWA itself never issues deletes (profile teardown is stop-only). If you do not
+use the built-in datastore orchestration (Dashboard → Infrastructure built-in
+toggles), disable the proxy entirely — see the `docker-proxy` comments in
+`docker-compose.yml`; `DockerService` then reports Docker unavailable and
+orchestration degrades gracefully.
diff --git a/docker-compose.yml b/docker-compose.yml
index d7bd3f1c0..e906f8a3f 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -15,13 +15,28 @@ services:
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
environment:
+ # Minimal set that keeps DockerService (src/modules/docker/docker.service.ts) working:
+ # PING (health), INFO (getSystemInfo), CONTAINERS (list/inspect/create/start/stop),
+ # IMAGES (pull), VOLUMES (createVolume). POST is the proxy's single all-or-nothing
+ # method gate for non-GET requests (haproxy.cfg: `deny unless METH_GET || env(POST)`).
+ # Two consequences of the pinned v0.4.2 config, accepted and documented in SECURITY.md:
+ # - its `DELETE` env flag is dead config (never read), so it is not set here; DELETE is
+ # admitted to enabled paths as a side effect of POST — OpenWA itself never issues
+ # deletes (profile teardown is stop-only, see DockerService.stopManagedService).
+ # - the proxy cannot scope container-create payloads, so a compromised API container
+ # could create containers with host bind-mounts. If you don't use the built-in
+ # datastore orchestration (Dashboard > Infrastructure built-in toggles), disable
+ # this service entirely, e.g. via a docker-compose.override.yml:
+ # services:
+ # docker-proxy:
+ # profiles: ['disabled']
+ # DockerService then reports Docker unavailable and orchestration degrades gracefully.
CONTAINERS: 1
IMAGES: 1
VOLUMES: 1
INFO: 1
PING: 1
POST: 1
- DELETE: 1
# Everything else is denied by default (AUTH, SECRETS, NETWORKS, PLUGINS, SWARM, TASKS, SERVICES, CONFIGS, NODES, DISTRIBUTIONS)
labels:
- 'com.openwa.service=docker-proxy'
@@ -185,6 +200,9 @@ services:
depends_on:
docker-proxy:
condition: service_started
+ # Not required: lets operators disable the proxy (see the docker-proxy env comment)
+ # without breaking `docker compose up`. DockerService degrades gracefully without it.
+ required: false
postgres:
condition: service_healthy
required: false
diff --git a/scripts/smoke-test-docker-proxy.sh b/scripts/smoke-test-docker-proxy.sh
index 341eb50eb..ff60deeff 100644
--- a/scripts/smoke-test-docker-proxy.sh
+++ b/scripts/smoke-test-docker-proxy.sh
@@ -40,6 +40,33 @@ if [ "$PROXY_STATE" != "running" ]; then
fi
echo "PASS: openwa-docker-proxy is running"
+echo ""
+echo "==> Verifying the proxy permits the read operations orchestration needs (from openwa-api)..."
+# openwa-api is the only container that can reach docker-proxy:2375 (internal network), so
+# the ACL is exercised from inside it. Node's global fetch (Node 18+) avoids a curl dependency.
+for endpoint in _ping containers/json; do
+ CODE=$(docker exec openwa-api node -e "fetch('http://docker-proxy:2375/$endpoint').then(r=>console.log(r.status)).catch(()=>console.log(0))" 2>/dev/null || echo 0)
+ if [ "$CODE" != "200" ]; then
+ echo "FAIL: GET /$endpoint via proxy returned HTTP $CODE (expected 200)" >&2
+ exit 1
+ fi
+ echo "PASS: GET /$endpoint via proxy -> 200"
+done
+
+echo ""
+echo "==> Verifying a denied endpoint family stays denied (GET /networks must be 403)..."
+CODE=$(docker exec openwa-api node -e "fetch('http://docker-proxy:2375/networks').then(r=>console.log(r.status)).catch(()=>console.log(0))" 2>/dev/null || echo 0)
+if [ "$CODE" != "403" ]; then
+ echo "FAIL: GET /networks via proxy returned HTTP $CODE (expected 403)" >&2
+ exit 1
+fi
+echo "PASS: GET /networks via proxy -> 403 (denied)"
+# NOTE: there is intentionally no "DELETE is rejected" check. With POST=1 the pinned proxy
+# (tecnativa/docker-socket-proxy v0.4.2) admits EVERY method to the enabled paths — its
+# DELETE env flag is dead config — so such a check would fail against the working
+# configuration. OpenWA itself never issues deletes (profile teardown is stop-only);
+# see SECURITY.md "Docker socket proxy — scope and residual risk".
+
echo ""
echo "==> Verifying openwa-api socket mount is gone..."
SOCKET_MOUNT=$(docker inspect openwa-api --format='{{range .Mounts}}{{.Source}}{{"\n"}}{{end}}' 2>/dev/null | grep "docker.sock" || true)
diff --git a/src/modules/docker/docker.service.spec.ts b/src/modules/docker/docker.service.spec.ts
index 90a334ae2..7a14c568b 100644
--- a/src/modules/docker/docker.service.spec.ts
+++ b/src/modules/docker/docker.service.spec.ts
@@ -71,6 +71,64 @@ describe('DockerService.buildDockerOptions', () => {
});
});
+describe('DockerService.stopManagedService (stop-only teardown)', () => {
+ // Teardown is deliberately stop-only: the pinned docker-socket-proxy v0.4.2 never reads its
+ // DELETE env flag (deletion is admitted only as an undocumented side effect of its POST
+ // method gate), so the code must not depend on container.remove() at all.
+ const makeService = (container: unknown) => {
+ const service = new DockerService();
+ const getContainerByService = jest.spyOn(service, 'getContainerByService').mockResolvedValue(container as never);
+ return { service, getContainerByService };
+ };
+
+ it('maps the profile to its service label and stops a running container without removing it', async () => {
+ const container = {
+ inspect: jest.fn().mockResolvedValue({ State: { Running: true } }),
+ stop: jest.fn().mockResolvedValue(undefined),
+ remove: jest.fn(),
+ };
+ const { service, getContainerByService } = makeService(container);
+
+ await expect(service.stopManagedService('postgres')).resolves.toBe(true);
+
+ expect(getContainerByService).toHaveBeenCalledWith('database');
+ expect(container.stop).toHaveBeenCalledTimes(1);
+ expect(container.remove).not.toHaveBeenCalled();
+ });
+
+ it('leaves an already-stopped container alone (no stop, no remove)', async () => {
+ const container = {
+ inspect: jest.fn().mockResolvedValue({ State: { Running: false } }),
+ stop: jest.fn(),
+ remove: jest.fn(),
+ };
+ const { service } = makeService(container);
+
+ await expect(service.stopManagedService('redis')).resolves.toBe(true);
+
+ expect(container.stop).not.toHaveBeenCalled();
+ expect(container.remove).not.toHaveBeenCalled();
+ });
+
+ it('returns true when the container is already gone', async () => {
+ const { service } = makeService(null);
+ await expect(service.stopManagedService('minio')).resolves.toBe(true);
+ });
+
+ it('reports failure honestly when stop fails (and still never removes)', async () => {
+ const container = {
+ inspect: jest.fn().mockResolvedValue({ State: { Running: true } }),
+ stop: jest.fn().mockRejectedValue(new Error('daemon gone')),
+ remove: jest.fn(),
+ };
+ const { service } = makeService(container);
+
+ await expect(service.stopManagedService('postgres')).resolves.toBe(false);
+
+ expect(container.remove).not.toHaveBeenCalled();
+ });
+});
+
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 —
diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.ts
index 2c19d49b2..ecad0378c 100644
--- a/src/modules/docker/docker.service.ts
+++ b/src/modules/docker/docker.service.ts
@@ -2,8 +2,8 @@ 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.
+ * The only Docker profiles OpenWA manages (and may start/stop). Used to bound teardown so a
+ * caller-supplied profile name can never reach stopManagedService for an unrelated container.
*/
export const MANAGED_DOCKER_PROFILES: readonly string[] = ['postgres', 'redis', 'minio'];
@@ -20,7 +20,6 @@ interface OrchestrationResult {
message: string;
containersStarted: string[];
containersStopped: string[];
- containersRemoved: string[];
errors: string[];
estimatedTime: number; // Estimated restart time in seconds
}
@@ -426,42 +425,32 @@ export class DockerService implements OnModuleInit {
}
/**
- * Stop and remove a container by service name to save space
+ * Stop a managed profile's container and RETAIN it for a later re-enable.
+ *
+ * Deliberately stop-only — no `container.remove()`. The bundled docker-socket-proxy
+ * (tecnativa/docker-socket-proxy, pinned v0.4.2) never reads its `DELETE` env flag: its
+ * haproxy.cfg method gate is `deny unless METH_GET || env(POST)`, so container deletion is
+ * admitted only as an undocumented side effect of POST being enabled — a contract any proxy
+ * upgrade may withdraw. Stopping needs nothing beyond POST /containers/{id}/stop, which the
+ * orchestration feature already requires, and retention is what the disable→re-enable flow
+ * wants anyway: the named data volume and container config survive, and
+ * startService()/createService() simply restart the retained container. Stop-only is also
+ * strictly less destructive (a remove with `v: true` discards anonymous volumes).
+ *
+ * Caveat: a retained container keeps its original env. If the service's credentials changed
+ * while it was disabled, remove the container from the host (`docker rm <name>`) before
+ * re-enabling so it is recreated fresh. To reclaim disk space, likewise remove it manually.
*/
- async removeService(profile: string): Promise<boolean> {
- this.logger.log(`Removing service with profile: ${profile}`);
+ async stopManagedService(profile: string): Promise<boolean> {
+ this.logger.log(`Stopping service with profile: ${profile} (container retained, not removed)`);
- // First try to get the container and remove via dockerode
const serviceMap: Record<string, string> = {
postgres: 'database',
redis: 'cache',
minio: 'storage',
};
- const service = serviceMap[profile] || profile;
- const container = await this.getContainerByService(service);
-
- if (container) {
- try {
- const info = await container.inspect();
- if (info.State.Running) {
- await container.stop();
- this.logger.log(`Stopped container: ${profile}`);
- }
- // v: true removes only the container's ANONYMOUS volumes; named datastore volumes
- // (redis/postgres/minio data) are preserved, so disable + re-enable keeps the data.
- await container.remove({ v: true });
- this.logger.log(`Removed container: ${profile}`);
- return true;
- } catch (error) {
- this.logger.error(`Failed to remove container: ${error instanceof Error ? error.message : error}`);
- return false;
- }
- }
-
- // Container doesn't exist - that's fine for removal
- this.logger.log(`Container for service '${profile}' not found, nothing to remove`);
- return true;
+ return this.stopService(serviceMap[profile] || profile);
}
/**
@@ -507,7 +496,6 @@ export class DockerService implements OnModuleInit {
message: '',
containersStarted: [],
containersStopped: [],
- containersRemoved: [],
errors: [],
estimatedTime,
};
diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.ts
index cdc00b765..a7fecc2b7 100644
--- a/src/modules/infra/infra.controller.spec.ts
+++ b/src/modules/infra/infra.controller.spec.ts
@@ -1127,21 +1127,42 @@ describe('InfraController.requestRestart constrains teardown to managed profiles
{ shutdown: jest.fn() } as never, // shutdownService
);
- it('removes only allowlisted profiles, never an unknown or empty entry', async () => {
- const removeService = jest.fn().mockResolvedValue(true);
+ it('tears down only allowlisted profiles, never an unknown or empty entry', async () => {
+ const stopManagedService = jest.fn().mockResolvedValue(true);
const controller = buildController({
isDockerAvailable: () => true,
- removeService,
+ stopManagedService,
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');
+ const torn = stopManagedService.mock.calls.map(call => String((call as unknown[])[0])).sort();
+ expect(torn).toEqual(['postgres', 'redis']);
+ expect(torn).not.toContain('');
+ expect(torn).not.toContain('evil');
+ });
+
+ it('reports teardown as stopped-not-removed, with honest per-profile errors', async () => {
+ const stopManagedService = jest
+ .fn()
+ .mockResolvedValueOnce(true) // postgres stops cleanly
+ .mockResolvedValueOnce(false); // redis fails
+ const controller = buildController({
+ isDockerAvailable: () => true,
+ stopManagedService,
+ orchestrateProfiles: jest.fn().mockResolvedValue({}),
+ });
+
+ const result = await controller.requestRestart({ profilesToRemove: ['postgres', 'redis'] });
+
+ // Teardown is stop-only (containers are retained, never deleted) — the payload must say so.
+ expect(result.removal).toEqual({
+ stopped: ['postgres'],
+ errors: ['Failed to stop redis'],
+ });
+ expect(JSON.stringify(result.removal)).not.toContain('removed');
});
});
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index af8817c4f..2813438b9 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -1004,7 +1004,9 @@ export class InfraController {
const profiles = body?.profiles || [];
const profilesToRemove = body?.profilesToRemove || [];
let orchestrationResult: object | undefined;
- let removalResult: { removed: string[]; errors: string[] } | undefined;
+ // Teardown is stop-only (see DockerService.stopManagedService): containers are stopped and
+ // retained for re-enable, never deleted — the result below reports exactly that.
+ let removalResult: { stopped: string[]; errors: string[] } | undefined;
this.logger.log('Restart requested', { profiles });
this.logger.log('Profiles to remove', { profilesToRemove });
@@ -1018,7 +1020,7 @@ export class InfraController {
// away from a built-in backend and then reloading the page before restarting can leave the old
// container running until the next explicit change.)
// 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
+ // would otherwise reach stopManagedService 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));
@@ -1027,24 +1029,24 @@ export class InfraController {
this.logger.warn('Ignoring non-managed profiles in profilesToRemove', { ignored });
}
- // First, remove containers for disabled services
+ // First, stop containers for disabled services (stop-only: retained, never deleted)
if (toRemove.length > 0) {
- this.logger.log('Removing disabled profiles...', { toRemove });
- removalResult = { removed: [], errors: [] };
+ this.logger.log('Stopping disabled profiles (containers retained)...', { toRemove });
+ removalResult = { stopped: [], errors: [] };
for (const profile of toRemove) {
try {
- const success = await this.dockerService.removeService(profile);
+ const success = await this.dockerService.stopManagedService(profile);
if (success) {
- removalResult.removed.push(profile);
+ removalResult.stopped.push(profile);
} else {
- removalResult.errors.push(`Failed to remove ${profile}`);
+ removalResult.errors.push(`Failed to stop ${profile}`);
}
} catch (err) {
- removalResult.errors.push(`Error removing ${profile}: ${err}`);
+ removalResult.errors.push(`Error stopping ${profile}: ${err}`);
}
}
- this.logger.log('Removal result', { removalResult });
+ this.logger.log('Teardown result', { removalResult });
}
// Then, start containers for enabled services