dotnet / dotnet/aspnetcore

Rate Limiting configuration - policy validation

Open
#45,684 11 comments 0 reactions 0 assignees View on GitHub
api-needs-work area-middleware area-networking feature-rate-limit
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

## Background and Motivation

The ASP.NET Core rate limiting middleware is great, but "limited" in terms of policy validation. Let's start with some code that you can write today in .NET 7:

```cs
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("customPolicy", opt =>
{
opt.PermitLimit = 4;
opt.Window = TimeSpan.FromSeconds(12);
opt.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
opt.QueueLimit = 2;
});
// ...
});
```

There is no way to validate that `customPolicy` actually exists. This is useful when configuring multiple routes from configuration such as is the case for YARP. See https://github.com/microsoft/reverse-proxy/pull/1967

## Proposed API

It would be preferred to something similar to [`IAuthorizationPolicyProvider`](https://github.com/dotnet/aspnetcore/blob/2b63a5fc7fee6944af03723767be2335f1d9bf9c/src/Security/Authorization/Core/src/IAuthorizationPolicyProvider.cs) implemented via [`DefaultAuthorizationPolicyProvider`](https://github.com/dotnet/aspnetcore/blob/2b63a5fc7fee6944af03723767be2335f1d9bf9c/src/Security/Authorization/Core/src/DefaultAuthorizationPolicyProvider.cs) and [`ICorsPolicyProvider`](https://github.com/dotnet/aspnetcore/blob/2b63a5fc7fee6944af03723767be2335f1d9bf9c/src/Middleware/CORS/src/Infrastructure/ICorsPolicyProvider.cs) implemented via [`DefaultCorsPolicyProvider`](https://github.com/dotnet/aspnetcore/blob/2b63a5fc7fee6944af03723767be2335f1d9bf9c/src/Middleware/CORS/src/Infrastructure/DefaultCorsPolicyProvider.cs)

```diff
namespace Microsoft.AspNetCore.RateLimiting;

- internal struct DefaultKeyType
+ public struct DefaultKeyType
{
// omitted ...
}
+
+ public interface IRateLimiterPolicyProvider
+ {
+ ValueTask?> GetDefaultPolicyAsync();
+ ValueTask?> GetPolicyAsync(string policyName);
+ }
+
+ public class DefaultRateLimiterPolicyProvider : IRateLimiterPolicyProvider
+ {
+ private readonly RateLimiterOptions _options;
+
+ public DefaultRateLimiterPolicyProvider(IOptions options)
+ {
+
+ }
+
+ public ValueTask?> GetPolicyAsync(string policyName)
+ {
+ options.PolicyMap[policyName] ?? options.UnactivatedPolicyMap[policyName];
+ }
+ }
```

`RateLimiterOptions.PolicyMap` is internal hence this feature cannot be added in another library or the final application.

## Usage Examples

See YARP: https://github.com/microsoft/reverse-proxy/blob/26ce1d15f868cb8da1891d65db1e59a20fd6ecbf/src/ReverseProxy/Configuration/ConfigValidator.cs#L312-L318

## Alternative Designs

None

## Risks

None

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.