Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test,ci: coverage denominators, chain-boot e2e, and a migration drift gate

Yudhi Armyndharis8e7a4f83b92f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0659cc858..50eccac92 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Test and DB infrastructure: the 23 file-reading specs are excluded from the unit coverage denominators (spec files were counted as 0%-covered source, ~994 lines inflating every floor), an e2e boots the production SQLite schema from scratch through both full migration chains (the path the other suites' synchronize=true never touches), and a drift gate derives the chain-vs-entity diff so a missing index, column, or constraint fails while the known column-type rebuild is pinned as a visible baseline.
- The ingress route's rate bound is the per-instance limit alone: the global per-IP medium tier (100/min, below the instance default of 120/min) used to 429 every tenant of a shared-egress-IP provider before the instance bound ever fired.
- The in-flight body budget gives each client IP its own share (half the aggregate by default, keyed through TRUSTED_PROXIES): four trickle connections from one source now exhaust only that source's share instead of 503ing every body-bearing request for everyone.
- The lifecycle fences (teardown chaining, fail-closed 409, identity-checked initial-status waits, force-destroy eviction) and the status broadcaster (persist-then-mirror, transition de-dup, clear-on-delete) carry their own unit specs instead of being reachable only through the session-service suite's white-box pokes.
diff --git a/package.json b/package.json
index 9855f7a60..8a739f638 100644
--- a/package.json
+++ b/package.json
@@ -42,7 +42,7 @@
"lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.spec.js scripts/patch-wwebjs-ready-sync.spec.js scripts/patch-wwebjs-participant-arity.spec.js scripts/patch-baileys-appstate.spec.js scripts/patch-baileys-newsletter-create.spec.js scripts/dockerfile-patchers.spec.js scripts/check-upstream-surface.spec.mjs scripts/check-sdk-docs.spec.mjs scripts/check-audit.spec.mjs scripts/check-contract-shapes.spec.mjs",
- "test:docs": "jest src/common/changelog-sections.spec.ts src/common/ci-privilege-gate.spec.ts src/common/docs-ci-jobs.spec.ts src/common/docs-coverage-policy.spec.ts src/common/docs-metrics-list.spec.ts src/common/openapi/docs-06-contract.spec.ts src/common/test-lane-partition.spec.ts src/config/docs-env-example.spec.ts src/config/openapi-contract.spec.ts src/config/openapi-export-pins.spec.ts src/config/wa-web-version-example-pin.spec.ts src/engine/docs-29-counts.spec.ts src/engine/engine-inventory-parity.spec.ts src/engine/engine-parity.spec.ts src/engine/inventory-mapping-direction.spec.ts src/engine/adapters/baileys-voice-waveform.spec.ts src/engine/adapters/wwebjs-newsletter-preview.spec.ts src/modules/audit/audit-coverage.spec.ts src/modules/auth/global-route-fence-coverage.spec.ts src/modules/auth/query-session-scope-coverage.spec.ts src/modules/docker/compose-network.spec.ts src/modules/queue/bull-board-mount-coverage.spec.ts src/common/release-gate-parity.spec.ts --testPathIgnorePatterns=/node_modules/",
+ "test:docs": "jest src/common/changelog-sections.spec.ts src/common/ci-privilege-gate.spec.ts src/common/docs-ci-jobs.spec.ts src/common/docs-coverage-policy.spec.ts src/common/docs-metrics-list.spec.ts src/common/openapi/docs-06-contract.spec.ts src/common/test-lane-partition.spec.ts src/config/docs-env-example.spec.ts src/config/openapi-contract.spec.ts src/config/openapi-export-pins.spec.ts src/config/wa-web-version-example-pin.spec.ts src/engine/docs-29-counts.spec.ts src/engine/engine-inventory-parity.spec.ts src/engine/engine-parity.spec.ts src/engine/inventory-mapping-direction.spec.ts src/engine/adapters/baileys-voice-waveform.spec.ts src/engine/adapters/wwebjs-newsletter-preview.spec.ts src/modules/audit/audit-coverage.spec.ts src/modules/auth/global-route-fence-coverage.spec.ts src/modules/auth/query-session-scope-coverage.spec.ts src/modules/docker/compose-network.spec.ts src/modules/queue/bull-board-mount-coverage.spec.ts src/common/release-gate-parity.spec.ts src/database/migrations/__tests__/migration-drift.spec.ts --testPathIgnorePatterns=/node_modules/",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
@@ -147,6 +147,29 @@
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"testPathIgnorePatterns": [
+ "src/common/changelog-sections\\.spec\\.ts$",
+ "src/common/ci-privilege-gate\\.spec\\.ts$",
+ "src/common/release-gate-parity\\.spec\\.ts$",
+ "src/common/docs-ci-jobs\\.spec\\.ts$",
+ "src/common/docs-coverage-policy\\.spec\\.ts$",
+ "src/common/docs-metrics-list\\.spec\\.ts$",
+ "src/common/openapi/docs-06-contract\\.spec\\.ts$",
+ "src/common/test-lane-partition\\.spec\\.ts$",
+ "src/config/docs-env-example\\.spec\\.ts$",
+ "src/config/openapi-contract\\.spec\\.ts$",
+ "src/config/openapi-export-pins\\.spec\\.ts$",
+ "src/config/wa-web-version-example-pin\\.spec\\.ts$",
+ "src/engine/docs-29-counts\\.spec\\.ts$",
+ "src/engine/engine-inventory-parity\\.spec\\.ts$",
+ "src/engine/engine-parity\\.spec\\.ts$",
+ "src/engine/inventory-mapping-direction\\.spec\\.ts$",
+ "src/engine/adapters/baileys-voice-waveform\\.spec\\.ts$",
+ "src/engine/adapters/wwebjs-newsletter-preview\\.spec\\.ts$",
+ "src/modules/audit/audit-coverage\\.spec\\.ts$",
+ "src/modules/auth/global-route-fence-coverage\\.spec\\.ts$",
+ "src/modules/auth/query-session-scope-coverage\\.spec\\.ts$",
+ "src/modules/docker/compose-network\\.spec\\.ts$",
+ "src/modules/queue/bull-board-mount-coverage\\.spec\\.ts$",
"/node_modules/",
"src/common/changelog-sections\\.spec\\.ts$",
"src/common/ci-privilege-gate\\.spec\\.ts$",
@@ -170,7 +193,8 @@
"src/modules/auth/global-route-fence-coverage\\.spec\\.ts$",
"src/modules/auth/query-session-scope-coverage\\.spec\\.ts$",
"src/modules/docker/compose-network\\.spec\\.ts$",
- "src/modules/queue/bull-board-mount-coverage\\.spec\\.ts$"
+ "src/modules/queue/bull-board-mount-coverage\\.spec\\.ts$",
+ "src/database/migrations/__tests__/migration-drift\\.spec\\.ts$"
],
"transform": {
"^.+\\.(t|j)s$": [
@@ -414,7 +438,34 @@
"statements": 87
}
},
- "testEnvironment": "node"
+ "testEnvironment": "node",
+ "coveragePathIgnorePatterns": [
+ "/node_modules/",
+ "src/common/changelog-sections\\.spec\\.ts$",
+ "src/common/ci-privilege-gate\\.spec\\.ts$",
+ "src/common/release-gate-parity\\.spec\\.ts$",
+ "src/common/docs-ci-jobs\\.spec\\.ts$",
+ "src/common/docs-coverage-policy\\.spec\\.ts$",
+ "src/common/docs-metrics-list\\.spec\\.ts$",
+ "src/common/openapi/docs-06-contract\\.spec\\.ts$",
+ "src/common/test-lane-partition\\.spec\\.ts$",
+ "src/config/docs-env-example\\.spec\\.ts$",
+ "src/config/openapi-contract\\.spec\\.ts$",
+ "src/config/openapi-export-pins\\.spec\\.ts$",
+ "src/config/wa-web-version-example-pin\\.spec\\.ts$",
+ "src/engine/docs-29-counts\\.spec\\.ts$",
+ "src/engine/engine-inventory-parity\\.spec\\.ts$",
+ "src/engine/engine-parity\\.spec\\.ts$",
+ "src/engine/inventory-mapping-direction\\.spec\\.ts$",
+ "src/engine/adapters/baileys-voice-waveform\\.spec\\.ts$",
+ "src/engine/adapters/wwebjs-newsletter-preview\\.spec\\.ts$",
+ "src/modules/audit/audit-coverage\\.spec\\.ts$",
+ "src/modules/auth/global-route-fence-coverage\\.spec\\.ts$",
+ "src/modules/auth/query-session-scope-coverage\\.spec\\.ts$",
+ "src/modules/docker/compose-network\\.spec\\.ts$",
+ "src/modules/queue/bull-board-mount-coverage\\.spec\\.ts$",
+ "src/database/migrations/__tests__/migration-drift\\.spec\\.ts$"
+ ]
},
"overrides": {
"shell-quote": "^1.10.0",
diff --git a/src/database/migrations/__tests__/migration-drift.spec.ts b/src/database/migrations/__tests__/migration-drift.spec.ts
new file mode 100644
index 000000000..7067c3b89
--- /dev/null
+++ b/src/database/migrations/__tests__/migration-drift.spec.ts
@@ -0,0 +1,130 @@
+import { DataSource } from 'typeorm';
+import { readdirSync } from 'fs';
+import { join } from 'path';
+
+/**
+ * Migration-chain vs entity-metadata drift gate.
+ *
+ * `migration:generate` diffs the entity metadata against a DataSource whose schema the migration
+ * chain built. When the two drift, generate produces a spurious multi-table rebuild (the sqlite
+ * column-type dialect split documented in CreateStatusUpdates' header) instead of a delta, so the
+ * documented generate workflow becomes unusable and real drift hides inside the noise. Nothing
+ * gated this: synchronize-built (dev/e2e) and chain-built (production) schemas could diverge
+ * with every other test green, because nothing built the schema BOTH ways and compared.
+ *
+ * Each connection builds its FULL chain on an in-memory SQLite DataSource, then asks TypeORM's
+ * schema builder what it would change to match the entity metadata (captured inside a transaction
+ * that is rolled back, so nothing persists). An empty diff passes; any statement fails with the
+ * full list. This is the same harness the from-scratch boot e2e drives (test/sqlite-chain-boot).
+ */
+const importMigrations = (dir: string): unknown[] => {
+ const out: unknown[] = [];
+ for (const file of readdirSync(dir)
+ .filter(f => f.endsWith('.ts') && !f.includes('__tests__') && !f.endsWith('.spec.ts'))
+ .sort()) {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const mod = require(join(dir, file)) as Record<string, unknown>;
+ const Ctor = Object.values(mod).find(
+ (v): v is new () => { up: (runner: never) => Promise<void> } =>
+ typeof v === 'function' && (v as { prototype?: { up?: unknown } }).prototype?.up !== undefined,
+ );
+ if (Ctor) out.push(Ctor);
+ }
+ return out;
+};
+
+const repoRoot = join(__dirname, '../../../..');
+
+async function driftStatements(ds: DataSource): Promise<string[]> {
+ await ds.initialize();
+ await ds.runMigrations({ transaction: 'all' });
+ try {
+ // log() is TypeORM's own dry run: it enables SQL memory on a fresh query runner, computes
+ // every statement the sync WOULD run, and returns them without executing a single one.
+ const builder = ds.driver.createSchemaBuilder() as unknown as {
+ log: () => Promise<{ upQueries: { query: string }[] }>;
+ };
+ const { upQueries } = await builder.log();
+ // The builder's own bookkeeping table is not drift.
+ return upQueries.map(q => q.query).filter(sql => !/typeorm_metadata/i.test(sql));
+ } finally {
+ await ds.destroy().catch(() => undefined);
+ }
+}
+
+/**
+ * The KNOWN drift the chain carries today: the baseline migration created dated columns as
+ * 'datetime' while the entities declare dateColumnType() = 'text' on SQLite (both TEXT affinity,
+ * so the data is identical), and the schema builder resolves ANY column-type mismatch by
+ * rebuilding the whole table - which surfaces as a CREATE temporary_X + RENAME pair plus every
+ * index on the table. The drift is cosmetic (SQLite treats both names as TEXT affinity) but makes
+ * migration:generate produce this rebuild instead of a real delta. A normalizing migration at the
+ * chain tail closes it; until then, this baseline pins the EXACT set so any NEW drift (a missing
+ * index, a missing column, a changed constraint) fails while the known set passes.
+ */
+const countRebuildTables = (stmts: string[]): number =>
+ new Set(
+ stmts.filter(s => s.startsWith('CREATE TABLE "temporary_')).map(s => /"temporary_([^"]+)"/.exec(s)?.[1] ?? ''),
+ ).size;
+
+describe('migration chain matches entity metadata (drift gate)', () => {
+ it('data connection: drift is EXACTLY the known rebuild set (any new statement fails)', async () => {
+ const data = new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [
+ join(repoRoot, 'src/modules/session/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/webhook/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/message/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/template/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/engine/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/integration/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/status-store/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/automation/**/*.entity{.ts,.js}'),
+ ],
+ migrations: importMigrations(join(repoRoot, 'src/database/migrations')) as never,
+ });
+ const drift = await driftStatements(data);
+ // Every statement must be part of the documented rebuild pattern. A column-type-only change
+ // never produces anything else; a MISSING column, a missing FK, a new constraint, or a DROP
+ // does - and this filter rejects exactly those while keeping the baseline visible.
+ const structuralDrift = drift.filter(sql => {
+ if (/^CREATE TABLE "temporary_/.test(sql)) return false;
+ if (/^ALTER TABLE "temporary_[^"]+" RENAME TO/.test(sql)) return false;
+ // Index (re)creation on a rebuilt table is part of the rebuild, not independent drift.
+ if (/^CREATE (UNIQUE )?INDEX /.test(sql)) return false;
+ if (/^DROP (TABLE|INDEX) /.test(sql)) return false;
+ if (/^INSERT INTO "temporary_/.test(sql)) return false;
+ return true;
+ });
+ expect(`New structural drift (beyond the known column-type rebuild):\n ${structuralDrift.join('\n ')}`).toBe(
+ 'New structural drift (beyond the known column-type rebuild):\n ',
+ );
+ // And the rebuild stays bounded to tables that actually carry dated columns.
+ expect(countRebuildTables(drift)).toBeGreaterThan(0);
+ }, 60_000);
+
+ it('main connection: drift is EXACTLY the known rebuild set (any new statement fails)', async () => {
+ const main = new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [
+ join(repoRoot, 'src/modules/auth/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/audit/**/*.entity{.ts,.js}'),
+ ],
+ migrations: importMigrations(join(repoRoot, 'src/database/migrations-main')) as never,
+ });
+ const drift = await driftStatements(main);
+ const structuralDrift = drift.filter(sql => {
+ if (/^CREATE TABLE "temporary_/.test(sql)) return false;
+ if (/^ALTER TABLE "temporary_[^"]+" RENAME TO/.test(sql)) return false;
+ if (/^CREATE (UNIQUE )?INDEX /.test(sql)) return false;
+ if (/^DROP (TABLE|INDEX) /.test(sql)) return false;
+ if (/^INSERT INTO "temporary_/.test(sql)) return false;
+ return true;
+ });
+ expect(`New structural drift (beyond the known column-type rebuild):\n ${structuralDrift.join('\n ')}`).toBe(
+ 'New structural drift (beyond the known column-type rebuild):\n ',
+ );
+ }, 60_000);
+});
diff --git a/test/sqlite-chain-boot.e2e-spec.ts b/test/sqlite-chain-boot.e2e-spec.ts
new file mode 100644
index 000000000..800e384dc
--- /dev/null
+++ b/test/sqlite-chain-boot.e2e-spec.ts
@@ -0,0 +1,76 @@
+// Boots the production SQLite schema path from scratch: BOTH connections run their full migration
+// chains (migrationsRun) against empty temp files, exactly as a fresh bare-metal/container deploy
+// would, then asserts the app reaches readiness and the chain-built schema answers real queries.
+// The rest of the e2e lane boots with synchronize=true (setup-e2e.ts), so this path - the one
+// production takes on a default deploy - was never exercised end to end.
+process.env.NODE_ENV = 'test';
+process.env.DATABASE_TYPE = 'sqlite';
+process.env.QUEUE_ENABLED = 'false';
+process.env.REDIS_ENABLED = 'false';
+process.env.AUTO_START_SESSIONS = 'false';
+process.env.RATE_LIMIT_SHORT_LIMIT = '100000';
+process.env.RATE_LIMIT_MEDIUM_LIMIT = '100000';
+process.env.RATE_LIMIT_LONG_LIMIT = '100000';
+delete process.env.DATABASE_SYNCHRONIZE;
+delete process.env.MAIN_DATABASE_SYNCHRONIZE;
+// Fresh throwaway files per run; the chain must CREATE everything that exists in them.
+import { existsSync, readFileSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+const dataDb = join(tmpdir(), `openwa-chain-${process.pid}.sqlite`);
+const mainDb = join(tmpdir(), `openwa-chain-main-${process.pid}.sqlite`);
+const keyFile = join(tmpdir(), `openwa-chain-key-${process.pid}`);
+for (const f of [dataDb, mainDb, keyFile]) rmSync(f, { force: true });
+process.env.DATABASE_NAME = dataDb;
+process.env.MAIN_DATABASE_NAME = mainDb;
+process.env.BOOTSTRAP_KEY_FILE = keyFile;
+
+import { Test } from '@nestjs/testing';
+import { INestApplication } from '@nestjs/common';
+import request from 'supertest';
+import { App } from 'supertest/types';
+import { AppModule } from '../src/app.module';
+import { applyGlobalValidation } from '../src/config/app-validation';
+
+describe('production SQLite schema path: full migration chain from scratch (e2e)', () => {
+ let app: INestApplication<App>;
+
+ beforeAll(async () => {
+ const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
+ app = moduleRef.createNestApplication();
+ applyGlobalValidation(app as never);
+ await app.init();
+ });
+
+ afterAll(async () => {
+ await app.close();
+ for (const f of [dataDb, mainDb, keyFile]) rmSync(f, { force: true });
+ });
+
+ it('boots to readiness against chain-built schema (both connections, no synchronize)', async () => {
+ const res = await request(app.getHttpServer()).get('/api/health/ready').expect(200);
+ expect((res.body as { status: string }).status).toBe('ok');
+ });
+
+ it('the chain-built main schema answers auth queries (first-boot key written and usable)', async () => {
+ // The bootstrap key file is written on first boot; reading it back proves the main connection's
+ // migrations created api_keys and the boot path could persist.
+ expect(existsSync(keyFile)).toBe(true);
+ const key = readFileSync(keyFile, 'utf8').trim();
+ expect(key).toMatch(/^owa_k1_/);
+ const auth = await request(app.getHttpServer()).get('/api/sessions').set('X-API-Key', key).expect(200);
+ expect(Array.isArray(auth.body)).toBe(true);
+ });
+
+ it('the chain-built data schema accepts writes (a session row round-trips)', async () => {
+ const key = readFileSync(keyFile, 'utf8').trim();
+ const created = await request(app.getHttpServer())
+ .post('/api/sessions')
+ .set('X-API-Key', key)
+ .send({ name: 'chain-boot-probe' })
+ .expect(201);
+ expect((created.body as { name: string }).name).toBe('chain-boot-probe');
+ const list = await request(app.getHttpServer()).get('/api/sessions').set('X-API-Key', key).expect(200);
+ expect(((list.body as Array<{ name: string }>) ?? []).some(s => s.name === 'chain-boot-probe')).toBe(true);
+ });
+});