Publish Zonghengjia Windows 0.3.13 client source
This commit is contained in:
@@ -1,6 +1,4 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
@@ -9,205 +7,97 @@ 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")
|
||||
NodeInfo[] profile = [new() { Slug = "primary" }, new() { Slug = "backup" }, new PrivateAuxiliaryNode { Slug = "private" }];
|
||||
var auto = ConnectionSelection.Create(false, null, profile.Select(n => n.Slug));
|
||||
var auxiliary = new PrivateAuxiliaryNode { Slug = "private", ProbeIpv4 = "100.84.199.104" };
|
||||
var failed = new Dictionary<string, DateTimeOffset>();
|
||||
var requests = new List<string>();
|
||||
var privateSearches = 0;
|
||||
Task<IReadOnlyList<PrivateAuxiliaryNode>> RankPrivate(CancellationToken _)
|
||||
{
|
||||
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())!;
|
||||
privateSearches++;
|
||||
return Task.FromResult<IReadOnlyList<PrivateAuxiliaryNode>>([auxiliary]);
|
||||
}
|
||||
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]));
|
||||
ConfigResponse Response(string slug, string route = "smart", string scope = "public") =>
|
||||
new() { Node = new() { Slug = slug }, RouteMode = route, ConnectionScope = scope };
|
||||
|
||||
requested.Clear();
|
||||
var pending = new Dictionary<string, TaskCompletionSource<bool>>();
|
||||
await foreach (var attempt in TransportPlan.AttemptsAsync(auto, "smart", 8, null, RankPrivate, default))
|
||||
{
|
||||
requests.Add(VpnApiClient.ConfigPath(attempt.Slug, "smart", failed.Keys));
|
||||
auto.ValidateConfig(attempt, Response("primary"), "smart", profile, failed);
|
||||
break;
|
||||
}
|
||||
checks["healthy_primary_consumes_one_sticky_dispatch"] = privateSearches == 0 && requests.SequenceEqual(
|
||||
["api/v1/client/config/?node=auto&route=smart"]);
|
||||
|
||||
requests.Clear();
|
||||
var attempted = new List<string>();
|
||||
await foreach (var attempt in TransportPlan.AttemptsAsync(auto, "smart", 8, null, RankPrivate, default))
|
||||
{
|
||||
if (attempt.IsPrivate) { attempted.Add(attempt.Slug); continue; }
|
||||
requests.Add(VpnApiClient.ConfigPath(attempt.Slug, "smart", failed.Keys));
|
||||
var node = failed.ContainsKey("primary") ? "backup" : "primary";
|
||||
auto.ValidateConfig(attempt, Response(node), "smart", profile, failed);
|
||||
attempted.Add(node);
|
||||
if (node == "backup") break;
|
||||
failed[node] = DateTimeOffset.UtcNow.AddMinutes(5);
|
||||
}
|
||||
checks["primary_failure_defers_private_search_and_backup_dispatch"] = privateSearches == 1
|
||||
&& attempted.SequenceEqual(["primary", "private", "backup"])
|
||||
&& requests.SequenceEqual(["api/v1/client/config/?node=auto&route=smart", "api/v1/client/config/?node=auto&route=smart&exclude=primary"]);
|
||||
|
||||
attempted.Clear();
|
||||
await foreach (var attempt in TransportPlan.AttemptsAsync(auto, "global", 99, "primary", RankPrivate, default))
|
||||
attempted.Add(attempt.Slug);
|
||||
checks["same_node_retry_precedes_discovery_and_two_public_backups"] =
|
||||
attempted.SequenceEqual(["primary", "private", "auto", "auto"]);
|
||||
checks["same_node_config_does_not_request_rebalance_or_exclusions"] =
|
||||
VpnApiClient.ConfigPath("primary", "global", failed.Keys) == "api/v1/client/config/?node=primary&route=global";
|
||||
|
||||
var manual = ConnectionSelection.Create(true, "private", profile.Select(n => n.Slug));
|
||||
attempted.Clear();
|
||||
await foreach (var attempt in TransportPlan.AttemptsAsync(manual, "smart", 3, "primary", RankPrivate, default))
|
||||
attempted.Add(attempt.Slug);
|
||||
checks["manual_stays_at_selected_site"] = attempted.SequenceEqual(["private"]);
|
||||
var before = privateSearches;
|
||||
attempted.Clear();
|
||||
await foreach (var attempt in TransportPlan.AttemptsAsync(auto, "direct", 3, null, RankPrivate, default))
|
||||
attempted.Add(attempt.Slug);
|
||||
checks["direct_has_no_endpoint_discovery"] = privateSearches == before && attempted.SequenceEqual(["auto", "auto", "auto"]);
|
||||
|
||||
bool Rejected(ConfigResponse response, string requested = "auto")
|
||||
{
|
||||
try { auto.ValidateConfig(new(requested, null), response, "smart", profile, failed); return false; }
|
||||
catch (InvalidOperationException) { return true; }
|
||||
}
|
||||
checks["auto_cannot_repeat_excluded_node"] = Rejected(Response("primary"));
|
||||
checks["auto_cannot_probe_node_outside_authorized_profile"] = Rejected(Response("unexpected"));
|
||||
checks["public_config_cannot_use_private_scope_or_private_slug"] =
|
||||
Rejected(Response("backup", scope: PrivateAuxiliaryRouting.Scope)) && Rejected(Response("private"));
|
||||
checks["mismatched_route_and_explicit_node_rejected"] =
|
||||
Rejected(Response("backup", "global")) && Rejected(Response("backup"), "primary");
|
||||
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
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 never = new TaskCompletionSource<IReadOnlyList<PrivateAuxiliaryNode>>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
async Task ConsumeAsync()
|
||||
{
|
||||
var task = pending[portSlugs[port]].Task;
|
||||
if (port == 10805) entered.TrySetResult();
|
||||
return await task;
|
||||
await foreach (var _ in TransportPlan.AttemptsAsync(auto, "smart", 0, null, _ =>
|
||||
{ entered.SetResult(); return never.Task; }, cancelled.Token)) { }
|
||||
}
|
||||
var pending = ConsumeAsync();
|
||||
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 })
|
||||
cancelled.Cancel();
|
||||
try
|
||||
{
|
||||
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);
|
||||
await pending.WaitAsync(TimeSpan.FromSeconds(1));
|
||||
checks["cancellation_interrupts_discovery"] = false;
|
||||
}
|
||||
catch (OperationCanceledException) { checks["cancellation_interrupts_discovery"] = true; }
|
||||
|
||||
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 dispatchNodes = new[] { Node("busy"), Node("quiet") };
|
||||
var dispatchCalls = new List<string[]>();
|
||||
Task<ConfigResponse> Dispatch(IReadOnlyCollection<string> 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<ConfigResponse>(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<ConfigResponse>(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 }));
|
||||
var report = new { passed = checks.Values.All(v => v), checks, simulated_transport = true, network_modified = false };
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "public-tailnet-selection-self-test.json"),
|
||||
JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return report.passed ? 0 : 83;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user