a537d34dcc
* Demonstration of bug to test when middleware added - Adding middleware, even no-op, causes test to fail * Make middleware async, but introduce delay. Revert test back to original. * Revert tests * Add a 1ms sleep to the test to reduce likelihood of flakiness * Rate limiting on all express endpoints using middleware * Adds all configuration for existing rate limited endpoints * It is helpful to add the package to yarn first * Implements respectsLimits using Redis rate limiter * Fix for test `Should rate-limit user creation` - if rate limit error, post to `/auth/local/register` will return a 429 status code * All rate limiting provided by new ratelimiter.ts * Consolidate typescript interfaces * Amend signature of function to require source to be passed in, and not try to guess it from the request * Rename respectsLimits to isWithinRateLimits * Throw within catch of Promise * Replace rejectsRequestWithRatelimitStatusIfNeeded throughout code * Sending rate limit response should deal with other types of error - Sentry notified of the error * Express middleware rate limits by a 3 second burst or a daily rate - Provide action when generating 429 response * Prevent DOS of Redis * Add 'Retry-After' for all cases when responding with 429 status code - default of 1 day, but dynamic based on available information * Generate rate limiters once, on init - Improved and consistent handling of exit from functions - fixed environment variable names * WIP Refactor rate limiting setup Co-authored-by: Iain Sproat <iainsproat@users.noreply.github.com> * WIP: fixed references, now runs but tests fail * Use getSourceFromRequest where possible * WIP: unit tests for rate limiter * Unit tests for ratelimiter * feat(IFC): WIP IFC parser improvements * Revert "feat(IFC): WIP IFC parser improvements" This reverts commit093089a2c4. * refactor authz, rate limiting middleware to global Co-authored-by: Kristaps Fabians Geikins <fabis94@users.noreply.github.com> Co-authored-by: Iain Sproat <iainsproat@users.noreply.github.com> * invites tests fix * fix(server ratelimiter): export public interfaces * Unit test for rate limiter use in memory rate limiter - in memory rate limiter is configured with zero limit by default * Fixed #1219 (#1221) * WIP: improve auth test for rate limiting user creation * ci(circleci config): publishing was broken when main branch was tagged (i.e. for releases) (#1224) * Gitignore CPU profiles * All tests are now passing locally * Fixed an issue in the frontend which was causing the views not to work. Fixed an issue with object selection camera animation where the dolly lerp factor was much too high for smooth animation (#1225) * feat(structured logging): implements structured logging for backend (#1217) * each log line is a json object * structured logging allows logs to be ingested by machines and the logs to be indexed and queried addresses #1105 * structured logging allows arbitrary properties to be appended to each log line, and ingestion of logs to remain robust * Structured logging provided by `pino` library * Add `express-pino-logger` dependency * Remove `debug`, `morgan`, and `morgan-debug` and replace with structured logging * `console.log` & `console.error` replaced with structured logging in backend * Remove `DEBUG` environment variable and replace with `LOG_LEVEL` - Note that there is a test which reads from a logged line on `stdout`. This is not robust, it would be better to use the childProcess.pid to look up the port number. * Log errors at points we explicitly send error to Sentry * Amend indentation of a couple of log messages to align indentation with others * Revert "feat(structured logging): implements structured logging for backend (#1217)" (#1227) This reverts commit84cb74e8b3. * Move error to core/errors - augmented typescript types moved to type-augmentations * Added a missing wait in the screenshot generation loop (#1228) * refactor(server rest api): remove duplicate rate limit requests * feat(server rate limits): increase rate limits for the upload endpoints * chore(server rate limits): final cleanup Co-authored-by: Gergő Jedlicska <gergo@jedlicska.com> Co-authored-by: Iain Sproat <iainsproat@users.noreply.github.com> Co-authored-by: Dimitrie Stefanescu <didimitrie@gmail.com> Co-authored-by: Kristaps Fabians Geikins <fabis94@users.noreply.github.com> Co-authored-by: Kristaps Fabians Geikins <fabis94@live.com> Co-authored-by: Alexandru Popovici <alexandrupopoviciioan@gmail.com>
314 lines
9.7 KiB
TypeScript
314 lines
9.7 KiB
TypeScript
import express, { RequestWithAuthContext } from 'express'
|
|
import Redis from 'ioredis'
|
|
import {
|
|
getRedisUrl,
|
|
getIntFromEnv,
|
|
isTestEnv
|
|
} from '@/modules/shared/helpers/envHelper'
|
|
import {
|
|
BurstyRateLimiter,
|
|
RateLimiterAbstract,
|
|
RateLimiterMemory,
|
|
RateLimiterRedis,
|
|
RateLimiterRes
|
|
} from 'rate-limiter-flexible'
|
|
import { TIME } from '@speckle/shared'
|
|
import { getIpFromRequest } from '@/modules/shared/utils/ip'
|
|
import { RateLimitError } from '@/modules/core/errors/ratelimit'
|
|
|
|
// typescript definitions
|
|
export enum RateLimitAction {
|
|
ALL_REQUESTS = 'ALL_REQUESTS',
|
|
USER_CREATE = 'USER_CREATE',
|
|
STREAM_CREATE = 'STREAM_CREATE',
|
|
COMMIT_CREATE = 'COMMIT_CREATE',
|
|
'POST /api/getobjects/:streamId' = 'POST /api/getobjects/:streamId',
|
|
'POST /api/diff/:streamId' = 'POST /api/diff/:streamId',
|
|
'POST /objects/:streamId' = 'POST /objects/:streamId',
|
|
'GET /objects/:streamId/:objectId' = 'GET /objects/:streamId/:objectId',
|
|
'GET /objects/:streamId/:objectId/single' = 'GET /objects/:streamId/:objectId/single',
|
|
'POST /graphql' = 'POST /graphql'
|
|
}
|
|
|
|
export interface RateLimitResult {
|
|
isWithinLimits: boolean
|
|
action: RateLimitAction
|
|
}
|
|
|
|
export interface RateLimitSuccess extends RateLimitResult {
|
|
isWithinLimits: true
|
|
remainingPoints: number
|
|
}
|
|
|
|
export interface RateLimitBreached extends RateLimitResult {
|
|
isWithinLimits: false
|
|
msBeforeNext: number
|
|
}
|
|
|
|
type BurstyRateLimiterOptions = {
|
|
regularOptions: RateLimits
|
|
burstOptions: RateLimits
|
|
}
|
|
|
|
export type RateLimits = {
|
|
limitCount: number
|
|
duration: number
|
|
}
|
|
|
|
type RateLimiterOptions = {
|
|
[key in RateLimitAction]: BurstyRateLimiterOptions
|
|
}
|
|
|
|
export type RateLimiterMapping = {
|
|
[key in RateLimitAction]: (
|
|
source: string
|
|
) => Promise<RateLimitSuccess | RateLimitBreached>
|
|
}
|
|
|
|
export const LIMITS: RateLimiterOptions = {
|
|
ALL_REQUESTS: {
|
|
regularOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_ALL_REQUESTS', '500'),
|
|
duration: 1 * TIME.second
|
|
},
|
|
burstOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_BURST_ALL_REQUESTS', '2000'),
|
|
duration: 1 * TIME.minute
|
|
}
|
|
},
|
|
USER_CREATE: {
|
|
regularOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_USER_CREATE', '6'),
|
|
duration: 1 * TIME.hour
|
|
},
|
|
burstOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_BURST_USER_CREATE', '1000'),
|
|
duration: 1 * TIME.week
|
|
}
|
|
},
|
|
STREAM_CREATE: {
|
|
regularOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_STREAM_CREATE', '1'),
|
|
duration: 1 * TIME.second
|
|
},
|
|
burstOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_BURST_STREAM_CREATE', '100'),
|
|
duration: 1 * TIME.minute
|
|
}
|
|
},
|
|
COMMIT_CREATE: {
|
|
regularOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_COMMIT_CREATE', '1'),
|
|
duration: 1 * TIME.second
|
|
},
|
|
burstOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_BURST_COMMIT_CREATE', '100'),
|
|
duration: 1 * TIME.minute
|
|
}
|
|
},
|
|
'POST /api/getobjects/:streamId': {
|
|
regularOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_POST_GETOBJECTS_STREAMID', '3'),
|
|
duration: 1 * TIME.second
|
|
},
|
|
burstOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_BURST_POST_GETOBJECTS_STREAMID', '200'),
|
|
duration: 1 * TIME.minute
|
|
}
|
|
},
|
|
'POST /api/diff/:streamId': {
|
|
regularOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_POST_DIFF_STREAMID', '10'),
|
|
duration: 1 * TIME.second
|
|
},
|
|
burstOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_BURST_POST_DIFF_STREAMID', '1000'),
|
|
duration: 1 * TIME.minute
|
|
}
|
|
},
|
|
'POST /objects/:streamId': {
|
|
regularOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_POST_OBJECTS_STREAMID', '6'),
|
|
duration: 1 * TIME.second
|
|
},
|
|
burstOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_BURST_POST_OBJECTS_STREAMID', '400'),
|
|
duration: 1 * TIME.minute
|
|
}
|
|
},
|
|
'GET /objects/:streamId/:objectId': {
|
|
regularOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_GET_OBJECTS_STREAMID_OBJECTID', '3'),
|
|
duration: 1 * TIME.second
|
|
},
|
|
burstOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_BURST_GET_OBJECTS_STREAMID_OBJECTID', '200'),
|
|
duration: 1 * TIME.minute
|
|
}
|
|
},
|
|
'GET /objects/:streamId/:objectId/single': {
|
|
regularOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_GET_OBJECTS_STREAMID_OBJECTID_SINGLE', '3'),
|
|
duration: 1 * TIME.second
|
|
},
|
|
burstOptions: {
|
|
limitCount: getIntFromEnv(
|
|
'RATELIMIT_BURST_GET_OBJECTS_STREAMID_OBJECTID_SINGLE',
|
|
'200'
|
|
),
|
|
duration: 1 * TIME.minute
|
|
}
|
|
},
|
|
'POST /graphql': {
|
|
regularOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_POST_GRAPHQL', '50'),
|
|
duration: 1 * TIME.second
|
|
},
|
|
burstOptions: {
|
|
limitCount: getIntFromEnv('RATELIMIT_BURST_POST_GRAPHQL', '200'),
|
|
duration: 1 * TIME.minute
|
|
}
|
|
}
|
|
}
|
|
|
|
export const sendRateLimitResponse = (
|
|
res: express.Response,
|
|
rateLimitBreached: RateLimitBreached
|
|
): express.Response => {
|
|
res.setHeader('Retry-After', rateLimitBreached.msBeforeNext / 1000)
|
|
res.removeHeader('X-RateLimit-Remaining')
|
|
res.setHeader(
|
|
'X-RateLimit-Reset',
|
|
new Date(Date.now() + rateLimitBreached.msBeforeNext).toISOString()
|
|
)
|
|
res.setHeader('X-Speckle-Meditation', 'https://http.cat/429')
|
|
return res.status(429).send({
|
|
err: 'You are sending too many requests. You have been rate limited. Please try again later.'
|
|
})
|
|
}
|
|
|
|
export const getActionForPath = (path: string, verb: string): RateLimitAction => {
|
|
const maybeAction = `${verb} ${path}` as keyof typeof RateLimitAction
|
|
return RateLimitAction[maybeAction] || RateLimitAction.ALL_REQUESTS
|
|
}
|
|
|
|
export const getSourceFromRequest = (req: express.Request): string => {
|
|
let source: string | null =
|
|
((req as RequestWithAuthContext)?.context?.userId as string) ||
|
|
getIpFromRequest(req)
|
|
|
|
if (!source) source = 'unknown'
|
|
return source
|
|
}
|
|
|
|
export const createRateLimiterMiddleware = (
|
|
rateLimiterMapping: RateLimiterMapping = RATE_LIMITERS
|
|
) => {
|
|
return async (
|
|
req: express.Request,
|
|
res: express.Response,
|
|
next: express.NextFunction
|
|
) => {
|
|
if (isTestEnv()) return next()
|
|
const path = req.originalUrl ? req.originalUrl : req.path
|
|
const action = getActionForPath(path, req.method)
|
|
const source = getSourceFromRequest(req)
|
|
|
|
const rateLimitResult = await getRateLimitResult(action, source, rateLimiterMapping)
|
|
if (isRateLimitBreached(rateLimitResult)) {
|
|
return sendRateLimitResponse(res, rateLimitResult)
|
|
} else {
|
|
try {
|
|
res.setHeader('X-RateLimit-Remaining', rateLimitResult.remainingPoints)
|
|
return next()
|
|
} catch (err) {
|
|
if (!(err instanceof RateLimitError)) throw err
|
|
return sendRateLimitResponse(res, err.rateLimitBreached)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// we need to take the `BurstyRateLimiter` specific type because
|
|
// its not considered as an RateLimiterAbstract in the rate-limiter-flexible package
|
|
// This is just a rant comment, but why define the Abstract then if not
|
|
// all RateLimiters are implementing it?
|
|
export const createConsumer =
|
|
(action: RateLimitAction, rateLimiter: RateLimiterAbstract | BurstyRateLimiter) =>
|
|
async (source: string): Promise<RateLimitSuccess | RateLimitBreached> => {
|
|
try {
|
|
const rateLimitRes = await rateLimiter.consume(source)
|
|
return {
|
|
action,
|
|
isWithinLimits: true,
|
|
remainingPoints: rateLimitRes.remainingPoints
|
|
}
|
|
} catch (err) {
|
|
if (err instanceof RateLimiterRes)
|
|
return { action, isWithinLimits: false, msBeforeNext: err.msBeforeNext }
|
|
throw err
|
|
}
|
|
}
|
|
|
|
export const initializeRedisRateLimiters = (
|
|
options: RateLimiterOptions = LIMITS
|
|
): RateLimiterMapping => {
|
|
const redisClient = new Redis(getRedisUrl(), {
|
|
enableReadyCheck: false,
|
|
maxRetriesPerRequest: null
|
|
})
|
|
const allActions = Object.values(RateLimitAction)
|
|
const mapping = Object.fromEntries(
|
|
allActions.map((action) => {
|
|
const limits = options[action]
|
|
const burstyLimiter = new BurstyRateLimiter(
|
|
new RateLimiterRedis({
|
|
storeClient: redisClient,
|
|
keyPrefix: action,
|
|
points: limits.regularOptions.limitCount,
|
|
duration: limits.regularOptions.duration,
|
|
inMemoryBlockOnConsumed: limits.regularOptions.limitCount, // stops additional requests going to Redis once the limit is reached
|
|
inMemoryBlockDuration: limits.regularOptions.duration,
|
|
insuranceLimiter: new RateLimiterMemory({
|
|
keyPrefix: action,
|
|
points: limits.regularOptions.limitCount,
|
|
duration: limits.regularOptions.duration
|
|
})
|
|
}),
|
|
new RateLimiterRedis({
|
|
storeClient: redisClient,
|
|
keyPrefix: `BURST_${action}`,
|
|
points: limits.burstOptions.limitCount,
|
|
duration: limits.burstOptions.duration,
|
|
inMemoryBlockOnConsumed: limits.burstOptions.limitCount,
|
|
inMemoryBlockDuration: limits.burstOptions.duration,
|
|
insuranceLimiter: new RateLimiterMemory({
|
|
keyPrefix: `BURST_${action}`,
|
|
points: limits.burstOptions.limitCount,
|
|
duration: limits.burstOptions.duration
|
|
})
|
|
})
|
|
)
|
|
|
|
return [action, createConsumer(action, burstyLimiter)]
|
|
})
|
|
)
|
|
// i know that all the values are in there, but TS doesn't...
|
|
return mapping as RateLimiterMapping
|
|
}
|
|
|
|
export const RATE_LIMITERS = initializeRedisRateLimiters()
|
|
|
|
export const isRateLimitBreached = (
|
|
rateLimitResult: RateLimitResult
|
|
): rateLimitResult is RateLimitBreached => !rateLimitResult.isWithinLimits
|
|
|
|
export async function getRateLimitResult(
|
|
action: RateLimitAction,
|
|
source: string,
|
|
rateLimiterMapping: RateLimiterMapping = RATE_LIMITERS
|
|
): Promise<RateLimitSuccess | RateLimitBreached> {
|
|
const consumerFunc = rateLimiterMapping[action]
|
|
return await consumerFunc(source)
|
|
}
|