[backend/api-shared] Fix upload of files larger than 28MB.

This commit is contained in:
Laura Hausmann 2024-09-05 22:08:50 +02:00
parent 89efdff3c0
commit b50121d0a1
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
4 changed files with 29 additions and 0 deletions

View file

@ -25,6 +25,7 @@ namespace Iceshrimp.Backend.Controllers.Mastodon;
[Produces(MediaTypeNames.Application.Json)]
public class MediaController(DriveService driveSvc, DatabaseContext db) : ControllerBase
{
[MaxRequestSizeIsMaxUploadSize]
[HttpPost("/api/v1/media")]
[HttpPost("/api/v2/media")]
[ProducesResults(HttpStatusCode.OK)]

View file

@ -0,0 +1,24 @@
using Iceshrimp.Backend.Core.Configuration;
using Iceshrimp.Backend.Core.Middleware;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
namespace Iceshrimp.Backend.Controllers.Shared.Attributes;
public class MaxRequestSizeIsMaxUploadSize : Attribute, IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
var feature = context.HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>() ??
throw new Exception("Failed to get IHttpMaxRequestBodySizeFeature");
var config = context.HttpContext.RequestServices.GetRequiredService<IOptionsSnapshot<Config.StorageSection>>();
feature.MaxRequestBodySize = config.Value.MaxUploadSizeBytes;
if (context.HttpContext.Request.ContentLength > config.Value.MaxUploadSizeBytes)
throw GracefulException.RequestEntityTooLarge("Attachment is too large.",
$"The media upload size limit is set to {config.Value.MaxUploadSizeBytes} bytes.");
}
public void OnResourceExecuted(ResourceExecutedContext context) { }
}

View file

@ -82,6 +82,7 @@ public class DriveController(
[Authorize]
[Produces(MediaTypeNames.Application.Json)]
[ProducesResults(HttpStatusCode.OK)]
[MaxRequestSizeIsMaxUploadSize]
public async Task<DriveFileResponse> UploadFile(IFormFile file)
{
var user = HttpContext.GetUserOrFail();

View file

@ -232,6 +232,9 @@ public class GracefulException(
public static GracefulException Conflict(string message, string? details = null) =>
new(HttpStatusCode.Conflict, message, details);
public static GracefulException RequestEntityTooLarge(string message, string? details = null) =>
new(HttpStatusCode.RequestEntityTooLarge, message, details);
public static GracefulException RecordNotFound() => new(HttpStatusCode.NotFound, "Record not found");
public static GracefulException MisdirectedRequest() =>