Skip to content

Commit

Permalink
feat: rate limitter
Browse files Browse the repository at this point in the history
  • Loading branch information
kraikov committed Oct 19, 2023
1 parent f368e41 commit 0579d7d
Show file tree
Hide file tree
Showing 13 changed files with 1,433 additions and 1,332 deletions.
18 changes: 14 additions & 4 deletions apps/gateway/src/gateway.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,30 @@ import { UserJwtStrategy } from '@lib/guards';
import { HealthModule } from '@lib/health';
import { LoggerModule } from '@lib/logger';
import { MetricsModule } from '@lib/metrics';
import { CustomFaviconMiddleware, NodeRateLimiterMiddleware } from '@lib/middlewares';
import { CustomFaviconMiddleware } from '@lib/middlewares';
import { PrismaModule } from '@lib/prisma';
import { RateLimiterModule } from '@lib/rate.limiter';
import { ServiceRegistryModule } from '@lib/service.registry';
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { ThrottlerGuard } from '@nestjs/throttler';
import { Clients } from './gateway.providers';
import { AuthController } from './services/auth/auth.controller';

@Module({
imports: [LoggerModule, AuditLoggerModule, ServiceRegistryModule, HealthModule, MetricsModule, PrismaModule],
imports: [LoggerModule, AuditLoggerModule, ServiceRegistryModule, HealthModule, MetricsModule, PrismaModule, RateLimiterModule],
controllers: [AuthController],
providers: [...Clients, UserJwtStrategy],
providers: [
...Clients,
UserJwtStrategy,
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class GatewayModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(CustomFaviconMiddleware, NodeRateLimiterMiddleware).forRoutes('*');
consumer.apply(CustomFaviconMiddleware).forRoutes('*');
}
}
6 changes: 6 additions & 0 deletions apps/gateway/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useLogger } from '@lib/logger';
import { Logger, VERSION_NEUTRAL, ValidationPipe, VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import * as compression from 'compression';
import helmet from 'helmet';
import { GatewayModule } from './gateway.module';
import { getServerLoadEvent } from './logServerLoadEvent';
import { setupSwagger } from './swagger';
Expand Down Expand Up @@ -41,6 +42,11 @@ async function bootstrap() {
*/
app.use(compression());

/**
* Use security middlewares
*/
app.use(helmet());

/**
* Enable CORS
*/
Expand Down
5 changes: 4 additions & 1 deletion libs/config/src/common.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { bool, cleanEnv, str } from 'envalid';
import { bool, cleanEnv, num, str } from 'envalid';
import { v4 as uuidv4 } from 'uuid';

export default cleanEnv(process.env, {
Expand All @@ -10,4 +10,7 @@ export default cleanEnv(process.env, {
INSTANCE_ID: str({ default: uuidv4() }),

API_CACHE_ENABLED: bool({ default: false }),

API_RATE_LIMITTER_TTL: num({ default: 60 }),
API_RATE_LIMITTER_LIMIT: num({ default: 60 }),
});
1 change: 0 additions & 1 deletion libs/middlewares/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from './middleware.module';

export { CustomFaviconMiddleware } from './favico.middleware';
export { NodeRateLimiterMiddleware } from './rate.limiter.middleware';
5 changes: 2 additions & 3 deletions libs/middlewares/src/middleware.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { Module } from '@nestjs/common';
import { CustomFaviconMiddleware } from './favico.middleware';
import { NodeRateLimiterMiddleware } from './rate.limiter.middleware';

@Module({
providers: [NodeRateLimiterMiddleware, CustomFaviconMiddleware],
exports: [NodeRateLimiterMiddleware, CustomFaviconMiddleware],
providers: [CustomFaviconMiddleware],
exports: [CustomFaviconMiddleware],
})
export class MiddlewareModule {}
13 changes: 0 additions & 13 deletions libs/middlewares/src/rate.limiter.middleware.ts

This file was deleted.

1 change: 1 addition & 0 deletions libs/rate.limiter/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './rate.limiter.module';
19 changes: 19 additions & 0 deletions libs/rate.limiter/src/rate.limiter.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Config } from '@lib/config';
import { Module } from '@nestjs/common';
import { ThrottlerModule, seconds } from '@nestjs/throttler';
import { Redis } from 'ioredis';
import { ThrottlerStorageRedisService } from 'nestjs-throttler-storage-redis';

@Module({
imports: [
ThrottlerModule.forRoot({
throttlers: [{ limit: Config.API_RATE_LIMITTER_LIMIT, ttl: seconds(Config.API_RATE_LIMITTER_TTL) }],
storage: new ThrottlerStorageRedisService(
new Redis({ host: Config.REDIS_HOST, port: Config.REDIS_PORT, password: Config.REDIS_PASSWORD }),
),
}),
],
providers: [],
exports: [],
})
export class RateLimiterModule {}
9 changes: 9 additions & 0 deletions libs/rate.limiter/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"declaration": true,
"outDir": "../../dist/libs/rate.limiter"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}
9 changes: 9 additions & 0 deletions nest-cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,15 @@
"compilerOptions": {
"tsConfigPath": "libs/guards/tsconfig.lib.json"
}
},
"rate.limiter": {
"type": "library",
"root": "libs/rate.limiter",
"entryFile": "index",
"sourceRoot": "libs/rate.limiter/src",
"compilerOptions": {
"tsConfigPath": "libs/rate.limiter/tsconfig.lib.json"
}
}
}
}
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"@nestjs/schedule": "3.0.4",
"@nestjs/swagger": "7.1.13",
"@nestjs/terminus": "10.1.1",
"@nestjs/throttler": "5.0.0",
"@prisma/client": "5.4.1",
"@willsoto/nestjs-prometheus": "5.5.1",
"argon2": "0.31.1",
Expand All @@ -58,6 +59,7 @@
"lodash": "4.17.21",
"luxon": "3.4.3",
"nestjs-pino": "3.5.0",
"nestjs-throttler-storage-redis": "0.4.1",
"passport-jwt": "4.0.1",
"pino-pretty": "10.2.3",
"prisma-field-encryption": "1.5.0",
Expand Down Expand Up @@ -134,7 +136,8 @@
"^@lib/service.registry(|/.*)$": "<rootDir>/libs/service.registry/src/$1",
"^@lib/metrics(|/.*)$": "<rootDir>/libs/metrics/src/$1",
"^@lib/dtos(|/.*)$": "<rootDir>/libs/dtos/src/$1",
"^@lib/guards(|/.*)$": "<rootDir>/libs/guards/src/$1"
"^@lib/guards(|/.*)$": "<rootDir>/libs/guards/src/$1",
"^@lib/rate.limiter(|/.*)$": "<rootDir>/libs/rate.limiter/src/$1"
}
}
}
Loading

0 comments on commit 0579d7d

Please sign in to comment.