Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): ignore inherited object names as restart profiles
Yudhi Armyndharis24117506d0e2
diff --git a/dashboard/src/utils/bundledHost.test.ts b/dashboard/src/utils/bundledHost.test.tsindex f362b25a6..ede5e994c 100644--- a/dashboard/src/utils/bundledHost.test.ts+++ b/dashboard/src/utils/bundledHost.test.ts@@ -5,6 +5,8 @@ import { namesBundledContainer as serverRule } from '../../../src/modules/dockerimport { HOST_SPELLINGS, type ServiceName } from '../../../test/fixtures/builtin-mode-cases.ts';const PROFILE: Record<ServiceName, string> = { database: 'postgres', redis: 'redis', storage: 'minio' };+// Names every object inherits, which are no profile.+const INHERITED = ['constructor', '__proto__', 'toString', 'hasOwnProperty', 'valueOf'];// Every host spelling the shared table lists, plus generated ones: letter cases, trailing dots and spaces around the// alias, the container name and a few other names, bare and inside endpoint URLs.@@ -18,13 +20,14 @@ function candidates(): string[] {),);const listed = Object.values(HOST_SPELLINGS).flatMap(s => [...s.reach, ...s.elsewhere]);- return [...new Set([...listed, ...hosts, ...urls, '', ' ', 'not a url'])];+ const inherited = INHERITED.flatMap(n => [n, `openwa-${n}`, `http://${n}:9000`]);+ return [...new Set([...listed, ...hosts, ...urls, ...inherited, '', ' ', 'not a url'])];}test('the page reads every host spelling the way the server does', () => {const values = candidates();let compared = 0;- for (const profile of ['postgres', 'redis', 'minio', 'other']) {+ for (const profile of ['postgres', 'redis', 'minio', 'other', ...INHERITED]) {for (const value of [...values, undefined]) {assert.equal(namesBundledContainer(profile, value),@@ -47,6 +50,15 @@ test('the shared spellings reach the bundled container, the others do not', () =}});+test('a name every object inherits is no profile, on the page and on the server', () => {+ for (const name of INHERITED) {+ for (const host of [name, `openwa-${name}`]) {+ assert.equal(namesBundledContainer(name, host), false, `page ${name} ${host}`);+ assert.equal(serverRule(name, host), false, `server ${name} ${host}`);+ }+ }+});+test('two spellings of the bundled container are the same host, other hosts only when equal', () => {assert.ok(sameHost('postgres', 'postgres', 'OpenWA-Postgres.'));assert.ok(sameHost('minio', 'http://minio:9000', 'http://MINIO:9000/'));diff --git a/dashboard/src/utils/bundledHost.ts b/dashboard/src/utils/bundledHost.tsindex 3980532f5..b717204fb 100644--- a/dashboard/src/utils/bundledHost.ts+++ b/dashboard/src/utils/bundledHost.ts@@ -1,9 +1,10 @@-// The container each managed profile runs, as the restart dialog names it.-export const CONTAINER_OF: Record<string, string> = {+// The container each managed profile runs, as the restart dialog names it. No prototype, as the server's table: a+// name such as `constructor` finds nothing.+export const CONTAINER_OF: Record<string, string> = Object.assign(Object.create(null) as Record<string, string>, {postgres: 'openwa-postgres',redis: 'openwa-redis',minio: 'openwa-minio',-};+});/*** Whether a host (for minio, the host of an S3 endpoint) reaches the profile's bundled container: its network aliasdiff --git a/src/modules/docker/bundled-host.ts b/src/modules/docker/bundled-host.tsindex 3dbc116fb..76479bb04 100644--- a/src/modules/docker/bundled-host.ts+++ b/src/modules/docker/bundled-host.ts@@ -1,9 +1,15 @@-/** The env key and value that point the app at each managed profile's bundled container. */-export const BUNDLED_SERVICE_ENV: Record<string, [string, string]> = {- postgres: ['DATABASE_HOST', 'postgres'],- redis: ['REDIS_HOST', 'redis'],- minio: ['S3_ENDPOINT', 'http://minio:9000'],-};+/**+ * The env key and value that point the app at each managed profile's bundled container. Looked up by the profile names+ * a restart request carries, so it has no prototype: a name such as `constructor` finds nothing, like any other.+ */+export const BUNDLED_SERVICE_ENV: Record<string, [string, string]> = Object.assign(+ Object.create(null) as Record<string, [string, string]>,+ {+ postgres: ['DATABASE_HOST', 'postgres'],+ redis: ['REDIS_HOST', 'redis'],+ minio: ['S3_ENDPOINT', 'http://minio:9000'],+ },+);/*** Whether a host (for minio, the host of an S3 endpoint) reaches the profile's bundled container: its network aliasdiff --git a/src/modules/infra/infra-config.controller.spec.ts b/src/modules/infra/infra-config.controller.spec.tsindex 7de330ad6..90520af25 100644--- a/src/modules/infra/infra-config.controller.spec.ts+++ b/src/modules/infra/infra-config.controller.spec.ts@@ -26,10 +26,17 @@ jest.mock('../../config/storage-root', () => {return { ...actual, resolveStorageRoot: jest.fn((options: { configured?: string }) => options.configured ?? '') };});-import { BadRequestException } from '@nestjs/common';+import type { Server } from 'http';+import { BadRequestException, type INestApplication } from '@nestjs/common';+import { Test } from '@nestjs/testing';import { plainToInstance } from 'class-transformer';import { validate } from 'class-validator';+import request from 'supertest';import { InfraConfigController } from './infra-config.controller';+import { applyGlobalValidation } from '../../config/app-validation';+import { ShutdownService } from '../../common/services/shutdown.service';+import { EngineFactory } from '../../engine/engine.factory';+import { DockerService } from '../docker';import { SaveConfigDto } from './dto/save-config.dto';import { AuditAction } from '../audit/entities/audit-log.entity';import { recordOsEnvKeys, recordPinnedEnvKeys } from '../../config/env-precedence';@@ -2086,6 +2093,46 @@ describe('InfraConfigController.requestRestart constrains teardown to managed prexpect(JSON.stringify(result.removal)).not.toContain('removed');});+ // A name every object inherits is no profile either: it is ignored like any other unknown name, and the managed+ // names beside it still act.+ describe('POST /api/infra/restart with a profile name an object inherits', () => {+ const stopManagedService = jest.fn().mockResolvedValue(true);+ const orchestrateProfiles = jest.fn().mockResolvedValue({});+ let app: INestApplication;++ beforeAll(async () => {+ const moduleRef = await Test.createTestingModule({+ controllers: [InfraConfigController],+ providers: [+ { provide: EngineFactory, useValue: {} },+ {+ provide: DockerService,+ useValue: { isDockerAvailable: () => true, stopManagedService, orchestrateProfiles },+ },+ { provide: ShutdownService, useValue: { shutdown: jest.fn() } },+ ],+ }).compile();+ app = moduleRef.createNestApplication({ logger: false });+ applyGlobalValidation(app);+ await app.init();+ });+ afterAll(() => app.close());+ beforeEach(() => {+ stopManagedService.mockClear();+ orchestrateProfiles.mockClear();+ });++ it.each(['constructor', '__proto__', 'toString', 'hasOwnProperty', 'valueOf'])('ignores %s', async name => {+ const res = await request(app.getHttpServer() as Server)+ .post('/api/infra/restart')+ .send({ profiles: [name, 'redis'], profilesToRemove: [name, 'postgres'] });++ expect(res.status).toBe(200);+ expect(orchestrateProfiles.mock.calls).toEqual([[['redis']]]);+ expect(stopManagedService.mock.calls).toEqual([['postgres']]);+ });+ });+describe('a service the environment pins the app to', () => {const KEYS = ['DATABASE_HOST', 'REDIS_HOST', 'S3_ENDPOINT'];let savedEnv: Array<[string, string | undefined]>;