2026-10-11 23:23:20 +00:00
using System.Text.Json ;
using System.Text.Json.Nodes ;
namespace UCVL.VPNPlus ;
internal static class TailnetTransportSelfTest
{
internal static async Task < int > RunAsync ()
{
var checks = new Dictionary < string , bool >();
ConfigResponse Sample ( Action < JsonObject >? change = null )
{
var root = JsonNode . Parse ( """
{
"config_contract" : 2 , "connection_scope" : "public" , "node" :{ "slug" : "tokyo" , "name" : "VPN002" }, "route_mode" : "smart" ,
"tailscale_endpoint" :{ "contract" : 1 , "node_slug" : "tokyo" , "address" : "100.64.0.2" , "port" : 10803 },
"config" :{
"inbounds" :[], "outbounds" :[
{ "tag" : "proxy" , "protocol" : "vless" , "settings" :{ "vnext" :[{ "address" : "vpn002.example.invalid" , "port" : 11082 ,
"users" :[{ "id" : "11111111-1111-1111-1111-111111111111" , "encryption" : "none" , "flow" : "xtls-rprx-vision" }]}]},
"streamSettings" :{ "network" : "tcp" , "security" : "reality" , "realitySettings" :{ "serverName" : "one.one.one.one" , "publicKey" : "fixture-key" , "shortId" : "aabb" }}},
{ "tag" : "direct" , "protocol" : "freedom" },{ "tag" : "block" , "protocol" : "blackhole" }],
"routing" :{ "rules" :[]}}
}
""")!.AsObject();
change ?. Invoke ( root );
return JsonSerializer . Deserialize < ConfigResponse >( root . ToJsonString ())!;
}
string Host ( string json ) => JsonNode . Parse ( json )![ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "address" ]!. GetValue < string >();
var response = Sample ();
var original = response . GetRuntimeConfigJson ();
var prepared = TailnetTransport . TryPrepare ( response )!;
var clone = JsonNode . Parse ( prepared )!. AsObject ();
clone . Remove ( TailnetTransport . Marker );
clone [ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "address" ] = "vpn002.example.invalid" ;
clone [ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "port" ] = 11082 ;
checks [ "only_address_port_metadata_change" ] = JsonNode . DeepEquals ( clone , JsonNode . Parse ( original ));
checks [ "input_not_mutated" ] = original == response . GetRuntimeConfigJson ();
checks [ "tokyo_uses_backend_not_ingress_port" ] = JsonNode . Parse ( prepared )![ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "port" ]!. GetValue < int >() == 10803 ;
checks [ "silicon_endpoint_supported" ] = Host ( TailnetTransport . TryPrepare ( Sample ( r => {
r [ "tailscale_endpoint" ]![ "address" ] = "100.64.0.3" ; r [ "tailscale_endpoint" ]![ "port" ] = 11083 ;
}))!) == "100.64.0.3" ;
foreach ( var address in new [] { "127.0.0.1" , "8.8.8.8" , "192.168.50.111" , "100.100.100.100" , "100.64.0.0" , "100.127.255.255" , "100.128.0.1" , "100.63.255.255" , "100.099.142.38" , "100.64.0.2/32" , "::1" , "example.com" })
checks [ "reject_address_" + address ] = TailnetTransport . TryPrepare ( Sample ( r => r [ "tailscale_endpoint" ]![ "address" ] = address )) is null ;
foreach ( var port in new [] { 0 , - 1 , 65536 })
checks [ "reject_port_" + port ] = TailnetTransport . TryPrepare ( Sample ( r => r [ "tailscale_endpoint" ]![ "port" ] = port )) is null ;
checks [ "wrong_node_rejected" ] = TailnetTransport . TryPrepare ( Sample ( r => r [ "tailscale_endpoint" ]![ "node_slug" ] = "other" )) is null ;
checks [ "wrong_contract_rejected" ] = TailnetTransport . TryPrepare ( Sample ( r => r [ "tailscale_endpoint" ]![ "contract" ] = 99 )) is null ;
checks [ "wrong_config_contract_rejected" ] = TailnetTransport . TryPrepare ( Sample ( r => r [ "config_contract" ] = 3 )) is null ;
checks [ "private_scope_rejected" ] = TailnetTransport . TryPrepare ( Sample ( r => r [ "connection_scope" ] = "private_auxiliary" )) is null ;
checks [ "direct_mode_no_alternate" ] = TailnetTransport . TryPrepare ( Sample ( r => r [ "route_mode" ] = "direct" )) is null ;
checks [ "legacy_response_no_alternate" ] = TailnetTransport . TryPrepare ( Sample ( r => r . Remove ( "tailscale_endpoint" ))) is null ;
checks [ "plaintext_rejected" ] = TailnetTransport . TryPrepare ( Sample ( r => r [ "config" ]![ "outbounds" ]![ 0 ]![ "streamSettings" ]![ "security" ] = "none" )) is null ;
checks [ "wrong_protocol_rejected" ] = TailnetTransport . TryPrepare ( Sample ( r => r [ "config" ]![ "outbounds" ]![ 0 ]![ "protocol" ] = "socks" )) is null ;
checks [ "missing_identity_rejected" ] = TailnetTransport . TryPrepare ( Sample ( r => r [ "config" ]![ "outbounds" ]![ 0 ]![ "streamSettings" ]![ "realitySettings" ]!. AsObject (). Remove ( "publicKey" ))) is null ;
checks [ "duplicate_proxy_rejected" ] = TailnetTransport . TryPrepare ( Sample ( r => {
var o = r [ "config" ]![ "outbounds" ]!. AsArray (); o . Add ( o [ 0 ]!. DeepClone ());
})) is null ;
var runtime = JsonNode . Parse ( TunConfigBuilder . Build ( prepared , "Phone" , false , includeTun : false , tailnetInterfaceName : "UserNetwork" ))!;
checks [ "proxy_binds_user_route" ] = runtime [ "outbounds" ]![ 0 ]![ "streamSettings" ]![ "sockopt" ]![ "interface" ]!. GetValue < string >() == "UserNetwork" ;
checks [ "direct_stays_physical" ] = runtime [ "outbounds" ]![ 1 ]![ "streamSettings" ]![ "sockopt" ]![ "interface" ]!. GetValue < string >() == "Phone" ;
checks [ "metadata_not_sent_to_xray" ] = runtime [ TailnetTransport . Marker ] is null ;
checks [ "no_tun_in_fixture" ] = runtime [ "inbounds" ]!. AsArray (). Count == 0 ;
checks [ "missing_route_binding_rejected" ] = Throws (() => TunConfigBuilder . Build ( prepared , "Phone" , false , includeTun : false ));
var altered = JsonNode . Parse ( prepared )!. AsObject (); altered [ TailnetTransport . Marker ]![ "address" ] = "100.65.1.1" ;
checks [ "metadata_config_mismatch_rejected" ] = Throws (() => TailnetTransport . Address ( altered ));
var usable = new HashSet < int > { 9 , 34 };
var route = new Ipv4Route ( "100.64.0.0" , "255.192.0.0" , "0.0.0.0" , 34 );
checks [ "existing_overlay_route" ] = TailnetTransport . SelectRoute ( "100.64.0.2" , [ route ], usable ) == 34 ;
checks [ "user_gateway_host_route" ] = TailnetTransport . SelectRoute ( "100.64.0.2" , [ new ( "100.64.0.2" , "255.255.255.255" , "172.16.0.1" , 9 )], usable )== 9 ;
checks [ "default_and_tun_not_sufficient" ] = TailnetTransport . SelectRoute ( "100.64.0.2" , [ new ( "0.0.0.0" , "0.0.0.0" , "1.1.1.1" , 9 ), new ( "0.0.0.0" , "128.0.0.0" , "0.0.0.0" , 34 )], usable ) is null ;
checks [ "down_route_refused" ] = TailnetTransport . SelectRoute ( "100.64.0.2" , [ route ], new HashSet < int >{ 9 }) is null ;
checks [ "more_specific_own_tun_refused" ] = TailnetTransport . SelectRoute ( "100.64.0.2" , [ route , new ( "100.64.0.2" , "255.255.255.255" , "0.0.0.0" , 99 )], usable ) is null ;
checks [ "ambiguous_interface_refused" ] = TailnetTransport . SelectRoute ( "100.64.0.2" , [ route , route with { InterfaceIndex = 9 }], usable ) is null ;
checks [ "noncontiguous_mask_refused" ] = TailnetTransport . SelectRoute ( "100.64.0.2" , [ route with { Mask = "255.0.255.0" }], usable ) is null ;
checks [ "unrelated_route_refused" ] = TailnetTransport . SelectRoute ( "100.64.0.2" , [ route with { Destination = "172.16.0.0" , Mask = "255.255.0.0" }], usable ) is null ;
var preference = new TailnetPreference ();
long tick = 100 ;
var starts = new List < string >(); var stops = 0 ; var probes = 0 ; var routeReads = 0 ;
var statuses = new List < string >();
Task Start ( string json , CancellationToken token ) { token . ThrowIfCancellationRequested (); starts . Add ( Host ( json )); return Task . CompletedTask ; }
Task Stop () { stops ++; return Task . CompletedTask ; }
Task < bool > Healthy ( CancellationToken token ) { token . ThrowIfCancellationRequested (); probes ++; return Task . FromResult ( true ); }
void Route ( string _ ) { routeReads ++; }
var selected = await NodeTransportConnector . ConnectAsync ( response , preference , Start , Stop , Healthy , Route , _ =>{}, ()=> tick , CancellationToken . None );
checks [ "success_one_start_no_stop" ] = selected && starts . SequenceEqual ( new []{ "100.64.0.2" }) && stops == 0 && probes == 1 ;
starts . Clear (); probes = 0 ;
selected = await NodeTransportConnector . ConnectAsync ( response , preference , Start , Stop , _ => Task . FromResult ( false ), Route , statuses . Add ,()=> tick , CancellationToken . None );
checks [ "failed_proof_falls_back_same_node" ] = ! selected && starts . SequenceEqual ( new []{ "100.64.0.2" , "vpn002.example.invalid" }) && stops == 1 ;
checks [ "failed_proof_status_identifies_protocol_and_public_fallback" ] = statuses . Last () == "Tailscale 协议或代理出口验证失败,回退同一节点公网入口" ;
starts . Clear (); routeReads = 0 ;
selected = await NodeTransportConnector . ConnectAsync ( response , preference , Start , Stop , Healthy , Route , _ =>{},()=> tick + 299999 , CancellationToken . None );
checks [ "cooldown_skips_route_and_probe" ] = ! selected && starts . SequenceEqual ( new []{ "vpn002.example.invalid" }) && routeReads == 0 && probes == 0 ;
2026-10-27 02:00:33 +00:00
checks [ "domain_fallback_stays_sticky_after_five_minutes" ] = ! preference . MayTry ( "tokyo" , tick + 300000 )
&& ! preference . MayTry ( "tokyo" , tick + 86_400_000 );
checks [ "domain_fallback_blocks_other_internal_nodes_this_session" ] = ! preference . MayTry ( "silicon" , tick );
preference . ResetForUserConnect ();
checks [ "explicit_user_connect_resets_domain_choice" ] = preference . MayTry ( "tokyo" , tick + 1 ) && preference . MayTry ( "silicon" , tick + 1 );
2026-10-11 23:23:20 +00:00
starts . Clear (); statuses . Clear ();
selected = await NodeTransportConnector . ConnectAsync ( response , new (), Start , Stop , Healthy , _ => throw new IOException ( "SYNTHETIC_SECRET route unavailable" ), statuses . Add ,()=> tick , CancellationToken . None );
checks [ "route_read_failure_keeps_original" ] = ! selected && starts . SequenceEqual ( new []{ "vpn002.example.invalid" });
checks [ "route_failure_status_is_specific_and_redacted" ] = statuses . SequenceEqual ( new []{ "Tailscale 无独立内网路由,使用同一节点公网入口" });
starts . Clear (); var failStarts = 0 ;
selected = await NodeTransportConnector . ConnectAsync ( response , new (),( json , token )=> {
failStarts ++; if ( failStarts == 1 ) throw new IOException ( "fixture startup failure" ); return Start ( json , token );
}, Stop , Healthy , Route , _ =>{},()=> tick , CancellationToken . None );
checks [ "start_failure_same_node_fallback" ] = ! selected && failStarts == 2 && starts . SequenceEqual ( new []{ "vpn002.example.invalid" });
starts . Clear ();
checks [ "restore_failure_stops_sequence" ] = await ThrowsAsync (()=> NodeTransportConnector . ConnectAsync ( response , new (), Start ,
()=> throw new IOException ( "fixture restore failure" ), _ => Task . FromResult ( false ), Route , _ =>{},()=> tick , CancellationToken . None ))
&& starts . SequenceEqual ( new []{ "100.64.0.2" });
starts . Clear ();
checks [ "local_network_failure_no_fallback" ] = await ThrowsAsync (()=> NodeTransportConnector . ConnectAsync ( response , new (),
( _ , _ )=> throw new LocalNetworkException ( "fixture local failure" ), Stop , Healthy , Route , _ =>{},()=> tick , CancellationToken . None )) && starts . Count == 0 ;
using var cancel = new CancellationTokenSource (); starts . Clear (); var priorStops = stops ;
checks [ "user_cancel_never_falls_back" ] = await ThrowsAsync (()=> NodeTransportConnector . ConnectAsync ( response , new (),
( json , token )=> { starts . Add ( Host ( json )); cancel . Cancel (); token . ThrowIfCancellationRequested (); return Task . CompletedTask ; },
Stop , Healthy , Route , _ =>{},()=> tick , cancel . Token )) && starts . SequenceEqual ( new []{ "100.64.0.2" }) && stops == priorStops ;
starts . Clear ();
checks [ "pre_cancel_has_no_side_effect" ] = await ThrowsAsync (()=> NodeTransportConnector . ConnectAsync ( response , new (), Start , Stop , Healthy , Route , _ =>{},()=> tick , cancel . Token )) && starts . Count == 0 ;
starts . Clear (); routeReads = 0 ; probes = 0 ;
selected = await NodeTransportConnector . ConnectAsync ( Sample ( r => r . Remove ( "tailscale_endpoint" )), new (), Start , Stop , Healthy , Route , _ =>{},()=> tick , CancellationToken . None );
checks [ "old_backend_original_only" ] = ! selected && starts . SequenceEqual ( new []{ "vpn002.example.invalid" }) && routeReads == 0 && probes == 0 ;
checks [ "fallback_same_authorization" ] = TailnetTransport . SameAuthorizedFallback ( prepared , original );
checks [ "fallback_changed_credentials_denied" ] = ! TailnetTransport . SameAuthorizedFallback ( prepared ,
original . Replace ( "11111111-1111-1111-1111-111111111111" , "22222222-2222-2222-2222-222222222222" ));
checks [ "fallback_changed_identity_denied" ] = ! TailnetTransport . SameAuthorizedFallback ( prepared , original . Replace ( "fixture-key" , "wrong-key" ));
starts . Clear (); var beforeStops = stops ;
var rebound = await NodeTransportConnector . RebindAsync ( prepared , original ,( json , token )=> {
starts . Add ( Host ( json )); if ( TailnetTransport . Address ( json ) is not null ) throw new IOException ( "new phone network has no overlay route" );
return Task . CompletedTask ;
}, Stop , Healthy , CancellationToken . None );
checks [ "handover_lost_overlay_same_node_fallback" ] = rebound == original && starts . SequenceEqual ( new []{ "100.64.0.2" , "vpn002.example.invalid" }) && stops == beforeStops + 1 ;
starts . Clear (); beforeStops = stops ;
rebound = await NodeTransportConnector . RebindAsync ( prepared , original , Start , Stop , Healthy , CancellationToken . None );
checks [ "handover_healthy_overlay_kept" ] = rebound == prepared && starts . SequenceEqual ( new []{ "100.64.0.2" }) && stops == beforeStops ;
starts . Clear ();
checks [ "handover_missing_fallback_denied" ] = await ThrowsAsync (()=> NodeTransportConnector . RebindAsync ( prepared , null , Start , Stop , Healthy , CancellationToken . None )) && starts . Count == 0 ;
starts . Clear ();
checks [ "handover_restore_failure_no_second_start" ] = await ThrowsAsync (()=> NodeTransportConnector . RebindAsync ( prepared , original , Start ,
()=> throw new IOException ( "fixture restore failure" ), _ => Task . FromResult ( false ), CancellationToken . None )) && starts . Count == 1 ;
starts . Clear ();
checks [ "handover_cancel_no_fallback" ] = await ThrowsAsync (()=> NodeTransportConnector . RebindAsync ( prepared , original , Start , Stop , Healthy , cancel . Token )) && starts . Count == 0 ;
var merged = LearningPolicy . Merge ( LearningPolicy . DirectFirst ( prepared ), new RoutingManifest {
Contract = 1 , Revision = new string ( '0' , 64 ), Rules =[] });
var learningRouting = JsonNode . Parse ( TunConfigBuilder . BuildLearningRouting ( merged , "Phone" , 18091 , 18092 , "UserNetwork" ))!. AsObject ();
checks [ "real_learning_build_accepts_tailnet_binding" ] = learningRouting . Count == 1 && learningRouting [ "routing" ] is JsonObject ;
checks [ "learning_update_cannot_replace_outbounds" ] = learningRouting [ "outbounds" ] is null && learningRouting [ TailnetTransport . Marker ] is null ;
var newNetwork = new TunRouting . PhysicalNetwork ( "PhoneFixture" , 9 , System . Net . IPAddress . Parse ( "192.0.2.2" ), 24 ,
System . Net . IPAddress . Parse ( "192.0.2.1" ),[ System . Net . IPAddress . Parse ( "192.0.2.1" )]);
var handoverRuntime = new HandoverFixture { BoundNetworkFingerprint = "old-network" , Current = prepared ,
Rebind =()=> NodeTransportConnector . RebindAsync ( prepared , original ,( json , _ )=> {
if ( TailnetTransport . Address ( json ) is not null ) throw new IOException ( "fixture route disappeared" );
return Task . CompletedTask ;
},()=> Task . CompletedTask , _ => Task . FromResult ( true ), CancellationToken . None ),
NextFingerprint = PhysicalUplink . Fingerprint ( newNetwork ) };
var handover = new NetworkHandover ( handoverRuntime ,()=> 3000 );
await handover . ObserveAsync ( new ( true , newNetwork ), 0 , CancellationToken . None );
var result = await handover . ObserveAsync ( new ( true , newNetwork ), 3000 , CancellationToken . None );
checks [ "handover_pending_clears_after_same_node_fallback" ] = result == NetworkHandover . Result . Recovered
&& ! handover . Pending && ! handover . Settling && handoverRuntime . Current == original ;
var cachedConfig = prepared ; var failedStarts = new List < string >();
checks [ "handover_double_failure_retains_original" ] = await ThrowsAsync (()=> NodeTransportConnector . RebindAsync ( cachedConfig , original ,
( json , _ )=> { cachedConfig = json ; failedStarts . Add ( Host ( json )); throw new IOException ( "fixture both paths unavailable" ); },
()=> Task . CompletedTask , _ => Task . FromResult ( false ), CancellationToken . None ))
&& cachedConfig == original && failedStarts . SequenceEqual ( new []{ "100.64.0.2" , "vpn002.example.invalid" });
starts . Clear (); probes = 0 ;
rebound = await NodeTransportConnector . RebindAsync ( cachedConfig , original , Start , Stop , Healthy , CancellationToken . None );
checks [ "handover_next_retry_public_only" ] = rebound == original && starts . SequenceEqual ( new []{ "vpn002.example.invalid" }) && probes == 0 ;
starts . Clear (); var internalCancelledStarts = 0 ;
selected = await NodeTransportConnector . ConnectAsync ( response , new (),( json , token )=> {
if (++ internalCancelledStarts == 1 ) throw new OperationCanceledException ( "fixture internal deadline" );
return Start ( json , token );
}, Stop , Healthy , Route , _ =>{},()=> tick , CancellationToken . None );
checks [ "internal_timeout_falls_back_not_user_cancel" ] = ! selected && internalCancelledStarts == 2 && starts . SequenceEqual ( new []{ "vpn002.example.invalid" });
ConfigResponse Known ( Action < JsonObject >? change = null ) => Sample ( r => {
r . Remove ( "tailscale_endpoint" ); r [ "node" ]![ "slug" ] = "aliyun-tokyo-002" ;
change ?. Invoke ( r );
});
var known = Known ();
var compatible = TailnetTransport . TryPrepare ( known , allowKnownEndpoints : true )!;
checks [ "known_tokyo_compatibility_mapping" ] = Host ( compatible ) == "100.64.0.2" && TailnetTransport . Port ( compatible ) == 10803 ;
checks [ "known_compatibility_still_same_authorization" ] = TailnetTransport . SameAuthorizedFallback ( compatible , known . GetRuntimeConfigJson ());
checks [ "known_compatibility_requires_mapping_permission" ] = TailnetTransport . TryPrepare ( known ) is null ;
checks [ "known_mapping_flag_is_not_identity_policy" ] = KnownTailnetEndpoints . Resolve ( known , allowCompatibilityMapping : true ) is not null
&& KnownTailnetEndpoints . Resolve ( known , allowCompatibilityMapping : false ) is null ;
checks [ "explicit_null_disables_known_mapping" ] = TailnetTransport . TryPrepare ( Known ( r => r [ "tailscale_endpoint" ] = null ), true ) is null ;
checks [ "invalid_explicit_metadata_never_uses_known_mapping" ] = TailnetTransport . TryPrepare ( Known ( r => r [ "tailscale_endpoint" ] = new JsonObject ()), true ) is null ;
checks [ "unknown_named_node_does_not_use_known_mapping" ] = TailnetTransport . TryPrepare ( Sample ( r => r . Remove ( "tailscale_endpoint" )), true ) is null ;
checks [ "known_changed_public_host_rejected" ] = TailnetTransport . TryPrepare ( Known ( r => r [ "config" ]![ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "address" ] = "other.example.com" ), true ) is null ;
checks [ "known_changed_public_port_rejected" ] = TailnetTransport . TryPrepare ( Known ( r => r [ "config" ]![ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "port" ] = 11083 ), true ) is null ;
checks [ "known_wrong_protocol_rejected" ] = TailnetTransport . TryPrepare ( Known ( r => r [ "config" ]![ "outbounds" ]![ 0 ]![ "protocol" ] = "socks" ), true ) is null ;
checks [ "known_plaintext_rejected" ] = TailnetTransport . TryPrepare ( Known ( r => r [ "config" ]![ "outbounds" ]![ 0 ]![ "streamSettings" ]![ "security" ] = "none" ), true ) is null ;
checks [ "known_missing_reality_identity_rejected" ] = TailnetTransport . TryPrepare ( Known ( r => r [ "config" ]![ "outbounds" ]![ 0 ]![ "streamSettings" ]![ "realitySettings" ]!. AsObject (). Remove ( "publicKey" )), true ) is null ;
checks [ "known_wrong_contract_rejected" ] = TailnetTransport . TryPrepare ( Known ( r => r [ "config_contract" ] = 1 ), true ) is null ;
checks [ "known_private_scope_rejected" ] = TailnetTransport . TryPrepare ( Known ( r => r [ "connection_scope" ] = "private_auxiliary" ), true ) is null ;
checks [ "known_direct_mode_unchanged" ] = TailnetTransport . TryPrepare ( Known ( r => r [ "route_mode" ] = "direct" ), true ) is null ;
var silicon = TailnetTransport . TryPrepare ( Known ( r => {
r [ "node" ]![ "slug" ] = "aliyun-siliconvalley-003" ;
r [ "config" ]![ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "address" ] = "vpn003.example.invalid" ;
r [ "config" ]![ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "port" ] = 11083 ;
}), true )!;
checks [ "known_silicon_exact_mapping" ] = Host ( silicon ) == "100.64.0.3" && TailnetTransport . Port ( silicon ) == 11083 ;
var future = TailnetTransport . TryPrepare ( Known ( r => r [ "tailscale_endpoint" ] = new JsonObject {
["contract"] = 1 , [ "node_slug" ] = "aliyun-tokyo-002" , [ "address" ] = "100.65.1.9" , [ "port" ] = 2345
}), true )!;
checks [ "explicit_server_metadata_takes_priority" ] = Host ( future ) == "100.65.1.9" && TailnetTransport . Port ( future ) == 2345 ;
2026-10-27 02:00:33 +00:00
var gatewayKnown = Known ( r => r [ "gateway" ] = new JsonObject { [ "host" ] = "vpn.example.invalid" , [ "ipv4" ] = "192.0.2.1" });
2026-10-11 23:23:20 +00:00
checks [ "compatibility_checks_node_before_gateway_rewrite" ] = Host ( TailnetTransport . TryPrepare ( gatewayKnown , true )!) == "100.64.0.2" ;
checks [ "compatibility_fallback_keeps_api_public_gateway" ] = TailnetTransport . SameAuthorizedFallback (
TailnetTransport . TryPrepare ( gatewayKnown , true )!, gatewayKnown . GetRuntimeConfigJson ()) && Host ( gatewayKnown . GetRuntimeConfigJson ()) == "192.0.2.1" ;
starts . Clear (); beforeStops = stops ; probes = 0 ; var preflights = 0 ;
selected = await NodeTransportConnector . ConnectAsync ( known , new (), Start , Stop , Healthy , Route , _ =>{},()=> tick , CancellationToken . None ,
allowKnownEndpoints : true , endpointProbe :( address , port , _ )=> {
preflights ++; checks [ "preflight_exact_tokyo_endpoint" ] = address == "100.64.0.2" && port == 10803 ;
return Task . FromResult ( true );
});
checks [ "compatible_success_verified_before_label" ] = selected && preflights == 1 && probes == 1 && stops == beforeStops
&& starts . SequenceEqual ( new []{ "100.64.0.2" });
starts . Clear (); beforeStops = stops ; probes = 0 ; statuses . Clear (); var deniedPreference = new TailnetPreference ();
selected = await NodeTransportConnector . ConnectAsync ( known , deniedPreference , Start , Stop , Healthy , Route , statuses . Add ,()=> tick , CancellationToken . None ,
allowKnownEndpoints : true , endpointProbe :( _ , _ , _ )=> Task . FromResult ( false ));
checks [ "closed_port_skips_tailnet_start_and_stop" ] = ! selected && starts . SequenceEqual ( new []{ "vpn002.example.invalid" }) && stops == beforeStops && probes == 0 ;
2026-10-27 02:00:33 +00:00
checks [ "ping_unreachable_status_is_distinct_from_route_failure" ] = statuses . Last () == "内网 IP Ping 不通,回退域名并保持" ;
2026-10-11 23:23:20 +00:00
checks [ "closed_port_sets_node_cooldown" ] = ! deniedPreference . MayTry ( known . Node . Slug , tick + 1 );
starts . Clear ();
selected = await NodeTransportConnector . ConnectAsync ( known , deniedPreference , Start , Stop , Healthy , Route , _ =>{},()=> tick + 1 , CancellationToken . None ,
allowKnownEndpoints : true , endpointProbe :( _ , _ , _ )=> throw new InvalidOperationException ( "must not probe during cooldown" ));
checks [ "preflight_not_repeated_in_cooldown" ] = ! selected && starts . SequenceEqual ( new []{ "vpn002.example.invalid" });
deniedPreference . Failed ( "other-node" , tick );
deniedPreference . ResetForUserConnect ();
checks [ "user_connect_reset_clears_node_cooldowns" ] = deniedPreference . MayTry ( known . Node . Slug , tick + 1 ) && deniedPreference . MayTry ( "other-node" , tick + 1 );
starts . Clear (); preflights = 0 ; probes = 0 ;
selected = await NodeTransportConnector . ConnectAsync ( known , deniedPreference , Start , Stop , Healthy , Route , _ =>{},()=> tick + 1 , CancellationToken . None ,
allowKnownEndpoints : true , endpointProbe :( _ , _ , _ )=> { preflights ++; return Task . FromResult ( true ); });
checks [ "manual_reset_reprobes_and_requires_protocol_health" ] = selected && preflights == 1 && probes == 1 && starts . SequenceEqual ( new []{ "100.64.0.2" });
deniedPreference . Failed ( known . Node . Slug , tick + 2 );
starts . Clear (); preflights = 0 ; probes = 0 ;
selected = await NodeTransportConnector . ConnectAsync ( known , deniedPreference , Start , Stop , Healthy , Route , _ =>{},()=> tick + 3 , CancellationToken . None ,
allowKnownEndpoints : true , endpointProbe :( _ , _ , _ )=> { preflights ++; return Task . FromResult ( true ); });
checks [ "automatic_retry_keeps_cooldown_after_later_failure" ] = ! selected && preflights == 0 && probes == 0 && starts . SequenceEqual ( new []{ "vpn002.example.invalid" });
starts . Clear (); using var preflightCancel = new CancellationTokenSource ();
checks [ "preflight_cancel_keeps_both_paths_unstarted" ] = await ThrowsAsync (()=> NodeTransportConnector . ConnectAsync ( known , new (), Start , Stop , Healthy , Route , _ =>{},()=> tick , preflightCancel . Token ,
allowKnownEndpoints : true , endpointProbe :( _ , _ , ct )=> { preflightCancel . Cancel (); ct . ThrowIfCancellationRequested (); return Task . FromResult ( true ); })) && starts . Count == 0 ;
starts . Clear (); probes = 0 ;
selected = await NodeTransportConnector . ConnectAsync ( Known ( r => r [ "tailscale_endpoint" ]= null ), new (), Start , Stop , Healthy , Route , _ =>{},()=> tick , CancellationToken . None ,
allowKnownEndpoints : true , endpointProbe :( _ , _ , _ )=> throw new InvalidOperationException ( "explicit null must not probe" ));
checks [ "explicit_disabled_transport_never_probed" ] = ! selected && starts . SequenceEqual ( new []{ "vpn002.example.invalid" }) && probes == 0 ;
2026-10-22 05:43:39 +00:00
TailnetTransport . TryPrepare ( Known ( r => r [ "tailscale_endpoint" ]= null ), out var skipReason , true );
checks [ "diagnostic_explicit_null_is_not_missing_metadata" ] = skipReason == "explicit_endpoint_disabled" ;
TailnetTransport . TryPrepare ( Known ( r => r [ "config_contract" ]= 1 ), out skipReason , true );
checks [ "diagnostic_unknown_contract_preserves_rejection" ] = skipReason == "config_contract_unsupported" ;
TailnetTransport . TryPrepare ( Known ( r => r [ "config" ]![ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "address" ]= "other.example.com" ), out skipReason , true );
checks [ "diagnostic_known_ingress_mismatch_is_distinct" ] = skipReason == "known_original_ingress_mismatch" ;
TailnetTransport . TryPrepare ( known , out skipReason , true );
checks [ "diagnostic_compatibility_source_identified" ] = skipReason == "known_endpoint" ;
var diagnostics = new List < TransportDiagnostic >();
starts . Clear (); beforeStops = stops ;
var tailnetFailure = "" ;
try
{
await NodeTransportConnector . ConnectAsync ( known , new (), Start , Stop , Healthy , Route , _ =>{},()=> tick , CancellationToken . None ,
allowKnownEndpoints : true , endpointProbe :( _ , _ , _ )=> Task . FromResult ( false ), tailnetOnly : true , diagnostic : diagnostics . Add );
}
catch ( TailnetUnavailableException failure ) { tailnetFailure = failure . Reason ; }
checks [ "internal_first_closed_port_never_starts_public" ] = tailnetFailure == "endpoint_unreachable" && starts . Count == 0 && stops == beforeStops ;
checks [ "diagnostics_persist_specific_probe_failure" ] = diagnostics . Any ( d => d . Event == "tailnet_skipped" && d . Reason == "endpoint_unreachable" && d . Node == known . Node . Slug );
starts . Clear (); diagnostics . Clear (); beforeStops = stops ;
checks [ "internal_first_failed_auth_cleans_up_before_other_node" ] = await ThrowsAsync (()=> NodeTransportConnector . ConnectAsync ( known , new (), Start , Stop ,
_ => Task . FromResult ( false ), Route , _ =>{},()=> tick , CancellationToken . None , allowKnownEndpoints : true ,
endpointProbe :( _ , _ , _ )=> Task . FromResult ( true ), tailnetOnly : true , diagnostic : diagnostics . Add ))
&& starts . SequenceEqual ( new []{ "100.64.0.2" }) && stops == beforeStops + 1
&& ! diagnostics . Any ( d => d . Reason == "public_ingress" );
starts . Clear (); diagnostics . Clear ();
var heldPreference = new TailnetPreference (); heldPreference . Failed ( known . Node . Slug , tick );
checks [ "internal_first_cooldown_never_starts_public" ] = await ThrowsAsync (()=> NodeTransportConnector . ConnectAsync ( known , heldPreference , Start , Stop , Healthy ,
Route , _ =>{},()=> tick + 1 , CancellationToken . None , allowKnownEndpoints : true , tailnetOnly : true , diagnostic : diagnostics . Add ))
&& starts . Count == 0 && diagnostics . Single (). Reason == "cooldown_active" ;
var safeDiagnostic = new TransportDiagnostic ( "selected\nconfig" , "SYNTHETIC_SECRET?\r\n" , new string ( 'n' , 120 )). SafeMessage ;
checks [ "diagnostics_line_and_identifier_bounded" ] = ! safeDiagnostic . Contains ( '\n' ) && ! safeDiagnostic . Contains ( '\r' ) && ! safeDiagnostic . Contains ( '?' ) && safeDiagnostic . Length < 260 ;
starts . Clear (); beforeStops = stops ; probes = 0 ; preflights = 0 ; routeReads = 0 ; diagnostics . Clear ();
rebound = await NodeTransportConnector . RebindAsync ( original , null , Start , Stop , Healthy , CancellationToken . None ,
preferredTailnetConfig : prepared , requireRoute : Route , endpointProbe :( _ , _ , _ )=>{ preflights ++; return Task . FromResult ( true );}, diagnostic : diagnostics . Add );
2026-10-27 02:00:33 +00:00
checks [ "handover_public_never_rechecks_or_promotes_internal" ] = rebound == original && starts . SequenceEqual ( new []{ "vpn002.example.invalid" })
&& stops == beforeStops && preflights == 0 && routeReads == 0 && probes == 0 ;
checks [ "handover_reports_public_choice" ] = diagnostics . Any ( d => d . Event == "rebind_selected" && d . Reason == "public_ingress" );
2026-10-22 05:43:39 +00:00
starts . Clear (); beforeStops = stops ; probes = 0 ;
rebound = await NodeTransportConnector . RebindAsync ( original , null , Start , Stop , Healthy , CancellationToken . None ,
preferredTailnetConfig : prepared , requireRoute : Route , endpointProbe :( _ , _ , _ )=> Task . FromResult ( false ));
checks [ "handover_unreachable_alternate_keeps_public_without_replacement_attempt" ] = rebound == original
&& starts . SequenceEqual ( new []{ "vpn002.example.invalid" }) && stops == beforeStops && probes == 0 ;
starts . Clear (); beforeStops = stops ;
rebound = await NodeTransportConnector . RebindAsync ( original , null , Start , Stop , _ => Task . FromResult ( false ), CancellationToken . None ,
preferredTailnetConfig : prepared , requireRoute : Route , endpointProbe :( _ , _ , _ )=> Task . FromResult ( true ));
2026-10-27 02:00:33 +00:00
checks [ "handover_public_does_not_restart_internal_even_when_probe_would_succeed" ] = rebound == original
&& starts . SequenceEqual ( new []{ "vpn002.example.invalid" }) && stops == beforeStops ;
starts . Clear ();
try {
rebound = await NodeTransportConnector . RebindAsync ( original , null , Start , Stop , Healthy , CancellationToken . None ,
preferredTailnetConfig : prepared . Replace ( "fixture-key" , "different-key" ), requireRoute : Route , endpointProbe :( _ , _ , _ )=> Task . FromResult ( true ));
checks [ "handover_ignores_unused_preferred_credentials" ] = rebound == original && starts . SequenceEqual ( new []{ "vpn002.example.invalid" });
} catch { checks [ "handover_ignores_unused_preferred_credentials" ] = false ; }
starts . Clear ();
try {
rebound = await NodeTransportConnector . RebindAsync ( original , null , Start , Stop , Healthy , CancellationToken . None ,
preferredTailnetConfig : prepared , requireRoute : Route );
checks [ "handover_public_needs_no_internal_probe" ] = rebound == original && starts . SequenceEqual ( new []{ "vpn002.example.invalid" });
} catch { checks [ "handover_public_needs_no_internal_probe" ] = false ; }
2026-10-22 05:43:39 +00:00
starts . Clear ();
checks [ "handover_preferred_cancellation_does_not_start_any_path" ] = await ThrowsAsync (()=> NodeTransportConnector . RebindAsync ( original , null , Start , Stop , Healthy , cancel . Token ,
preferredTailnetConfig : prepared , requireRoute : Route , endpointProbe :( _ , _ , _ )=> Task . FromResult ( true ))) && starts . Count == 0 ;
// Exercise the actual public ranker + connector as one offline sequence:
// socket availability is ordering evidence, never proxy-health proof.
var rankedResponses = new Dictionary < string , ConfigResponse > {
["tokyo"] = response ,
["silicon"] = Sample ( r => {
r [ "node" ]![ "slug" ]= "silicon" ;
r [ "tailscale_endpoint" ]![ "node_slug" ]= "silicon" ;
r [ "tailscale_endpoint" ]![ "address" ]= "100.64.0.3" ;
r [ "tailscale_endpoint" ]![ "port" ]= 11083 ;
r [ "config" ]![ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "address" ]= "vpn003.example.invalid" ;
r [ "config" ]![ "outbounds" ]![ 0 ]![ "settings" ]![ "vnext" ]![ 0 ]![ "port" ]= 11083 ;
})
};
var rankedCandidates = await PublicTailnetSelection . RankAsync ( rankedResponses . Values . Select ( r => r . Node ), "smart" , _ => false ,
( slug , _ )=> Task . FromResult ( rankedResponses [ slug ]), async ( address , _ , ct )=> {
if ( address == "100.64.0.3" ) await Task . Delay ( 20 , ct );
return true ;
}, CancellationToken . None );
checks [ "integration_ranker_keeps_both_authorized_endpoints" ] = rankedCandidates . Count == 2
&& rankedCandidates [ 0 ]. Response . Node . Slug == "tokyo" && rankedCandidates [ 1 ]. Response . Node . Slug == "silicon" ;
starts . Clear (); beforeStops = stops ;
var rankedPreference = new TailnetPreference ();
var connectedSecond = false ;
foreach ( var rankedCandidate in rankedCandidates )
{
try
{
connectedSecond = await NodeTransportConnector . ConnectAsync ( rankedCandidate . Response , rankedPreference , Start , Stop ,
_ => Task . FromResult ( starts . LastOrDefault ()== "100.64.0.3" ), Route , _ =>{},()=> tick , CancellationToken . None ,
endpointProbe :( _ , _ , _ )=> Task . FromResult ( true ), tailnetOnly : true );
if ( connectedSecond ) break ;
}
catch ( TailnetUnavailableException ) { /* MainForm continues the inner pass, not a node penalty. */ }
}
checks [ "integration_protocol_failure_tries_next_internal_before_public" ] = connectedSecond
&& starts . SequenceEqual ( new []{ "100.64.0.2" , "100.64.0.3" }) && stops == beforeStops + 1 ;
checks [ "integration_transport_failure_does_not_cool_other_node" ] = ! rankedPreference . MayTry ( "tokyo" , tick + 1 )
&& rankedPreference . MayTry ( "silicon" , tick + 1 );
starts . Clear (); beforeStops = stops ; rankedPreference = new ();
var unavailableCandidates = 0 ;
foreach ( var rankedCandidate in rankedCandidates )
{
try
{
await NodeTransportConnector . ConnectAsync ( rankedCandidate . Response , rankedPreference , Start , Stop , _ => Task . FromResult ( false ),
Route , _ =>{},()=> tick , CancellationToken . None , endpointProbe :( _ , _ , _ )=> Task . FromResult ( true ), tailnetOnly : true );
}
catch ( TailnetUnavailableException ) { unavailableCandidates ++; }
}
checks [ "integration_all_internal_fail_without_early_public_start" ] = unavailableCandidates == 2
&& starts . SequenceEqual ( new []{ "100.64.0.2" , "100.64.0.3" }) && stops == beforeStops + 2 ;
selected = await NodeTransportConnector . ConnectAsync ( response , rankedPreference , Start , Stop , Healthy , Route , _ =>{},()=> tick + 1 , CancellationToken . None );
checks [ "integration_public_pass_only_after_all_internal_fail" ] = ! selected
&& starts . SequenceEqual ( new []{ "100.64.0.2" , "100.64.0.3" , "vpn002.example.invalid" });
2026-10-27 02:00:33 +00:00
starts . Clear ();
rebound = await NodeTransportConnector . RebindAsync ( prepared , original , Start , Stop , Healthy , CancellationToken . None ,
endpointProbe :( _ , _ , _ )=> Task . FromResult ( false ));
checks [ "handover_ping_failure_uses_domain_without_internal_start" ] = rebound == original
&& starts . SequenceEqual ( new []{ "vpn002.example.invalid" });
var privateResponse = Sample ( r => {
r [ "connection_scope" ] = "private_auxiliary" ; r [ "config_contract" ] = 3 ;
r [ "config_expires_at" ] = DateTimeOffset . UtcNow . AddMinutes ( 2 ). ToString ( "O" );
r [ "config" ]![ "outbounds" ]![ 0 ] = new JsonObject {
["tag"] = "proxy" ,[ "protocol" ]= "socks" ,[ "settings" ]= new JsonObject {
["servers"] = new JsonArray ( new JsonObject {[ "address" ]= "192.168.50.111" ,[ "port" ]= 18081 }) }
};
});
var privatePreference = new TailnetPreference ();
await NodeTransportConnector . ConnectAsync ( privateResponse , privatePreference ,( _ , _ )=> Task . CompletedTask ,
Stop , Healthy , Route , _ =>{},()=> tick , CancellationToken . None );
checks [ "private_ip_success_is_not_domain_fallback" ] = ! privatePreference . DomainOnly
&& privatePreference . MayTry ( "tokyo" , tick + 1 );
2026-10-11 23:23:20 +00:00
var report = new { passed = checks . Values . All ( x => x ), checks , simulated_transport = true ,
production_network_actions = Array . Empty < string >(), note = "Pure config/route models and fake start/stop/probe delegates; not a live Tailscale or release acceptance." };
File . WriteAllText ( Path . Combine ( AppContext . BaseDirectory , "tailnet-transport-self-test.json" ), JsonSerializer . Serialize ( report , new JsonSerializerOptions { WriteIndented = true }));
return report . passed ? 0 : 81 ;
}
private static bool Throws ( Action action ) { try { action (); return false ; } catch { return true ; } }
private static async Task < bool > ThrowsAsync ( Func < Task > action ) { try { await action (); return false ; } catch { return true ; } }
private sealed class HandoverFixture : IHandoverRuntime
{
public string? BoundNetworkFingerprint { get ; set ; }
public bool CanRebindNetwork => true ;
public bool IsRunning => true ;
internal string? NextFingerprint ;
internal string Current = "" ;
internal Func < Task < string >> Rebind = null !;
public Task SuspendForNetworkChangeAsync ( CancellationToken token ) => Task . CompletedTask ;
public async Task RebindNetworkAsync ( CancellationToken token )
{
token . ThrowIfCancellationRequested (); Current = await Rebind (); BoundNetworkFingerprint = NextFingerprint ;
}
}
}