Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(health): disclose the running version only to authenticated callers

Yudhi Armyndharisc5ac3afc699a
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 699eff2e0..51dd7874e 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -4858,9 +4858,9 @@ System endpoints expose operational status, Prometheus metrics, aggregate statis
#### GET /api/health
-Basic health check returning status, the current timestamp, and the running app version.
+Basic health check returning status and the current timestamp; the running app version is disclosed only to authenticated callers.
-**Auth:** public
+**Auth:** public — the check itself needs no credentials, so uptime probes keep working. The `version` field is added only when the request carries a valid API key (`X-API-Key` header or `Authorization: Bearer`); an absent or invalid key still answers `200` without it.
**Response** `200`
@@ -4868,7 +4868,7 @@ Basic health check returning status, the current timestamp, and the running app
{ "status": "ok", "timestamp": "2026-06-25T12:34:56.789Z", "version": "0.7.3" }
```
-Notes: `timestamp` is an ISO-8601 string (`new Date().toISOString()`). `version` is read from `package.json` at module load. Exempt from rate limiting (`@SkipThrottle`).
+Notes: `timestamp` is an ISO-8601 string (`new Date().toISOString()`). `version` is read from `package.json` at module load and present only on an authenticated request. Exempt from rate limiting (`@SkipThrottle`).
#### GET /api/health/live
diff --git a/openapi.json b/openapi.json
index 0b1a0b88c..46ceb5d2f 100644
--- a/openapi.json
+++ b/openapi.json
@@ -12522,14 +12522,13 @@
},
"version": {
"type": "string",
- "description": "Running application version.",
+ "description": "Running application version. Included only when the request carries a valid API key.",
"example": "0.14.4"
}
},
"required": [
"status",
- "timestamp",
- "version"
+ "timestamp"
]
},
"LivenessResponseDto": {
diff --git a/src/modules/auth/api-key-usage-write-scope.spec.ts b/src/modules/auth/api-key-usage-write-scope.spec.ts
index 9b3660d9f..564e567b2 100644
--- a/src/modules/auth/api-key-usage-write-scope.spec.ts
+++ b/src/modules/auth/api-key-usage-write-scope.spec.ts
@@ -177,6 +177,7 @@ describe('validateApiKey entrypoint coverage', () => {
['common/security/bull-board-auth.middleware.ts', 'queue dashboard middleware'],
['modules/auth/guards/api-key.guard.ts', 'REST route guard'],
['modules/events/events.gateway.ts', 'websocket connect and per-subscribe re-validation'],
+ ['modules/health/health.controller.ts', 'version disclosure on the public health check'],
]);
/** Where validateApiKey is declared, which is not a caller. */
diff --git a/src/modules/health/dto/health-response.dto.ts b/src/modules/health/dto/health-response.dto.ts
index 755eef4ee..6c4f97e2f 100644
--- a/src/modules/health/dto/health-response.dto.ts
+++ b/src/modules/health/dto/health-response.dto.ts
@@ -1,4 +1,4 @@
-import { ApiProperty } from '@nestjs/swagger';
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
/**
* Response shapes for the health routes — the raw handler value, no envelope.
@@ -13,8 +13,11 @@ export class HealthCheckResponseDto {
@ApiProperty({ description: 'ISO-8601 timestamp of the reply.', example: '2026-08-07T12:00:00.000Z' })
timestamp!: string;
- @ApiProperty({ description: 'Running application version.', example: '0.14.4' })
- version!: string;
+ @ApiPropertyOptional({
+ description: 'Running application version. Included only when the request carries a valid API key.',
+ example: '0.14.4',
+ })
+ version?: string;
}
export class LivenessResponseDto {
diff --git a/src/modules/health/health.controller.spec.ts b/src/modules/health/health.controller.spec.ts
index f34e5d8ba..30cfd588f 100644
--- a/src/modules/health/health.controller.spec.ts
+++ b/src/modules/health/health.controller.spec.ts
@@ -1,14 +1,21 @@
import { Test, TestingModule } from '@nestjs/testing';
import { getDataSourceToken } from '@nestjs/typeorm';
-import { ServiceUnavailableException } from '@nestjs/common';
+import { ServiceUnavailableException, UnauthorizedException } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
+import { Request } from 'express';
import { HealthController } from './health.controller';
import { ShutdownService } from '../../common/services/shutdown.service';
+import { AuthService } from '../auth/auth.service';
describe('HealthController', () => {
let controller: HealthController;
const mainQuery = jest.fn();
const dataQuery = jest.fn();
const isShuttingDown = jest.fn();
+ const validateApiKey = jest.fn();
+
+ const reqWith = (headers: Record<string, string> = {}): Request =>
+ ({ headers, socket: { remoteAddress: '127.0.0.1' } }) as unknown as Request;
beforeEach(async () => {
mainQuery.mockResolvedValue([{ '1': 1 }]);
@@ -21,6 +28,8 @@ describe('HealthController', () => {
{ provide: getDataSourceToken('main'), useValue: { query: mainQuery } },
{ provide: getDataSourceToken('data'), useValue: { query: dataQuery } },
{ provide: ShutdownService, useValue: { isShuttingDown } },
+ { provide: AuthService, useValue: { validateApiKey } },
+ { provide: ConfigService, useValue: { get: () => undefined } },
],
}).compile();
@@ -31,19 +40,49 @@ describe('HealthController', () => {
mainQuery.mockReset();
dataQuery.mockReset();
isShuttingDown.mockReset();
+ validateApiKey.mockReset();
});
describe('check', () => {
- it('returns ok with a timestamp (static)', () => {
- const result = controller.check();
+ it('returns ok with a timestamp (static)', async () => {
+ const result = await controller.check(reqWith());
expect(result.status).toBe('ok');
expect(result.timestamp).toBeDefined();
});
- it('reports the running version (from package.json) so the dashboard reads it live', () => {
+ it('omits the version for an unauthenticated caller and never touches the key store', async () => {
+ const result = await controller.check(reqWith());
+ expect(result).not.toHaveProperty('version');
+ expect(validateApiKey).not.toHaveBeenCalled();
+ });
+
+ it('omits the version when the presented key is invalid (the check itself still answers ok)', async () => {
+ validateApiKey.mockRejectedValue(new UnauthorizedException('Invalid API key'));
+
+ const result = await controller.check(reqWith({ 'x-api-key': 'wrong' }));
+
+ expect(result.status).toBe('ok');
+ expect(result).not.toHaveProperty('version');
+ });
+
+ it('reports the running version to a valid API key (X-API-Key header)', async () => {
+ validateApiKey.mockResolvedValue({ id: 'k1' });
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { version } = require('../../../package.json') as { version: string };
- expect(controller.check().version).toBe(version);
+
+ const result = await controller.check(reqWith({ 'x-api-key': 'good-key' }));
+
+ expect(result.version).toBe(version);
+ expect(validateApiKey).toHaveBeenCalledWith('good-key', '127.0.0.1');
+ });
+
+ it('accepts a Bearer token the same way the guard does', async () => {
+ validateApiKey.mockResolvedValue({ id: 'k1' });
+
+ const result = await controller.check(reqWith({ authorization: 'Bearer good-key' }));
+
+ expect(result.version).toBeDefined();
+ expect(validateApiKey).toHaveBeenCalledWith('good-key', '127.0.0.1');
});
});
diff --git a/src/modules/health/health.controller.ts b/src/modules/health/health.controller.ts
index 7388ccefe..7348c5d4b 100644
--- a/src/modules/health/health.controller.ts
+++ b/src/modules/health/health.controller.ts
@@ -1,11 +1,15 @@
-import { Controller, Get, ServiceUnavailableException } from '@nestjs/common';
+import { Controller, Get, Req, ServiceUnavailableException } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { HealthCheckResponseDto, LivenessResponseDto, ReadinessResponseDto } from './dto/health-response.dto';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';
+import { ConfigService } from '@nestjs/config';
+import type { Request } from 'express';
import { Public } from '../auth/decorators/auth.decorators';
import { SkipThrottle } from '@nestjs/throttler';
import { ShutdownService } from '../../common/services/shutdown.service';
+import { AuthService } from '../auth/auth.service';
+import { resolveClientIp } from '../../common/utils/ip';
interface DependencyStatus {
status: 'up' | 'down';
@@ -19,8 +23,9 @@ interface HealthCheckResult {
/** Bound each dependency probe so a hung connection can't stall the readiness check. */
const READINESS_PROBE_TIMEOUT_MS = 3000;
-// Source the running version from package.json (same pattern as swagger.config.ts) so the dashboard
-// can read it live and never show a stale build-time-baked version. Read once at module load.
+// Source the running version from package.json (same pattern as swagger.config.ts) so authenticated
+// callers (e.g. the dashboard) read it live and never show a stale build-time-baked version. Read
+// once at module load.
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { version: APP_VERSION } = require('../../../package.json') as { version: string };
@@ -33,17 +38,45 @@ export class HealthController {
@InjectDataSource('main') private readonly mainDataSource: DataSource,
@InjectDataSource('data') private readonly dataDataSource: DataSource,
private readonly shutdownService: ShutdownService,
+ private readonly authService: AuthService,
+ private readonly configService: ConfigService,
) {}
@Get()
@ApiOperation({ summary: 'Basic health check' })
@ApiResponse({ status: 200, description: 'Application is healthy', type: HealthCheckResponseDto })
- check(): { status: string; timestamp: string; version: string } {
- return {
+ async check(@Req() req: Request): Promise<{ status: string; timestamp: string; version?: string }> {
+ const body: { status: string; timestamp: string; version?: string } = {
status: 'ok',
timestamp: new Date().toISOString(),
- version: APP_VERSION,
};
+ // The exact running version is disclosed only to authenticated callers; the route itself stays
+ // public so uptime probes keep working without credentials.
+ if (await this.hasValidApiKey(req)) {
+ body.version = APP_VERSION;
+ }
+ return body;
+ }
+
+ /**
+ * The route is @Public, so the global ApiKeyGuard never runs here — resolve a presented key the
+ * same way the guard does (X-API-Key header or Bearer token, trusted-proxy-aware client IP so an
+ * allowedIps-restricted key is enforced identically). Any outcome other than a validated key —
+ * none presented, invalid, revoked, IP-denied — withholds the version; it never fails the check.
+ */
+ private async hasValidApiKey(req: Request): Promise<boolean> {
+ const xApiKey = req.headers['x-api-key'];
+ const authHeader = req.headers['authorization'];
+ const rawKey =
+ (typeof xApiKey === 'string' && xApiKey) || (authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : undefined);
+ if (!rawKey) return false;
+ try {
+ const trustedProxies = this.configService.get<string[]>('security.trustedProxies') ?? [];
+ await this.authService.validateApiKey(rawKey, resolveClientIp(req, trustedProxies));
+ return true;
+ } catch {
+ return false;
+ }
}
@Get('live')
diff --git a/test/app.e2e-spec.ts b/test/app.e2e-spec.ts
index 51ea73ac9..7462766b3 100644
--- a/test/app.e2e-spec.ts
+++ b/test/app.e2e-spec.ts
@@ -52,6 +52,29 @@ describe('App smoke (e2e)', () => {
});
});
+ it('GET /api/health withholds the version without credentials, discloses it to a valid key', async () => {
+ const authService = app.get(AuthService);
+ const { rawKey } = await authService.createApiKey({ name: 'e2e-health', role: ApiKeyRole.VIEWER });
+
+ await request(app.getHttpServer())
+ .get('/api/health')
+ .expect(200)
+ .expect(res => {
+ if ('version' in (res.body as object)) throw new Error('version disclosed without credentials');
+ });
+
+ await request(app.getHttpServer())
+ .get('/api/health')
+ .set('X-API-Key', rawKey)
+ .expect(200)
+ .expect(res => {
+ const body = res.body as { version?: string };
+ if (typeof body.version !== 'string' || !body.version) {
+ throw new Error('version missing for an authenticated caller');
+ }
+ });
+ });
+
it('GET /api/sessions without an API key is rejected (401)', () => {
return request(app.getHttpServer()).get('/api/sessions').expect(401);
});