Expand server tests and enforce coverage

Consolidate server tests under tests/, upgrade them to .NET 10, and add CI coverage thresholds and reports. Expand API and application boundary coverage while fixing related issues in media handling, friend blocking, session crypto, presence, username validation, and local storage.
This commit is contained in:
Artemy
2026-10-24 15:30:32 +07:00
parent 33550d4fc9
commit 2d99c57a3b
161 changed files with 5515 additions and 8419 deletions
@@ -0,0 +1,94 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Govor.Application.E2ee;
using Govor.Contracts.DTOs;
using Govor.Contracts.Responses;
using Microsoft.EntityFrameworkCore;
namespace Govor.Server.Tests;
public partial class ReadApiTests
{
[Test]
public async Task HealthAndSwaggerEndpointsExposeExpectedContracts()
{
Assert.That((await _client.GetAsync("/server/ping")).StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That(await _client.GetStringAsync("/"), Is.EqualTo("Not for browsers"));
var ready = await _client.GetAsync("/server/ready");
Assert.That(ready.StatusCode, Is.EqualTo(_db.Connection is Npgsql.NpgsqlConnection
? HttpStatusCode.OK : HttpStatusCode.ServiceUnavailable));
var swagger = await _client.GetAsync("/swagger/v1/swagger.json");
Assert.That(swagger.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var document = JsonDocument.Parse(await swagger.Content.ReadAsStringAsync());
Assert.That(document.RootElement.GetProperty("paths").TryGetProperty("/api/e2ee/device", out _), Is.True);
Assert.That(document.RootElement.GetProperty("components").GetProperty("securitySchemes")
.GetProperty("Bearer").GetProperty("scheme").GetString(), Is.EqualTo("bearer"));
}
[Test]
public async Task AdminHttpRoutesRequireRoleAndReturnPersistedUserAndInvitationData()
{
Assert.That((await _client.GetAsync("/api/admin/Users/all")).StatusCode,Is.EqualTo(HttpStatusCode.Unauthorized));
Authorize(role:"Admin");
var list=await _client.GetAsync("/api/admin/Users/all");Assert.That(list.StatusCode,Is.EqualTo(HttpStatusCode.OK));
using var users=JsonDocument.Parse(await list.Content.ReadAsStringAsync());Assert.That(users.RootElement.GetArrayLength(),Is.EqualTo(3));
Assert.That((await _client.GetAsync($"/api/admin/Users/{_db.Alice}")).StatusCode,Is.EqualTo(HttpStatusCode.OK));
Assert.That((await _client.GetAsync($"/api/admin/Users/{Guid.NewGuid()}")).StatusCode,Is.EqualTo(HttpStatusCode.NotFound));
var before=(await _db.Context.Users.AsNoTracking().SingleAsync(x=>x.Id==_db.Alice)).PasswordHash;
Assert.That((await _client.PostAsJsonAsync($"/api/admin/Users/user/{_db.Alice}/password",new{password="new-password-123"})).StatusCode,Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _db.Context.Users.AsNoTracking().SingleAsync(x=>x.Id==_db.Alice)).PasswordHash,Is.Not.EqualTo(before));
var created=await _client.PostAsJsonAsync("/api/admin/InviteUser/Invitation",new{endDate=DateTime.UtcNow.AddDays(2),maxParticipants=5,isAdmin=false,description="http invitation"});
Assert.That(created.StatusCode,Is.EqualTo(HttpStatusCode.OK));
var invitation=await _db.Context.Invitations.AsNoTracking().SingleAsync(x=>x.Description=="http invitation");
foreach(var path in new[]{"/api/admin/InviteUser","/api/admin/InviteUser/GetAllActiveInvitations",$"/api/admin/InviteUser/{invitation.Id}"})
Assert.That((await _client.GetAsync(path)).StatusCode,Is.EqualTo(HttpStatusCode.OK));
Assert.That((await _client.GetAsync($"/api/admin/InviteUser/{Guid.NewGuid()}")).StatusCode,Is.EqualTo(HttpStatusCode.NotFound));
Authorize();
Assert.That((await _client.PostAsJsonAsync("/api/admin/InviteUser/Invitation",new{endDate=DateTime.UtcNow.AddDays(2),maxParticipants=5})).StatusCode,Is.EqualTo(HttpStatusCode.Forbidden));
}
[Test]
public async Task ReactionPackHttpCrudAndSubscriptionsUseRealMappings()
{
Authorize(role:"Admin");ReactionTests.MakeAdmin(_db.Context,_db.Bob);
var created=await _client.PostAsJsonAsync("/api/admin/reaction-packs",new{name="http pack",description="original"});
Assert.That(created.StatusCode,Is.EqualTo(HttpStatusCode.OK));var pack=(await created.Content.ReadFromJsonAsync<ReactionPackResponse>())!;
Assert.That((await _client.PutAsJsonAsync($"/api/admin/reaction-packs/{pack.Id}",new{name="updated",description="changed",isEnabled=true})).StatusCode,Is.EqualTo(HttpStatusCode.OK));
var emoji=await _client.PostAsJsonAsync($"/api/admin/reaction-packs/{pack.Id}/reactions/emoji",new{name="wave",emoji="👋"});
Assert.That(emoji.StatusCode,Is.EqualTo(HttpStatusCode.OK));var item=(await emoji.Content.ReadFromJsonAsync<ReactionItemResponse>())!;
foreach(var path in new[]{"/api/reaction-packs",$"/api/reaction-packs/{pack.Id}",$"/api/reaction-packs/shared/{pack.ShareCode}",$"/api/reactions/{item.Id}","/api/reaction-packs/limits",$"/api/admin/reaction-packs/{pack.Id}"})
Assert.That((await _client.GetAsync(path)).StatusCode,Is.EqualTo(HttpStatusCode.OK),path);
Assert.That((await _client.PutAsync($"/api/reaction-packs/{pack.Id}/subscription",null)).StatusCode,Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _client.DeleteAsync($"/api/reaction-packs/{pack.Id}/subscription")).StatusCode,Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _client.DeleteAsync($"/api/admin/reaction-packs/{pack.Id}/reactions/{item.Id}")).StatusCode,Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _client.DeleteAsync($"/api/admin/reaction-packs/{pack.Id}")).StatusCode,Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _client.GetAsync($"/api/reaction-packs/{pack.Id}")).StatusCode,Is.EqualTo(HttpStatusCode.NotFound));
Assert.That((await _client.GetAsync($"/api/admin/reaction-packs/{pack.Id}")).StatusCode,Is.EqualTo(HttpStatusCode.OK));
}
[Test]
public async Task E2eeHttpRegistrationIsIdempotentAndImmutableAndDirectoryChecksAccess()
{
Authorize();
var privateKeys=E2eeProtocol.GenerateKeys();var key=E2eeProtocol.PublicKey(privateKeys,_db.Bob,_session);
Assert.That((await _client.PutAsJsonAsync("/api/e2ee/device",key)).StatusCode,Is.EqualTo(HttpStatusCode.OK));
Assert.That((await _client.PutAsJsonAsync("/api/e2ee/device",key)).StatusCode,Is.EqualTo(HttpStatusCode.OK));
var replacement=E2eeProtocol.PublicKey(E2eeProtocol.GenerateKeys(),_db.Bob,_session);
Assert.That((await _client.PutAsJsonAsync("/api/e2ee/device",replacement)).StatusCode,Is.EqualTo(HttpStatusCode.Conflict));
Assert.That((await _client.PutAsJsonAsync("/api/e2ee/device",key with{UserId=_db.Alice})).StatusCode,Is.EqualTo(HttpStatusCode.Forbidden));
Assert.That((await _client.PutAsJsonAsync("/api/e2ee/device",key with{IdentityKey="invalid"})).StatusCode,Is.EqualTo(HttpStatusCode.BadRequest));
Assert.That((await _client.GetAsync($"/api/e2ee/conversations/0/{_db.ChatId}/keys")).StatusCode,Is.EqualTo(HttpStatusCode.Conflict));
Assert.That((await _client.GetAsync($"/api/e2ee/conversations/0/{Guid.NewGuid()}/keys")).StatusCode,Is.EqualTo(HttpStatusCode.Forbidden));
foreach(var path in new[]{$"/api/e2ee/conversations/2/{_db.ChatId}/keys",$"/api/e2ee/conversations/0/{Guid.Empty}/keys"})
Assert.That((await _client.GetAsync(path)).StatusCode,Is.EqualTo(HttpStatusCode.BadRequest));
var aliceSession=new Govor.Domain.Models.Users.UserSession{UserId=_db.Alice,RefreshTokenHash="alice-e2ee",ExpiresAt=DateTime.UtcNow.AddDays(1)};
_db.Context.UserSessions.Add(aliceSession);await _db.Context.SaveChangesAsync();
var aliceKey=E2eeProtocol.PublicKey(E2eeProtocol.GenerateKeys(),_db.Alice,aliceSession.Id);
await new E2eeService(_db.Context).RegisterAsync(_db.Alice,aliceSession.Id,aliceKey);
var directoryResponse=await _client.GetAsync($"/api/e2ee/conversations/0/{_db.ChatId}/keys");
Assert.That(directoryResponse.StatusCode,Is.EqualTo(HttpStatusCode.OK));
var directory=(await directoryResponse.Content.ReadFromJsonAsync<ConversationKeys>())!;
Assert.That(directory.Members,Is.EquivalentTo(new[]{_db.Alice,_db.Bob}));Assert.That(directory.Devices,Has.Length.EqualTo(2));
}
}
@@ -0,0 +1,594 @@
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Net.WebSockets;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using Govor.API.Hubs.Infrastructure;
using Govor.API.Hubs;
using Govor.Application.Storage;
using Govor.Contracts.Requests;
using Govor.Contracts.Responses;
using Govor.Domain.Models.Reactions;
using Microsoft.AspNetCore.SignalR;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Govor.Contracts.Responses.SignalR;
using Govor.Domain;
using Govor.Domain.Models.Users;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Moq;
namespace Govor.Server.Tests;
[TestFixture]
[NonParallelizable]
public partial class ReadApiTests
{
private const string Secret = "Govor-server-tests-only-signing-key-at-least-64-characters-long-123456";
private TestDatabase _db = null!;
private TestFactory _factory = null!;
private HttpClient _client = null!;
private Mock<IChatNotificationService> _notifier = null!;
private Guid _session;
[SetUp]
public void SetUp()
{
_db = new TestDatabase();
var session = new UserSession { UserId = _db.Bob, ExpiresAt = DateTime.UtcNow.AddDays(1) };
_db.Context.UserSessions.Add(session);
_db.Context.SaveChanges();
_session = session.Id;
_notifier = new Mock<IChatNotificationService>();
_notifier.Setup(n => n.NotifyChatReadAsync(It.IsAny<ChatReadResponse>())).Returns(Task.CompletedTask);
_notifier.Setup(n => n.NotifyMessageReactionsChangedAsync(It.IsAny<MessageReactionsChangedResponse>())).Returns(Task.CompletedTask);
_notifier.Setup(n => n.NotifyChannelReactionPolicyChangedAsync(It.IsAny<ChannelReactionPolicyResponse>())).Returns(Task.CompletedTask);
_notifier.Setup(n => n.NotifyGroupProfileChangedAsync(It.IsAny<Guid>())).Returns(Task.CompletedTask);
_notifier.Setup(n => n.NotifyGroupMemberChangedAsync(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(Task.CompletedTask);
_notifier.Setup(n => n.NotifyUserJoinedGroupsAsync(It.IsAny<Guid>())).Returns(Task.CompletedTask);
_factory = new TestFactory(_db, _notifier.Object);
_client = _factory.CreateClient();
}
[TearDown]
public void TearDown()
{
_client.Dispose();
_factory.Dispose();
_db.Dispose();
}
[Test]
public async Task OnlineStatusEndpointUsesPersistedLastSeenAndHandlesMissingUser()
{
Assert.That((await _client.GetAsync($"/api/online/status/{_db.Alice}")).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
Authorize();
var response = await _client.GetAsync($"/api/online/status/{_db.Alice}");
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var expected = (await _db.Context.Users.AsNoTracking().SingleAsync(u => u.Id == _db.Alice)).WasOnline;
Assert.That(json.RootElement.GetProperty("lastSeen").GetDateTime(), Is.EqualTo(expected));
var missing = await _client.GetAsync($"/api/online/status/{Guid.NewGuid()}");
Assert.That(missing.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var missingJson = JsonDocument.Parse(await missing.Content.ReadAsStringAsync());
Assert.That(missingJson.RootElement.GetProperty("lastSeen").ValueKind, Is.EqualTo(JsonValueKind.Null));
}
[Test]
[TestCase(false)]
[TestCase(true)]
public async Task EncryptedAttachmentUploadAcceptsMissingOrEmptyDecryptionKey(bool sendEmptyKey)
{
Authorize();
using var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(new byte[] { 1, 2, 3 }), "FromFile", "encrypted.bin");
form.Add(new StringContent("0"), "Type");
form.Add(new StringContent("0"), "OwnerType");
form.Add(new StringContent(Govor.Application.E2ee.E2eeProtocol.EncryptedMimeType), "MimeType");
if (sendEmptyKey) form.Add(new StringContent(""), "EncryptedKey");
var response = await _client.PostAsync("/api/media/upload", form);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK), await response.Content.ReadAsStringAsync());
var media = await _db.Context.MediaFiles.AsNoTracking().SingleAsync();
Assert.That(media.UploaderId, Is.EqualTo(_db.Bob));
Assert.That(media.MineType, Is.EqualTo(Govor.Application.E2ee.E2eeProtocol.EncryptedMimeType));
}
[Test]
public async Task ReadEndpointPersistsReceiptsNotifiesAndReturnsUnreadCount()
{
var message = _db.AddMessage();
Authorize();
var response = await _client.PostAsJsonAsync($"/api/chats/{_db.ChatId}/read",
new { recipientType = 0, messageIds = new[] { message.Id } });
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var body = await response.Content.ReadFromJsonAsync<ChatReadResponse>();
Assert.That(body!.ReadCount, Is.EqualTo(1));
Assert.That(body.UnreadCount, Is.Zero);
_notifier.Verify(n => n.NotifyChatReadAsync(It.Is<ChatReadResponse>(r => r.ReaderId == _db.Bob && r.ChatId == _db.ChatId)), Times.Once);
var count = await _client.GetAsync($"/api/chats/{_db.ChatId}/unread-count?recipientType=0");
Assert.That(count.StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That(await count.Content.ReadAsStringAsync(), Does.Contain("\"unreadCount\":0"));
}
[Test]
public async Task PushRegistrationRotationAndUnregisterAffectOnlyTheAuthenticatedSession()
{
var otherSession = new UserSession { UserId = _db.Bob, ExpiresAt = DateTime.UtcNow.AddDays(1), RefreshTokenHash = "other-device" };
_db.Context.UserSessions.Add(otherSession);
_db.Context.UserPushTokens.Add(new UserPushToken
{ UserId = _db.Bob, UserSessionId = otherSession.Id, Token = "other-device", Platform = "android" });
await _db.Context.SaveChangesAsync();
Assert.That((await _client.DeleteAsync("/api/pushes/token")).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
Authorize();
foreach (var token in new[] { "original", "rotated" })
Assert.That((await _client.PostAsJsonAsync("/api/pushes/token/register", new { token, platform = "android" })).StatusCode,
Is.EqualTo(HttpStatusCode.NoContent));
var registered = await _db.Context.UserPushTokens.AsNoTracking().SingleAsync(t => t.UserSessionId == _session);
Assert.That(registered.Token, Is.EqualTo("rotated"));
foreach (var _ in Enumerable.Range(0, 2))
Assert.That((await _client.DeleteAsync("/api/pushes/token")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _db.Context.UserPushTokens.AsNoTracking().SingleAsync(t => t.UserSessionId == _session)).IsActive, Is.False);
Assert.That((await _db.Context.UserPushTokens.AsNoTracking().SingleAsync(t => t.UserSessionId == otherSession.Id)).IsActive, Is.True);
Assert.That((await _client.PostAsJsonAsync("/api/pushes/token/register", new { token = "rotated", platform = "android" })).StatusCode,
Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _db.Context.UserPushTokens.AsNoTracking().SingleAsync(t => t.UserSessionId == _session)).IsActive, Is.True);
}
[TestCase(null, "android")]
[TestCase("", "android")]
[TestCase(" ", "android")]
[TestCase("token", " ")]
[TestCase("token", null)]
public async Task PushRegistrationRejectsMissingOrBlankFields(string? token, string? platform)
{
Authorize();
Assert.That((await _client.PostAsJsonAsync("/api/pushes/token/register", new { token, platform })).StatusCode,
Is.EqualTo(HttpStatusCode.BadRequest));
Assert.That(await _db.Context.UserPushTokens.CountAsync(), Is.Zero);
}
[Test]
public async Task AnonymousAndRefreshTokenCannotUseReadApi()
{
var path = $"/api/chats/{_db.ChatId}/unread-count?recipientType=0";
Assert.That((await _client.GetAsync(path)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
Authorize(tokenType: "refresh");
Assert.That((await _client.GetAsync(path)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
}
[Test]
public async Task SessionRevocationInvalidatesAnAlreadyIssuedAccessToken()
{
Authorize();
await _db.Context.UserSessions.Where(s => s.Id == _session)
.ExecuteUpdateAsync(setters => setters.SetProperty(s => s.IsRevoked, true));
var response = await _client.GetAsync($"/api/chats/{_db.ChatId}/unread-count?recipientType=0");
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
}
[Test]
public async Task ForeignChatIsForbiddenAndInvalidSelectionIsBadRequest()
{
var message = _db.AddMessage();
Authorize();
var foreign = await _client.PostAsJsonAsync($"/api/chats/{Guid.NewGuid()}/read", new { recipientType = 0 });
Assert.That(foreign.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
var invalid = await _client.PostAsJsonAsync($"/api/chats/{_db.ChatId}/read",
new { recipientType = 0, messageIds = new[] { message.Id }, upToMessageId = message.Id });
Assert.That(invalid.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
Assert.That(await _db.Context.MessageViews.CountAsync(), Is.Zero);
}
[Test]
public async Task OrdinaryUserCannotReadAdminUserList()
{
Authorize();
var response = await _client.GetAsync("/api/admin/Users/all");
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
}
[Test]
public async Task ReactionHttpApiReturnsVersionedCountsAndNotifiesOnlyOnChange()
{
var message = _db.AddMessage();
Authorize();
var packs = await _client.GetFromJsonAsync<List<ReactionPackResponse>>("/api/reaction-packs/mine");
var reaction = packs!.Single(p => p.IsDefault).Reactions.First().Id;
var path = $"/api/messages/{message.Id}/reactions";
var response = await _client.PutAsJsonAsync(path + "/me", new { reactionId = reaction });
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var state = await response.Content.ReadFromJsonAsync<MessageReactionsChangedResponse>();
Assert.That(state!.Version, Is.EqualTo(1));
Assert.That(state.ActorReaction!.ReactionId, Is.EqualTo(reaction));
Assert.That(state.Counts.Single().Count, Is.EqualTo(1));
Assert.That((await _client.PutAsJsonAsync(path + "/me", new { reactionId = reaction })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
_notifier.Verify(n => n.NotifyMessageReactionsChangedAsync(It.IsAny<MessageReactionsChangedResponse>()), Times.Once);
Assert.That((await _client.PutAsJsonAsync(path + "/me", new { reactionId = Guid.Empty })).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
var removed = await _client.DeleteAsync(path + "/me");
Assert.That(removed.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var empty = await _client.GetFromJsonAsync<MessageReactionsChangedResponse>(path);
Assert.That(empty!.Version, Is.EqualTo(2));
Assert.That(empty.Counts, Is.Empty);
}
[Test]
public async Task AdminPackUploadUsesRealContentAndCanBeSharedAndDownloaded()
{
Authorize();
Assert.That((await _client.PostAsJsonAsync("/api/admin/reaction-packs", new { name = "Custom" })).StatusCode,
Is.EqualTo(HttpStatusCode.Forbidden));
Authorize(role: "Admin");
Assert.That((await _client.PostAsJsonAsync("/api/admin/reaction-packs", new { name = "Custom" })).StatusCode,
Is.EqualTo(HttpStatusCode.Forbidden));
ReactionTests.MakeAdmin(_db.Context, _db.Bob);
var created = await _client.PostAsJsonAsync("/api/admin/reaction-packs", new { name = "Custom", description = "Shared" });
Assert.That(created.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var pack = (await created.Content.ReadFromJsonAsync<ReactionPackResponse>())!;
using var image = new Image<Rgba32>(256, 256);
using var bytes = new MemoryStream();
await image.SaveAsPngAsync(bytes);
using var multipart = new MultipartFormDataContent();
multipart.Add(new StringContent("Picture"), "name");
var upload = new ByteArrayContent(bytes.ToArray());
upload.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
multipart.Add(upload, "file", "incorrect.txt");
var response = await _client.PostAsync($"/api/admin/reaction-packs/{pack.Id}/reactions/media", multipart);
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var item = (await response.Content.ReadFromJsonAsync<ReactionItemResponse>())!;
Assert.That(item.Kind, Is.EqualTo(ReactionKind.Image));
Assert.That(item.Width, Is.EqualTo(128));
Authorize();
var shared = await _client.GetFromJsonAsync<ReactionPackResponse>(pack.SharePath);
Assert.That(shared!.Reactions.Single().Id, Is.EqualTo(item.Id));
Assert.That((await _client.PutAsync($"/api/reaction-packs/{pack.Id}/subscription", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
var downloaded = await _client.GetAsync(item.MediaUrl);
Assert.That(downloaded.StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That(downloaded.Content.Headers.ContentType!.MediaType, Is.EqualTo("image/png"));
using var decoded = Image.Load(await downloaded.Content.ReadAsByteArrayAsync());
Assert.That(decoded.Width, Is.EqualTo(128));
}
[Test]
public async Task SignalRReactionMethodsUseTheSameStateAndAccessChecks()
{
var message = _db.AddMessage();
using var scope = _factory.Services.CreateScope();
var hub = ActivatorUtilities.CreateInstance<ChatsHub>(scope.ServiceProvider);
var caller = new Mock<HubCallerContext>();
caller.SetupGet(c => c.User).Returns(new ClaimsPrincipal(new ClaimsIdentity(new[]
{ new Claim("userId", _db.Bob.ToString()), new Claim("sid", _session.ToString()) }, "test")));
hub.Context = caller.Object;
var reaction = DefaultReactionPack.Items().First().Id;
var result = await hub.React(message.Id, new SetReactionRequest { ReactionId = reaction });
Assert.That(result.Status, Is.EqualTo(HubResultStatus.Success));
Assert.That(result.Result!.Counts.Single().Count, Is.EqualTo(1));
Assert.That((await hub.RemoveReaction(message.Id)).Status, Is.EqualTo(HubResultStatus.Success));
Assert.That((await hub.React(Guid.NewGuid(), new SetReactionRequest { ReactionId = reaction })).Status, Is.EqualTo(HubResultStatus.NotFound));
}
[Test]
public async Task PrivateGroupHttpInvitationPreviewJoinAndRolesRespectPermissions()
{
Authorize();
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "PrivateGroup", description = "test", isPrivate = true });
Assert.That(created.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var group = (await created.Content.ReadFromJsonAsync<GroupResponse>())!;
Assert.That(group.MyRole, Is.EqualTo(Govor.Domain.Models.GroupRole.Owner));
Assert.That(group.MemberCount, Is.EqualTo(1));
var invitation = await _client.PostAsJsonAsync($"/api/groups/{group.Id}/invitations", new { maxParticipants = 1 });
var link = (await invitation.Content.ReadFromJsonAsync<GroupInvitationResponse>())!;
Authorize(userId: _db.Alice);
Assert.That((await _client.GetAsync($"/api/groups/{group.Id}")).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
Assert.That((await _client.GetFromJsonAsync<List<GroupResponse>>("/api/groups/search?q=PrivateGroup")), Is.Empty);
Assert.That((await _client.GetAsync(link.PreviewPath)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That(await _db.Context.GroupMemberships.AnyAsync(m => m.GroupId == group.Id && m.UserId == _db.Alice), Is.False);
Assert.That((await _client.PostAsync(link.JoinPath, null)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That((await _client.PutAsJsonAsync($"/api/groups/{group.Id}", new { name = "Hijacked" })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Assert.That((await _client.PutAsync($"/api/groups/{group.Id}/members/{_db.Alice}/administrator", null)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Authorize();
Assert.That((await _client.PutAsync($"/api/groups/{group.Id}/members/{_db.Alice}/administrator", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Authorize(userId: _db.Alice);
Assert.That((await _client.PutAsync($"/api/groups/{group.Id}/members/{_db.Bob}/ban", null)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Assert.That((await _client.DeleteAsync($"/api/groups/{group.Id}/members/me")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _client.GetAsync($"/api/groups/{group.Id}/messages")).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
}
[Test]
public async Task ChannelOwnerControlsReactionsAndModerationHttpNotifiesDeletion()
{
Authorize();
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "Channel", isPrivate = false, isChannel = true });
var group = (await created.Content.ReadFromJsonAsync<GroupResponse>())!;
var id = group.Id;
var policy = await _client.PutAsJsonAsync($"/api/groups/{id}/reactions", new
{ mode = 2, reactionIds = new[] { DefaultReactionPack.Items()[0].Id } });
Assert.That(policy.StatusCode, Is.EqualTo(HttpStatusCode.OK));
_notifier.Verify(n => n.NotifyChannelReactionPolicyChangedAsync(It.Is<ChannelReactionPolicyResponse>(p => p.GroupId == id)), Times.Once);
Authorize(userId: _db.Alice);
await _client.PostAsync($"/api/groups/{id}/join", null);
Assert.That((await _client.PutAsJsonAsync($"/api/groups/{id}/reactions", new { mode = 1 })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Authorize();
var own = _db.AddMessage(sender: _db.Bob, chat: id, type: Govor.Domain.Models.Messages.RecipientType.Group);
Assert.That((await _client.DeleteAsync($"/api/groups/{Guid.NewGuid()}/messages/{own.Id}")).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
Assert.That((await _client.DeleteAsync($"/api/groups/{id}/messages/{own.Id}")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
_notifier.Verify(n => n.NotifyMessageRemovedAsync(It.Is<MessageRemovedResponse>(m => m.MessageId == own.Id && m.RecipientId == id)), Times.Once);
}
[Test]
public async Task RequiredChannelHttpRequiresServerAdminAndRegistrationAddsMembership()
{
Authorize();
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "Required", isPrivate = true, isChannel = true });
var id = (await created.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = id, allowLeave = false })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Authorize(role: "Admin");
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = id })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
ReactionTests.MakeAdmin(_db.Context, _db.Bob);
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = id, allowLeave = false })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
var invite = _db.Context.Invitations.Single(i => i.Code == "test");
invite.Code = Guid.NewGuid().ToString("N");
await _db.Context.SaveChangesAsync();
_client.DefaultRequestHeaders.Authorization = null;
var registered = await _client.PostAsJsonAsync("/api/auth/register", new
{ name = "НовыйУчастник123", password = "Secure-test123!", inviteLink = invite.Code, deviceInfo = "test" });
Assert.That(registered.StatusCode, Is.EqualTo(HttpStatusCode.OK), await registered.Content.ReadAsStringAsync());
var user = await _db.Context.Users.AsNoTracking().SingleAsync(u => u.Username == "НовыйУчастник123");
_notifier.Verify(n => n.NotifyUserJoinedGroupsAsync(user.Id), Times.Once);
Assert.That(await _db.Context.GroupMemberships.AnyAsync(m => m.UserId == user.Id && m.GroupId == id && !m.IsBanned), Is.True);
Authorize(userId: user.Id);
Assert.That((await _client.DeleteAsync($"/api/groups/{id}/members/me")).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
}
[Test]
public async Task GroupAvatarIsOwnerControlledAndPrivateFilesAreProtected()
{
Authorize();
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "AvatarGroup", isPrivate = false });
var group = (await created.Content.ReadFromJsonAsync<GroupResponse>())!;
using var image = new Image<Rgba32>(256, 256);
using var bytes = new MemoryStream();
await image.SaveAsPngAsync(bytes);
using var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(bytes.ToArray()), "file", "avatar.png");
Assert.That((await _client.PostAsync($"/api/groups/{group.Id}/avatar", form)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(group.Id), Times.Once);
var updated = (await _client.GetFromJsonAsync<GroupResponse>($"/api/groups/{group.Id}"))!;
Assert.That(updated.ImageId, Is.Not.EqualTo(Guid.Empty));
Authorize(userId: _db.Alice);
Assert.That((await _client.GetAsync(updated.ImageUrl)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That((await _client.DeleteAsync($"/api/groups/{group.Id}/avatar")).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(group.Id), Times.Once);
Authorize();
await _client.PutAsJsonAsync($"/api/groups/{group.Id}", new { name = "AvatarGroup", isPrivate = true });
var invitation = await _client.PostAsJsonAsync($"/api/groups/{group.Id}/invitations", new { });
var link = (await invitation.Content.ReadFromJsonAsync<GroupInvitationResponse>())!;
Authorize(userId: _db.Alice);
Assert.That((await _client.GetAsync(updated.ImageUrl)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
await _client.PostAsync(link.JoinPath, null);
Assert.That((await _client.GetAsync(updated.ImageUrl)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
Authorize();
await _client.PutAsync($"/api/groups/{group.Id}/members/{_db.Alice}/ban", null);
Authorize(userId: _db.Alice);
Assert.That((await _client.GetAsync(updated.ImageUrl)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Authorize();
Assert.That((await _client.DeleteAsync($"/api/groups/{group.Id}/avatar")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(group.Id), Times.Exactly(3));
}
[Test]
public async Task GroupCommandsNotifyAfterSuccessAndDeniedCommandsDoNotNotify()
{
Authorize();
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "Live", isPrivate = false });
var id = (await created.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Bob), Times.Once);
Authorize(userId: _db.Alice);
Assert.That((await _client.PostAsync($"/api/groups/{id}/join", null)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Alice), Times.Once);
_notifier.Invocations.Clear();
Assert.That((await _client.PutAsJsonAsync($"/api/groups/{id}", new { name = "Forbidden", isPrivate = false })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Bob}/administrator", null)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Bob}/ban", null)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
Assert.That(_notifier.Invocations, Is.Empty);
Authorize();
Assert.That((await _client.PutAsJsonAsync($"/api/groups/{id}", new { name = "Renamed", isPrivate = true })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(id), Times.Once);
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Alice}/administrator", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _client.DeleteAsync($"/api/groups/{id}/members/{_db.Alice}/administrator")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Alice}/ban", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
Assert.That((await _client.DeleteAsync($"/api/groups/{id}/members/{_db.Alice}/ban")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Alice), Times.Exactly(4));
_notifier.Invocations.Clear();
Assert.That((await _client.PostAsync($"/api/groups/{id}/ownership/{_db.Alice}", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(id), Times.Once);
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Bob), Times.Once);
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Alice), Times.Once);
Assert.That((await _client.DeleteAsync($"/api/groups/{id}/members/me")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Bob), Times.Exactly(2));
}
[Test]
public async Task InvitationPreviewDoesNotNotifyAndSuccessfulJoinDoes()
{
Authorize();
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "Invite", isPrivate = true });
var id = (await created.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
var invitation = await _client.PostAsJsonAsync($"/api/groups/{id}/invitations", new { });
var link = (await invitation.Content.ReadFromJsonAsync<GroupInvitationResponse>())!;
_notifier.Invocations.Clear();
Authorize(userId: _db.Alice);
Assert.That((await _client.GetAsync(link.PreviewPath)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
Assert.That((await _client.PostAsync("/api/group-invites/invalid/join", null)).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
Assert.That(_notifier.Invocations, Is.Empty);
Assert.That((await _client.PostAsync(link.JoinPath, null)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Alice), Times.Once);
}
[Test]
public async Task RequiredChannelChangeNotifiesOldAndNewChannelButFailedChangeDoesNot()
{
ReactionTests.MakeAdmin(_db.Context, _db.Bob);
Authorize(role: "Admin");
var first = await _client.PostAsJsonAsync("/api/groups", new { name = "First", isChannel = true });
var second = await _client.PostAsJsonAsync("/api/groups", new { name = "Second", isChannel = true });
var firstId = (await first.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
var secondId = (await second.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
_notifier.Invocations.Clear();
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = firstId, allowLeave = false })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(firstId), Times.Once);
_notifier.Invocations.Clear();
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = secondId, allowLeave = true })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(firstId), Times.Once);
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(secondId), Times.Once);
_notifier.Invocations.Clear();
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = Guid.NewGuid() })).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
Assert.That(_notifier.Invocations, Is.Empty);
}
private void Authorize(string tokenType = "access", string role = "User", Guid? userId = null)
{
var actorId = userId ?? _db.Bob;
var sessionId = _session;
if (actorId != _db.Bob)
{
var session = new UserSession { UserId = actorId, RefreshTokenHash = Guid.NewGuid().ToString("N"), ExpiresAt = DateTime.UtcNow.AddDays(1) };
_db.Context.UserSessions.Add(session);
_db.Context.SaveChanges();
sessionId = session.Id;
}
var token = new JwtSecurityToken(claims: new[]
{
new Claim("userId", actorId.ToString()), new Claim("sid", sessionId.ToString()),
new Claim("tokenType", tokenType), new Claim(ClaimTypes.Role, role)
}, expires: DateTime.UtcNow.AddMinutes(10),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secret)), SecurityAlgorithms.HmacSha256));
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", new JwtSecurityTokenHandler().WriteToken(token));
}
[Test]
public async Task GroupChangesArriveOverRealSignalRConnectionsForBothParticipants()
{
_client.Dispose();
_factory.Dispose();
_factory = new TestFactory(_db, null);
_client = _factory.CreateClient();
Authorize();
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "Realtime", isPrivate = false });
var id = (await created.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
Authorize(userId: _db.Alice);
await _client.PostAsync($"/api/groups/{id}/join", null);
using var alice = await ConnectHubAsync();
Authorize();
using var bob = await ConnectHubAsync();
Assert.That((await _client.PutAsJsonAsync($"/api/groups/{id}", new { name = "Live profile", isPrivate = true })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
foreach (var connection in new[] { alice, bob })
{
var frame = await connection.ReadAsync();
Assert.That(frame.GetProperty("target").GetString(), Is.EqualTo("GroupProfileChanged"));
Assert.That(frame.GetProperty("arguments")[0].GetProperty("groupId").GetGuid(), Is.EqualTo(id));
}
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Alice}/administrator", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
foreach (var connection in new[] { alice, bob })
{
var frame = await connection.ReadAsync();
Assert.That(frame.GetProperty("target").GetString(), Is.EqualTo("GroupMemberChanged"));
var change = frame.GetProperty("arguments")[0];
Assert.That(change.GetProperty("userId").GetGuid(), Is.EqualTo(_db.Alice));
Assert.That(change.GetProperty("status").GetInt32(), Is.Zero);
Assert.That(change.GetProperty("role").GetInt32(), Is.EqualTo(1));
}
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Alice}/ban", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
foreach (var connection in new[] { alice, bob })
{
var change = (await connection.ReadAsync()).GetProperty("arguments")[0];
Assert.That(change.GetProperty("status").GetInt32(), Is.EqualTo(1));
Assert.That(change.GetProperty("role").ValueKind, Is.EqualTo(JsonValueKind.Null));
}
Authorize(userId: _db.Alice);
Assert.That((await _client.GetAsync($"/api/groups/{id}")).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
}
private async Task<TestHubConnection> ConnectHubAsync()
{
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));
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.
await connection.SendAsync("{\"type\":1,\"invocationId\":\"ready\",\"target\":\"Unknown\",\"arguments\":[]}");
Assert.That((await connection.ReadAsync()).GetProperty("type").GetInt32(), Is.EqualTo(3));
return connection;
}
private sealed class TestHubConnection(WebSocket socket) : IDisposable
{
private string _pending = "";
public Task SendAsync(string json) => socket.SendAsync(Encoding.UTF8.GetBytes(json + '\u001e'), WebSocketMessageType.Text, true, CancellationToken.None);
public async Task<JsonElement> ReadAsync()
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var buffer = new byte[4096];
while (true)
{
var separator = _pending.IndexOf('\u001e');
if (separator >= 0)
{
using var document = JsonDocument.Parse(_pending[..separator]);
_pending = _pending[(separator + 1)..];
if (document.RootElement.TryGetProperty("type", out var type) && type.GetInt32() == 6) continue;
return document.RootElement.Clone();
}
var result = await socket.ReceiveAsync(buffer, timeout.Token);
Assert.That(result.MessageType, Is.EqualTo(WebSocketMessageType.Text));
_pending += Encoding.UTF8.GetString(buffer, 0, result.Count);
}
}
public void Dispose() => socket.Dispose();
}
private sealed class TestFactory(TestDatabase db, IChatNotificationService? notifier) : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Development");
builder.UseSetting("Firebase:Enabled", "false");
builder.UseSetting("JwtAccessOption:SecretKey", Secret);
builder.ConfigureServices(services =>
{
services.AddDataProtection().UseEphemeralDataProtectionProvider();
services.RemoveAll<IDataProtectionProvider>();
services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());
foreach (var registration in services.Where(d => d.ServiceType == typeof(IHostedService) &&
d.ImplementationType?.FullName == "Microsoft.AspNetCore.DataProtection.Internal.DataProtectionHostedService").ToArray())
services.Remove(registration);
var worker = services.Single(d => d.ServiceType == typeof(IHostedService) && d.ImplementationType == typeof(ChatPushWorker));
services.Remove(worker);
services.RemoveAll<DbContextOptions<GovorDbContext>>();
services.RemoveAll<IDbContextOptionsConfiguration<GovorDbContext>>();
services.AddDbContext<GovorDbContext>(db.ConfigureOptions);
if (notifier is not null)
{
services.RemoveAll<IChatNotificationService>();
services.AddSingleton(notifier);
}
services.RemoveAll<IStorageService>();
services.AddSingleton<IStorageService>(new TestReactionStorage());
});
}
}
}
@@ -0,0 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="../../Govor.API/Govor.API.csproj" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.10" />
</ItemGroup>
</Project>
@@ -0,0 +1,267 @@
using Govor.Application.Authentication;
using Govor.Application.Groups;
using Govor.Application.Infrastructure.Common;
using Govor.Application.Infrastructure.Validators;
using Govor.Application.Messages;
using Govor.Application.Messages.Parameters;
using Govor.Application.Reactions;
using Govor.Application.Users;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Govor.Domain.Models.Reactions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Govor.Domain;
using System.Data.Common;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using SmartRes;
namespace Govor.Server.Tests;
[TestFixture]
public class GroupTests
{
private TestDatabase _db = null!;
private GroupManagementService _groups = null!;
private Mock<INowDateTimeProvider> _clock = null!;
private readonly DateTime _now = new(2026, 10, 3, 13, 0, 0, DateTimeKind.Utc);
[SetUp]
public void SetUp()
{
_db = new TestDatabase();
_clock = new Mock<INowDateTimeProvider>();
_clock.SetupGet(c => c.Now).Returns(_now);
_groups = new GroupManagementService(_db.Context, _clock.Object);
}
[TearDown]
public void TearDown() => _db.Dispose();
private async Task<Guid> Create(bool isPrivate = false, bool channel = false) =>
(await _groups.CreateAsync(_db.Alice, "Community", "Description", isPrivate, channel)).Value.Group.Id;
[Test]
public async Task PublicSearchDoesNotExposePrivateGroupsOrPrivateHistory()
{
var publicId = await Create();
var privateId = await Create(isPrivate: true);
Assert.That((await _groups.SearchAsync(_db.Bob, "comm")).Select(g => g.Group.Id), Is.EqualTo(new[] { publicId }));
Assert.That((await _groups.GetAsync(_db.Bob, privateId)).Error.Type, Is.EqualTo(ErrorType.NotFound));
Assert.That((await _groups.JoinPublicAsync(_db.Bob, privateId)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
var before = await new MessagesLoader(_db.Context).LoadMessagesInChatGroup(publicId, _db.Bob, null);
Assert.That(before.Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That((await _groups.JoinPublicAsync(_db.Bob, publicId)).Value.MyRole, Is.EqualTo(GroupRole.Member));
Assert.That((await _groups.MineAsync(_db.Bob)).Single().Group.Id, Is.EqualTo(publicId));
}
[Test]
public async Task InvitationPreviewDoesNotJoinAndUsageDoesNotResetAfterLeaving()
{
var id = await Create(isPrivate: true);
var invite = (await _groups.CreateInvitationAsync(_db.Alice, id, 1, 1, "one use")).Value;
Assert.That((await _groups.PreviewInvitationAsync(_db.Bob, invite.InvitationCode)).IsSuccess, Is.True);
Assert.That(await _db.Context.GroupMemberships.CountAsync(), Is.EqualTo(1));
await _groups.JoinByInvitationAsync(_db.Bob, invite.InvitationCode);
await _groups.JoinByInvitationAsync(_db.Bob, invite.InvitationCode);
Assert.That(await _db.Context.GroupMemberships.CountAsync(), Is.EqualTo(2));
Assert.That((await _groups.InvitationsAsync(_db.Alice, id)).Value.Single().UsedCount, Is.EqualTo(1));
Assert.That((await _groups.JoinByInvitationAsync(_db.Outsider, invite.InvitationCode)).Error.Type, Is.EqualTo(ErrorType.Validation));
await _groups.LeaveAsync(_db.Bob, id);
Assert.That((await _groups.JoinByInvitationAsync(_db.Bob, invite.InvitationCode)).IsFailure, Is.True);
}
[Test]
public async Task ExpiredAndRevokedInvitationsAreRejectedAndMembersCannotIssueThem()
{
var id = await Create();
await _groups.JoinPublicAsync(_db.Bob, id);
Assert.That((await _groups.CreateInvitationAsync(_db.Bob, id, 7, 0, "")).Error.Type, Is.EqualTo(ErrorType.Forbidden));
var invite = (await _groups.CreateInvitationAsync(_db.Alice, id, 1, 0, "")).Value;
await _groups.RevokeInvitationAsync(_db.Alice, id, invite.Id);
Assert.That((await _groups.JoinByInvitationAsync(_db.Outsider, invite.InvitationCode)).IsFailure, Is.True);
var expired = (await _groups.CreateInvitationAsync(_db.Alice, id, 1, 0, "")).Value;
_clock.SetupGet(c => c.Now).Returns(_now.AddDays(2));
Assert.That((await _groups.JoinByInvitationAsync(_db.Outsider, expired.InvitationCode)).IsFailure, Is.True);
}
[Test]
public async Task OwnerControlsProfileAndAdminsCannotEscalateOrBanOwner()
{
var id = await Create();
await _groups.JoinPublicAsync(_db.Bob, id);
await _groups.JoinPublicAsync(_db.Outsider, id);
Assert.That((await _groups.SetAdministratorAsync(_db.Bob, id, _db.Bob, true)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Bob, true);
Assert.That((await _groups.GetAsync(_db.Bob, id)).Value.MyRole, Is.EqualTo(GroupRole.Admin));
Assert.That((await _groups.UpdateAsync(_db.Bob, id, "Hijacked", "", true)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That((await _groups.SetBanAsync(_db.Bob, id, _db.Alice, true)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Outsider, true);
Assert.That((await _groups.SetBanAsync(_db.Bob, id, _db.Outsider, true)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That((await _groups.UpdateAsync(_db.Alice, id, "Renamed", "new", true)).Value.Group.Name, Is.EqualTo("Renamed"));
Assert.That(await _groups.SearchAsync(_db.Bob, ""), Is.Empty);
}
[Test]
public async Task BanBlocksRejoiningHistoryPostingReadingAndReactingAndRemovesAdminRole()
{
var id = await Create();
await _groups.JoinPublicAsync(_db.Bob, id);
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Bob, true);
var invite = (await _groups.CreateInvitationAsync(_db.Alice, id, 7, 0, "")).Value;
var message = _db.AddMessage(chat: id, type: RecipientType.Group);
await _groups.SetBanAsync(_db.Alice, id, _db.Bob, true);
Assert.That(await _db.Context.GroupAdmins.AnyAsync(a => a.UserId == _db.Bob && a.GroupId == id), Is.False);
Assert.That((await _groups.JoinPublicAsync(_db.Bob, id)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That((await _groups.JoinByInvitationAsync(_db.Bob, invite.InvitationCode)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That((await new MessagesLoader(_db.Context).LoadMessagesInChatGroup(id, _db.Bob, null)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That((await Sender().SendMessageAsync(new SendMessage("test", null, id, RecipientType.Group, _db.Bob, _now, []))).IsSuccess, Is.False);
var reader = new MessageReadingService(_db.Context, NullLogger<MessageReadingService>.Instance, _clock.Object);
Assert.That((await reader.ReadMessageAsync(_db.Bob, message.Id)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
var reactions = new MessageReactionService(_db.Context, _clock.Object);
Assert.That((await reactions.SetAsync(_db.Bob, message.Id, DefaultReactionPack.Items()[0].Id)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That((await _groups.MembersAsync(_db.Alice, id, true, 0, 50)).Value.Single().UserId, Is.EqualTo(_db.Bob));
await _groups.SetBanAsync(_db.Alice, id, _db.Bob, false);
Assert.That((await _groups.GetAsync(_db.Bob, id)).Value.MyRole, Is.EqualTo(GroupRole.Member));
Assert.That((await _groups.MineAsync(_db.Bob)).Count, Is.EqualTo(1));
}
[Test]
public async Task OwnerAndAdminCanPostInChannelAndDemotionRevokesPostingAndPolicy()
{
var id = await Create(channel: true);
await _groups.JoinPublicAsync(_db.Bob, id);
Assert.That((await Sender().SendMessageAsync(new SendMessage("owner", null, id, RecipientType.Group, _db.Alice, _now, []))).IsSuccess, Is.True);
Assert.That((await Sender().SendMessageAsync(new SendMessage("member", null, id, RecipientType.Group, _db.Bob, _now, []))).IsSuccess, Is.False);
var reactions = new MessageReactionService(_db.Context, _clock.Object);
Assert.That((await reactions.SetPolicyAsync(_db.Alice, id, ChannelReactionMode.Selected, new[] { DefaultReactionPack.Items()[0].Id })).IsSuccess, Is.True);
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Bob, true);
var post = await Sender().SendMessageAsync(new SendMessage("admin", null, id, RecipientType.Group, _db.Bob, _now, []));
Assert.That(post.IsSuccess, Is.True);
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Bob, false);
Assert.That((await Sender().SendMessageAsync(new SendMessage("demoted", null, id, RecipientType.Group, _db.Bob, _now, []))).IsSuccess, Is.False);
Assert.That((await reactions.SetPolicyAsync(_db.Bob, id, ChannelReactionMode.None, Array.Empty<Guid>())).Error.Type, Is.EqualTo(ErrorType.Forbidden));
var editor = new MessageEditingService(_db.Context, NullLogger<MessageEditingService>.Instance, Options.Create(new MessageEditingOptions()));
Assert.That((await editor.EditMessageAsync(new EditMessage(_db.Bob, post.Message.Id, "demoted edit", _now))).IsSuccess, Is.False);
}
[Test]
public async Task GroupAdminsCanDeleteMembersMessagesButMembersCannotDeleteOthers()
{
var id = await Create();
await _groups.JoinPublicAsync(_db.Bob, id);
await _groups.JoinPublicAsync(_db.Outsider, id);
var message = _db.AddMessage(sender: _db.Outsider, chat: id, type: RecipientType.Group);
var remover = new MessageRemovingService(_db.Context, NullLogger<MessageRemovingService>.Instance);
Assert.That((await remover.DeleteMessageAsync(new DeleteMessage(_db.Bob, message.Id, true))).Error.Type, Is.EqualTo(ErrorType.Forbidden));
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Bob, true);
await _groups.SetBanAsync(_db.Bob, id, _db.Outsider, true);
Assert.That((await remover.DeleteMessageAsync(new DeleteMessage(_db.Bob, message.Id, true))).IsSuccess, Is.True);
Assert.That(await _db.Context.Messages.AnyAsync(m => m.Id == message.Id), Is.False);
}
[Test]
public async Task OwnershipTransferKeepsOwnerUntilAnActiveSuccessorIsChosen()
{
var id = await Create();
Assert.That((await _groups.LeaveAsync(_db.Alice, id)).Error.Type, Is.EqualTo(ErrorType.Validation));
Assert.That((await _groups.TransferOwnershipAsync(_db.Alice, id, _db.Bob)).IsFailure, Is.True);
await _groups.JoinPublicAsync(_db.Bob, id);
await _groups.TransferOwnershipAsync(_db.Alice, id, _db.Bob);
Assert.That((await _groups.GetAsync(_db.Bob, id)).Value.MyRole, Is.EqualTo(GroupRole.Owner));
Assert.That((await _groups.GetAsync(_db.Alice, id)).Value.MyRole, Is.EqualTo(GroupRole.Admin));
Assert.That((await _groups.LeaveAsync(_db.Alice, id)).IsSuccess, Is.True);
Assert.That(await _db.Context.IsGroupAdministratorAsync(id, _db.Alice), Is.False);
}
[Test]
public async Task ServerAdminConfiguresRequiredChannelAndRegistrationJoinsAtomically()
{
var id = await Create(isPrivate: true, channel: true);
Assert.That((await _groups.SetRequiredChannelAsync(_db.Bob, id, false)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
ReactionTests.MakeAdmin(_db.Context, _db.Alice);
await _groups.SetRequiredChannelAsync(_db.Alice, id, false);
var invite = _db.Context.Invitations.Single(i => i.Code == "test");
var registered = await Account().RegistrationAsync("NewUser", "password", invite);
Assert.That(registered.IsSuccess, Is.True);
Assert.That(registered.Value.WasOnline, Is.EqualTo(_now));
Assert.That((await _groups.MineAsync(registered.Value.Id)).Single().Group.Id, Is.EqualTo(id));
Assert.That((await _groups.GetAsync(registered.Value.Id, id)).Value.CanLeave, Is.False);
Assert.That((await _groups.LeaveAsync(registered.Value.Id, id)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
await _groups.SetRequiredChannelAsync(_db.Alice, id, true);
Assert.That((await _groups.LeaveAsync(registered.Value.Id, id)).IsSuccess, Is.True);
Assert.That(await _db.Context.GroupMemberships.AnyAsync(m => m.UserId == _db.Bob && m.GroupId == id), Is.False);
}
[Test]
public async Task RequiredChannelRejectsOrdinaryGroupAndCanBeDisabledForNewRegistrations()
{
ReactionTests.MakeAdmin(_db.Context, _db.Alice);
var groupId = await Create();
Assert.That((await _groups.SetRequiredChannelAsync(_db.Alice, groupId, false)).Error.Type, Is.EqualTo(ErrorType.Validation));
var channelId = await Create(channel: true);
await _groups.SetRequiredChannelAsync(_db.Alice, channelId, false);
await _groups.SetRequiredChannelAsync(_db.Alice, null, true);
var registered = await Account().RegistrationAsync("OtherUser", "password", _db.Context.Invitations.Single(i => i.Code == "test"));
Assert.That(registered.IsSuccess, Is.True);
Assert.That(await _db.Context.GroupMemberships.AnyAsync(m => m.UserId == registered.Value.Id), Is.False);
}
[TestCase(0)]
[TestCase(2)]
public async Task RegistrationFailureDoesNotConsumeInvitationOrCreateMembership(int maxParticipants)
{
ReactionTests.MakeAdmin(_db.Context, _db.Alice);
var id = await Create(channel: true);
await _groups.SetRequiredChannelAsync(_db.Alice, id, false);
var invite = _db.Context.Invitations.Single(i => i.Code == "test");
await _db.Context.Invitations.Where(i => i.Id == invite.Id).ExecuteUpdateAsync(s => s.SetProperty(i => i.MaxParticipants, maxParticipants));
var registered = await Account().RegistrationAsync("Unavailable", "password", invite);
Assert.That(registered.IsFailure, Is.True);
Assert.That(await _db.Context.Users.AnyAsync(u => u.Username == "Unavailable"), Is.False);
Assert.That(await _db.Context.GroupMemberships.CountAsync(m => m.GroupId == id), Is.EqualTo(1));
Assert.That(await _db.Context.Invitations.Where(i => i.Id == invite.Id).Select(i => i.Participants).SingleAsync(), Is.Zero);
}
private MessageSendingService Sender() => new(_db.Context, NullLogger<MessageSendingService>.Instance);
[Test]
public async Task RequiredMembershipWriteFailureRollsBackAccountAndInvitation()
{
ReactionTests.MakeAdmin(_db.Context, _db.Alice);
var id = await Create(channel: true);
await _groups.SetRequiredChannelAsync(_db.Alice, id, false);
var invite = _db.Context.Invitations.Single(i => i.Code == "test");
using var failing = _db.CreateContext(new FailMembershipInsert());
Assert.ThrowsAsync<DbUpdateException>(async () =>
await Account(failing).RegistrationAsync("FailedUser", "password", invite));
Assert.That(await _db.Context.Users.AnyAsync(u => u.Username == "FailedUser"), Is.False);
Assert.That(await _db.Context.Invitations.Where(i => i.Id == invite.Id).Select(i => i.Participants).SingleAsync(), Is.Zero);
Assert.That(await _db.Context.GroupMemberships.CountAsync(m => m.GroupId == id), Is.EqualTo(1));
}
private sealed class FailMembershipInsert : DbCommandInterceptor
{
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command,
CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
{
if (command.CommandText.Contains("INSERT INTO \"GroupMemberships\"", StringComparison.Ordinal))
throw new InvalidOperationException("Simulated required membership persistence failure.");
return ValueTask.FromResult(result);
}
}
private AuthService Account(GovorDbContext? context = null)
{
var username = new Mock<IUsernameValidator>();
username.Setup(v => v.Validate(It.IsAny<string>())).Returns(Govor.Domain.Common.Result.Success());
var exists = new Mock<IUserNameExistValidator>();
exists.Setup(v => v.IsUsernameExistsAsync(It.IsAny<string>())).ReturnsAsync(false);
var hash = new Mock<IPasswordHasher>();
hash.Setup(h => h.Hash(It.IsAny<string>())).Returns("test hash");
return new AuthService(context ?? _db.Context, exists.Object, hash.Object, username.Object, _clock.Object);
}
}
@@ -0,0 +1,41 @@
using Govor.Application.Authentication;
using Govor.Application.Infrastructure.Common;
using Microsoft.EntityFrameworkCore;
using Moq;
namespace Govor.Server.Tests;
[TestFixture]
public class InvitationClockTests
{
[TestCase(-1, false)]
[TestCase(0, false)]
[TestCase(1, true)]
public async Task ExpirationUsesInjectedClockIncludingExactBoundary(int offsetMinutes, bool expectedSuccess)
{
using var db = new TestDatabase();
var now = new DateTime(2026, 11, 1, 12, 0, 0, DateTimeKind.Utc);
var invitation = await db.Context.Invitations.SingleAsync(i => i.Code == "test");
invitation.EndDate = now.AddMinutes(offsetMinutes);
await db.Context.SaveChangesAsync();
var clock = new Mock<INowDateTimeProvider>();
clock.SetupGet(c => c.Now).Returns(now);
var service = new InvitesService(db.Context, clock.Object);
Assert.That((await service.ValidateAsync("test")).IsSuccess, Is.EqualTo(expectedSuccess));
clock.VerifyGet(c => c.Now, Times.Once);
}
[Test]
public async Task InactiveInvitationIsRejectedEvenWhenItExpiresInTheFuture()
{
using var db = new TestDatabase();
var now = new DateTime(2026, 11, 1, 12, 0, 0, DateTimeKind.Utc);
var invitation = await db.Context.Invitations.SingleAsync(i => i.Code == "test");
invitation.IsActive = false;
invitation.EndDate = now.AddDays(1);
await db.Context.SaveChangesAsync();
var clock = new Mock<INowDateTimeProvider>();
clock.SetupGet(c => c.Now).Returns(now);
Assert.That((await new InvitesService(db.Context, clock.Object).ValidateAsync("test")).IsFailure, Is.True);
}
}
@@ -0,0 +1,218 @@
using Govor.Application.Infrastructure.Common;
using Govor.Application.Medias;
using Govor.Application.Messages;
using Govor.Application.Messages.Parameters;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
namespace Govor.Server.Tests;
[TestFixture]
public class MessageAccessTests
{
private TestDatabase _db = null!;
private MessageReadingService _reader = null!;
private readonly DateTime _now = new(2026, 10, 3, 0, 0, 0, DateTimeKind.Utc);
[SetUp]
public void SetUp()
{
_db = new TestDatabase();
var clock = new Mock<INowDateTimeProvider>();
clock.SetupGet(c => c.Now).Returns(_now);
_reader = new MessageReadingService(_db.Context, NullLogger<MessageReadingService>.Instance, clock.Object);
}
[TearDown]
public void TearDown() => _db.Dispose();
[Test]
public async Task OutsiderCannotLoadSendReadOrDownloadPrivateMessages()
{
// The outsider has a different chat; that must not grant access to Alice–Bob.
_db.Context.PrivateChats.Add(new PrivateChat
{ Id = Guid.NewGuid(), UserAId = _db.Outsider, UserBId = _db.Alice });
var message = _db.AddMessage();
var loader = new MessagesLoader(_db.Context);
var loaded = await loader.LoadMessagesInUserChat(_db.ChatId, _db.Outsider, null);
var read = await _reader.ReadMessageAsync(_db.Outsider, message.Id);
var sender = new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance);
var sent = await sender.SendMessageAsync(new SendMessage("intrusion", null, _db.ChatId,
RecipientType.User, _db.Outsider, _now, []));
Assert.Multiple(() =>
{
Assert.That(loaded.Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That(read.Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That(sent.IsSuccess, Is.False);
});
Assert.That(await _db.Context.MessageViews.CountAsync(), Is.Zero);
Assert.That(await _db.Context.Messages.CountAsync(), Is.EqualTo(1));
}
[Test]
public async Task RepeatedSingleReadReturnsTheSameReceipt()
{
var message = _db.AddMessage();
var first = await _reader.ReadMessageAsync(_db.Bob, message.Id);
var second = await _reader.ReadMessageAsync(_db.Bob, message.Id);
Assert.That(first.IsSuccess && second.IsSuccess, Is.True);
Assert.That(second.Value.MessageViews.Single().Id, Is.EqualTo(first.Value.MessageViews.Single().Id));
Assert.That(second.Value.MessageViews.Single().ViewedAt, Is.EqualTo(_now));
Assert.That(await _db.Context.MessageViews.CountAsync(), Is.EqualTo(1));
}
[Test]
public async Task VisibleMessageSelectionDoesNotReadOffscreenOrOwnMessages()
{
var visible = _db.AddMessage();
_db.AddMessage();
_db.AddMessage(_db.Bob);
var result = await _reader.ReadChatAsync(_db.Bob, _db.ChatId, RecipientType.User, [visible.Id]);
Assert.That(result.IsSuccess, Is.True);
Assert.That(result.Value.ReadCount, Is.EqualTo(1));
Assert.That(result.Value.UnreadCount, Is.EqualTo(1));
Assert.That(await _db.Context.MessageViews.CountAsync(), Is.EqualTo(1));
}
[Test]
public async Task InvalidMixedChatSelectionDoesNotPartiallyWrite()
{
var valid = _db.AddMessage();
var other = _db.AddMessage(chat: Guid.NewGuid());
var result = await _reader.ReadChatAsync(_db.Bob, _db.ChatId, RecipientType.User, [valid.Id, other.Id]);
Assert.That(result.IsFailure, Is.True);
Assert.That(await _db.Context.MessageViews.CountAsync(), Is.Zero);
}
[Test]
public async Task ReadThroughBoundaryHandlesEqualTimestampsAndLeavesNewerUnread()
{
var earlier = _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000001"));
var boundary = _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000002"));
_db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000003"));
_db.AddMessage(sentAt: _now.AddSeconds(1));
var result = await _reader.ReadChatAsync(_db.Bob, _db.ChatId, RecipientType.User, upToMessageId: boundary.Id);
Assert.That(result.IsSuccess, Is.True);
Assert.That(result.Value.ReadCount, Is.EqualTo(2));
Assert.That(result.Value.UnreadCount, Is.EqualTo(2));
Assert.That(await _db.Context.MessageViews.AnyAsync(v => v.MessageId == earlier.Id), Is.True);
}
[Test]
public async Task MarkAllReadsMoreThanOneBatchAndSurvivesRepeatedCall()
{
for (var i = 0; i < 205; i++)
_db.AddMessage(sentAt: _now.AddSeconds(i));
_db.AddMessage(_db.Bob, sentAt: _now.AddSeconds(300));
var first = await _reader.ReadChatAsync(_db.Bob, _db.ChatId, RecipientType.User);
var second = await _reader.ReadChatAsync(_db.Bob, _db.ChatId, RecipientType.User);
Assert.That(first.Value.ReadCount, Is.EqualTo(205));
Assert.That(second.Value.ReadCount, Is.Zero);
Assert.That(second.Value.UnreadCount, Is.Zero);
}
[Test]
public async Task GroupReadRequiresMembershipAndExcludesOwnMessages()
{
var group = new ChatGroup { Id = Guid.NewGuid(), Name = "group", Description = "" };
_db.Context.ChatGroups.Add(group);
_db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = group.Id, UserId = _db.Bob });
_db.Context.SaveChanges();
_db.AddMessage(chat: group.Id, type: RecipientType.Group);
_db.AddMessage(_db.Bob, group.Id, RecipientType.Group);
var denied = await _reader.ReadChatAsync(_db.Outsider, group.Id, RecipientType.Group);
var read = await _reader.ReadChatAsync(_db.Bob, group.Id, RecipientType.Group);
Assert.That(denied.Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That(read.Value.ReadCount, Is.EqualTo(1));
Assert.That(read.Value.UnreadCount, Is.Zero);
}
[Test]
public async Task PrivateAttachmentIsAvailableToBothParticipantsOnly()
{
var message = _db.AddMessage();
var file = new MediaFile { Id = Guid.NewGuid(), UploaderId = _db.Alice,
Url = "test", MineType = "image/png", OwnerType = MediaOwnerType.Message };
_db.Context.MediaFiles.Add(file);
_db.Context.MediaAttachments.Add(new MediaAttachments
{ Id = Guid.NewGuid(), MessageId = message.Id, MediaFileId = file.Id });
_db.Context.SaveChanges();
var access = new AccesserToDownloadMediaService(_db.Context);
Assert.That(await access.HasAccessAsync(file.Id, _db.Alice), Is.True);
Assert.That(await access.HasAccessAsync(file.Id, _db.Bob), Is.True);
Assert.That(await access.HasAccessAsync(file.Id, _db.Outsider), Is.False);
}
[Test]
public async Task HideForMeNeverDeletesForEveryone()
{
var message = _db.AddMessage();
var remover = new MessageRemovingService(_db.Context, NullLogger<MessageRemovingService>.Instance);
var result = await remover.DeleteMessageAsync(new DeleteMessage(_db.Alice, message.Id, false));
Assert.That(result.IsFailure, Is.True);
Assert.That(await _db.Context.Messages.AnyAsync(m => m.Id == message.Id), Is.True);
}
[Test]
public async Task SameTimestampHistoryDoesNotSkipMessagesAroundCursor()
{
var earlier = _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000001"));
var cursor = _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000002"));
var later = _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000003"));
var result = await new MessagesLoader(_db.Context).LoadMessagesInUserChat(_db.ChatId, _db.Bob, cursor.Id);
Assert.That(result.Value.Select(m => m.Id), Is.EqualTo(new[] { earlier.Id, cursor.Id, later.Id }));
}
[Test]
public async Task RecipientCannotEditOrDeleteAnotherAuthorsMessage()
{
var message = _db.AddMessage(sentAt: _now);
var editor = new MessageEditingService(_db.Context, NullLogger<MessageEditingService>.Instance,
Microsoft.Extensions.Options.Options.Create(new MessageEditingOptions()));
var edited = await editor.EditMessageAsync(new EditMessage(_db.Bob, message.Id, "changed", _now));
var remover = new MessageRemovingService(_db.Context, NullLogger<MessageRemovingService>.Instance);
var removed = await remover.DeleteMessageAsync(new DeleteMessage(_db.Bob, message.Id, true));
Assert.That(edited.Exception, Is.TypeOf<UnauthorizedAccessException>());
Assert.That(removed.Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That((await _db.Context.Messages.AsNoTracking().SingleAsync()).EncryptedContent, Is.EqualTo("hello"));
}
[Test]
public async Task BannedGroupMemberCannotLoadSendOrReadMessages()
{
var group = new ChatGroup { Id = Guid.NewGuid(), Name = "group", Description = "" };
_db.Context.ChatGroups.Add(group);
_db.Context.GroupMemberships.Add(new GroupMembership
{ Id = Guid.NewGuid(), GroupId = group.Id, UserId = _db.Bob, IsBanned = true });
_db.Context.SaveChanges();
var loaded = await new MessagesLoader(_db.Context).LoadMessagesInChatGroup(group.Id, _db.Bob, null);
var read = await _reader.ReadChatAsync(_db.Bob, group.Id, RecipientType.Group);
var sent = await new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance)
.SendMessageAsync(new SendMessage("hello", null, group.Id, RecipientType.Group, _db.Bob, _now, []));
Assert.That(loaded.Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That(read.Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That(sent.Exception, Is.TypeOf<UnauthorizedAccessException>());
}
[Test]
public async Task ForeignUploadAndReplyFromAnotherChatCannotBeAttached()
{
var file = new MediaFile { Id = Guid.NewGuid(), UploaderId = _db.Bob,
Url = "test", MineType = "image/png", OwnerType = MediaOwnerType.Message };
_db.Context.MediaFiles.Add(file);
_db.Context.SaveChanges();
var sender = new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance);
var attachment = await sender.SendMessageAsync(new SendMessage("hello", null, _db.ChatId,
RecipientType.User, _db.Alice, _now, new[] { new SendMedia(file.Id, "") }));
var other = _db.AddMessage(chat: Guid.NewGuid());
var reply = await sender.SendMessageAsync(new SendMessage("hello", other.Id, _db.ChatId,
RecipientType.User, _db.Alice, _now, []));
Assert.That(attachment.Exception, Is.TypeOf<UnauthorizedAccessException>());
Assert.That(reply.Exception, Is.TypeOf<ArgumentException>());
Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.Zero);
}
}
@@ -0,0 +1,84 @@
using System.Data.Common;
using Govor.Application.Infrastructure.Common;
using Govor.Application.Messages;
using Govor.Domain;
using Govor.Domain.Models.Messages;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
namespace Govor.Server.Tests;
[TestFixture]
public class ReadConcurrencyTests
{
[Test]
public async Task AnotherDeviceCanInsertTheReceiptBetweenSelectionAndWrite()
{
using var db = new TestDatabase();
var message = db.AddMessage();
var clock = new Mock<INowDateTimeProvider>();
clock.SetupGet(c => c.Now).Returns(DateTime.UtcNow);
using var other = db.CreateContext();
var competingReader = new MessageReadingService(other, NullLogger<MessageReadingService>.Instance, clock.Object);
var interceptor = new BeforeReceiptInsert(async () =>
{
var result = await competingReader.ReadMessageAsync(db.Bob, message.Id);
Assert.That(result.IsSuccess, Is.True);
});
using var first = db.CreateContext(interceptor);
var reader = new MessageReadingService(first, NullLogger<MessageReadingService>.Instance, clock.Object);
var read = await reader.ReadChatAsync(db.Bob, db.ChatId, RecipientType.User, new[] { message.Id });
Assert.That(read.IsSuccess, Is.True);
Assert.That(read.Value.ReadCount, Is.Zero);
Assert.That(await db.Context.MessageViews.CountAsync(), Is.EqualTo(1));
}
[Test]
public async Task MessageRemovedBetweenSelectionAndWriteDoesNotCreateOrphanReceipt()
{
using var db = new TestDatabase();
var message = db.AddMessage();
var clock = new Mock<INowDateTimeProvider>();
clock.SetupGet(c => c.Now).Returns(DateTime.UtcNow);
using var other = db.CreateContext();
var interceptor = new BeforeReceiptInsert(async () =>
await other.Messages.Where(m => m.Id == message.Id).ExecuteDeleteAsync());
using var first = db.CreateContext(interceptor);
var reader = new MessageReadingService(first, NullLogger<MessageReadingService>.Instance, clock.Object);
var read = await reader.ReadChatAsync(db.Bob, db.ChatId, RecipientType.User, new[] { message.Id });
Assert.That(read.IsSuccess, Is.True);
Assert.That(read.Value.ReadCount, Is.Zero);
Assert.That(await db.Context.MessageViews.CountAsync(), Is.Zero);
}
[Test]
public void ReadBoundaryQueryTranslatesForPostgreSql()
{
using var db = new GovorDbContext(new DbContextOptionsBuilder<GovorDbContext>()
.UseNpgsql("Host=localhost;Database=translation_tests;Username=tests").Options);
var boundary = Guid.NewGuid();
var sentAt = DateTime.UtcNow;
var sql = db.Messages.Where(m => m.SentAt < sentAt ||
(m.SentAt == sentAt && m.Id.CompareTo(boundary) <= 0))
.OrderBy(m => m.SentAt).ThenBy(m => m.Id).ToQueryString();
Assert.That(sql, Does.Contain("ORDER BY"));
}
// Deterministically interleave a competing device/deletion after SELECT, before INSERT.
private sealed class BeforeReceiptInsert(Func<Task> callback) : DbCommandInterceptor
{
private bool _invoked;
public override async ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command,
CommandEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
if (!_invoked && command.CommandText.StartsWith("INSERT INTO \"MessageViews\"", StringComparison.Ordinal))
{
_invoked = true;
await callback();
}
return result;
}
}
}
@@ -0,0 +1,124 @@
using System.Collections.Concurrent;
using System.Net;
using System.Text;
using System.Text.Json;
using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Http;
using Govor.Application.Interfaces.PushNotifications.Models;
using Govor.Application.PushNotifications.Providers;
using Microsoft.Extensions.Logging.Abstractions;
namespace Govor.Server.Tests;
[TestFixture]
public class FirebasePushProviderTests
{
private FirebaseApp _app = null!;
private FirebasePushProvider _provider = null!;
private readonly ConcurrentQueue<JsonElement> _requests = new();
private HttpStatusCode _status;
private string _response = "";
[SetUp]
public void SetUp()
{
_requests.Clear();
_status = HttpStatusCode.OK;
_response = """{"name":"projects/test/messages/accepted"}""";
_app = FirebaseApp.Create(new AppOptions
{
ProjectId = "test",
Credential = GoogleCredential.FromAccessToken("test-access-token"),
HttpClientFactory = new StubHttpFactory(async request =>
{
using var json = JsonDocument.Parse(await request.Content!.ReadAsStringAsync());
_requests.Enqueue(json.RootElement.GetProperty("message").Clone());
return new HttpResponseMessage(_status) { Content = new StringContent(_response, Encoding.UTF8, "application/json") };
})
}, Guid.NewGuid().ToString());
_provider = new FirebasePushProvider(NullLogger<FirebasePushProvider>.Instance, FirebaseMessaging.GetMessaging(_app));
}
[TearDown]
public void TearDown() => _app.Delete();
[TestCase(false)]
[TestCase(true)]
public async Task SingleAndMulticastUseEquivalentPlatformPayloads(bool multicast)
{
var message = new PushMessage { Title = "Alice", Body = "New message", ChannelId = "chat_messages",
Tag = "chat_123", Data = new() { ["messageId"] = "123" } };
var result = multicast
? await _provider.SendMulticastAsync(new[] { "device", "device" }, message)
: await _provider.SendToTokenAsync("device", message);
Assert.That(result.SuccessCount, Is.EqualTo(1));
var sent = _requests.Single();
Assert.That(sent.GetProperty("token").GetString(), Is.EqualTo("device"));
Assert.That(sent.GetProperty("data").GetProperty("messageId").GetString(), Is.EqualTo("123"));
Assert.That(sent.GetProperty("android").GetProperty("priority").GetString(), Is.EqualTo("high"));
var android = sent.GetProperty("android").GetProperty("notification");
Assert.That(android.GetProperty("channel_id").GetString(), Is.EqualTo("chat_messages"));
Assert.That(android.GetProperty("tag").GetString(), Is.EqualTo("chat_123"));
var apns = sent.GetProperty("apns");
Assert.That(apns.GetProperty("headers").GetProperty("apns-push-type").GetString(), Is.EqualTo("alert"));
Assert.That(apns.GetProperty("payload").GetProperty("aps").GetProperty("thread-id").GetString(), Is.EqualTo("chat_123"));
Assert.That(sent.GetProperty("webpush").GetProperty("notification").GetProperty("tag").GetString(), Is.EqualTo("chat_123"));
}
[Test]
public async Task LargeMulticastBatchesDistinctTokensAndUsesDefaultPlatformChannel()
{
var tokens = Enumerable.Range(0, 501).Select(i => "device-" + i).ToArray();
var result = await _provider.SendMulticastAsync(tokens.Append(tokens[0]).ToArray(), new PushMessage { Title = "test", Body = "test" });
Assert.That(result.SuccessCount, Is.EqualTo(501));
Assert.That(result.FailureCount, Is.Zero);
Assert.That(_requests.Select(r => r.GetProperty("token").GetString()), Is.EquivalentTo(tokens));
Assert.That(_requests.First().GetProperty("android").GetProperty("notification").GetProperty("channel_id").GetString(), Is.EqualTo("chat_messages"));
Assert.That((await _provider.SendMulticastAsync(Array.Empty<string>(), new PushMessage())).SuccessCount, Is.Zero);
}
[TestCase("UNREGISTERED", HttpStatusCode.NotFound, true)]
[TestCase("INVALID_ARGUMENT", HttpStatusCode.BadRequest, false)]
public async Task SingleDeliveryInvalidatesOnlyPermanentlyUnregisteredDevice(string code, HttpStatusCode status, bool permanent)
{
_status = status;
_response = JsonSerializer.Serialize(new { error = new { code = (int)status, message = "FCM failure",
status = status == HttpStatusCode.NotFound ? "NOT_FOUND" : "INVALID_ARGUMENT",
details = new[] { new Dictionary<string, string> { ["@type"] = "type.googleapis.com/google.firebase.fcm.v1.FcmError", ["errorCode"] = code } } } });
if (permanent)
{
var result = await _provider.SendToTokenAsync("device", new PushMessage { Title = "test", Body = "test" });
Assert.That(result.SuccessCount, Is.Zero);
Assert.That(result.FailedTokens, Is.EqualTo(new[] { "device" }));
}
else Assert.ThrowsAsync<FirebaseMessagingException>(() => _provider.SendToTokenAsync("device", new PushMessage { Title = "test", Body = "test" }));
}
[TestCase("UNREGISTERED", HttpStatusCode.NotFound, true)]
[TestCase("INVALID_ARGUMENT", HttpStatusCode.BadRequest, false)]
[TestCase("SENDER_ID_MISMATCH", HttpStatusCode.Forbidden, false)]
public async Task MulticastInvalidatesOnlyUnregisteredTokens(string code, HttpStatusCode status, bool invalid)
{
_status = status;
_response = JsonSerializer.Serialize(new { error = new { code = (int)status, message = "FCM failure",
status = status == HttpStatusCode.NotFound ? "NOT_FOUND" : status == HttpStatusCode.BadRequest ? "INVALID_ARGUMENT" : "PERMISSION_DENIED",
details = new[] { new Dictionary<string, string> { ["@type"] = "type.googleapis.com/google.firebase.fcm.v1.FcmError", ["errorCode"] = code } } } });
var result = await _provider.SendMulticastAsync(new[] { "device" }, new PushMessage { Title = "test", Body = "test" });
Assert.That(result.FailureCount, Is.EqualTo(1));
Assert.That(result.FailedTokens, Is.EqualTo(invalid ? new[] { "device" } : Array.Empty<string>()));
}
private sealed class StubHttpFactory(Func<HttpRequestMessage, Task<HttpResponseMessage>> send) : Google.Apis.Http.HttpClientFactory
{
protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args) => new StubHandler(send);
}
private sealed class StubHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> send) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => send(request);
}
}
@@ -0,0 +1,264 @@
using Govor.API.Hubs;
using Govor.API.Hubs.Infrastructure;
using Govor.Application.PrivateUserChats;
using Govor.Application.Profiles;
using Govor.Application.PushNotifications;
using Govor.Contracts.Responses.SignalR;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Govor.Domain.Models.Users;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using SmartRes;
namespace Govor.Server.Tests;
[TestFixture]
public class NotificationTests
{
private TestDatabase _db = null!;
private Mock<IPushNotificationService> _push = null!;
private Mock<IClientProxy> _proxy = null!;
private ChatNotificationService _notifier = null!;
private readonly List<(string Method, string[] Groups, object Payload)> _events = [];
private string[] _targetGroups = [];
private Guid _aliceSession;
private Guid _bobSession;
[SetUp]
public void SetUp()
{
_db = new TestDatabase();
_events.Clear();
_aliceSession = AddSession(_db.Alice);
_bobSession = AddSession(_db.Bob);
AddSession(_db.Bob, revoked: true);
AddSession(_db.Outsider);
_proxy = new Mock<IClientProxy>();
_proxy.Setup(p => p.SendCoreAsync(It.IsAny<string>(), It.IsAny<object?[]>(), It.IsAny<CancellationToken>()))
.Callback<string, object?[], CancellationToken>((method, args, _) => _events.Add((method, _targetGroups, args[0]!)))
.Returns(Task.CompletedTask);
var clients = new Mock<IHubClients>();
clients.Setup(c => c.Groups(It.IsAny<IReadOnlyList<string>>()))
.Callback<IReadOnlyList<string>>(groups => _targetGroups = groups.ToArray())
.Returns(_proxy.Object);
var hub = new Mock<IHubContext<ChatsHub>>();
hub.SetupGet(h => h.Clients).Returns(clients.Object);
var chats = new Mock<IUserPrivateChatsGetterService>();
chats.Setup(c => c.GetPrivateChatAsync(_db.ChatId))
.ReturnsAsync(Result<PrivateChat, Error>.Success(_db.Context.PrivateChats.Single()));
var profiles = new Mock<IProfileService>();
profiles.Setup(p => p.GetUserProfileAsync(_db.Alice))
.ReturnsAsync(Result<UserProfile, Error>.Success(new UserProfile { Id = _db.Alice, Username = "Alice" }));
_push = new Mock<IPushNotificationService>();
_push.Setup(p => p.SendToUsersAsync(It.IsAny<IEnumerable<Guid>>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>?>()))
.ReturnsAsync(Govor.Domain.Common.Result.Success());
_notifier = new ChatNotificationService(hub.Object, _push.Object, chats.Object, profiles.Object,
_db.Context, NullLogger<ChatNotificationService>.Instance);
}
[TearDown]
public void TearDown() => _db.Dispose();
[Test]
public async Task PrivateMessageReachesBothActiveSessionsAndPushGoesOnlyToRecipient()
{
var message = Message();
await _notifier.NotifyMessageSentAsync(message);
await _notifier.DeliverPushAsync(message);
Assert.That(_events.Single(e => e.Method == ChatHubConstants.ReceiveMessage).Groups,
Is.EquivalentTo(new[] { ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) }));
Assert.That(_events.Single(e => e.Method == ChatHubConstants.MessageSent).Groups,
Is.EqualTo(new[] { ChatHubConstants.GetSessionGroup(_aliceSession) }));
_push.Verify(p => p.SendToUsersAsync(It.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(new[] { _db.Bob })),
"Alice", "New message", "chat_messages", $"chat_{_db.ChatId}",
It.Is<Dictionary<string, string>?>(data => data != null && data["messageId"] == message.MessageId.ToString())), Times.Once);
}
[Test]
public async Task GroupMessageExcludesBannedMembersFromSignalRAndPush()
{
var group = new ChatGroup { Id = Guid.NewGuid(), Name = "group", Description = "" };
_db.Context.ChatGroups.Add(group);
foreach (var user in new[] { _db.Alice, _db.Bob, _db.Outsider })
_db.Context.GroupMemberships.Add(new GroupMembership
{ Id = Guid.NewGuid(), GroupId = group.Id, UserId = user, IsBanned = user == _db.Outsider });
_db.Context.SaveChanges();
var message = Message();
message.RecipientId = group.Id;
message.RecipientType = RecipientType.Group;
await _notifier.NotifyMessageSentAsync(message);
await _notifier.DeliverPushAsync(message);
Assert.That(_events.Single(e => e.Method == ChatHubConstants.ReceiveMessage).Groups.Length, Is.EqualTo(2));
_push.Verify(p => p.SendToUsersAsync(It.Is<IEnumerable<Guid>>(ids => ids.SequenceEqual(new[] { _db.Bob })),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<Dictionary<string, string>?>()), Times.Once);
}
[Test]
public async Task MessageReadBeforeRetrySuppressesPush()
{
var saved = _db.AddMessage();
_db.Context.MessageViews.Add(new MessageView
{ Id = Guid.NewGuid(), MessageId = saved.Id, UserId = _db.Bob, ViewedAt = DateTime.UtcNow });
await _db.Context.SaveChangesAsync();
var message = Message();
message.MessageId = saved.Id;
Assert.That(await _notifier.DeliverPushAsync(message), Is.True);
_push.Verify(p => p.SendToUsersAsync(It.IsAny<IEnumerable<Guid>>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>?>()), Times.Never);
}
[Test]
public async Task PushDoesNotExposeContentAndKeepsRoutingData()
{
var message = Message();
message.EncryptedContent = "sensitive plaintext or ciphertext";
Assert.That(await _notifier.DeliverPushAsync(message), Is.True);
_push.Verify(p => p.SendToUsersAsync(It.IsAny<IEnumerable<Guid>>(), "Alice", "New message",
"chat_messages", $"chat_{_db.ChatId}", It.Is<Dictionary<string, string>?>(data => data != null &&
data["type"] == "chat_message" && data["senderId"] == _db.Alice.ToString() &&
data["chatId"] == _db.ChatId.ToString() && data["isGroup"] == "false" &&
data["messageId"] == message.MessageId.ToString() && !data.Values.Contains(message.EncryptedContent))), Times.Once);
}
[Test]
public async Task SignalRFailureStillAttemptsPushAndProviderFailureDoesNotFailSavedSend()
{
_proxy.Setup(p => p.SendCoreAsync(It.IsAny<string>(), It.IsAny<object?[]>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException("offline"));
_push.Setup(p => p.SendToUsersAsync(It.IsAny<IEnumerable<Guid>>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>?>()))
.ThrowsAsync(new InvalidOperationException("provider unavailable"));
await _notifier.NotifyMessageSentAsync(Message());
Assert.That(await _notifier.DeliverPushAsync(Message()), Is.False);
_push.Verify(p => p.SendToUsersAsync(It.IsAny<IEnumerable<Guid>>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>?>()), Times.Once);
}
[Test]
public async Task ReadNotificationReachesReaderAndAuthorDevices()
{
await _notifier.NotifyChatReadAsync(new ChatReadResponse { ChatId = _db.ChatId, ReaderId = _db.Bob, RecipientType = RecipientType.User });
Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.ChatRead));
Assert.That(_events.Single().Groups, Is.EquivalentTo(new[]
{ ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) }));
}
[Test]
public async Task ReactionChangesReachBothParticipantsActiveDevices()
{
await _notifier.NotifyMessageReactionsChangedAsync(new MessageReactionsChangedResponse
{ MessageId = Guid.NewGuid(), RecipientId = _db.ChatId, RecipientType = RecipientType.User, ActorId = _db.Bob });
Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.MessageReactionsChanged));
Assert.That(_events.Single().Groups, Is.EquivalentTo(new[]
{ ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) }));
}
[Test]
public async Task ChannelPolicyChangesExcludeBannedMembers()
{
var group = new ChatGroup { Id = Guid.NewGuid(), Name = "channel", Description = "", IsChannel = true };
_db.Context.ChatGroups.Add(group);
foreach (var user in new[] { _db.Alice, _db.Bob, _db.Outsider })
_db.Context.GroupMemberships.Add(new GroupMembership
{ Id = Guid.NewGuid(), GroupId = group.Id, UserId = user, IsBanned = user == _db.Outsider });
await _db.Context.SaveChangesAsync();
await _notifier.NotifyChannelReactionPolicyChangedAsync(new ChannelReactionPolicyResponse { GroupId = group.Id });
Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.ChannelReactionPolicyChanged));
Assert.That(_events.Single().Groups, Is.EquivalentTo(new[]
{ ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) }));
}
[Test]
public async Task GroupProfileChangeReachesAllActiveDevicesWithoutLeakingToBannedOrForeignUsers()
{
var group = AddGroup();
var secondDevice = AddSession(_db.Bob);
var expired = AddSession(_db.Bob);
await _db.Context.UserSessions.Where(s => s.Id == expired)
.ExecuteUpdateAsync(s => s.SetProperty(s => s.ExpiresAt, DateTime.UtcNow.AddMinutes(-1)));
await _notifier.NotifyGroupProfileChangedAsync(group.Id);
Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.GroupProfileChanged));
Assert.That(_events.Single().Groups, Is.EquivalentTo(new[]
{
ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession),
ChatHubConstants.GetSessionGroup(secondDevice)
}));
Assert.That(((GroupProfileChangedResponse)_events.Single().Payload).GroupId, Is.EqualTo(group.Id));
}
[TestCase(GroupMemberStatus.Active, GroupRole.Member)]
[TestCase(GroupMemberStatus.Active, GroupRole.Admin)]
[TestCase(GroupMemberStatus.Active, GroupRole.Owner)]
[TestCase(GroupMemberStatus.Banned, null)]
[TestCase(GroupMemberStatus.Left, null)]
public async Task MembershipEventReportsCommittedStatusAndStillReachesAffectedUser(GroupMemberStatus status, GroupRole? role)
{
var group = AddGroup();
if (status == GroupMemberStatus.Banned)
await _db.Context.GroupMemberships.Where(m => m.GroupId == group.Id && m.UserId == _db.Bob)
.ExecuteUpdateAsync(s => s.SetProperty(m => m.IsBanned, true));
if (status == GroupMemberStatus.Left)
await _db.Context.GroupMemberships.Where(m => m.GroupId == group.Id && m.UserId == _db.Bob).ExecuteDeleteAsync();
if (role == GroupRole.Admin)
{
_db.Context.GroupAdmins.Add(new GroupAdmins { Id = Guid.NewGuid(), GroupId = group.Id, UserId = _db.Bob });
await _db.Context.SaveChangesAsync();
}
if (role == GroupRole.Owner)
await _db.Context.ChatGroups.Where(g => g.Id == group.Id).ExecuteUpdateAsync(s => s.SetProperty(g => g.OwnerUserId, _db.Bob));
await _notifier.NotifyGroupMemberChangedAsync(group.Id, _db.Bob);
var change = (GroupMemberChangedResponse)_events.Single().Payload;
Assert.That(change.GroupId, Is.EqualTo(group.Id));
Assert.That(change.UserId, Is.EqualTo(_db.Bob));
Assert.That(change.Status, Is.EqualTo(status));
Assert.That(change.Role, Is.EqualTo(role));
Assert.That(_events.Single().Groups, Is.EquivalentTo(new[]
{ ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) }));
_events.Clear();
await _notifier.NotifyGroupProfileChangedAsync(group.Id);
Assert.That(_events.Single().Groups.Contains(ChatHubConstants.GetSessionGroup(_bobSession)),
Is.EqualTo(status == GroupMemberStatus.Active));
}
[Test]
public async Task GroupEventDeliveryFailureDoesNotFailTheAlreadyCommittedOperation()
{
var group = AddGroup();
_proxy.Setup(p => p.SendCoreAsync(It.IsAny<string>(), It.IsAny<object?[]>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException("offline"));
await _notifier.NotifyGroupProfileChangedAsync(group.Id);
await _notifier.NotifyGroupMemberChangedAsync(group.Id, _db.Bob);
await _notifier.NotifyUserJoinedGroupsAsync(_db.Bob);
}
private ChatGroup AddGroup()
{
var group = new ChatGroup { Id = Guid.NewGuid(), Name = "Private", Description = "", IsPrivate = true, OwnerUserId = _db.Alice };
_db.Context.ChatGroups.Add(group);
foreach (var userId in new[] { _db.Alice, _db.Bob, _db.Outsider })
_db.Context.GroupMemberships.Add(new GroupMembership
{ Id = Guid.NewGuid(), GroupId = group.Id, UserId = userId, IsBanned = userId == _db.Outsider });
_db.Context.SaveChanges();
return group;
}
private Guid AddSession(Guid userId, bool revoked = false)
{
var session = new UserSession { UserId = userId, RefreshTokenHash = Guid.NewGuid().ToString(), IsRevoked = revoked, ExpiresAt = DateTime.UtcNow.AddDays(1) };
_db.Context.UserSessions.Add(session);
_db.Context.SaveChanges();
return session.Id;
}
private UserMessageResponse Message() => new()
{
MessageId = Guid.NewGuid(), SenderId = _db.Alice, RecipientId = _db.ChatId,
RecipientType = RecipientType.User, EncryptedContent = "hello"
};
}
@@ -0,0 +1,99 @@
using Govor.Application.Interfaces.PushNotifications.Models;
using Govor.Application.PushNotifications;
using Govor.Application.PushNotifications.Providers;
using Govor.Domain.Common;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using SmartRes;
namespace Govor.Server.Tests;
[TestFixture]
public class PushDeliveryTests
{
private Mock<IPushTokenService> _tokens = null!;
private Mock<IPushNotificationProvider> _provider = null!;
private PushNotificationService _service = null!;
private Guid _user;
[SetUp]
public void SetUp()
{
_user = Guid.NewGuid();
_tokens = new Mock<IPushTokenService>(MockBehavior.Strict);
_provider = new Mock<IPushNotificationProvider>(MockBehavior.Strict);
_service = new PushNotificationService(_provider.Object, _tokens.Object,
NullLogger<PushNotificationService>.Instance);
}
[Test]
public async Task MulticastDeduplicatesAndContinuesAfterOneBatchFails()
{
var tokens = Enumerable.Range(0, 501).Select(i => $"token-{i}").ToList();
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_user))
.ReturnsAsync(Result<List<string>, Error>.Success(tokens.Concat(tokens).ToList()));
_provider.Setup(p => p.SendMulticastAsync(It.Is<IReadOnlyList<string>>(t => t.Count == 500), It.IsAny<PushMessage>()))
.ThrowsAsync(new HttpRequestException("Provider unavailable"));
_provider.Setup(p => p.SendMulticastAsync(It.Is<IReadOnlyList<string>>(t => t.Count == 1 && t[0] == "token-500"), It.IsAny<PushMessage>()))
.ReturnsAsync(new SendPushResult(1, 0, []));
var result = await _service.SendToUserAsync(_user, "title", "body", "chat_messages");
Assert.That(result.IsFailure, Is.True);
_provider.VerifyAll();
_tokens.Verify(t => t.RemoveTokensAsync(It.IsAny<IEnumerable<string>>()), Times.Never);
}
[TestCase(1, true)]
[TestCase(2, false)]
public async Task OnlyUnregisteredTokensAreRemovedAndTemporaryFailuresRequireRetry(int failures, bool success)
{
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_user))
.ReturnsAsync(Result<List<string>, Error>.Success(["good", "unregistered", "temporary"]));
_provider.Setup(p => p.SendMulticastAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<PushMessage>()))
.ReturnsAsync(new SendPushResult(3 - failures, failures, ["unregistered"]));
_tokens.Setup(t => t.RemoveTokensAsync(It.Is<IEnumerable<string>>(t => t.SequenceEqual(new[] { "unregistered" }))))
.ReturnsAsync(Govor.Domain.Common.Result.Success());
var result = await _service.SendToUserAsync(_user, "title", "body", "chat_messages");
Assert.That(result.IsSuccess, Is.EqualTo(success));
_tokens.VerifyAll();
}
[Test]
public async Task FailedCleanupIsNotAcknowledgedForEitherSingleOrMulticastDelivery()
{
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_user))
.ReturnsAsync(Result<List<string>, Error>.Success(["unregistered"]));
_tokens.Setup(t => t.GetActiveTokenBySessionAsync(_user))
.ReturnsAsync(Result<string?, Error>.Success("unregistered"));
_tokens.Setup(t => t.RemoveTokensAsync(It.IsAny<IEnumerable<string>>()))
.ReturnsAsync(Govor.Domain.Common.Result.Failure(Error.ServerError("Test.Cleanup", "Unavailable")));
_provider.Setup(p => p.SendMulticastAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<PushMessage>()))
.ReturnsAsync(new SendPushResult(0, 1, ["unregistered"]));
_provider.Setup(p => p.SendToTokenAsync("unregistered", It.IsAny<PushMessage>()))
.ReturnsAsync(new SendPushResult(0, 1, ["unregistered"]));
Assert.That((await _service.SendToUserAsync(_user, "title", "body", "chat_messages")).IsFailure, Is.True);
Assert.That((await _service.SendToSessionAsync(_user, "title", "body", "chat_messages")).IsFailure, Is.True);
}
[Test]
public async Task IncompleteProviderResponseDoesNotLoseTheNotification()
{
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_user))
.ReturnsAsync(Result<List<string>, Error>.Success(["token"]));
_provider.Setup(p => p.SendMulticastAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<PushMessage>()))
.ReturnsAsync(new SendPushResult(0, 0, []));
Assert.That((await _service.SendToUserAsync(_user, "title", "body", "chat_messages")).IsFailure, Is.True);
}
[Test]
public async Task NoTokensIsSuccessfulWithoutContactingProvider()
{
_tokens.Setup(t => t.GetStringsActiveTokensAsync(_user))
.ReturnsAsync(Result<List<string>, Error>.Success([]));
Assert.That((await _service.SendToUserAsync(_user, "title", "body", "chat_messages")).IsSuccess, Is.True);
_provider.VerifyNoOtherCalls();
}
}
@@ -0,0 +1,192 @@
using Govor.API.Hubs.Infrastructure;
using Govor.Application.Infrastructure.Common;
using Govor.Application.Messages;
using Govor.Application.Messages.Parameters;
using Govor.Application.Profiles;
using Govor.Application.PushNotifications;
using Govor.Contracts.Responses.SignalR;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Users;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
namespace Govor.Server.Tests;
[TestFixture]
public class PushReliabilityTests
{
private TestDatabase _db = null!;
private Mock<INowDateTimeProvider> _clock = null!;
private PushTokenService _tokens = null!;
private DateTime _now;
[SetUp]
public void SetUp()
{
_db = new TestDatabase();
_now = DateTime.UtcNow.AddMinutes(1);
_now = _now.AddTicks(-(_now.Ticks % TimeSpan.TicksPerMicrosecond));
_clock = new Mock<INowDateTimeProvider>();
_clock.SetupGet(c => c.Now).Returns(() => _now);
_tokens = new PushTokenService(_db.Context, _clock.Object, NullLogger<PushTokenService>.Instance);
}
[TearDown]
public void TearDown() => _db.Dispose();
[Test]
public async Task SavedMessageHasDurablePushAndFailureRetriesAfterBackoff()
{
var sender = new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance);
var sent = await sender.SendMessageAsync(new SendMessage(await EncryptedHelloAsync(), null, _db.ChatId,
Govor.Domain.Models.Messages.RecipientType.User, _db.Alice, _now, []));
Assert.That(sent.IsSuccess, Is.True);
Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.EqualTo(1));
var notifier = new Mock<IChatNotificationService>();
notifier.SetupSequence(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>())).ReturnsAsync(false).ReturnsAsync(true);
var dispatcher = new ChatPushDispatcher(_db.Context, notifier.Object, _clock.Object);
await dispatcher.DispatchAsync();
var pending = await _db.Context.ChatPushNotifications.AsNoTracking().SingleAsync();
Assert.That(pending.Attempts, Is.EqualTo(1));
Assert.That(pending.NextAttemptAt, Is.GreaterThan(_now));
await dispatcher.DispatchAsync();
notifier.Verify(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>()), Times.Once);
_now = pending.NextAttemptAt.AddSeconds(1);
// A new scope simulates worker restart, while the queued row remains durable.
using var restarted = _db.CreateContext();
await new ChatPushDispatcher(restarted, notifier.Object, _clock.Object).DispatchAsync();
notifier.Verify(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>()), Times.Exactly(2));
Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.Zero);
}
private async Task<string> EncryptedHelloAsync()
{
var directory = new Govor.Application.E2ee.E2eeService(_db.Context);
var devices = new List<Govor.Application.E2ee.DeviceKey>();
var privateKeys = Govor.Application.E2ee.E2eeProtocol.GenerateKeys();
foreach (var user in new[] { _db.Alice, _db.Bob })
{
var session = new UserSession { UserId = user, RefreshTokenHash = Guid.NewGuid().ToString(),
ExpiresAt = DateTime.UtcNow.AddDays(30) };
_db.Context.UserSessions.Add(session);
await _db.Context.SaveChangesAsync();
var key = Govor.Application.E2ee.E2eeProtocol.PublicKey(user == _db.Alice ? privateKeys :
Govor.Application.E2ee.E2eeProtocol.GenerateKeys(), user, session.Id);
await directory.RegisterAsync(user, session.Id, key);
devices.Add(key);
}
return Govor.Application.E2ee.E2eeProtocol.Encrypt(new("hello", []), privateKeys, devices[0],
await directory.GetConversationKeysAsync(_db.Alice, _db.ChatId, Govor.Domain.Models.Messages.RecipientType.User), Guid.NewGuid());
}
[Test]
public async Task ReassignedDeviceTokenCannotNotifyThePreviousAccount()
{
var aliceSession = AddSession(_db.Alice);
var bobSession = AddSession(_db.Bob);
await _tokens.AddOrUpdateTokenAsync(_db.Alice, aliceSession, "device-token", "android");
await _tokens.AddOrUpdateTokenAsync(_db.Bob, bobSession, "other-token", "android");
var result = await _tokens.AddOrUpdateTokenAsync(_db.Bob, bobSession, "device-token", "ios");
Assert.That(result.IsSuccess, Is.True);
Assert.That((await _tokens.GetStringsActiveTokensAsync(_db.Alice)).Value, Is.Empty);
Assert.That((await _tokens.GetStringsActiveTokensAsync(_db.Bob)).Value, Is.EqualTo(new[] { "device-token" }));
Assert.That(await _db.Context.UserPushTokens.CountAsync(), Is.EqualTo(1));
}
[Test]
public async Task InactiveTokenCanBeReactivatedButForeignSessionCannotRegisterIt()
{
var session = AddSession(_db.Bob);
await _tokens.AddOrUpdateTokenAsync(_db.Bob, session, "token", "android");
await _tokens.DeactivateTokenBySessionAsync(session);
_db.Context.ChangeTracker.Clear();
Assert.That((await _tokens.GetStringsActiveTokensAsync(_db.Bob)).Value, Is.Empty);
await _tokens.AddOrUpdateTokenAsync(_db.Bob, session, "token", "android");
Assert.That((await _tokens.GetStringsActiveTokensAsync(_db.Bob)).Value, Has.Count.EqualTo(1));
var foreign = await _tokens.AddOrUpdateTokenAsync(_db.Alice, session, "stolen", "android");
Assert.That(foreign.Error.Type, Is.EqualTo(ErrorType.Forbidden));
}
[Test]
public async Task ExpiredOrRevokedSessionTokensAreExcludedWithoutWaitingForCleanup()
{
var session = AddSession(_db.Bob);
await _tokens.AddOrUpdateTokenAsync(_db.Bob, session, "token", "android");
await _db.Context.UserSessions.Where(s => s.Id == session)
.ExecuteUpdateAsync(s => s.SetProperty(row => row.IsRevoked, true));
Assert.That((await _tokens.GetStringsActiveTokensAsync(_db.Bob)).Value, Is.Empty);
Assert.That((await _tokens.GetUsersStringsActiveTokensAsync(new[] { _db.Bob })).Value, Is.Empty);
Assert.That((await _tokens.GetActiveTokenBySessionAsync(session)).Value, Is.Null);
}
[Test]
public async Task ForeignAttachmentCannotBePublishedAsAnAvatar()
{
var media = new MediaFile { Id = Guid.NewGuid(), UploaderId = _db.Alice,
OwnerType = MediaOwnerType.Message, Url = "test", MineType = "image/png" };
_db.Context.MediaFiles.Add(media);
_db.Context.SaveChanges();
var profiles = new ProfileService(_db.Context, NullLogger<ProfileService>.Instance);
var forbidden = await profiles.SetNewIcon(_db.Bob, media.Id);
Assert.That(forbidden.Error.Type, Is.EqualTo(ErrorType.Forbidden));
}
[TestCase(true)]
[TestCase(false)]
public async Task ExpiredWorkerCannotDeleteOrRescheduleANewerLease(bool delivered)
{
var message = _db.AddMessage();
_db.Context.ChatPushNotifications.Add(new Govor.Domain.Models.Messages.ChatPushNotification
{ MessageId = message.Id, NextAttemptAt = _now });
await _db.Context.SaveChangesAsync();
var notifier = new Mock<IChatNotificationService>();
var secondWorker = new Mock<IChatNotificationService>();
secondWorker.Setup(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>())).ReturnsAsync(false);
DateTime retryAt = default;
notifier.Setup(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>())).Returns(async () =>
{
_now = _now.AddMinutes(3);
using var otherContext = _db.CreateContext();
await new ChatPushDispatcher(otherContext, secondWorker.Object, _clock.Object).DispatchAsync();
retryAt = (await otherContext.ChatPushNotifications.AsNoTracking().SingleAsync()).NextAttemptAt;
_now = _now.AddSeconds(1);
return delivered;
});
await new ChatPushDispatcher(_db.Context, notifier.Object, _clock.Object).DispatchAsync();
var pending = await _db.Context.ChatPushNotifications.AsNoTracking().SingleAsync();
Assert.That(pending.Attempts, Is.EqualTo(2));
Assert.That(pending.NextAttemptAt, Is.EqualTo(retryAt));
}
[Test]
public async Task NotificationExceptionDoesNotBlockRemainingMessagesInBatch()
{
foreach (var _ in Enumerable.Range(0, 2))
{
var message = _db.AddMessage();
_db.Context.ChatPushNotifications.Add(new Govor.Domain.Models.Messages.ChatPushNotification
{ MessageId = message.Id, NextAttemptAt = _now });
}
await _db.Context.SaveChangesAsync();
var notifier = new Mock<IChatNotificationService>();
notifier.SetupSequence(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>()))
.ThrowsAsync(new HttpRequestException("offline")).ReturnsAsync(true);
await new ChatPushDispatcher(_db.Context, notifier.Object, _clock.Object).DispatchAsync();
notifier.Verify(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>()), Times.Exactly(2));
var pending = await _db.Context.ChatPushNotifications.AsNoTracking().SingleAsync();
Assert.That(pending.NextAttemptAt, Is.EqualTo(_now.AddSeconds(2)));
}
private Guid AddSession(Guid user)
{
var session = new UserSession { UserId = user, ExpiresAt = _now.AddDays(1), RefreshTokenHash = Guid.NewGuid().ToString() };
_db.Context.UserSessions.Add(session);
_db.Context.SaveChanges();
return session.Id;
}
}
@@ -0,0 +1,81 @@
using Govor.Application.Reactions;
using Govor.Domain.Models.Reactions;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Gif;
using SixLabors.ImageSharp.Metadata.Profiles.Exif;
using SixLabors.ImageSharp.PixelFormats;
namespace Govor.Server.Tests;
[TestFixture]
public class ReactionMediaTests
{
private readonly ReactionMediaProcessor _processor = new();
[Test]
public async Task StaticImageIsResizedReencodedAndMetadataIsRemoved()
{
using var source = new Image<Rgba32>(512, 256, Color.Red.ToPixel<Rgba32>());
source.Metadata.ExifProfile = new ExifProfile();
source.Metadata.ExifProfile.SetValue(ExifTag.Artist, "private metadata");
using var input = new MemoryStream();
await source.SaveAsJpegAsync(input);
var result = await _processor.ProcessAsync(input.ToArray());
Assert.That(result.IsSuccess, Is.True);
Assert.That(result.Value.Kind, Is.EqualTo(ReactionKind.Image));
Assert.That(result.Value.MimeType, Is.EqualTo("image/png"));
Assert.That(result.Value.Width, Is.LessThanOrEqualTo(128));
Assert.That(result.Value.Height, Is.LessThanOrEqualTo(128));
Assert.That(result.Value.Data.Length, Is.LessThanOrEqualTo(256 * 1024));
using var decoded = Image.Load(result.Value.Data);
Assert.That(decoded.Metadata.ExifProfile, Is.Null);
}
[Test]
public async Task GifKeepsFramesAndTimingWithinLimits()
{
var input = await GifAsync(2, 25, 256);
var result = await _processor.ProcessAsync(input);
Assert.That(result.IsSuccess, Is.True);
Assert.That(result.Value.Kind, Is.EqualTo(ReactionKind.Gif));
Assert.That(result.Value.DurationMilliseconds, Is.EqualTo(500));
Assert.That(result.Value.Data.Length, Is.LessThanOrEqualTo(512 * 1024));
using var decoded = Image.Load(result.Value.Data);
Assert.That(decoded.Frames.Count, Is.EqualTo(2));
Assert.That(decoded.Width, Is.LessThanOrEqualTo(128));
Assert.That(decoded.Frames.Select(f => f.Metadata.GetGifMetadata().FrameDelay), Is.EqualTo(new[] { 25, 25 }));
}
[Test]
public async Task LongAndExcessiveFrameAnimationsAreRejected()
{
Assert.That((await _processor.ProcessAsync(await GifAsync(2, 300))).IsFailure, Is.True);
Assert.That((await _processor.ProcessAsync(await GifAsync(61, 2))).IsFailure, Is.True);
}
[Test]
public async Task UnsupportedMalformedAndOversizedInputsAreRejected()
{
Assert.That((await _processor.ProcessAsync("<svg xmlns='http://www.w3.org/2000/svg'/>"u8.ToArray())).IsFailure, Is.True);
Assert.That((await _processor.ProcessAsync(new byte[ReactionMediaLimits.MaxUploadBytes + 1])).IsFailure, Is.True);
using var source = new Image<Rgba32>(4096, 1);
using var input = new MemoryStream();
await source.SaveAsPngAsync(input);
Assert.That((await _processor.ProcessAsync(input.ToArray())).IsFailure, Is.True);
}
public static async Task<byte[]> GifAsync(int frames, int delay, int dimension = 16)
{
using var image = new Image<Rgba32>(dimension, dimension, Color.Red.ToPixel<Rgba32>());
image.Frames.RootFrame.Metadata.GetGifMetadata().FrameDelay = delay;
for (var i = 1; i < frames; i++)
{
using var next = new Image<Rgba32>(dimension, dimension, (i % 2 == 0 ? Color.Red : Color.Blue).ToPixel<Rgba32>());
next.Frames.RootFrame.Metadata.GetGifMetadata().FrameDelay = delay;
image.Frames.AddFrame(next.Frames.RootFrame);
}
using var input = new MemoryStream();
await image.SaveAsGifAsync(input);
return input.ToArray();
}
}
@@ -0,0 +1,194 @@
using Govor.Application.Infrastructure.Common;
using Govor.Application.Reactions;
using Govor.Application.Storage;
using Govor.Domain;
using Govor.Domain.Common;
using Govor.Domain.Models;
using Govor.Domain.Models.Reactions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
namespace Govor.Server.Tests;
[TestFixture]
public class ReactionTests
{
private TestDatabase _db = null!;
private MessageReactionService _reactions = null!;
private ReactionPackService _packs = null!;
private TestReactionStorage _storage = null!;
private readonly DateTime _now = new(2026, 10, 3, 10, 0, 0, DateTimeKind.Utc);
private Guid First => DefaultReactionPack.Items()[0].Id;
private Guid Second => DefaultReactionPack.Items()[1].Id;
[SetUp]
public void SetUp()
{
_db = new TestDatabase();
var clock = new Mock<INowDateTimeProvider>();
clock.SetupGet(c => c.Now).Returns(_now);
_storage = new TestReactionStorage();
_reactions = new MessageReactionService(_db.Context, clock.Object);
_packs = new ReactionPackService(_db.Context, clock.Object, new ReactionMediaProcessor(), _storage,
NullLogger<ReactionPackService>.Instance);
MakeAdmin(_db.Context, _db.Alice);
}
[TearDown]
public void TearDown() => _db.Dispose();
[Test]
public async Task DefaultPackIsAutomaticallyAvailableAndImmutable()
{
var mine = await _packs.ListAsync(_db.Bob, installedOnly: true);
Assert.That(mine.Single().IsDefault, Is.True);
Assert.That(mine.Single().Reactions.Count, Is.EqualTo(12));
Assert.That((await _packs.DisableAsync(_db.Alice, DefaultReactionPack.Id)).Error.Type, Is.EqualTo(ErrorType.Validation));
Assert.That((await _packs.AddEmojiAsync(_db.Alice, DefaultReactionPack.Id, "new", "😎")).IsFailure, Is.True);
Assert.That((await _packs.SubscribeAsync(_db.Bob, DefaultReactionPack.Id, false)).IsFailure, Is.True);
}
[Test]
public async Task PutIsIdempotentAndReplacementKeepsOneOwnReaction()
{
var message = _db.AddMessage();
var first = await _reactions.SetAsync(_db.Bob, message.Id, First);
var repeated = await _reactions.SetAsync(_db.Bob, message.Id, First);
Assert.That(first.Value.Version, Is.EqualTo(1));
Assert.That(repeated.Value.Changed, Is.False);
Assert.That(repeated.Value.Version, Is.EqualTo(1));
Assert.That(repeated.Value.ActorReaction!.ReactedAt, Is.EqualTo(_now));
var replaced = await _reactions.SetAsync(_db.Bob, message.Id, Second);
Assert.That(replaced.Value.Version, Is.EqualTo(2));
Assert.That(replaced.Value.Counts.Single().ReactionId, Is.EqualTo(Second));
Assert.That(await _db.Context.MessageReactions.CountAsync(), Is.EqualTo(1));
}
[Test]
public async Task AggregateCountsAndRemovingOwnReactionDoNotRemoveOtherUsers()
{
var message = _db.AddMessage();
await _reactions.SetAsync(_db.Alice, message.Id, First);
await _reactions.SetAsync(_db.Bob, message.Id, First);
var state = await _reactions.GetAsync(_db.Alice, message.Id);
Assert.That(state.Value.Counts.Single().Count, Is.EqualTo(2));
var removed = await _reactions.SetAsync(_db.Bob, message.Id, null);
Assert.That(removed.Value.ActorReaction, Is.Null);
Assert.That(removed.Value.Counts.Single().Count, Is.EqualTo(1));
Assert.That((await _reactions.SetAsync(_db.Bob, message.Id, null)).Value.Changed, Is.False);
Assert.That((await _db.Context.MessageReactions.SingleAsync()).UserId, Is.EqualTo(_db.Alice));
}
[Test]
public async Task OutsiderCannotReadSetOrDeleteReactions()
{
var message = _db.AddMessage();
await _reactions.SetAsync(_db.Alice, message.Id, First);
foreach (var result in new[]
{
await _reactions.GetAsync(_db.Outsider, message.Id),
await _reactions.SetAsync(_db.Outsider, message.Id, Second),
await _reactions.SetAsync(_db.Outsider, message.Id, null)
}) Assert.That(result.Error.Type, Is.EqualTo(ErrorType.Forbidden));
Assert.That(await _db.Context.MessageReactions.CountAsync(), Is.EqualTo(1));
}
[Test]
public async Task ChannelAdministratorSelectsAllowedReactionsAndPolicyFailureRollsBack()
{
var groupId = Channel();
var message = _db.AddMessage(chat: groupId, type: Govor.Domain.Models.Messages.RecipientType.Group);
var selected = await _reactions.SetPolicyAsync(_db.Alice, groupId, ChannelReactionMode.Selected, new[] { First });
Assert.That(selected.Value.Version, Is.EqualTo(1));
Assert.That((await _reactions.SetAsync(_db.Bob, message.Id, First)).IsSuccess, Is.True);
Assert.That((await _reactions.SetAsync(_db.Bob, message.Id, Second)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
var invalid = await _reactions.SetPolicyAsync(_db.Alice, groupId, ChannelReactionMode.Selected, new[] { Second, Guid.NewGuid() });
Assert.That(invalid.IsFailure, Is.True);
var unchanged = await _reactions.GetPolicyAsync(_db.Bob, groupId);
Assert.That(unchanged.Value.Version, Is.EqualTo(1));
Assert.That(unchanged.Value.ReactionIds, Is.EqualTo(new[] { First }));
await _reactions.SetPolicyAsync(_db.Alice, groupId, ChannelReactionMode.None, Array.Empty<Guid>());
Assert.That((await _reactions.SetAsync(_db.Bob, message.Id, First)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
// Restricting new reactions does not erase history; users can still remove their own.
Assert.That((await _reactions.SetAsync(_db.Bob, message.Id, null)).IsSuccess, Is.True);
}
[Test]
public async Task OrdinaryAndBannedMembersCannotChangeChannelPolicy()
{
var group = Channel();
Assert.That((await _reactions.SetPolicyAsync(_db.Bob, group, ChannelReactionMode.None, Array.Empty<Guid>())).Error.Type,
Is.EqualTo(ErrorType.Forbidden));
await _db.Context.GroupMemberships.Where(m => m.GroupId == group && m.UserId == _db.Alice)
.ExecuteUpdateAsync(s => s.SetProperty(m => m.IsBanned, true));
Assert.That((await _reactions.SetPolicyAsync(_db.Alice, group, ChannelReactionMode.All, Array.Empty<Guid>())).Error.Type,
Is.EqualTo(ErrorType.Forbidden));
var message = _db.AddMessage(chat: group, type: Govor.Domain.Models.Messages.RecipientType.Group);
Assert.That((await _reactions.SetAsync(_db.Alice, message.Id, First)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
}
[Test]
public async Task UsersCanShareInstallAndUninstallAnAdminCreatedPack()
{
Assert.That((await _packs.CreateAsync(_db.Bob, "forbidden", "")).Error.Type, Is.EqualTo(ErrorType.Forbidden));
var pack = (await _packs.CreateAsync(_db.Alice, "Custom", "description")).Value;
var item = (await _packs.AddEmojiAsync(_db.Alice, pack.Id, "cool", "😎")).Value;
Assert.That((await _packs.GetSharedAsync(pack.ShareCode)).Value.Reactions.Single().Id, Is.EqualTo(item.Id));
await _packs.SubscribeAsync(_db.Bob, pack.Id, true);
await _packs.SubscribeAsync(_db.Bob, pack.Id, true);
Assert.That(await _db.Context.UserReactionPacks.CountAsync(), Is.EqualTo(1));
Assert.That((await _packs.ListAsync(_db.Bob, installedOnly: true)).Count, Is.EqualTo(2));
await _packs.SubscribeAsync(_db.Bob, pack.Id, false);
Assert.That((await _packs.ListAsync(_db.Bob, installedOnly: true)).Count, Is.EqualTo(1));
// Installation affects the picker, not who may use a publicly shared reaction.
Assert.That((await _reactions.SetAsync(_db.Bob, _db.AddMessage().Id, item.Id)).IsSuccess, Is.True);
}
[Test]
public async Task DisabledPackBlocksNewReactionsButPreservesHistoryAndDefinition()
{
var pack = (await _packs.CreateAsync(_db.Alice, "Custom", "")).Value;
var item = (await _packs.AddEmojiAsync(_db.Alice, pack.Id, "cool", "😎")).Value;
var message = _db.AddMessage();
await _reactions.SetAsync(_db.Bob, message.Id, item.Id);
await _packs.DisableAsync(_db.Alice, pack.Id);
Assert.That((await _reactions.SetAsync(_db.Alice, message.Id, item.Id)).Error.Type, Is.EqualTo(ErrorType.NotFound));
Assert.That((await _reactions.GetAsync(_db.Bob, message.Id)).Value.Counts.Single().ReactionId, Is.EqualTo(item.Id));
Assert.That((await _packs.GetReactionAsync(item.Id)).IsSuccess, Is.True);
Assert.That((await _packs.GetSharedAsync(pack.ShareCode)).IsFailure, Is.True);
}
public static void MakeAdmin(GovorDbContext context, Guid userId)
{
var invite = new Invitation { Id = Guid.NewGuid(), Code = Guid.NewGuid().ToString("N"), IsAdmin = true,
Description = "admin test", EndDate = DateTime.UtcNow.AddDays(1), MaxParticipants = 10 };
context.Invitations.Add(invite);
context.Users.Single(u => u.Id == userId).InviteId = invite.Id;
context.SaveChanges();
}
private Guid Channel()
{
var group = new ChatGroup { Id = Guid.NewGuid(), Name = "channel", Description = "", IsChannel = true };
_db.Context.ChatGroups.Add(group);
foreach (var user in new[] { _db.Alice, _db.Bob })
_db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = group.Id, UserId = user });
_db.Context.GroupAdmins.Add(new GroupAdmins { Id = Guid.NewGuid(), GroupId = group.Id, UserId = _db.Alice });
_db.Context.SaveChanges();
return group.Id;
}
}
public class TestReactionStorage : IStorageService
{
public Dictionary<string, byte[]> Files { get; } = new();
public Task<string> SaveAsync(byte[] data, string fileName)
{
var path = Guid.NewGuid().ToString("N") + fileName;
Files.Add(path, data.ToArray());
return Task.FromResult(path);
}
public Task<Stream> LoadAsync(string url) => Task.FromResult<Stream>(new MemoryStream(Files[url], writable: false));
public Task RemoveAsync(string url) { Files.Remove(url); return Task.CompletedTask; }
}
@@ -0,0 +1,301 @@
using System.Security.Cryptography;
using System.Text;
using Govor.Application.E2ee;
using Govor.Application.Messages;
using Govor.Application.Messages.Parameters;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Govor.Domain.Models.Users;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using NUnit.Framework;
namespace Govor.Server.Tests;
[TestFixture]
public class E2eeTests
{
private DevicePrivateKeys _alice = null!, _bob = null!, _other = null!;
private TestDatabase _db = null!;
private E2eeService _e2ee = null!;
private DeviceKey _a = null!, _b = null!;
[OneTimeSetUp]
public void Keys() { _alice = E2eeProtocol.GenerateKeys(); _bob = E2eeProtocol.GenerateKeys(); _other = E2eeProtocol.GenerateKeys(); }
[SetUp]
public async Task SetUp()
{
_db = new TestDatabase();
_e2ee = new E2eeService(_db.Context);
_a = await Register(_db.Alice, _alice);
_b = await Register(_db.Bob, _bob);
}
[TearDown] public void Cleanup() => _db.Dispose();
private async Task<DeviceKey> Register(Guid user, DevicePrivateKeys keys)
{
var session = new UserSession { UserId = user, RefreshTokenHash = Guid.NewGuid().ToString(), ExpiresAt = DateTime.UtcNow.AddDays(30) };
_db.Context.UserSessions.Add(session);
await _db.Context.SaveChangesAsync();
var key = E2eeProtocol.PublicKey(keys, user, session.Id);
await _e2ee.RegisterAsync(user, session.Id, key);
return key;
}
private async Task<string> Encrypt(Guid? id = null, bool edit = false, Guid? conversation = null, int type = 0,
AttachmentSecret[]? attachments = null) => E2eeProtocol.Encrypt(new("секретное сообщение", attachments ?? []),
_alice, _a, await _e2ee.GetConversationKeysAsync(_db.Alice, conversation ?? _db.ChatId, (RecipientType)type),
id ?? Guid.NewGuid(), isEdit: edit);
[Test]
public async Task EveryParticipantNeedsARegisteredDeviceAndDeviceCountIsBounded()
{
await _db.Context.UserCryptoSessions.Where(c => c.UserSessionId == _b.SessionId).ExecuteDeleteAsync();
Assert.ThrowsAsync<InvalidOperationException>(() => _e2ee.GetConversationKeysAsync(_db.Alice, _db.ChatId, RecipientType.User));
_b = await Register(_db.Bob, _bob);
Assert.That((await _e2ee.GetConversationKeysAsync(_db.Alice, _db.ChatId, RecipientType.User)).Devices, Has.Length.EqualTo(2));
for (var i = 0; i < E2eeProtocol.MaxDevices; i++)
{
var session = new UserSession { UserId = _db.Alice, RefreshTokenHash = "limit-" + i, ExpiresAt = DateTime.UtcNow.AddDays(1) };
var cryptoId = Guid.NewGuid();
_db.Context.UserCryptoSessions.Add(new Govor.Domain.Models.Users.Crypto.UserCryptoSession
{
Id = cryptoId, UserSession = session, UserSessionId = session.Id,
PublicIdentityKey = Convert.FromBase64String(_a.IdentityKey),
SignedPreKey = new Govor.Domain.Models.Users.Crypto.SignedPreKey
{
Id = Guid.NewGuid(), UserCryptoSessionId = cryptoId,
PublicSignedPreKey = Convert.FromBase64String(_a.EncryptionKey), SignedPreKeySignature = Convert.FromBase64String(_a.Signature)
},
OneTimePreKeys = []
});
}
await _db.Context.SaveChangesAsync();
var limitError = Assert.ThrowsAsync<InvalidOperationException>(() => _e2ee.GetConversationKeysAsync(_db.Alice, _db.ChatId, RecipientType.User));
Assert.That(limitError!.Message, Does.Contain("Too many E2EE devices"));
}
[TestCase(false)]
[TestCase(true)]
public async Task ExpiredOrRevokedSessionCannotRegisterKeys(bool revoked)
{
await _db.Context.UserSessions.Where(s => s.Id == _a.SessionId).ExecuteUpdateAsync(s => s
.SetProperty(s => s.IsRevoked, revoked).SetProperty(s => s.ExpiresAt, DateTime.UtcNow.AddDays(revoked ? 1 : -1)));
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _e2ee.RegisterAsync(_db.Alice, _a.SessionId, _a));
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _e2ee.RegisterAsync(_db.Alice, Guid.NewGuid(), _a));
}
[TestCase("malformed")]
[TestCase("routing")]
[TestCase("stale")]
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,
_db.ChatId, RecipientType.User, null, []));
}
[TestCase(false)]
[TestCase(true)]
public async Task EncryptedMessageRejectsPlaintextAttachmentAndLeakedKey(bool leakedKey)
{
var mediaId = Guid.NewGuid();
_db.Context.MediaFiles.Add(new MediaFile { Id = mediaId, UploaderId = _db.Alice, OwnerType = MediaOwnerType.Message,
Url = "attachment.bin", MineType = leakedKey ? E2eeProtocol.EncryptedMimeType : "image/png" });
await _db.Context.SaveChangesAsync();
var content = await Encrypt(attachments: [new(mediaId, "secret", "attachment.png", "image/png")]);
var result = await new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance).SendMessageAsync(
new(content, null, _db.ChatId, RecipientType.User, _db.Alice, DateTime.UtcNow, [new(mediaId, leakedKey ? "leaked" : "")]));
Assert.That(result.IsSuccess, Is.False);
Assert.That(result.Exception, Is.TypeOf<ArgumentException>());
Assert.That(await _db.Context.Messages.CountAsync(), Is.Zero);
Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.Zero);
}
[Test]
public async Task BothParticipantsCanDecryptButServerAndOutsiderCannot()
{
var ciphertext = await Encrypt();
var envelope = E2eeProtocol.Verify(ciphertext);
foreach (var keys in new[] { _alice, _bob })
Assert.That(E2eeProtocol.Decrypt(ciphertext, keys, envelope.MessageId, _db.ChatId, 0, _db.Alice).Text,
Is.EqualTo("секретное сообщение"));
Assert.Throws<CryptographicException>(() => E2eeProtocol.Decrypt(ciphertext, _other,
envelope.MessageId, _db.ChatId, 0, _db.Alice));
Assert.That(ciphertext, Does.Not.Contain("секретное сообщение"));
}
[Test]
public async Task ServerPersistsOnlyCiphertextAndRetriesAreIdempotent()
{
var ciphertext = await Encrypt();
var sender = new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance);
var request = new SendMessage(ciphertext, null, _db.ChatId, RecipientType.User, _db.Alice, DateTime.UtcNow, []);
Assert.That((await sender.SendMessageAsync(request)).IsSuccess, Is.True);
Assert.That((await sender.SendMessageAsync(request)).IsSuccess, Is.True);
Assert.That(await _db.Context.Messages.CountAsync(), Is.EqualTo(1));
Assert.That((await _db.Context.Messages.SingleAsync()).EncryptedContent, Is.EqualTo(ciphertext));
Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.EqualTo(1));
}
[Test]
public async Task PlaintextIsRejectedForPrivateChats()
{
var sender = new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance);
var result = await sender.SendMessageAsync(new("hello", null, _db.ChatId, RecipientType.User,
_db.Alice, DateTime.UtcNow, []));
Assert.That(result.IsSuccess, Is.False);
Assert.That(await _db.Context.Messages.CountAsync(), Is.Zero);
}
[Test]
public async Task NewDeviceMakesOldRecipientManifestInvalid()
{
var ciphertext = await Encrypt();
await Register(_db.Bob, _other);
Assert.ThrowsAsync<ArgumentException>(() => _e2ee.ValidateAsync(ciphertext,
_db.Alice, _db.ChatId, RecipientType.User, null, []));
}
[Test]
public async Task RevokedSigningDeviceCannotSend()
{
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,
_db.Alice, _db.ChatId, RecipientType.User, null, []));
}
[Test]
public async Task ExpiredOfflineDeviceStillReceivesFutureMessages()
{
await _db.Context.UserSessions.Where(s => s.Id == _b.SessionId)
.ExecuteUpdateAsync(u => u.SetProperty(s => s.ExpiresAt, DateTime.UtcNow.AddDays(-1)));
var ciphertext = await Encrypt();
var envelope = E2eeProtocol.Verify(ciphertext);
Assert.That(E2eeProtocol.Decrypt(ciphertext, _bob, envelope.MessageId, _db.ChatId, 0, _db.Alice).Text,
Is.EqualTo("секретное сообщение"));
}
[Test]
public async Task KeysAreIdempotentImmutableAndOwnedBySession()
{
await _e2ee.RegisterAsync(_db.Alice, _a.SessionId, _a);
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _e2ee.RegisterAsync(_db.Bob, _a.SessionId, _a));
var replacement = E2eeProtocol.PublicKey(_other, _db.Alice, _a.SessionId);
Assert.ThrowsAsync<InvalidOperationException>(() => _e2ee.RegisterAsync(_db.Alice, _a.SessionId, replacement));
}
[Test]
public async Task OutsiderCannotRetrieveConversationKeys() =>
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _e2ee.GetConversationKeysAsync(_db.Outsider, _db.ChatId, RecipientType.User));
[Test]
public async Task InvalidKeyBindingIsRejected()
{
var invalid = _a with { EncryptionKey = _b.EncryptionKey };
Assert.Throws<CryptographicException>(() => E2eeProtocol.ValidatePublicKey(invalid));
Assert.ThrowsAsync<CryptographicException>(() => _e2ee.RegisterAsync(_db.Alice, _a.SessionId, invalid));
}
[Test]
public async Task SignedMessageCannotBeMovedToAnotherAuthorChatReplyOrId()
{
var ciphertext = await Encrypt();
var envelope = E2eeProtocol.Verify(ciphertext);
Assert.Throws<CryptographicException>(() => E2eeProtocol.Decrypt(ciphertext, _bob, Guid.NewGuid(), _db.ChatId, 0, _db.Alice));
Assert.Throws<CryptographicException>(() => E2eeProtocol.Decrypt(ciphertext, _bob, envelope.MessageId, Guid.NewGuid(), 0, _db.Alice));
Assert.Throws<CryptographicException>(() => E2eeProtocol.Decrypt(ciphertext, _bob, envelope.MessageId, _db.ChatId, 0, _db.Outsider));
Assert.Throws<CryptographicException>(() => E2eeProtocol.Decrypt(ciphertext, _bob, envelope.MessageId, _db.ChatId, 0, _db.Alice, Guid.NewGuid()));
}
[Test]
public async Task TamperingWithSignedPayloadFails()
{
var ciphertext = await Encrypt();
var parts = ciphertext[E2eeProtocol.Prefix.Length..].Split('.');
var json = Encoding.UTF8.GetString(Jose.Base64Url.Decode(parts[1]));
parts[1] = Jose.Base64Url.Encode(Encoding.UTF8.GetBytes(json.Replace(_db.Alice.ToString(), _db.Outsider.ToString())));
Assert.Catch(() => E2eeProtocol.Verify(E2eeProtocol.Prefix + string.Join('.', parts)));
}
[Test]
public async Task ExcludedMemberCannotDecryptNewGroupMessagesAndStaleSendIsRejected()
{
var group = new ChatGroup { Id = Guid.NewGuid(), Name = "private", Description = "", IsPrivate = true };
_db.Context.ChatGroups.Add(group);
foreach (var user in new[] { _db.Alice, _db.Bob })
_db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = group.Id, UserId = user });
await _db.Context.SaveChangesAsync();
var old = await Encrypt(conversation: group.Id, type: 1);
await _db.Context.GroupMemberships.Where(m => m.GroupId == group.Id && m.UserId == _db.Bob)
.ExecuteUpdateAsync(u => u.SetProperty(m => m.IsBanned, true));
Assert.ThrowsAsync<ArgumentException>(() => _e2ee.ValidateAsync(old, _db.Alice, group.Id, RecipientType.Group, null, []));
var current = await Encrypt(conversation: group.Id, type: 1);
Assert.Catch(() => E2eeProtocol.Decrypt(current, _bob, E2eeProtocol.Inspect(current).MessageId, group.Id, 1, _db.Alice));
}
[Test]
public void AttachmentIsAuthenticatedAndWrongKeyOrModifiedDataFails()
{
var original = Encoding.UTF8.GetBytes("private attachment bytes");
var (encrypted, key) = E2eeProtocol.EncryptAttachment(original);
Assert.That(E2eeProtocol.DecryptAttachment(encrypted, key), Is.EqualTo(original));
Assert.Catch(() => E2eeProtocol.DecryptAttachment(encrypted, Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))));
encrypted[15] ^= 1;
Assert.Catch(() => E2eeProtocol.DecryptAttachment(encrypted, key));
}
[Test]
public async Task AttachmentKeyExistsOnlyInsideEncryptedPayload()
{
var (_, key) = E2eeProtocol.EncryptAttachment("secret"u8.ToArray());
var media = new AttachmentSecret(Guid.NewGuid(), key, "secret.png", "image/png");
var ciphertext = await Encrypt(attachments: [media]);
Assert.That(ciphertext, Does.Not.Contain(key).And.Not.Contain("secret.png"));
var plaintext = E2eeProtocol.Decrypt(ciphertext, _bob, E2eeProtocol.Inspect(ciphertext).MessageId, _db.ChatId, 0, _db.Alice);
Assert.That(plaintext.Attachments.Single(), Is.EqualTo(media));
}
[Test]
public async Task EncryptedEditIsAcceptedButPlaintextAndOlderEditsAreRejected()
{
var first = await Encrypt();
var sender = new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance);
var sent = await sender.SendMessageAsync(new(first, null, _db.ChatId, RecipientType.User, _db.Alice, DateTime.UtcNow, []));
var editor = new MessageEditingService(_db.Context, NullLogger<MessageEditingService>.Instance,
Microsoft.Extensions.Options.Options.Create(new MessageEditingOptions { Enabled = false }));
var directory = await _e2ee.GetConversationKeysAsync(_db.Alice, _db.ChatId, RecipientType.User);
var edited = E2eeProtocol.Encrypt(new("edited secret", []), _alice, _a, directory, sent.Message.Id,
isEdit: true, createdAt: E2eeProtocol.Inspect(first).CreatedAt + 1);
var result = await editor.EditMessageAsync(new(_db.Alice, sent.Message.Id, edited, DateTime.UtcNow));
Assert.That(result.IsSuccess, Is.True);
var plaintext = await editor.EditMessageAsync(new(_db.Alice, sent.Message.Id, "leak", DateTime.UtcNow));
Assert.That(plaintext.IsSuccess, Is.False);
var replay = await editor.EditMessageAsync(new(_db.Alice, sent.Message.Id, edited, DateTime.UtcNow));
Assert.That(replay.IsSuccess, Is.False);
Assert.That((await _db.Context.Messages.SingleAsync()).EncryptedContent, Is.EqualTo(edited));
}
[Test]
public async Task PlaintextIsRejectedForPrivateGroupsAndChannels()
{
foreach (var channel in new[] { false, true })
{
var group = new ChatGroup { Id = Guid.NewGuid(), Name = "private", Description = "",
IsPrivate = true, IsChannel = channel, OwnerUserId = _db.Alice };
_db.Context.ChatGroups.Add(group);
_db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = group.Id, UserId = _db.Alice });
await _db.Context.SaveChangesAsync();
var sender = new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.Instance);
Assert.That((await sender.SendMessageAsync(new("plaintext", null, group.Id,
RecipientType.Group, _db.Alice, DateTime.UtcNow, []))).IsSuccess, Is.False);
}
Assert.That(await _db.Context.Messages.CountAsync(), Is.Zero);
}
}
@@ -0,0 +1,37 @@
using Govor.API.Filters;
using Govor.Contracts.Responses.SignalR;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
namespace Govor.Server.Tests;
[TestFixture]
public class HubSessionTests
{
[Test]
public async Task InvalidSessionReturnsAHubResultAndAbortsWithoutRunningMethod()
{
using var db = new TestDatabase();
var caller = new Mock<HubCallerContext>();
var hub = new StubHub();
var invocation = new HubInvocationContext(caller.Object, Mock.Of<IServiceProvider>(), hub,
typeof(StubHub).GetMethod(nameof(StubHub.Echo))!, Array.Empty<object?>());
var filter = new HubExceptionFilter(NullLogger<HubExceptionFilter>.Instance, db.Context);
var invoked = false;
var response = await filter.InvokeMethodAsync(invocation, _ =>
{
invoked = true;
return ValueTask.FromResult<object?>(HubResult<string>.Ok("unexpected"));
});
Assert.That(invoked, Is.False);
Assert.That(response, Is.TypeOf<HubResult<string>>());
Assert.That(((HubResult<string>)response!).Status, Is.EqualTo(HubResultStatus.Unauthorized));
caller.Verify(c => c.Abort(), Times.Once);
}
private sealed class StubHub : Hub
{
public Task<HubResult<string>> Echo() => Task.FromResult(HubResult<string>.Ok("ok"));
}
}