feat(api): BIT-2601 rate-limit typing, login preset, and rejection metrics
CI / Test ingest-api (push) Has been cancelled
CI / Test api (push) Has been cancelled
CI / Lint and typecheck admin-ui (push) Has been cancelled
CI / Validate Docker build (push) Has been cancelled

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
This commit is contained in:
David Santos committed 2026-04-12 11:29:31 +00:00
1 parent 6c22dc8bb9
commit b29f72bef4
9 files changed
+155 -58

No files matched your search

+18 -4
View File
@@ -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
+21
View File
@@ -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);
});
});
+17
View File
@@ -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;
}
+8
View File
@@ -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({
+73 -52
View File
@@ -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<HubRouteRateLimitOptions, 'max' | 'timeWindow'> = {
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<string, unknown>;
login: Record<string, unknown>;
global: Record<string, unknown>;
mutation: Record<string, unknown>;
ingest: HubRouteRateLimitOptions;
login: HubRouteRateLimitOptions;
global: Pick<HubRouteRateLimitOptions, 'max' | 'timeWindow'>;
mutation: HubRouteRateLimitOptions;
};
}
}
+1
View File
@@ -35,6 +35,7 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
app.post<{ Body: LoginBody }>(
'/admin/auth/login',
{
config: { rateLimit: app.rateLimits.login },
schema: {
body: {
type: 'object',
@@ -50,9 +50,11 @@ async function buildApp(pool?: ReturnType<typeof makePool>): Promise<FastifyInst
app.decorate('db', p as unknown as FastifyInstance['db']);
app.decorate('auditLog', vi.fn().mockResolvedValue(undefined));
app.decorate('rateLimits', {
ingest: {}, login: {}, global: {},
ingest: { max: 1000, timeWindow: 60_000 },
login: { max: 10, timeWindow: 300_000 },
global: { max: 500, timeWindow: 60_000 },
mutation: { max: 100, timeWindow: 60_000 },
} as unknown as FastifyInstance['rateLimits']);
});
await app.register(errorMonitoringMutationsRoutes);
return app;
+12
View File
@@ -15,6 +15,18 @@
---
## Hub API — rate limiting (`api/`)
The hub registers `@fastify/rate-limit` globally and attaches stricter presets to selected routes (`api/src/plugins/rate-limit.ts`, `api/src/index.ts`). Defaults and env tunables are documented in the plugin header (`RATE_*`, body size caps).
### Request augmentation: `ingest_token_id`
Hub ingest handlers (e.g. future `POST /api/ingest/*`) **may** set `request.ingest_token_id` to the authenticated ingest key’s stable id **before** the rate-limit hook runs. The ingest preset’s `keyGenerator` then uses `ingest:token:<id>` instead of `ingest:ip:<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`
+1
View File
@@ -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)