using System.Collections.Concurrent; using System.Text.Json; using System.Text.Json.Nodes; namespace UCVL.VPNPlus; internal static class PublicTailnetSelectionSelfTest { internal static async Task RunAsync() { var checks = new Dictionary(); ConfigResponse Config(string slug, string route = "smart", string scope = "public") { var fixture = JsonNode.Parse(""" {"config_contract":2,"connection_scope":"public","node":{"slug":"fixture"},"route_mode":"smart", "tailscale_endpoint":{"contract":1,"node_slug":"fixture","address":"100.64.0.2","port":10803}, "config":{"inbounds":[],"outbounds":[{"tag":"proxy","protocol":"vless", "settings":{"vnext":[{"address":"fixture.example.com","port":11082,"users":[{"id":"fixture-id"}]}]}, "streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"fixture.example.com","publicKey":"fixture-key"}}}], "routing":{"rules":[]}}} """)!; fixture["connection_scope"] = scope; fixture["node"]!["slug"] = slug; fixture["route_mode"] = route; fixture["tailscale_endpoint"]!["node_slug"] = slug; return JsonSerializer.Deserialize(fixture.ToJsonString())!; } NodeInfo Node(string slug) => new() { Slug = slug }; var requested = new ConcurrentQueue(); var loaded = new ConcurrentDictionary(); Task Load(string slug, CancellationToken _) { requested.Enqueue(slug); var response = Config(slug); loaded[slug] = response; return Task.FromResult(response); } Task Reachable(string _, int __, CancellationToken ___) => Task.FromResult(true); var candidates = await PublicTailnetSelection.RankAsync( new[] { Node("node-a"), Node("node-a"), new PrivateAuxiliaryNode { Slug = "private-a" }, Node("auto"), Node("bad slug"), Node("cooling") } .Concat(Enumerable.Range(0, 12).Select(i => Node("node-" + i))), "smart", slug => slug == "cooling", Load, Reachable, CancellationToken.None); checks["at_most_eight_distinct_authorized_public_nodes"] = requested.Count == 8 && requested.Distinct().Count() == 8 && candidates.Count == 8; checks["private_auto_invalid_and_cooldown_not_fetched"] = !requested.Intersect(new[] { "private-a", "auto", "bad slug", "cooling" }).Any(); checks["cached_response_not_refetched"] = candidates.All(c => ReferenceEquals(c.Response, loaded[c.Response.Node.Slug])); requested.Clear(); var pending = new Dictionary>(); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // Unique endpoint ports allow deterministic completion ordering without // actual sockets, route inspection or millisecond timing assumptions. var rankedNodes = new[] { Node("slow"), Node("fast"), Node("medium") }; var portSlugs = new Dictionary { [10803] = "slow", [10804] = "fast", [10805] = "medium" }; foreach (var node in rankedNodes) pending[node.Slug] = new(TaskCreationOptions.RunContinuationsAsynchronously); var ranking = PublicTailnetSelection.RankAsync(rankedNodes, "smart", _ => false, (slug, _) => Task.FromResult(JsonSerializer.Deserialize(JsonSerializer.Serialize(Config(slug)) .Replace("10803", (10803 + Array.FindIndex(rankedNodes, n => n.Slug == slug)).ToString()))!), (_, port, _) => Probe(port), CancellationToken.None); async Task Probe(int port) { var task = pending[portSlugs[port]].Task; if (port == 10805) entered.TrySetResult(); return await task; } await entered.Task.WaitAsync(TimeSpan.FromSeconds(1)); await Task.Delay(20); pending["fast"].SetResult(true); await Task.Delay(35); pending["medium"].SetResult(true); await Task.Delay(35); pending["slow"].SetResult(true); candidates = await ranking; checks["reachable_endpoints_rank_by_probe_latency"] = candidates.Select(c => c.Response.Node.Slug).SequenceEqual(new[] { "fast", "medium", "slow" }); var diagnostics = new ConcurrentQueue(); var probes = 0; candidates = await PublicTailnetSelection.RankAsync(new[] { Node("wrong-node"), Node("wrong-route"), Node("private-scope"), Node("unreachable"), Node("broken") }, "smart", _ => false, (slug, _) => slug switch { "wrong-node" => Task.FromResult(Config("some-other-node")), "wrong-route" => Task.FromResult(Config(slug, "global")), "private-scope" => Task.FromResult(Config(slug, scope: "private_auxiliary")), "broken" => Task.FromException(new IOException("secret-config-body")), _ => Task.FromResult(Config(slug)) }, (_, _, _) => { Interlocked.Increment(ref probes); return Task.FromResult(false); }, CancellationToken.None, diagnostic: (_, reason) => diagnostics.Enqueue(reason)); checks["wrong_slug_route_and_private_scope_rejected_before_probe"] = candidates.Count == 0 && probes == 1 && diagnostics.Contains("response_node_mismatch") && diagnostics.Contains("response_route_mismatch"); checks["diagnostics_never_include_exception_body"] = !diagnostics.Any(d => d.Contains("secret", StringComparison.Ordinal)); probes = 0; candidates = await PublicTailnetSelection.RankAsync([Node("disabled")], "smart", _ => false, (slug, _) => { var fixture = JsonNode.Parse(JsonSerializer.Serialize(Config(slug)))!; fixture["tailscale_endpoint"] = null; return Task.FromResult(JsonSerializer.Deserialize(fixture.ToJsonString())!); }, (_, _, _) => { probes++; return Task.FromResult(true); }, CancellationToken.None, allowKnownEndpoints: true); checks["explicit_null_metadata_never_probed"] = candidates.Count == 0 && probes == 0; candidates = await PublicTailnetSelection.RankAsync([Node("missing"), Node("good")], "smart", _ => false, (slug, _) => slug == "missing" ? Task.FromException(new ApiException(404, "fixture missing")) : Task.FromResult(Config(slug)), Reachable, CancellationToken.None); checks["per_node_404_keeps_other_authorized_candidate"] = candidates.Count == 1 && candidates[0].Response.Node.Slug == "good"; foreach (var status in new[] { 401, 403 }) { ApiException? observed = null; var expected = new ApiException(status, "fixture rejected"); try { await PublicTailnetSelection.RankAsync(new[] { Node("denied"), Node("other") }, "smart", _ => false, (slug, _) => slug == "denied" ? Task.FromException(expected) : Task.FromResult(Config(slug)), Reachable, CancellationToken.None); } catch (ApiException error) { observed = error; } checks["authorization_" + status + "_propagates_same_exception"] = ReferenceEquals(observed, expected); } using (var cancelled = new CancellationTokenSource()) { cancelled.Cancel(); var called = false; var cancellationObserved = false; try { await PublicTailnetSelection.RankAsync([Node("node")], "smart", _ => false, (_, _) => { called = true; return Task.FromResult(Config("node")); }, Reachable, cancelled.Token); } catch (OperationCanceledException) { cancellationObserved = true; } checks["pre_cancelled_caller_does_not_fetch"] = cancellationObserved && !called; } using (var cancelled = new CancellationTokenSource()) { var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var operation = PublicTailnetSelection.RankAsync([Node("node")], "smart", _ => false, async (_, token) => { started.SetResult(); await Task.Delay(Timeout.Infinite, token); return Config("node"); }, Reachable, cancelled.Token); await started.Task.WaitAsync(TimeSpan.FromSeconds(1)); cancelled.Cancel(); var cancellationObserved = false; try { await operation; } catch (OperationCanceledException) { cancellationObserved = true; } checks["inflight_caller_cancellation_propagates"] = cancellationObserved; } var never = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); candidates = await PublicTailnetSelection.RankAsync([Node("node")], "smart", _ => false, (_, _) => never.Task, Reachable, CancellationToken.None, budget: TimeSpan.FromMilliseconds(30)); checks["deadline_bounds_callback_ignoring_token"] = candidates.Count == 0; requested.Clear(); candidates = await PublicTailnetSelection.RankAsync([Node("node")], "direct", _ => false, Load, Reachable, CancellationToken.None); checks["direct_mode_never_probes_or_fetches"] = candidates.Count == 0 && requested.Count == 0; var active = 0; var maximum = 0; candidates = await PublicTailnetSelection.RankAsync(Enumerable.Range(0, 8).Select(i => Node("parallel-" + i)), "smart", _ => false, async (slug, token) => { var current = Interlocked.Increment(ref active); lock (checks) maximum = Math.Max(maximum, current); try { await Task.Delay(15, token); return Config(slug); } finally { Interlocked.Decrement(ref active); } }, Reachable, CancellationToken.None); checks["at_most_three_parallel_fetches"] = candidates.Count == 8 && maximum is > 1 and <= 3; var dispatchNodes = new[] { Node("busy"), Node("quiet") }; var dispatchCalls = new List(); Task Dispatch(IReadOnlyCollection excluded, CancellationToken _) { dispatchCalls.Add(excluded.OrderBy(s => s, StringComparer.Ordinal).ToArray()); var selected = new[] { "quiet", "busy" }.First(slug => !excluded.Contains(slug)); return Task.FromResult(JsonSerializer.Deserialize(JsonSerializer.Serialize(Config(selected)) .Replace("10803", selected == "quiet" ? "10804" : "10805"))!); } candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, Dispatch, async (_, port, token) => { if (port == 10804) await Task.Delay(20, token); return true; }, CancellationToken.None); checks["backend_load_order_precedes_ping_order"] = candidates.Select(c => c.Response.Node.Slug).SequenceEqual(new[] { "quiet", "busy" }); checks["dispatch_excludes_each_already_planned_node"] = dispatchCalls.Count == 2 && dispatchCalls[0].Length == 0 && dispatchCalls[1].SequenceEqual(new[] { "quiet" }); dispatchCalls.Clear(); candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, Dispatch, (_, port, _) => Task.FromResult(port == 10805), CancellationToken.None); checks["unreachable_dispatch_candidate_does_not_block_other_inner"] = candidates.Count == 1 && candidates[0].Response.Node.Slug == "busy" && dispatchCalls.Count == 2; var confirmed = await PublicTailnetSelection.ConfirmDispatchAsync(candidates[0], dispatchNodes, "smart", Dispatch, CancellationToken.None); checks["actual_attempt_rebinds_shared_reservation_and_config"] = confirmed.Node.Slug == "busy" && dispatchCalls[^1].SequenceEqual(new[] { "quiet" }) && !ReferenceEquals(confirmed, candidates[0].Response); dispatchCalls.Clear(); candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", slug => slug == "quiet", Dispatch, Reachable, CancellationToken.None); checks["dispatch_honors_existing_per_node_cooldown"] = candidates.Count == 1 && candidates[0].Response.Node.Slug == "busy" && dispatchCalls[0].SequenceEqual(new[] { "quiet" }); var dispatchProbes = 0; candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, (_, _) => Task.FromResult(Config("outside-profile")), (_, _, _) => { dispatchProbes++; return Task.FromResult(true); }, CancellationToken.None); checks["auto_response_outside_authorized_profile_is_never_probed"] = candidates.Count == 0 && dispatchProbes == 0; candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, (_, _) => Task.FromResult(Config("quiet", route: "global")), Reachable, CancellationToken.None); checks["auto_response_wrong_route_is_not_candidate"] = candidates.Count == 0; var repeatedCalls = 0; candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, (_, _) => { repeatedCalls++; return Task.FromResult(Config("quiet")); }, Reachable, CancellationToken.None); checks["repeated_auto_response_is_bounded"] = candidates.Count == 1 && repeatedCalls == 2; foreach (var status in new[] { 401, 403 }) { var expected = new ApiException(status, "dispatch fixture denied"); ApiException? observed = null; try { await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, (_, _) => Task.FromException(expected), Reachable, CancellationToken.None); } catch (ApiException error) { observed = error; } checks["dispatch_auth_" + status + "_propagates"] = ReferenceEquals(expected, observed); } var confirmationRejected = false; try { await PublicTailnetSelection.ConfirmDispatchAsync(new(Config("quiet"), 0), dispatchNodes, "smart", (_, _) => Task.FromResult(Config("busy")), CancellationToken.None); } catch (InvalidOperationException) { confirmationRejected = true; } checks["dispatch_confirmation_rejects_wrong_node"] = confirmationRejected; dispatchCalls.Clear(); candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "direct", _ => false, Dispatch, Reachable, CancellationToken.None); checks["direct_does_not_dispatch"] = candidates.Count == 0 && dispatchCalls.Count == 0; candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, (_, _) => never.Task, Reachable, CancellationToken.None, budget: TimeSpan.FromMilliseconds(30)); checks["dispatch_deadline_bounds_uncooperative_callback"] = candidates.Count == 0; foreach (var check in await TransportPlanSelfTest.CheckAsync()) checks.Add(check.Key, check.Value); var report = new { passed = checks.Values.All(v => v), checks, simulated_transport = true, network_modified = false, note = "Fake config/probe callbacks only. TCP availability is selection evidence, not authenticated proxy acceptance." }; File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "public-tailnet-selection-self-test.json"), JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true })); return report.passed ? 0 : 83; } }