From b29f72bef4598e1dcbf8ff7d7dcfa10f57f8c27a Mon Sep 17 00:00:00 2001 From: David Santos Date: Sun, 12 Apr 2026 11:29:31 +0000 Subject: [PATCH] feat(api): BIT-2601 rate-limit typing, login preset, and rejection metrics Align hub rate-limit error context with @fastify/rate-limit types, parse RATE_* and body-size env vars via parsePositiveIntEnv, wire POST /admin/auth/login to the login preset, increment er_api_rate_limit_rejections_total per bucket, and document ingest_token_id plus Prometheus scraping notes. Made-with: Cursor --- api/src/index.ts | 22 ++- api/src/lib/parsePositiveIntEnv.test.ts | 21 +++ api/src/lib/parsePositiveIntEnv.ts | 17 +++ api/src/plugins/prometheus.ts | 8 ++ api/src/plugins/rate-limit.ts | 125 ++++++++++-------- api/src/routes/admin/auth.ts | 1 + .../public/errorMonitoringMutations.test.ts | 6 +- docs/HTTP_CONTRACTS.md | 12 ++ docs/OBSERVABILITY_PROMETHEUS.md | 1 + 9 files changed, 155 insertions(+), 58 deletions(-) create mode 100644 api/src/lib/parsePositiveIntEnv.test.ts create mode 100644 api/src/lib/parsePositiveIntEnv.ts diff --git a/api/src/index.ts b/api/src/index.ts index b664de4..f3a3525 100644 --- a/api/src/index.ts +++ b/api/src/index.ts @@ -12,7 +12,13 @@ import authPlugin from './plugins/auth.js'; import rbacPlugin from './plugins/rbac.js'; import auditPlugin from './plugins/audit.js'; import rateLimitPlugin from './plugins/rate-limit.js'; -import { INGEST_MAX_BODY_BYTES, ADMIN_MAX_BODY_BYTES } from './plugins/rate-limit.js'; +import { + INGEST_MAX_BODY_BYTES, + ADMIN_MAX_BODY_BYTES, + type RateLimitErrorContext, +} from './plugins/rate-limit.js'; +import { parsePositiveIntEnv } from './lib/parsePositiveIntEnv.js'; +import { rateLimitRejectionsTotal } from './plugins/prometheus.js'; import adminAuthRoutes from './routes/admin/auth.js'; import adminStatsRoutes from './routes/admin/stats.js'; @@ -50,11 +56,19 @@ await app.register(jwt, { cookie: { cookieName: '__Host-access', signed: false }, }); -// Global rate limit (per-route limits override this) +// Global rate limit (per-route limits override this; custom builder labels 429 metrics) await app.register(rateLimit, { global: true, - max: parseInt(process.env.RATE_GLOBAL_MAX ?? '500', 10), - timeWindow: parseInt(process.env.RATE_GLOBAL_WINDOW_MS ?? '60000', 10), + max: parsePositiveIntEnv(process.env.RATE_GLOBAL_MAX, 500), + timeWindow: parsePositiveIntEnv(process.env.RATE_GLOBAL_WINDOW_MS, 60_000), + errorResponseBuilder: (_request, context: RateLimitErrorContext) => { + rateLimitRejectionsTotal.inc({ bucket: 'global' }); + const err = new Error(`Rate limit exceeded, retry in ${context.after}`) as Error & { + statusCode: number; + }; + err.statusCode = context.ban ? 403 : 429; + return err; + }, }); // Database diff --git a/api/src/lib/parsePositiveIntEnv.test.ts b/api/src/lib/parsePositiveIntEnv.test.ts new file mode 100644 index 0000000..19a046d --- /dev/null +++ b/api/src/lib/parsePositiveIntEnv.test.ts @@ -0,0 +1,21 @@ +import { describe, it, expect } from 'vitest'; +import { parsePositiveIntEnv } from './parsePositiveIntEnv.js'; + +describe('parsePositiveIntEnv', () => { + it('returns default when raw is undefined or empty', () => { + expect(parsePositiveIntEnv(undefined, 42)).toBe(42); + expect(parsePositiveIntEnv('', 42)).toBe(42); + }); + + it('parses valid positive integers', () => { + expect(parsePositiveIntEnv('1', 99)).toBe(1); + expect(parsePositiveIntEnv('120', 99)).toBe(120); + }); + + it('falls back on NaN, zero, or negative', () => { + expect(parsePositiveIntEnv('0', 10)).toBe(10); + expect(parsePositiveIntEnv('-3', 10)).toBe(10); + expect(parsePositiveIntEnv('abc', 10)).toBe(10); + expect(parsePositiveIntEnv('12.5', 10)).toBe(12); + }); +}); diff --git a/api/src/lib/parsePositiveIntEnv.ts b/api/src/lib/parsePositiveIntEnv.ts new file mode 100644 index 0000000..3984825 --- /dev/null +++ b/api/src/lib/parsePositiveIntEnv.ts @@ -0,0 +1,17 @@ +/** + * Parse a positive integer from process.env-style values for rate-limit and similar tunables. + * Invalid or non-positive values fall back to `defaultValue` (never NaN). + */ +export function parsePositiveIntEnv( + raw: string | undefined, + defaultValue: number, +): number { + if (raw === undefined || raw === '') { + return defaultValue; + } + const parsed = parseInt(raw, 10); + if (!Number.isFinite(parsed) || parsed < 1) { + return defaultValue; + } + return parsed; +} diff --git a/api/src/plugins/prometheus.ts b/api/src/plugins/prometheus.ts index e70010a..04ff23c 100644 --- a/api/src/plugins/prometheus.ts +++ b/api/src/plugins/prometheus.ts @@ -38,6 +38,14 @@ const httpRequestsTotal = new Counter({ registers: [register], }); +/** Incremented when @fastify/rate-limit emits a 429 (per bucket / policy). */ +export const rateLimitRejectionsTotal = new Counter({ + name: 'er_api_rate_limit_rejections_total', + help: 'Hub API rate-limit denials (HTTP 429) by policy bucket', + labelNames: ['bucket'] as const, + registers: [register], +}); + /* ── Domain gauges (set externally via metricsGauges) ────────────────── */ const incidentsTotalGauge = new Gauge({ diff --git a/api/src/plugins/rate-limit.ts b/api/src/plugins/rate-limit.ts index 0d0fecb..3077fcd 100644 --- a/api/src/plugins/rate-limit.ts +++ b/api/src/plugins/rate-limit.ts @@ -22,30 +22,39 @@ * * @fastify/rate-limit uses an in-memory store unless a custom store is * configured at registration time (see `src/index.ts`). + * + * Request augmentation: optional `request.ingest_token_id` (see module `fastify` augmentation + * below) lets per-token keys apply once `/api/ingest/*` routes validate a bearer token. */ import fp from 'fastify-plugin'; import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; +import type fastifyRateLimit from '@fastify/rate-limit'; +import { parsePositiveIntEnv } from '../lib/parsePositiveIntEnv.js'; +import { rateLimitRejectionsTotal } from './prometheus.js'; -/** Shape of the `context` argument to @fastify/rate-limit `errorResponseBuilder`. */ -interface RateLimitErrorContext { - ban: boolean; - after: string; - max: number; - ttl: number; -} +/** Mirrors @fastify/rate-limit `errorResponseBuilder` context (kept as a named alias for hub docs). */ +export type RateLimitErrorContext = fastifyRateLimit.errorResponseBuilderContext; -const RATE_INGEST_MAX = parseInt(process.env.RATE_INGEST_MAX ?? '1000', 10); -const RATE_INGEST_WINDOW_MS = parseInt(process.env.RATE_INGEST_WINDOW_MS ?? '60000', 10); -const RATE_LOGIN_MAX = parseInt(process.env.RATE_LOGIN_MAX ?? '10', 10); -const RATE_LOGIN_WINDOW_MS = parseInt(process.env.RATE_LOGIN_WINDOW_MS ?? '300000', 10); -const RATE_GLOBAL_MAX = parseInt(process.env.RATE_GLOBAL_MAX ?? '500', 10); -const RATE_GLOBAL_WINDOW_MS = parseInt(process.env.RATE_GLOBAL_WINDOW_MS ?? '60000', 10); -const RATE_MUTATION_MAX = parseInt(process.env.RATE_MUTATION_MAX ?? '120', 10); -const RATE_MUTATION_WINDOW_MS = parseInt(process.env.RATE_MUTATION_WINDOW_MS ?? '60000', 10); +export type HubRouteRateLimitOptions = fastifyRateLimit.RateLimitOptions; -export const INGEST_MAX_BODY_BYTES = parseInt(process.env.INGEST_MAX_BODY_BYTES ?? String(512 * 1024), 10); -export const ADMIN_MAX_BODY_BYTES = parseInt(process.env.ADMIN_MAX_BODY_BYTES ?? String(64 * 1024), 10); +const RATE_INGEST_MAX = parsePositiveIntEnv(process.env.RATE_INGEST_MAX, 1000); +const RATE_INGEST_WINDOW_MS = parsePositiveIntEnv(process.env.RATE_INGEST_WINDOW_MS, 60000); +const RATE_LOGIN_MAX = parsePositiveIntEnv(process.env.RATE_LOGIN_MAX, 10); +const RATE_LOGIN_WINDOW_MS = parsePositiveIntEnv(process.env.RATE_LOGIN_WINDOW_MS, 300000); +const RATE_GLOBAL_MAX = parsePositiveIntEnv(process.env.RATE_GLOBAL_MAX, 500); +const RATE_GLOBAL_WINDOW_MS = parsePositiveIntEnv(process.env.RATE_GLOBAL_WINDOW_MS, 60000); +const RATE_MUTATION_MAX = parsePositiveIntEnv(process.env.RATE_MUTATION_MAX, 120); +const RATE_MUTATION_WINDOW_MS = parsePositiveIntEnv(process.env.RATE_MUTATION_WINDOW_MS, 60000); + +export const INGEST_MAX_BODY_BYTES = parsePositiveIntEnv( + process.env.INGEST_MAX_BODY_BYTES, + 512 * 1024, +); +export const ADMIN_MAX_BODY_BYTES = parsePositiveIntEnv( + process.env.ADMIN_MAX_BODY_BYTES, + 64 * 1024, +); /** Key generator for ingest rate limiting: prefer token ID, fall back to IP. */ function ingest_key(request: FastifyRequest): string { @@ -62,43 +71,55 @@ export default fp(async function rateLimitPlugin(app: FastifyInstance) { * Per-route rate limit configs — consumed by @fastify/rate-limit's * route-level config option `{ config: { rateLimit: { ... } } }`. */ - app.decorate('rateLimits', { - ingest: { - max: RATE_INGEST_MAX, - timeWindow: RATE_INGEST_WINDOW_MS, - keyGenerator: ingest_key, - errorResponseBuilder: (_request: FastifyRequest, context: RateLimitErrorContext) => ({ - error: 'TooManyRequests', - message: 'Ingest rate limit exceeded. Slow down.', + const ingest: HubRouteRateLimitOptions = { + max: RATE_INGEST_MAX, + timeWindow: RATE_INGEST_WINDOW_MS, + keyGenerator: ingest_key, + errorResponseBuilder: (_request: FastifyRequest, context: RateLimitErrorContext) => { + rateLimitRejectionsTotal.inc({ bucket: 'ingest' }); + return { + error: 'TooManyRequests', + message: 'Ingest rate limit exceeded. Slow down.', retryAfter: Math.ceil(context.ttl / 1000), - }), + }; }, - login: { - max: RATE_LOGIN_MAX, - timeWindow: RATE_LOGIN_WINDOW_MS, - keyGenerator: (request: FastifyRequest) => `login:ip:${request.ip}`, - errorResponseBuilder: (_request: FastifyRequest, context: RateLimitErrorContext) => ({ - error: 'TooManyRequests', - message: 'Too many login attempts. Try again later.', + }; + + const login: HubRouteRateLimitOptions = { + max: RATE_LOGIN_MAX, + timeWindow: RATE_LOGIN_WINDOW_MS, + keyGenerator: (request: FastifyRequest) => `login:ip:${request.ip}`, + errorResponseBuilder: (_request: FastifyRequest, context: RateLimitErrorContext) => { + rateLimitRejectionsTotal.inc({ bucket: 'login' }); + return { + error: 'TooManyRequests', + message: 'Too many login attempts. Try again later.', retryAfter: Math.ceil(context.ttl / 1000), - }), + }; }, - global: { - max: RATE_GLOBAL_MAX, - timeWindow: RATE_GLOBAL_WINDOW_MS, - }, - mutation: { - max: RATE_MUTATION_MAX, - timeWindow: RATE_MUTATION_WINDOW_MS, - keyGenerator: (request: FastifyRequest) => `errmon_mut:ip:${request.ip}`, - errorResponseBuilder: (_request: FastifyRequest, context: RateLimitErrorContext) => ({ - success: false, - error: 'TooManyRequests', - message: 'Error-monitoring mutation rate limit exceeded. Slow down.', + }; + + const global: Pick = { + max: RATE_GLOBAL_MAX, + timeWindow: RATE_GLOBAL_WINDOW_MS, + }; + + const mutation: HubRouteRateLimitOptions = { + max: RATE_MUTATION_MAX, + timeWindow: RATE_MUTATION_WINDOW_MS, + keyGenerator: (request: FastifyRequest) => `errmon_mut:ip:${request.ip}`, + errorResponseBuilder: (_request: FastifyRequest, context: RateLimitErrorContext) => { + rateLimitRejectionsTotal.inc({ bucket: 'mutation' }); + return { + success: false, + error: 'TooManyRequests', + message: 'Error-monitoring mutation rate limit exceeded. Slow down.', retryAfter: Math.ceil(context.ttl / 1000), - }), + }; }, - }); + }; + + app.decorate('rateLimits', { ingest, login, global, mutation }); /** * Body size enforcement hook. @@ -134,10 +155,10 @@ declare module 'fastify' { } interface FastifyInstance { rateLimits: { - ingest: Record; - login: Record; - global: Record; - mutation: Record; + ingest: HubRouteRateLimitOptions; + login: HubRouteRateLimitOptions; + global: Pick; + mutation: HubRouteRateLimitOptions; }; } } diff --git a/api/src/routes/admin/auth.ts b/api/src/routes/admin/auth.ts index 5c0928f..27691b1 100644 --- a/api/src/routes/admin/auth.ts +++ b/api/src/routes/admin/auth.ts @@ -35,6 +35,7 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise( '/admin/auth/login', { + config: { rateLimit: app.rateLimits.login }, schema: { body: { type: 'object', diff --git a/api/src/routes/public/errorMonitoringMutations.test.ts b/api/src/routes/public/errorMonitoringMutations.test.ts index 903e51f..70dcb4f 100644 --- a/api/src/routes/public/errorMonitoringMutations.test.ts +++ b/api/src/routes/public/errorMonitoringMutations.test.ts @@ -50,9 +50,11 @@ async function buildApp(pool?: ReturnType): Promise` instead of `ingest:ip:`, so many clients behind one NAT do not share one counter. The separate **ingest-api** process already applies DB-backed per-key limits; this field keeps the hub aligned if ingest is ever co-hosted in the same Fastify app. + +Rate-limit denials are counted in Prometheus as **`er_api_rate_limit_rejections_total`** (`bucket` label: `global`, `ingest`, `login`, `mutation`). See [OBSERVABILITY_PROMETHEUS.md](OBSERVABILITY_PROMETHEUS.md). + +--- + ## Hub API — health & metrics ### `GET /health` diff --git a/docs/OBSERVABILITY_PROMETHEUS.md b/docs/OBSERVABILITY_PROMETHEUS.md index 8172fd7..f19b68f 100644 --- a/docs/OBSERVABILITY_PROMETHEUS.md +++ b/docs/OBSERVABILITY_PROMETHEUS.md @@ -45,6 +45,7 @@ If TLS or auth is fronted by Nginx, scrape the **internal** listener or enable m - **`er_api_http_requests_total`** — labels: `method`, `route`, `status_code`. - **`er_api_http_request_duration_seconds`** — histogram for latency SLOs. +- **`er_api_rate_limit_rejections_total`** — labels: `bucket` (`global`, `ingest`, `login`, `mutation`). Increments when `@fastify/rate-limit` returns 429 (or 403 when ban applies) for that policy. Use alongside `status_code="429"` on the HTTP counter to alert on abuse vs. organic load. ### Domain gauges (refreshed when **`GET /api/error-monitoring/stats`** runs)