Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(docker,docs): align managed container specs with compose and refresh supported versions (#968)
Yudhi Armyndharisa15d0feb6e23
diff --git a/SECURITY.md b/SECURITY.mdindex fab9de4ec..ed74724dc 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -6,12 +6,13 @@ socket. Security matters here, and we appreciate responsible disclosure.## Supported versions-Security fixes land on the latest minor release. Please upgrade older deployments.+Security fixes land on the latest minor release (currently 0.10.x). Older minor+lines receive no backports — please upgrade older deployments.| Version | Supported || ------- | ------------------ |-| 0.8.x | :white_check_mark: |-| < 0.8 | :x: |+| 0.10.x | :white_check_mark: |+| < 0.10 | :x: |## Reporting a vulnerabilitydiff --git a/src/modules/docker/compose-parity.spec.ts b/src/modules/docker/compose-parity.spec.tsnew file mode 100644index 000000000..50621e250--- /dev/null+++ b/src/modules/docker/compose-parity.spec.ts@@ -0,0 +1,281 @@+import { readFileSync } from 'fs';+import { join } from 'path';+import { DockerService, MANAGED_DOCKER_PROFILES } from './docker.service';++// js-yaml has no bundled types here; require + cast (matches the compose-network.spec.ts pattern).+// eslint-disable-next-line @typescript-eslint/no-require-imports+const yaml = require('js-yaml') as { load: (src: string) => unknown };++interface ComposeHealthcheck {+ test: string[];+ interval: string;+ timeout: string;+ retries: number;+}++interface ComposeService {+ image: string;+ container_name: string;+ profiles?: string[];+ restart?: string;+ networks?: string[];+ security_opt?: string[];+ environment?: Record<string, string>;+ command?: string;+ volumes?: string[];+ ports?: string[];+ labels?: string[];+ healthcheck?: ComposeHealthcheck;+ mem_limit?: string;+ pids_limit?: number;+ deploy?: unknown;+}++interface ComposeFile {+ services: Record<string, ComposeService>;+ volumes: Record<string, { name?: string }>;+ networks: Record<string, { name?: string }>;+}++/** The subset of Docker.ContainerCreateOptions that createService populates from a spec. */+interface CapturedConfig {+ name: string;+ Image: string;+ Cmd?: string[];+ Env?: string[];+ Labels: Record<string, string>;+ HostConfig: {+ NetworkMode: string;+ RestartPolicy: { Name: string };+ Binds?: string[];+ SecurityOpt?: string[];+ PortBindings?: Record<string, { HostIp: string; HostPort: string }[]>;+ Memory?: number;+ NanoCpus?: number;+ PidsLimit?: number;+ };+ Healthcheck?: { Test: string[]; Interval: number; Timeout: number; Retries: number };+ NetworkingConfig: { EndpointsConfig: Record<string, { Aliases: string[] }> };+}++const PROFILES = ['postgres', 'redis', 'minio'] as const;++const VOLUME_PATH: Record<string, string> = {+ postgres: '/var/lib/postgresql/data',+ redis: '/data',+ minio: '/data',+};++/** Compose durations are strings like '5s'; the Docker API wants nanoseconds. */+const seconds = (v: string): number => {+ const m = /^(\d+)s$/.exec(v);+ if (!m) throw new Error(`unexpected compose duration: ${v}`);+ return parseInt(m[1], 10) * 1e9;+};++const labelsToMap = (list: string[]): Record<string, string> =>+ Object.fromEntries(list.map(l => l.split('=') as [string, string]));++/**+ * Runs createService against a fake daemon and returns the exact ContainerCreateOptions the+ * profile's spec produces — parity is asserted on what would actually be sent to the daemon.+ */+async function capture(profile: string): Promise<CapturedConfig> {+ const service = new DockerService();+ jest.spyOn(service, 'getContainerByService').mockResolvedValue(null);+ let captured: CapturedConfig | undefined;+ const fakeDocker = {+ pull: (_image: string, cb: (err: Error | null, stream: null) => void) => cb(null, null),+ modem: { followProgress: (_stream: null, cb: (err: Error | null) => void) => cb(null) },+ createVolume: jest.fn().mockResolvedValue({}),+ createContainer: (config: CapturedConfig) => {+ captured = config;+ return Promise.resolve({ start: () => Promise.resolve() });+ },+ };+ Object.assign(service as unknown as Record<string, unknown>, { docker: fakeDocker, isAvailable: true });+ await service.createService(profile);+ if (!captured) throw new Error(`createService(${profile}) never created a container`);+ return captured;+}++/**+ * Regression lock: the Docker-API orchestration path (DockerService.getContainerSpec) must stay+ * in parity with the equivalent services in docker-compose.yml. Reads the real compose file so a+ * drift on EITHER side fails here. Deliberate differences (built-in credentials, the postgres+ * init-script mount) are locked too — see the getContainerSpec docblock for the rationale.+ */+describe('DockerService managed specs ↔ docker-compose.yml parity', () => {+ const compose = yaml.load(readFileSync(join(__dirname, '../../../docker-compose.yml'), 'utf8')) as ComposeFile;++ // getContainerSpec reads the S3 credential env vars at call time; scrub them so the+ // default-fallback assertions don't depend on the developer's shell.+ const S3_VARS = ['S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY', 'S3_ACCESS_KEY', 'S3_SECRET_KEY'];+ let savedEnv: Record<string, string | undefined> = {};+ beforeEach(() => {+ savedEnv = {};+ for (const k of S3_VARS) {+ savedEnv[k] = process.env[k];+ delete process.env[k];+ }+ });+ afterEach(() => {+ for (const k of S3_VARS) {+ if (savedEnv[k] === undefined) delete process.env[k];+ else process.env[k] = savedEnv[k];+ }+ });++ it('the managed profiles are exactly the compose services labeled as built-in', () => {+ const builtin = Object.entries(compose.services)+ .filter(([, svc]) => (svc.labels ?? []).includes('com.openwa.builtin=true'))+ .map(([name]) => name)+ .sort();+ expect([...MANAGED_DOCKER_PROFILES].sort()).toEqual(builtin);+ for (const profile of MANAGED_DOCKER_PROFILES) {+ expect(compose.services[profile].profiles).toContain(profile);+ }+ });++ it.each(PROFILES)('%s: pins the exact compose image and container name', async profile => {+ const cfg = await capture(profile);+ expect(cfg.Image).toBe(compose.services[profile].image);+ expect(cfg.Image).toContain(':'); // an explicit tag, never the floating default+ expect(cfg.name).toBe(compose.services[profile].container_name);+ });++ it.each(PROFILES)('%s: attaches to the fixed openwa-network like the compose service', async profile => {+ const cfg = await capture(profile);+ expect(cfg.HostConfig.NetworkMode).toBe('openwa-network');+ expect(compose.networks['openwa-network'].name).toBe('openwa-network');+ expect(compose.services[profile].networks).toContain('openwa-network');+ // Compose DNS resolves peers by service name; the Docker-API path adds it as an alias.+ expect(cfg.NetworkingConfig.EndpointsConfig['openwa-network'].Aliases).toContain(profile);+ });++ it.each(PROFILES)('%s: uses the same restart policy as compose', async profile => {+ const cfg = await capture(profile);+ expect(compose.services[profile].restart).toBe('unless-stopped');+ expect(cfg.HostConfig.RestartPolicy).toEqual({ Name: 'unless-stopped' });+ });++ it.each(PROFILES)('%s: carries the same labels as the compose service', async profile => {+ const cfg = await capture(profile);+ expect(cfg.Labels).toEqual(labelsToMap(compose.services[profile].labels ?? []));+ });++ it.each(PROFILES)('%s: applies the same no-new-privileges hardening as compose', async profile => {+ const cfg = await capture(profile);+ expect(compose.services[profile].security_opt).toContain('no-new-privileges:true');+ expect(cfg.HostConfig.SecurityOpt).toEqual(compose.services[profile].security_opt);+ });++ it.each(PROFILES)('%s: binds the same pinned named volume as compose', async profile => {+ const cfg = await capture(profile);+ const composeVol = `${profile}-data`;+ expect(compose.services[profile].volumes).toContain(`${composeVol}:${VOLUME_PATH[profile]}`);+ // The compose volume name is pinned to the literal name the Docker-API path binds.+ expect(compose.volumes[composeVol].name).toBe(`openwa_${composeVol}`);+ expect(cfg.HostConfig.Binds).toEqual([`openwa_${composeVol}:${VOLUME_PATH[profile]}`]);+ });++ it.each(PROFILES)('%s: matches the compose healthcheck timing', async profile => {+ const cfg = await capture(profile);+ const hc = compose.services[profile].healthcheck!;+ expect(cfg.Healthcheck).toMatchObject({+ Interval: seconds(hc.interval),+ Timeout: seconds(hc.timeout),+ Retries: hc.retries,+ });+ });++ it.each(PROFILES)('%s: sets no CPU/memory/PID limits on either path (only openwa-api is limited)', async profile => {+ const svc = compose.services[profile];+ expect(svc.mem_limit).toBeUndefined();+ expect(svc.pids_limit).toBeUndefined();+ expect(svc.deploy).toBeUndefined();+ const cfg = await capture(profile);+ expect(cfg.HostConfig.Memory).toBeUndefined();+ expect(cfg.HostConfig.NanoCpus).toBeUndefined();+ expect(cfg.HostConfig.PidsLimit).toBeUndefined();+ });++ it('postgres: provisions the fixed built-in credentials; compose defaults agree on user/db only', async () => {+ const cfg = await capture('postgres');+ expect(cfg.Env).toEqual(['POSTGRES_USER=openwa', 'POSTGRES_PASSWORD=openwa', 'POSTGRES_DB=openwa']);+ const env = compose.services.postgres.environment!;+ // Compose is the manual operator path: same user/db defaults, but deliberately NO default+ // password (the image fails fast on an empty one). The orchestrated built-in path instead+ // provisions the fixed credential the production boot guard exempts for the built-in,+ // internal-host deployment (see the getContainerSpec docblock).+ expect(env.POSTGRES_USER).toBe('${DATABASE_USERNAME:-openwa}');+ expect(env.POSTGRES_DB).toBe('${DATABASE_NAME:-openwa}');+ expect(env.POSTGRES_PASSWORD).toBe('${DATABASE_PASSWORD:-}');+ });++ it('postgres: healthcheck resolves to the same pg_isready command as compose', async () => {+ const cfg = await capture('postgres');+ const composeTest = compose.services.postgres.healthcheck!.test;+ // Compose interpolates the manual-path user default; the built-in user is always openwa.+ expect(cfg.Healthcheck!.Test[0]).toBe(composeTest[0]);+ expect(cfg.Healthcheck!.Test[1]).toBe(composeTest[1].replace('${DATABASE_USERNAME:-openwa}', 'openwa'));+ });++ it('postgres: publishes no host ports, like compose', async () => {+ const cfg = await capture('postgres');+ expect(compose.services.postgres.ports).toBeUndefined();+ expect(cfg.HostConfig.PortBindings).toBeUndefined();+ });++ it('redis: runs the same command and healthcheck, with no credentials, like compose', async () => {+ const cfg = await capture('redis');+ expect(cfg.Cmd?.join(' ')).toBe(compose.services.redis.command);+ expect(cfg.Healthcheck!.Test).toEqual(compose.services.redis.healthcheck!.test);+ expect(compose.services.redis.environment).toBeUndefined();+ expect(cfg.Env).toBeUndefined();+ });++ it('redis: publishes no host ports, like compose', async () => {+ const cfg = await capture('redis');+ expect(compose.services.redis.ports).toBeUndefined();+ expect(cfg.HostConfig.PortBindings).toBeUndefined();+ });++ it('minio: runs the same server command and healthcheck as compose', async () => {+ const cfg = await capture('minio');+ // Compose quotes the console address; the argv form needs no quotes.+ expect(cfg.Cmd?.join(' ')).toBe(compose.services.minio.command!.replace(/"/g, ''));+ expect(cfg.Healthcheck!.Test).toEqual(compose.services.minio.healthcheck!.test);+ });++ it('minio: falls back to the fixed built-in credentials the dashboard saves', async () => {+ const cfg = await capture('minio');+ expect(cfg.Env).toEqual(['MINIO_ROOT_USER=minioadmin', 'MINIO_ROOT_PASSWORD=minioadmin']);+ const env = compose.services.minio.environment!;+ // Compose (manual path) deliberately ships no default and fails fast on empty creds; the+ // orchestrated path provisions the built-in default instead (see the getContainerSpec docblock).+ expect(env.MINIO_ROOT_USER).toBe('${S3_ACCESS_KEY_ID:-${S3_ACCESS_KEY:-}}');+ expect(env.MINIO_ROOT_PASSWORD).toBe('${S3_SECRET_ACCESS_KEY:-${S3_SECRET_KEY:-}}');+ });++ it('minio: prefers the canonical S3 credential env vars, then the legacy ones', async () => {+ process.env.S3_ACCESS_KEY = 'legacy-user';+ process.env.S3_SECRET_KEY = 'legacy-secret';+ let cfg = await capture('minio');+ expect(cfg.Env).toEqual(['MINIO_ROOT_USER=legacy-user', 'MINIO_ROOT_PASSWORD=legacy-secret']);++ process.env.S3_ACCESS_KEY_ID = 'canonical-user';+ process.env.S3_SECRET_ACCESS_KEY = 'canonical-secret';+ cfg = await capture('minio');+ expect(cfg.Env).toEqual(['MINIO_ROOT_USER=canonical-user', 'MINIO_ROOT_PASSWORD=canonical-secret']);+ });++ it('minio: publishes the same localhost-only ports as compose', async () => {+ const cfg = await capture('minio');+ expect(compose.services.minio.ports).toEqual(['127.0.0.1:9000:9000', '127.0.0.1:9001:9001']);+ expect(cfg.HostConfig.PortBindings).toEqual({+ '9000/tcp': [{ HostIp: '127.0.0.1', HostPort: '9000' }],+ '9001/tcp': [{ HostIp: '127.0.0.1', HostPort: '9001' }],+ });+ });+});diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.tsindex ecad0378c..52ad7df80 100644--- a/src/modules/docker/docker.service.ts+++ b/src/modules/docker/docker.service.ts@@ -204,8 +204,24 @@ export class DockerService implements OnModuleInit {}/**- * Container specifications for optional services- * Mirrors docker-compose.yml settings but uses Docker API directly+ * Container specifications for the three managed profiles, kept in parity with the matching+ * services in docker-compose.yml (same image pin, container/volume/network names, command,+ * healthcheck, labels, restart policy, no-new-privileges). compose-parity.spec.ts is the+ * regression lock: it reads docker-compose.yml and fails when either side drifts.+ *+ * Deliberate differences from the compose services — do not "fix" these:+ * - Credentials: the compose services are the MANUAL operator path and deliberately ship no+ * default secret (empty POSTGRES_PASSWORD / MINIO_ROOT_* fail fast on boot). The specs below+ * are the dashboard built-in path: they provision the fixed built-in credentials+ * (openwa/openwa, minioadmin/minioadmin) that infra.controller writes to data/.env.generated+ * and that the production boot guard (bootstrap-security.ts) exempts only while the+ * *_BUILTIN flag is set AND the datastore host resolves to the internal-only container.+ * - Postgres init script: compose bind-mounts scripts/postgres-init-schema.sh from the host+ * checkout to support a custom POSTGRES_SCHEMA. The Docker-API path cannot know a host path+ * to mount, and the built-in flow always pins POSTGRES_SCHEMA=public, so no init script (or+ * POSTGRES_SCHEMA env) is set here.+ * - Resource limits: neither path sets CPU/memory/PID limits on the datastore containers;+ * only openwa-api carries mem_limit/pids_limit (in compose).*/private getContainerSpec(profile: string): {image: string;@@ -217,6 +233,7 @@ export class DockerService implements OnModuleInit {healthcheck?: { test: string[]; interval: number; timeout: number; retries: number };labels: Record<string, string>;ports?: { container: number; host: number }[];+ securityOpt: string[];} | null {const specs: Record<string, ReturnType<typeof this.getContainerSpec>> = {redis: {@@ -235,12 +252,15 @@ export class DockerService implements OnModuleInit {'com.openwa.service': 'cache','com.openwa.builtin': 'true',},+ securityOpt: ['no-new-privileges:true'],},postgres: {image: 'postgres:16-alpine',name: 'openwa-postgres',alias: 'postgres',- // Use hardcoded defaults for built-in container (don't inherit SQLite paths)+ // Fixed built-in credentials — the dashboard saves these same values to+ // data/.env.generated (infra.controller) and the production boot guard exempts them only+ // for the built-in, internal-host deployment (see the getContainerSpec docblock).env: ['POSTGRES_USER=openwa', 'POSTGRES_PASSWORD=openwa', 'POSTGRES_DB=openwa'],volumes: [{ name: 'openwa_postgres-data', path: '/var/lib/postgresql/data' }],healthcheck: {@@ -253,9 +273,11 @@ export class DockerService implements OnModuleInit {'com.openwa.service': 'database','com.openwa.builtin': 'true',},+ securityOpt: ['no-new-privileges:true'],},minio: {- image: 'minio/minio',+ // Same pin as the compose minio service — never track the floating `latest` tag.+ image: 'minio/minio:RELEASE.2025-09-07T16-13-09Z',name: 'openwa-minio',alias: 'minio',cmd: ['server', '/data', '--console-address', ':9001'],@@ -280,6 +302,7 @@ export class DockerService implements OnModuleInit {'com.openwa.service': 'storage','com.openwa.builtin': 'true',},+ securityOpt: ['no-new-privileges:true'],},};return specs[profile] || null;@@ -352,6 +375,7 @@ export class DockerService implements OnModuleInit {NetworkMode: 'openwa-network',RestartPolicy: { Name: 'unless-stopped' },Binds: spec.volumes?.map(v => `${v.name}:${v.path}`),+ SecurityOpt: spec.securityOpt,PortBindings: spec.ports?.reduce<Record<string, { HostIp: string; HostPort: string }[]>>((acc, p) => {acc[`${p.container}/tcp`] = [{ HostIp: '127.0.0.1', HostPort: p.host.toString() }];return acc;