Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat] Add Rate Limiting to authenticate endpoint #445

Merged
merged 10 commits into from
Mar 1, 2025

Conversation

samuelmbabhazi
Copy link
Contributor

@samuelmbabhazi samuelmbabhazi commented Jan 17, 2025

Before submitting the PR, please make sure you do the following

  1. Contributor license agreement
    For us it's important to have the agreement of our contributors to use their work, whether it be code or documentation. Therefore, we are asking all contributors to sign a contributor license agreement (CLA) as commonly accepted in most open source projects. Just open the pull request and our CLA bot will prompt you briefly.

  2. Please check our contribution guidelines for some help in the process.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added rate limiting to protect against excessive authentication requests.
    • Implemented Redis-based user login attempt tracking.
  • Security Enhancements

    • Added custom throttling guard to prevent potential abuse.
    • Enhanced login attempt management with configurable limits.
  • Performance

    • Integrated configuration management and Redis support.
  • Chores

    • Disabled Angular CLI analytics.
    • Updated project dependencies.

Copy link

vercel bot commented Jan 17, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
traduora-docs-co ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 24, 2025 7:11pm

@samuelmbabhazi samuelmbabhazi self-assigned this Jan 17, 2025
Copy link

coderabbitai bot commented Jan 17, 2025

Walkthrough

This pull request introduces several enhancements to the API project's security and configuration management. The changes focus on implementing rate limiting, adding Redis support, and improving user authentication mechanisms. The modifications span multiple files, including package.json, app.module.ts, and various service and controller files. The primary additions include new dependencies for configuration management, request throttling, and Redis integration, along with new classes to handle user login attempts and custom throttling guards.

Changes

File Change Summary
api/package.json Added dependencies: @nestjs/config, @nestjs/throttler, ioredis
api/src/app.module.ts Imported ThrottlerModule, ConfigModule, RedisModule; Added CustomThrottlerGuard and UserLoginAttemptsStorage as providers
api/src/controllers/auth.controller.ts Added @Throttle decorator to token method with 10 requests per minute limit
api/src/guards/custom-throttler.guard.ts Created new CustomThrottlerGuard with custom error message
api/src/redis/redis.module.ts Added global Redis module with configuration from environment variables
api/src/redis/user-login-attempts.storage.ts Created new storage class for managing user login attempts
api/src/services/user.service.ts Refactored authentication logic to use UserLoginAttemptsStorage
webapp/angular.json Disabled Angular CLI analytics

Poem

🐰 Throttling rabbits, Redis so bright,
Guarding our API with all of our might!
Configs dancing, attempts in check,
Security leaping with each little trek.
Hop, hop, hurray for code so clean! 🚀


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 071a936 and 64d35e2.

📒 Files selected for processing (1)
  • api/src/redis/user-login-attempts.storage.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (4)
api/src/redis/user-login-attempts.storage.ts (4)

7-7: Consider implementing memory limits for in-memory storage.

The in-memory storage should have a maximum size limit to prevent memory exhaustion attacks.

-private inMemoryStorage: Map<string, { attempts: number; expiry: number }> = new Map();
+private readonly MAX_ENTRIES = 10000;
+private inMemoryStorage: Map<string, { attempts: number; expiry: number }> = new Map();
+
+private enforceMemoryLimit(): void {
+  if (this.inMemoryStorage.size >= this.MAX_ENTRIES) {
+    const now = Date.now();
+    // Clean expired entries first
+    for (const [key, value] of this.inMemoryStorage.entries()) {
+      if (value.expiry <= now) {
+        this.inMemoryStorage.delete(key);
+      }
+    }
+    // If still at limit, remove oldest entries
+    if (this.inMemoryStorage.size >= this.MAX_ENTRIES) {
+      const entries = Array.from(this.inMemoryStorage.entries());
+      entries.sort((a, b) => a[1].expiry - b[1].expiry);
+      const entriesToRemove = entries.slice(0, entries.length - this.MAX_ENTRIES + 1);
+      entriesToRemove.forEach(([key]) => this.inMemoryStorage.delete(key));
+    }
+  }
+}

39-69: LGTM! Well-implemented retrieval logic.

The implementation includes proper input validation, safe type coercion, and comprehensive error handling for both storage types.


71-73: Avoid exposing Redis client directly.

Consider removing this method as it exposes the internal implementation details. If needed, create specific methods for the required Redis operations instead.


75-82: LGTM! Efficient cleanup implementation.

The cleanup logic is simple and effective, removing expired entries to prevent memory leaks.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

socket-security bot commented Jan 17, 2025

No dependency changes detected. Learn more about Socket for GitHub ↗︎

👍 No dependency changes detected in pull request

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (3)
api/src/services/user.service.ts (1)

220-264: Add Unit Tests for New Authentication Logic

The newly introduced methods (getLoginAttempts, handlePasswordAuthentication, incrementLoginAttempts, resetLoginAttempts, saveUser) enhance the authentication flow. To ensure their reliability and correctness, consider adding unit tests covering various scenarios, including:

  • Successful authentication with correct credentials.
  • Authentication failures due to incorrect passwords.
  • Handling of login attempt increments and resets.
  • Behavior when Redis is available versus when it is not.
api/src/redis/redis.module.ts (1)

11-13: Enhance configuration validation.

Consider validating the Redis password when provided to ensure secure configuration.

 const redisHost = configService.get<string>('REDIS_HOST');
 const redisPort = configService.get<number>('REDIS_PORT');
 const redisPassword = configService.get<string>('REDIS_PASSWORD');
+
+if (redisPassword === '') {
+  Logger.warn('Redis password is empty. This is not recommended for production.');
+}
api/src/redis/user-login-attempts.storage.ts (1)

29-47: Add rate limiting metrics.

Consider adding metrics for monitoring rate limiting effectiveness.

+private metrics = {
+  totalAttempts: 0,
+  blockedAttempts: 0,
+};

 async getUserAttempts(userKey: string): Promise<number> {
+  this.metrics.totalAttempts++;
   if (this.redisClient) {
     try {
       const attempts = await this.redisClient.get(userKey);
-      return attempts ? parseInt(attempts, 10) : 0;
+      const count = attempts ? parseInt(attempts, 10) : 0;
+      if (count > 0) this.metrics.blockedAttempts++;
+      return count;
     } catch (error) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9516f96 and 0b66e50.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (8)
  • api/package.json (3 hunks)
  • api/src/app.module.ts (4 hunks)
  • api/src/controllers/auth.controller.ts (2 hunks)
  • api/src/guards/custom-throttler.guard.ts (1 hunks)
  • api/src/redis/redis.module.ts (1 hunks)
  • api/src/redis/user-login-attempts.storage.ts (1 hunks)
  • api/src/services/user.service.ts (2 hunks)
  • webapp/angular.json (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: test
🔇 Additional comments (4)
api/src/app.module.ts (1)

85-88: Global Throttling Guard Implemented Successfully

The CustomThrottlerGuard has been correctly set as a global guard using APP_GUARD, ensuring that rate limiting is applied across all controllers in the application.

api/src/controllers/auth.controller.ts (1)

Line range hint 183-234: Enhance error handling for rate-limited requests.

The token endpoint should provide clear feedback when rate limits are exceeded.

webapp/angular.json (1)

108-109: LGTM!

Disabling analytics is a reasonable choice for privacy concerns.

api/package.json (1)

35-35: LGTM! Verify Redis configuration.

The added dependencies align well with the rate limiting implementation:

  • @nestjs/config and @nestjs/throttler versions are compatible with NestJS v10
  • ioredis is appropriate for distributed rate limiting storage

Please ensure Redis configuration is properly validated on startup. Run this script to check if Redis config validation exists:

Also applies to: 41-41, 55-55

✅ Verification successful

Redis configuration validation is properly implemented

The codebase already includes robust Redis configuration validation in redis.module.ts:

  • Validates required REDIS_HOST and REDIS_PORT environment variables
  • Includes graceful fallback to in-memory storage when Redis is not configured
  • Provides clear warning logs for missing configuration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if Redis configuration validation exists
# Expected: Find Redis configuration validation in config files

# Look for Redis configuration validation
rg -i 'redis.*validation|validate.*redis' --type ts

# Look for Redis environment variables
rg -i 'redis.*env|env.*redis' --type ts

Length of output: 95


Script:

#!/bin/bash
# Search for Redis and Throttler configuration
# Look for files containing Redis setup
rg -i "redis" --type ts -A 5

# Look for ThrottlerModule configuration
ast-grep --pattern 'ThrottlerModule.forRoot' -l

# Look for ConfigModule setup with validation
ast-grep --pattern 'ConfigModule.forRoot({
  $$$
  validate: $$$
  $$$
})'

# Find potential config files
fd -e ts -e json config

Length of output: 7925

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
api/src/redis/user-login-attempts.storage.ts (2)

7-7: Add type definition for storage value.

Define an interface for the storage value structure to improve type safety and maintainability.

+interface LoginAttempt {
+  attempts: number;
+  expiry: number;
+}
-private inMemoryStorage: Map<string, { attempts: number; expiry: number }> = new Map();
+private inMemoryStorage: Map<string, LoginAttempt> = new Map();

55-62: Add error handling and metrics to cleanup process.

The cleanup process should handle errors and track metrics for monitoring.

 private cleanupExpiredEntries(): void {
-  const now = Date.now();
-  for (const [key, value] of this.inMemoryStorage.entries()) {
-    if (value.expiry <= now) {
-      this.inMemoryStorage.delete(key);
+  try {
+    const now = Date.now();
+    let cleanedEntries = 0;
+    for (const [key, value] of this.inMemoryStorage.entries()) {
+      if (value.expiry <= now) {
+        this.inMemoryStorage.delete(key);
+        cleanedEntries++;
+      }
     }
+    this.logger.debug(`Cleaned up ${cleanedEntries} expired entries`);
+  } catch (error) {
+    this.logger.error('Error during cleanup:', error.message);
   }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7ab1d47 and 071a936.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (2)
  • api/src/redis/user-login-attempts.storage.ts (1 hunks)
  • api/src/services/user.service.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/src/services/user.service.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test
🔇 Additional comments (2)
api/src/redis/user-login-attempts.storage.ts (2)

7-7: Consider implementing memory limits for in-memory storage.

The in-memory storage should have a maximum size limit to prevent memory exhaustion attacks.


9-15: Verify Redis client connection status.

The constructor should verify that the Redis client is properly connected before using it.

 constructor(@Inject('REDIS_CLIENT') private readonly redisClient?: Redis) {
   if (!this.redisClient) {
     this.logger.warn('Redis client is not initialized. Using in-memory storage.');
     // Set up periodic cleanup every 5 minutes
     setInterval(() => this.cleanupExpiredEntries(), 5 * 60 * 1000);
+  } else {
+    // Verify Redis connection
+    this.redisClient.ping().catch(error => {
+      this.logger.error('Redis connection failed:', error.message);
+      throw new Error('Redis connection failed');
+    });
   }
 }

@evereq evereq merged commit fe702b5 into develop Mar 1, 2025
10 of 11 checks passed
@evereq evereq deleted the feat/add-rate-limit branch March 1, 2025 07:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants