Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(metrics): bound failed METRICS_TOKEN attempts per client

Yudhi Armyndharis4f5014261833
diff --git a/src/modules/metrics/metrics.controller.ts b/src/modules/metrics/metrics.controller.ts
index 1fdcdefb6..e3cf027b4 100644
--- a/src/modules/metrics/metrics.controller.ts
+++ b/src/modules/metrics/metrics.controller.ts
@@ -9,7 +9,8 @@ import { METRICS_BEARER_SCHEME } from '../../config/swagger.config';
/**
* Prometheus scrape endpoint. `@Public()` bypasses the API-key guard and
* `@SkipThrottle()` keeps a scrape interval from eating the rate-limit budget; access is
- * instead gated by METRICS_TOKEN inside the service (disabled-by-default).
+ * instead gated by METRICS_TOKEN inside the service (disabled-by-default), which bounds
+ * failed token attempts per client on its own.
*/
@ApiTags('metrics')
@Controller('metrics')
@@ -28,12 +29,13 @@ export class MetricsController {
})
@ApiResponse({ status: 401, description: 'METRICS_TOKEN is configured but the bearer is missing or wrong' })
@ApiResponse({ status: 404, description: 'Metrics endpoint is disabled (METRICS_TOKEN unset)' })
+ @ApiResponse({ status: 429, description: 'Too many failed token attempts from this client; retry after a minute' })
@Header('Content-Type', 'text/plain; version=0.0.4; charset=utf-8')
@Header('Cache-Control', 'no-store')
// @Req (not @Headers('authorization')) so the OpenAPI op doesn't sprout a spurious required
// `authorization` header parameter — the bearer is expressed via the security scheme above.
async scrape(@Req() req: Request): Promise<string> {
- this.metricsService.assertScrapeAuthorized(req.headers.authorization);
+ this.metricsService.assertScrapeAuthorized(req.headers.authorization, req);
return this.metricsService.render();
}
}
diff --git a/src/modules/metrics/metrics.service.spec.ts b/src/modules/metrics/metrics.service.spec.ts
index b5baf3efd..0af6150d5 100644
--- a/src/modules/metrics/metrics.service.spec.ts
+++ b/src/modules/metrics/metrics.service.spec.ts
@@ -1,4 +1,4 @@
-import { NotFoundException, UnauthorizedException } from '@nestjs/common';
+import { HttpException, HttpStatus, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { MetricsService, METRICS_RENDER_TTL_MS } from './metrics.service';
import { StatsService, OverviewStats } from '../stats/stats.service';
@@ -46,6 +46,34 @@ describe('MetricsService', () => {
const svc = makeService('s3cret');
expect(() => svc.assertScrapeAuthorized('bearer s3cret')).not.toThrow();
});
+
+ // The route skips the shared throttler so scrapes cost no budget; failed compares get their own.
+ it('answers 429 once one client has failed too often, without comparing further guesses', () => {
+ const svc = makeService('s3cret');
+ const guesser = { headers: {}, socket: { remoteAddress: '198.51.100.7' } };
+ for (let i = 0; i < 10; i++) {
+ expect(() => svc.assertScrapeAuthorized('Bearer nope', guesser)).toThrow(UnauthorizedException);
+ }
+ const locked = (): void => svc.assertScrapeAuthorized('Bearer s3cret', guesser);
+ expect(locked).toThrow(HttpException);
+ try {
+ locked();
+ } catch (err) {
+ expect((err as HttpException).getStatus()).toBe(HttpStatus.TOO_MANY_REQUESTS);
+ }
+ // Another client is unaffected.
+ expect(() =>
+ svc.assertScrapeAuthorized('Bearer s3cret', { headers: {}, socket: { remoteAddress: '203.0.113.9' } }),
+ ).not.toThrow();
+ });
+
+ it('never charges a successful scrape against that budget', () => {
+ const svc = makeService('s3cret');
+ const scraper = { headers: {}, socket: { remoteAddress: '198.51.100.8' } };
+ for (let i = 0; i < 50; i++) {
+ expect(() => svc.assertScrapeAuthorized('Bearer s3cret', scraper)).not.toThrow();
+ }
+ });
});
describe('render', () => {
diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.ts
index 75981ebd6..be919e75a 100644
--- a/src/modules/metrics/metrics.service.ts
+++ b/src/modules/metrics/metrics.service.ts
@@ -1,6 +1,8 @@
-import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';
+import { HttpException, HttpStatus, Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { constantTimeEqual } from '../../common/security/constantTimeEqual';
+import { limiterKeyForIp, resolveClientIp, type RequestLike } from '../../common/utils/ip';
+import { SlidingWindowLimiter } from '../events/ws-rate-limit';
import { StatsService } from '../stats/stats.service';
import { getWebhookDeliveryFailuresTotal } from '../../common/metrics/webhook-delivery-metrics';
import {
@@ -34,6 +36,13 @@ export class MetricsService {
private cachedRender: { at: number; text: string } | null = null;
+ /**
+ * The route skips the shared throttler so a scrape interval costs no request budget, which left
+ * token guesses unbounded. This window is charged per client before the compare and refunded when
+ * it succeeds, so only failures spend it: 10 a minute, then 429 until the window slides.
+ */
+ private readonly failedScrapeLimiter = new SlidingWindowLimiter(10, 60_000);
+
constructor(
private readonly config: ConfigService,
private readonly statsService: StatsService,
@@ -45,17 +54,25 @@ export class MetricsService {
/**
* Throws if the caller may not scrape: 404 when metrics are disabled (no token configured),
- * 401 when a token is configured but the request's bearer is missing or wrong.
+ * 401 when a token is configured but the request's bearer is missing or wrong, 429 once `client`
+ * has spent its failed-attempt window.
*/
- assertScrapeAuthorized(authorizationHeader: string | undefined): void {
+ assertScrapeAuthorized(authorizationHeader: string | undefined, client?: RequestLike): void {
const expected = this.token;
if (!expected) {
throw new NotFoundException('Metrics endpoint is disabled (set METRICS_TOKEN to enable)');
}
+ const subject = client
+ ? limiterKeyForIp(resolveClientIp(client, this.config.get<string[]>('security.trustedProxies') ?? []))
+ : '';
+ if (!this.failedScrapeLimiter.allow(subject)) {
+ throw new HttpException('Too many failed metrics token attempts', HttpStatus.TOO_MANY_REQUESTS);
+ }
const provided = (authorizationHeader ?? '').replace(/^Bearer\s+/i, '').trim();
if (!provided || !this.safeEqual(provided, expected)) {
throw new UnauthorizedException('Invalid metrics token');
}
+ this.failedScrapeLimiter.refund(subject);
}
private safeEqual(a: string, b: string): boolean {