| | | 1 | | using Microsoft.AspNetCore.RateLimiting; |
| | | 2 | | using System.Threading.RateLimiting; |
| | | 3 | | using static System.Globalization.CultureInfo; |
| | | 4 | | |
| | | 5 | | namespace Anichron.API.Infrastructure; |
| | | 6 | | |
| | | 7 | | internal static class RateLimiting |
| | | 8 | | { |
| | | 9 | | // RemoteIpAddress is populated by UseForwardedHeaders before this middleware runs. |
| | | 10 | | // Requests with no resolvable IP share a tight "unresolved" bucket to prevent IP-hiding abuse. |
| | | 11 | | internal static string PartitionKey(HttpContext httpContext) |
| | 171 | 12 | | => httpContext.Connection.RemoteIpAddress?.ToString() ?? "unresolved"; |
| | | 13 | | |
| | | 14 | | internal static Task RejectAsync(HttpContext httpContext, TimeSpan retryAfter) |
| | 6 | 15 | | { |
| | 6 | 16 | | httpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString(InvariantCulture); |
| | 6 | 17 | | return ApiProblems.Problem( |
| | 6 | 18 | | StatusCodes.Status429TooManyRequests, ErrorCodes.RateLimited, ProblemMessages.TooManyRequests) |
| | 6 | 19 | | .ExecuteAsync(httpContext); |
| | 6 | 20 | | } |
| | | 21 | | } |
| | | 22 | | |
| | | 23 | | internal static class AuthRateLimitPolicies |
| | | 24 | | { |
| | | 25 | | internal const string Sensitive = "auth-sensitive"; |
| | | 26 | | internal const string Refresh = "auth-refresh"; |
| | | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <summary>A per-client sliding window whose rejection asks the client to wait one whole window.</summary> |
| | | 30 | | /// <param name="permitLimit">The requests one client may make per window.</param> |
| | | 31 | | /// <param name="window">The window.</param> |
| | | 32 | | /// <param name="segmentsPerWindow">The segments the window slides by.</param> |
| | | 33 | | internal sealed class SlidingWindowPolicy(int permitLimit, TimeSpan window, int segmentsPerWindow) : IRateLimiterPolicy< |
| | | 34 | | { |
| | | 35 | | public Func<OnRejectedContext, CancellationToken, ValueTask> OnRejected |
| | | 36 | | => (context, _) => new ValueTask(RateLimiting.RejectAsync(context.HttpContext, window)); |
| | | 37 | | |
| | | 38 | | public RateLimitPartition<string> GetPartition(HttpContext httpContext) |
| | | 39 | | => RateLimitPartition.GetSlidingWindowLimiter( |
| | | 40 | | partitionKey: RateLimiting.PartitionKey(httpContext), |
| | | 41 | | factory: _ => new SlidingWindowRateLimiterOptions |
| | | 42 | | { |
| | | 43 | | PermitLimit = permitLimit, |
| | | 44 | | Window = window, |
| | | 45 | | SegmentsPerWindow = segmentsPerWindow, |
| | | 46 | | QueueProcessingOrder = QueueProcessingOrder.OldestFirst, |
| | | 47 | | QueueLimit = 0, |
| | | 48 | | }); |
| | | 49 | | } |