using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; 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.Core.Security; using GsDChat.Server.Configuration; using GsDChat.Server.Data; using GsDChat.Server.Services; using GsDChat.Server.WebSockets; using Xunit; namespace GsDChat.Tests; public class VoiceCallTests : IAsyncLifetime { private readonly string _testDir; private WebApplication? _app; private int _port; private string _serverUrl = string.Empty; public VoiceCallTests() { _testDir = Path.Combine(Path.GetTempPath(), "gsdchat_voice_tests_" + Guid.NewGuid().ToString("N")); } public async Task InitializeAsync() { Environment.SetEnvironmentVariable("GSDCHAT_DISABLE_OS_AUDIO", "1"); using var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); _port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); _serverUrl = $"http://127.0.0.1:{_port}"; var builder = WebApplication.CreateBuilder(); builder.WebHost.UseUrls(_serverUrl); builder.Logging.ClearProviders(); var (vapidPub, vapidPriv) = WebPushCrypto.GenerateVapidKeys(); var serverOptions = new ServerOptions { Host = "127.0.0.1", Port = _port, UseTls = false, DataDirectory = _testDir, ServerName = "Voice Call Test Server", EnableVoiceCalls = true, AllowVoiceRelayFallback = true, MaxVoiceCallUsers = 8, StunServers = new List { "stun:stun.l.google.com:19302" }, TurnServers = new List { new IceServerConfig { Urls = new List { "turn:turn.example.org:3478?transport=tcp" }, Username = "turnuser", Credential = "turnpass" } }, VapidPublicKey = vapidPub, VapidPrivateKey = vapidPriv }; builder.Services.AddSingleton(serverOptions); builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory)); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); _app = builder.Build(); var db = _app.Services.GetRequiredService(); await db.InitializeAsync(); _app.UseWebSockets(); _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, AllowDmE2ee = opt.AllowDmE2ee, MaxGroupChatUsers = opt.MaxGroupChatUsers, EnableVoiceCalls = opt.EnableVoiceCalls, AllowVoiceRelayFallback = opt.AllowVoiceRelayFallback, MaxVoiceCallUsers = opt.MaxVoiceCallUsers, IceServers = opt.GetIceServers() })); _app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth) => { 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) => { var res = await auth.LoginAsync(req); return res.Success ? Results.Ok(res) : Results.BadRequest(res); }); _app.MapGet("/ws", async (HttpContext context, ChatWebSocketManager wsManager, IAuthService auth, ServerOptions options) => { if (!context.WebSockets.IsWebSocketRequest) { context.Response.StatusCode = 400; return; } string? token = null; if (context.Request.Headers.TryGetValue("Authorization", out var h) && h.ToString().StartsWith("Bearer ")) token = h.ToString().Substring(7).Trim(); else if (context.Request.Query.TryGetValue("token", out var q)) token = q.ToString(); var user = await auth.ValidateSessionTokenAsync(token ?? ""); if (user == null) { context.Response.StatusCode = 401; return; } using var ws = await context.WebSockets.AcceptWebSocketAsync(); await wsManager.HandleClientAsync(ws, user, context.RequestAborted, options.MaxWebSocketMessageSizeBytes); }); await _app.StartAsync(); } public async Task DisposeAsync() { if (_app != null) { await _app.StopAsync(); await _app.DisposeAsync(); } try { if (Directory.Exists(_testDir)) { Directory.Delete(_testDir, true); } } catch { } } private ClientState CreateClientState(string name) { return new ClientState(Path.Combine(_testDir, $"e2ee_{name}.json")) { ServerUrl = _serverUrl }; } private static async Task WaitUntilAsync(Func condition, int timeoutMs = 4000) { var sw = System.Diagnostics.Stopwatch.StartNew(); while (sw.ElapsedMilliseconds < timeoutMs) { if (condition()) return true; await Task.Delay(25); } return condition(); } [Fact] public void G711AudioCodec_MuLawRoundTrip_ShouldPreserveSineWaveAndComputeRms() { const int sampleCount = 640; // 40ms @ 16kHz byte[] pcm16 = new byte[sampleCount * 2]; for (int i = 0; i < sampleCount; i++) { short sample = (short)(Math.Sin(2.0 * Math.PI * 440.0 * i / 16000.0) * 4000); pcm16[i * 2] = (byte)(sample & 0xFF); pcm16[i * 2 + 1] = (byte)((sample >> 8) & 0xFF); } Assert.Equal(0f, G711AudioCodec.ComputeRmsLevelFromPcm16(new byte[128])); double rmsPcm = G711AudioCodec.ComputeRmsLevelFromPcm16(pcm16); Assert.InRange(rmsPcm, 0.20, 0.35); byte[] muLaw = G711AudioCodec.EncodePcm16ToMuLaw(pcm16); Assert.Equal(sampleCount, muLaw.Length); double rmsMuLaw = G711AudioCodec.ComputeRmsLevelFromMuLaw(muLaw); Assert.InRange(rmsMuLaw, 0.20, 0.35); byte[] decodedPcm16 = G711AudioCodec.DecodeMuLawToPcm16(muLaw); Assert.Equal(pcm16.Length, decodedPcm16.Length); // Verify G.711 logarithmic quantization stays close to original signal for (int i = 0; i < sampleCount; i++) { short orig = (short)(pcm16[i * 2] | (pcm16[i * 2 + 1] << 8)); short dec = (short)(decodedPcm16[i * 2] | (decodedPcm16[i * 2 + 1] << 8)); Assert.True(Math.Abs(orig - dec) <= 750, $"Sample {i} delta too large: orig={orig}, dec={dec}"); } } [Fact] public void E2eeCrypto_VoiceAudioFrameEncryption_ShouldRoundTripAndRejectTampering() { var (alicePub, alicePriv) = E2eeCrypto.GenerateKeyPair(); var (bobPub, bobPriv) = E2eeCrypto.GenerateKeyPair(); byte[] originalAudio = new byte[640]; RandomNumberGenerator.Fill(originalAudio); string encryptedFrame = E2eeCrypto.EncryptAudioFrame(originalAudio, alicePriv, bobPub); Assert.True(E2eeCrypto.IsVoiceEncryptedPayload(encryptedFrame)); Assert.StartsWith("VENC:v1:", encryptedFrame); byte[]? decryptedByBob = E2eeCrypto.DecryptAudioFrame(encryptedFrame, bobPriv, alicePub); Assert.NotNull(decryptedByBob); Assert.Equal(originalAudio, decryptedByBob); // Tamper with a third party's keypair -> should fail authentication tag verification var (_, malloryPriv) = E2eeCrypto.GenerateKeyPair(); byte[]? decryptedByMallory = E2eeCrypto.DecryptAudioFrame(encryptedFrame, malloryPriv, alicePub); Assert.Null(decryptedByMallory); // Also test ephemeral UDP P2P session key encryption byte[] sessionKey = RandomNumberGenerator.GetBytes(32); string encryptedUdpPayload = E2eeCrypto.EncryptWithSessionKey(originalAudio, sessionKey); Assert.True(E2eeCrypto.IsVoiceEncryptedPayload(encryptedUdpPayload)); byte[]? decryptedUdpPacket = E2eeCrypto.DecryptWithSessionKey(encryptedUdpPayload, sessionKey); Assert.NotNull(decryptedUdpPacket); Assert.Equal(originalAudio, decryptedUdpPacket); } [Fact] public async Task StunClient_BindingRequestAndResponse_ShouldDiscoverXorMappedEndpoint() { var (host, port) = StunClient.ParseStunUri("stun:stun.l.google.com:19302"); Assert.Equal("stun.l.google.com", host); Assert.Equal(19302, port); // Spin up a local loopback RFC 5389 STUN responder using var stunServerSocket = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0)); int stunPort = ((IPEndPoint)stunServerSocket.Client.LocalEndPoint!).Port; using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var responderTask = Task.Run(async () => { var received = await stunServerSocket.ReceiveAsync(cts.Token); Assert.True(received.Buffer.Length >= 20); ReadOnlySpan txId = received.Buffer.AsSpan(8, 12); byte[] response = StunClient.CreateBindingSuccessResponse(txId, received.RemoteEndPoint); await stunServerSocket.SendAsync(response, response.Length, received.RemoteEndPoint); }, cts.Token); using var clientSocket = new UdpClient(new IPEndPoint(IPAddress.Loopback, 0)); int expectedLocalPort = ((IPEndPoint)clientSocket.Client.LocalEndPoint!).Port; IPEndPoint? discovered = await StunClient.QueryPublicEndpointAsync( clientSocket, $"stun:127.0.0.1:{stunPort}", cts.Token); await responderTask; Assert.NotNull(discovered); Assert.Equal(IPAddress.Loopback, discovered!.Address); Assert.Equal(expectedLocalPort, discovered.Port); } [Fact] public void ServerOptions_GetIceServers_ShouldIncludeStunAndTurnCredentials() { var opts = new ServerOptions { StunServers = new List { "stun:stun.l.google.com:19302" }, TurnServers = new List { new IceServerConfig { Urls = new List { "turns:turn.example.com:443?transport=tcp" }, Username = "alice", Credential = "secret123" } } }; var ice = opts.GetIceServers(); Assert.Equal(2, ice.Count); Assert.Contains("stun:stun.l.google.com:19302", ice[0].Urls); Assert.Null(ice[0].Username); Assert.Contains("turns:turn.example.com:443?transport=tcp", ice[1].Urls); Assert.Equal("alice", ice[1].Username); Assert.Equal("secret123", ice[1].Credential); } [Fact] public async Task DirectMessageVoiceCall_RingingAcceptAndEncryptedSinglePortRelay_ShouldSucceed() { var aliceState = CreateClientState("alice"); var bobState = CreateClientState("bob"); using var alice = new ChatClientConnection(aliceState, allowInsecure: true); using var bob = new ChatClientConnection(bobState, allowInsecure: true); var aliceReg = await alice.RegisterAsync("voice_alice", "Pass123!", null, null); var bobReg = await bob.RegisterAsync("voice_bob", "Pass123!", null, null); Assert.True(aliceReg.Success); Assert.True(bobReg.Success); await alice.StartWebSocketAsync(); await bob.StartWebSocketAsync(); await alice.UnlockOrInitializeE2eeWithPinAsync("1111"); await bob.UnlockOrInitializeE2eeWithPinAsync("2222"); Assert.True(await WaitUntilAsync(() => aliceState.Channels.Count > 0 && bobState.Channels.Count > 0)); // Start a DM between Alice and Bob await alice.StartDmAsync("voice_bob"); Assert.True(await WaitUntilAsync(() => aliceState.DirectMessages.Count == 1 && bobState.DirectMessages.Count == 1)); string dmChannelId = aliceState.DirectMessages[0].Id; // 1. Alice starts a DM voice call -> state becomes 'Ringing' await alice.StartVoiceCallAsync(dmChannelId); Assert.True(await WaitUntilAsync(() => bobState.ActiveVoiceCalls.TryGetValue(dmChannelId, out var s) && s.Status == VoiceCallStatus.Ringing)); // 2. Bob accepts the DM voice call -> state becomes 'Active' with both participants await bob.AcceptVoiceCallAsync(dmChannelId); Assert.True(await WaitUntilAsync(() => aliceState.ActiveVoiceCalls.TryGetValue(dmChannelId, out var s) && s.Status == VoiceCallStatus.Active && s.Participants.Count == 2)); // 3. Test Single-Port WebSocket Audio Relay with E2EE encrypted voice frame int prevFrames = bobState.VoiceFramesReceivedCount; byte[] samplePcm16 = new byte[1280]; // 640 samples (40ms @ 16kHz) for (int i = 0; i < 640; i++) { short val = (short)(Math.Sin(2.0 * Math.PI * 440.0 * i / 16000.0) * 12000); samplePcm16[i * 2] = (byte)(val & 0xFF); samplePcm16[i * 2 + 1] = (byte)((val >> 8) & 0xFF); } byte[] sampleMuLaw = G711AudioCodec.EncodePcm16ToMuLaw(samplePcm16); string encryptedPayload = E2eeCrypto.EncryptAudioFrame( sampleMuLaw, aliceState.PrivateKeyBase64, bobState.PublicKeyBase64); await alice.SendVoiceAudioFrameAsync(new VoiceAudioFramePacket { ChannelId = dmChannelId, Sequence = 42, Codec = "ulaw-16k", DataBase64 = encryptedPayload, IsEncrypted = true, SenderPublicKey = aliceState.PublicKeyBase64, SpeakingLevel = 0.25f }); Assert.True(await WaitUntilAsync(() => bobState.VoiceFramesReceivedCount > prevFrames)); Assert.Equal(aliceReg.UserId, bobState.LastVoiceFrameSenderId); Assert.NotNull(bobState.LastReceivedVoiceMuLaw); Assert.Equal(sampleMuLaw, bobState.LastReceivedVoiceMuLaw); Assert.NotNull(bobState.LastReceivedVoicePcm16); Assert.Equal(1280, bobState.LastReceivedVoicePcm16!.Length); // 4. Alice hangs up -> DM call ends await alice.LeaveVoiceCallAsync(dmChannelId); Assert.True(await WaitUntilAsync(() => !bobState.ActiveVoiceCalls.ContainsKey(dmChannelId))); } [Fact] public async Task DirectMessageVoiceCall_DeclineRingingCall_ShouldEndCallSession() { var aliceState = CreateClientState("decline_alice"); var bobState = CreateClientState("decline_bob"); using var alice = new ChatClientConnection(aliceState, allowInsecure: true); using var bob = new ChatClientConnection(bobState, allowInsecure: true); var aliceReg = await alice.RegisterAsync("decline_alice", "Pass123!", null, null); var bobReg = await bob.RegisterAsync("decline_bob", "Pass123!", null, null); Assert.True(aliceReg.Success); Assert.True(bobReg.Success); await alice.StartWebSocketAsync(); await bob.StartWebSocketAsync(); Assert.True(await WaitUntilAsync(() => aliceState.Channels.Count > 0 && bobState.Channels.Count > 0)); await alice.StartDmAsync("decline_bob"); Assert.True(await WaitUntilAsync(() => aliceState.DirectMessages.Count == 1 && bobState.DirectMessages.Count == 1)); string dmChannelId = aliceState.DirectMessages[0].Id; await alice.StartVoiceCallAsync(dmChannelId); Assert.True(await WaitUntilAsync(() => bobState.ActiveVoiceCalls.TryGetValue(dmChannelId, out var s) && s.Status == VoiceCallStatus.Ringing)); await bob.DeclineVoiceCallAsync(dmChannelId); Assert.True(await WaitUntilAsync(() => !aliceState.ActiveVoiceCalls.ContainsKey(dmChannelId) && !bobState.ActiveVoiceCalls.ContainsKey(dmChannelId))); } [Fact] public async Task ChannelVoiceRoom_MultiPeerJoinStateUpdateAndRelay_ShouldSucceed() { var s1 = CreateClientState("room_u1"); var s2 = CreateClientState("room_u2"); var s3 = CreateClientState("room_u3"); using var user1 = new ChatClientConnection(s1, allowInsecure: true); using var user2 = new ChatClientConnection(s2, allowInsecure: true); using var user3 = new ChatClientConnection(s3, allowInsecure: true); var r1 = await user1.RegisterAsync("room_u1", "Pass123!", null, null); var r2 = await user2.RegisterAsync("room_u2", "Pass123!", null, null); var r3 = await user3.RegisterAsync("room_u3", "Pass123!", null, null); Assert.True(r1.Success); Assert.True(r2.Success); Assert.True(r3.Success); await user1.StartWebSocketAsync(); await user2.StartWebSocketAsync(); await user3.StartWebSocketAsync(); Assert.True(await WaitUntilAsync(() => s1.Channels.Count > 0 && s2.Channels.Count > 0 && s3.Channels.Count > 0)); string generalChannelId = s1.Channels[0].Id; // User 1 starts voice room in #general -> immediately Active await user1.StartVoiceCallAsync(generalChannelId); Assert.True(await WaitUntilAsync(() => s2.ActiveVoiceCalls.TryGetValue(generalChannelId, out var s) && s.Status == VoiceCallStatus.Active && s.Participants.Count == 1)); // User 2 and User 3 join the voice room await user2.StartVoiceCallAsync(generalChannelId); await user3.StartVoiceCallAsync(generalChannelId); Assert.True(await WaitUntilAsync(() => s1.ActiveVoiceCalls.TryGetValue(generalChannelId, out var s) && s.Participants.Count == 3)); // User 2 mutes microphone and switches to relay mode -> broadcast to room await user2.ToggleVoiceMuteAsync(true); await user2.ToggleVoiceRelayModeAsync(true); Assert.True(await WaitUntilAsync(() => { if (!s1.ActiveVoiceCalls.TryGetValue(generalChannelId, out var s)) return false; var p2 = s.Participants.FirstOrDefault(p => p.UserId == r2.UserId); return p2 != null && p2.IsMuted && p2.TransportMode == VoiceTransportModes.Relay; })); // User 1 sends a relayed audio frame -> both User 2 and User 3 receive it, but User 1 does not echo to self byte[] testMuLaw = new byte[640]; Array.Fill(testMuLaw, (byte)0x7F); await user1.SendVoiceAudioFrameAsync(new VoiceAudioFramePacket { ChannelId = generalChannelId, Sequence = 7, Codec = "ulaw-16k", DataBase64 = Convert.ToBase64String(testMuLaw), SpeakingLevel = 0.2f }); Assert.True(await WaitUntilAsync(() => s2.VoiceFramesReceivedCount > 0 && s3.VoiceFramesReceivedCount > 0)); Assert.Equal(0, s1.VoiceFramesReceivedCount); Assert.Equal(testMuLaw, s2.LastReceivedVoiceMuLaw); Assert.Equal(testMuLaw, s3.LastReceivedVoiceMuLaw); } }