Harden media uploads and message attachments

Enforce upload limits and safer media metadata, validate attachment ownership and encrypted-message references, and make message attachment binding idempotent. Add gallery media round-trip coverage and a regression test for closing older sessions.
This commit is contained in:
Artemy
2026-10-24 17:29:22 +07:00
parent a049a80e04
commit 55cc9538f7
6 changed files with 177 additions and 17 deletions
+39 -14
View File
@@ -33,6 +33,7 @@ public class MediaController : Controller
[HttpPost("upload")]
[RequestSizeLimit(20_000_000)] // ~20MB
[RequestFormLimits(MultipartBodyLengthLimit = 20_000_000)]
public async Task<IActionResult> Upload([FromForm] MediaUploadRequest request)
{
if (!ModelState.IsValid)
@@ -47,7 +48,8 @@ public class MediaController : Controller
if (request.FromFile.Length > 20_000_000)
return BadRequest("File is too large");
if (string.IsNullOrWhiteSpace(request.MimeType))
if (string.IsNullOrWhiteSpace(request.MimeType) || request.MimeType.Length > 128 ||
!Enum.IsDefined(request.Type))
return BadRequest("Missing MIME type");
if (request.OwnerType == MediaOwnerType.Message &&
@@ -57,13 +59,17 @@ public class MediaController : Controller
try
{
byte[] fileBytes = await ReadFileAsync(request.FromFile);
var media = new Media(
_currentUserService.GetCurrentUserId(),
DateTime.UtcNow,
Path.GetFileName(request.FromFile.FileName),
request.OwnerType == MediaOwnerType.Message
? Guid.NewGuid().ToString("N") + ".bin"
: Path.GetFileName(request.FromFile.FileName),
fileBytes,
request.Type,
request.OwnerType == MediaOwnerType.Message
? Govor.Domain.Models.Messages.MediaType.File
: request.Type,
request.MimeType,
request.EncryptedKey ?? string.Empty,
request.OwnerType,
@@ -71,23 +77,23 @@ public class MediaController : Controller
{
OwnerType = request.OwnerType,
OwnerId = request.OwnerType == MediaOwnerType.Avatar
? _currentUserService.GetCurrentUserId()
: null,
? _currentUserService.GetCurrentUserId()
: null,
};
var result = await _mediaService.UploadMediaAsync(media);
_logger.LogInformation("Uploaded file {FileName} from user {UserId}",
media.FileName, media.UploaderId);
if (result.IsFailure)
{
_logger.LogWarning("Uploaded file {FileName} from user {UserId} finished with error: {Error}",
media.FileName,
media.UploaderId,
media.FileName,
media.UploaderId,
result.Error);
}
return result.ToActionResult();
}
catch (UnauthorizedAccessException ex)
@@ -95,6 +101,10 @@ public class MediaController : Controller
_logger.LogWarning(ex, ex.Message);
return Forbid();
}
catch (InvalidDataException)
{
return BadRequest("Invalid file or file is too large.");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error uploading media");
@@ -105,7 +115,16 @@ public class MediaController : Controller
private async Task<byte[]> ReadFileAsync(IFormFile file)
{
await using var ms = new MemoryStream();
await file.CopyToAsync(ms);
await using var source = file.OpenReadStream();
var buffer = new byte[81920];
int read;
while ((read = await source.ReadAsync(buffer)) != 0)
{
if (ms.Length + read > 20_000_000) throw new InvalidDataException();
await ms.WriteAsync(buffer.AsMemory(0, read));
}
if (ms.Length == 0 || ms.Length != file.Length) throw new InvalidDataException();
return ms.ToArray();
}
@@ -119,11 +138,17 @@ public class MediaController : Controller
return Forbid();
var mediaResult = await _mediaService.GetMediaByIdAsync(id);
if (mediaResult.IsFailure)
return mediaResult.ToActionResult();
var media = mediaResult.Value;
if (HttpContext is not null)
{
Response.Headers.CacheControl = "no-store";
Response.Headers["X-Content-Type-Options"] = "nosniff";
}
return File(media.Data, media.MimeType, Path.GetFileName(media.FileName));
}
}
}
+16
View File
@@ -1,5 +1,7 @@
using Govor.Application.Storage;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Govor.Application.E2ee;
using Govor.Domain;
using Govor.Domain.Common;
using Microsoft.EntityFrameworkCore;
@@ -169,6 +171,20 @@ public class MediaService : IMediaService
);
}
var message = await _dbContext.Messages.FirstOrDefaultAsync(m => m.Id == messageId);
if (message is null)
return Result<Unit, Error>.Failure(Error.NotFound("File.AttachToMessage", "Message not found."));
if (message.SenderId != mediaFile.UploaderId)
return Result<Unit, Error>.Failure(Error.Forbidden("File.AttachToMessage", "Only the message author's uploads can be attached."));
if (E2eeProtocol.IsEncrypted(message.EncryptedContent) &&
(mediaFile.MineType != E2eeProtocol.EncryptedMimeType ||
!E2eeProtocol.Inspect(message.EncryptedContent).MediaIds.Contains(mediaId)))
return Result<Unit, Error>.Failure(Error.Validation("File.AttachToMessage", "Attachment is not authenticated by the encrypted message."));
if (!await _dbContext.MediaAttachments.AnyAsync(a => a.MediaFileId == mediaId && a.MessageId == messageId))
_dbContext.MediaAttachments.Add(new MediaAttachments
{ Id = Guid.NewGuid(), MediaFileId = mediaId, MessageId = messageId });
mediaFile.OwnerType = MediaOwnerType.Message;
mediaFile.OwnerId = messageId;
@@ -48,7 +48,8 @@ public class MessageSendingService : IMessageSendingService
{
var media = sendParams.Media?.ToArray() ?? [];
if ((string.IsNullOrWhiteSpace(sendParams.EncryptContent) && media.Length == 0) ||
(sendParams.EncryptContent?.Length ?? 0) > E2eeProtocol.MaxEnvelopeLength || media.Length > 100)
(sendParams.EncryptContent?.Length ?? 0) > E2eeProtocol.MaxEnvelopeLength || media.Length > 100 ||
media.Any(m => m.MediaId == Guid.Empty) || media.Select(m => m.MediaId).Distinct().Count() != media.Length)
return new SendMessageResult(false, new ArgumentException("Invalid message content or attachment count."), default);
var validationResult = sendParams.RecipientType switch
@@ -67,7 +68,11 @@ public class MessageSendingService : IMessageSendingService
var completed = await _dbContext.Messages.AsNoTracking().Include(m => m.MediaAttachments)
.ThenInclude(m => m.MediaFile).FirstOrDefaultAsync(m => m.Id == operationId);
if (completed is not null)
return completed.SenderId == sendParams.FromUserId && completed.EncryptedContent == sendParams.EncryptContent
return completed.SenderId == sendParams.FromUserId && completed.EncryptedContent == sendParams.EncryptContent &&
completed.RecipientId == sendParams.RecipientId && completed.RecipientType == sendParams.RecipientType &&
completed.ReplyToMessageId == sendParams.ReplyToMessageId &&
completed.MediaAttachments.Select(a => a.MediaFileId).Order().SequenceEqual(media.Select(a => a.MediaId).Order()) &&
(!E2eeProtocol.IsEncrypted(sendParams.EncryptContent) || media.All(m => string.IsNullOrEmpty(m.EncryptedKey)))
? new SendMessageResult(true, null, completed)
: new SendMessageResult(false, new ArgumentException("Message ID already exists."), default);
@@ -11,7 +11,7 @@ public class MediaUploadRequest
public IFormFile FromFile { get; set; }
[Required]
public MediaType Type { get; set; }
[Required, MaxLength(255)]
[Required, MaxLength(128)]
public string MimeType { get; set; } = string.Empty;
public string? EncryptedKey { get; set; } = string.Empty;
[Required]
@@ -104,7 +104,19 @@ public class MediaServiceTests
Assert.That((await _service.AttachToMessageAsync(avatar.MediaId, message.Id)).IsFailure, Is.True);
_db.Context.ChangeTracker.Clear();
Assert.That((await _db.Context.MediaFiles.SingleAsync(m => m.Id == messageMedia.MediaId)).OwnerId, Is.EqualTo(message.Id));
Assert.That(await _db.Context.MediaAttachments.CountAsync(a => a.MediaFileId == messageMedia.MediaId && a.MessageId == message.Id), Is.EqualTo(1));
Assert.That((await _service.AttachToMessageAsync(messageMedia.MediaId, message.Id)).IsSuccess, Is.True);
Assert.That(await _db.Context.MediaAttachments.CountAsync(a => a.MediaFileId == messageMedia.MediaId), Is.EqualTo(1));
Assert.That((await _db.Context.MediaFiles.SingleAsync(m => m.Id == avatar.MediaId)).OwnerType, Is.EqualTo(MediaOwnerType.Avatar));
}
[Test]
public async Task AttachmentCannotBeBoundToAnotherAuthorsMessage()
{
var uploaded = (await Upload()).Value;
var message = _db.AddMessage(sender: _db.Bob);
Assert.That((await _service.AttachToMessageAsync(uploaded.MediaId, message.Id)).IsFailure, Is.True);
Assert.That(await _db.Context.MediaAttachments.CountAsync(), Is.Zero);
}
}
@@ -0,0 +1,102 @@
using System.Net;
using System.Net.Http.Json;
using System.Security.Claims;
using Govor.API.Hubs;
using Govor.Application.E2ee;
using Govor.Application.Medias;
using Govor.Contracts.Requests.SignalR;
using Govor.Contracts.Responses;
using Govor.Contracts.Responses.SignalR;
using Govor.Domain.Models.Messages;
using Govor.Domain.Models.Users;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Moq;
namespace Govor.Server.Tests;
public partial class ReadApiTests
{
[TestCase(false)]
[TestCase(true)]
public async Task GalleryAttachmentUploadHubHistoryDownloadAndDeletionRoundTrip(bool mediaOnly)
{
Authorize();
var bob = E2eeProtocol.GenerateKeys();
var alice = E2eeProtocol.GenerateKeys();
var e2ee = new E2eeService(_db.Context);
var own = E2eeProtocol.PublicKey(bob, _db.Bob, _session);
await e2ee.RegisterAsync(_db.Bob, _session, own);
var aliceSession = new UserSession { UserId = _db.Alice, RefreshTokenHash = Guid.NewGuid().ToString(), ExpiresAt = DateTime.UtcNow.AddDays(1) };
_db.Context.UserSessions.Add(aliceSession);
await _db.Context.SaveChangesAsync();
await e2ee.RegisterAsync(_db.Alice, aliceSession.Id, E2eeProtocol.PublicKey(alice, _db.Alice, aliceSession.Id));
var original = "gallery photo bytes"u8.ToArray();
var (encrypted, key) = E2eeProtocol.EncryptAttachment(original);
using var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(encrypted), "FromFile", "private-location.jpg");
form.Add(new StringContent("0"), "Type");
form.Add(new StringContent("0"), "OwnerType");
form.Add(new StringContent(E2eeProtocol.EncryptedMimeType), "MimeType");
var uploaded = await _client.PostAsync("/api/media/upload", form);
Assert.That(uploaded.StatusCode, Is.EqualTo(HttpStatusCode.OK), await uploaded.Content.ReadAsStringAsync());
var file = (await uploaded.Content.ReadFromJsonAsync<MediaUploadResult>())!;
Assert.That(file.Url, Does.Not.Contain("private-location"));
Assert.That((await _client.GetAsync($"/api/media/download/{file.MediaId}")).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
var id = Guid.NewGuid();
var caption = mediaOnly ? "" : "Подпись к фото";
var envelope = E2eeProtocol.Encrypt(new(caption, [new(file.MediaId, key, "photo.jpg", "image/jpeg")]), bob, own,
await e2ee.GetConversationKeysAsync(_db.Bob, _db.ChatId, RecipientType.User), id);
using var scope = _factory.Services.CreateScope();
using var hub = ActivatorUtilities.CreateInstance<ChatsHub>(scope.ServiceProvider);
var caller = new Mock<HubCallerContext>();
caller.SetupGet(c => c.User).Returns(new ClaimsPrincipal(new ClaimsIdentity([
new Claim("userId", _db.Bob.ToString()), new Claim("sid", _session.ToString())])));
hub.Context = caller.Object;
var request = new MessageRequest { RecipientId = _db.ChatId, RecipientType = RecipientType.User,
EncryptedContent = envelope, MediaAttachments = [new() { MediaId = file.MediaId }] };
var sent = await hub.Send(request);
Assert.That(sent.Status, Is.EqualTo(HubResultStatus.Success), sent.ErrorMessage);
Assert.That(sent.Result!.MediaAttachments.Select(a => a.Id), Is.EqualTo(new[] { file.MediaId }));
Assert.That((await hub.Send(request)).Status, Is.EqualTo(HubResultStatus.Success));
Assert.That(await _db.Context.MediaAttachments.CountAsync(a => a.MessageId == id), Is.EqualTo(1));
var tampered = await hub.Send(request with { MediaAttachments = [] });
Assert.That(tampered.Status, Is.EqualTo(HubResultStatus.BadRequest));
var history = await _client.GetFromJsonAsync<List<MessageResponse>>($"/api/user/{_db.ChatId}/messages?Before=20&After=0");
Assert.That(history!.Single().MediaAttachments.Single().MediaFileId, Is.EqualTo(file.MediaId));
var plaintext = E2eeProtocol.Decrypt(history!.Single().EncryptedContent, alice, id, _db.ChatId, 0, _db.Bob);
Assert.That(plaintext.Text, Is.EqualTo(caption));
Assert.That(plaintext.Attachments.Single().Key, Is.EqualTo(key));
var download = await _client.GetAsync($"/api/media/download/{file.MediaId}");
Assert.That(download.StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That(download.Headers.CacheControl!.NoStore, Is.True);
Assert.That(E2eeProtocol.DecryptAttachment(await download.Content.ReadAsByteArrayAsync(), key), Is.EqualTo(original));
Authorize(userId: _db.Outsider);
Assert.That((await _client.GetAsync($"/api/media/download/{file.MediaId}")).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Authorize();
var removed = await hub.Remove(new() { MessageId = id, RequestType = RemoveMessageRequestType.ForceRemove });
Assert.That(removed.Status, Is.EqualTo(HubResultStatus.Success), removed.ErrorMessage);
Assert.That((await _client.GetAsync($"/api/media/download/{file.MediaId}")).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Assert.That(await _db.Context.MediaAttachments.CountAsync(a => a.MessageId == id), Is.Zero);
}
[Test]
public async Task ClosingAnOlderSessionOnTheSameDeviceKeepsCurrentSessionAuthenticated()
{
var current = await _db.Context.UserSessions.SingleAsync(s => s.Id == _session);
current.DeviceInfo = "Same phone on Android 16";
var older = new UserSession { UserId = _db.Bob, DeviceInfo = current.DeviceInfo,
RefreshTokenHash = Guid.NewGuid().ToString(), ExpiresAt = DateTime.UtcNow.AddDays(1) };
_db.Context.UserSessions.Add(older);
await _db.Context.SaveChangesAsync();
Authorize();
Assert.That((await _client.DeleteAsync($"/api/session/close/{older.Id}")).IsSuccessStatusCode, Is.True);
Assert.That((await _client.GetAsync("/api/session/all")).StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That((await _db.Context.UserSessions.AsNoTracking().SingleAsync(s => s.Id == _session)).IsRevoked, Is.False);
Assert.That((await _db.Context.UserSessions.AsNoTracking().SingleAsync(s => s.Id == older.Id)).IsRevoked, Is.True);
}
}