mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 17:11:10 +00:00
Merge pull request #63 from BinaryAlley/refactor/update-rate-limiting-rule-to-be-ip-based
Updates rate limiting rule to be IP based
This commit is contained in:
2 files changed
+40
-8
No files matched your search
+38
-8
@@ -5,15 +5,14 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Http.Json;
|
using Microsoft.AspNetCore.Http.Json;
|
||||||
using Microsoft.AspNetCore.Mvc.Infrastructure;
|
|
||||||
using Microsoft.AspNetCore.RateLimiting;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using Serilog;
|
||||||
using System;
|
using System;
|
||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json;
|
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using System.Threading.RateLimiting;
|
using System.Threading.RateLimiting;
|
||||||
#endregion
|
#endregion
|
||||||
@@ -44,14 +43,36 @@ public static class PresentationApiLayerServices
|
|||||||
jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
|
jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// TODO: also implement account locking after a number of failed login attempts
|
||||||
services.AddRateLimiter(options =>
|
services.AddRateLimiter(options =>
|
||||||
{
|
{
|
||||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
options.OnRejected = async (context, cancellationToken) =>
|
options.OnRejected = async (context, cancellationToken) =>
|
||||||
{
|
{
|
||||||
|
ILogger logger = context.HttpContext.RequestServices.GetRequiredService<ILogger>();
|
||||||
|
|
||||||
|
string clientIp = context.HttpContext.Request.Headers["X-Forwarded-For"]
|
||||||
|
.FirstOrDefault()?.Split(',')[0].Trim()
|
||||||
|
?? context.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||||
|
?? "unknown";
|
||||||
|
Log.Warning(
|
||||||
|
"Rate limit exceeded. IP: {IpAddress}, Route: {Route}, Lease Acquired: {IsAcquired}",
|
||||||
|
clientIp,
|
||||||
|
context.HttpContext.Request.Path,
|
||||||
|
context.Lease.IsAcquired); // when False, the request was rejected because it exceeded rate limits
|
||||||
|
|
||||||
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
context.HttpContext.Response.ContentType = "application/problem+json";
|
context.HttpContext.Response.ContentType = "application/problem+json";
|
||||||
|
|
||||||
|
// set standard rate limit headers
|
||||||
|
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out TimeSpan retryAfter))
|
||||||
|
context.HttpContext.Response.Headers.RetryAfter = ((int)retryAfter.TotalSeconds).ToString();
|
||||||
|
|
||||||
|
// set custom rate limit headers
|
||||||
|
context.HttpContext.Response.Headers["X-RateLimit-Limit"] = "10";
|
||||||
|
context.HttpContext.Response.Headers["X-RateLimit-Remaining"] = "0";
|
||||||
|
context.HttpContext.Response.Headers["X-RateLimit-Reset"] = DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds().ToString();
|
||||||
|
|
||||||
var problem = new
|
var problem = new
|
||||||
{
|
{
|
||||||
type = "https://tools.ietf.org/html/rfc7231#section-6.5.29",
|
type = "https://tools.ietf.org/html/rfc7231#section-6.5.29",
|
||||||
@@ -63,12 +84,21 @@ public static class PresentationApiLayerServices
|
|||||||
|
|
||||||
await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
|
await context.HttpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
|
||||||
};
|
};
|
||||||
options.AddFixedWindowLimiter("authenticationPolicy", config =>
|
options.AddPolicy("authenticationPolicy", httpContext =>
|
||||||
{
|
{
|
||||||
config.PermitLimit = 10; // allow 10 attempts
|
string clientIp = httpContext.Request.Headers["X-Forwarded-For"] // first check forwarded headers, in case this is behind a reverse proxy
|
||||||
config.Window = TimeSpan.FromMinutes(15); // within 15 minute window
|
.FirstOrDefault()?.Split(',')[0].Trim() // take first IP, if multiple available, to avoid IP spoofing attempts
|
||||||
config.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
|
?? httpContext.Connection.RemoteIpAddress?.ToString() // then try RemoteIpAddress
|
||||||
config.QueueLimit = 0; // don't queue requests
|
?? "unknown"; // fallback if both are null
|
||||||
|
return RateLimitPartition.GetFixedWindowLimiter(
|
||||||
|
partitionKey: $"auth_{clientIp}",
|
||||||
|
factory: _ => new FixedWindowRateLimiterOptions
|
||||||
|
{
|
||||||
|
PermitLimit = 10, // allow 10 attempts
|
||||||
|
Window = TimeSpan.FromMinutes(15), // within 15 minute window
|
||||||
|
QueueLimit = 0, // don't queue requests
|
||||||
|
AutoReplenishment = true // automatically reset rate limiter tokens
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+2
@@ -7,6 +7,7 @@ using Lumina.Contracts.Responses.Authentication;
|
|||||||
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
|
using Lumina.Presentation.Api.Common.Routes.UsersManagement;
|
||||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||||
using Mediator;
|
using Mediator;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -40,6 +41,7 @@ public class RegisterEndpoint : BaseEndpoint<RegistrationRequest, IResult>
|
|||||||
Version(1);
|
Version(1);
|
||||||
AllowAnonymous();
|
AllowAnonymous();
|
||||||
DontCatchExceptions();
|
DontCatchExceptions();
|
||||||
|
Options(x => x.RequireRateLimiting("authenticationPolicy"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
Reference in new issue
Block a user