Skip to content

Commit

Permalink
feat: rate limit per measurement id
Browse files Browse the repository at this point in the history
  • Loading branch information
alexey-yarmosh committed Sep 26, 2024
1 parent 50b3004 commit 601d673
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
11 changes: 6 additions & 5 deletions src/lib/rate-limiter/rate-limiter-get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,32 +22,33 @@ export const authenticatedRateLimiter = new RateLimiterRedis({
duration: config.get<number>('measurement.rateLimit.get.reset'),
});

const getRateLimiter = (ctx: ExtendedContext): {
const getRateLimiter = (ctx: ExtendedContext, extraId?: string): {
type: 'user'| 'ip',
id: string,
rateLimiter: RateLimiterRedis
} => {
if (ctx.state.user?.id) {
return {
type: 'user',
id: ctx.state.user.id,
id: extraId ? `${ctx.state.user.id}:${extraId}` : ctx.state.user.id,
rateLimiter: authenticatedRateLimiter,
};
}

const ip = requestIp.getClientIp(ctx.req) ?? '';
return {
type: 'ip',
id: requestIp.getClientIp(ctx.req) ?? '',
id: extraId ? `${ip}:${extraId}` : ip,
rateLimiter: anonymousRateLimiter,
};
};

export const rateLimitMW = async (ctx: ExtendedContext, next: Next) => {
export const getMeasurementRateLimit = async (ctx: ExtendedContext, next: Next) => {
if (ctx['isAdmin']) {
return next();
}

const { rateLimiter, id } = getRateLimiter(ctx);
const { rateLimiter, id } = getRateLimiter(ctx, ctx.params['id']);

try {
await rateLimiter.consume(id);
Expand Down
4 changes: 2 additions & 2 deletions src/measurement/route/get-measurement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type Router from '@koa/router';
import { getMeasurementStore } from '../store.js';
import { corsAuthHandler } from '../../lib/http/middleware/cors.js';
import { authenticate } from '../../lib/http/middleware/authenticate.js';
import { rateLimitMW } from '../../lib/rate-limiter/rate-limiter-get.js';
import { getMeasurementRateLimit } from '../../lib/rate-limiter/rate-limiter-get.js';

const store = getMeasurementStore();

Expand All @@ -27,5 +27,5 @@ const handle = async (ctx: ParameterizedContext<DefaultState, DefaultContext & R
};

export const registerGetMeasurementRoute = (router: Router): void => {
router.get('/measurements/:id', '/measurements/:id([a-zA-Z0-9]+)', corsAuthHandler(), authenticate(), rateLimitMW, handle);
router.get('/measurements/:id', '/measurements/:id([a-zA-Z0-9]+)', corsAuthHandler(), authenticate(), getMeasurementRateLimit, handle);
};

0 comments on commit 601d673

Please sign in to comment.