]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/middlewares/rate-limiter.ts
Fix runner api rate limit bypass
[github/Chocobozzz/PeerTube.git] / server / middlewares / rate-limiter.ts
CommitLineData
0c9668f7
C
1import express from 'express'
2import RateLimit, { Options as RateLimitHandlerOptions } from 'express-rate-limit'
e915cde3 3import { CONFIG } from '@server/initializers/config'
0c9668f7 4import { RunnerModel } from '@server/models/runner/runner'
e5a781ec 5import { UserRole } from '@shared/models'
e5a781ec
C
6import { optionalAuthenticate } from './auth'
7
8const whitelistRoles = new Set([ UserRole.ADMINISTRATOR, UserRole.MODERATOR ])
9
0c9668f7 10export function buildRateLimiter (options: {
e5a781ec
C
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) => {
0c9668f7
C
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
e5a781ec
C
32 return optionalAuthenticate(req, res, () => {
33 if (res.locals.authenticated === true && whitelistRoles.has(res.locals.oauth.token.User.role)) {
34 return next()
35 }
36
0c9668f7 37 return sendRateLimited(res, options)
e5a781ec
C
38 })
39 }
40 })
41}
42
e915cde3
C
43export const apiRateLimiter = buildRateLimiter({
44 windowMs: CONFIG.RATES_LIMIT.API.WINDOW_MS,
45 max: CONFIG.RATES_LIMIT.API.MAX
46})
47
0c9668f7
C
48// ---------------------------------------------------------------------------
49// Private
50// ---------------------------------------------------------------------------
51
52function sendRateLimited (res: express.Response, options: RateLimitHandlerOptions) {
53 return res.status(options.statusCode).send(options.message)
e5a781ec 54}