-
Notifications
You must be signed in to change notification settings - Fork 894
Added support for AspNetCore 7 rate limiting #1967
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
3fd4e9c
Added support for AspNetCore 7 rate limiting
mburumaxwell bb68b3f
Documentation updates
mburumaxwell 6bac908
Support default case
mburumaxwell f364ee7
Reference relevant issue
mburumaxwell ff03388
Fix typos
mburumaxwell 9aa5ba6
Update src/ReverseProxy/Configuration/RouteConfig.cs
mburumaxwell eea89bc
Update docs/docfx/articles/rate-limiting.md
mburumaxwell 26ce1d1
Validate reverse proxy policies using reflection
mburumaxwell 970b505
Cleanup ifdefs
Tratcher 152fafc
Apply suggestions from code review
Tratcher File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
# Rate Limiting | ||
|
||
## Introduction | ||
The reverse proxy can be used to rate-limit requests before they are proxied to the destination servers. This can reduce load on the destination servers, add a layer of protection, and ensure consistent policies are implemented across your applications. | ||
mburumaxwell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
> This feature is only available when using .NET 7.0 or later | ||
|
||
## Defaults | ||
|
||
No rate limiting is performed on requests unless enabled in the route or application configuration. However, the Rate Limiting middleware (`app.UseRateLimiter()`) can apply a default limiter applied to all routes, and this doesn't require any opt-in from the config. | ||
|
||
Example: | ||
```c# | ||
builder.Services.AddRateLimiter(options => options.GlobalLimiter = globalLimiter); | ||
``` | ||
|
||
## Configuration | ||
Rate Limiter policies can be specified per route via [RouteConfig.RateLimiterPolicy](xref:Yarp.ReverseProxy.Configuration.RouteConfig) and can be bound from the `Routes` sections of the config file. As with other route properties, this can be modified and reloaded without restarting the proxy. Policy names are case insensitive. | ||
|
||
Example: | ||
```JSON | ||
{ | ||
"ReverseProxy": { | ||
"Routes": { | ||
"route1" : { | ||
"ClusterId": "cluster1", | ||
"RateLimiterPolicy": "customPolicy", | ||
"Match": { | ||
"Hosts": [ "localhost" ] | ||
}, | ||
} | ||
}, | ||
"Clusters": { | ||
"cluster1": { | ||
"Destinations": { | ||
"cluster1/destination1": { | ||
"Address": "https://localhost:10001/" | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
``` | ||
|
||
[RateLimiter policies](https://learn.microsoft.com/aspnet/core/performance/rate-limit) are an ASP.NET Core concept that the proxy utilizes. The proxy provides the above configuration to specify a policy per route and the rest is handled by existing ASP.NET Core rate limiting middleware. | ||
|
||
RateLimiter policies can be configured in Startup.ConfigureServices as follows: | ||
```c# | ||
public void ConfigureServices(IServiceCollection services) | ||
{ | ||
services.AddRateLimiter(options => | ||
{ | ||
options.AddFixedWindowLimiter("customPolicy", opt => | ||
{ | ||
opt.PermitLimit = 4; | ||
opt.Window = TimeSpan.FromSeconds(12); | ||
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; | ||
opt.QueueLimit = 2; | ||
}); | ||
}); | ||
} | ||
``` | ||
|
||
In Startup.Configure add the RateLimiter middleware between Routing and Endpoints. | ||
|
||
```c# | ||
public void Configure(IApplicationBuilder app) | ||
{ | ||
app.UseRouting(); | ||
|
||
app.UseRateLimiter(); | ||
|
||
app.UseEndpoints(endpoints => | ||
{ | ||
endpoints.MapReverseProxy(); | ||
}); | ||
} | ||
``` | ||
|
||
See the [Rate Limiting](https://learn.microsoft.com/aspnet/core/performance/rate-limit) docs for setting up your preferred kind of rate limiting. | ||
|
||
### Disable Rate Limiting | ||
|
||
Specifying the value `disable` in a route's `RateLimiterPolicy` parameter means the rate limiter middleware will not apply any policies to this route, even the default policy. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
src/ReverseProxy/Configuration/IYarpRateLimiterPolicyProvider.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT License. | ||
|
||
#if NET7_0_OR_GREATER | ||
using System; | ||
using System.Collections; | ||
using System.Reflection; | ||
using Microsoft.AspNetCore.RateLimiting; | ||
using Microsoft.Extensions.Options; | ||
#endif | ||
|
||
using System.Threading.Tasks; | ||
|
||
namespace Yarp.ReverseProxy.Configuration; | ||
|
||
// TODO: update or remove this once AspNetCore provides a mechanism to validate the RateLimiter policies https://github.com/dotnet/aspnetcore/issues/45684 | ||
|
||
|
||
internal interface IYarpRateLimiterPolicyProvider | ||
Tratcher marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
ValueTask<object?> GetPolicyAsync(string policyName); | ||
} | ||
|
||
internal class YarpRateLimiterPolicyProvider : IYarpRateLimiterPolicyProvider | ||
{ | ||
#if NET7_0_OR_GREATER | ||
private readonly RateLimiterOptions _rateLimiterOptions; | ||
|
||
private readonly IDictionary _policyMap, _unactivatedPolicyMap; | ||
|
||
public YarpRateLimiterPolicyProvider(IOptions<RateLimiterOptions> rateLimiterOptions) | ||
{ | ||
_rateLimiterOptions = rateLimiterOptions?.Value ?? throw new ArgumentNullException(nameof(rateLimiterOptions)); | ||
|
||
var type = typeof(RateLimiterOptions); | ||
var flags = BindingFlags.Instance | BindingFlags.NonPublic; | ||
_policyMap = type.GetProperty("PolicyMap", flags)?.GetValue(_rateLimiterOptions, null) as IDictionary | ||
?? throw new NotSupportedException("This version of YARP is incompatible with the current version of ASP.NET Core."); | ||
_unactivatedPolicyMap = type.GetProperty("UnactivatedPolicyMap", flags)?.GetValue(_rateLimiterOptions, null) as IDictionary | ||
?? throw new NotSupportedException("This version of YARP is incompatible with the current version of ASP.NET Core."); | ||
} | ||
|
||
public ValueTask<object?> GetPolicyAsync(string policyName) | ||
Tratcher marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
return ValueTask.FromResult(_policyMap[policyName] ?? _unactivatedPolicyMap[policyName]); | ||
} | ||
#else | ||
public ValueTask<object?> GetPolicyAsync(string policyName) | ||
{ | ||
return default; | ||
} | ||
#endif | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT License. | ||
|
||
namespace Yarp.ReverseProxy.Configuration; | ||
|
||
internal static class RateLimitingConstants | ||
{ | ||
internal const string Default = "Default"; | ||
internal const string Disable = "Disable"; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.