English
Attachments
Step 1. Limits, errors and the download record
Why. Topic 3 decided that files are uploaded before the message is sent and linked when it is sent. The attachment service needs settings (the size limit and the allowed media types), its errors, and a record that tells the API how to serve a download.
Do. Complete AttachmentDtos.cs from topic 10 (new lines in green):
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);
}AttachmentDownloadcarries the storage path, the name, the type and the size. The API either streams the file throughOpenReadAsyncor, in production, could let Nginx send it directly (X-Accel-Redirect), which is why the path is part of it.AttachmentOptionsis the second options class: bound from theAttachmentssection, validated with data annotations. The default limit is 20 MB.- The allow-list of media types is the important security decision: everything that is not listed is refused. HTML, JavaScript and SVG are missing on purpose. A file served back from our own domain with such a type could run scripts in the context of Chatex — a stored cross-site scripting attack.
Step 2. The service
Do.
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;
}
}Uploading
- The media type is normalised before the check:
text/plain; charset=utf-8becomestext/plain. - The size is checked twice, as for avatars: the claimed length first, the real length while saving through
LimitedReadStream. - An empty file is refused after saving, using
content.Position— the number of bytes really read — and the empty file is deleted. - The stored size is the real size,
content.Position, not the length the client claimed. - The file name is cleaned: only the last segment of a path survives (
C:\fakepath\..\notes.txt→notes.txt; old browsers send such paths), control characters are removed, and the name is cut to 255 characters. It is stored for display only; it is never used as a path. - If saving the database row fails, the file is deleted again — with
CancellationToken.None, so a cancelled request still cleans up — and the exception is rethrown.
Downloading
The uploader may always download their own file. Anybody else may download it only once it is attached to a message, and only if they may see that message's chat (ChatAccess.GetVisibleAsync from topic 10). Everything else is attachment_not_found — the same as a file that does not exist, so ids of other people's files cannot be probed.
Cleaning up
CleanupStaleAsync deletes uploads that were never sent and are older than the given age, in batches of 500. The database rows are deleted first, then the files: a crash in between leaves a file without a row (harmless) rather than a row without a file (a broken download). The hourly maintenance job of topic 13 calls it with 24 hours.
Check
dotnet build succeeds. The service is registered together with the message service in the next chapter.