Skip to content

Conversation

nanotaboada
Copy link
Owner

@nanotaboada nanotaboada commented Jul 26, 2025

Summary by CodeRabbit

  • New Features

    • Introduced global IP-based rate limiting (default: 60 requests/minute, 429 on excess).
    • Added utility to more reliably extract client IPs, including common proxy headers.
  • Improvements

    • CORS now enabled only in development.
    • Middleware and service registration order optimized for consistent request handling.
  • Chores

    • Rate limiter settings added to configuration with sensible defaults.

Copy link

codacy-production bot commented Jul 26, 2025

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
-0.81% 0.00%
Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (7f10db6) 1115 196 17.58%
Head commit (2e72cdc) 1169 (+54) 196 (+0) 16.77% (-0.81%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#269) 66 0 0.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

See your quality gate settings    Change summary preferences

coderabbitai[bot]

This comment was marked as outdated.

@nanotaboada nanotaboada force-pushed the feature/rate-limiting branch from ef85056 to 98f133c Compare July 28, 2025 13:18
@nanotaboada nanotaboada changed the title feat: add rate limiting and refactor DI setup with ServiceCollection extensions feat: rate limiting configuration with IP-based partitioning Jul 28, 2025
@nanotaboada
Copy link
Owner Author

@coderabbitai full review

Copy link

coderabbitai bot commented Jul 28, 2025

✅ Actions performed

Full review triggered.

Repository owner deleted a comment from coderabbitai bot Jul 28, 2025
Copy link

coderabbitai bot commented Jul 28, 2025

Walkthrough

Adds client-IP extraction utility, a configurable global IP-based fixed-window rate limiter, limits permissive CORS to development via an environment-aware extension, reorders service registrations/middleware, and introduces rate limiter configuration and settings.

Changes

Cohort / File(s) Change Summary
ServiceCollectionExtensions Enhancements
src/Dotnet.Samples.AspNetCore.WebApi/Extensions/ServiceCollectionExtensions.cs
Converted class to partial; updated AddCorsDefaultPolicy to accept IWebHostEnvironment and enable permissive CORS only in Development; added AddFixedWindowRateLimiter(IConfiguration) to configure global IP-partitioned fixed window rate limiting.
Program Startup Refactor
src/Dotnet.Samples.AspNetCore.WebApi/Program.cs
Reordered service registrations and middleware: register rate limiter, health checks, controllers; call HTTPS redirection, health checks, rate limiter, and MapControllers earlier; apply CORS only in development; removed duplicate middleware calls.
Client IP Extraction Utility
src/Dotnet.Samples.AspNetCore.WebApi/Utilities/HttpContextUtilities.cs
New HttpContextUtilities.ExtractIpAddress(HttpContext) to obtain client IP from X-Forwarded-For, X-Real-IP, connection info, or fallback to unknown-{guid}.
Rate Limiter Configuration Class
src/Dotnet.Samples.AspNetCore.WebApi/Configurations/RateLimiterConfiguration.cs
New RateLimiterConfiguration with properties PermitLimit (default 60), WindowSeconds (default 60), and QueueLimit (default 0).
Configuration Files Update
src/Dotnet.Samples.AspNetCore.WebApi/appsettings.json, src/Dotnet.Samples.AspNetCore.WebApi/appsettings.Development.json
Added RateLimiter section with PermitLimit, WindowSeconds, and QueueLimit settings.
Project File Adjustments
src/Dotnet.Samples.AspNetCore.WebApi/Dotnet.Samples.AspNetCore.WebApi.csproj, test/Dotnet.Samples.AspNetCore.WebApi.Tests/Dotnet.Samples.AspNetCore.WebApi.Tests.csproj
Reformatted package references; moved FluentValidation.DependencyInjectionExtensions from dev-only to runtime dependencies; consolidated <PrivateAssets> attributes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant RateLimiterExt as ServiceCollectionExtensions
    participant HttpUtil as HttpContextUtilities
    Note over Server,RateLimiterExt: Startup configuration
    Server->>RateLimiterExt: AddFixedWindowRateLimiter(config)
    RateLimiterExt->>HttpUtil: ExtractIpAddress(HttpContext) [partition key]
    HttpUtil-->>RateLimiterExt: client IP or fallback
    RateLimiterExt-->>Server: configure IP-partitioned fixed window limiter
    Note over Client,Server: Runtime request flow
    Client->>Server: HTTP Request
    Server->>RateLimiterExt: Rate limiter checks partition for client IP
    alt within limits
        Server-->>Client: Proceed to controllers (200...)
    else exceeded
        Server-->>Client: Respond 429 Too Many Requests
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 2e72cdc and b63e916.

📒 Files selected for processing (1)
  • test/Dotnet.Samples.AspNetCore.WebApi.Tests/Dotnet.Samples.AspNetCore.WebApi.Tests.csproj (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/Dotnet.Samples.AspNetCore.WebApi.Tests/Dotnet.Samples.AspNetCore.WebApi.Tests.csproj
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (csharp)
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/rate-limiting

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit 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:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

@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: 1

♻️ Duplicate comments (1)
src/Dotnet.Samples.AspNetCore.WebApi/Program.cs (1)

58-61: Middleware ordering correctly addresses health check concerns.

The current middleware order places health checks (MapHealthChecks("/health")) before rate limiting (UseRateLimiter()), which ensures monitoring endpoints remain accessible even when rate limits are exceeded. This addresses the concern raised in previous reviews about health check availability.

🧹 Nitpick comments (5)
src/Dotnet.Samples.AspNetCore.WebApi/appsettings.Development.json (1)

37-41: Consider development-specific rate limiting configuration.

The identical rate limiting settings across environments ensure consistent behavior. However, you might consider more lenient limits in development (e.g., higher PermitLimit) to facilitate testing and debugging activities.

src/Dotnet.Samples.AspNetCore.WebApi/Configurations/RateLimiterConfiguration.cs (1)

6-25: Consider adding validation attributes for configuration robustness.

The configuration class looks well-structured with reasonable defaults. However, consider adding validation attributes to prevent invalid configurations that could cause runtime issues.

+using System.ComponentModel.DataAnnotations;
+
 /// <summary>
 /// Configuration options for the Fixed Window Rate Limiter.
 /// </summary>
 public class RateLimiterConfiguration
 {
     /// <summary>
     /// Gets or sets the maximum number of permits that can be leased per window.
     /// Default value is 60 requests.
     /// </summary>
+    [Range(1, int.MaxValue, ErrorMessage = "PermitLimit must be greater than 0")]
     public int PermitLimit { get; set; } = 60;

     /// <summary>
     /// Gets or sets the time window in seconds for rate limiting.
     /// Default value is 60 seconds (1 minute).
     /// </summary>
+    [Range(1, 3600, ErrorMessage = "WindowSeconds must be between 1 and 3600 seconds")]
     public int WindowSeconds { get; set; } = 60;

     /// <summary>
     /// Gets or sets the maximum number of requests that can be queued when the permit limit is exceeded.
     /// A value of 0 means no queuing (default).
     /// </summary>
+    [Range(0, 1000, ErrorMessage = "QueueLimit must be between 0 and 1000")]
     public int QueueLimit { get; set; } = 0;
 }
src/Dotnet.Samples.AspNetCore.WebApi/Utilities/HttpContextUtilities.cs (2)

26-35: Consider validating extracted IP addresses for security.

The X-Forwarded-For header parsing accepts the first valid IP without additional validation. In production environments behind trusted proxies, this is generally safe, but consider documenting the trust assumptions.

         if (headers.TryGetValue("X-Forwarded-For", out var xForwardedFor))
         {
             var clientIp = xForwardedFor
                 .ToString()
                 .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
                 .FirstOrDefault();

-            if (!string.IsNullOrWhiteSpace(clientIp) && IPAddress.TryParse(clientIp, out ipAddress))
+            if (!string.IsNullOrWhiteSpace(clientIp) && 
+                IPAddress.TryParse(clientIp, out ipAddress) && 
+                !IPAddress.IsLoopback(ipAddress) && 
+                !ipAddress.Equals(IPAddress.Any) && 
+                !ipAddress.Equals(IPAddress.IPv6Any))
                 return ipAddress.ToString();
         }

10-18: Document security assumptions for proxy header trust.

The method trusts proxy headers (X-Forwarded-For, X-Real-IP) without validation. Consider adding documentation about when this is safe to use and potential security implications.

     /// <summary>
+    /// Extracts the client IP address from the HTTP context.
+    /// 
+    /// SECURITY NOTE: This method trusts proxy headers (X-Forwarded-For, X-Real-IP).
+    /// Only use in environments where you trust the proxy infrastructure, or consider
+    /// implementing additional validation for untrusted proxy scenarios.
+    /// 
     /// This method checks for the "X-Forwarded-For" and "X-Real-IP" headers,
     /// which are commonly used by proxies to forward the original client IP address.
     /// If these headers are not present or the IP address cannot be parsed,
     /// it falls back to the remote IP address from the connection.
     /// If no valid IP address can be determined, it returns "unknown".
     /// </summary>
src/Dotnet.Samples.AspNetCore.WebApi/Extensions/ServiceCollectionExtensions.cs (1)

171-173: Consider validation for rate limiter configuration.

The configuration binding uses null-coalescing to provide defaults, but there's no validation of the loaded configuration values. Invalid values could cause runtime issues.

         var settings =
             configuration.GetSection("RateLimiter").Get<RateLimiterConfiguration>()
             ?? new RateLimiterConfiguration();
+
+        // Validate configuration values
+        if (settings.PermitLimit <= 0)
+            throw new InvalidOperationException("RateLimiter:PermitLimit must be greater than 0");
+        if (settings.WindowSeconds <= 0)
+            throw new InvalidOperationException("RateLimiter:WindowSeconds must be greater than 0");
+        if (settings.QueueLimit < 0)
+            throw new InvalidOperationException("RateLimiter:QueueLimit must be >= 0");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7f10db6 and 3e63fa0.

📒 Files selected for processing (8)
  • src/Dotnet.Samples.AspNetCore.WebApi/Configurations/RateLimiterConfiguration.cs (1 hunks)
  • src/Dotnet.Samples.AspNetCore.WebApi/Dotnet.Samples.AspNetCore.WebApi.csproj (2 hunks)
  • src/Dotnet.Samples.AspNetCore.WebApi/Extensions/ServiceCollectionExtensions.cs (4 hunks)
  • src/Dotnet.Samples.AspNetCore.WebApi/Program.cs (2 hunks)
  • src/Dotnet.Samples.AspNetCore.WebApi/Utilities/HttpContextUtilities.cs (1 hunks)
  • src/Dotnet.Samples.AspNetCore.WebApi/appsettings.Development.json (1 hunks)
  • src/Dotnet.Samples.AspNetCore.WebApi/appsettings.json (1 hunks)
  • test/Dotnet.Samples.AspNetCore.WebApi.Tests/Dotnet.Samples.AspNetCore.WebApi.Tests.csproj (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/Dotnet.Samples.AspNetCore.WebApi/Extensions/ServiceCollectionExtensions.cs (2)
src/Dotnet.Samples.AspNetCore.WebApi/Configurations/RateLimiterConfiguration.cs (1)
  • RateLimiterConfiguration (6-25)
src/Dotnet.Samples.AspNetCore.WebApi/Utilities/HttpContextUtilities.cs (2)
  • HttpContextUtilities (8-47)
  • ExtractIpAddress (19-46)
🔇 Additional comments (11)
test/Dotnet.Samples.AspNetCore.WebApi.Tests/Dotnet.Samples.AspNetCore.WebApi.Tests.csproj (1)

12-17: LGTM! Clean formatting improvement.

The consolidation of PackageReference elements from multiline to single-line format with inline PrivateAssets attributes improves readability and consistency without affecting functionality.

src/Dotnet.Samples.AspNetCore.WebApi/appsettings.json (1)

37-41: Rate limiting configuration looks reasonable.

The settings provide a balanced approach:

  • 60 requests per minute is moderate and suitable for most API scenarios
  • Zero queue limit ensures immediate rejection when limits are exceeded, preventing request delays

Consider if these limits align with your expected API usage patterns and whether you might need different limits for authenticated vs. anonymous users in the future.

src/Dotnet.Samples.AspNetCore.WebApi/Dotnet.Samples.AspNetCore.WebApi.csproj (2)

21-21: Correct dependency categorization.

Moving FluentValidation.DependencyInjectionExtensions to runtime dependencies is appropriate since dependency injection extensions are needed at runtime for service registration, not just during development.


11-12: LGTM! Consistent formatting improvement.

The inline PrivateAssets attributes maintain consistency with the formatting improvements made across the project files.

src/Dotnet.Samples.AspNetCore.WebApi/Program.cs (2)

25-29: Service registration improvements look good.

The reordering of service registrations and the addition of the rate limiter service are well-structured. The environment parameter passed to AddCorsDefaultPolicy enables environment-specific CORS configuration.


65-65: CORS properly scoped to development environment.

Moving CORS middleware inside the development environment block and placing it first ensures it only applies when needed, improving security in production environments.

src/Dotnet.Samples.AspNetCore.WebApi/Extensions/ServiceCollectionExtensions.cs (5)

17-19: LGTM!

The class declaration changes are appropriate. Making the class partial allows for better organization of extension methods, and the updated XML documentation correctly specifies the target interface.


57-78: LGTM! Addresses previous security concerns.

The CORS policy has been improved to only apply the permissive configuration in development environments, which addresses the security concerns raised in previous reviews. This is a much safer approach for production deployments.


108-110: LGTM!

Extracting the OpenApiInfo configuration into a variable improves readability and follows good practices for configuration binding.


177-193: LGTM! Well-implemented IP-based rate limiting.

The rate limiter implementation is well-structured:

  • Uses IP-based partitioning for fair limiting across clients
  • Configurable parameters from settings
  • Proper use of FixedWindowRateLimiterOptions
  • Appropriate queue processing order (OldestFirst)

The integration with HttpContextUtilities.ExtractIpAddress provides proper IP extraction handling proxy scenarios.


195-195: LGTM!

Setting the rejection status code to 429 (Too Many Requests) is the correct HTTP status code for rate limiting scenarios.

@nanotaboada nanotaboada linked an issue Jul 28, 2025 that may be closed by this pull request
@nanotaboada
Copy link
Owner Author

@dependabot recreate

Copy link

Copy link

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
-0.81% 0.00%
Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (3abc021) 1115 196 17.58%
Head commit (b63e916) 1169 (+54) 196 (+0) 16.77% (-0.81%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#269) 66 0 0.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

See your quality gate settings    Change summary preferences

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.

Configure global Rate Limiting policy
1 participant