From 31d704712c01f50915d5ac112fcc5f070b6c703b Mon Sep 17 00:00:00 2001 From: Artemy <109195690+stalcker2288969@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:26:00 +0700 Subject: [PATCH] Expose chat read positions and E2EE errors Add optional chat activity and read-position details to the unread-count endpoint. Return stable E2EE rejection codes for stale timestamps and untrusted signing devices, with tests for both behaviors. --- .../Controllers/MessageReadController.cs | 9 +++++- Govor.API/Hubs/ChatsHub.cs | 9 ++++++ Govor.Application/E2ee/E2eeProtocol.cs | 2 ++ Govor.Application/E2ee/E2eeService.cs | 9 +++--- .../Messages/IMessageReadingService.cs | 5 ++++ .../Messages/MessageReadingService.cs | 27 ++++++++++++++++++ .../Unit/Hubs/ChatsHubTests.cs | 16 +++++++++++ .../Integration/Messages/ReadBoundaryTests.cs | 28 +++++++++++++++++++ .../Govor.Server.Tests/Security/E2eeTests.cs | 11 ++++++-- 9 files changed, 108 insertions(+), 8 deletions(-) diff --git a/Govor.API/Controllers/MessageReadController.cs b/Govor.API/Controllers/MessageReadController.cs index 301456c..dc4e9c2 100644 --- a/Govor.API/Controllers/MessageReadController.cs +++ b/Govor.API/Controllers/MessageReadController.cs @@ -44,8 +44,15 @@ public class MessageReadController : ControllerBase } [HttpGet("unread-count")] - public async Task GetUnreadCount(Guid chatId, [FromQuery] RecipientType recipientType) + public async Task GetUnreadCount(Guid chatId, [FromQuery] RecipientType recipientType, + [FromQuery] bool includeActivity = false, [FromQuery] bool includeReadPosition = false) { + if (includeActivity) + { + var activity = await _reader.GetChatActivityAsync(_currentUser.GetCurrentUserId(), chatId, recipientType, + includeReadPosition); + return activity.IsFailure ? activity.ToActionResult() : Ok(activity.Value); + } var result = await _reader.GetUnreadCountAsync(_currentUser.GetCurrentUserId(), chatId, recipientType); return result.IsFailure ? result.ToActionResult() : Ok(new { unreadCount = result.Value }); } diff --git a/Govor.API/Hubs/ChatsHub.cs b/Govor.API/Hubs/ChatsHub.cs index 92e319d..88abde5 100644 --- a/Govor.API/Hubs/ChatsHub.cs +++ b/Govor.API/Hubs/ChatsHub.cs @@ -101,7 +101,16 @@ public class ChatsHub : Hub var result = await _messageSendingService.SendMessageAsync(sendParams); if (!result.IsSuccess) + { + if (result.Exception is UnauthorizedAccessException { Message: E2eeProtocol.SigningDeviceRejectedError }) + { + _logger.LogWarning("Message rejected for {UserId}: {Reason}", userId, E2eeProtocol.SigningDeviceRejectedError); + return HubResult.Forbidden(E2eeProtocol.SigningDeviceRejectedError); + } + if (result.Exception is ArgumentException { Message: E2eeProtocol.TimestampOutOfRangeError or E2eeProtocol.DevicesChangedError } rejection) + _logger.LogWarning("Message rejected for {UserId}: {Reason}", userId, rejection.Message); throw result.Exception ?? new InvalidOperationException("Failed to send message"); + } var response = MapToResponse(result.Message, request.ReplyToMessageId); diff --git a/Govor.Application/E2ee/E2eeProtocol.cs b/Govor.Application/E2ee/E2eeProtocol.cs index c36b945..ff84b46 100644 --- a/Govor.Application/E2ee/E2eeProtocol.cs +++ b/Govor.Application/E2ee/E2eeProtocol.cs @@ -55,6 +55,8 @@ public static class E2eeProtocol public const int MaxDevices = 500; public const string EncryptedMimeType = "application/vnd.govor.encrypted"; public const string DevicesChangedError = "E2EE_DEVICES_CHANGED"; + public const string TimestampOutOfRangeError = "E2EE_TIMESTAMP_OUT_OF_RANGE"; + public const string SigningDeviceRejectedError = "E2EE_SIGNING_DEVICE_REJECTED"; public static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true }; public static bool IsEncrypted(string? value) diff --git a/Govor.Application/E2ee/E2eeService.cs b/Govor.Application/E2ee/E2eeService.cs index fb89c04..27d4919 100644 --- a/Govor.Application/E2ee/E2eeService.cs +++ b/Govor.Application/E2ee/E2eeService.cs @@ -224,9 +224,10 @@ public sealed class E2eeService(GovorDbContext context) envelope.RecipientType != (int)type || envelope.ReplyToMessageId != replyTo || envelope.IsEdit != editedMessage.HasValue || (editedMessage.HasValue && envelope.MessageId != editedMessage) || - !envelope.MediaIds.Order().SequenceEqual(media.Order()) || - Math.Abs((double)envelope.CreatedAt - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) > 300_000) - throw new ArgumentException("E2EE routing, attachment or time context does not match."); + !envelope.MediaIds.Order().SequenceEqual(media.Order())) + throw new ArgumentException("E2EE routing or attachment context does not match."); + if (Math.Abs((double)envelope.CreatedAt - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) > 300_000) + throw new ArgumentException(E2eeProtocol.TimestampOutOfRangeError); var signingSession = await context.UserSessions.AsNoTracking().Include(s => s.CryptoSession) .ThenInclude(c => c.SignedPreKey).SingleOrDefaultAsync(s => s.Id == envelope.Sender.SessionId && @@ -235,7 +236,7 @@ public sealed class E2eeService(GovorDbContext context) ToDeviceKey(signingSession.CryptoSession, sender).Fingerprint != envelope.Sender.Fingerprint || signingSession.CryptoSession.AccountIdentityKey != envelope.Sender.AccountIdentityKey || signingSession.CryptoSession.Generation != envelope.Sender.Generation) - throw new UnauthorizedAccessException("E2EE signing device is unknown or revoked."); + throw new UnauthorizedAccessException(E2eeProtocol.SigningDeviceRejectedError); var directory = await GetConversationKeysAsync(sender, conversation, type); var expected = directory.Devices.Select(k => k.Fingerprint).Distinct().Order(StringComparer.Ordinal); if (!expected.SequenceEqual(envelope.Recipients.Order(StringComparer.Ordinal))) diff --git a/Govor.Application/Messages/IMessageReadingService.cs b/Govor.Application/Messages/IMessageReadingService.cs index df2e63d..af8ea07 100644 --- a/Govor.Application/Messages/IMessageReadingService.cs +++ b/Govor.Application/Messages/IMessageReadingService.cs @@ -11,4 +11,9 @@ public interface IMessageReadingService Task> ReadChatAsync(Guid readerId, Guid chatId, RecipientType type, IReadOnlyCollection? messageIds = null, Guid? upToMessageId = null); Task> GetUnreadCountAsync(Guid readerId, Guid chatId, RecipientType type); + Task> GetChatActivityAsync(Guid readerId, Guid chatId, RecipientType type, + bool includeReadPosition = false); } + +public sealed record ChatActivity(int UnreadCount, DateTime? LastMessageAt, + Guid? LastReadMessageId = null, Guid? FirstUnreadMessageId = null); diff --git a/Govor.Application/Messages/MessageReadingService.cs b/Govor.Application/Messages/MessageReadingService.cs index d4ce697..503bba4 100644 --- a/Govor.Application/Messages/MessageReadingService.cs +++ b/Govor.Application/Messages/MessageReadingService.cs @@ -148,6 +148,33 @@ public class MessageReadingService : IMessageReadingService chat.CountAsync(m => m.SenderId != readerId && !_dbContext.MessageViews.Any(v => v.MessageId == m.Id && v.UserId == readerId)); + public async Task> GetChatActivityAsync(Guid readerId, Guid chatId, RecipientType type, + bool includeReadPosition = false) + { + if (!await _dbContext.HasChatAccessAsync(readerId, chatId, type)) + return Result.Failure(Denied()); + + var chat = _dbContext.Messages.AsNoTracking() + .Where(m => m.RecipientId == chatId && m.RecipientType == type); + var activity = await chat.GroupBy(_ => 1).Select(g => new ChatActivity( + g.Count(m => m.SenderId != readerId && + !_dbContext.MessageViews.Any(v => v.MessageId == m.Id && v.UserId == readerId)), + g.Max(m => (DateTime?)m.SentAt))).SingleOrDefaultAsync(); + if (activity is null) return new ChatActivity(0, null); + if (!includeReadPosition) return activity; + + var firstUnread = await chat.Where(m => m.SenderId != readerId && + !_dbContext.MessageViews.Any(v => v.MessageId == m.Id && v.UserId == readerId)) + .OrderBy(m => m.SentAt).ThenBy(m => m.Id) + .Select(m => new { m.Id, m.SentAt }).FirstOrDefaultAsync(); + // Outgoing messages count as read. Do not skip an earlier unread incoming message. + var readHistory = firstUnread is null ? chat : chat.Where(m => m.SentAt < firstUnread.SentAt || + (m.SentAt == firstUnread.SentAt && m.Id.CompareTo(firstUnread.Id) < 0)); + var lastRead = await readHistory.OrderByDescending(m => m.SentAt).ThenByDescending(m => m.Id) + .Select(m => (Guid?)m.Id).FirstOrDefaultAsync(); + return activity with { LastReadMessageId = lastRead, FirstUnreadMessageId = firstUnread?.Id }; + } + private static Error Denied() => Error.Forbidden("Chat.AccessDenied", "You are not a member of this chat."); } diff --git a/tests/Govor.API.Tests/Unit/Hubs/ChatsHubTests.cs b/tests/Govor.API.Tests/Unit/Hubs/ChatsHubTests.cs index 41a0336..6002904 100644 --- a/tests/Govor.API.Tests/Unit/Hubs/ChatsHubTests.cs +++ b/tests/Govor.API.Tests/Unit/Hubs/ChatsHubTests.cs @@ -2,6 +2,7 @@ using AutoMapper; using Govor.API.Common.SignalR.Helpers; using Govor.API.Hubs; using Govor.API.Hubs.Infrastructure; +using Govor.Application.E2ee; using Govor.Application.Exceptions.VerifyFriendship; using Govor.Application.Infrastructure.Common; using Govor.Application.Messages; @@ -106,6 +107,21 @@ public class ChatsHubTests Assert.That((await _hub.Send(new(){EncryptedContent="cipher"})).Status,Is.EqualTo(HubResultStatus.BadRequest)); } + [TestCase(E2eeProtocol.SigningDeviceRejectedError, HubResultStatus.Forbidden)] + [TestCase(E2eeProtocol.TimestampOutOfRangeError, HubResultStatus.BadRequest)] + [TestCase(E2eeProtocol.DevicesChangedError, HubResultStatus.BadRequest)] + public async Task SendReturnsSafeE2eeRejectionCodeWithoutNotifying(string code, HubResultStatus status) + { + Exception error = status == HubResultStatus.Forbidden + ? new UnauthorizedAccessException(code) : new ArgumentException(code); + _send.Setup(x => x.SendMessageAsync(It.IsAny())) + .ReturnsAsync(new SendMessageResult(false, error, null!)); + var response = await _hub.Send(new() { RecipientId = _chat, EncryptedContent = "cipher" }); + Assert.That(response.Status, Is.EqualTo(status)); + Assert.That(response.ErrorMessage, Is.EqualTo(code)); + _notifier.VerifyNoOtherCalls(); + } + [Test] public async Task ReadMapsCurrentReadersViewAndNotifies() { diff --git a/tests/Govor.Application.Tests/Integration/Messages/ReadBoundaryTests.cs b/tests/Govor.Application.Tests/Integration/Messages/ReadBoundaryTests.cs index e171980..476a0e9 100644 --- a/tests/Govor.Application.Tests/Integration/Messages/ReadBoundaryTests.cs +++ b/tests/Govor.Application.Tests/Integration/Messages/ReadBoundaryTests.cs @@ -10,6 +10,34 @@ namespace Govor.Application.Tests.Integration.Messages; [TestFixture] public class ReadBoundaryTests { + [Test] + public async Task ActivityAndReadingPositionIncludeOutgoingWithoutSkippingUnreadIncoming() + { + using var db = new TestDatabase(); + var reader = new MessageReadingService(db.Context, NullLogger.Instance, + Mock.Of(c => c.Now == DateTime.UtcNow.Date)); + var first = db.AddMessage(sender: db.Bob); + var incoming = db.AddMessage(sender: db.Alice); + var last = db.AddMessage(sender: db.Bob); + first.SentAt = DateTime.UtcNow.AddMinutes(-3); + incoming.SentAt = first.SentAt.AddMinutes(1); + last.SentAt = first.SentAt.AddMinutes(2); + await db.Context.SaveChangesAsync(); + + var before = (await reader.GetChatActivityAsync(db.Bob, db.ChatId, RecipientType.User, true)).Value; + Assert.That(before.LastMessageAt, Is.EqualTo(last.SentAt)); + Assert.That(before.UnreadCount, Is.EqualTo(1)); + Assert.That(before.LastReadMessageId, Is.EqualTo(first.Id)); + Assert.That(before.FirstUnreadMessageId, Is.EqualTo(incoming.Id)); + Assert.That((await reader.GetChatActivityAsync(db.Outsider, db.ChatId, RecipientType.User, true)).IsFailure, Is.True); + + await reader.ReadChatAsync(db.Bob, db.ChatId, RecipientType.User, upToMessageId: last.Id); + var after = (await reader.GetChatActivityAsync(db.Bob, db.ChatId, RecipientType.User, true)).Value; + Assert.That(after.UnreadCount, Is.Zero); + Assert.That(after.LastReadMessageId, Is.EqualTo(last.Id)); + Assert.That(after.FirstUnreadMessageId, Is.Null); + Assert.That(await db.Context.MessageViews.Select(v => v.MessageId).SingleAsync(), Is.EqualTo(incoming.Id)); + } [Test] public async Task EmptyChatReturnsZeroAndMissingBoundaryDoesNotCreateReceipts() { diff --git a/tests/Govor.Server.Tests/Security/E2eeTests.cs b/tests/Govor.Server.Tests/Security/E2eeTests.cs index 29fe1ed..1ec3637 100644 --- a/tests/Govor.Server.Tests/Security/E2eeTests.cs +++ b/tests/Govor.Server.Tests/Security/E2eeTests.cs @@ -90,13 +90,17 @@ public class E2eeTests [TestCase("malformed")] [TestCase("routing")] [TestCase("stale")] + [TestCase("future")] public async Task InvalidEnvelopeContextIsReturnedAsValidationFailure(string reason) { var directory = await _e2ee.GetConversationKeysAsync(_db.Alice, _db.ChatId, RecipientType.User); var content = reason == "malformed" ? E2eeProtocol.Prefix + "invalid" : E2eeProtocol.Encrypt(new("secret", []), - _alice, _a, directory, Guid.NewGuid(), createdAt: DateTimeOffset.UtcNow.AddMinutes(reason == "stale" ? -6 : 0).ToUnixTimeMilliseconds()); - Assert.ThrowsAsync(() => _e2ee.ValidateAsync(content, reason == "routing" ? _db.Bob : _db.Alice, + _alice, _a, directory, Guid.NewGuid(), createdAt: DateTimeOffset.UtcNow.AddMinutes(reason switch + { "stale" => -6, "future" => 6, _ => 0 }).ToUnixTimeMilliseconds()); + var failure = Assert.ThrowsAsync(() => _e2ee.ValidateAsync(content, reason == "routing" ? _db.Bob : _db.Alice, _db.ChatId, RecipientType.User, null, [])); + if (reason is "stale" or "future") + Assert.That(failure!.Message, Is.EqualTo(E2eeProtocol.TimestampOutOfRangeError)); } [TestCase(false)] @@ -206,8 +210,9 @@ public class E2eeTests var ciphertext = await Encrypt(); await _db.Context.UserSessions.Where(s => s.Id == _a.SessionId) .ExecuteUpdateAsync(u => u.SetProperty(s => s.IsRevoked, true)); - Assert.ThrowsAsync(() => _e2ee.ValidateAsync(ciphertext, + var failure = Assert.ThrowsAsync(() => _e2ee.ValidateAsync(ciphertext, _db.Alice, _db.ChatId, RecipientType.User, null, [])); + Assert.That(failure!.Message, Is.EqualTo(E2eeProtocol.SigningDeviceRejectedError)); } [Test]