Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
- `pnpm run test:all` before release or before merge of large refactors.
- If you add tests, list the exact `pnpm exec vitest run <path>` command in the PR description.
- `GET /api/parser-health` (API key required) for parser status and metrics.
- API rate limiting: `config.api.rateLimit` (defaults: 120 req/min/ip). Keyed strictly by IP to prevent token-rotation bypass. Responses use IETF `RateLimit*` headers (`draft-7`). Set `trustProxy: true` behind a reverse proxy so the real client IP is used.
- `GET /api/health` (no auth) returns `{ ok, uptime, services, parserOk }` — safe for container healthchecks and load balancer probes.
- `GET /api/metrics` (no auth) returns Prometheus text-format metrics: `bot_up`, `bot_uptime_seconds`, `bot_services_enabled`, `bot_service_enabled{service=...}`, `bot_parser_ok`, `bot_parser_last_update_timestamp_seconds`, `bot_parser_staleness_seconds`, `bot_process_memory_bytes{area=...}`.

Expand Down
8 changes: 7 additions & 1 deletion config.example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,13 @@ export const config: ConfigScheme = {
noticer: true
},
api: {
url: '/api'
url: '/api',
rateLimit: {
enabled: true,
windowMs: 60_000,
max: 120,
trustProxy: false
}
},
alice: {},
google: {
Expand Down
6 changes: 6 additions & 0 deletions config.scheme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ export type ConfigScheme = {
// apk: {},
api: {
url: string;
rateLimit?: {
enabled?: boolean;
windowMs?: number;
max?: number;
trustProxy?: boolean;
};
};
alice: {};
google: {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"cron": "^4.4.0",
"express": "^5.2.1",
"express-async-handler": "^1.2.0",
"express-rate-limit": "^8.4.0",
"gaxios": "^7.1.4",
"googleapis": "^171.4.0",
"got": "^11.8.6",
Expand Down
17 changes: 15 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 14 additions & 1 deletion src/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,20 @@ const viberSchema = z.object({
});

const apiSchema = z.object({
url: z.string().min(1)
url: z.string().min(1),
rateLimit: z
.object({
enabled: z.boolean().default(true),
windowMs: z.number().int().positive().default(60_000),
max: z.number().int().positive().default(120),
trustProxy: z.boolean().default(false)
})
.default({
enabled: true,
windowMs: 60_000,
max: 120,
trustProxy: false
})
});

const googleSchema = z.object({
Expand Down
3 changes: 3 additions & 0 deletions src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ export class HttpService implements AppService {
}

public run() {
if (config.api.rateLimit?.trustProxy) {
this.http.set('trust proxy', 1);
}
this.http.use(express.static('./public/'));
this.http.use((req, res, next) => {
const incoming = req.header('x-request-id');
Expand Down
31 changes: 31 additions & 0 deletions src/services/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Request, Response } from 'express';
import rateLimit, { ipKeyGenerator } from 'express-rate-limit';
import { readdirSync } from 'fs';
import path from 'path';
import { StatusCode } from 'status-code-enum';
Expand All @@ -11,6 +12,27 @@ import { Logger } from '../../logger';
import { ApiKeyModel } from './key';
import ApiDefaultMethod, { HandlerParams } from './methods/_default';

export type ApiRateLimitConfig = {
enabled: boolean;
windowMs: number;
max: number;
trustProxy: boolean;
};

export const createApiRateLimiter = (rl: Pick<ApiRateLimitConfig, 'windowMs' | 'max'>) =>
rateLimit({
windowMs: rl.windowMs,
limit: rl.max,
standardHeaders: 'draft-7',
legacyHeaders: false,
keyGenerator: (request) => ipKeyGenerator(request.ip ?? ''),
handler: (_request, response) => {
response.status(StatusCode.ClientErrorTooManyRequests).send({
error: 'Превышен лимит запросов'
});
}
});

export class Api implements AppService {
private readonly logger = new Logger('API');
private loaded: {
Expand Down Expand Up @@ -39,6 +61,15 @@ export class Api implements AppService {

this.loadMethods();

const rl = {
enabled: config.api.rateLimit?.enabled ?? true,
windowMs: config.api.rateLimit?.windowMs ?? 60_000,
max: config.api.rateLimit?.max ?? 120
};
if (rl.enabled) {
server.use(`${config.api.url}/:method`, createApiRateLimiter(rl));
}

server.use(`${config.api.url}/:method`, (request, response) => {
const requestId = request.header('x-request-id') || newTraceId();
return runWithLogContext(
Expand Down
47 changes: 47 additions & 0 deletions tests/api/rate-limit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import express from 'express';
import request from 'supertest';
import { describe, expect, it } from 'vitest';
import { createApiRateLimiter } from '../../src/services/api';

const mkServer = (max: number) => {
const srv = express();
srv.use('/api/:method', createApiRateLimiter({ windowMs: 60_000, max }));
srv.get('/api/:method', (_req, res) => res.json({ ok: true }));
return srv;
};

describe('createApiRateLimiter', () => {
it('returns 429 after the configured max is exceeded for anonymous ip', async () => {
const srv = mkServer(3);
const agent = request.agent(srv);

for (let i = 0; i < 3; i++) {
const res = await agent.get('/api/info');
expect(res.status).toBe(200);
}
const overflow = await agent.get('/api/info');
expect(overflow.status).toBe(429);
expect(overflow.body.error).toBe('Превышен лимит запросов');
});

it('limits by ip regardless of authorization header (prevents token rotation bypass)', async () => {
const srv = mkServer(3);
const agent = request.agent(srv);

for (let i = 0; i < 3; i++) {
const res = await agent.get('/api/info').set('authorization', `Bearer rotating-${i}`);
expect(res.status).toBe(200);
}
const overflow = await agent.get('/api/info').set('authorization', 'Bearer rotating-overflow');
expect(overflow.status).toBe(429);
});

it('emits RateLimit standard headers on successful requests', async () => {
const srv = mkServer(5);
const res = await request(srv).get('/api/info');

expect(res.status).toBe(200);
expect(res.headers['ratelimit']).toBeDefined();
expect(res.headers['x-ratelimit-limit']).toBeUndefined();
});
});
Loading