using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Net.Sockets; using System.Numerics; using System.Text; using System.Threading; using System.Threading.Tasks; using GameCult.Networking; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using RustToDust.Core; using RustToDust.DirectoryService; using RustToDust.Net; using RustToDust.Ymir; using Xunit; namespace RustToDust.Tests { public sealed class LobbyAndDirectoryTests { private static async Task<(WebApplication App, string BaseUrl)> StartDirectoryServerAsync(DirectoryRegistryOptions? options = null) { var opts = options ?? new DirectoryRegistryOptions(); var app = DirectoryApp.Build(Array.Empty(), opts); app.Urls.Clear(); app.Urls.Add("http://127.0.0.1:0"); await app.StartAsync(); string baseUrl = app.Urls.First(); return (app, baseUrl); } private static void PumpHostAndClients(ServerMatchHost host, params RemoteArenaSession[] clients) { long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); host.StepOnce(nowMs); for (int i = 0; i < clients.Length; i++) { clients[i].PumpNetwork(nowMs); } } private static void PumpListenHostAndClient(ListenHostArenaSession listenHost, RemoteArenaSession client, int ticks = 1) { for (int i = 0; i < ticks; i++) { listenHost.SubmitLocalInput(default, isPhysicsTick: true); client.PumpNetwork(); Thread.Sleep(2); } } [Fact] public async Task Directory_Heartbeat_LeaseTokenSecrecy_AuthRejection_LoopbackSpoof_And_TtlExpiry() { var now = DateTimeOffset.UtcNow; var opts = new DirectoryRegistryOptions { EntryTtl = TimeSpan.FromMilliseconds(350), ReaperInterval = TimeSpan.FromMilliseconds(60), UtcNow = () => now }; var (app, baseUrl) = await StartDirectoryServerAsync(opts); try { using var http = new HttpClient { BaseAddress = new Uri(baseUrl) }; // 1. Register with empty publicHost behind simulated nginx X-Real-IP -> auto-resolves to caller IP using var regReq = new HttpRequestMessage(HttpMethod.Post, "/api/v1/servers/heartbeat") { Content = JsonContent.Create(new DirectoryHeartbeatRequest { Name = "Yggdrasil Ring", PublicHost = "", UdpPort = 3076, Map = "sion", Seed = 77, Humans = 2, MaxHumans = 12, Phase = "Lobby", Wave = 0 }) }; regReq.Headers.TryAddWithoutValidation("X-Real-IP", "203.0.113.42"); using var regResp = await http.SendAsync(regReq); Assert.Equal(HttpStatusCode.OK, regResp.StatusCode); var ack = await regResp.Content.ReadFromJsonAsync(); Assert.NotNull(ack); Assert.NotEqual(Guid.Empty, ack!.ServerId); Assert.False(string.IsNullOrWhiteSpace(ack.LeaseToken)); Assert.True(ack.TtlSeconds >= 1); // 2. GET /api/v1/servers returns resolved publicHost and NEVER exposes leaseToken string rawListJson = await http.GetStringAsync("/api/v1/servers"); Assert.DoesNotContain(ack.LeaseToken, rawListJson, StringComparison.Ordinal); var list = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http); Assert.Single(list); Assert.Equal(ack.ServerId, list[0].ServerId); Assert.Equal("203.0.113.42", list[0].PublicHost); Assert.Equal("sion", list[0].Map); Assert.Equal("Lobby", list[0].Phase); // 3. Non-loopback X-Real-IP attempting to spoof loopback publicHost is rejected (400) foreach (string spoofHost in new[] { "127.0.0.1", "localhost", "::1" }) { using var spoofReq = new HttpRequestMessage(HttpMethod.Post, "/api/v1/servers/heartbeat") { Content = JsonContent.Create(new DirectoryHeartbeatRequest { Name = "Spoofed", PublicHost = spoofHost, UdpPort = 3076 }) }; spoofReq.Headers.TryAddWithoutValidation("X-Real-IP", "203.0.113.42"); using var spoofResp = await http.SendAsync(spoofReq); Assert.Equal(HttpStatusCode.BadRequest, spoofResp.StatusCode); } // 4. Wrong leaseToken on refresh -> 403, entry stays intact using var badRefresh = await http.PostAsJsonAsync("/api/v1/servers/heartbeat", new DirectoryHeartbeatRequest { ServerId = ack.ServerId, LeaseToken = "wrong-token-value", Name = "Hijacked", PublicHost = "203.0.113.42", UdpPort = 3076 }); Assert.Equal(HttpStatusCode.Forbidden, badRefresh.StatusCode); // 5. Wrong leaseToken on DELETE -> 403, entry stays intact using var badDeleteReq = new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/servers/{ack.ServerId}"); badDeleteReq.Headers.TryAddWithoutValidation("X-Lease-Token", "wrong-token-value"); using var badDeleteResp = await http.SendAsync(badDeleteReq); Assert.Equal(HttpStatusCode.Forbidden, badDeleteResp.StatusCode); var stillPresent = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http); Assert.Single(stillPresent); Assert.Equal("Yggdrasil Ring", stillPresent[0].Name); // 6. Valid leaseToken refresh succeeds and keeps entry alive using var goodRefresh = await http.PostAsJsonAsync("/api/v1/servers/heartbeat", new DirectoryHeartbeatRequest { ServerId = ack.ServerId, LeaseToken = ack.LeaseToken, Name = "Yggdrasil Ring Updated", PublicHost = "203.0.113.42", UdpPort = 3076, Humans = 5, Phase = "Active", Wave = 1 }); Assert.Equal(HttpStatusCode.OK, goodRefresh.StatusCode); // 7. Advance clock past TTL -> entry expires cleanly and disappears now = now + TimeSpan.FromMilliseconds(500); await Task.Delay(150); var afterExpiry = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http); Assert.Empty(afterExpiry); } finally { await app.StopAsync(); await app.DisposeAsync(); } } [Fact] public async Task DirectoryReporter_Registers_Updates_And_DeregistersOnDispose() { var (app, baseUrl) = await StartDirectoryServerAsync(); try { int humans = 1; string phase = "Lobby"; var reporter = new DirectoryReporter( baseUrl, () => new DirectoryHeartbeatSnapshot( "Reporter Test Ring", "127.0.0.1", 3079, "desert", 42, humans, 12, phase, 0), heartbeatInterval: TimeSpan.FromSeconds(30)); try { var deadline = DateTime.UtcNow.AddSeconds(15); IReadOnlyList servers = Array.Empty(); while (DateTime.UtcNow < deadline) { servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl); if (servers.Count > 0) break; await Task.Delay(25); } Assert.Single(servers); Assert.Equal("Reporter Test Ring", servers[0].Name); Assert.Equal(1, servers[0].Humans); humans = 4; phase = "Active"; reporter.NotifyChanged(); deadline = DateTime.UtcNow.AddSeconds(15); while (DateTime.UtcNow < deadline) { servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl); if (servers.Count == 1 && servers[0].Humans == 4 && servers[0].Phase == "Active") break; await Task.Delay(25); } Assert.Equal(4, servers[0].Humans); Assert.Equal("Active", servers[0].Phase); } finally { await reporter.DisposeAsync(); } var afterDispose = await DirectoryBrowserClient.FetchServersAsync(baseUrl); Assert.Empty(afterDispose); } finally { await app.StopAsync(); await app.DisposeAsync(); } } [Fact] public async Task StatelessUdpPing_CoexistsWithActiveRemoteSession_AndHandlesMalformedPingsSafely() { using var host = new ServerMatchHost( IPAddress.Loopback, 0, seed: 77, mapKind: ArenaMapKind.Desert, serverName: "Ping Coexistence Arena", startInLobby: false); using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "ProbePilot"); var joinDeadline = DateTime.UtcNow.AddSeconds(3); while (!client.IsJoined && DateTime.UtcNow < joinDeadline) { PumpHostAndClients(host, client); await Task.Delay(5); } Assert.True(client.IsJoined); // Drive and fire concurrently on the active RUDP session while probing RTDP pings for (int i = 0; i < 15; i++) { client.SubmitLocalInput(new PlayerInput(1f, 0.25f, 30f, 40f, Fire: true, InteractPickup: false, Brake: false), isPhysicsTick: true); PumpHostAndClients(host, client); } var target = new IPEndPoint(IPAddress.Loopback, host.BoundPort); var pingTask = Task.Run(async () => { var results = new List(4); for (int i = 0; i < 4; i++) { results.Add(await ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2))); } return results; }); while (!pingTask.IsCompleted) { client.SubmitLocalInput(new PlayerInput(0.8f, -0.1f, 25f, 35f, Fire: true, InteractPickup: false, Brake: false), isPhysicsTick: true); PumpHostAndClients(host, client); await Task.Delay(3); } var pingResults = await pingTask; Assert.Equal(4, pingResults.Count); foreach (var r in pingResults) { Assert.True(r.Success, "Expected stateless RTDP ping to succeed alongside active RUDP session"); Assert.True(r.Summary.HasValue); Assert.Equal("Ping Coexistence Arena", r.Summary!.Value.ServerName); Assert.Equal(1, r.Summary.Value.Humans); Assert.Equal(12, r.Summary.Value.MaxHumans); Assert.Equal(MatchPhase.Active, r.Summary.Value.Phase); Assert.Equal(ArenaMapKind.Desert, r.Summary.Value.MapKind); Assert.Equal(77, r.Summary.Value.Seed); Assert.True(r.Summary.Value.AcceptingJoin); Assert.True(SnapshotCodec.EncodePong(r.Summary.Value).Length < 110); } Assert.Equal(0, host.TransportPacketsDropped); Assert.True(client.ConnectionStatus.Connected); // Send truncated "RTDP" packet (< 16B) and bogus magic packet; host must not crash or drop RUDP peer using (var rawSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { byte[] truncatedPing = Encoding.ASCII.GetBytes("RTDP\x01\x01short"); // 11 bytes rawSock.SendTo(truncatedPing, target); for (int i = 0; i < 4; i++) { PumpHostAndClients(host, client); await Task.Delay(2); } Assert.Equal(0, host.TransportPacketsDropped); byte[] bogusMagic = Encoding.ASCII.GetBytes("JUNK_NOT_RTDP_OR_CNR0_PAYLOAD_DATA"); rawSock.SendTo(bogusMagic, target); for (int i = 0; i < 4; i++) { PumpHostAndClients(host, client); await Task.Delay(2); } } Assert.True(client.IsJoined); Assert.True(client.ConnectionStatus.Connected); // Valid ping still succeeds after malformed datagrams var finalPingTask = ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2)); while (!finalPingTask.IsCompleted) { PumpHostAndClients(host, client); await Task.Delay(2); } var finalPing = await finalPingTask; Assert.True(finalPing.Success); } [Fact] public void Lobby_NonHostConfigAndStartRejected_AndLocalOutcomeIsActive() { using var listenHost = new ListenHostArenaSession( IPAddress.Loopback, 0, seed: 42, mapKind: ArenaMapKind.Desert, startInLobby: true, serverName: "Host Authority Lobby"); using var client = new RemoteArenaSession( new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort), "Guest"); var joinDeadline = DateTime.UtcNow.AddSeconds(3); while (!client.IsJoined && DateTime.UtcNow < joinDeadline) { PumpListenHostAndClient(listenHost, client); } Assert.True(client.IsJoined); Assert.Equal(MatchPhase.Lobby, listenHost.ViewState.Phase); Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase); Assert.Equal(ClientMatchOutcome.Active, listenHost.LocalOutcome); Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome); // Guest attempts unauthorized config change and launch Assert.True(client.RequestLobbyConfig(999, ArenaMapKind.Sion)); Assert.True(client.RequestLobbyStart()); PumpListenHostAndClient(listenHost, client, ticks: 15); Assert.Equal(MatchPhase.Lobby, listenHost.ViewState.Phase); Assert.Equal(ArenaMapKind.Desert, listenHost.ViewState.MapKind); Assert.Equal(42, listenHost.ViewState.Seed); Assert.Null(listenHost.LobbyState?.CountdownSeconds); Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase); Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome); } [Fact] public void Lobby_CountdownStartsWhenAllReady_CancelsOnUnready_AndResetsOnMapSwitch() { using var host = new ServerMatchHost( IPAddress.Loopback, 0, seed: 42, mapKind: ArenaMapKind.Desert, allowClientReset: true, startInLobby: true, minHumansToStart: 2); using var peerA = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Alpha"); using var peerB = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Bravo"); var deadline = DateTime.UtcNow.AddSeconds(3); while ((!peerA.IsJoined || !peerB.IsJoined) && DateTime.UtcNow < deadline) { PumpHostAndClients(host, peerA, peerB); Thread.Sleep(3); } Assert.True(peerA.IsJoined); Assert.True(peerB.IsJoined); // Peer A readies up; Peer B not ready -> no countdown yet Assert.True(peerA.SetLobbyReady(true)); for (int i = 0; i < 10; i++) { PumpHostAndClients(host, peerA, peerB); Thread.Sleep(2); } Assert.Null(host.Lobby?.CountdownSeconds); // Peer B readies up -> countdown starts Assert.True(peerB.SetLobbyReady(true)); for (int i = 0; i < 15; i++) { PumpHostAndClients(host, peerA, peerB); Thread.Sleep(2); } Assert.NotNull(host.Lobby?.CountdownSeconds); Assert.True(host.Lobby!.CountdownSeconds!.Value > 0f && host.Lobby.CountdownSeconds.Value < 5.0f); Assert.NotNull(peerA.LobbyState?.CountdownSeconds); // Peer B un-readies -> countdown cancels and Wave 0 does NOT launch Assert.True(peerB.SetLobbyReady(false)); for (int i = 0; i < 15; i++) { PumpHostAndClients(host, peerA, peerB); Thread.Sleep(2); } Assert.Null(host.Lobby?.CountdownSeconds); Assert.Null(peerA.LobbyState?.CountdownSeconds); Assert.Equal(MatchPhase.Lobby, host.Session.State.Phase); Assert.Empty(host.Session.State.OrbitalDrop.ActivePods); // Authorized config switch in Lobby resets ready flags and syncs all peers Assert.True(peerA.SetLobbyReady(true)); for (int i = 0; i < 6; i++) { PumpHostAndClients(host, peerA, peerB); Thread.Sleep(2); } Assert.True(host.ConfigureLobby(peerA.LocalContenderId, 99, ArenaMapKind.Sion)); for (int i = 0; i < 15; i++) { PumpHostAndClients(host, peerA, peerB); Thread.Sleep(2); } Assert.Equal(MatchPhase.Lobby, host.Session.State.Phase); Assert.Equal(ArenaMapKind.Sion, host.Session.State.MapKind); Assert.Equal(99, host.Session.State.Seed); Assert.Equal(ArenaMapKind.Sion, peerA.ViewState.MapKind); Assert.Equal(99, peerA.ViewState.Seed); Assert.Equal(ArenaMapKind.Sion, peerB.ViewState.MapKind); Assert.Equal(99, peerB.ViewState.Seed); Assert.All(host.Lobby!.Slots.Where(s => s.IsHuman), s => Assert.False(s.IsReady)); Assert.Equal(ClientMatchOutcome.Active, peerA.LocalOutcome); Assert.Equal(ClientMatchOutcome.Active, peerB.LocalOutcome); } [Fact] public void Lobby_IdleClientKeptAlivePastIdleTimeout_WithActiveOutcome() { using var host = new ServerMatchHost( IPAddress.Loopback, 0, seed: 42, mapKind: ArenaMapKind.Desert, startInLobby: true); using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "IdlePilot"); long simNowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); for (int i = 0; i < 100 && !client.IsJoined; i++) { simNowMs += 20; host.StepOnce(simNowMs); client.PumpNetwork(simNowMs); Thread.Sleep(2); } Assert.True(client.IsJoined); // Advance 8.5 seconds (> IdleTimeoutMs 5000ms and > ClientDisconnectTimeoutMs 6000ms) with ZERO SubmitLocalInput for (int step = 0; step < 170; step++) { simNowMs += 50; host.StepOnce(simNowMs); client.PumpNetwork(simNowMs); } Assert.True(client.IsJoined); Assert.True(client.ConnectionStatus.Connected); Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome); Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase); Assert.Equal(1, host.ConnectedHumanCount); } [Fact] public void Lobby_SynchronizedLaunch_TransitionsToActiveAndDropsWave0AcrossHostAndRemote() { using var listenHost = new ListenHostArenaSession( IPAddress.Loopback, 0, seed: 42, mapKind: ArenaMapKind.Desert, startInLobby: true, minHumansToStart: 2); using var remote = new RemoteArenaSession( new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort), "DropMate"); var deadline = DateTime.UtcNow.AddSeconds(3); while (!remote.IsJoined && DateTime.UtcNow < deadline) { PumpListenHostAndClient(listenHost, remote); } Assert.True(remote.IsJoined); Assert.True(listenHost.SetLobbyReady(true)); Assert.True(remote.SetLobbyReady(true)); // Step 320 ticks (~5.33s at 60Hz) so the 5.0s countdown completes cleanly for (int tick = 0; tick < 330; tick++) { listenHost.SubmitLocalInput(default, isPhysicsTick: true); remote.PumpNetwork(); if (listenHost.ViewState.Phase == MatchPhase.Active && remote.ViewState.Phase == MatchPhase.Active && remote.ActivePods.Count > 0) { break; } Thread.Sleep(1); } // Pump a few extra frames to ensure all Wave 0 reliable events arrive on remote PumpListenHostAndClient(listenHost, remote, ticks: 10); Assert.Equal(MatchPhase.Active, listenHost.ViewState.Phase); Assert.Equal(MatchPhase.Active, remote.ViewState.Phase); Assert.Equal(ClientMatchOutcome.Active, listenHost.LocalOutcome); Assert.Equal(ClientMatchOutcome.Active, remote.LocalOutcome); Assert.True(listenHost.ActivePods.Count >= MatchState.ContenderCount); Assert.Equal(ContenderLifecycle.Deploying, listenHost.LocalContender.Lifecycle); Assert.Equal(ContenderLifecycle.Deploying, remote.LocalContender.Lifecycle); Assert.Contains(remote.ActivePods, p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == remote.LocalContenderId); var remoteEvents = new List(); remote.DrainSimEvents(remoteEvents); Assert.Contains(remoteEvents, e => e is MatchStartedEvent); } [Fact] public void CorePvs_RoundTripsMatchPhaseLobby_Within1152Bytes() { var state = new MatchState(seed: 42, ArenaMapKind.Desert, startInLobby: true); var local = state.Contenders[0]; local.Grid.SwapChassis(Catalog.Bastion); var contenders = new List(12); var walkers = new List(12); var specs = new List(10); for (int i = 0; i < 12; i++) { contenders.Add(new NetContenderState { SlotId = (byte)i, Alive = true, IsHuman = i < 2, Lifecycle = ContenderLifecycle.Deploying, Pos = new Vector3(i * 10f, 3f, -i * 5f), Rot = Quaternion.Identity, Vel = Vector3.Zero, CoreHpRatio = 1f }); var ws = new WalkerVisualSnapshot { LegCount = 4 }; walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws }); } byte[] payload = SnapshotCodec.EncodeCorePvs( 1, 5, 10, 0f, 0, 0, 772f, MatchPhase.Lobby, null, 0, 0xFFF, local, Vector3.Zero, contenders, walkers, specs); byte[] wireFrame = SnapshotCodec.WrapLatest(payload, 1, 5); byte[] rudpDatagram = CultNetRudpPacketCodec.Encode(new CultNetRudpPacket { ConnectionId = 0x52544431, PacketType = CultNetRudpPacketType.Data, ChannelId = SnapshotCodec.ChannelLatest, Sequence = 5, Sequenced = true, Payload = wireFrame }); Assert.True(rudpDatagram.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Lobby CorePvs UDP datagram {rudpDatagram.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); Assert.True(SnapshotCodec.TryDecodeCorePvs(payload, out var decoded)); Assert.Equal(MatchPhase.Lobby, decoded.Phase); Assert.Null(decoded.WinnerContenderId); // Also verify Completed + WinnerContenderId still round-trips via bit 2 (0x04) byte[] completedPayload = SnapshotCodec.EncodeCorePvs( 1, 6, 12, 100f, 0, 0, 120f, MatchPhase.Completed, 3, 0, 0xFFF, local, Vector3.Zero, contenders, walkers, specs); Assert.True(SnapshotCodec.TryDecodeCorePvs(completedPayload, out var decodedCompleted)); Assert.Equal(MatchPhase.Completed, decodedCompleted.Phase); Assert.Equal(3, decodedCompleted.WinnerContenderId); } [Fact] public async Task StatelessUdpPing_HandlesMultiByteUtf8ServerName_WithoutOverflow() { string multiByteName = new string('\u2022', 24); using var host = new ServerMatchHost( IPAddress.Loopback, 0, seed: 77, mapKind: ArenaMapKind.Desert, serverName: multiByteName, startInLobby: true); var target = new IPEndPoint(IPAddress.Loopback, host.BoundPort); var pingTask = ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2)); while (!pingTask.IsCompleted) { host.PollStatelessPings(); await Task.Delay(5); } var res = await pingTask; Assert.True(res.Success); Assert.NotNull(res.Summary); Assert.Equal(new string('\u2022', 16), res.Summary!.Value.ServerName); } } }