mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-16 20:56:03 +00:00
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.
This commit is contained in:
@@ -44,8 +44,15 @@ public class MessageReadController : ControllerBase
|
||||
}
|
||||
|
||||
[HttpGet("unread-count")]
|
||||
public async Task<IActionResult> GetUnreadCount(Guid chatId, [FromQuery] RecipientType recipientType)
|
||||
public async Task<IActionResult> 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 });
|
||||
}
|
||||
|
||||
@@ -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<UserMessageResponse>.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);
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)))
|
||||
|
||||
@@ -11,4 +11,9 @@ public interface IMessageReadingService
|
||||
Task<Result<ChatReadResult, Error>> ReadChatAsync(Guid readerId, Guid chatId,
|
||||
RecipientType type, IReadOnlyCollection<Guid>? messageIds = null, Guid? upToMessageId = null);
|
||||
Task<Result<int, Error>> GetUnreadCountAsync(Guid readerId, Guid chatId, RecipientType type);
|
||||
Task<Result<ChatActivity, Error>> GetChatActivityAsync(Guid readerId, Guid chatId, RecipientType type,
|
||||
bool includeReadPosition = false);
|
||||
}
|
||||
|
||||
public sealed record ChatActivity(int UnreadCount, DateTime? LastMessageAt,
|
||||
Guid? LastReadMessageId = null, Guid? FirstUnreadMessageId = null);
|
||||
|
||||
@@ -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<Result<ChatActivity, Error>> GetChatActivityAsync(Guid readerId, Guid chatId, RecipientType type,
|
||||
bool includeReadPosition = false)
|
||||
{
|
||||
if (!await _dbContext.HasChatAccessAsync(readerId, chatId, type))
|
||||
return Result.Failure<ChatActivity>(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.");
|
||||
}
|
||||
|
||||
@@ -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<SendMessage>()))
|
||||
.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()
|
||||
{
|
||||
|
||||
@@ -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<MessageReadingService>.Instance,
|
||||
Mock.Of<INowDateTimeProvider>(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()
|
||||
{
|
||||
|
||||
@@ -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<ArgumentException>(() => _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<ArgumentException>(() => _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<UnauthorizedAccessException>(() => _e2ee.ValidateAsync(ciphertext,
|
||||
var failure = Assert.ThrowsAsync<UnauthorizedAccessException>(() => _e2ee.ValidateAsync(ciphertext,
|
||||
_db.Alice, _db.ChatId, RecipientType.User, null, []));
|
||||
Assert.That(failure!.Message, Is.EqualTo(E2eeProtocol.SigningDeviceRejectedError));
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
Reference in New Issue
Block a user