1248 lines
52 KiB
C#
1248 lines
52 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using GsDChat.Client.Network;
|
|
using GsDChat.Client.State;
|
|
using GsDChat.Core.Models;
|
|
using GsDChat.Core.Protocol;
|
|
using GsDChat.Server.Configuration;
|
|
using GsDChat.Server.Data;
|
|
using GsDChat.Server.Services;
|
|
using GsDChat.Server.WebSockets;
|
|
using Xunit;
|
|
|
|
namespace GsDChat.Tests;
|
|
|
|
public class EndToEndChatTests : IAsyncLifetime
|
|
{
|
|
private readonly string _testDir;
|
|
private WebApplication? _app;
|
|
private int _port;
|
|
private string _serverUrl = string.Empty;
|
|
|
|
public EndToEndChatTests()
|
|
{
|
|
_testDir = Path.Combine(Path.GetTempPath(), "gsdchat_e2e_" + Guid.NewGuid().ToString("N"));
|
|
}
|
|
|
|
public async Task InitializeAsync()
|
|
{
|
|
// Pick an unused local port
|
|
using var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
|
|
listener.Start();
|
|
_port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
|
|
listener.Stop();
|
|
|
|
_serverUrl = $"http://127.0.0.1:{_port}";
|
|
|
|
var builder = WebApplication.CreateBuilder();
|
|
builder.WebHost.UseUrls(_serverUrl);
|
|
builder.Logging.ClearProviders(); // Keep test output clean
|
|
|
|
var (vapidPub, vapidPriv) = GsDChat.Core.Security.WebPushCrypto.GenerateVapidKeys();
|
|
var serverOptions = new ServerOptions
|
|
{
|
|
Host = "127.0.0.1",
|
|
Port = _port,
|
|
UseTls = false,
|
|
DataDirectory = _testDir,
|
|
ServerName = "E2E Test Server",
|
|
Motd = "Testing GsDChat E2E",
|
|
MaxWebSocketMessageSizeBytes = 1048576,
|
|
VapidPublicKey = vapidPub,
|
|
VapidPrivateKey = vapidPriv,
|
|
VapidSubject = "mailto:test@gsdchat.local"
|
|
};
|
|
|
|
builder.Services.AddSingleton(serverOptions);
|
|
builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory));
|
|
builder.Services.AddSingleton<InviteTokenService>();
|
|
builder.Services.AddSingleton<IAuthService, AuthService>();
|
|
builder.Services.AddSingleton<FileStorageService>();
|
|
builder.Services.AddSingleton<WebPushService>();
|
|
builder.Services.AddSingleton<ChatWebSocketManager>();
|
|
builder.Services.AddSingleton<RateLimitService>();
|
|
builder.Services.AddSingleton<ConnectionLimiterService>();
|
|
builder.Services.AddSingleton<CsrfProtectionService>();
|
|
|
|
_app = builder.Build();
|
|
|
|
var db = _app.Services.GetRequiredService<ChatDatabase>();
|
|
await db.InitializeAsync();
|
|
|
|
_app.UseWebSockets();
|
|
|
|
string? ExtractToken(HttpRequest req)
|
|
{
|
|
if (req.Headers.TryGetValue("Authorization", out var h) && h.ToString().StartsWith("Bearer "))
|
|
return h.ToString().Substring(7).Trim();
|
|
if (req.Query.TryGetValue("token", out var q))
|
|
return q.ToString();
|
|
return null;
|
|
}
|
|
|
|
_app.MapGet("/api/csrf-token", (CsrfProtectionService csrf) =>
|
|
{
|
|
var token = csrf.GenerateToken();
|
|
return Results.Ok(new { token });
|
|
});
|
|
|
|
_app.MapGet("/api/info", (ServerOptions opt) => Results.Ok(new ServerInfoResponse
|
|
{
|
|
ServerName = opt.ServerName,
|
|
Version = "1.0.0",
|
|
RegistrationMode = opt.RegistrationMode,
|
|
RequiresServerPassword = !string.IsNullOrWhiteSpace(opt.ServerWidePassword),
|
|
Motd = opt.Motd,
|
|
MaxFileSizeMb = opt.MaxFileSizeMb,
|
|
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
|
|
AllowDmE2ee = opt.AllowDmE2ee,
|
|
MaxGroupChatUsers = opt.MaxGroupChatUsers,
|
|
VapidPublicKey = opt.VapidPublicKey
|
|
}));
|
|
|
|
_app.MapGet("/api/push/vapid-public-key", (ServerOptions opt) =>
|
|
{
|
|
return Results.Ok(new { publicKey = opt.VapidPublicKey });
|
|
});
|
|
|
|
_app.MapPost("/api/push/subscribe", async (PushSubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) =>
|
|
{
|
|
string? token = ExtractToken(httpReq);
|
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
|
if (user == null) return Results.Unauthorized();
|
|
|
|
await chatDb.SavePushSubscriptionAsync(new PushSubscriptionRecord
|
|
{
|
|
UserId = user.Id,
|
|
Endpoint = req.Endpoint.Trim(),
|
|
P256dh = req.P256dh.Trim(),
|
|
Auth = req.Auth.Trim(),
|
|
UserAgent = req.UserAgent ?? string.Empty
|
|
});
|
|
return Results.Ok(new { success = true });
|
|
});
|
|
|
|
_app.MapPost("/api/push/unsubscribe", async (PushUnsubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) =>
|
|
{
|
|
string? token = ExtractToken(httpReq);
|
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
|
if (user == null) return Results.Unauthorized();
|
|
|
|
await chatDb.RemovePushSubscriptionAsync(user.Id, req.Endpoint.Trim());
|
|
return Results.Ok(new { success = true });
|
|
});
|
|
|
|
_app.MapPost("/api/push/test", async (HttpRequest httpReq, IAuthService auth, WebPushService webPush) =>
|
|
{
|
|
string? token = ExtractToken(httpReq);
|
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
|
if (user == null) return Results.Unauthorized();
|
|
|
|
bool delivered = await webPush.SendTestPushAsync(user.Id, user.Username);
|
|
return Results.Ok(new { success = delivered });
|
|
});
|
|
|
|
_app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth, CsrfProtectionService csrf, HttpContext context) =>
|
|
{
|
|
string? csrfToken = context.Request.Headers["X-CSRF-Token"];
|
|
if (!csrf.ValidateToken(csrfToken ?? "", ""))
|
|
{
|
|
return Results.BadRequest(new { error = "Invalid CSRF token" });
|
|
}
|
|
|
|
var res = await auth.RegisterAsync(req);
|
|
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
|
});
|
|
|
|
_app.MapPost("/api/auth/login", async (LoginRequest req, IAuthService auth, CsrfProtectionService csrf, HttpContext context) =>
|
|
{
|
|
string? csrfToken = context.Request.Headers["X-CSRF-Token"];
|
|
if (!csrf.ValidateToken(csrfToken ?? "", ""))
|
|
{
|
|
return Results.BadRequest(new { error = "Invalid CSRF token" });
|
|
}
|
|
|
|
var res = await auth.LoginAsync(req);
|
|
return res.Success ? Results.Ok(res) : Results.BadRequest(res);
|
|
});
|
|
|
|
_app.MapPost("/api/files/upload", async (HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileSvc, ChatWebSocketManager ws, RateLimitService rateLimiter, HttpContext context) =>
|
|
{
|
|
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
|
if (!rateLimiter.IsAllowed($"upload:{clientIp}"))
|
|
{
|
|
return Results.StatusCode(429);
|
|
}
|
|
|
|
string? token = ExtractToken(req);
|
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
|
if (user == null) return Results.Unauthorized();
|
|
|
|
var form = await req.ReadFormAsync();
|
|
var file = form.Files.GetFile("file");
|
|
if (file == null) return Results.BadRequest();
|
|
string chId = form["channelId"].ToString();
|
|
|
|
if (!await chatDb.CanUserAccessChannelAsync(chId, user.Id))
|
|
{
|
|
return Results.StatusCode(StatusCodes.Status403Forbidden);
|
|
}
|
|
|
|
using var stream = file.OpenReadStream();
|
|
var (record, savedMsg) = await fileSvc.StoreFileWithMessageAsync(chId, user.Id, user.Username, file.FileName, file.ContentType, stream, file.Length, user.Role);
|
|
await ws.BroadcastFileUploadedAsync(record, savedMsg);
|
|
|
|
return Results.Ok(new UploadFileResponse
|
|
{
|
|
Success = true,
|
|
FileId = record.Id,
|
|
FileName = record.OriginalFileName,
|
|
FileSizeBytes = record.FileSizeBytes,
|
|
ChannelId = record.ChannelId
|
|
});
|
|
});
|
|
|
|
_app.MapGet("/api/files/{id}", async (string id, HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileSvc) =>
|
|
{
|
|
string? token = ExtractToken(req);
|
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
|
if (user == null) return Results.Unauthorized();
|
|
|
|
var record = await fileSvc.GetFileRecordAsync(id);
|
|
if (record == null) return Results.NotFound();
|
|
|
|
if (!await chatDb.CanUserAccessChannelAsync(record.ChannelId, user.Id))
|
|
{
|
|
return Results.StatusCode(StatusCodes.Status403Forbidden);
|
|
}
|
|
|
|
var stream = fileSvc.OpenFileStream(record);
|
|
if (stream == null) return Results.NotFound();
|
|
|
|
return Results.File(stream, record.ContentType, record.OriginalFileName);
|
|
});
|
|
|
|
_app.MapDelete("/api/files/{id}", async (string id, HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileSvc, ChatWebSocketManager ws) =>
|
|
{
|
|
string? token = ExtractToken(req);
|
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
|
if (user == null) return Results.Unauthorized();
|
|
|
|
var record = await fileSvc.GetFileRecordAsync(id);
|
|
if (record == null) return Results.NotFound(new DeleteFileResponse { Success = false, ErrorMessage = "File not found." });
|
|
|
|
bool isUploader = string.Equals(user.Id, record.UploaderId, StringComparison.OrdinalIgnoreCase) ||
|
|
string.Equals(user.Username, record.UploaderUsername, StringComparison.OrdinalIgnoreCase);
|
|
bool isAdmin = string.Equals(user.Role, UserRoles.Admin, StringComparison.OrdinalIgnoreCase) ||
|
|
string.Equals(user.Role, UserRoles.Owner, StringComparison.OrdinalIgnoreCase);
|
|
|
|
if (!isUploader && !isAdmin)
|
|
{
|
|
return Results.Json(new DeleteFileResponse
|
|
{
|
|
Success = false,
|
|
ErrorMessage = "You do not have permission to delete this file. Only the uploader or an admin can delete it."
|
|
}, statusCode: StatusCodes.Status403Forbidden);
|
|
}
|
|
|
|
bool deleted = await fileSvc.DeleteFileAsync(record.Id);
|
|
if (!deleted)
|
|
{
|
|
return Results.BadRequest(new DeleteFileResponse { Success = false, ErrorMessage = "Failed to delete file." });
|
|
}
|
|
|
|
await ws.BroadcastFileDeletedAsync(record, user.Username);
|
|
|
|
return Results.Ok(new DeleteFileResponse
|
|
{
|
|
Success = true,
|
|
FileId = record.Id
|
|
});
|
|
});
|
|
|
|
_app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager ws, ConnectionLimiterService connLimiter, ServerOptions options) =>
|
|
{
|
|
if (!context.WebSockets.IsWebSocketRequest)
|
|
{
|
|
context.Response.StatusCode = 400;
|
|
return;
|
|
}
|
|
|
|
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
|
if (!connLimiter.TryAddConnection(clientIp))
|
|
{
|
|
context.Response.StatusCode = 429;
|
|
return;
|
|
}
|
|
|
|
string? token = ExtractToken(context.Request);
|
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
|
if (user == null)
|
|
{
|
|
connLimiter.RemoveConnection(clientIp);
|
|
context.Response.StatusCode = 401;
|
|
return;
|
|
}
|
|
|
|
var socket = await context.WebSockets.AcceptWebSocketAsync();
|
|
try
|
|
{
|
|
await ws.HandleClientAsync(socket, user, context.RequestAborted, options.MaxWebSocketMessageSizeBytes);
|
|
}
|
|
finally
|
|
{
|
|
connLimiter.RemoveConnection(clientIp);
|
|
}
|
|
});
|
|
|
|
await _app.StartAsync();
|
|
}
|
|
|
|
private ClientState CreateClientState()
|
|
{
|
|
return new ClientState(Path.Combine(_testDir, "e2ee_keys_test.json"))
|
|
{
|
|
ServerUrl = _serverUrl
|
|
};
|
|
}
|
|
|
|
public async Task DisposeAsync()
|
|
{
|
|
if (_app != null)
|
|
{
|
|
// Dispose the RateLimitService to stop the cleanup timer
|
|
var rateLimiter = _app.Services.GetService<RateLimitService>();
|
|
if (rateLimiter is IDisposable disposableRateLimiter)
|
|
{
|
|
disposableRateLimiter.Dispose();
|
|
}
|
|
|
|
await _app.StopAsync();
|
|
await _app.DisposeAsync();
|
|
}
|
|
|
|
try
|
|
{
|
|
if (Directory.Exists(_testDir))
|
|
{
|
|
Directory.Delete(_testDir, true);
|
|
}
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
[Fact]
|
|
public async Task FullChatAndFileTransferFlow_ShouldSucceed()
|
|
{
|
|
// 1. Client 1 (Alice): Register
|
|
var stateAlice = CreateClientState();
|
|
using var connAlice = new ChatClientConnection(stateAlice);
|
|
|
|
var regAlice = await connAlice.RegisterAsync("Alice", "AliceSecretPassword123");
|
|
Assert.True(regAlice.Success);
|
|
Assert.Equal(UserRoles.Owner, regAlice.Role);
|
|
stateAlice.Token = regAlice.Token!;
|
|
stateAlice.CurrentUserId = regAlice.UserId!;
|
|
stateAlice.CurrentUsername = regAlice.Username!;
|
|
stateAlice.CurrentUserRole = regAlice.Role!;
|
|
|
|
// 2. Client 2 (Bob): Register
|
|
var stateBob = CreateClientState();
|
|
using var connBob = new ChatClientConnection(stateBob);
|
|
|
|
var regBob = await connBob.RegisterAsync("Bob", "BobSecretPassword123");
|
|
Assert.True(regBob.Success);
|
|
Assert.Equal(UserRoles.Member, regBob.Role);
|
|
stateBob.Token = regBob.Token!;
|
|
stateBob.CurrentUserId = regBob.UserId!;
|
|
stateBob.CurrentUsername = regBob.Username!;
|
|
stateBob.CurrentUserRole = regBob.Role!;
|
|
|
|
// 3. Connect both clients to WebSockets
|
|
await connAlice.StartWebSocketAsync();
|
|
await connBob.StartWebSocketAsync();
|
|
|
|
// Allow initial sync to complete
|
|
await Task.Delay(300);
|
|
|
|
Assert.True(stateAlice.Channels.Count > 0);
|
|
Assert.True(stateBob.Channels.Count > 0);
|
|
Assert.False(string.IsNullOrEmpty(stateAlice.ActiveChannelId));
|
|
string generalChannelId = stateAlice.ActiveChannelId;
|
|
|
|
// 4. Alice sends a chat message
|
|
await connAlice.SendChatMessageAsync(generalChannelId, "Hello Bob, welcome to GsDChat!");
|
|
|
|
// Wait for broadcast to reach Bob
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.ChannelMessages.TryGetValue(generalChannelId, out var msgs) && msgs.Exists(m => m.Content.Contains("Hello Bob")))
|
|
{
|
|
break;
|
|
}
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.True(stateBob.ChannelMessages.TryGetValue(generalChannelId, out var bobMsgs));
|
|
Assert.Contains(bobMsgs, m => m.Content == "Hello Bob, welcome to GsDChat!" && m.SenderUsername == "Alice");
|
|
|
|
// 5. Alice uploads a test file
|
|
string localFilePath = Path.Combine(_testDir, "shared_document.txt");
|
|
string fileContent = "This is a confidential community file uploaded over secure HTTPS.";
|
|
await File.WriteAllTextAsync(localFilePath, fileContent);
|
|
|
|
bool uploadSuccess = await connAlice.UploadFileAsync(localFilePath, generalChannelId);
|
|
Assert.True(uploadSuccess);
|
|
|
|
// Wait for file list sync to reach Bob
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.Files.Exists(f => f.OriginalFileName == "shared_document.txt"))
|
|
{
|
|
break;
|
|
}
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
var sharedFile = stateBob.Files.Find(f => f.OriginalFileName == "shared_document.txt");
|
|
Assert.NotNull(sharedFile);
|
|
|
|
// 6. Bob downloads the file
|
|
string bobDownloadsDir = Path.Combine(_testDir, "bob_downloads");
|
|
bool downloadSuccess = await connBob.DownloadFileAsync(sharedFile.Id, bobDownloadsDir);
|
|
Assert.True(downloadSuccess);
|
|
|
|
string downloadedFilePath = Path.Combine(bobDownloadsDir, "shared_document.txt");
|
|
Assert.True(File.Exists(downloadedFilePath));
|
|
string downloadedText = await File.ReadAllTextAsync(downloadedFilePath);
|
|
Assert.Equal(fileContent, downloadedText);
|
|
|
|
// 7. Bob (non-uploader, member) tries to delete Alice's file -> should fail with permission error
|
|
bool bobDeleteSuccess = await connBob.DeleteFileAsync(sharedFile.Id);
|
|
Assert.False(bobDeleteSuccess);
|
|
Assert.Contains("403", stateBob.StatusMessage);
|
|
|
|
// 8. Alice (uploader) deletes the file -> succeeds
|
|
bool aliceDeleteSuccess = await connAlice.DeleteFileAsync(sharedFile.Id);
|
|
Assert.True(aliceDeleteSuccess);
|
|
|
|
// Wait for file list sync to reflect deletion for both Bob and Alice
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (!stateBob.Files.Exists(f => f.Id == sharedFile.Id) && !stateAlice.Files.Exists(f => f.Id == sharedFile.Id))
|
|
{
|
|
break;
|
|
}
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.DoesNotContain(stateBob.Files, f => f.Id == sharedFile.Id);
|
|
Assert.DoesNotContain(stateAlice.Files, f => f.Id == sharedFile.Id);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ChannelCreationAndSelection_ShouldSyncState()
|
|
{
|
|
var stateAlice = CreateClientState();
|
|
using var connAlice = new ChatClientConnection(stateAlice);
|
|
|
|
var regAlice = await connAlice.RegisterAsync("AliceChannelAdmin", "Password123!");
|
|
Assert.True(regAlice.Success);
|
|
stateAlice.Token = regAlice.Token!;
|
|
stateAlice.CurrentUserId = regAlice.UserId!;
|
|
stateAlice.CurrentUsername = regAlice.Username!;
|
|
stateAlice.CurrentUserRole = regAlice.Role!;
|
|
|
|
await connAlice.StartWebSocketAsync();
|
|
await Task.Delay(300);
|
|
|
|
Assert.True(stateAlice.Channels.Count >= 2);
|
|
int initialCount = stateAlice.Channels.Count;
|
|
|
|
// Create new channel
|
|
await connAlice.CreateChannelAsync("dev-team", "Developers room");
|
|
|
|
// Wait for channel list sync
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice.Channels.Count > initialCount) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.Equal(initialCount + 1, stateAlice.Channels.Count);
|
|
var newChannel = stateAlice.Channels.Find(c => c.Name == "dev-team");
|
|
Assert.NotNull(newChannel);
|
|
|
|
// Join new channel
|
|
await connAlice.JoinChannelAsync(newChannel.Id);
|
|
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice.ActiveChannelId == newChannel.Id) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.Equal(newChannel.Id, stateAlice.ActiveChannelId);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task BroadcastUserList_ShouldMarkConnectedUsersAsOnline()
|
|
{
|
|
var stateAlice = CreateClientState();
|
|
using var connAlice = new ChatClientConnection(stateAlice);
|
|
|
|
var regAlice = await connAlice.RegisterAsync("AliceOnline", "Pass1234!");
|
|
Assert.True(regAlice.Success);
|
|
stateAlice.Token = regAlice.Token!;
|
|
stateAlice.CurrentUserId = regAlice.UserId!;
|
|
|
|
var stateBob = CreateClientState();
|
|
using var connBob = new ChatClientConnection(stateBob);
|
|
|
|
var regBob = await connBob.RegisterAsync("BobOnline", "Pass1234!");
|
|
Assert.True(regBob.Success);
|
|
stateBob.Token = regBob.Token!;
|
|
stateBob.CurrentUserId = regBob.UserId!;
|
|
|
|
await connAlice.StartWebSocketAsync();
|
|
await connBob.StartWebSocketAsync();
|
|
|
|
for (int i = 0; i < 30; i++)
|
|
{
|
|
if (stateAlice.Users.Count(u => u.IsOnline) >= 2) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.Equal(2, stateAlice.Users.Count(u => u.IsOnline));
|
|
|
|
// When Bob disconnects, Alice's user list should reflect Bob as offline
|
|
connBob.Dispose();
|
|
|
|
for (int i = 0; i < 30; i++)
|
|
{
|
|
if (stateAlice.Users.Count(u => u.IsOnline) == 1) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.Equal(1, stateAlice.Users.Count(u => u.IsOnline));
|
|
var aliceUser = stateAlice.Users.Find(u => u.Username == "AliceOnline");
|
|
Assert.NotNull(aliceUser);
|
|
Assert.True(aliceUser.IsOnline);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DirectMessaging_WithE2eeSettingOn_ShouldBeFullE2eeAndNotVisibleToServer()
|
|
{
|
|
var serverOptions = _app!.Services.GetRequiredService<ServerOptions>();
|
|
serverOptions.AllowDmE2ee = true;
|
|
var db = _app.Services.GetRequiredService<ChatDatabase>();
|
|
|
|
// 1. Register & connect Alice (strictly username + password)
|
|
var stateAlice = CreateClientState();
|
|
using var connAlice = new ChatClientConnection(stateAlice);
|
|
var regAlice = await connAlice.RegisterAsync("AliceDmE2ee", "AlicePass123!");
|
|
Assert.True(regAlice.Success);
|
|
stateAlice.Token = regAlice.Token!;
|
|
stateAlice.CurrentUserId = regAlice.UserId!;
|
|
stateAlice.CurrentUsername = regAlice.Username!;
|
|
|
|
// 2. Register & connect Bob (strictly username + password)
|
|
var stateBob = CreateClientState();
|
|
using var connBob = new ChatClientConnection(stateBob);
|
|
var regBob = await connBob.RegisterAsync("BobDmE2ee", "BobPass123!");
|
|
Assert.True(regBob.Success);
|
|
stateBob.Token = regBob.Token!;
|
|
stateBob.CurrentUserId = regBob.UserId!;
|
|
stateBob.CurrentUsername = regBob.Username!;
|
|
|
|
await connAlice.StartWebSocketAsync();
|
|
await connBob.StartWebSocketAsync();
|
|
await Task.Delay(300);
|
|
|
|
// 3. Alice starts a DM with Bob -> lazy E2EE PIN prompt triggers
|
|
await connAlice.StartDmAsync("BobDmE2ee");
|
|
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice.DirectMessages.Count > 0 && stateBob.DirectMessages.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.Single(stateAlice.DirectMessages);
|
|
Assert.Single(stateBob.DirectMessages);
|
|
string dmChannelId = stateAlice.DirectMessages[0].Id;
|
|
Assert.True(stateAlice.DirectMessages[0].IsE2ee);
|
|
|
|
// 4. Both Alice and Bob initialize their dedicated E2EE PINs
|
|
var alicePinRes = await connAlice.UnlockOrInitializeE2eeWithPinAsync("AliceSecretPin#1");
|
|
Assert.True(alicePinRes.Success);
|
|
var bobPinRes = await connBob.UnlockOrInitializeE2eeWithPinAsync("BobSecretPin#2");
|
|
Assert.True(bobPinRes.Success);
|
|
|
|
// Wait for public keys to sync across clients
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (!string.IsNullOrEmpty(stateAlice.GetPeerPublicKeyForDm(stateAlice.DirectMessages[0]))) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
// 5. Alice sends a secret DM message
|
|
string secretPlaintext = "Ultra secret E2EE message that the server cannot read!";
|
|
await connAlice.SendChatMessageAsync(dmChannelId, secretPlaintext);
|
|
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.ChannelMessages.TryGetValue(dmChannelId, out var bMsgs) && bMsgs.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
// 6. Verify Bob decrypted the message
|
|
Assert.True(stateBob.ChannelMessages.TryGetValue(dmChannelId, out var bobDmMsgs));
|
|
Assert.Single(bobDmMsgs);
|
|
Assert.True(bobDmMsgs[0].IsEncrypted);
|
|
Assert.Equal(secretPlaintext, bobDmMsgs[0].Content);
|
|
|
|
// 7. Verify the server database ONLY has ciphertext (with both SenderPublicKey and RecipientPublicKey) and cannot see the plaintext
|
|
var serverStoredMsgs = await db.GetRecentMessagesAsync(dmChannelId, 10);
|
|
Assert.Single(serverStoredMsgs);
|
|
Assert.True(serverStoredMsgs[0].IsEncrypted);
|
|
Assert.StartsWith("E2EE:v1:", serverStoredMsgs[0].Content);
|
|
Assert.DoesNotContain("Ultra secret", serverStoredMsgs[0].Content);
|
|
Assert.Equal(stateAlice.PublicKeyBase64, serverStoredMsgs[0].SenderPublicKey);
|
|
Assert.Equal(stateBob.PublicKeyBase64, serverStoredMsgs[0].RecipientPublicKey);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DirectMessaging_SwitchingClients_And_KeyReset_ShouldPreserveFullPeerAndOwnHistory()
|
|
{
|
|
var serverOptions = _app!.Services.GetRequiredService<ServerOptions>();
|
|
serverOptions.AllowDmE2ee = true;
|
|
|
|
// 1. Register Alice and Bob on Client Device 1
|
|
var stateAlice1 = CreateClientState();
|
|
using var connAlice1 = new ChatClientConnection(stateAlice1);
|
|
var regAlice = await connAlice1.RegisterAsync("AliceSwitch", "AliceLoginPass!");
|
|
stateAlice1.Token = regAlice.Token!;
|
|
stateAlice1.CurrentUserId = regAlice.UserId!;
|
|
stateAlice1.CurrentUsername = regAlice.Username!;
|
|
|
|
var stateBob1 = CreateClientState();
|
|
using var connBob1 = new ChatClientConnection(stateBob1);
|
|
var regBob = await connBob1.RegisterAsync("BobSwitch", "BobLoginPass!");
|
|
stateBob1.Token = regBob.Token!;
|
|
stateBob1.CurrentUserId = regBob.UserId!;
|
|
stateBob1.CurrentUsername = regBob.Username!;
|
|
|
|
await connAlice1.StartWebSocketAsync();
|
|
await connBob1.StartWebSocketAsync();
|
|
await Task.Delay(300);
|
|
|
|
await connAlice1.StartDmAsync("BobSwitch");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice1.DirectMessages.Count > 0 && stateBob1.DirectMessages.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
string dmId = stateAlice1.DirectMessages[0].Id;
|
|
|
|
// Initialize dedicated E2EE PINs (distinct from login passwords)
|
|
Assert.True((await connAlice1.UnlockOrInitializeE2eeWithPinAsync("1111-alice-pin")).Success);
|
|
Assert.True((await connBob1.UnlockOrInitializeE2eeWithPinAsync("2222-bob-pin")).Success);
|
|
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (!string.IsNullOrEmpty(stateAlice1.GetPeerPublicKeyForDm(stateAlice1.DirectMessages[0])) &&
|
|
!string.IsNullOrEmpty(stateBob1.GetPeerPublicKeyForDm(stateBob1.DirectMessages[0])))
|
|
break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
// 2. Both Alice and Bob send encrypted DM messages
|
|
await connAlice1.SendChatMessageAsync(dmId, "Message 1 from Alice");
|
|
await Task.Delay(150);
|
|
await connBob1.SendChatMessageAsync(dmId, "Message 2 from Bob");
|
|
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice1.ChannelMessages.TryGetValue(dmId, out var aMsgs) && aMsgs.Count >= 2 &&
|
|
stateBob1.ChannelMessages.TryGetValue(dmId, out var bMsgs) && bMsgs.Count >= 2)
|
|
break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
// Clear local device cache to simulate switching to a completely new machine/browser
|
|
connAlice1.LockE2eeKeys();
|
|
connBob1.LockE2eeKeys();
|
|
|
|
// 3. Alice logs in on a brand-new client instance (Device 2) and joins the DM
|
|
var stateAlice2 = CreateClientState();
|
|
using var connAlice2 = new ChatClientConnection(stateAlice2);
|
|
var loginAlice2 = await connAlice2.LoginAsync("AliceSwitch", "AliceLoginPass!");
|
|
Assert.True(loginAlice2.Success);
|
|
Assert.False(string.IsNullOrEmpty(stateAlice2.ServerEncryptedPrivateKey));
|
|
// Before entering PIN, local private key is empty
|
|
Assert.True(string.IsNullOrEmpty(stateAlice2.PrivateKeyBase64));
|
|
|
|
await connAlice2.StartWebSocketAsync();
|
|
await Task.Delay(250);
|
|
await connAlice2.JoinChannelAsync(dmId);
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice2.ChannelMessages.TryGetValue(dmId, out var m) && m.Count >= 2) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
// Unlock with wrong PIN should fail
|
|
var wrongPin = await connAlice2.UnlockOrInitializeE2eeWithPinAsync("wrong-pin");
|
|
Assert.False(wrongPin.Success);
|
|
|
|
// Unlock with Alice's dedicated E2EE PIN -> should unwrap WRAP:v1 backup and decrypt both sent and received messages in place!
|
|
var rightPin = await connAlice2.UnlockOrInitializeE2eeWithPinAsync("1111-alice-pin");
|
|
Assert.True(rightPin.Success);
|
|
|
|
var aliceRestoredMsgs = stateAlice2.ChannelMessages[dmId];
|
|
Assert.Contains(aliceRestoredMsgs, m => m.Content == "Message 1 from Alice");
|
|
Assert.Contains(aliceRestoredMsgs, m => m.Content == "Message 2 from Bob");
|
|
|
|
// 4. Now Alice forgets/resets her E2EE PIN & generates a brand-new keypair!
|
|
string oldAlicePubKey = stateAlice2.PublicKeyBase64;
|
|
var resetRes = await connAlice2.UnlockOrInitializeE2eeWithPinAsync("9999-new-alice-pin", resetKeys: true);
|
|
Assert.True(resetRes.Success);
|
|
Assert.NotEqual(oldAlicePubKey, stateAlice2.PublicKeyBase64);
|
|
await Task.Delay(200);
|
|
|
|
// 5. Bob logs in on a brand-new client instance (Device 2) after Alice reset her keys!
|
|
connBob1.LockE2eeKeys();
|
|
var stateBob2 = CreateClientState();
|
|
using var connBob2 = new ChatClientConnection(stateBob2);
|
|
var loginBob2 = await connBob2.LoginAsync("BobSwitch", "BobLoginPass!");
|
|
Assert.True(loginBob2.Success);
|
|
await connBob2.StartWebSocketAsync();
|
|
await Task.Delay(250);
|
|
await connBob2.JoinChannelAsync(dmId);
|
|
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob2.ChannelMessages.TryGetValue(dmId, out var m) && m.Count >= 2) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
// Bob unlocks his vault with his E2EE PIN -> Because RecipientPublicKey & SenderPublicKey were saved on each message,
|
|
// Bob still decrypts 100% of his sent AND received history even after Alice reset her keypair!
|
|
var bobUnlock = await connBob2.UnlockOrInitializeE2eeWithPinAsync("2222-bob-pin");
|
|
Assert.True(bobUnlock.Success);
|
|
|
|
var bobRestoredMsgs = stateBob2.ChannelMessages[dmId];
|
|
Assert.Contains(bobRestoredMsgs, m => m.Content == "Message 1 from Alice");
|
|
Assert.Contains(bobRestoredMsgs, m => m.Content == "Message 2 from Bob");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DirectMessaging_TogglesAndHistoryPagination_ShouldSyncAndPaginateOnDemand()
|
|
{
|
|
var serverOptions = _app!.Services.GetRequiredService<ServerOptions>();
|
|
serverOptions.AllowDmE2ee = true;
|
|
var db = _app.Services.GetRequiredService<ChatDatabase>();
|
|
|
|
var stateAlice = CreateClientState();
|
|
using var connAlice = new ChatClientConnection(stateAlice);
|
|
var regAlice = await connAlice.RegisterAsync("AliceToggle", "Pass123!");
|
|
stateAlice.Token = regAlice.Token!;
|
|
stateAlice.CurrentUserId = regAlice.UserId!;
|
|
stateAlice.CurrentUsername = regAlice.Username!;
|
|
|
|
var stateBob = CreateClientState();
|
|
using var connBob = new ChatClientConnection(stateBob);
|
|
var regBob = await connBob.RegisterAsync("BobToggle", "Pass123!");
|
|
stateBob.Token = regBob.Token!;
|
|
stateBob.CurrentUserId = regBob.UserId!;
|
|
stateBob.CurrentUsername = regBob.Username!;
|
|
|
|
await connAlice.StartWebSocketAsync();
|
|
await connBob.StartWebSocketAsync();
|
|
await Task.Delay(300);
|
|
|
|
// 1. Toggle per-DM E2EE off and back on
|
|
await connAlice.StartDmAsync("BobToggle");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice.DirectMessages.Count > 0 && stateBob.DirectMessages.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
string dmId = stateAlice.DirectMessages[0].Id;
|
|
Assert.True(stateAlice.DirectMessages[0].IsE2ee);
|
|
|
|
await connAlice.ToggleE2eeAsync("dm", enabled: false, channelId: dmId);
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (!stateAlice.DirectMessages[0].IsE2ee && !stateBob.DirectMessages[0].IsE2ee) break;
|
|
await Task.Delay(100);
|
|
}
|
|
Assert.False(stateAlice.DirectMessages[0].IsE2ee);
|
|
Assert.False(stateBob.DirectMessages[0].IsE2ee);
|
|
|
|
// 2. Seed 65 messages in DM and verify 50-message initial load + FETCH_HISTORY pagination
|
|
for (int idx = 1; idx <= 65; idx++)
|
|
{
|
|
await db.SaveMessageAsync(new ChatMessage
|
|
{
|
|
ChannelId = dmId,
|
|
SenderId = stateAlice.CurrentUserId,
|
|
SenderUsername = "AliceToggle",
|
|
Content = $"History line #{idx}",
|
|
CreatedAt = DateTime.UtcNow.AddMinutes(-100 + idx)
|
|
});
|
|
}
|
|
|
|
await connAlice.JoinChannelAsync(dmId);
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice.ChannelMessages.TryGetValue(dmId, out var m) && m.Count == 50) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.Equal(50, stateAlice.ChannelMessages[dmId].Count);
|
|
Assert.True(stateAlice.ChannelHasMoreHistory[dmId]);
|
|
Assert.Equal("History line #16", stateAlice.ChannelMessages[dmId][0].Content);
|
|
Assert.Equal("History line #65", stateAlice.ChannelMessages[dmId][^1].Content);
|
|
|
|
// Fetch older 15 messages on demand
|
|
await connAlice.FetchOlderHistoryAsync(dmId);
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice.ChannelMessages[dmId].Count == 65) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.Equal(65, stateAlice.ChannelMessages[dmId].Count);
|
|
Assert.False(stateAlice.ChannelHasMoreHistory[dmId]);
|
|
Assert.Equal("History line #1", stateAlice.ChannelMessages[dmId][0].Content);
|
|
Assert.Equal("History line #65", stateAlice.ChannelMessages[dmId][^1].Content);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DirectMessaging_WithE2eeSettingOff_ShouldBlockE2eeAndStorePlaintextVisibleToServer()
|
|
{
|
|
var serverOptions = _app!.Services.GetRequiredService<ServerOptions>();
|
|
serverOptions.AllowDmE2ee = false;
|
|
var db = _app.Services.GetRequiredService<ChatDatabase>();
|
|
|
|
var stateAlice = CreateClientState();
|
|
using var connAlice = new ChatClientConnection(stateAlice);
|
|
await connAlice.GetServerInfoAsync();
|
|
Assert.False(stateAlice.AllowDmE2ee);
|
|
|
|
var regAlice = await connAlice.RegisterAsync("AlicePlainDm", "AlicePass123!");
|
|
stateAlice.Token = regAlice.Token!;
|
|
stateAlice.CurrentUserId = regAlice.UserId!;
|
|
stateAlice.CurrentUsername = regAlice.Username!;
|
|
|
|
var stateBob = CreateClientState();
|
|
using var connBob = new ChatClientConnection(stateBob);
|
|
await connBob.GetServerInfoAsync();
|
|
var regBob = await connBob.RegisterAsync("BobPlainDm", "BobPass123!");
|
|
stateBob.Token = regBob.Token!;
|
|
stateBob.CurrentUserId = regBob.UserId!;
|
|
stateBob.CurrentUsername = regBob.Username!;
|
|
|
|
await connAlice.StartWebSocketAsync();
|
|
await connBob.StartWebSocketAsync();
|
|
await Task.Delay(300);
|
|
|
|
await connAlice.StartDmAsync("BobPlainDm");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice.DirectMessages.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
string dmId = stateAlice.DirectMessages[0].Id;
|
|
Assert.False(stateAlice.DirectMessages[0].IsE2ee);
|
|
|
|
// 1. Attempting to force E2EE when server setting is OFF should be rejected by server
|
|
await connAlice.SendChatMessageAsync(dmId, "ShouldBeBlocked", forceEncrypt: true);
|
|
await Task.Delay(200);
|
|
var blockedCheck = await db.GetRecentMessagesAsync(dmId, 10);
|
|
Assert.Empty(blockedCheck);
|
|
Assert.Contains("disabled", stateAlice.StatusMessage, StringComparison.OrdinalIgnoreCase);
|
|
|
|
// 2. Normal DM goes through unencrypted and is visible to the server
|
|
await connAlice.SendChatMessageAsync(dmId, "Hello in server-visible mode");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.ChannelMessages.TryGetValue(dmId, out var bMsgs) && bMsgs.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
var storedPlain = await db.GetRecentMessagesAsync(dmId, 10);
|
|
Assert.Single(storedPlain);
|
|
Assert.False(storedPlain[0].IsEncrypted);
|
|
Assert.Equal("Hello in server-visible mode", storedPlain[0].Content);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task GroupChats_CreateInviteAndEnforceVariableMaxUserCountInSettings()
|
|
{
|
|
var serverOptions = _app!.Services.GetRequiredService<ServerOptions>();
|
|
serverOptions.MaxGroupChatUsers = 3;
|
|
|
|
// Register 4 users: Alice, Bob, Charlie, Dave
|
|
var stateAlice = CreateClientState();
|
|
using var connAlice = new ChatClientConnection(stateAlice);
|
|
var regAlice = await connAlice.RegisterAsync("AliceGrp", "Pass123!");
|
|
stateAlice.Token = regAlice.Token!;
|
|
stateAlice.CurrentUserId = regAlice.UserId!;
|
|
stateAlice.CurrentUsername = regAlice.Username!;
|
|
|
|
var stateBob = CreateClientState();
|
|
using var connBob = new ChatClientConnection(stateBob);
|
|
var regBob = await connBob.RegisterAsync("BobGrp", "Pass123!");
|
|
stateBob.Token = regBob.Token!;
|
|
stateBob.CurrentUserId = regBob.UserId!;
|
|
stateBob.CurrentUsername = regBob.Username!;
|
|
|
|
var stateCharlie = CreateClientState();
|
|
using var connCharlie = new ChatClientConnection(stateCharlie);
|
|
var regCharlie = await connCharlie.RegisterAsync("CharlieGrp", "Pass123!");
|
|
stateCharlie.Token = regCharlie.Token!;
|
|
stateCharlie.CurrentUserId = regCharlie.UserId!;
|
|
stateCharlie.CurrentUsername = regCharlie.Username!;
|
|
|
|
var stateDave = CreateClientState();
|
|
using var connDave = new ChatClientConnection(stateDave);
|
|
var regDave = await connDave.RegisterAsync("DaveGrp", "Pass123!");
|
|
stateDave.Token = regDave.Token!;
|
|
stateDave.CurrentUserId = regDave.UserId!;
|
|
stateDave.CurrentUsername = regDave.Username!;
|
|
|
|
await connAlice.StartWebSocketAsync();
|
|
await connBob.StartWebSocketAsync();
|
|
await connCharlie.StartWebSocketAsync();
|
|
await connDave.StartWebSocketAsync();
|
|
await Task.Delay(300);
|
|
|
|
// 1. Attempt to create a group with 4 users when MaxGroupChatUsers = 3 -> should fail
|
|
await connAlice.CreateGroupChatAsync("TooBigGroup", new[] { "BobGrp", "CharlieGrp", "DaveGrp" });
|
|
await Task.Delay(200);
|
|
Assert.Empty(stateAlice.GroupChats);
|
|
Assert.Contains("Maximum allowed is 3", stateAlice.StatusMessage, StringComparison.OrdinalIgnoreCase);
|
|
|
|
// 2. Create a group with 2 users (Alice + Bob) -> should succeed
|
|
await connAlice.CreateGroupChatAsync("ProjectTeam", new[] { "BobGrp" }, "Alpha project");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice.GroupChats.Count > 0 && stateBob.GroupChats.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.Single(stateAlice.GroupChats);
|
|
Assert.Single(stateBob.GroupChats);
|
|
Assert.Empty(stateCharlie.GroupChats);
|
|
string groupId = stateAlice.GroupChats[0].Id;
|
|
|
|
// 3. Invite Charlie (brings group to 3/3 max users) -> should succeed
|
|
await connAlice.InviteToGroupAsync(groupId, "CharlieGrp");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateCharlie.GroupChats.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
Assert.Single(stateCharlie.GroupChats);
|
|
Assert.Equal(3, stateAlice.GroupChats[0].MemberIds.Count);
|
|
|
|
// 4. Attempt to invite Dave (would be 4/3) -> should be rejected by max user count
|
|
await connAlice.InviteToGroupAsync(groupId, "DaveGrp");
|
|
await Task.Delay(200);
|
|
Assert.Empty(stateDave.GroupChats);
|
|
Assert.Contains("maximum user limit", stateAlice.StatusMessage, StringComparison.OrdinalIgnoreCase);
|
|
|
|
// 5. Send message in group chat -> Alice, Bob, Charlie receive it; Dave does not
|
|
await connBob.SendChatMessageAsync(groupId, "Hello team members!");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateCharlie.ChannelMessages.TryGetValue(groupId, out var cMsgs) && cMsgs.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.True(stateCharlie.ChannelMessages.TryGetValue(groupId, out var charlieGroupMsgs));
|
|
Assert.Contains(charlieGroupMsgs, m => m.Content == "Hello team members!");
|
|
Assert.False(stateDave.ChannelMessages.ContainsKey(groupId));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task InboxNotifications_MentionsAnnouncementsFollowedChannelsAndDms_ShouldDeliverAndMarkReadOnJoin()
|
|
{
|
|
var stateAlice = CreateClientState();
|
|
using var connAlice = new ChatClientConnection(stateAlice);
|
|
var regAlice = await connAlice.RegisterAsync("AliceInbox", "Pass123!");
|
|
stateAlice.Token = regAlice.Token!;
|
|
stateAlice.CurrentUserId = regAlice.UserId!;
|
|
stateAlice.CurrentUsername = regAlice.Username!;
|
|
stateAlice.CurrentUserRole = regAlice.Role!;
|
|
|
|
var stateBob = CreateClientState();
|
|
using var connBob = new ChatClientConnection(stateBob);
|
|
var regBob = await connBob.RegisterAsync("BobInbox", "Pass123!");
|
|
stateBob.Token = regBob.Token!;
|
|
stateBob.CurrentUserId = regBob.UserId!;
|
|
stateBob.CurrentUsername = regBob.Username!;
|
|
stateBob.CurrentUserRole = regBob.Role!;
|
|
|
|
await connAlice.StartWebSocketAsync();
|
|
await connBob.StartWebSocketAsync();
|
|
await Task.Delay(300);
|
|
|
|
string generalId = stateAlice.Channels.First(c => c.Name == "general").Id;
|
|
string announcementsId = stateAlice.Channels.First(c => c.Name == "announcements").Id;
|
|
|
|
// 1. Alice mentions @BobInbox in #general -> Bob receives an unread Mention inbox item
|
|
await connAlice.SendChatMessageAsync(generalId, "Hello @BobInbox please review the PR!");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.UnreadInboxCount >= 1) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.Equal(1, stateBob.UnreadInboxCount);
|
|
var bobItems = stateBob.GetInboxItems();
|
|
Assert.Single(bobItems);
|
|
Assert.Equal(InboxCategories.Mention, bobItems[0].Category);
|
|
Assert.Contains("Hello @BobInbox", bobItems[0].ContentPreview);
|
|
Assert.False(bobItems[0].IsRead);
|
|
|
|
// 2. Alice posts in #announcements -> Bob receives an unread Announcement inbox item
|
|
await connAlice.SendChatMessageAsync(announcementsId, "Release v2.0 is live!");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.UnreadInboxCount >= 2) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
Assert.Equal(2, stateBob.UnreadInboxCount);
|
|
bobItems = stateBob.GetInboxItems();
|
|
Assert.Contains(bobItems, x => x.Category == InboxCategories.Announcement && x.ContentPreview.Contains("Release v2.0"));
|
|
|
|
// 3. Bob joins #announcements -> auto-marks #announcements inbox items as read!
|
|
await connBob.JoinChannelAsync(announcementsId);
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.UnreadInboxCount == 1) break;
|
|
await Task.Delay(100);
|
|
}
|
|
Assert.Equal(1, stateBob.UnreadInboxCount);
|
|
|
|
// 4. Bob follows #general -> non-mention messages in #general now create FollowedChannel inbox items for Bob
|
|
await connBob.ToggleFollowChannelAsync(generalId, follow: true);
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.IsConversationFollowed(stateBob.Channels.First(c => c.Id == generalId))) break;
|
|
await Task.Delay(100);
|
|
}
|
|
Assert.True(stateBob.IsConversationFollowed(stateBob.Channels.First(c => c.Id == generalId)));
|
|
|
|
await connAlice.SendChatMessageAsync(generalId, "Regular update in followed general channel");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.UnreadInboxCount >= 2) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
bobItems = stateBob.GetInboxItems();
|
|
Assert.Contains(bobItems, x => x.Category == InboxCategories.FollowedChannel && x.ContentPreview.Contains("Regular update"));
|
|
|
|
// 4b. Bob looks at / joins #general -> all inbox items for #general are auto-marked read!
|
|
await connBob.JoinChannelAsync(generalId);
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.UnreadInboxCount == 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
Assert.Equal(0, stateBob.UnreadInboxCount);
|
|
bobItems = stateBob.GetInboxItems();
|
|
Assert.All(bobItems, item => Assert.True(item.IsRead));
|
|
|
|
// 4c. Alice sends DM to Bob while Bob is in #general -> Bob receives unread DM inbox item
|
|
await connAlice.StartDmAsync(stateBob.CurrentUsername, stateBob.CurrentUserId);
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice.DirectMessages.Count > 0 && stateBob.DirectMessages.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
string dmId = stateBob.DirectMessages[0].Id;
|
|
await connAlice.SendChatMessageAsync(dmId, "Hey Bob, private message here!");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.UnreadInboxCount >= 1) break;
|
|
await Task.Delay(100);
|
|
}
|
|
Assert.Equal(1, stateBob.UnreadInboxCount);
|
|
|
|
// When Bob opens/looks at the DM -> DM inbox item is marked read!
|
|
await connBob.JoinChannelAsync(dmId);
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.UnreadInboxCount == 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
Assert.Equal(0, stateBob.UnreadInboxCount);
|
|
|
|
// 5. Bob marks all read and clears read items
|
|
await connBob.SendInboxActionAsync("mark_all_read");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.UnreadInboxCount == 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
Assert.Equal(0, stateBob.UnreadInboxCount);
|
|
|
|
await connBob.SendInboxActionAsync("clear_read");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateBob.GetInboxItems().Count == 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
Assert.Empty(stateBob.GetInboxItems());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task InboxNotifications_WithE2eeDirectMessage_ShouldDecryptInClientInboxAndDeliverEncryptedWebPush()
|
|
{
|
|
var serverOptions = _app!.Services.GetRequiredService<ServerOptions>();
|
|
serverOptions.AllowDmE2ee = true;
|
|
var db = _app.Services.GetRequiredService<ChatDatabase>();
|
|
|
|
// Spin up a local mock Web Push receiver endpoint to capture the RFC 8291 encrypted push HTTP POST
|
|
using var pushListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
|
|
pushListener.Start();
|
|
int pushPort = ((System.Net.IPEndPoint)pushListener.LocalEndpoint).Port;
|
|
pushListener.Stop();
|
|
|
|
byte[]? receivedEncryptedPushBody = null;
|
|
string? receivedAuthHeader = null;
|
|
string? receivedContentEncoding = null;
|
|
|
|
var pushBuilder = WebApplication.CreateBuilder();
|
|
pushBuilder.WebHost.UseUrls($"http://127.0.0.1:{pushPort}");
|
|
pushBuilder.Logging.ClearProviders();
|
|
await using var pushEndpointApp = pushBuilder.Build();
|
|
pushEndpointApp.MapPost("/push-sink", async (HttpContext ctx) =>
|
|
{
|
|
receivedAuthHeader = ctx.Request.Headers["Authorization"].ToString();
|
|
receivedContentEncoding = ctx.Request.Headers["Content-Encoding"].ToString();
|
|
using var ms = new MemoryStream();
|
|
await ctx.Request.Body.CopyToAsync(ms);
|
|
receivedEncryptedPushBody = ms.ToArray();
|
|
return Results.StatusCode(201);
|
|
});
|
|
await pushEndpointApp.StartAsync();
|
|
|
|
try
|
|
{
|
|
var stateAlice = CreateClientState();
|
|
using var connAlice = new ChatClientConnection(stateAlice);
|
|
var regAlice = await connAlice.RegisterAsync("AlicePushDm", "Pass123!");
|
|
stateAlice.Token = regAlice.Token!;
|
|
stateAlice.CurrentUserId = regAlice.UserId!;
|
|
stateAlice.CurrentUsername = regAlice.Username!;
|
|
|
|
var stateBob = CreateClientState();
|
|
using var connBob = new ChatClientConnection(stateBob);
|
|
var regBob = await connBob.RegisterAsync("BobPushDm", "Pass123!");
|
|
stateBob.Token = regBob.Token!;
|
|
stateBob.CurrentUserId = regBob.UserId!;
|
|
stateBob.CurrentUsername = regBob.Username!;
|
|
|
|
await connAlice.StartWebSocketAsync();
|
|
await connBob.StartWebSocketAsync();
|
|
await Task.Delay(250);
|
|
|
|
// Register a simulated browser Web Push subscription for Bob
|
|
var (subPub, subPriv) = GsDChat.Core.Security.WebPushCrypto.GenerateVapidKeys();
|
|
byte[] authBytes = new byte[16];
|
|
System.Security.Cryptography.RandomNumberGenerator.Fill(authBytes);
|
|
string subAuth = GsDChat.Core.Security.WebPushCrypto.Base64UrlEncode(authBytes);
|
|
|
|
using var http = new HttpClient { BaseAddress = new Uri(_serverUrl) };
|
|
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", stateBob.Token);
|
|
var subPayload = JsonSerializer.Serialize(new PushSubscribeRequest
|
|
{
|
|
Endpoint = $"http://127.0.0.1:{pushPort}/push-sink",
|
|
P256dh = subPub,
|
|
Auth = subAuth,
|
|
UserAgent = "Xunit-Push-Test"
|
|
});
|
|
var subRes = await http.PostAsync("/api/push/subscribe", new StringContent(subPayload, Encoding.UTF8, "application/json"));
|
|
Assert.True(subRes.IsSuccessStatusCode);
|
|
|
|
// Start E2EE DM between Alice and Bob
|
|
await connAlice.StartDmAsync("BobPushDm");
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (stateAlice.DirectMessages.Count > 0 && stateBob.DirectMessages.Count > 0) break;
|
|
await Task.Delay(100);
|
|
}
|
|
string dmId = stateAlice.DirectMessages[0].Id;
|
|
|
|
Assert.True((await connAlice.UnlockOrInitializeE2eeWithPinAsync("alice-pin-123")).Success);
|
|
Assert.True((await connBob.UnlockOrInitializeE2eeWithPinAsync("bob-pin-456")).Success);
|
|
|
|
for (int i = 0; i < 20; i++)
|
|
{
|
|
if (!string.IsNullOrEmpty(stateAlice.GetPeerPublicKeyForDm(stateAlice.DirectMessages[0]))) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
// Alice sends an E2EE DM to Bob
|
|
string secretText = "Secret Inbox & Push DM payload!";
|
|
await connAlice.SendChatMessageAsync(dmId, secretText);
|
|
|
|
for (int i = 0; i < 30; i++)
|
|
{
|
|
if (stateBob.UnreadInboxCount >= 1 && receivedEncryptedPushBody != null) break;
|
|
await Task.Delay(100);
|
|
}
|
|
|
|
// 1. Verify Server DB stored only ciphertext in inbox_items
|
|
var dbInboxItems = await db.GetInboxItemsForUserAsync(stateBob.CurrentUserId);
|
|
Assert.Single(dbInboxItems);
|
|
Assert.True(dbInboxItems[0].IsEncrypted);
|
|
Assert.StartsWith("E2EE:v1:", dbInboxItems[0].ContentPreview);
|
|
Assert.DoesNotContain("Secret Inbox", dbInboxItems[0].ContentPreview);
|
|
|
|
// 2. Verify Bob's client decrypted the Inbox item preview automatically using his unlocked E2EE key vault
|
|
var bobClientInbox = stateBob.GetInboxItems();
|
|
Assert.Single(bobClientInbox);
|
|
Assert.Equal(InboxCategories.DirectMessage, bobClientInbox[0].Category);
|
|
Assert.Equal(secretText, bobClientInbox[0].ContentPreview);
|
|
|
|
// 3. Verify WebPushService sent an RFC 8292 VAPID + RFC 8291 aes128gcm Push Notification to Bob's subscription
|
|
Assert.NotNull(receivedEncryptedPushBody);
|
|
Assert.Equal("aes128gcm", receivedContentEncoding);
|
|
Assert.NotNull(receivedAuthHeader);
|
|
Assert.StartsWith("vapid t=", receivedAuthHeader);
|
|
|
|
// Decrypt the Web Push payload as the browser would, and verify E2EE privacy is preserved in OS push banner
|
|
byte[] pushJsonBytes = GsDChat.Core.Security.WebPushCrypto.DecryptPayload(receivedEncryptedPushBody!, subPub, subPriv, subAuth);
|
|
string pushJson = Encoding.UTF8.GetString(pushJsonBytes);
|
|
Assert.Contains("New encrypted message from @AlicePushDm", pushJson);
|
|
Assert.DoesNotContain("Secret Inbox", pushJson);
|
|
}
|
|
finally
|
|
{
|
|
await pushEndpointApp.StopAsync();
|
|
}
|
|
}
|
|
}
|
|
|