Українська
Вкладення
Крок 1. Обмеження, помилки та запис отримання
Навіщо. У темі 3 вирішено, що файли завантажують перед надсиланням повідомлення, а прив’язують під час надсилання. Сервісу вкладень потрібні налаштування (обмеження розміру й дозволені типи носіїв), власні помилки та запис, який підказує API, як віддати файл для отримання.
Що зробити. Завершіть AttachmentDtos.cs із теми 10 (нові рядки зеленим):
cs
using System.ComponentModel.DataAnnotations;
using Chatex.Core.Common;
using Chatex.Data.Entities;
namespace Chatex.Core.Attachments;
public sealed record AttachmentDto(Guid Id, string FileName, string ContentType, long SizeBytes);
/// <summary>
/// What the Api needs to serve a file: <see cref="StoragePath"/> for an Nginx X-Accel-Redirect in production,
/// or <c>IAttachmentService.OpenReadAsync</c> to stream it directly.
/// </summary>
public sealed record AttachmentDownload(string StoragePath, string FileName, string ContentType, long SizeBytes);
/// <summary>Upload limits, bound from the <c>Attachments</c> configuration section.</summary>
public sealed class AttachmentOptions
{
public const string Section = "Attachments";
[Range(1, 1024L * 1024 * 1024)]
public long MaxBytes { get; set; } = 20 * 1024 * 1024;
/// <summary>Media types that can be uploaded. Anything else is rejected, so no HTML or scripts are served back.</summary>
[MinLength(1)]
public string[] AllowedContentTypes { get; set; } =
[
"image/jpeg", "image/png", "image/gif", "image/webp",
"application/pdf", "text/plain", "application/zip",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"audio/mpeg", "audio/ogg", "video/mp4",
];
}
public static class AttachmentErrors
{
public static Error NotFound { get; } = Error.NotFound("attachment_not_found", "The file does not exist.");
public static Error InvalidType { get; } =
Error.Validation("contentType", "attachment_invalid_type", "This file type cannot be uploaded.");
public static Error TooLarge { get; } = Error.Validation("file", "attachment_too_large", "The file is too large.");
public static Error Empty { get; } = Error.Validation("file", "attachment_empty", "The file is empty.");
}
internal static class AttachmentMappings
{
public static AttachmentDto ToDto(this Attachment attachment) =>
new(attachment.Id, attachment.FileName, attachment.ContentType, attachment.SizeBytes);
}AttachmentDownloadнесе шлях у сховищі, ім’я, тип і розмір. API або передає файл потоком черезOpenReadAsync, або в робочому середовищі може доручити Nginx надіслати його напряму (X-Accel-Redirect) – тому шлях є частиною запису.AttachmentOptions– другий клас параметрів: зв’язаний із розділомAttachments, перевіряється анотаціями даних. Типове обмеження – 20 МБ.- Список дозволених типів носіїв – важливе рішення безпеки: усе, чого немає в списку, відхиляється. HTML, JavaScript і SVG відсутні навмисно. Файл, який віддають із нашого власного домену з таким типом, міг би виконувати скрипти в контексті Chatex – це збережена міжсайтова атака зі скриптами (stored XSS).
Крок 2. Сервіс
Що зробити.
cs
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using Microsoft.Extensions.Options;
namespace Chatex.Core.Attachments;
public interface IAttachmentService
{
/// <summary>Stores a file for a message the caller is about to send; pass its id in <c>SendMessageCommand.AttachmentIds</c>.</summary>
Task<Result<AttachmentDto>> UploadAsync(Guid userId, FileUpload upload, CancellationToken cancellationToken = default);
/// <summary>Allowed for the uploader and for anyone who can see the chat the file was sent to.</summary>
Task<Result<AttachmentDownload>> GetDownloadAsync(Guid userId, Guid attachmentId, CancellationToken cancellationToken = default);
Task<Stream> OpenReadAsync(AttachmentDownload download, CancellationToken cancellationToken = default);
/// <summary>Deletes uploads that were never sent within <paramref name="olderThan"/>; returns how many.</summary>
Task<int> CleanupStaleAsync(TimeSpan olderThan, CancellationToken cancellationToken = default);
}
internal sealed class AttachmentService(
IAttachmentRepository attachments,
IUnitOfWork unitOfWork,
IFileStorage storage,
ChatAccess chatAccess,
IOptions<AttachmentOptions> options,
TimeProvider timeProvider) : IAttachmentService
{
private const int MaxFileNameLength = 255;
private const int CleanupBatchSize = 500;
public async Task<Result<AttachmentDto>> UploadAsync(Guid userId, FileUpload upload, CancellationToken cancellationToken = default)
{
var limits = options.Value;
var contentType = upload.ContentType.Split(';')[0].Trim().ToLowerInvariant();
if (!limits.AllowedContentTypes.Contains(contentType, StringComparer.OrdinalIgnoreCase))
{
return AttachmentErrors.InvalidType;
}
if (upload.Length > limits.MaxBytes)
{
return AttachmentErrors.TooLarge;
}
var content = new LimitedReadStream(upload.Content, limits.MaxBytes);
string storagePath;
try
{
storagePath = await storage.SaveAsync(content, cancellationToken);
}
catch (FileTooLargeException)
{
return AttachmentErrors.TooLarge;
}
if (content.Position == 0)
{
await storage.DeleteAsync(storagePath, cancellationToken);
return AttachmentErrors.Empty;
}
var attachment = new Attachment
{
UploaderId = userId,
FileName = CleanFileName(upload.FileName),
ContentType = contentType,
SizeBytes = content.Position,
StoragePath = storagePath,
};
attachments.Add(attachment);
try
{
await unitOfWork.SaveChangesAsync(cancellationToken);
}
catch
{
await storage.DeleteAsync(storagePath, CancellationToken.None);
throw;
}
return attachment.ToDto();
}
public async Task<Result<AttachmentDownload>> GetDownloadAsync(
Guid userId, Guid attachmentId, CancellationToken cancellationToken = default)
{
var attachment = await attachments.GetByIdAsync(attachmentId, cancellationToken);
if (attachment is null)
{
return AttachmentErrors.NotFound;
}
if (attachment.UploaderId != userId)
{
if (attachment.Message is null
|| !(await chatAccess.GetVisibleAsync(userId, attachment.Message.ChatId, cancellationToken)).IsSuccess)
{
return AttachmentErrors.NotFound;
}
}
return new AttachmentDownload(attachment.StoragePath, attachment.FileName, attachment.ContentType, attachment.SizeBytes);
}
public Task<Stream> OpenReadAsync(AttachmentDownload download, CancellationToken cancellationToken = default) =>
storage.OpenReadAsync(download.StoragePath, cancellationToken);
public async Task<int> CleanupStaleAsync(TimeSpan olderThan, CancellationToken cancellationToken = default)
{
var stale = await attachments.GetStalePendingAsync(timeProvider.GetUtcNow() - olderThan, CleanupBatchSize, cancellationToken);
if (stale.Count == 0)
{
return 0;
}
foreach (var attachment in stale)
{
attachments.Remove(attachment);
}
await unitOfWork.SaveChangesAsync(cancellationToken);
foreach (var attachment in stale)
{
await storage.DeleteAsync(attachment.StoragePath, cancellationToken);
}
return stale.Count;
}
/// <summary>Keeps only the last path segment of a client file name, without control characters.</summary>
private static string CleanFileName(string? fileName)
{
var name = fileName ?? "";
name = name[(name.LastIndexOfAny(['/', '\\']) + 1)..];
name = new string(name.Where(c => !char.IsControl(c)).ToArray()).Trim();
if (name.Length == 0)
{
return "file";
}
return name.Length > MaxFileNameLength ? name[..MaxFileNameLength] : name;
}
}Завантаження
- Тип носія нормалізують перед перевіркою:
text/plain; charset=utf-8стаєtext/plain. - Розмір перевіряють двічі, як і для аватарів: спершу заявлену довжину, потім справжню під час збереження через
LimitedReadStream. - Порожній файл відхиляється після збереження за
content.Position– кількістю байтів, що справді прочитано, – і порожній файл видаляють. - Збережений розмір – справжній розмір,
content.Position, а не довжина, яку заявив клієнт. - Ім’я файлу очищають: від шляху лишається тільки останній сегмент (
C:\fakepath\..\notes.txt→notes.txt; старі браузери надсилають такі шляхи), керівні символи вилучають, а ім’я обрізають до 255 символів. Його зберігають лише для показу; як шлях його ніколи не використовують. - Якщо збереження рядка в базі даних не вдалося, файл знову видаляють – з
CancellationToken.None, щоб скасований запит усе одно прибрав за собою, – а виняток передають далі.
Отримання
Той, хто завантажив файл, завжди може його отримати. Будь-хто інший може отримати його лише тоді, коли його прикріплено до повідомлення, і лише якщо він може бачити чат цього повідомлення (ChatAccess.GetVisibleAsync із теми 10). Усе інше – attachment_not_found, так само як для файлу, якого не існує, тож ідентифікатори чужих файлів не можна вгадувати.
Очищення
CleanupStaleAsync видаляє завантаження, які ніколи не надсилали й які старші за заданий вік, пакетами по 500. Спершу видаляють рядки бази даних, потім файли: збій посередині лишає файл без рядка (нешкідливо), а не рядок без файлу (зламане отримання). Щогодинне завдання обслуговування з теми 13 викликає його з 24 годинами.
Перевірка
dotnet build завершується успішно. Сервіс буде зареєстровано разом із сервісом повідомлень у наступному розділі.