| | | 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 | | { |
| | 168 | 27 | | services.Configure<ApplicationRateLimitingOptions>(options => |
| | 168 | 28 | | { |
| | 280 | 29 | | ApplicationRateLimitingOptions defaultOptions = CreateDefaultOptions(environment); |
| | 168 | 30 | | |
| | 280 | 31 | | options.Enabled = defaultOptions.Enabled; |
| | 280 | 32 | | options.UseGlobalLimiter = defaultOptions.UseGlobalLimiter; |
| | 280 | 33 | | options.UseSharedUnknownClientPartition = defaultOptions.UseSharedUnknownClientPartition; |
| | 280 | 34 | | options.UnknownClientPartitionKey = defaultOptions.UnknownClientPartitionKey; |
| | 168 | 35 | | |
| | 280 | 36 | | options.GlobalFixedWindow.PermitLimit = defaultOptions.GlobalFixedWindow.PermitLimit; |
| | 280 | 37 | | options.GlobalFixedWindow.WindowSeconds = defaultOptions.GlobalFixedWindow.WindowSeconds; |
| | 280 | 38 | | options.GlobalFixedWindow.QueueLimit = defaultOptions.GlobalFixedWindow.QueueLimit; |
| | 168 | 39 | | |
| | 280 | 40 | | options.FixedWindowPolicy.PermitLimit = defaultOptions.FixedWindowPolicy.PermitLimit; |
| | 280 | 41 | | options.FixedWindowPolicy.WindowSeconds = defaultOptions.FixedWindowPolicy.WindowSeconds; |
| | 280 | 42 | | options.FixedWindowPolicy.QueueLimit = defaultOptions.FixedWindowPolicy.QueueLimit; |
| | 168 | 43 | | |
| | 280 | 44 | | options.ConcurrencyPolicy.PermitLimit = defaultOptions.ConcurrencyPolicy.PermitLimit; |
| | 280 | 45 | | options.ConcurrencyPolicy.QueueLimit = defaultOptions.ConcurrencyPolicy.QueueLimit; |
| | 448 | 46 | | }); |
| | | 47 | | |
| | 168 | 48 | | services |
| | 168 | 49 | | .AddOptions<ApplicationRateLimitingOptions>() |
| | 168 | 50 | | .Bind(configuration.GetSection(ApplicationRateLimitingOptions.SectionName)) |
| | 280 | 51 | | .Validate(options => !string.IsNullOrWhiteSpace(options.UnknownClientPartitionKey), |
| | 168 | 52 | | "ProjectTemplate:RateLimiting:UnknownClientPartitionKey must not be empty.") |
| | 280 | 53 | | .Validate(options => options.GlobalFixedWindow.PermitLimit > 0, |
| | 168 | 54 | | "ProjectTemplate:RateLimiting:GlobalFixedWindow:PermitLimit must be greater than zero.") |
| | 280 | 55 | | .Validate(options => options.GlobalFixedWindow.WindowSeconds > 0, |
| | 168 | 56 | | "ProjectTemplate:RateLimiting:GlobalFixedWindow:WindowSeconds must be greater than zero.") |
| | 280 | 57 | | .Validate(options => options.GlobalFixedWindow.QueueLimit >= 0, |
| | 168 | 58 | | "ProjectTemplate:RateLimiting:GlobalFixedWindow:QueueLimit must be zero or greater.") |
| | 280 | 59 | | .Validate(options => options.FixedWindowPolicy.PermitLimit > 0, |
| | 168 | 60 | | "ProjectTemplate:RateLimiting:FixedWindowPolicy:PermitLimit must be greater than zero.") |
| | 280 | 61 | | .Validate(options => options.FixedWindowPolicy.WindowSeconds > 0, |
| | 168 | 62 | | "ProjectTemplate:RateLimiting:FixedWindowPolicy:WindowSeconds must be greater than zero.") |
| | 280 | 63 | | .Validate(options => options.FixedWindowPolicy.QueueLimit >= 0, |
| | 168 | 64 | | "ProjectTemplate:RateLimiting:FixedWindowPolicy:QueueLimit must be zero or greater.") |
| | 280 | 65 | | .Validate(options => options.ConcurrencyPolicy.PermitLimit > 0, |
| | 168 | 66 | | "ProjectTemplate:RateLimiting:ConcurrencyPolicy:PermitLimit must be greater than zero.") |
| | 280 | 67 | | .Validate(options => options.ConcurrencyPolicy.QueueLimit >= 0, |
| | 168 | 68 | | "ProjectTemplate:RateLimiting:ConcurrencyPolicy:QueueLimit must be zero or greater.") |
| | 168 | 69 | | .ValidateOnStart(); |
| | | 70 | | |
| | 168 | 71 | | _ = services.AddRateLimiter(); |
| | | 72 | | |
| | 168 | 73 | | _ = services.AddOptions<RateLimiterOptions>() |
| | 168 | 74 | | .Configure<IOptions<ApplicationRateLimitingOptions>>((options, rateLimitingOptionsAccessor) => |
| | 168 | 75 | | { |
| | 136 | 76 | | ApplicationRateLimitingOptions rateLimitingOptions = rateLimitingOptionsAccessor.Value; |
| | 168 | 77 | | |
| | 136 | 78 | | options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; |
| | 168 | 79 | | |
| | 136 | 80 | | options.OnRejected = async (context, cancellationToken) => |
| | 136 | 81 | | { |
| | 8 | 82 | | HttpContext httpContext = context.HttpContext; |
| | 8 | 83 | | HttpResponse response = httpContext.Response; |
| | 136 | 84 | | |
| | 8 | 85 | | TimeSpan? retryAfter = null; |
| | 136 | 86 | | |
| | 8 | 87 | | if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfterValue)) |
| | 136 | 88 | | { |
| | 6 | 89 | | retryAfter = retryAfterValue; |
| | 136 | 90 | | |
| | 6 | 91 | | response.Headers.RetryAfter = |
| | 6 | 92 | | Math.Ceiling(retryAfterValue.TotalSeconds) |
| | 6 | 93 | | .ToString(CultureInfo.InvariantCulture); |
| | 136 | 94 | | } |
| | 136 | 95 | | |
| | 8 | 96 | | ILogger logger = httpContext.RequestServices |
| | 8 | 97 | | .GetRequiredService<ILoggerFactory>() |
| | 8 | 98 | | .CreateLogger("Template.Web.RateLimiting"); |
| | 136 | 99 | | |
| | 8 | 100 | | LogRateLimitRejectedRequest( |
| | 8 | 101 | | logger, |
| | 8 | 102 | | httpContext.Request.Method, |
| | 8 | 103 | | httpContext.Request.Path.Value ?? string.Empty, |
| | 8 | 104 | | httpContext.Connection.RemoteIpAddress?.ToString(), |
| | 8 | 105 | | httpContext.GetEndpoint()?.DisplayName, |
| | 8 | 106 | | retryAfter?.TotalSeconds, |
| | 8 | 107 | | httpContext.TraceIdentifier); |
| | 136 | 108 | | |
| | 8 | 109 | | response.StatusCode = StatusCodes.Status429TooManyRequests; |
| | 8 | 110 | | response.ContentType = "application/json"; |
| | 136 | 111 | | |
| | 8 | 112 | | await response.WriteAsJsonAsync(new |
| | 8 | 113 | | { |
| | 8 | 114 | | error = "Too many requests.", |
| | 8 | 115 | | statusCode = StatusCodes.Status429TooManyRequests, |
| | 8 | 116 | | traceId = httpContext.TraceIdentifier |
| | 8 | 117 | | }, cancellationToken); |
| | 144 | 118 | | }; |
| | 168 | 119 | | |
| | 136 | 120 | | if (!rateLimitingOptions.Enabled) |
| | 168 | 121 | | { |
| | 2 | 122 | | return; |
| | 168 | 123 | | } |
| | 168 | 124 | | |
| | 134 | 125 | | if (rateLimitingOptions.UseGlobalLimiter) |
| | 168 | 126 | | { |
| | 130 | 127 | | options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext => |
| | 252 | 128 | | RateLimitPartition.GetFixedWindowLimiter( |
| | 252 | 129 | | partitionKey: GetClientPartitionKey(httpContext, rateLimitingOptions), |
| | 346 | 130 | | factory: _ => CreateFixedWindowRateLimiterOptions(rateLimitingOptions.GlobalFixedWindow))); |
| | 168 | 131 | | } |
| | 168 | 132 | | |
| | 134 | 133 | | options.AddPolicy(ApplicationRateLimitingPolicyNames.Fixed, httpContext => |
| | 140 | 134 | | RateLimitPartition.GetFixedWindowLimiter( |
| | 140 | 135 | | partitionKey: GetClientPartitionKey(httpContext, rateLimitingOptions), |
| | 142 | 136 | | factory: _ => CreateFixedWindowRateLimiterOptions(rateLimitingOptions.FixedWindowPolicy))); |
| | 168 | 137 | | |
| | 134 | 138 | | options.AddPolicy(ApplicationRateLimitingPolicyNames.Concurrency, httpContext => |
| | 140 | 139 | | RateLimitPartition.GetConcurrencyLimiter( |
| | 140 | 140 | | partitionKey: GetEndpointPartitionKey(httpContext), |
| | 142 | 141 | | factory: _ => CreateConcurrencyLimiterOptions(rateLimitingOptions.ConcurrencyPolicy))); |
| | 302 | 142 | | }); |
| | | 143 | | |
| | 168 | 144 | | return services; |
| | | 145 | | } |
| | | 146 | | private static ApplicationRateLimitingOptions CreateDefaultOptions(IHostEnvironment environment) |
| | | 147 | | { |
| | 280 | 148 | | ApplicationRateLimitingOptions options = new(); |
| | | 149 | | |
| | 280 | 150 | | if (environment.IsDevelopment()) |
| | | 151 | | { |
| | 0 | 152 | | options.GlobalFixedWindow.PermitLimit = 300; |
| | 0 | 153 | | options.GlobalFixedWindow.WindowSeconds = 60; |
| | | 154 | | |
| | 0 | 155 | | options.FixedWindowPolicy.PermitLimit = 120; |
| | 0 | 156 | | options.FixedWindowPolicy.WindowSeconds = 60; |
| | | 157 | | |
| | 0 | 158 | | options.ConcurrencyPolicy.PermitLimit = 20; |
| | | 159 | | } |
| | | 160 | | |
| | 280 | 161 | | return options; |
| | | 162 | | } |
| | | 163 | | |
| | | 164 | | private static FixedWindowRateLimiterOptions CreateFixedWindowRateLimiterOptions( |
| | | 165 | | FixedWindowRateLimitingOptions options) |
| | | 166 | | { |
| | 96 | 167 | | return new FixedWindowRateLimiterOptions |
| | 96 | 168 | | { |
| | 96 | 169 | | AutoReplenishment = true, |
| | 96 | 170 | | PermitLimit = EnsureAtLeast(options.PermitLimit, minimum: 1), |
| | 96 | 171 | | Window = TimeSpan.FromSeconds(EnsureAtLeast(options.WindowSeconds, minimum: 1)), |
| | 96 | 172 | | QueueProcessingOrder = QueueProcessingOrder.OldestFirst, |
| | 96 | 173 | | QueueLimit = EnsureAtLeast(options.QueueLimit, minimum: 0) |
| | 96 | 174 | | }; |
| | | 175 | | } |
| | | 176 | | |
| | | 177 | | private static ConcurrencyLimiterOptions CreateConcurrencyLimiterOptions( |
| | | 178 | | ConcurrencyRateLimitingOptions options) |
| | | 179 | | { |
| | 2 | 180 | | return new ConcurrencyLimiterOptions |
| | 2 | 181 | | { |
| | 2 | 182 | | PermitLimit = EnsureAtLeast(options.PermitLimit, minimum: 1), |
| | 2 | 183 | | QueueProcessingOrder = QueueProcessingOrder.OldestFirst, |
| | 2 | 184 | | QueueLimit = EnsureAtLeast(options.QueueLimit, minimum: 0) |
| | 2 | 185 | | }; |
| | | 186 | | } |
| | | 187 | | |
| | | 188 | | private static string GetClientPartitionKey( |
| | | 189 | | HttpContext httpContext, |
| | | 190 | | ApplicationRateLimitingOptions options) |
| | | 191 | | { |
| | 128 | 192 | | ILogger logger = httpContext.RequestServices |
| | 128 | 193 | | .GetRequiredService<ILoggerFactory>() |
| | 128 | 194 | | .CreateLogger("Template.Web.RateLimiting"); |
| | | 195 | | |
| | 128 | 196 | | return GetClientPartitionKey(httpContext, options, logger); |
| | | 197 | | } |
| | | 198 | | |
| | | 199 | | internal static string GetClientPartitionKey( |
| | | 200 | | HttpContext httpContext, |
| | | 201 | | ApplicationRateLimitingOptions options, |
| | | 202 | | ILogger logger) |
| | | 203 | | { |
| | 134 | 204 | | string? remoteIpAddress = httpContext.Connection.RemoteIpAddress?.ToString(); |
| | | 205 | | |
| | 134 | 206 | | if (!string.IsNullOrWhiteSpace(remoteIpAddress)) |
| | | 207 | | { |
| | 4 | 208 | | return remoteIpAddress; |
| | | 209 | | } |
| | | 210 | | |
| | 130 | 211 | | string fallbackPartitionKey = string.IsNullOrWhiteSpace(options.UnknownClientPartitionKey) |
| | 130 | 212 | | ? "unknown-client" |
| | 130 | 213 | | : options.UnknownClientPartitionKey.Trim(); |
| | 130 | 214 | | string fallbackMode = options.UseSharedUnknownClientPartition ? "Shared" : "PerRequest"; |
| | 130 | 215 | | string fallbackDiscriminator = string.IsNullOrWhiteSpace(httpContext.TraceIdentifier) |
| | 130 | 216 | | ? Guid.NewGuid().ToString("N") |
| | 130 | 217 | | : httpContext.TraceIdentifier; |
| | | 218 | | |
| | 130 | 219 | | if (!options.UseSharedUnknownClientPartition) |
| | | 220 | | { |
| | 110 | 221 | | fallbackPartitionKey = $"{fallbackPartitionKey}:{fallbackDiscriminator}"; |
| | | 222 | | } |
| | | 223 | | |
| | 130 | 224 | | LogRateLimitingClientPartitionFallback( |
| | 130 | 225 | | logger, |
| | 130 | 226 | | fallbackMode, |
| | 130 | 227 | | fallbackPartitionKey, |
| | 130 | 228 | | fallbackDiscriminator); |
| | | 229 | | |
| | 130 | 230 | | return fallbackPartitionKey; |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | private static string GetEndpointPartitionKey(HttpContext httpContext) |
| | | 234 | | { |
| | 6 | 235 | | return httpContext.GetEndpoint()?.DisplayName |
| | 6 | 236 | | ?? httpContext.Request.Path.Value |
| | 6 | 237 | | ?? "unknown-endpoint"; |
| | | 238 | | } |
| | | 239 | | |
| | | 240 | | private static int EnsureAtLeast(int value, int minimum) |
| | | 241 | | { |
| | 292 | 242 | | return value < minimum ? minimum : value; |
| | | 243 | | } |
| | | 244 | | |
| | | 245 | | [LoggerMessage( |
| | | 246 | | EventId = 6001, |
| | | 247 | | Level = LogLevel.Warning, |
| | | 248 | | Message = "Rate limit rejected request. Method: {Method}; Path: {Path}; RemoteIpAddress: {RemoteIpAddress}; Endp |
| | | 249 | | private static partial void LogRateLimitRejectedRequest( |
| | | 250 | | ILogger logger, |
| | | 251 | | string method, |
| | | 252 | | string path, |
| | | 253 | | string? remoteIpAddress, |
| | | 254 | | string? endpoint, |
| | | 255 | | double? retryAfterSeconds, |
| | | 256 | | string traceIdentifier); |
| | | 257 | | |
| | | 258 | | [LoggerMessage( |
| | | 259 | | EventId = 6002, |
| | | 260 | | Level = LogLevel.Warning, |
| | | 261 | | Message = "Rate limiting used fallback client partition because RemoteIpAddress was unavailable. FallbackMode: { |
| | | 262 | | private static partial void LogRateLimitingClientPartitionFallback( |
| | | 263 | | ILogger logger, |
| | | 264 | | string fallbackMode, |
| | | 265 | | string partitionKey, |
| | | 266 | | string traceIdentifier); |
| | | 267 | | } |