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

+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;
};
}
}