Files
mtusi2026lab4/scr/Messenger.Api/Endpoints/AttachmentEndpoints.cs
T

166 lines
10 KiB
C#

using System.Security.Cryptography;
using Messenger.Api.Data;
using Messenger.Api.Models;
using Messenger.Api.Services;
using Microsoft.EntityFrameworkCore;
using StbImageSharp;
namespace Messenger.Api.Endpoints;
public static class AttachmentEndpoints
{
public static IEndpointRouteBuilder MapAttachmentEndpoints(this IEndpointRouteBuilder endpoints)
{
endpoints.MapPost("/api/v1/chats/{chatId}/attachments", Upload).RequireAuthorization();
endpoints.MapGet("/api/v1/attachments/{attachmentId}", Metadata).RequireAuthorization();
endpoints.MapGet("/api/v1/attachments/{attachmentId}/content", Content).RequireAuthorization();
return endpoints;
}
private static async Task<IResult> Upload(Guid chatId, HttpContext http, MessengerDbContext db,
IAttachmentStorage storage, UploadSettings limits, UploadGate gate, UploadCleanupSettings cleanup)
{
var user = http.GetUserId();
if (!await db.ChatMembers.AnyAsync(m => m.ChatId == chatId && m.UserId == user, http.RequestAborted))
return ApiErrors.Error(http, 404, "not_found", "Объект не найден");
var names = http.Request.Query["filename"];
var name = names.Count == 1 ? names[0] : null;
if (string.IsNullOrWhiteSpace(name) || ApiErrors.CodePoints(name) > 255 ||
name.Any(c => c is '/' or '\\' || char.IsControl(c)))
return ApiErrors.Error(http, 400, "invalid_request", "Некорректное имя файла");
var mime = http.Request.ContentType?.Split(';', 2)[0].Trim().ToLowerInvariant();
if (mime is not ("image/png" or "image/jpeg"))
return ApiErrors.Error(http, 415, "unsupported_media_type", "Требуется PNG или JPEG");
if (http.Request.ContentLength > limits.MaxBytes)
return ApiErrors.Error(http, 413, "payload_too_large", "Файл превышает лимит размера");
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
var ct = timeout.Token;
if (!await gate.Slots.WaitAsync(TimeSpan.FromSeconds(2), ct))
return ApiErrors.Error(http, 503, "unavailable", "Загрузка временно перегружена");
try
{
// Только временный spool; оригинал после 201 существует в S3, не на диске API.
var path = Path.Combine(Path.GetTempPath(), $"attachment-{Guid.NewGuid():N}");
await using var file = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None,
65536, FileOptions.Asynchronous | FileOptions.DeleteOnClose);
var buffer = new byte[65536];
long size = 0;
while (true)
{
var count = await http.Request.Body.ReadAsync(buffer, ct);
if (count == 0) break;
size += count;
if (size > limits.MaxBytes)
return ApiErrors.Error(http, 413, "payload_too_large", "Файл превышает лимит размера");
await file.WriteAsync(buffer.AsMemory(0, count), ct);
}
file.Position = 0;
try
{
var signature = new byte[8];
if (size < 12) throw new InvalidDataException("Truncated image");
await file.ReadExactlyAsync(signature, ct);
var actual = signature.AsSpan().SequenceEqual(new byte[] {137,80,78,71,13,10,26,10}) ? "image/png" :
signature[0] == 255 && signature[1] == 216 ? "image/jpeg" : "unknown";
if (actual != mime)
return ApiErrors.Error(http, 415, "unsupported_media_type", "Содержимое не соответствует MIME");
file.Position = 0;
var info = ImageInfo.FromStream(file) ?? throw new InvalidDataException("Invalid image header");
if (info.Width <= 0 || info.Height <= 0) throw new InvalidDataException("Invalid dimensions");
if ((long)info.Width * info.Height > limits.MaxPixels)
return ApiErrors.Error(http, 413, "payload_too_large", "Слишком много пикселей");
if (mime == "image/png") await PngIntegrity.ValidateAsync(file,
(long)info.Width * info.Height * 8 + info.Height * 8L + 1024, ct);
file.Position = 0;
var image = ImageResult.FromStream(file, ColorComponents.Grey);
if (image.Width != info.Width || image.Height != info.Height) throw new InvalidDataException("Invalid dimensions");
ct.ThrowIfCancellationRequested();
// Декодеры могут принимать обрезанные JPEG: обязательно проверяем окончание файла.
var tail = new byte[12];
if (size < tail.Length) throw new InvalidDataException("Truncated image");
file.Position = size - tail.Length;
await file.ReadExactlyAsync(tail, ct);
if (mime == "image/png" && !tail.AsSpan().SequenceEqual(new byte[] { 0,0,0,0,73,69,78,68,174,66,96,130 }) ||
mime == "image/jpeg" && (tail[^2] != 255 || tail[^1] != 217))
throw new InvalidDataException("Truncated image");
}
catch (Exception ex) when (ex is InvalidDataException or EndOfStreamException or InvalidOperationException or ArgumentException or IndexOutOfRangeException)
{
return ApiErrors.Error(http, 415, "unsupported_media_type", "Повреждённое изображение");
}
file.Position = 0;
var hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(file, ct));
var id = Guid.CreateVersion7();
var now = Timestamps.UtcNowMilliseconds();
var entity = new AttachmentEntity
{
Id = id, ChatId = chatId, OwnerId = user, Filename = name!, ContentType = mime!,
ObjectKey = $"originals/{id:N}", SizeBytes = size, ChecksumSha256 = hash,
Status = "ready", CreatedAt = now, UploadedAt = now
};
var intent = new UploadIntentEntity
{
Id = id, ObjectKey = entity.ObjectKey, CreatedAt = now,
ExpiresAt = now + cleanup.Grace, NextAttemptAt = now + cleanup.Grace
};
db.UploadIntents.Add(intent);
await db.SaveChangesAsync(ct); // S3 PUT не начинается без устойчивого журнала.
file.Position = 0;
await storage.PutAsync(entity.ObjectKey, file, entity.ContentType, ct);
await using var tx = await db.Database.BeginTransactionAsync(ct);
var activeIntent = await db.UploadIntents.FromSqlInterpolated($"""
SELECT * FROM upload_intents WHERE id = {id} AND expires_at > clock_timestamp() FOR UPDATE
""").SingleOrDefaultAsync(ct);
if (activeIntent is null)
return ApiErrors.Error(http, 503, "unavailable", "Время публикации вложения истекло");
db.Attachments.Add(entity);
db.UploadIntents.Remove(activeIntent);
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct); // Attachment и удаление intent — один COMMIT.
return Results.Created($"/api/v1/attachments/{id}", ToDto(entity));
}
catch (OperationCanceledException) when (!http.RequestAborted.IsCancellationRequested)
{
return ApiErrors.Error(http, 503, "unavailable", "Истекло время загрузки");
}
finally { gate.Slots.Release(); }
}
private static Task<AttachmentEntity?> Find(Guid id, HttpContext http, MessengerDbContext db) =>
db.Attachments.AsNoTracking().FirstOrDefaultAsync(a => a.Id == id &&
db.ChatMembers.Any(m => m.ChatId == a.ChatId && m.UserId == http.GetUserId()), http.RequestAborted);
private static async Task<IResult> Metadata(Guid attachmentId, HttpContext http, MessengerDbContext db)
{
var entity = await Find(attachmentId, http, db);
return entity is null ? ApiErrors.Error(http, 404, "not_found", "Объект не найден") : Results.Ok(ToDto(entity));
}
private static async Task<IResult> Content(Guid attachmentId, HttpContext http, MessengerDbContext db,
IAttachmentStorage storage, string? variant)
{
var entity = await Find(attachmentId, http, db);
if (entity is null) return ApiErrors.Error(http, 404, "not_found", "Объект не найден");
if (entity.Status != "ready") return ApiErrors.Error(http, 409, "conflict", "Вложение не готово");
if (variant is not (null or "original")) return ApiErrors.Error(http, 404, "not_found", "Вариант не найден");
// Ограниченный 10 MiB буфер до начала ответа позволяет честно вернуть 503 при отказе S3.
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
using var output = new LimitedDownloadStream(Math.Min(entity.SizeBytes, 10485760));
try { await storage.CopyToAsync(entity.ObjectKey, output, timeout.Token); }
catch (OperationCanceledException) when (!http.RequestAborted.IsCancellationRequested)
{ return ApiErrors.Error(http, 503, "unavailable", "Истекло время скачивания"); }
catch (IOException) { return ApiErrors.Error(http, 503, "unavailable", "Ошибка чтения объекта"); }
if (output.Length != entity.SizeBytes ||
Convert.ToHexStringLower(SHA256.HashData(output.GetBuffer().AsSpan(0, (int)output.Length))) != entity.ChecksumSha256)
return ApiErrors.Error(http, 503, "unavailable", "Объект не соответствует метаданным");
http.Response.Headers["X-Content-Type-Options"] = "nosniff";
return Results.File(output.ToArray(), entity.ContentType);
}
private static Attachment ToDto(AttachmentEntity a) => new(a.Id, a.ChatId, a.OwnerId, a.Filename,
a.ContentType, a.SizeBytes, a.ChecksumSha256, a.Status, [], null, a.CreatedAt, a.UploadedAt ?? a.CreatedAt);
}