2026-10-11 23:23:20 +00:00
using System.Text.Json ;
using System.Text.Json.Nodes ;
namespace UCVL.VPNPlus ;
internal static class LearningSelfTest
{
internal static int Run ()
{
var checks = new Dictionary < string , bool >();
const string baseConfig = """{" inbounds ":[]," outbounds ":[{" tag ":" proxy "," protocol ":" socks "," settings ":{" servers ":[{" address ":" 8.8 . 8.8 "," port ":443}]}},{" tag ":" direct "," protocol ":" freedom "},{" tag ":" block "," protocol ":" blackhole "}]," routing ":{" rules ":[{" type ":" field "," ip ":[" geoip : private "]," outboundTag ":" direct "},{" type ":" field "," domain ":[" domain : openai . com "]," outboundTag ":" proxy "," ruleTag ":" ucvl - learned "},{" type ":" field "," domain ":[" geosite : category - ads - all "]," outboundTag ":" block "},{" type ":" field "," network ":" tcp , udp "," outboundTag ":" direct "}]}}""" ;
bool Throws ( Action action ) { try { action (); return false ; } catch ( InvalidDataException ) { return true ; } }
LearningObservation ? Parse ( string text ) => LearningPolicy . Parse ( text , "fixture" , "public" );
var line = "[Info] [123] app/proxyman/outbound: failed to process outbound traffic > proxy/freedom: failed to open connection to tcp:learn.example.com:443 > i/o timeout" ;
var parsed = Parse ( line );
checks [ "freedom_without_direct_detected" ] = parsed is { Target : "learn.example.com" , FailureKind : "timeout" , Port : 443 };
checks [ "acceptance_is_not_success" ] = Parse ( "from tcp:127.0.0.1:777 accepted tcp:learn.example.com:443 [socks-in -> direct]" ) is null ;
checks [ "http_auth_status_is_not_failure" ] = Parse ( "HTTP 401 / 403 / 429 direct learn.example.com:443" ) is null ;
checks [ "proxy_failures_not_direct" ] = Parse ( line . Replace ( "proxy/freedom" , "proxy/vless/outbound" )) is null ;
2026-11-13 10:35:04 +08:00
checks [ "private_failures_not_collected" ] = Parse ( line . Replace ( "learn.example.com" , "172.16.0.111" )) is null ;
checks [ "company_not_collected" ] = Parse ( line . Replace ( "learn.example.com" , "vpn.toplc.cn" )) is null ;
2026-10-11 23:23:20 +00:00
checks [ "source_not_misidentified" ] = Parse ( "tcp:127.0.0.1:777 " + line )?. Target == "learn.example.com" ;
checks [ "oversized_line_rejected" ] = Parse ( new string ( 'x' , 8193 ) + line ) is null ;
const string attempt = "[Info] [1753901314] app/dispatcher: taking detour [direct] for [tcp:tls-gap.example.com:443]" ;
checks [ "tls_attempt_detected_before_failure_log" ] = LearningPolicy . ParseAttempt ( attempt , "fixture" , "public" )?. Target == "tls-gap.example.com" ;
var tagged = attempt . Replace ( "app/dispatcher: " , "app/dispatcher: Hit route rule: [ucvl-fixture-0] so " );
checks [ "real_tagged_attempt_detected" ] = LearningPolicy . ParseAttempt ( tagged , "fixture" , "public" )?. Target == "tls-gap.example.com" ;
checks [ "tagged_proxy_not_collected" ] = LearningPolicy . ParseAttempt ( tagged . Replace ( "[direct]" , "[proxy]" ), "fixture" , "public" ) is null ;
checks [ "tagged_probe_not_recursive" ] = LearningPolicy . ParseAttempt ( tagged . Replace ( "[direct]" , "[ucvl-learning-direct]" ), "fixture" , "public" ) is null ;
checks [ "oversized_tag_rejected" ] = LearningPolicy . ParseAttempt ( tagged . Replace ( "ucvl-fixture-0" , new string ( 'x' , 201 )), "fixture" , "public" ) is null ;
checks [ "multiline_tag_rejected" ] = LearningPolicy . ParseAttempt ( tagged . Replace ( "ucvl-fixture-0" , "ucvl-\n0" ), "fixture" , "public" ) is null ;
checks [ "attempt_is_not_failure_evidence" ] = Parse ( attempt ) is null ;
checks [ "probe_not_recursively_observed" ] = LearningPolicy . ParseAttempt ( attempt . Replace ( "[direct]" , "[ucvl-learning-direct]" ), "fixture" , "public" ) is null ;
checks [ "proxy_attempt_not_observed" ] = LearningPolicy . ParseAttempt ( attempt . Replace ( "[direct]" , "[proxy]" ), "fixture" , "public" ) is null ;
2026-11-13 10:35:04 +08:00
checks [ "private_attempt_not_observed" ] = LearningPolicy . ParseAttempt ( attempt . Replace ( "tls-gap.example.com" , "172.16.0.111" ), "fixture" , "public" ) is null ;
2026-10-11 23:23:20 +00:00
checks [ "non_tls_attempt_not_observed" ] = LearningPolicy . ParseAttempt ( attempt . Replace ( ":443]" , ":80]" ), "fixture" , "public" ) is null ;
checks [ "no_url_collection" ] = LearningPolicy . ParseAttempt ( attempt . Replace ( "tls-gap.example.com" , "example.com/path?token=x" ), "fixture" , "public" ) is null ;
foreach ( bool? directTls in new bool? [] { true , false , null })
foreach ( bool? proxyTls in new bool? [] { true , false , null })
checks [ $"pair_{directTls}_{proxyTls}" ] = new ProxyProbe . PathComparison ( directTls , proxyTls ). ShouldProxy == ( directTls == false && proxyTls == true );
var budget = new LearningProbeBudget ();
checks [ "four_concurrent_probes" ] = Enumerable . Range ( 0 , 4 ). All ( i => budget . TryEnter ( "target" + i , 100_000 ));
checks [ "fifth_probe_bounded" ] = ! budget . TryEnter ( "fifth" , 100_000 );
budget . Exit ();
checks [ "duplicate_suppressed" ] = ! budget . TryEnter ( "target0" , 100_001 );
checks [ "free_slot_available" ] = budget . TryEnter ( "fifth" , 100_001 );
for ( var i = 0 ; i < 4 ; i ++) budget . Exit ();
checks [ "target_rechecked_after_cooldown" ] = budget . TryEnter ( "target0" , 130_001 );
budget . Exit ();
NetworkLearningLeaseSelfTest . AddChecks ( checks );
var rate = new LearningProbeBudget ();
checks [ "sixty_per_minute" ] = Enumerable . Range ( 0 , 60 ). All ( i =>{ var allowed = rate . TryEnter ( "r" + i , 100_000 ); if ( allowed ) rate . Exit (); return allowed ; });
checks [ "rate_limit_enforced" ] = ! rate . TryEnter ( "overflow" , 100_001 );
checks [ "rate_window_recovers" ] = rate . TryEnter ( "new" , 160_001 );
foreach ( var host in new [] { "127.0.0.1" , "100.100.1.1" , "192.168.1.1" , "169.254.169.254" , "::1" , "::ffff:127.0.0.1" , "203.0.113.1" })
checks [ "nonpublic_ip_" + host ] = ! LearningPolicy . Allowed ( "ip" , host );
2026-11-13 10:35:04 +08:00
foreach ( var host in new [] { "172.16.0.111" , "a.local" , "a.invalid" , "x.toplc.cn" , "a.com/path" , "a.com?secret=1" , "bad_.com" , "-bad.com" })
2026-10-11 23:23:20 +00:00
checks [ "unsafe_domain_" + host ] = ! LearningPolicy . Allowed ( "domain" , host );
checks [ "public_ip_allowed" ] = LearningPolicy . Allowed ( "ip" , "8.8.8.8" );
var direct = LearningPolicy . DirectFirst ( baseConfig );
checks [ "new_network_removes_shared_forcing" ] = ! direct . Contains ( "openai.com" ) && direct . Contains ( "category-ads-all" );
var root = JsonNode . Parse ( direct )!;
checks [ "private_and_default_stay_direct" ] = root [ "routing" ]![ "rules" ]![ 0 ]![ "outboundTag" ]!. GetValue < string >() == "direct"
&& root [ "routing" ]![ "rules" ]!. AsArray (). Last ()![ "outboundTag" ]!. GetValue < string >() == "direct" ;
RoutingManifest Rules ( string target ) => new () { Contract = 1 , Mode = "direct_first_candidates" , Revision = new string ( 'a' , 64 ),
Rules = [ new RoutingTarget { TargetType = "domain" , Target = target , MatchMode = "exact" }] };
var verified = LearningPolicy . Merge ( direct , Rules ( "learn.example.com" ));
checks [ "confirmed_exact_only" ] = verified . Contains ( "full:learn.example.com" ) && ! verified . Contains ( "domain:learn.example.com" );
checks [ "only_verified_tcp443_is_proxied" ] = JsonNode . Parse ( verified )![ "routing" ]![ "rules" ]![ 1 ]![ "port" ]!. GetValue < string >() == "443"
&& JsonNode . Parse ( verified )![ "routing" ]![ "rules" ]![ 1 ]![ "network" ]!. GetValue < string >() == "tcp" ;
checks [ "private_precedes_learned" ] = JsonNode . Parse ( verified )![ "routing" ]![ "rules" ]![ 0 ]![ "ip" ]![ 0 ]!. GetValue < string >() == "geoip:private" ;
checks [ "expiry_restores_direct" ] = ! LearningPolicy . Merge ( verified , new () { Contract = 1 , Revision = new string ( 'b' , 64 ) }). Contains ( "learn.example.com" );
checks [ "network_change_restores_direct" ] = ! LearningPolicy . DirectFirst ( verified ). Contains ( "learn.example.com" );
2026-11-13 10:35:04 +08:00
checks [ "unsafe_manifest_rejected" ] = Throws (() => LearningPolicy . Merge ( direct , Rules ( "vpn.toplc.cn" )));
2026-10-11 23:23:20 +00:00
checks [ "invalid_manifest_contract_rejected" ] = Throws (() => LearningPolicy . Merge ( direct , new () { Contract = 99 , Revision = new string ( 'a' , 64 ) }));
var runtime = JsonNode . Parse ( TunConfigBuilder . Build ( direct , "Ethernet" , true , includeTun : false , routingApiPort : 18090 , learningProbePort : 18091 ))!;
checks [ "info_in_memory_access_disabled" ] = runtime [ "log" ]![ "loglevel" ]!. GetValue < string >() == "info" && runtime [ "log" ]![ "access" ]!. GetValue < string >() == "none" ;
checks [ "probe_loopback_only" ] = runtime [ "inbounds" ]![ 0 ]![ "listen" ]!. GetValue < string >() == "127.0.0.1" ;
checks [ "probe_forced_proxy_after_private_guard" ] = runtime [ "routing" ]![ "rules" ]![ 0 ]![ "outboundTag" ]!. GetValue < string >() == "block"
&& runtime [ "routing" ]![ "rules" ]![ 1 ]![ "outboundTag" ]!. GetValue < string >() == "proxy" ;
checks [ "no_tun_in_test" ] = runtime [ "inbounds" ]!. AsArray (). All ( x => x ![ "protocol" ]!. GetValue < string >() != "tun" );
var both = JsonNode . Parse ( TunConfigBuilder . Build ( direct , "Ethernet" , true , includeTun : false , learningProbePort : 18091 , directProbePort : 18092 ))!;
var directInbound = both [ "inbounds" ]!. AsArray (). Single ( x => x ![ "tag" ]!. GetValue < string >()== "ucvl-direct-probe" )!;
checks [ "direct_probe_loopback_only" ] = directInbound [ "listen" ]!. GetValue < string >() == "127.0.0.1" ;
checks [ "direct_probe_no_sniff" ] = directInbound [ "sniffing" ] is null ;
var directOutbound = both [ "outbounds" ]!. AsArray (). Single ( x => x ![ "tag" ]!. GetValue < string >()== "ucvl-learning-direct" )!;
checks [ "direct_probe_binds_physical" ] = directOutbound [ "streamSettings" ]![ "sockopt" ]![ "interface" ]!. GetValue < string >() == "Ethernet" ;
checks [ "direct_probe_not_learned_route" ] = both [ "routing" ]![ "rules" ]![ 0 ]![ "outboundTag" ]!. GetValue < string >() == "block" && both [ "routing" ]![ "rules" ]![ 1 ]![ "outboundTag" ]!. GetValue < string >() == "ucvl-learning-direct" ;
var report = new { scope = "isolated policy tests; no current core or OS networking changed" , passed = checks . Values . All ( x => x ), checks };
File . WriteAllText ( Path . Combine ( AppContext . BaseDirectory , "learning-self-test.json" ), JsonSerializer . Serialize ( report , new JsonSerializerOptions { WriteIndented = true }));
return report . passed ? 0 : 31 ;
}
}