| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Net; |
| | | 3 | | using System.Net.Sockets; |
| | | 4 | | using System.Threading.RateLimiting; |
| | | 5 | | using Microsoft.AspNetCore.Mvc; |
| | | 6 | | using Microsoft.AspNetCore.RateLimiting; |
| | | 7 | | using Microsoft.Extensions.Options; |
| | | 8 | | using ProjectTemplate.Web.Constants; |
| | | 9 | | using ProjectTemplate.Web.Diagnostics; |
| | | 10 | | using ProjectTemplate.Web.ErrorHandling; |
| | | 11 | | using ProjectTemplate.Web.Options; |
| | | 12 | | |
| | | 13 | | namespace ProjectTemplate.Web.Extensions; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Provides extension methods to register rate limiting services for the application. |
| | | 17 | | /// </summary> |
| | | 18 | | public static partial class RateLimitingServiceExtensions |
| | | 19 | | { |
| | | 20 | | internal const string RejectionTitle = "Too Many Requests"; |
| | | 21 | | internal const string RejectionDetail = "Too many requests were received. Please try again later."; |
| | | 22 | | internal const string RejectionProblemType = "https://www.rfc-editor.org/rfc/rfc6585#section-4"; |
| | | 23 | | |
| | | 24 | | private const int _ipv6AddressBitCount = 128; |
| | | 25 | | |
| | | 26 | | /// <summary> |
| | | 27 | | /// Adds the application's predefined rate limiting policies to the service collection. |
| | | 28 | | /// </summary> |
| | | 29 | | /// <param name="services">The <see cref="IServiceCollection"/> to add the rate limiting services to.</param> |
| | | 30 | | /// <param name="configuration">The application configuration source.</param> |
| | | 31 | | /// <param name="environment">The current hosting environment.</param> |
| | | 32 | | /// <returns>The same <see cref="IServiceCollection"/> instance so calls can be chained.</returns> |
| | | 33 | | public static IServiceCollection AddApplicationRateLimiting( |
| | | 34 | | this IServiceCollection services, |
| | | 35 | | IConfiguration configuration, |
| | | 36 | | IHostEnvironment environment) |
| | | 37 | | { |
| | 116 | 38 | | RateLimitingFallbackWarningThrottle fallbackWarningThrottle = new( |
| | 116 | 39 | | TimeProvider.System, |
| | 116 | 40 | | RateLimitingFallbackWarningThrottle.DefaultInterval); |
| | | 41 | | |
| | 116 | 42 | | services.Configure<ApplicationRateLimitingOptions>(options => |
| | 116 | 43 | | { |
| | 116 | 44 | | ApplicationRateLimitingOptions defaultOptions = CreateDefaultOptions(environment); |
| | 116 | 45 | | |
| | 116 | 46 | | options.Enabled = defaultOptions.Enabled; |
| | 116 | 47 | | options.UseGlobalLimiter = defaultOptions.UseGlobalLimiter; |
| | 116 | 48 | | options.UseSharedUnknownClientPartition = defaultOptions.UseSharedUnknownClientPartition; |
| | 116 | 49 | | options.UnknownClientPartitionKey = defaultOptions.UnknownClientPartitionKey; |
| | 116 | 50 | | |
| | 116 | 51 | | options.GlobalFixedWindow.PermitLimit = defaultOptions.GlobalFixedWindow.PermitLimit; |
| | 116 | 52 | | options.GlobalFixedWindow.WindowSeconds = defaultOptions.GlobalFixedWindow.WindowSeconds; |
| | 116 | 53 | | options.GlobalFixedWindow.QueueLimit = defaultOptions.GlobalFixedWindow.QueueLimit; |
| | 116 | 54 | | |
| | 116 | 55 | | options.FixedWindowPolicy.PermitLimit = defaultOptions.FixedWindowPolicy.PermitLimit; |
| | 116 | 56 | | options.FixedWindowPolicy.WindowSeconds = defaultOptions.FixedWindowPolicy.WindowSeconds; |
| | 116 | 57 | | options.FixedWindowPolicy.QueueLimit = defaultOptions.FixedWindowPolicy.QueueLimit; |
| | 116 | 58 | | |
| | 116 | 59 | | options.ConcurrencyPolicy.PermitLimit = defaultOptions.ConcurrencyPolicy.PermitLimit; |
| | 116 | 60 | | options.ConcurrencyPolicy.QueueLimit = defaultOptions.ConcurrencyPolicy.QueueLimit; |
| | 116 | 61 | | }); |
| | | 62 | | |
| | 116 | 63 | | services |
| | 116 | 64 | | .AddOptions<ApplicationRateLimitingOptions>() |
| | 116 | 65 | | .Bind(configuration.GetSection(ApplicationRateLimitingOptions.SectionName)) |
| | 116 | 66 | | .Validate(options => !string.IsNullOrWhiteSpace(options.UnknownClientPartitionKey), |
| | 116 | 67 | | "ProjectTemplate:RateLimiting:UnknownClientPartitionKey must not be empty.") |
| | 116 | 68 | | .Validate(options => options.IPv6PartitionPrefixLength is >= 1 and <= _ipv6AddressBitCount, |
| | 116 | 69 | | "ProjectTemplate:RateLimiting:IPv6PartitionPrefixLength must be between 1 and 128.") |
| | 116 | 70 | | .Validate(options => options.GlobalFixedWindow.PermitLimit > 0, |
| | 116 | 71 | | "ProjectTemplate:RateLimiting:GlobalFixedWindow:PermitLimit must be greater than zero.") |
| | 116 | 72 | | .Validate(options => options.GlobalFixedWindow.WindowSeconds > 0, |
| | 116 | 73 | | "ProjectTemplate:RateLimiting:GlobalFixedWindow:WindowSeconds must be greater than zero.") |
| | 116 | 74 | | .Validate(options => options.GlobalFixedWindow.QueueLimit >= 0, |
| | 116 | 75 | | "ProjectTemplate:RateLimiting:GlobalFixedWindow:QueueLimit must be zero or greater.") |
| | 116 | 76 | | .Validate(options => options.FixedWindowPolicy.PermitLimit > 0, |
| | 116 | 77 | | "ProjectTemplate:RateLimiting:FixedWindowPolicy:PermitLimit must be greater than zero.") |
| | 116 | 78 | | .Validate(options => options.FixedWindowPolicy.WindowSeconds > 0, |
| | 116 | 79 | | "ProjectTemplate:RateLimiting:FixedWindowPolicy:WindowSeconds must be greater than zero.") |
| | 116 | 80 | | .Validate(options => options.FixedWindowPolicy.QueueLimit >= 0, |
| | 116 | 81 | | "ProjectTemplate:RateLimiting:FixedWindowPolicy:QueueLimit must be zero or greater.") |
| | 116 | 82 | | .Validate(options => options.ConcurrencyPolicy.PermitLimit > 0, |
| | 116 | 83 | | "ProjectTemplate:RateLimiting:ConcurrencyPolicy:PermitLimit must be greater than zero.") |
| | 116 | 84 | | .Validate(options => options.ConcurrencyPolicy.QueueLimit >= 0, |
| | 116 | 85 | | "ProjectTemplate:RateLimiting:ConcurrencyPolicy:QueueLimit must be zero or greater.") |
| | 116 | 86 | | .ValidateOnStart(); |
| | | 87 | | |
| | 116 | 88 | | _ = services.AddRateLimiter(); |
| | | 89 | | |
| | 116 | 90 | | _ = services.AddOptions<RateLimiterOptions>() |
| | 116 | 91 | | .Configure<IOptions<ApplicationRateLimitingOptions>>((options, rateLimitingOptionsAccessor) => |
| | 116 | 92 | | { |
| | 116 | 93 | | ApplicationRateLimitingOptions rateLimitingOptions = rateLimitingOptionsAccessor.Value; |
| | 116 | 94 | | |
| | 116 | 95 | | options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; |
| | 116 | 96 | | |
| | 116 | 97 | | options.OnRejected = async (context, cancellationToken) => |
| | 116 | 98 | | { |
| | 116 | 99 | | HttpContext httpContext = context.HttpContext; |
| | 116 | 100 | | |
| | 116 | 101 | | TimeSpan? retryAfter = context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter |
| | 116 | 102 | | ? retryAfterValue |
| | 116 | 103 | | : null; |
| | 116 | 104 | | |
| | 116 | 105 | | ILogger logger = httpContext.RequestServices |
| | 116 | 106 | | .GetRequiredService<ILoggerFactory>() |
| | 116 | 107 | | .CreateLogger("Template.Web.RateLimiting"); |
| | 116 | 108 | | |
| | 116 | 109 | | LogRejectedRequest(httpContext, logger, retryAfter); |
| | 116 | 110 | | |
| | 116 | 111 | | await WriteRejectionResponseAsync(httpContext, retryAfter, cancellationToken) |
| | 116 | 112 | | .ConfigureAwait(false); |
| | 116 | 113 | | }; |
| | 116 | 114 | | |
| | 116 | 115 | | if (!rateLimitingOptions.Enabled) |
| | 116 | 116 | | { |
| | 116 | 117 | | return; |
| | 116 | 118 | | } |
| | 116 | 119 | | |
| | 116 | 120 | | if (rateLimitingOptions.UseGlobalLimiter) |
| | 116 | 121 | | { |
| | 116 | 122 | | options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext => |
| | 116 | 123 | | RateLimitPartition.GetFixedWindowLimiter( |
| | 116 | 124 | | partitionKey: GetClientPartitionKey(httpContext, rateLimitingOptions, fallbackWarningThrottl |
| | 116 | 125 | | factory: _ => CreateFixedWindowRateLimiterOptions(rateLimitingOptions.GlobalFixedWindow))); |
| | 116 | 126 | | } |
| | 116 | 127 | | |
| | 116 | 128 | | options.AddPolicy(ApplicationRateLimitingPolicyNames.Fixed, httpContext => |
| | 116 | 129 | | RateLimitPartition.GetFixedWindowLimiter( |
| | 116 | 130 | | partitionKey: GetClientPartitionKey(httpContext, rateLimitingOptions, fallbackWarningThrottle), |
| | 116 | 131 | | factory: _ => CreateFixedWindowRateLimiterOptions(rateLimitingOptions.FixedWindowPolicy))); |
| | 116 | 132 | | |
| | 116 | 133 | | options.AddPolicy(ApplicationRateLimitingPolicyNames.Concurrency, httpContext => |
| | 116 | 134 | | RateLimitPartition.GetConcurrencyLimiter( |
| | 116 | 135 | | partitionKey: GetConcurrencyPartitionKey( |
| | 116 | 136 | | httpContext, |
| | 116 | 137 | | rateLimitingOptions, |
| | 116 | 138 | | CreateRateLimitingLogger(httpContext), |
| | 116 | 139 | | fallbackWarningThrottle), |
| | 116 | 140 | | factory: _ => CreateConcurrencyLimiterOptions(rateLimitingOptions.ConcurrencyPolicy))); |
| | 116 | 141 | | }); |
| | | 142 | | |
| | 116 | 143 | | return services; |
| | | 144 | | } |
| | | 145 | | /// <summary> |
| | | 146 | | /// Writes the rejection log entry for a rate-limited request, honoring the request-logging privacy options. |
| | | 147 | | /// </summary> |
| | | 148 | | /// <param name="httpContext">The rejected request's HTTP context.</param> |
| | | 149 | | /// <param name="logger">The logger that receives the entry.</param> |
| | | 150 | | /// <param name="retryAfter">The retry interval reported by the limiter lease, when available.</param> |
| | | 151 | | internal static void LogRejectedRequest( |
| | | 152 | | HttpContext httpContext, |
| | | 153 | | ILogger logger, |
| | | 154 | | TimeSpan? retryAfter) |
| | | 155 | | { |
| | 7 | 156 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | 7 | 157 | | ArgumentNullException.ThrowIfNull(logger); |
| | | 158 | | |
| | 7 | 159 | | LogRateLimitRejectedRequest( |
| | 7 | 160 | | logger, |
| | 7 | 161 | | httpContext.Request.Method, |
| | 7 | 162 | | httpContext.Request.Path.Value ?? string.Empty, |
| | 7 | 163 | | RequestLoggingPrivacy.GetLoggableRemoteIpAddress(httpContext), |
| | 7 | 164 | | httpContext.GetEndpoint()?.DisplayName, |
| | 7 | 165 | | retryAfter?.TotalSeconds, |
| | 7 | 166 | | httpContext.TraceIdentifier); |
| | 7 | 167 | | } |
| | | 168 | | |
| | | 169 | | /// <summary> |
| | | 170 | | /// Writes the <c>429 Too Many Requests</c> response for a rate-limited request. |
| | | 171 | | /// </summary> |
| | | 172 | | /// <remarks> |
| | | 173 | | /// API-shaped requests, as classified by <see cref="ProblemDetailsRequestClassifier"/>, receive a Problem Details |
| | | 174 | | /// response through <see cref="IProblemDetailsService"/>, so the shared customization adds the trace, request, and |
| | | 175 | | /// correlation identifiers. Other requests receive a short plain-text body. The browser error page is intentionally |
| | | 176 | | /// not re-executed: rejections must stay cheap, and rendering a view for every rejected request would work against |
| | | 177 | | /// the protection the limiter provides. |
| | | 178 | | /// </remarks> |
| | | 179 | | /// <param name="httpContext">The rejected request's HTTP context.</param> |
| | | 180 | | /// <param name="retryAfter">The retry interval reported by the limiter lease, when available.</param> |
| | | 181 | | /// <param name="cancellationToken">A token that cancels writing the response.</param> |
| | | 182 | | /// <returns>A task that completes when the response has been written.</returns> |
| | | 183 | | internal static async Task WriteRejectionResponseAsync( |
| | | 184 | | HttpContext httpContext, |
| | | 185 | | TimeSpan? retryAfter, |
| | | 186 | | CancellationToken cancellationToken) |
| | | 187 | | { |
| | 5 | 188 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | | 189 | | |
| | 5 | 190 | | HttpResponse response = httpContext.Response; |
| | 5 | 191 | | response.StatusCode = StatusCodes.Status429TooManyRequests; |
| | | 192 | | |
| | 5 | 193 | | if (retryAfter is TimeSpan retryAfterValue) |
| | | 194 | | { |
| | 4 | 195 | | response.Headers.RetryAfter = Math.Ceiling(retryAfterValue.TotalSeconds) |
| | 4 | 196 | | .ToString(CultureInfo.InvariantCulture); |
| | | 197 | | } |
| | | 198 | | |
| | 5 | 199 | | if (ProblemDetailsRequestClassifier.ShouldWriteProblemDetails(httpContext)) |
| | | 200 | | { |
| | 1 | 201 | | IProblemDetailsService? problemDetailsService = httpContext.RequestServices? |
| | 1 | 202 | | .GetService<IProblemDetailsService>(); |
| | | 203 | | |
| | 1 | 204 | | if (problemDetailsService is not null) |
| | | 205 | | { |
| | 1 | 206 | | ProblemDetailsContext problemDetailsContext = new() |
| | 1 | 207 | | { |
| | 1 | 208 | | HttpContext = httpContext, |
| | 1 | 209 | | ProblemDetails = new ProblemDetails |
| | 1 | 210 | | { |
| | 1 | 211 | | Status = StatusCodes.Status429TooManyRequests, |
| | 1 | 212 | | Title = RejectionTitle, |
| | 1 | 213 | | Type = RejectionProblemType, |
| | 1 | 214 | | Detail = RejectionDetail |
| | 1 | 215 | | } |
| | 1 | 216 | | }; |
| | | 217 | | |
| | 1 | 218 | | if (await problemDetailsService.TryWriteAsync(problemDetailsContext).ConfigureAwait(false)) |
| | | 219 | | { |
| | 1 | 220 | | return; |
| | | 221 | | } |
| | | 222 | | } |
| | | 223 | | } |
| | | 224 | | |
| | 4 | 225 | | if (HttpMethods.IsHead(httpContext.Request.Method)) |
| | | 226 | | { |
| | 0 | 227 | | return; |
| | | 228 | | } |
| | | 229 | | |
| | 4 | 230 | | response.ContentType = "text/plain; charset=utf-8"; |
| | 4 | 231 | | await response.WriteAsync(RejectionDetail, cancellationToken).ConfigureAwait(false); |
| | 5 | 232 | | } |
| | | 233 | | |
| | | 234 | | private static ApplicationRateLimitingOptions CreateDefaultOptions(IHostEnvironment environment) |
| | | 235 | | { |
| | 202 | 236 | | ApplicationRateLimitingOptions options = new(); |
| | | 237 | | |
| | 202 | 238 | | if (environment.IsDevelopment()) |
| | | 239 | | { |
| | 0 | 240 | | options.GlobalFixedWindow.PermitLimit = 300; |
| | 0 | 241 | | options.GlobalFixedWindow.WindowSeconds = 60; |
| | | 242 | | |
| | 0 | 243 | | options.FixedWindowPolicy.PermitLimit = 120; |
| | 0 | 244 | | options.FixedWindowPolicy.WindowSeconds = 60; |
| | | 245 | | |
| | 0 | 246 | | options.ConcurrencyPolicy.PermitLimit = 20; |
| | | 247 | | } |
| | | 248 | | |
| | 202 | 249 | | return options; |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | private static FixedWindowRateLimiterOptions CreateFixedWindowRateLimiterOptions( |
| | | 253 | | FixedWindowRateLimitingOptions options) |
| | | 254 | | { |
| | 84 | 255 | | return new FixedWindowRateLimiterOptions |
| | 84 | 256 | | { |
| | 84 | 257 | | AutoReplenishment = true, |
| | 84 | 258 | | PermitLimit = EnsureAtLeast(options.PermitLimit, minimum: 1), |
| | 84 | 259 | | Window = TimeSpan.FromSeconds(EnsureAtLeast(options.WindowSeconds, minimum: 1)), |
| | 84 | 260 | | QueueProcessingOrder = QueueProcessingOrder.OldestFirst, |
| | 84 | 261 | | QueueLimit = EnsureAtLeast(options.QueueLimit, minimum: 0) |
| | 84 | 262 | | }; |
| | | 263 | | } |
| | | 264 | | |
| | | 265 | | private static ConcurrencyLimiterOptions CreateConcurrencyLimiterOptions( |
| | | 266 | | ConcurrencyRateLimitingOptions options) |
| | | 267 | | { |
| | 1 | 268 | | return new ConcurrencyLimiterOptions |
| | 1 | 269 | | { |
| | 1 | 270 | | PermitLimit = EnsureAtLeast(options.PermitLimit, minimum: 1), |
| | 1 | 271 | | QueueProcessingOrder = QueueProcessingOrder.OldestFirst, |
| | 1 | 272 | | QueueLimit = EnsureAtLeast(options.QueueLimit, minimum: 0) |
| | 1 | 273 | | }; |
| | | 274 | | } |
| | | 275 | | |
| | | 276 | | private static string GetClientPartitionKey( |
| | | 277 | | HttpContext httpContext, |
| | | 278 | | ApplicationRateLimitingOptions options, |
| | | 279 | | RateLimitingFallbackWarningThrottle fallbackWarningThrottle) |
| | | 280 | | { |
| | 115 | 281 | | return GetClientPartitionKey( |
| | 115 | 282 | | httpContext, |
| | 115 | 283 | | options, |
| | 115 | 284 | | CreateRateLimitingLogger(httpContext), |
| | 115 | 285 | | fallbackWarningThrottle); |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | private static ILogger CreateRateLimitingLogger(HttpContext httpContext) |
| | | 289 | | { |
| | 118 | 290 | | return httpContext.RequestServices |
| | 118 | 291 | | .GetRequiredService<ILoggerFactory>() |
| | 118 | 292 | | .CreateLogger("Template.Web.RateLimiting"); |
| | | 293 | | } |
| | | 294 | | |
| | | 295 | | internal static string GetClientPartitionKey( |
| | | 296 | | HttpContext httpContext, |
| | | 297 | | ApplicationRateLimitingOptions options, |
| | | 298 | | ILogger logger, |
| | | 299 | | RateLimitingFallbackWarningThrottle? fallbackWarningThrottle = null) |
| | | 300 | | { |
| | 128 | 301 | | IPAddress? remoteIpAddress = httpContext.Connection.RemoteIpAddress; |
| | | 302 | | |
| | 128 | 303 | | if (remoteIpAddress is not null) |
| | | 304 | | { |
| | 4 | 305 | | return GetAddressPartitionKey(remoteIpAddress, options.IPv6PartitionPrefixLength); |
| | | 306 | | } |
| | | 307 | | |
| | 124 | 308 | | string fallbackPartitionKey = string.IsNullOrWhiteSpace(options.UnknownClientPartitionKey) |
| | 124 | 309 | | ? "unknown-client" |
| | 124 | 310 | | : options.UnknownClientPartitionKey.Trim(); |
| | 124 | 311 | | string fallbackMode = options.UseSharedUnknownClientPartition ? "Shared" : "PerRequest"; |
| | 124 | 312 | | string fallbackDiscriminator = string.IsNullOrWhiteSpace(httpContext.TraceIdentifier) |
| | 124 | 313 | | ? Guid.NewGuid().ToString("N") |
| | 124 | 314 | | : httpContext.TraceIdentifier; |
| | | 315 | | |
| | 124 | 316 | | if (!options.UseSharedUnknownClientPartition) |
| | | 317 | | { |
| | 103 | 318 | | fallbackPartitionKey = $"{fallbackPartitionKey}:{fallbackDiscriminator}"; |
| | | 319 | | } |
| | | 320 | | |
| | 124 | 321 | | long suppressedWarningCount = 0; |
| | | 322 | | |
| | 124 | 323 | | if (fallbackWarningThrottle is null || |
| | 124 | 324 | | fallbackWarningThrottle.TryAcquire(out suppressedWarningCount)) |
| | | 325 | | { |
| | 83 | 326 | | LogRateLimitingClientPartitionFallback( |
| | 83 | 327 | | logger, |
| | 83 | 328 | | fallbackMode, |
| | 83 | 329 | | fallbackPartitionKey, |
| | 83 | 330 | | fallbackDiscriminator, |
| | 83 | 331 | | suppressedWarningCount); |
| | | 332 | | } |
| | | 333 | | |
| | 124 | 334 | | return fallbackPartitionKey; |
| | | 335 | | } |
| | | 336 | | |
| | | 337 | | /// <summary> |
| | | 338 | | /// Returns the rate limiting partition key for a client address. |
| | | 339 | | /// </summary> |
| | | 340 | | /// <remarks> |
| | | 341 | | /// IPv4-mapped IPv6 addresses are converted to IPv4 first, because a dual-stack listener reports IPv4 clients in |
| | | 342 | | /// that form and masking them as IPv6 would place every IPv4 client in one partition. Other IPv6 addresses are |
| | | 343 | | /// reduced to their network prefix so a client cannot bypass the limiter by rotating addresses inside it. |
| | | 344 | | /// </remarks> |
| | | 345 | | /// <param name="address">The client address.</param> |
| | | 346 | | /// <param name="ipv6PrefixLength">The IPv6 prefix length that identifies one client.</param> |
| | | 347 | | /// <returns>The partition key.</returns> |
| | | 348 | | internal static string GetAddressPartitionKey(IPAddress address, int ipv6PrefixLength) |
| | | 349 | | { |
| | 12 | 350 | | ArgumentNullException.ThrowIfNull(address); |
| | | 351 | | |
| | 12 | 352 | | IPAddress normalizedAddress = address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address; |
| | | 353 | | |
| | 12 | 354 | | if (normalizedAddress.AddressFamily != AddressFamily.InterNetworkV6 |
| | 12 | 355 | | || ipv6PrefixLength >= _ipv6AddressBitCount) |
| | | 356 | | { |
| | 6 | 357 | | return normalizedAddress.ToString(); |
| | | 358 | | } |
| | | 359 | | |
| | 6 | 360 | | int prefixLength = Math.Max(ipv6PrefixLength, 1); |
| | 6 | 361 | | byte[] addressBytes = normalizedAddress.GetAddressBytes(); |
| | 788 | 362 | | for (int bitIndex = prefixLength; bitIndex < _ipv6AddressBitCount; bitIndex++) |
| | | 363 | | { |
| | 388 | 364 | | addressBytes[bitIndex / 8] &= (byte)~(0x80 >> (bitIndex % 8)); |
| | | 365 | | } |
| | | 366 | | |
| | 6 | 367 | | return string.Create(CultureInfo.InvariantCulture, $"{new IPAddress(addressBytes)}/{prefixLength}"); |
| | | 368 | | } |
| | | 369 | | |
| | | 370 | | /// <summary> |
| | | 371 | | /// Returns the partition key used by the named concurrency policy. |
| | | 372 | | /// </summary> |
| | | 373 | | /// <param name="httpContext">The current HTTP context.</param> |
| | | 374 | | /// <param name="options">The rate limiting options.</param> |
| | | 375 | | /// <param name="logger">The logger used when the client address falls back to an unknown-client partition.</param> |
| | | 376 | | /// <param name="fallbackWarningThrottle">An optional throttle for fallback warnings.</param> |
| | | 377 | | /// <returns>The endpoint key, combined with the client key when concurrency is partitioned by client.</returns> |
| | | 378 | | internal static string GetConcurrencyPartitionKey( |
| | | 379 | | HttpContext httpContext, |
| | | 380 | | ApplicationRateLimitingOptions options, |
| | | 381 | | ILogger logger, |
| | | 382 | | RateLimitingFallbackWarningThrottle? fallbackWarningThrottle = null) |
| | | 383 | | { |
| | 5 | 384 | | ArgumentNullException.ThrowIfNull(httpContext); |
| | 5 | 385 | | ArgumentNullException.ThrowIfNull(options); |
| | | 386 | | |
| | 5 | 387 | | string endpointPartitionKey = GetEndpointPartitionKey(httpContext); |
| | | 388 | | |
| | 5 | 389 | | return options.ConcurrencyPolicy.PartitionByClient |
| | 5 | 390 | | ? $"{endpointPartitionKey}|{GetClientPartitionKey(httpContext, options, logger, fallbackWarningThrottle)}" |
| | 5 | 391 | | : endpointPartitionKey; |
| | | 392 | | } |
| | | 393 | | |
| | | 394 | | private static string GetEndpointPartitionKey(HttpContext httpContext) |
| | | 395 | | { |
| | 5 | 396 | | return httpContext.GetEndpoint()?.DisplayName |
| | 5 | 397 | | ?? httpContext.Request.Path.Value |
| | 5 | 398 | | ?? "unknown-endpoint"; |
| | | 399 | | } |
| | | 400 | | |
| | | 401 | | private static int EnsureAtLeast(int value, int minimum) |
| | | 402 | | { |
| | 254 | 403 | | return value < minimum ? minimum : value; |
| | | 404 | | } |
| | | 405 | | |
| | | 406 | | [LoggerMessage( |
| | | 407 | | EventId = ApplicationLogEventIds.RateLimitRejectedRequest, |
| | | 408 | | Level = LogLevel.Warning, |
| | | 409 | | Message = "Rate limit rejected request. Method: {Method}; Path: {Path}; RemoteIpAddress: {RemoteIpAddress}; Endp |
| | | 410 | | private static partial void LogRateLimitRejectedRequest( |
| | | 411 | | ILogger logger, |
| | | 412 | | string method, |
| | | 413 | | string path, |
| | | 414 | | string? remoteIpAddress, |
| | | 415 | | string? endpoint, |
| | | 416 | | double? retryAfterSeconds, |
| | | 417 | | string traceIdentifier); |
| | | 418 | | |
| | | 419 | | [LoggerMessage( |
| | | 420 | | EventId = ApplicationLogEventIds.RateLimitClientPartitionFallback, |
| | | 421 | | Level = LogLevel.Warning, |
| | | 422 | | Message = "Rate limiting used fallback client partition because RemoteIpAddress was unavailable. FallbackMode: { |
| | | 423 | | private static partial void LogRateLimitingClientPartitionFallback( |
| | | 424 | | ILogger logger, |
| | | 425 | | string fallbackMode, |
| | | 426 | | string partitionKey, |
| | | 427 | | string traceIdentifier, |
| | | 428 | | long suppressedWarningCount); |
| | | 429 | | } |