Add forwarding, friend controls, and benefits

Add message forwarding and reply lookup, friend removal and blocking endpoints, and database-backed Govor+ privileges with customizable profile tags. Include migrations, integration tests, and updated API and operations documentation.
This commit is contained in:
Artemy
2026-10-31 18:29:40 +07:00
parent a3401ceedf
commit 632ac04b56
78 changed files with 5284 additions and 720 deletions
@@ -0,0 +1,34 @@
using Govor.API.Controllers;
using Govor.API.Hubs;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Profiles;
using Govor.Contracts.Requests;
using Govor.Domain.Models.Users;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
namespace Govor.API.Tests.Integration.Controllers;
[TestFixture]
public sealed class UserBenefitsControllerTests
{
[Test]
public async Task BroadcastFailureKeepsCommittedGrantSuccessfulAndReadable()
{
using var db = new TestDatabase();
var proxy = new Mock<IClientProxy>();
proxy.Setup(x => x.SendCoreAsync("UserBenefitsUpdated", It.IsAny<object[]>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new IOException("SignalR unavailable"));
var hub = new Mock<IHubContext<ProfileHub>>();
hub.Setup(x => x.Clients.All).Returns(proxy.Object);
var benefits = new UserBenefitsService(db.Context);
var controller = new UserBenefitsController(benefits, Mock.Of<ICurrentUserService>(), hub.Object,
NullLogger<UserBenefitsController>.Instance);
var result = await controller.SetPrivileges(db.Alice, new SetPrivilegesRequest(UserPrivileges.GovorPlus));
Assert.That(result, Is.TypeOf<OkObjectResult>());
Assert.That((await benefits.GetAsync(db.Alice)).IsGovorPlus, Is.True);
proxy.Verify(x => x.SendCoreAsync("UserBenefitsUpdated", It.IsAny<object[]>(), It.IsAny<CancellationToken>()), Times.Once);
}
}
@@ -0,0 +1,31 @@
using Govor.Application.Friends;
using Govor.Domain.Models;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Tests.Integration.Friends;
[TestFixture]
public sealed class FriendRemovalTests
{
[TestCase(FriendshipStatus.Pending)]
[TestCase(FriendshipStatus.Blocked)]
[TestCase(FriendshipStatus.Rejected)]
[TestCase(FriendshipStatus.Accepted)]
public async Task RemovalChangesOnlyAcceptedFriendshipAndRetainsHistory(FriendshipStatus status)
{
using var db = new TestDatabase();
db.Context.Friendships.Add(new Friendship { Id = Guid.NewGuid(), RequesterId = db.Alice, AddresseeId = db.Bob, Status = status });
await db.Context.SaveChangesAsync();
var message = db.AddMessage();
var service = new FriendshipService(db.Context);
await service.RemoveFriendAsync(db.Bob, db.Alice);
await service.RemoveFriendAsync(db.Alice, db.Bob);
Assert.That((await db.Context.Friendships.AsNoTracking().SingleAsync()).Status,
Is.EqualTo(status == FriendshipStatus.Accepted ? FriendshipStatus.Rejected : status));
Assert.That(await db.Context.Messages.AnyAsync(m => m.Id == message.Id), Is.True);
Assert.That(await db.Context.PrivateChats.AnyAsync(c => c.Id == db.ChatId), Is.True);
Assert.ThrowsAsync<ArgumentException>(() => service.RemoveFriendAsync(db.Alice, db.Alice));
Assert.ThrowsAsync<ArgumentException>(() => service.RemoveFriendAsync(Guid.Empty, db.Alice));
Assert.ThrowsAsync<ArgumentException>(() => service.RemoveFriendAsync(db.Alice, Guid.Empty));
}
}
@@ -0,0 +1,74 @@
using Govor.Application.Messages;
using Govor.Application.Messages.Parameters;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
namespace Govor.Application.Tests.Integration.Messages;
[TestFixture]
public sealed class ReplyAndForwardTests
{
private TestDatabase _db = null!;
private Guid _group;
private MessageSendingService _sender = null!;
[SetUp]
public void SetUp()
{
_db = new(); _group = Guid.NewGuid();
_db.Context.ChatGroups.Add(new ChatGroup { Id = _group, Name = "public", Description = "", OwnerUserId = _db.Alice });
_db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = _group, UserId = _db.Alice });
_db.Context.SaveChanges();
_sender = new(_db.Context, NullLogger<MessageSendingService>.Instance);
}
[TearDown] public void TearDown() => _db.Dispose();
private SendMessage Request(Guid? reply = null, Guid? forward = null) =>
new("content", reply, _group, RecipientType.Group, _db.Alice, DateTime.UtcNow, [], forward);
[Test]
public async Task ReplyPersistsAndAppearsInHistoryWhileCrossChatReplyIsRejected()
{
var source = _db.AddMessage(chat: _group, type: RecipientType.Group);
var reply = await _sender.SendMessageAsync(Request(reply: source.Id));
Assert.That(reply.IsSuccess, Is.True);
var history = await new MessagesLoader(_db.Context).LoadMessagesInChatGroup(_group, _db.Alice, null);
Assert.That(history.Value.Single(m => m.Id == reply.Message.Id).ReplyToMessageId, Is.EqualTo(source.Id));
var other = _db.AddMessage();
Assert.That((await _sender.SendMessageAsync(Request(reply: other.Id))).IsSuccess, Is.False);
Assert.That((await _sender.SendMessageAsync(Request(reply: Guid.Empty))).IsSuccess, Is.False);
}
[Test]
public async Task ForwardSnapshotsAuthorAndDateSurvivesSourceDeletionAndAppearsInHistory()
{
var source = _db.AddMessage(sender: _db.Bob);
var result = await _sender.SendMessageAsync(Request(forward: source.Id));
Assert.That(result.IsSuccess, Is.True);
Assert.That(result.Message.SenderId, Is.EqualTo(_db.Alice));
Assert.That(result.Message.ForwardedFromUserId, Is.EqualTo(_db.Bob));
Assert.That(result.Message.ForwardedFromSentAt, Is.EqualTo(source.SentAt));
await _db.Context.Messages.Where(m => m.Id == source.Id).ExecuteDeleteAsync();
var history = await new MessagesLoader(_db.Context).LoadMessagesInChatGroup(_group, _db.Alice, null);
Assert.That(history.Value.Single().ForwardedFromMessageId, Is.EqualTo(source.Id));
Assert.That(await _db.Context.ChatPushNotifications.AnyAsync(p => p.MessageId == result.Message.Id), Is.True);
}
[TestCase("missing")]
[TestCase("outsider")]
[TestCase("banned")]
public async Task CannotForwardMissingOrInaccessibleSource(string reason)
{
var otherGroup = Guid.NewGuid();
_db.Context.ChatGroups.Add(new ChatGroup { Id = otherGroup, Name = "other", Description = "", OwnerUserId = _db.Bob });
if (reason == "banned")
_db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = otherGroup, UserId = _db.Alice, IsBanned = true });
_db.Context.SaveChanges();
var id = reason == "missing" ? Guid.NewGuid() : _db.AddMessage(chat: otherGroup, type: RecipientType.Group).Id;
var before = await _db.Context.Messages.CountAsync();
var result = await _sender.SendMessageAsync(Request(forward: id));
Assert.That(result.IsSuccess, Is.False);
Assert.That(await _db.Context.Messages.CountAsync(), Is.EqualTo(before));
Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.Zero);
}
}
@@ -0,0 +1,128 @@
using Govor.Application.Profiles;
using Govor.Application.Tests.Support;
using Govor.Domain.Models.Users;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Govor.Application.Tests.Integration.Profiles;
[TestFixture]
public sealed class UserBenefitsTests
{
private TestDatabase _db = null!;
private UserBenefitsService _service = null!;
[SetUp] public void SetUp() { _db = new(); _service = new(_db.Context); }
[TearDown] public void TearDown() => _db.Dispose();
[Test]
public async Task GrantCustomizeRevokeAndRegrantUseLiveDatabaseRights()
{
Assert.That((await _service.GetAsync(_db.Alice)).Tag, Is.Null);
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.SetTagAsync(_db.Alice, new()));
var granted = await _service.SetPrivilegesAsync(_db.Alice, UserPrivileges.GovorPlus);
Assert.That(granted.IsGovorPlus, Is.True);
Assert.That(granted.Tag!.Text, Is.EqualTo("Govor+"));
var style = new ProfileTagStyle { Text = "Тест 👑", TextGradientEndColor = "#112233", GradientEndColor = "#998877",
BorderGradientEndColor = "#ABCDEF80", ShadowBlur = 20, FontFamily = "Roboto", FontSize = 24 };
var customized = await _service.SetTagAsync(_db.Alice, style);
Assert.That(customized.Tag, Is.EqualTo(style));
Assert.That(customized.Revision, Is.GreaterThan(granted.Revision));
var revoked = await _service.SetPrivilegesAsync(_db.Alice, UserPrivileges.None);
Assert.That(revoked.Tag, Is.Null);
Assert.That(revoked.CanCustomizeProfileTag, Is.False);
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.SetTagAsync(_db.Alice, style));
var restored = await _service.SetPrivilegesAsync(_db.Alice, UserPrivileges.CustomProfileTag);
Assert.That(restored.IsGovorPlus, Is.False);
Assert.That(restored.Tag, Is.EqualTo(style));
Assert.That((await _service.SetTagAsync(_db.Alice, null)).Tag, Is.Null);
Assert.That((await _service.GetAsync(_db.Bob)).Privileges, Is.EqualTo(UserPrivileges.None));
}
[TestCase("text")]
[TestCase("blank")]
[TestCase("control")]
[TestCase("color")]
[TestCase("color-newline")]
[TestCase("gradient")]
[TestCase("text-gradient")]
[TestCase("border-gradient")]
[TestCase("font")]
[TestCase("weight")]
[TestCase("size")]
[TestCase("border")]
[TestCase("blur")]
[TestCase("offset")]
[TestCase("nan")]
[TestCase("angle")]
public async Task InvalidAppearanceCannotReplacePersistedTag(string reason)
{
await _service.SetPrivilegesAsync(_db.Alice, UserPrivileges.GovorPlus);
var good = new ProfileTagStyle { Text = "saved" };
await _service.SetTagAsync(_db.Alice, good);
var bad = reason switch
{
"text" => good with { Text = new string('x', 33) },
"blank" => good with { Text = " " },
"control" => good with { Text = "a\nb" },
"color" => good with { TextColor = "url(evil)" },
"color-newline" => good with { TextColor = "#FFFFFF\n" },
"gradient" => good with { GradientEndColor = "red" },
"text-gradient" => good with { TextGradientEndColor = "#fff" },
"border-gradient" => good with { BorderGradientEndColor = "#abc" },
"font" => good with { FontFamily = "url(evil)" },
"weight" => good with { FontWeight = 650 },
"size" => good with { FontSize = 99 },
"border" => good with { BorderWidth = -1 },
"blur" => good with { ShadowBlur = 21 },
"offset" => good with { ShadowOffsetX = -11 },
"nan" => good with { ShadowOffsetY = double.NaN },
_ => good with { GradientAngle = 361 }
};
Assert.ThrowsAsync<ArgumentException>(() => _service.SetTagAsync(_db.Alice, bad));
Assert.That((await _service.GetAsync(_db.Alice)).Tag, Is.EqualTo(good));
}
[Test]
public async Task UnknownRightsAndUsersAreRejectedAndDeletingUserCascadesBenefits()
{
Assert.ThrowsAsync<ArgumentException>(() => _service.SetPrivilegesAsync(_db.Alice, (UserPrivileges)4));
Assert.ThrowsAsync<KeyNotFoundException>(() => _service.SetPrivilegesAsync(Guid.NewGuid(), UserPrivileges.GovorPlus));
Assert.ThrowsAsync<KeyNotFoundException>(() => _service.GetAsync(Guid.NewGuid()));
await _service.SetPrivilegesAsync(_db.Outsider, UserPrivileges.GovorPlus);
await _db.Context.Users.Where(u => u.Id == _db.Outsider).ExecuteDeleteAsync();
Assert.That(await _db.Context.UserBenefits.AnyAsync(), Is.False);
}
[Test]
public async Task ConcurrentFirstGrantReturnsConflictWithoutOverwritingWinner()
{
using var competing = _db.CreateContext(new BeforeSave(async () =>
{
_db.Context.UserBenefits.Add(new UserBenefits { UserId = _db.Alice, Privileges = UserPrivileges.CustomProfileTag, Revision = 1 });
await _db.Context.SaveChangesAsync();
}));
Assert.ThrowsAsync<DbUpdateConcurrencyException>(() =>
new UserBenefitsService(competing).SetPrivilegesAsync(_db.Alice, UserPrivileges.GovorPlus));
Assert.That((await _service.GetAsync(_db.Alice)).Privileges, Is.EqualTo(UserPrivileges.CustomProfileTag));
Assert.That(competing.ChangeTracker.Entries(), Is.Empty);
}
[Test]
public async Task FailedInitialGrantDoesNotCreatePrivileges()
{
using var failed = _db.CreateContext(new FailDatabaseCommand(sql => sql.Contains("INSERT INTO \"UserBenefits\"", StringComparison.Ordinal)));
Assert.ThrowsAsync<DbUpdateException>(() => new UserBenefitsService(failed).SetPrivilegesAsync(_db.Alice, UserPrivileges.GovorPlus));
Assert.That((await _service.GetAsync(_db.Alice)).Privileges, Is.EqualTo(UserPrivileges.None));
Assert.That(failed.ChangeTracker.Entries(), Is.Empty);
}
private sealed class BeforeSave(Func<Task> action) : SaveChangesInterceptor
{
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData,
InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
await action();
return result;
}
}
}
+2 -2
View File
@@ -518,12 +518,12 @@ public partial class ReadApiTests
Assert.That((await _client.GetAsync($"/api/groups/{id}")).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
private async Task<TestHubConnection> ConnectHubAsync()
private async Task<TestHubConnection> ConnectHubAsync(string path = "/hubs/chats")
{
var client = _factory.Server.CreateWebSocketClient();
var authorization = _client.DefaultRequestHeaders.Authorization;
client.ConfigureRequest = request => request.Headers.Authorization = authorization!.ToString();
var connection = new TestHubConnection(await client.ConnectAsync(new Uri("ws://localhost/hubs/chats"), CancellationToken.None));
var connection = new TestHubConnection(await client.ConnectAsync(new Uri("ws://localhost" + path), CancellationToken.None));
await connection.SendAsync("{\"protocol\":\"json\",\"version\":1}");
Assert.That((await connection.ReadAsync()).EnumerateObject().Count(), Is.Zero);
// A completion proves OnConnectedAsync has finished joining the session group.
@@ -0,0 +1,115 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Microsoft.EntityFrameworkCore;
namespace Govor.Server.Tests;
public partial class ReadApiTests
{
[Test]
public async Task BenefitsGrantTagEditAndRevocationBroadcastToEveryConnectedProfileClient()
{
Authorize(userId: _db.Alice);
using var alice = await ConnectHubAsync("/hubs/profiles");
Authorize();
using var bob = await ConnectHubAsync("/hubs/profiles");
Authorize(userId: _db.Outsider);
using var outsider = await ConnectHubAsync("/hubs/profiles");
Authorize(role: "Admin");
var route = $"/api/admin/users/{_db.Bob}/privileges";
Assert.That((await _client.PutAsJsonAsync(route, new { privileges = 1 })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
long previous = 0;
foreach (var stage in new[] { "grant", "edit", "reset", "revoke" })
{
if (stage == "edit")
{
Authorize();
Assert.That((await _client.PutAsJsonAsync("/api/profile/tag", new ProfileTagStyle { Text = "Live" })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
}
if (stage == "reset")
Assert.That((await _client.DeleteAsync("/api/profile/tag")).StatusCode, Is.EqualTo(HttpStatusCode.OK));
if (stage == "revoke")
{
Authorize(role: "Admin");
Assert.That((await _client.PutAsJsonAsync(route, new { privileges = 0 })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
}
long revision = 0;
foreach (var connection in new[] { alice, bob, outsider })
{
var frame = await connection.ReadAsync();
Assert.That(frame.GetProperty("target").GetString(), Is.EqualTo("UserBenefitsUpdated"));
var payload = frame.GetProperty("arguments")[0];
Assert.That(payload.GetProperty("userId").GetGuid(), Is.EqualTo(_db.Bob));
var benefits = payload.GetProperty("benefits");
revision = benefits.GetProperty("revision").GetInt64();
Assert.That(revision, Is.GreaterThan(previous));
Assert.That(benefits.GetProperty("isGovorPlus").GetBoolean(), Is.EqualTo(stage != "revoke"));
if (stage == "revoke") Assert.That(benefits.GetProperty("tag").ValueKind, Is.EqualTo(JsonValueKind.Null));
else Assert.That(benefits.GetProperty("tag").GetProperty("text").GetString(), Is.EqualTo(stage == "edit" ? "Live" : "Govor+"));
}
previous = revision;
}
Authorize();
Assert.That((await _client.PutAsJsonAsync("/api/profile/tag", new ProfileTagStyle())).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
using var profile = JsonDocument.Parse(await _client.GetStringAsync("/api/profile/download/me"));
Assert.That(profile.RootElement.GetProperty("benefits").GetProperty("revision").GetInt64(), Is.EqualTo(previous));
}
[Test]
public async Task BenefitsRoutesEnforceAuthenticationAdminRoleAndValidation()
{
var route = $"/api/admin/users/{_db.Bob}/privileges";
Assert.That((await _client.GetAsync($"/api/profile/{_db.Bob}/benefits")).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
Authorize();
Assert.That((await _client.PutAsJsonAsync(route, new { privileges = 1 })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Assert.That((await _client.PutAsJsonAsync("/api/profile/tag", new ProfileTagStyle())).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Authorize(role: "Admin");
Assert.That((await _client.PutAsJsonAsync(route, new { privileges = 4 })).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
Assert.That((await _client.PutAsJsonAsync($"/api/admin/users/{Guid.NewGuid()}/privileges", new { privileges = 1 })).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
Assert.That((await _client.PutAsJsonAsync(route, new { privileges = 1 })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
Authorize();
Assert.That((await _client.PutAsJsonAsync("/api/profile/tag", new ProfileTagStyle { TextColor = "invalid" })).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
Assert.That((await _client.GetAsync($"/api/profile/{Guid.NewGuid()}/benefits")).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
var value = await _client.GetFromJsonAsync<UserBenefitsView>($"/api/profile/{_db.Bob}/benefits");
Assert.That(value!.Tag!.Text, Is.EqualTo("Govor+"));
}
[Test]
public async Task FriendRemovalAndBlockHttpRoutesPreserveBlockOwnership()
{
_db.Context.Friendships.Add(new Friendship { Id = Guid.NewGuid(), RequesterId = _db.Alice,
AddresseeId = _db.Bob, Status = FriendshipStatus.Accepted });
await _db.Context.SaveChangesAsync();
var route = $"/api/friends/{_db.Alice}";
Assert.That((await _client.DeleteAsync(route)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
Authorize();
Assert.That((await _client.DeleteAsync(route)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _db.Context.Friendships.AsNoTracking().SingleAsync()).Status, Is.EqualTo(FriendshipStatus.Rejected));
Assert.That((await _client.PutAsync(route + "/block", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _client.DeleteAsync(route)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _db.Context.Friendships.AsNoTracking().SingleAsync()).Status, Is.EqualTo(FriendshipStatus.Blocked));
Authorize(userId: _db.Alice);
Assert.That((await _client.DeleteAsync($"/api/friends/{_db.Bob}/block")).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Authorize();
Assert.That((await _client.DeleteAsync(route + "/block")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _db.Context.Friendships.AsNoTracking().SingleAsync()).Status, Is.EqualTo(FriendshipStatus.Rejected));
Assert.That((await _client.PutAsync($"/api/friends/{_db.Bob}/block", null)).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
Assert.That((await _client.PutAsync($"/api/friends/{Guid.NewGuid()}/block", null)).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
[Test]
public async Task ReplyLookupDoesNotExposeMessagesToNonParticipants()
{
var message = _db.AddMessage();
Authorize();
var response = await _client.GetAsync($"/api/messages/{message.Id}");
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.That(json.RootElement.GetProperty("id").GetGuid(), Is.EqualTo(message.Id));
Authorize(userId: _db.Outsider);
Assert.That((await _client.GetAsync($"/api/messages/{message.Id}")).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
}
@@ -152,6 +152,45 @@ public class E2eeTests
Assert.That(await _db.Context.Messages.CountAsync(), Is.Zero);
}
[Test]
public async Task ForwardRequiresFreshEncryptionForDestinationAndRetryKeepsAttribution()
{
var sender = new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance);
var source = await sender.SendMessageAsync(new(await Encrypt(), null, _db.ChatId, RecipientType.User, _db.Alice, DateTime.UtcNow, []));
var destination = Guid.NewGuid();
_db.Context.PrivateChats.Add(new PrivateChat { Id = destination, UserAId = _db.Alice, UserBId = _db.Outsider });
await _db.Context.SaveChangesAsync();
await Register(_db.Outsider, _other);
var replay = await sender.SendMessageAsync(new(source.Message.EncryptedContent, null, destination,
RecipientType.User, _db.Alice, DateTime.UtcNow, [], source.Message.Id));
Assert.That(replay.IsSuccess, Is.False);
var ciphertext = await Encrypt(conversation: destination);
var request = new SendMessage(ciphertext, null, destination, RecipientType.User, _db.Alice, DateTime.UtcNow, [], source.Message.Id);
var forwarded = await sender.SendMessageAsync(request);
Assert.That(forwarded.IsSuccess, Is.True);
Assert.That(forwarded.Message.ForwardedFromMessageId, Is.EqualTo(source.Message.Id));
Assert.That((await sender.SendMessageAsync(request)).Message.Id, Is.EqualTo(forwarded.Message.Id));
Assert.That((await sender.SendMessageAsync(request with { ForwardedFromMessageId = null })).IsSuccess, Is.False);
Assert.That(E2eeProtocol.Decrypt(ciphertext, _other, forwarded.Message.Id, destination, 0, _db.Alice).Text,
Is.EqualTo("секретное сообщение"));
Assert.Throws<CryptographicException>(() => E2eeProtocol.Decrypt(ciphertext, _bob, forwarded.Message.Id, destination, 0, _db.Alice));
Assert.That(await _db.Context.Messages.CountAsync(), Is.EqualTo(2));
}
[Test]
public async Task EncryptedReplyBindsReplyTargetToSignedEnvelope()
{
var sender = new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance);
var source = await sender.SendMessageAsync(new(await Encrypt(), null, _db.ChatId, RecipientType.User, _db.Alice, DateTime.UtcNow, []));
var ciphertext = E2eeProtocol.Encrypt(new("ответ", []), _bob, _b,
await _e2ee.GetConversationKeysAsync(_db.Bob, _db.ChatId, RecipientType.User), Guid.NewGuid(), replyTo: source.Message.Id);
var request = new SendMessage(ciphertext, source.Message.Id, _db.ChatId, RecipientType.User, _db.Bob, DateTime.UtcNow, []);
Assert.That((await sender.SendMessageAsync(request with { ReplyToMessageId = null })).IsSuccess, Is.False);
var sent = await sender.SendMessageAsync(request);
Assert.That(sent.IsSuccess, Is.True);
Assert.That(sent.Message.ReplyToMessageId, Is.EqualTo(source.Message.Id));
}
[Test]
public async Task NewDeviceMakesOldRecipientManifestInvalid()
{