]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/rate-limiter.ts
Fix runner api rate limit bypass
[github/Chocobozzz/PeerTube.git] / server / middlewares / rate-limiter.ts
1 import express from 'express'
2 import RateLimit, { Options as RateLimitHandlerOptions } from 'express-rate-limit'
3 import { CONFIG } from '@server/initializers/config'
4 import { RunnerModel } from '@server/models/runner/runner'
5 import { UserRole } from '@shared/models'
6 import { optionalAuthenticate } from './auth'
7
8 const whitelistRoles = new Set([ UserRole.ADMINISTRATOR, UserRole.MODERATOR ])
9
10 export function buildRateLimiter (options: {
11 windowMs: number
12 max: number
13 skipFailedRequests?: boolean
14 }) {
15 return RateLimit({
16 windowMs: options.windowMs,
17 max: options.max,
18 skipFailedRequests: options.skipFailedRequests,
19
20 handler: (req, res, next, options) => {
21 // Bypass rate limit for registered runners
22 if (req.body?.runnerToken) {
23 return RunnerModel.loadByToken(req.body.runnerToken)
24 .then(runner => {
25 if (runner) return next()
26
27 return sendRateLimited(res, options)
28 })
29 }
30
31 // Bypass rate limit for admins/moderators
32 return optionalAuthenticate(req, res, () => {
33 if (res.locals.authenticated === true && whitelistRoles.has(res.locals.oauth.token.User.role)) {
34 return next()
35 }
36
37 return sendRateLimited(res, options)
38 })
39 }
40 })
41 }
42
43 export const apiRateLimiter = buildRateLimiter({
44 windowMs: CONFIG.RATES_LIMIT.API.WINDOW_MS,
45 max: CONFIG.RATES_LIMIT.API.MAX
46 })
47
48 // ---------------------------------------------------------------------------
49 // Private
50 // ---------------------------------------------------------------------------
51
52 function sendRateLimited (res: express.Response, options: RateLimitHandlerOptions) {
53 return res.status(options.statusCode).send(options.message)
54 }