mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-17 12:59:25 +00:00
Add primitive groups and required channel
Adds server-side group and channel management, private invitations, member moderation, avatar handling, and required-channel configuration. This change also introduces SignalR group profile/member notifications, updates registration to atomically join required channels, and adds EF migration and test coverage for group membership, permissions, and invitation expiry rules.
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
using Govor.Domain.Migrations;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore.Migrations.Operations;
|
||||
|
||||
namespace Govor.Server.Tests;
|
||||
|
||||
[TestFixture]
|
||||
public class GroupMigrationTests
|
||||
{
|
||||
[Test]
|
||||
public async Task LegacyCleanupPreservesBansChoosesActiveAdminAndRevokesAmbiguousLinks()
|
||||
{
|
||||
await using var connection = new SqliteConnection("Data Source=:memory:");
|
||||
await connection.OpenAsync();
|
||||
await using var command = connection.CreateCommand();
|
||||
command.CommandText = """
|
||||
CREATE TABLE "Users" ("Id" TEXT PRIMARY KEY);
|
||||
CREATE TABLE "ChatGroups" ("Id" TEXT PRIMARY KEY, "OwnerUserId" TEXT, "CreatedAt" TEXT);
|
||||
CREATE TABLE "GroupMemberships" ("Id" TEXT, "GroupId" TEXT, "UserId" TEXT, "IsBanned" INTEGER, "MemberSince" TEXT, "InvitationId" TEXT);
|
||||
CREATE TABLE "GroupAdmins" ("Id" TEXT, "GroupId" TEXT, "UserId" TEXT);
|
||||
CREATE TABLE "GroupInvitations" ("Id" TEXT, "InvitationCode" TEXT, "IsRevoked" INTEGER, "UsedCount" INTEGER);
|
||||
INSERT INTO "Users" VALUES ('alice'), ('bob'), ('carol');
|
||||
INSERT INTO "ChatGroups" VALUES ('group', NULL, NULL);
|
||||
INSERT INTO "GroupInvitations" VALUES ('inv-1', 'same', 0, 0), ('inv-2', 'same', 0, 0);
|
||||
INSERT INTO "GroupMemberships" VALUES
|
||||
('a', 'group', 'alice', 0, '2026-01-02', NULL),
|
||||
('b1', 'group', 'bob', 0, '2026-01-01', 'inv-1'),
|
||||
('b2', 'group', 'bob', 1, '2026-01-03', 'inv-1'),
|
||||
('c', 'group', 'carol', 0, '2026-01-01', 'inv-1'),
|
||||
('orphan', 'group', 'missing', 0, '2026-01-01', NULL);
|
||||
INSERT INTO "GroupAdmins" VALUES
|
||||
('a1', 'group', 'alice'), ('a2', 'group', 'alice'),
|
||||
('b', 'group', 'bob'), ('orphan', 'group', 'missing');
|
||||
""";
|
||||
await command.ExecuteNonQueryAsync();
|
||||
var migration = new PrimitiveGroupsAndRequiredChannel();
|
||||
command.CommandText = migration.UpOperations.OfType<SqlOperation>().Single().Sql;
|
||||
await command.ExecuteNonQueryAsync();
|
||||
command.CommandText = "SELECT COUNT(*) FROM \"GroupMemberships\"";
|
||||
Assert.That(Convert.ToInt32(await command.ExecuteScalarAsync()), Is.EqualTo(3));
|
||||
command.CommandText = "SELECT \"IsBanned\" FROM \"GroupMemberships\" WHERE \"UserId\" = 'bob'";
|
||||
Assert.That(Convert.ToInt32(await command.ExecuteScalarAsync()), Is.EqualTo(1));
|
||||
command.CommandText = "SELECT COUNT(*) FROM \"GroupAdmins\"";
|
||||
Assert.That(Convert.ToInt32(await command.ExecuteScalarAsync()), Is.EqualTo(1));
|
||||
command.CommandText = "SELECT \"OwnerUserId\" FROM \"ChatGroups\"";
|
||||
Assert.That(await command.ExecuteScalarAsync(), Is.EqualTo("alice"));
|
||||
command.CommandText = "SELECT COUNT(*) FROM \"GroupInvitations\" WHERE \"IsRevoked\" = 1";
|
||||
Assert.That(Convert.ToInt32(await command.ExecuteScalarAsync()), Is.EqualTo(2));
|
||||
command.CommandText = "SELECT \"UsedCount\" FROM \"GroupInvitations\" WHERE \"Id\" = 'inv-1'";
|
||||
Assert.That(Convert.ToInt32(await command.ExecuteScalarAsync()), Is.EqualTo(2));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ 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;
|
||||
@@ -22,7 +23,7 @@ public class NotificationTests
|
||||
private Mock<IPushNotificationService> _push = null!;
|
||||
private Mock<IClientProxy> _proxy = null!;
|
||||
private ChatNotificationService _notifier = null!;
|
||||
private readonly List<(string Method, string[] Groups)> _events = [];
|
||||
private readonly List<(string Method, string[] Groups, object Payload)> _events = [];
|
||||
private string[] _targetGroups = [];
|
||||
private Guid _aliceSession;
|
||||
private Guid _bobSession;
|
||||
@@ -38,7 +39,7 @@ public class NotificationTests
|
||||
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, _, _) => _events.Add((method, _targetGroups)))
|
||||
.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>>()))
|
||||
@@ -146,6 +147,80 @@ public class NotificationTests
|
||||
{ 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) };
|
||||
|
||||
@@ -2,8 +2,10 @@ 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;
|
||||
@@ -52,6 +54,9 @@ public class ReadApiTests
|
||||
_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();
|
||||
}
|
||||
@@ -200,18 +205,291 @@ public class ReadApiTests
|
||||
Assert.That((await hub.React(Guid.NewGuid(), new SetReactionRequest { ReactionId = reaction })).Status, Is.EqualTo(HubResultStatus.NotFound));
|
||||
}
|
||||
|
||||
private void Authorize(string tokenType = "access", string role = "User")
|
||||
[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", _db.Bob.ToString()), new Claim("sid", _session.ToString()),
|
||||
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));
|
||||
}
|
||||
|
||||
private sealed class TestFactory(TestDatabase db, IChatNotificationService notifier) : WebApplicationFactory<Program>
|
||||
[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)
|
||||
{
|
||||
@@ -221,13 +499,18 @@ public class ReadApiTests
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
services.AddDataProtection().UseEphemeralDataProtectionProvider();
|
||||
services.RemoveAll<IDataProtectionProvider>();
|
||||
services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());
|
||||
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);
|
||||
services.RemoveAll<IChatNotificationService>();
|
||||
services.AddSingleton(notifier);
|
||||
if (notifier is not null)
|
||||
{
|
||||
services.RemoveAll<IChatNotificationService>();
|
||||
services.AddSingleton(notifier);
|
||||
}
|
||||
services.RemoveAll<IStorageService>();
|
||||
services.AddSingleton<IStorageService>(new TestReactionStorage());
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user