Skip to content

Rate Limiting configuration - policy validation #45684

Open
@mburumaxwell

Description

@mburumaxwell

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:

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 dotnet/yarp#1967

Proposed API

It would be preferred to something similar to IAuthorizationPolicyProvider implemented via DefaultAuthorizationPolicyProvider and ICorsPolicyProvider implemented via DefaultCorsPolicyProvider

namespace Microsoft.AspNetCore.RateLimiting;

-  internal struct DefaultKeyType 
+  public struct DefaultKeyType 
{
// omitted ...
}
+
+ public interface IRateLimiterPolicyProvider
+ {
+     ValueTask<IRateLimiterPolicy<DefaultKeyType>?> GetDefaultPolicyAsync();
+     ValueTask<IRateLimiterPolicy<DefaultKeyType>?> GetPolicyAsync(string policyName);
+ }
+
+ public class DefaultRateLimiterPolicyProvider : IRateLimiterPolicyProvider
+ {
+     private readonly RateLimiterOptions _options;
+     
+     public DefaultRateLimiterPolicyProvider(IOptions<RateLimiterOptions> options)
+     {
+     
+     }
+     
+     public ValueTask<IRateLimiterPolicy<DefaultKeyType>?> 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-middlewareIncludes: URL rewrite, redirect, response cache/compression, session, and other general middlewaresarea-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractionsfeature-rate-limitWork related to use of rate limit primitives

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions