English
Safe uploads
Step 1. What a client sends
Why. An upload arrives at the API as a multipart request with a stream of bytes, a file name, a media type and a length. All four come from the client, so none of them can be trusted: the name may contain ../, the media type may claim image/png for an HTML page, and the length may be a lie. The business layer receives them in one record, without any ASP.NET Core type, so the services stay independent of HTTP and easy to test with a MemoryStream.
Do.
cs
namespace Chatex.Core.Common;
/// <summary>A file sent by a client. <see cref="Length"/> is what the client claims; the content is still capped while reading.</summary>
public sealed record FileUpload(Stream Content, string FileName, string ContentType, long Length);Step 2. A stream that enforces the limit
Why. Checking Length > limit is a good first filter, but the client can send Length = 1000 and then stream a gigabyte. The only reliable limit is to count the bytes while reading and stop once the limit is passed. A decorator does that: a stream that wraps another stream, passes every read through and counts.
Do.
cs
namespace Chatex.Core.Common;
/// <summary>Thrown by <see cref="LimitedReadStream"/> once more than the allowed number of bytes was read.</summary>
internal sealed class FileTooLargeException() : IOException("The file is larger than allowed.");
/// <summary>
/// Read-only wrapper that fails once the inner stream yields more than <paramref name="maxBytes"/>,
/// so a client cannot get past a size limit by lying about the length.
/// </summary>
internal sealed class LimitedReadStream(Stream inner, long maxBytes) : Stream
{
private long _read;
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => _read;
set => throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
public override int Read(Span<byte> buffer) => Count(inner.Read(buffer));
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) =>
Count(await inner.ReadAsync(buffer, cancellationToken));
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
private int Count(int read)
{
_read += read;
return _read > maxBytes ? throw new FileTooLargeException() : read;
}
}LimitedReadStreamderives from the abstractStreamand wrapsinner. Only reading is supported:CanSeekandCanWritearefalse, and the members that do not make sense throwNotSupportedException, as theStreamcontract expects.- All read methods end in
Count: the synchronousRead, theSpanandMemoryoverloads, and the old array-basedReadAsync. Overriding only one of them would leave a path around the limit, becauseCopyToAsyncmay call any of them. Countadds the bytes just read and throwsFileTooLargeExceptiononce the total exceeds the limit. The exception derives fromIOException, the usual type for stream failures; it isinternal, so only Chatex.Core catches it.Positionreturns the number of bytes read so far — after copying, it is the real size of the file, not the claimed one. The attachment service of topic 11 uses exactly that.- The exception class uses a primary constructor that passes the message to the base class:
class FileTooLargeException() : IOException("…").
Step 3. The avatar store
Why. Users and chats (topic 10) both have avatars, with the same rules: JPEG, PNG or WebP, at most 5 MB. A small class keeps those rules in one place, saves the image through IFileStorage (topic 5), and deletes replaced images.
Do.
cs
using Chatex.Data.Abstractions;
namespace Chatex.Core.Common;
/// <summary>Limits for avatar images, public so the Api can cap request bodies to match.</summary>
public static class AvatarLimits
{
public const long MaxBytes = 5 * 1024 * 1024;
}
/// <summary>Validates and stores avatar images for users and chats.</summary>
internal sealed class AvatarStore(IFileStorage storage)
{
public const long MaxBytes = AvatarLimits.MaxBytes;
private static readonly HashSet<string> AllowedContentTypes = new(StringComparer.OrdinalIgnoreCase)
{
"image/jpeg",
"image/png",
"image/webp",
};
public static Error InvalidType { get; } =
Error.Validation("contentType", "avatar_invalid_type", "Avatars must be JPEG, PNG or WebP images.");
public static Error TooLarge { get; } =
Error.Validation("file", "avatar_too_large", $"Avatars must be at most {MaxBytes / (1024 * 1024)} MB.");
/// <summary>Stores the image and returns its storage path.</summary>
public async Task<Result<string>> SaveAsync(FileUpload upload, CancellationToken cancellationToken)
{
if (!AllowedContentTypes.Contains(upload.ContentType))
{
return InvalidType;
}
if (upload.Length > MaxBytes)
{
return TooLarge;
}
try
{
return await storage.SaveAsync(new LimitedReadStream(upload.Content, MaxBytes), cancellationToken);
}
catch (FileTooLargeException)
{
return TooLarge;
}
}
/// <summary>Deletes a replaced avatar. Called after the database no longer points at it.</summary>
public Task DeleteAsync(string? storagePath, CancellationToken cancellationToken) =>
storagePath is null ? Task.CompletedTask : storage.DeleteAsync(storagePath, cancellationToken);
}AvatarLimitsis public, so the API can cap the request body to the same 5 MB before a single byte reaches the service (topic 13).AvatarStoreitself isinternal.- Allowed types are a
HashSet<string>with a case-insensitive comparer:image/PNGis accepted,image/svg+xmlis not. SVG images can contain scripts, so they are deliberately missing. SaveAsyncchecks in order of cost: the claimed type, the claimed length, then the real length while saving, throughLimitedReadStream. A file that turns out too large becomes the sameavatar_too_largeerror as a file that admitted it.DeleteAsyncis called by the services after the database no longer points at the old file. In the opposite order, a failed save would leave a profile with a deleted avatar.
Check
dotnet build succeeds.