From 4107ecc65457d5f1c73a7c78c9a2b8ed0a942e03 Mon Sep 17 00:00:00 2001 From: Slendy Date: Sun, 22 Jan 2023 04:29:53 -0600 Subject: [PATCH] Fix base64 image parsing and remove DBContext from rate limiter --- ProjectLighthouse/Files/FileHelper.cs | 10 +++++++++- ProjectLighthouse/Middlewares/RateLimitMiddleware.cs | 10 +++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/ProjectLighthouse/Files/FileHelper.cs b/ProjectLighthouse/Files/FileHelper.cs index bd4e7651..0a2ec16b 100644 --- a/ProjectLighthouse/Files/FileHelper.cs +++ b/ProjectLighthouse/Files/FileHelper.cs @@ -274,6 +274,13 @@ public static class FileHelper private static readonly Regex base64Regex = new(@"data:([^\/]+)\/([^;]+);base64,(.*)", RegexOptions.Compiled); + private static byte[]? TryParseBase64Data(string b64) + { + Span buffer = new(new byte[b64.Length]); + bool valid = Convert.TryFromBase64String(b64, buffer, out _); + return valid ? buffer.ToArray() : null; + } + public static async Task ParseBase64Image(string? image) { if (string.IsNullOrWhiteSpace(image)) return null; @@ -284,7 +291,8 @@ public static class FileHelper if (match.Groups.Count != 4) return null; - byte[] data = Convert.FromBase64String(match.Groups[3].Value); + byte[]? data = TryParseBase64Data(match.Groups[3].Value); + if (data == null) return null; LbpFile file = new(data); diff --git a/ProjectLighthouse/Middlewares/RateLimitMiddleware.cs b/ProjectLighthouse/Middlewares/RateLimitMiddleware.cs index 46b4d1b9..66f60fd5 100644 --- a/ProjectLighthouse/Middlewares/RateLimitMiddleware.cs +++ b/ProjectLighthouse/Middlewares/RateLimitMiddleware.cs @@ -13,16 +13,16 @@ using Microsoft.AspNetCore.Http; namespace LBPUnion.ProjectLighthouse.Middlewares; -public class RateLimitMiddleware : MiddlewareDBContext +public class RateLimitMiddleware : Middleware { - // (userId, requestData) + // (ipAddress, requestData) private static readonly ConcurrentDictionary> recentRequests = new(); public RateLimitMiddleware(RequestDelegate next) : base(next) { } - public override async Task InvokeAsync(HttpContext ctx, Database database) + public override async Task InvokeAsync(HttpContext ctx) { // We only want to rate limit POST requests if (ctx.Request.Method != "POST") @@ -51,9 +51,9 @@ public class RateLimitMiddleware : MiddlewareDBContext if (GetNumRequestsForPath(address, path) >= GetMaxNumRequests(options)) { - Logger.Info($"Request limit reached for {address.ToString()} ({ctx.Request.Path})", LogArea.RateLimit); + Logger.Info($"Request limit reached for {address} ({ctx.Request.Path})", LogArea.RateLimit); long nextExpiration = recentRequests[address][0]?.Expiration ?? TimeHelper.TimestampMillis; - ctx.Response.Headers.Add("Retry-After", "" + Math.Ceiling((nextExpiration - TimeHelper.TimestampMillis) / 1000f)); + ctx.Response.Headers.TryAdd("Retry-After", "" + Math.Ceiling((nextExpiration - TimeHelper.TimestampMillis) / 1000f)); ctx.Response.StatusCode = 429; return; }