| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Threading.RateLimiting; |
| | | 3 | | using Microsoft.AspNetCore.RateLimiting; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | using ProjectTemplate.Web.Constants; |
| | | 6 | | using ProjectTemplate.Web.Options; |
| | | 7 | | |
| | | 8 | | namespace ProjectTemplate.Web.Extensions; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Provides extension methods to register rate limiting services for the application. |
| | | 12 | | /// </summary> |
| | | 13 | | public static partial class RateLimitingServiceExtensions |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// Adds the application's predefined rate limiting policies to the service collection. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <param name="services">The <see cref="IServiceCollection"/> to add the rate limiting services to.</param> |
| | | 19 | | /// <param name="configuration">The application configuration source.</param> |
| | | 20 | | /// <param name="environment">The current hosting environment.</param> |
| | | 21 | | /// <returns>The same <see cref="IServiceCollection"/> instance so calls can be chained.</returns> |
| | | 22 | | public static IServiceCollection AddApplicationRateLimiting( |
| | | 23 | | this IServiceCollection services, |
| | | 24 | | IConfiguration configuration, |
| | | 25 | | IHostEnvironment environment) |
| | | 26 | | { |
| | 154 | 27 | | services.Configure<ApplicationRateLimitingOptions>(options => |
| | 154 | 28 | | { |
| | 260 | 29 | | ApplicationRateLimitingOptions defaultOptions = CreateDefaultOptions(environment); |
| | 154 | 30 | | |
| | 260 | 31 | | options.Enabled = defaultOptions.Enabled; |
| | 260 | 32 | | options.UseGlobalLimiter = defaultOptions.UseGlobalLimiter; |
| | 154 | 33 | | |
| | 260 | 34 | | options.GlobalFixedWindow.PermitLimit = defaultOptions.GlobalFixedWindow.PermitLimit; |
| | 260 | 35 | | options.GlobalFixedWindow.WindowSeconds = defaultOptions.GlobalFixedWindow.WindowSeconds; |
| | 260 | 36 | | options.GlobalFixedWindow.QueueLimit = defaultOptions.GlobalFixedWindow.QueueLimit; |
| | 154 | 37 | | |
| | 260 | 38 | | options.FixedWindowPolicy.PermitLimit = defaultOptions.FixedWindowPolicy.PermitLimit; |
| | 260 | 39 | | options.FixedWindowPolicy.WindowSeconds = defaultOptions.FixedWindowPolicy.WindowSeconds; |
| | 260 | 40 | | options.FixedWindowPolicy.QueueLimit = defaultOptions.FixedWindowPolicy.QueueLimit; |
| | 154 | 41 | | |
| | 260 | 42 | | options.ConcurrencyPolicy.PermitLimit = defaultOptions.ConcurrencyPolicy.PermitLimit; |
| | 260 | 43 | | options.ConcurrencyPolicy.QueueLimit = defaultOptions.ConcurrencyPolicy.QueueLimit; |
| | 414 | 44 | | }); |
| | | 45 | | |
| | 154 | 46 | | services |
| | 154 | 47 | | .AddOptions<ApplicationRateLimitingOptions>() |
| | 154 | 48 | | .Bind(configuration.GetSection(ApplicationRateLimitingOptions.SectionName)) |
| | 260 | 49 | | .Validate(options => options.GlobalFixedWindow.PermitLimit > 0, |
| | 154 | 50 | | "ProjectTemplate:RateLimiting:GlobalFixedWindow:PermitLimit must be greater than zero.") |
| | 260 | 51 | | .Validate(options => options.GlobalFixedWindow.WindowSeconds > 0, |
| | 154 | 52 | | "ProjectTemplate:RateLimiting:GlobalFixedWindow:WindowSeconds must be greater than zero.") |
| | 260 | 53 | | .Validate(options => options.GlobalFixedWindow.QueueLimit >= 0, |
| | 154 | 54 | | "ProjectTemplate:RateLimiting:GlobalFixedWindow:QueueLimit must be zero or greater.") |
| | 260 | 55 | | .Validate(options => options.FixedWindowPolicy.PermitLimit > 0, |
| | 154 | 56 | | "ProjectTemplate:RateLimiting:FixedWindowPolicy:PermitLimit must be greater than zero.") |
| | 260 | 57 | | .Validate(options => options.FixedWindowPolicy.WindowSeconds > 0, |
| | 154 | 58 | | "ProjectTemplate:RateLimiting:FixedWindowPolicy:WindowSeconds must be greater than zero.") |
| | 260 | 59 | | .Validate(options => options.FixedWindowPolicy.QueueLimit >= 0, |
| | 154 | 60 | | "ProjectTemplate:RateLimiting:FixedWindowPolicy:QueueLimit must be zero or greater.") |
| | 260 | 61 | | .Validate(options => options.ConcurrencyPolicy.PermitLimit > 0, |
| | 154 | 62 | | "ProjectTemplate:RateLimiting:ConcurrencyPolicy:PermitLimit must be greater than zero.") |
| | 260 | 63 | | .Validate(options => options.ConcurrencyPolicy.QueueLimit >= 0, |
| | 154 | 64 | | "ProjectTemplate:RateLimiting:ConcurrencyPolicy:QueueLimit must be zero or greater.") |
| | 154 | 65 | | .ValidateOnStart(); |
| | | 66 | | |
| | 154 | 67 | | _ = services.AddRateLimiter(); |
| | | 68 | | |
| | 154 | 69 | | _ = services.AddOptions<RateLimiterOptions>() |
| | 154 | 70 | | .Configure<IOptions<ApplicationRateLimitingOptions>>((options, rateLimitingOptionsAccessor) => |
| | 154 | 71 | | { |
| | 126 | 72 | | ApplicationRateLimitingOptions rateLimitingOptions = rateLimitingOptionsAccessor.Value; |
| | 154 | 73 | | |
| | 126 | 74 | | options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; |
| | 154 | 75 | | |
| | 126 | 76 | | options.OnRejected = async (context, cancellationToken) => |
| | 126 | 77 | | { |
| | 8 | 78 | | HttpContext httpContext = context.HttpContext; |
| | 8 | 79 | | HttpResponse response = httpContext.Response; |
| | 126 | 80 | | |
| | 8 | 81 | | TimeSpan? retryAfter = null; |
| | 126 | 82 | | |
| | 8 | 83 | | if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfterValue)) |
| | 126 | 84 | | { |
| | 6 | 85 | | retryAfter = retryAfterValue; |
| | 126 | 86 | | |
| | 6 | 87 | | response.Headers.RetryAfter = |
| | 6 | 88 | | Math.Ceiling(retryAfterValue.TotalSeconds) |
| | 6 | 89 | | .ToString(CultureInfo.InvariantCulture); |
| | 126 | 90 | | } |
| | 126 | 91 | | |
| | 8 | 92 | | ILogger logger = httpContext.RequestServices |
| | 8 | 93 | | .GetRequiredService<ILoggerFactory>() |
| | 8 | 94 | | .CreateLogger("Template.Web.RateLimiting"); |
| | 126 | 95 | | |
| | 8 | 96 | | LogRateLimitRejectedRequest( |
| | 8 | 97 | | logger, |
| | 8 | 98 | | httpContext.Request.Method, |
| | 8 | 99 | | httpContext.Request.Path.Value ?? string.Empty, |
| | 8 | 100 | | httpContext.Connection.RemoteIpAddress?.ToString(), |
| | 8 | 101 | | httpContext.GetEndpoint()?.DisplayName, |
| | 8 | 102 | | retryAfter?.TotalSeconds, |
| | 8 | 103 | | httpContext.TraceIdentifier); |
| | 126 | 104 | | |
| | 8 | 105 | | response.StatusCode = StatusCodes.Status429TooManyRequests; |
| | 8 | 106 | | response.ContentType = "application/json"; |
| | 126 | 107 | | |
| | 8 | 108 | | await response.WriteAsJsonAsync(new |
| | 8 | 109 | | { |
| | 8 | 110 | | error = "Too many requests.", |
| | 8 | 111 | | statusCode = StatusCodes.Status429TooManyRequests, |
| | 8 | 112 | | traceId = httpContext.TraceIdentifier |
| | 8 | 113 | | }, cancellationToken); |
| | 134 | 114 | | }; |
| | 154 | 115 | | |
| | 126 | 116 | | if (!rateLimitingOptions.Enabled) |
| | 154 | 117 | | { |
| | 2 | 118 | | return; |
| | 154 | 119 | | } |
| | 154 | 120 | | |
| | 124 | 121 | | if (rateLimitingOptions.UseGlobalLimiter) |
| | 154 | 122 | | { |
| | 120 | 123 | | options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext => |
| | 232 | 124 | | RateLimitPartition.GetFixedWindowLimiter( |
| | 232 | 125 | | partitionKey: GetClientPartitionKey(httpContext), |
| | 318 | 126 | | factory: _ => CreateFixedWindowRateLimiterOptions(rateLimitingOptions.GlobalFixedWindow))); |
| | 154 | 127 | | } |
| | 154 | 128 | | |
| | 124 | 129 | | options.AddPolicy(ApplicationRateLimitingPolicyNames.Fixed, httpContext => |
| | 130 | 130 | | RateLimitPartition.GetFixedWindowLimiter( |
| | 130 | 131 | | partitionKey: GetClientPartitionKey(httpContext), |
| | 132 | 132 | | factory: _ => CreateFixedWindowRateLimiterOptions(rateLimitingOptions.FixedWindowPolicy))); |
| | 154 | 133 | | |
| | 124 | 134 | | options.AddPolicy(ApplicationRateLimitingPolicyNames.Concurrency, httpContext => |
| | 130 | 135 | | RateLimitPartition.GetConcurrencyLimiter( |
| | 130 | 136 | | partitionKey: GetEndpointPartitionKey(httpContext), |
| | 132 | 137 | | factory: _ => CreateConcurrencyLimiterOptions(rateLimitingOptions.ConcurrencyPolicy))); |
| | 278 | 138 | | }); |
| | | 139 | | |
| | 154 | 140 | | return services; |
| | | 141 | | } |
| | | 142 | | private static ApplicationRateLimitingOptions CreateDefaultOptions(IHostEnvironment environment) |
| | | 143 | | { |
| | 260 | 144 | | ApplicationRateLimitingOptions options = new(); |
| | | 145 | | |
| | 260 | 146 | | if (environment.IsDevelopment()) |
| | | 147 | | { |
| | 0 | 148 | | options.GlobalFixedWindow.PermitLimit = 300; |
| | 0 | 149 | | options.GlobalFixedWindow.WindowSeconds = 60; |
| | | 150 | | |
| | 0 | 151 | | options.FixedWindowPolicy.PermitLimit = 120; |
| | 0 | 152 | | options.FixedWindowPolicy.WindowSeconds = 60; |
| | | 153 | | |
| | 0 | 154 | | options.ConcurrencyPolicy.PermitLimit = 20; |
| | | 155 | | } |
| | | 156 | | |
| | 260 | 157 | | return options; |
| | | 158 | | } |
| | | 159 | | |
| | | 160 | | private static FixedWindowRateLimiterOptions CreateFixedWindowRateLimiterOptions( |
| | | 161 | | FixedWindowRateLimitingOptions options) |
| | | 162 | | { |
| | 88 | 163 | | return new FixedWindowRateLimiterOptions |
| | 88 | 164 | | { |
| | 88 | 165 | | AutoReplenishment = true, |
| | 88 | 166 | | PermitLimit = EnsureAtLeast(options.PermitLimit, minimum: 1), |
| | 88 | 167 | | Window = TimeSpan.FromSeconds(EnsureAtLeast(options.WindowSeconds, minimum: 1)), |
| | 88 | 168 | | QueueProcessingOrder = QueueProcessingOrder.OldestFirst, |
| | 88 | 169 | | QueueLimit = EnsureAtLeast(options.QueueLimit, minimum: 0) |
| | 88 | 170 | | }; |
| | | 171 | | } |
| | | 172 | | |
| | | 173 | | private static ConcurrencyLimiterOptions CreateConcurrencyLimiterOptions( |
| | | 174 | | ConcurrencyRateLimitingOptions options) |
| | | 175 | | { |
| | 2 | 176 | | return new ConcurrencyLimiterOptions |
| | 2 | 177 | | { |
| | 2 | 178 | | PermitLimit = EnsureAtLeast(options.PermitLimit, minimum: 1), |
| | 2 | 179 | | QueueProcessingOrder = QueueProcessingOrder.OldestFirst, |
| | 2 | 180 | | QueueLimit = EnsureAtLeast(options.QueueLimit, minimum: 0) |
| | 2 | 181 | | }; |
| | | 182 | | } |
| | | 183 | | |
| | | 184 | | private static string GetClientPartitionKey(HttpContext httpContext) |
| | | 185 | | { |
| | 118 | 186 | | return httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown-client"; |
| | | 187 | | } |
| | | 188 | | |
| | | 189 | | private static string GetEndpointPartitionKey(HttpContext httpContext) |
| | | 190 | | { |
| | 6 | 191 | | return httpContext.GetEndpoint()?.DisplayName |
| | 6 | 192 | | ?? httpContext.Request.Path.Value |
| | 6 | 193 | | ?? "unknown-endpoint"; |
| | | 194 | | } |
| | | 195 | | |
| | | 196 | | private static int EnsureAtLeast(int value, int minimum) |
| | | 197 | | { |
| | 268 | 198 | | return value < minimum ? minimum : value; |
| | | 199 | | } |
| | | 200 | | |
| | | 201 | | [LoggerMessage( |
| | | 202 | | EventId = 6001, |
| | | 203 | | Level = LogLevel.Warning, |
| | | 204 | | Message = "Rate limit rejected request. Method: {Method}; Path: {Path}; RemoteIpAddress: {RemoteIpAddress}; Endp |
| | | 205 | | private static partial void LogRateLimitRejectedRequest( |
| | | 206 | | ILogger logger, |
| | | 207 | | string method, |
| | | 208 | | string path, |
| | | 209 | | string? remoteIpAddress, |
| | | 210 | | string? endpoint, |
| | | 211 | | double? retryAfterSeconds, |
| | | 212 | | string traceIdentifier); |
| | | 213 | | } |