213 lines
14 KiB
C#
213 lines
14 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Diagnostics;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
|
|
namespace UCVL.VPNPlus;
|
|
|
|
// An authorized node with private, loopback-only inbounds, plus a persistent
|
|
// local echo stream. Uses the production parser/lease book/routing updater.
|
|
// Injects direct-path failure ONLY into its own test core, to deterministically
|
|
// exercise leases even when the host's current direct path can work.
|
|
// No TUN, OS route/DNS/proxy writes, profile updates, telemetry submission,
|
|
// installed-client control, or authenticated Codex requests.
|
|
internal static class LearningExpirySoakSelfTest
|
|
{
|
|
internal static async Task<int> RunAsync(int minutes)
|
|
{
|
|
var reportPath = Path.Combine(AppContext.BaseDirectory, "learning-expiry-soak.json");
|
|
var progressPath = Path.Combine(AppContext.BaseDirectory, "learning-expiry-soak-progress.json");
|
|
var started = DateTimeOffset.Now;
|
|
var watch = Stopwatch.StartNew();
|
|
var samples = new List<object>();
|
|
var comparisons = new List<object>();
|
|
var book = new NetworkLearningLeases();
|
|
var hints = new ConcurrentDictionary<string, byte>();
|
|
var hosts = new[] { "www.google.com", "api.openai.com", "chatgpt.com" };
|
|
Process? core = null;
|
|
TcpClient? streamClient = null, streamServer = null;
|
|
var echo = new TcpListener(IPAddress.Loopback, 0);
|
|
var folder = Path.Combine(Path.GetTempPath(), "ucvl-expiry-soak-" + Guid.NewGuid().ToString("N"));
|
|
var configPath = Path.Combine(folder, "config.json");
|
|
var coreId = 0;
|
|
var renewals = 0;
|
|
var taggedHints = 0;
|
|
var healthy = 0;
|
|
var failed = 0;
|
|
var streamChecks = 0;
|
|
var passed = false;
|
|
string? failure = null;
|
|
try
|
|
{
|
|
using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(minutes + 2));
|
|
var token = deadline.Token;
|
|
using var api = new VpnApiClient();
|
|
var access = TokenStore.Load() ?? throw new IOException("Existing session required.");
|
|
var profile = await api.GetProfileAsync(access, token);
|
|
var node = profile.Nodes.Single(n => n.Name == "VPN002");
|
|
var response = await api.GetConfigAsync(access, node.Slug, "smart", token);
|
|
var config = LearningPolicy.DirectFirst(response.GetRuntimeConfigJson());
|
|
var addresses = new List<IPAddress>();
|
|
foreach (var host in TunConfigBuilder.GetProxyServerHosts(config))
|
|
addresses.AddRange(await Dns.GetHostAddressesAsync(host, token));
|
|
var physical = TunRouting.GetPhysicalNetwork(addresses);
|
|
var reservations = Enumerable.Range(0, 4).Select(_ => new TcpListener(IPAddress.Loopback, 0)).ToArray();
|
|
foreach (var reserve in reservations) reserve.Start();
|
|
var ports = reservations.Select(l => ((IPEndPoint)l.LocalEndpoint).Port).ToArray();
|
|
foreach (var reserve in reservations) reserve.Stop();
|
|
echo.Start();
|
|
var echoPort = ((IPEndPoint)echo.LocalEndpoint).Port;
|
|
var root = JsonNode.Parse(config)!.AsObject();
|
|
root["inbounds"] = new JsonArray(new JsonObject { ["tag"] = "soak-business", ["listen"] = "127.0.0.1",
|
|
["port"] = ports[0], ["protocol"] = "socks", ["settings"] = new JsonObject { ["auth"] = "noauth", ["udp"] = false } });
|
|
config = root.ToJsonString();
|
|
string Runtime(string source)
|
|
{
|
|
var runtime = JsonNode.Parse(TunConfigBuilder.Build(source, physical.InterfaceName, true,
|
|
includeTun: false, routingApiPort: ports[1], learningProbePort: ports[2], directProbePort: ports[3]))!;
|
|
var isolatedOutbounds = runtime["outbounds"]!.AsArray();
|
|
for (var index = 0; index < isolatedOutbounds.Count; index++) {
|
|
var tag = isolatedOutbounds[index]!["tag"]!.GetValue<string>();
|
|
if (tag is "direct" or "ucvl-learning-direct")
|
|
isolatedOutbounds[index] = new JsonObject { ["tag"] = tag, ["protocol"] = "blackhole" };
|
|
}
|
|
// Synthetic stream never leaves loopback and must not inherit a
|
|
// physical-interface binding intended for Internet direct traffic.
|
|
runtime["outbounds"]!.AsArray().Add(new JsonObject { ["tag"] = "soak-echo", ["protocol"] = "freedom" });
|
|
runtime["routing"]!["rules"]!.AsArray().Insert(0, new JsonObject { ["type"] = "field", ["ip"] = new JsonArray("127.0.0.1"),
|
|
["port"] = echoPort.ToString(), ["outboundTag"] = "soak-echo", ["ruleTag"] = "ucvl-soak-echo" });
|
|
return runtime.ToJsonString();
|
|
}
|
|
var xray = Path.Combine(AppContext.BaseDirectory, "xray", "xray.exe");
|
|
Directory.CreateDirectory(folder);
|
|
await File.WriteAllTextAsync(configPath, Runtime(config), token);
|
|
var startInfo = new ProcessStartInfo(xray) { UseShellExecute = false, CreateNoWindow = true,
|
|
WorkingDirectory = Path.GetDirectoryName(xray)!, RedirectStandardOutput = true, RedirectStandardError = true };
|
|
foreach (var argument in new[] { "run", "-c", configPath }) startInfo.ArgumentList.Add(argument);
|
|
core = new Process { StartInfo = startInfo };
|
|
void ReadLine(object sender, DataReceivedEventArgs e)
|
|
{
|
|
if (e.Data is not { } line) return;
|
|
var hint = LearningPolicy.ParseAttempt(line, "fixture", "public");
|
|
if (hint is null || !hosts.Contains(hint.Target)) return;
|
|
if (line.Contains("Hit route rule:")) Interlocked.Increment(ref taggedHints);
|
|
hints.TryAdd(hint.Target, 0);
|
|
}
|
|
core.OutputDataReceived += ReadLine; core.ErrorDataReceived += ReadLine;
|
|
core.Start(); core.BeginOutputReadLine(); core.BeginErrorReadLine();
|
|
coreId = core.Id;
|
|
await Task.Delay(900, token);
|
|
File.Delete(configPath); // The launched core has consumed credentials; never keep them in evidence.
|
|
|
|
async Task ApplyAsync()
|
|
{
|
|
if (!book.Dirty) return;
|
|
var merged = LearningPolicy.Merge(config, new() { Contract = 1, Revision = new string('0', 64), Rules = book.Targets.ToList() });
|
|
var runtime = JsonNode.Parse(Runtime(merged))!;
|
|
await XrayRoutingUpdater.ApplyAsync(xray, ports[1], new JsonObject { ["routing"] = runtime["routing"]!.DeepClone() }.ToJsonString(), token);
|
|
book.Applied();
|
|
}
|
|
async Task VerifyAsync(IEnumerable<(string Host, NetworkLearningLeases.Entry? Entry)> targets)
|
|
{
|
|
var proofs = await Task.WhenAll(targets.Select(async target => (
|
|
target.Host, target.Entry, Proof: await ProxyProbe.CompareTlsAsync(new() { Target = target.Host, Port = 443 }, ports[3], ports[2], token))));
|
|
foreach (var proof in proofs) {
|
|
book.Observe(new() { Target = proof.Host, TargetType = "domain", MatchMode = "exact" }, proof.Proof, Environment.TickCount64, proof.Entry);
|
|
if (proof.Entry is not null && proof.Proof.ShouldProxy) renewals++;
|
|
comparisons.Add(new { seconds = watch.Elapsed.TotalSeconds, target = proof.Host, direct = proof.Proof.DirectTls,
|
|
proxy = proof.Proof.ProxyTls, renewed = proof.Entry is not null && proof.Proof.ShouldProxy });
|
|
}
|
|
await ApplyAsync();
|
|
}
|
|
|
|
// First observe the real tagged DIRECT log. This starts on a cold
|
|
// isolated rule bank; no fixed warmup can hide a broken parser.
|
|
await NodeHealthProbe.CheckAsync(token, ports[0]);
|
|
var observed = hosts.Where(h => hints.TryRemove(h, out _)).ToArray();
|
|
if (observed.Length != 3 || taggedHints < 3) throw new IOException("Tagged direct attempts were not all observed.");
|
|
await VerifyAsync(observed.Select(h => (h, (NetworkLearningLeases.Entry?)null)));
|
|
if (book.Count == 0) throw new IOException("No proxy-needed rule available to exercise expiry.");
|
|
|
|
streamClient = await ConnectEchoAsync(ports[0], echoPort, token);
|
|
streamServer = await echo.AcceptTcpClientAsync(token);
|
|
var initialRules = book.Count;
|
|
var exerciseStarted = Stopwatch.StartNew();
|
|
var nextHealth = 0L;
|
|
while (exerciseStarted.Elapsed < TimeSpan.FromMinutes(minutes)) {
|
|
token.ThrowIfCancellationRequested();
|
|
if (core.HasExited || core.Id != coreId) throw new IOException("Isolated core did not remain alive.");
|
|
var now = Environment.TickCount64;
|
|
var due = book.Due(now);
|
|
if (due.Length > 0) {
|
|
foreach (var entry in due) book.Scheduled(entry, now);
|
|
await VerifyAsync(due.Select(e => (e.Target.Target, (NetworkLearningLeases.Entry?)e)));
|
|
}
|
|
book.Expire(Environment.TickCount64);
|
|
await ApplyAsync();
|
|
// No reconnect/retry hides an interrupted stream.
|
|
await EchoAsync(streamClient, streamServer, token);
|
|
streamChecks++;
|
|
if (exerciseStarted.ElapsedMilliseconds >= nextHealth) {
|
|
var ok = await NodeHealthProbe.CheckAsync(token, ports[0]);
|
|
if (ok) healthy++; else failed++;
|
|
samples.Add(new { seconds = exerciseStarted.Elapsed.TotalSeconds, ordinary_smart_healthy = ok,
|
|
same_core = !core.HasExited && core.Id == coreId, leases = book.Count, renewals, stream_checks = streamChecks });
|
|
nextHealth = exerciseStarted.ElapsedMilliseconds + 15_000;
|
|
await File.WriteAllTextAsync(progressPath, JsonSerializer.Serialize(new { running = true, started,
|
|
requested_minutes = minutes, elapsed_seconds = exerciseStarted.Elapsed.TotalSeconds, core_id = coreId,
|
|
healthy, failed, renewals, streamChecks, taggedHints, initialRules }), token);
|
|
}
|
|
await Task.Delay(5_000, token);
|
|
}
|
|
passed = failed == 0 && healthy > 0 && !core.HasExited && (minutes < 11 || renewals >= initialRules)
|
|
&& (minutes < 21 || renewals >= initialRules * 2) && (minutes < 30 || renewals >= initialRules * 3);
|
|
}
|
|
catch (Exception error) { failure = error.GetType().Name + ": " + error.Message; }
|
|
finally
|
|
{
|
|
streamClient?.Dispose(); streamServer?.Dispose(); echo.Stop();
|
|
if (core is not null) { try { if (!core.HasExited) core.Kill(true); await core.WaitForExitAsync(); } catch { } core.Dispose(); }
|
|
if (File.Exists(configPath)) File.Delete(configPath);
|
|
if (Directory.Exists(folder)) Directory.Delete(folder);
|
|
await File.WriteAllTextAsync(reportPath, JsonSerializer.Serialize(new { scope = "isolated direct-path fault injection, real authorized VPN002 transport, loopback lifecycle soak and persistent local TCP stream; NOT installed TUN or authenticated Codex acceptance",
|
|
started, finished = DateTimeOffset.Now, requested_minutes = minutes, elapsed_seconds = watch.Elapsed.TotalSeconds,
|
|
passed, failure, network_modified = false, installed_client_modified = false, production_observations_submitted = false,
|
|
direct_path_fault_injected_in_isolated_core = true,
|
|
core_id = coreId, taggedHints, renewals, streamChecks, healthy, failed, comparisons, samples }, new JsonSerializerOptions { WriteIndented = true }));
|
|
await File.WriteAllTextAsync(progressPath, JsonSerializer.Serialize(new { running = false, passed, failure, report = Path.GetFileName(reportPath) }));
|
|
}
|
|
return passed ? 0 : 34;
|
|
}
|
|
|
|
private static async Task<TcpClient> ConnectEchoAsync(int port, int targetPort, CancellationToken token)
|
|
{
|
|
var client = new TcpClient();
|
|
try {
|
|
await client.ConnectAsync(IPAddress.Loopback, port, token);
|
|
var stream = client.GetStream();
|
|
await stream.WriteAsync(new byte[] { 5, 1, 0 }, token);
|
|
var hello = new byte[2]; await stream.ReadExactlyAsync(hello, token);
|
|
if (!hello.SequenceEqual(new byte[] { 5, 0 })) throw new IOException("SOCKS greeting rejected.");
|
|
await stream.WriteAsync(new byte[] { 5, 1, 0, 1, 127, 0, 0, 1, (byte)(targetPort >> 8), (byte)targetPort }, token);
|
|
var reply = new byte[10]; await stream.ReadExactlyAsync(reply, token);
|
|
if (reply[1] != 0) throw new IOException("SOCKS connect rejected.");
|
|
return client;
|
|
} catch { client.Dispose(); throw; }
|
|
}
|
|
private static async Task EchoAsync(TcpClient client, TcpClient server, CancellationToken token)
|
|
{
|
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
|
|
deadline.CancelAfter(TimeSpan.FromSeconds(5));
|
|
var payload = Encoding.UTF8.GetBytes("ucvl-isolated-continuity-" + Guid.NewGuid());
|
|
var buffer = new byte[payload.Length];
|
|
await client.GetStream().WriteAsync(payload, deadline.Token);
|
|
await server.GetStream().ReadExactlyAsync(buffer, deadline.Token);
|
|
await server.GetStream().WriteAsync(buffer, deadline.Token);
|
|
await client.GetStream().ReadExactlyAsync(buffer, deadline.Token);
|
|
if (!buffer.SequenceEqual(payload)) throw new IOException("Persistent stream payload mismatch.");
|
|
}
|
|
}
|