152 lines
10 KiB
C#
152 lines
10 KiB
C#
|
|
using System.Collections.Concurrent;
|
||
|
|
using System.Text.Json;
|
||
|
|
using System.Text.Json.Nodes;
|
||
|
|
|
||
|
|
namespace UCVL.VPNPlus;
|
||
|
|
|
||
|
|
internal static class PublicTailnetSelectionSelfTest
|
||
|
|
{
|
||
|
|
internal static async Task<int> RunAsync()
|
||
|
|
{
|
||
|
|
var checks = new Dictionary<string, bool>();
|
||
|
|
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<ConfigResponse>(fixture.ToJsonString())!;
|
||
|
|
}
|
||
|
|
NodeInfo Node(string slug) => new() { Slug = slug };
|
||
|
|
var requested = new ConcurrentQueue<string>();
|
||
|
|
var loaded = new ConcurrentDictionary<string, ConfigResponse>();
|
||
|
|
Task<ConfigResponse> Load(string slug, CancellationToken _)
|
||
|
|
{ requested.Enqueue(slug); var response = Config(slug); loaded[slug] = response; return Task.FromResult(response); }
|
||
|
|
Task<bool> 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<string, TaskCompletionSource<bool>>();
|
||
|
|
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<int, string> { [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<ConfigResponse>(JsonSerializer.Serialize(Config(slug))
|
||
|
|
.Replace("10803", (10803 + Array.FindIndex(rankedNodes, n => n.Slug == slug)).ToString()))!),
|
||
|
|
(_, port, _) => Probe(port), CancellationToken.None);
|
||
|
|
async Task<bool> 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<string>(); 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<ConfigResponse>(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<ConfigResponse>(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<ConfigResponse>(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<ConfigResponse>(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<ConfigResponse>(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 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;
|
||
|
|
}
|
||
|
|
}
|