From ddff240cc9904a30cb56bbbb88e62af8da68ebe8 Mon Sep 17 00:00:00 2001 From: Frando Date: Tue, 30 Jun 2026 13:05:06 +0000 Subject: [PATCH] deploy: d36155bf153fddb840170c786b91d4ab85290170 --- pr/4348/docs/iroh/endpoint/index.html | 2 +- pr/4348/docs/src/iroh/endpoint.rs.html | 2326 ++++++++++++------------ 2 files changed, 1166 insertions(+), 1162 deletions(-) diff --git a/pr/4348/docs/iroh/endpoint/index.html b/pr/4348/docs/iroh/endpoint/index.html index a990ad9eac..ed54697c6f 100644 --- a/pr/4348/docs/iroh/endpoint/index.html +++ b/pr/4348/docs/iroh/endpoint/index.html @@ -1,4 +1,4 @@ -iroh::endpoint - Rust

Module endpoint

Module endpoint 

Source
Expand description

The Endpoint allows establishing connections to other iroh endpoints.

+iroh::endpoint - Rust

Module endpoint

Module endpoint 

Source
Expand description

The Endpoint allows establishing connections to other iroh endpoints.

The Endpoint is the main API interface to manage a local iroh endpoint. It allows connecting to and accepting connections from other endpoints. See the module docs for more details on how iroh connections work.

diff --git a/pr/4348/docs/src/iroh/endpoint.rs.html b/pr/4348/docs/src/iroh/endpoint.rs.html index c917b278a0..ddd926ae99 100644 --- a/pr/4348/docs/src/iroh/endpoint.rs.html +++ b/pr/4348/docs/src/iroh/endpoint.rs.html @@ -2937,1179 +2937,1183 @@ 2937 /// https://github.com/n0-computer/net-tools/pull/166, so this no longer fails. 2938 #[tokio::test] 2939 async fn endpoint_unreachable_relay_direct_connect_succeeds() -> Result { -2940 // Nothing listens on the relay url (127.0.0.1:1), so the relay is unreachable. -2941 let dead_relay: RelayUrl = "https://127.0.0.1:1".parse().expect("valid relay url"); -2942 -2943 // The QADv4 probe must hit a closed UDP port so it draws the ICMP port-unreachable -2944 // that the Windows socket reports back on its next recv. Bind a socket to claim an -2945 // ephemeral port, read its address, then close it: the port is now free, so nothing -2946 // answers the probe. There's nothing stopping the kernel from re-using the port -2947 // right away, but on most machines that's unlikely. This beats hoping that a -2948 // hard-coded port happens to be unused. -2949 let closed_quic_port = { -2950 let sock = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind"); -2951 sock.local_addr().expect("local addr").port() -2952 }; -2953 let dead_relay_config = -2954 RelayConfig::new(dead_relay.clone(), Some(RelayQuicConfig::new(closed_quic_port))); -2955 -2956 let bind_endpoint = async || { -2957 Endpoint::builder(presets::Minimal) -2958 // Use the broken relay to trigger the ICMP errors from the QaD sends. -2959 .relay_mode(RelayMode::Custom(RelayMap::from_iter([ -2960 dead_relay_config.clone(), -2961 ]))) -2962 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2963 .alpns(vec![TEST_ALPN.to_vec()]) -2964 // Bind on IPv4 only to ensure a single socket to not have spurious polls. -2965 .bind_addr((Ipv4Addr::LOCALHOST, 0)) -2966 .expect("valid addr") -2967 .bind() -2968 .await -2969 }; -2970 -2971 let server = bind_endpoint().await?; -2972 let server_addr = server.addr().with_relay_url(dead_relay.clone()); -2973 let client = bind_endpoint().await?; +2940 // The relay url and its QADv4 probe must both hit closed ports, so the relay is +2941 // unreachable and the probe draws the ICMP port-unreachable the Windows socket +2942 // reports on its next recv. Claim an ephemeral port, then close it: it's now free, +2943 // so nothing answers. There's nothing stopping the kernel from re-using a port +2944 // right away, but on most machines that's unlikely. The url is dialed over TCP +2945 // (HTTPS), the probe over UDP, so claim each with the matching socket type. +2946 let closed_tcp_port = { +2947 let sock = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind"); +2948 sock.local_addr().expect("local addr").port() +2949 }; +2950 let closed_udp_port = { +2951 let sock = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind"); +2952 sock.local_addr().expect("local addr").port() +2953 }; +2954 let dead_relay: RelayUrl = format!("https://127.0.0.1:{closed_tcp_port}") +2955 .parse() +2956 .expect("valid relay url"); +2957 let dead_relay_config = +2958 RelayConfig::new(dead_relay.clone(), Some(RelayQuicConfig::new(closed_udp_port))); +2959 +2960 let bind_endpoint = async || { +2961 Endpoint::builder(presets::Minimal) +2962 // Use the broken relay to trigger the ICMP errors from the QaD sends. +2963 .relay_mode(RelayMode::Custom(RelayMap::from_iter([ +2964 dead_relay_config.clone(), +2965 ]))) +2966 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2967 .alpns(vec![TEST_ALPN.to_vec()]) +2968 // Bind on IPv4 only to ensure a single socket to not have spurious polls. +2969 .bind_addr((Ipv4Addr::LOCALHOST, 0)) +2970 .expect("valid addr") +2971 .bind() +2972 .await +2973 }; 2974 -2975 // Server accepts the incoming connection and holds it open until the test ends. -2976 let accept = tokio::spawn(async move { -2977 let incoming = server.accept().await.anyerr()?; -2978 let conn = incoming.await.anyerr()?; -2979 conn.closed().await; -2980 server.close().await; -2981 n0_error::Ok(()) -2982 }); -2983 -2984 // The connect must complete over the direct loopback path despite the dead relay. -2985 let _conn = tokio::time::timeout( -2986 Duration::from_secs(10), -2987 client.connect(server_addr, TEST_ALPN), -2988 ) -2989 .await -2990 .expect("connection should succeed")?; -2991 client.close().await; -2992 accept.await.anyerr()??; -2993 Ok(()) -2994 } -2995 -2996 #[tokio::test] -2997 #[traced_test] -2998 async fn test_direct_addresses_no_qad_relay() -> Result { -2999 let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap(); -3000 -3001 let ep = Endpoint::builder(presets::Minimal) -3002 .relay_mode(RelayMode::Custom(relay_map)) -3003 .alpns(vec![TEST_ALPN.to_vec()]) -3004 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3005 .bind() -3006 .await?; -3007 -3008 assert!(ep.addr().ip_addrs().count() > 0); -3009 -3010 Ok(()) -3011 } -3012 -3013 /// Test that configured external addresses are included in the endpoint's -3014 /// direct addresses, both when set via builder and at runtime. -3015 #[tokio::test(flavor = "current_thread", start_paused = true)] -3016 #[traced_test] -3017 async fn test_external_addr() -> Result { -3018 let configured_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 12345)); -3019 -3020 // Test builder-configured external address -3021 let ep = Endpoint::builder(presets::Minimal) -3022 .external_addr(configured_addr) -3023 .bind() -3024 .await?; -3025 -3026 let addr = ep.addr(); -3027 assert!( -3028 addr.ip_addrs().any(|a| *a == configured_addr), -3029 "builder-configured external addr {configured_addr} not found in endpoint addr: {addr:?}" -3030 ); -3031 -3032 // Test runtime add -3033 let runtime_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(5, 6, 7, 8), 54321)); -3034 ep.add_external_addr(runtime_addr).await; -3035 tokio::time::sleep(Duration::from_millis(100)).await; -3036 -3037 let addr = ep.addr(); -3038 assert!( -3039 addr.ip_addrs().any(|a| *a == runtime_addr), -3040 "runtime-added external addr {runtime_addr} not found in endpoint addr: {addr:?}" -3041 ); -3042 -3043 // Test runtime remove -3044 let removed = ep.remove_external_addr(&runtime_addr).await; -3045 assert!(removed); -3046 tokio::time::sleep(Duration::from_millis(100)).await; -3047 -3048 let addr = ep.addr(); -3049 assert!( -3050 !addr.ip_addrs().any(|a| *a == runtime_addr), -3051 "removed external addr {runtime_addr} still found in endpoint addr: {addr:?}" -3052 ); +2975 let server = bind_endpoint().await?; +2976 let server_addr = server.addr().with_relay_url(dead_relay.clone()); +2977 let client = bind_endpoint().await?; +2978 +2979 // Server accepts the incoming connection and holds it open until the test ends. +2980 let accept = tokio::spawn(async move { +2981 let incoming = server.accept().await.anyerr()?; +2982 let conn = incoming.await.anyerr()?; +2983 conn.closed().await; +2984 server.close().await; +2985 n0_error::Ok(()) +2986 }); +2987 +2988 // The connect must complete over the direct loopback path despite the dead relay. +2989 let _conn = tokio::time::timeout( +2990 Duration::from_secs(10), +2991 client.connect(server_addr, TEST_ALPN), +2992 ) +2993 .await +2994 .expect("connection should succeed")?; +2995 client.close().await; +2996 accept.await.anyerr()??; +2997 Ok(()) +2998 } +2999 +3000 #[tokio::test] +3001 #[traced_test] +3002 async fn test_direct_addresses_no_qad_relay() -> Result { +3003 let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap(); +3004 +3005 let ep = Endpoint::builder(presets::Minimal) +3006 .relay_mode(RelayMode::Custom(relay_map)) +3007 .alpns(vec![TEST_ALPN.to_vec()]) +3008 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3009 .bind() +3010 .await?; +3011 +3012 assert!(ep.addr().ip_addrs().count() > 0); +3013 +3014 Ok(()) +3015 } +3016 +3017 /// Test that configured external addresses are included in the endpoint's +3018 /// direct addresses, both when set via builder and at runtime. +3019 #[tokio::test(flavor = "current_thread", start_paused = true)] +3020 #[traced_test] +3021 async fn test_external_addr() -> Result { +3022 let configured_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 12345)); +3023 +3024 // Test builder-configured external address +3025 let ep = Endpoint::builder(presets::Minimal) +3026 .external_addr(configured_addr) +3027 .bind() +3028 .await?; +3029 +3030 let addr = ep.addr(); +3031 assert!( +3032 addr.ip_addrs().any(|a| *a == configured_addr), +3033 "builder-configured external addr {configured_addr} not found in endpoint addr: {addr:?}" +3034 ); +3035 +3036 // Test runtime add +3037 let runtime_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(5, 6, 7, 8), 54321)); +3038 ep.add_external_addr(runtime_addr).await; +3039 tokio::time::sleep(Duration::from_millis(100)).await; +3040 +3041 let addr = ep.addr(); +3042 assert!( +3043 addr.ip_addrs().any(|a| *a == runtime_addr), +3044 "runtime-added external addr {runtime_addr} not found in endpoint addr: {addr:?}" +3045 ); +3046 +3047 // Test runtime remove +3048 let removed = ep.remove_external_addr(&runtime_addr).await; +3049 assert!(removed); +3050 tokio::time::sleep(Duration::from_millis(100)).await; +3051 +3052 let addr = ep.addr(); 3053 assert!( -3054 addr.ip_addrs().any(|a| *a == configured_addr), -3055 "builder-configured external addr should still be present: {addr:?}" +3054 !addr.ip_addrs().any(|a| *a == runtime_addr), +3055 "removed external addr {runtime_addr} still found in endpoint addr: {addr:?}" 3056 ); -3057 -3058 ep.close().await; -3059 Ok(()) -3060 } +3057 assert!( +3058 addr.ip_addrs().any(|a| *a == configured_addr), +3059 "builder-configured external addr should still be present: {addr:?}" +3060 ); 3061 -3062 #[tokio::test] -3063 #[traced_test] -3064 async fn graceful_close() -> Result { -3065 let client = Endpoint::bind(presets::Minimal).await?; -3066 let server = Endpoint::builder(presets::Minimal) -3067 .alpns(vec![TEST_ALPN.to_vec()]) -3068 .bind() -3069 .await?; -3070 let server_addr = server.addr(); -3071 let server_task = tokio::spawn(async move { -3072 let incoming = server.accept().await.anyerr()?; -3073 let conn = incoming.await.anyerr()?; -3074 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -3075 let msg = recv.read_to_end(1_000).await.anyerr()?; -3076 send.write_all(&msg).await.anyerr()?; -3077 send.finish().anyerr()?; -3078 let close_reason = conn.closed().await; -3079 Ok::<_, Error>(close_reason) -3080 }); -3081 -3082 let conn = client.connect(server_addr, TEST_ALPN).await?; -3083 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -3084 send.write_all(b"Hello, world!").await.anyerr()?; -3085 send.finish().anyerr()?; -3086 recv.read_to_end(1_000).await.anyerr()?; -3087 conn.close(42u32.into(), b"thanks, bye!"); -3088 client.close().await; -3089 -3090 let close_err = server_task.await.anyerr()??; -3091 let ConnectionError::ApplicationClosed(app_close) = close_err else { -3092 panic!("Unexpected close reason: {close_err:?}"); -3093 }; -3094 -3095 assert_eq!(app_close.error_code, 42u32.into()); -3096 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); -3097 -3098 Ok(()) -3099 } -3100 -3101 #[cfg(feature = "metrics")] -3102 #[tokio::test] -3103 #[traced_test] -3104 async fn metrics_smoke() -> Result { -3105 use iroh_metrics::Registry; -3106 -3107 let secret_key = SecretKey::from_bytes(&[0u8; 32]); -3108 let client = Endpoint::builder(presets::Minimal) -3109 .secret_key(secret_key) -3110 .bind() -3111 .await?; -3112 let secret_key = SecretKey::from_bytes(&[1u8; 32]); -3113 let server = Endpoint::builder(presets::Minimal) -3114 .secret_key(secret_key) -3115 .alpns(vec![TEST_ALPN.to_vec()]) -3116 .bind() -3117 .await?; -3118 let server_addr = server.addr(); -3119 let server_task = tokio::task::spawn(async move { -3120 let conn = server.accept().await.anyerr()?.await.anyerr()?; -3121 let mut uni = conn.accept_uni().await.anyerr()?; -3122 uni.read_to_end(10).await.anyerr()?; -3123 drop(conn); -3124 Ok::<_, Error>(server) -3125 }); -3126 let conn = client.connect(server_addr, TEST_ALPN).await?; -3127 let mut uni = conn.open_uni().await.anyerr()?; -3128 uni.write_all(b"helloworld").await.anyerr()?; -3129 uni.finish().anyerr()?; -3130 conn.closed().await; -3131 drop(conn); -3132 let server = server_task.await.anyerr()??; -3133 -3134 let m = client.metrics(); -3135 // assert_eq!(m.socket.num_direct_conns_added.get(), 1); -3136 // assert_eq!(m.socket.connection_became_direct.get(), 1); -3137 // assert_eq!(m.socket.connection_handshake_success.get(), 1); -3138 // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1); -3139 assert!(m.socket.recv_datagrams.get() > 0); -3140 -3141 let m = server.metrics(); -3142 // assert_eq!(m.socket.num_direct_conns_added.get(), 1); -3143 // assert_eq!(m.socket.connection_became_direct.get(), 1); -3144 // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1); -3145 // assert_eq!(m.socket.connection_handshake_success.get(), 1); -3146 assert!(m.socket.recv_datagrams.get() > 0); -3147 -3148 // test openmetrics encoding with labeled subregistries per endpoint -3149 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { -3150 let id = endpoint.id().fmt_short(); -3151 let sub_registry = registry.sub_registry_with_label("id", id.to_string()); -3152 sub_registry.register_all(endpoint.metrics()); -3153 } -3154 let mut registry = Registry::default(); -3155 register_endpoint(&mut registry, &client); -3156 register_endpoint(&mut registry, &server); -3157 // let s = registry.encode_openmetrics_to_string().anyerr()?; -3158 // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#)); -3159 // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#)); -3160 Ok(()) -3161 } -3162 -3163 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` -3164 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. -3165 async fn alpn_connection_test( -3166 accept_alpns: Vec<Vec<u8>>, -3167 primary_connect_alpn: &[u8], -3168 secondary_connect_alpns: Vec<Vec<u8>>, -3169 ) -> Result<Vec<u8>> { -3170 let client = Endpoint::bind(presets::Minimal).await?; -3171 let server = Endpoint::builder(presets::Minimal) -3172 .alpns(accept_alpns) -3173 .bind() -3174 .await?; -3175 let server_addr = server.addr(); -3176 let server_task = tokio::spawn({ -3177 let server = server.clone(); -3178 async move { -3179 let incoming = server.accept().await.anyerr()?; -3180 let conn = incoming.await.anyerr()?; -3181 conn.close(0u32.into(), b"bye!"); -3182 n0_error::Ok(conn.alpn().to_vec()) -3183 } -3184 }); -3185 -3186 let conn = client -3187 .connect_with_opts( -3188 server_addr, -3189 primary_connect_alpn, -3190 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), -3191 ) -3192 .await?; -3193 let conn = conn.await.anyerr()?; -3194 let client_alpn = conn.alpn(); -3195 conn.closed().await; -3196 client.close().await; -3197 server.close().await; -3198 -3199 let server_alpn = server_task.await.anyerr()??; -3200 -3201 assert_eq!(client_alpn, server_alpn); +3062 ep.close().await; +3063 Ok(()) +3064 } +3065 +3066 #[tokio::test] +3067 #[traced_test] +3068 async fn graceful_close() -> Result { +3069 let client = Endpoint::bind(presets::Minimal).await?; +3070 let server = Endpoint::builder(presets::Minimal) +3071 .alpns(vec![TEST_ALPN.to_vec()]) +3072 .bind() +3073 .await?; +3074 let server_addr = server.addr(); +3075 let server_task = tokio::spawn(async move { +3076 let incoming = server.accept().await.anyerr()?; +3077 let conn = incoming.await.anyerr()?; +3078 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +3079 let msg = recv.read_to_end(1_000).await.anyerr()?; +3080 send.write_all(&msg).await.anyerr()?; +3081 send.finish().anyerr()?; +3082 let close_reason = conn.closed().await; +3083 Ok::<_, Error>(close_reason) +3084 }); +3085 +3086 let conn = client.connect(server_addr, TEST_ALPN).await?; +3087 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +3088 send.write_all(b"Hello, world!").await.anyerr()?; +3089 send.finish().anyerr()?; +3090 recv.read_to_end(1_000).await.anyerr()?; +3091 conn.close(42u32.into(), b"thanks, bye!"); +3092 client.close().await; +3093 +3094 let close_err = server_task.await.anyerr()??; +3095 let ConnectionError::ApplicationClosed(app_close) = close_err else { +3096 panic!("Unexpected close reason: {close_err:?}"); +3097 }; +3098 +3099 assert_eq!(app_close.error_code, 42u32.into()); +3100 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); +3101 +3102 Ok(()) +3103 } +3104 +3105 #[cfg(feature = "metrics")] +3106 #[tokio::test] +3107 #[traced_test] +3108 async fn metrics_smoke() -> Result { +3109 use iroh_metrics::Registry; +3110 +3111 let secret_key = SecretKey::from_bytes(&[0u8; 32]); +3112 let client = Endpoint::builder(presets::Minimal) +3113 .secret_key(secret_key) +3114 .bind() +3115 .await?; +3116 let secret_key = SecretKey::from_bytes(&[1u8; 32]); +3117 let server = Endpoint::builder(presets::Minimal) +3118 .secret_key(secret_key) +3119 .alpns(vec![TEST_ALPN.to_vec()]) +3120 .bind() +3121 .await?; +3122 let server_addr = server.addr(); +3123 let server_task = tokio::task::spawn(async move { +3124 let conn = server.accept().await.anyerr()?.await.anyerr()?; +3125 let mut uni = conn.accept_uni().await.anyerr()?; +3126 uni.read_to_end(10).await.anyerr()?; +3127 drop(conn); +3128 Ok::<_, Error>(server) +3129 }); +3130 let conn = client.connect(server_addr, TEST_ALPN).await?; +3131 let mut uni = conn.open_uni().await.anyerr()?; +3132 uni.write_all(b"helloworld").await.anyerr()?; +3133 uni.finish().anyerr()?; +3134 conn.closed().await; +3135 drop(conn); +3136 let server = server_task.await.anyerr()??; +3137 +3138 let m = client.metrics(); +3139 // assert_eq!(m.socket.num_direct_conns_added.get(), 1); +3140 // assert_eq!(m.socket.connection_became_direct.get(), 1); +3141 // assert_eq!(m.socket.connection_handshake_success.get(), 1); +3142 // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1); +3143 assert!(m.socket.recv_datagrams.get() > 0); +3144 +3145 let m = server.metrics(); +3146 // assert_eq!(m.socket.num_direct_conns_added.get(), 1); +3147 // assert_eq!(m.socket.connection_became_direct.get(), 1); +3148 // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1); +3149 // assert_eq!(m.socket.connection_handshake_success.get(), 1); +3150 assert!(m.socket.recv_datagrams.get() > 0); +3151 +3152 // test openmetrics encoding with labeled subregistries per endpoint +3153 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { +3154 let id = endpoint.id().fmt_short(); +3155 let sub_registry = registry.sub_registry_with_label("id", id.to_string()); +3156 sub_registry.register_all(endpoint.metrics()); +3157 } +3158 let mut registry = Registry::default(); +3159 register_endpoint(&mut registry, &client); +3160 register_endpoint(&mut registry, &server); +3161 // let s = registry.encode_openmetrics_to_string().anyerr()?; +3162 // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#)); +3163 // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#)); +3164 Ok(()) +3165 } +3166 +3167 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` +3168 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. +3169 async fn alpn_connection_test( +3170 accept_alpns: Vec<Vec<u8>>, +3171 primary_connect_alpn: &[u8], +3172 secondary_connect_alpns: Vec<Vec<u8>>, +3173 ) -> Result<Vec<u8>> { +3174 let client = Endpoint::bind(presets::Minimal).await?; +3175 let server = Endpoint::builder(presets::Minimal) +3176 .alpns(accept_alpns) +3177 .bind() +3178 .await?; +3179 let server_addr = server.addr(); +3180 let server_task = tokio::spawn({ +3181 let server = server.clone(); +3182 async move { +3183 let incoming = server.accept().await.anyerr()?; +3184 let conn = incoming.await.anyerr()?; +3185 conn.close(0u32.into(), b"bye!"); +3186 n0_error::Ok(conn.alpn().to_vec()) +3187 } +3188 }); +3189 +3190 let conn = client +3191 .connect_with_opts( +3192 server_addr, +3193 primary_connect_alpn, +3194 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), +3195 ) +3196 .await?; +3197 let conn = conn.await.anyerr()?; +3198 let client_alpn = conn.alpn(); +3199 conn.closed().await; +3200 client.close().await; +3201 server.close().await; 3202 -3203 Ok(server_alpn.to_vec()) -3204 } -3205 -3206 #[tokio::test] -3207 #[traced_test] -3208 async fn connect_multiple_alpn_negotiated() -> Result { -3209 const ALPN_ONE: &[u8] = b"alpn/1"; -3210 const ALPN_TWO: &[u8] = b"alpn/2"; -3211 -3212 assert_eq!( -3213 alpn_connection_test( -3214 // Prefer version 2 over version 1 on the accept side -3215 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], -3216 ALPN_TWO, -3217 vec![ALPN_ONE.to_vec()], -3218 ) -3219 .await?, -3220 ALPN_TWO.to_vec(), -3221 "accept side prefers version 2 over 1" -3222 ); -3223 -3224 assert_eq!( -3225 alpn_connection_test( -3226 // Only support the old version -3227 vec![ALPN_ONE.to_vec()], -3228 ALPN_TWO, -3229 vec![ALPN_ONE.to_vec()], -3230 ) -3231 .await?, -3232 ALPN_ONE.to_vec(), -3233 "accept side only supports the old version" -3234 ); -3235 -3236 assert_eq!( -3237 alpn_connection_test( -3238 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], -3239 ALPN_ONE, -3240 vec![ALPN_TWO.to_vec()], -3241 ) -3242 .await?, -3243 ALPN_TWO.to_vec(), -3244 "connect side ALPN order doesn't matter" -3245 ); -3246 -3247 assert_eq!( -3248 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) -3249 .await?, -3250 ALPN_ONE.to_vec(), -3251 "connect side only supports the old version" -3252 ); -3253 -3254 Ok(()) -3255 } -3256 -3257 #[tokio::test] -3258 #[traced_test] -3259 #[cfg(feature = "unstable-net-report")] -3260 async fn watch_net_report() -> Result { -3261 let endpoint = Endpoint::builder(presets::Minimal) -3262 .relay_mode(RelayMode::Staging) -3263 .bind() -3264 .await?; -3265 -3266 // can get a first report -3267 endpoint.net_report().updated().await.anyerr()?; -3268 -3269 Ok(()) -3270 } -3271 -3272 /// Tests that initial connection establishment isn't extremely slow compared -3273 /// to subsequent connections. -3274 /// -3275 /// This is a time based test, but uses a very large ratio to reduce flakiness. -3276 /// It also does a number of connections to average out any anomalies. -3277 #[tokio::test] -3278 #[traced_test] -3279 async fn connect_multi_time() -> Result { -3280 let n = 32; -3281 -3282 const NOOP_ALPN: &[u8] = b"noop"; -3283 -3284 #[derive(Debug, Clone)] -3285 struct Noop; -3286 -3287 impl ProtocolHandler for Noop { -3288 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { -3289 connection.closed().await; -3290 Ok(()) -3291 } -3292 } -3293 -3294 async fn noop_server() -> Result<(Router, EndpointAddr)> { -3295 let endpoint = Endpoint::bind(presets::Minimal).await.anyerr()?; -3296 let addr = endpoint.addr(); -3297 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn(); -3298 Ok((router, addr)) -3299 } -3300 -3301 let routers = stream::iter(0..n) -3302 .map(|_| noop_server()) -3303 .buffered_unordered(32) -3304 .collect::<Vec<_>>() -3305 .await -3306 .into_iter() -3307 .collect::<Result<Vec<_>, _>>() -3308 .anyerr()?; -3309 -3310 let addrs = routers -3311 .iter() -3312 .map(|(_, addr)| addr.clone()) -3313 .collect::<Vec<_>>(); -3314 let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>(); -3315 let address_lookup = MemoryLookup::from_endpoint_info(addrs); -3316 let endpoint = Endpoint::builder(presets::Minimal) -3317 .address_lookup(address_lookup) -3318 .bind() -3319 .await -3320 .anyerr()?; -3321 // wait for the endpoint to be initialized. This should not be needed, -3322 // but we don't want to measure endpoint init time but connection time -3323 // from a fully initialized endpoint. -3324 endpoint.addr(); -3325 let t0 = Instant::now(); -3326 for id in &ids { -3327 let conn = endpoint.connect(*id, NOOP_ALPN).await?; -3328 conn.close(0u32.into(), b"done"); -3329 } -3330 let dt0 = t0.elapsed().as_secs_f64(); -3331 let t1 = Instant::now(); -3332 for id in &ids { -3333 let conn = endpoint.connect(*id, NOOP_ALPN).await?; -3334 conn.close(0u32.into(), b"done"); -3335 } -3336 let dt1 = t1.elapsed().as_secs_f64(); -3337 -3338 assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s"); -3339 Ok(()) -3340 } +3203 let server_alpn = server_task.await.anyerr()??; +3204 +3205 assert_eq!(client_alpn, server_alpn); +3206 +3207 Ok(server_alpn.to_vec()) +3208 } +3209 +3210 #[tokio::test] +3211 #[traced_test] +3212 async fn connect_multiple_alpn_negotiated() -> Result { +3213 const ALPN_ONE: &[u8] = b"alpn/1"; +3214 const ALPN_TWO: &[u8] = b"alpn/2"; +3215 +3216 assert_eq!( +3217 alpn_connection_test( +3218 // Prefer version 2 over version 1 on the accept side +3219 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +3220 ALPN_TWO, +3221 vec![ALPN_ONE.to_vec()], +3222 ) +3223 .await?, +3224 ALPN_TWO.to_vec(), +3225 "accept side prefers version 2 over 1" +3226 ); +3227 +3228 assert_eq!( +3229 alpn_connection_test( +3230 // Only support the old version +3231 vec![ALPN_ONE.to_vec()], +3232 ALPN_TWO, +3233 vec![ALPN_ONE.to_vec()], +3234 ) +3235 .await?, +3236 ALPN_ONE.to_vec(), +3237 "accept side only supports the old version" +3238 ); +3239 +3240 assert_eq!( +3241 alpn_connection_test( +3242 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +3243 ALPN_ONE, +3244 vec![ALPN_TWO.to_vec()], +3245 ) +3246 .await?, +3247 ALPN_TWO.to_vec(), +3248 "connect side ALPN order doesn't matter" +3249 ); +3250 +3251 assert_eq!( +3252 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) +3253 .await?, +3254 ALPN_ONE.to_vec(), +3255 "connect side only supports the old version" +3256 ); +3257 +3258 Ok(()) +3259 } +3260 +3261 #[tokio::test] +3262 #[traced_test] +3263 #[cfg(feature = "unstable-net-report")] +3264 async fn watch_net_report() -> Result { +3265 let endpoint = Endpoint::builder(presets::Minimal) +3266 .relay_mode(RelayMode::Staging) +3267 .bind() +3268 .await?; +3269 +3270 // can get a first report +3271 endpoint.net_report().updated().await.anyerr()?; +3272 +3273 Ok(()) +3274 } +3275 +3276 /// Tests that initial connection establishment isn't extremely slow compared +3277 /// to subsequent connections. +3278 /// +3279 /// This is a time based test, but uses a very large ratio to reduce flakiness. +3280 /// It also does a number of connections to average out any anomalies. +3281 #[tokio::test] +3282 #[traced_test] +3283 async fn connect_multi_time() -> Result { +3284 let n = 32; +3285 +3286 const NOOP_ALPN: &[u8] = b"noop"; +3287 +3288 #[derive(Debug, Clone)] +3289 struct Noop; +3290 +3291 impl ProtocolHandler for Noop { +3292 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { +3293 connection.closed().await; +3294 Ok(()) +3295 } +3296 } +3297 +3298 async fn noop_server() -> Result<(Router, EndpointAddr)> { +3299 let endpoint = Endpoint::bind(presets::Minimal).await.anyerr()?; +3300 let addr = endpoint.addr(); +3301 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn(); +3302 Ok((router, addr)) +3303 } +3304 +3305 let routers = stream::iter(0..n) +3306 .map(|_| noop_server()) +3307 .buffered_unordered(32) +3308 .collect::<Vec<_>>() +3309 .await +3310 .into_iter() +3311 .collect::<Result<Vec<_>, _>>() +3312 .anyerr()?; +3313 +3314 let addrs = routers +3315 .iter() +3316 .map(|(_, addr)| addr.clone()) +3317 .collect::<Vec<_>>(); +3318 let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>(); +3319 let address_lookup = MemoryLookup::from_endpoint_info(addrs); +3320 let endpoint = Endpoint::builder(presets::Minimal) +3321 .address_lookup(address_lookup) +3322 .bind() +3323 .await +3324 .anyerr()?; +3325 // wait for the endpoint to be initialized. This should not be needed, +3326 // but we don't want to measure endpoint init time but connection time +3327 // from a fully initialized endpoint. +3328 endpoint.addr(); +3329 let t0 = Instant::now(); +3330 for id in &ids { +3331 let conn = endpoint.connect(*id, NOOP_ALPN).await?; +3332 conn.close(0u32.into(), b"done"); +3333 } +3334 let dt0 = t0.elapsed().as_secs_f64(); +3335 let t1 = Instant::now(); +3336 for id in &ids { +3337 let conn = endpoint.connect(*id, NOOP_ALPN).await?; +3338 conn.close(0u32.into(), b"done"); +3339 } +3340 let dt1 = t1.elapsed().as_secs_f64(); 3341 -3342 #[tokio::test] -3343 async fn test_custom_relay() -> Result { -3344 let _ep = Endpoint::builder(presets::Minimal) -3345 .relay_mode(RelayMode::custom([RelayUrl::from_str( -3346 "https://use1-1.relay.n0.iroh.link.", -3347 )?])) -3348 .bind() -3349 .await?; -3350 -3351 let relays = RelayMap::try_from_iter([ -3352 "https://use1-1.relay.n0.iroh.link/", -3353 "https://euc1-1.relay.n0.iroh.link/", -3354 ])?; -3355 let _ep = Endpoint::builder(presets::Minimal) -3356 .relay_mode(RelayMode::Custom(relays)) -3357 .bind() -3358 .await?; -3359 -3360 Ok(()) -3361 } -3362 -3363 /// Testing bind_addr: Clear IP transports and add single IPv4 bind -3364 #[tokio::test] -3365 #[traced_test] -3366 async fn test_bind_addr_clear() -> Result { -3367 let ep = Endpoint::builder(presets::Minimal) -3368 .clear_ip_transports() -3369 .bind_addr((Ipv4Addr::LOCALHOST, 0))? -3370 .bind() -3371 .await?; -3372 let bound_sockets = ep.bound_sockets(); -3373 assert_eq!(bound_sockets.len(), 1); -3374 assert_eq!(bound_sockets[0].ip(), IpAddr::V4(Ipv4Addr::LOCALHOST)); -3375 ep.close().await; -3376 Ok(()) -3377 } -3378 -3379 /// Testing bind_addr: Do not clear IP transports and add single non-default IPv4 bind -3380 /// -3381 /// This will bind two sockets: default wildcard bind for IPv6, and our -3382 /// manually-added IPv4 bind. -3383 #[tokio::test] -3384 #[traced_test] -3385 async fn test_bind_addr_no_clear() -> Result { -3386 let ep = Endpoint::builder(presets::Minimal) -3387 .bind_addr((Ipv4Addr::LOCALHOST, 0))? -3388 .bind() -3389 .await?; -3390 let bound_sockets = ep.bound_sockets(); -3391 assert_eq!(bound_sockets.len(), 2); -3392 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); -3393 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); -3394 // Test that our manually added socket is there -3395 assert!( -3396 bound_sockets -3397 .iter() -3398 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -3399 ); -3400 ep.close().await; -3401 Ok(()) -3402 } -3403 -3404 // Testing bind_addr: Do not clear IP transports and add single default IPv4 bind. -3405 // -3406 // This replaces the default IPv4 bind added by the builder, -3407 // but keeps the default wildcard IPv6 bind. -3408 #[tokio::test] -3409 #[traced_test] -3410 async fn test_bind_addr_default() -> Result { -3411 let ep = Endpoint::builder(presets::Minimal) -3412 .bind_addr_with_opts( -3413 (Ipv4Addr::LOCALHOST, 0), -3414 BindOpts::default().set_is_default_route(true), -3415 )? -3416 .bind() -3417 .await?; -3418 let bound_sockets = ep.bound_sockets(); -3419 assert_eq!(bound_sockets.len(), 2); -3420 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); -3421 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); -3422 assert!( -3423 bound_sockets -3424 .iter() -3425 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -3426 ); -3427 ep.close().await; -3428 drop(ep); -3429 -3430 Ok(()) -3431 } -3432 -3433 /// Testing bind_addr: Do not clear IP transports and add single IPv4 bind with a non-zero prefix len -3434 /// -3435 /// This will bind three sockets: default wildcard bind for IPv4 and IPv6, and our -3436 /// manually-added IPv4 bind. -3437 #[tokio::test] -3438 #[traced_test] -3439 async fn test_bind_addr_nonzero_prefix() -> Result { -3440 let ep = Endpoint::builder(presets::Minimal) -3441 .bind_addr_with_opts( -3442 (Ipv4Addr::LOCALHOST, 0), -3443 BindOpts::default().set_prefix_len(32), -3444 )? -3445 .bind() -3446 .await?; -3447 let bound_sockets = ep.bound_sockets(); -3448 assert_eq!(bound_sockets.len(), 3); -3449 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 2); -3450 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); -3451 // Test that the default wildcard socket is there -3452 assert!( -3453 bound_sockets -3454 .iter() -3455 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) -3456 ); -3457 // Test that our manually added socket is there -3458 assert!( -3459 bound_sockets -3460 .iter() -3461 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -3462 ); -3463 ep.close().await; -3464 Ok(()) -3465 } -3466 -3467 /// Bind on an unusable port with the default opts. -3468 /// -3469 /// Binding the endpoint fails with an AddrInUse error. -3470 #[tokio::test] -3471 #[traced_test] -3472 async fn test_bind_addr_badport() -> Result { -3473 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -3474 let port = socket.local_addr()?.port(); -3475 -3476 let res = Endpoint::builder(presets::Minimal) -3477 .clear_ip_transports() -3478 .bind_addr((Ipv4Addr::LOCALHOST, port))? -3479 .bind() -3480 .await; -3481 -3482 assert!(matches!( -3483 res, -3484 Err(BindError::Sockets { -3485 source: io_error, -3486 .. -3487 }) -3488 if io_error.kind() == io::ErrorKind::AddrInUse -3489 )); -3490 Ok(()) -3491 } -3492 -3493 /// Bind a non-default route on an unusable port, but set is_required = false. -3494 /// -3495 /// Binding the endpoint succeeds. -3496 #[tokio::test] -3497 #[traced_test] -3498 async fn test_bind_addr_badport_notrequired() -> Result { -3499 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -3500 let port = socket.local_addr()?.port(); -3501 -3502 let ep = Endpoint::builder(presets::Minimal) -3503 .bind_addr_with_opts( -3504 (Ipv4Addr::LOCALHOST, port), -3505 BindOpts::default() -3506 .set_prefix_len(32) -3507 .set_is_required(false), -3508 )? -3509 .bind() -3510 .await?; -3511 let bound_sockets = ep.bound_sockets(); -3512 // just the default wildcard binds -3513 assert_eq!(bound_sockets.len(), 2); -3514 // our requested bind addr is not included because it failed to bind -3515 assert!( -3516 !bound_sockets -3517 .iter() -3518 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -3519 ); -3520 Ok(()) -3521 } -3522 -3523 /// Bind on a default route on an unusable port, but set is_required = false. -3524 /// -3525 /// Binding the endpoint succeeds. -3526 #[tokio::test] -3527 #[traced_test] -3528 async fn test_bind_addr_badport_default_notrequired() -> Result { -3529 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -3530 let port = socket.local_addr()?.port(); -3531 -3532 let ep = Endpoint::builder(presets::Minimal) -3533 .bind_addr_with_opts( -3534 (Ipv4Addr::LOCALHOST, port), -3535 BindOpts::default().set_is_required(false), -3536 )? -3537 .bind() -3538 .await?; -3539 let bound_sockets = ep.bound_sockets(); -3540 // just the IPv6 default, but no IPv4 bind at all because we replaced the default -3541 // with a bind with an unusable port and set it to not be required. -3542 assert_eq!(bound_sockets.len(), 1); -3543 assert!(bound_sockets[0].is_ipv6()); -3544 Ok(()) -3545 } -3546 -3547 /// Bind on an unusable port, with is_required = false, and no other transports. -3548 /// -3549 /// Binding the endpoint fails with "no valid address available". -3550 #[tokio::test] -3551 #[traced_test] -3552 async fn test_bind_addr_badport_notrequired_no_other_transports() -> Result { -3553 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -3554 let port = socket.local_addr()?.port(); -3555 -3556 let res = Endpoint::builder(presets::Minimal) -3557 .clear_ip_transports() -3558 .bind_addr_with_opts( -3559 (Ipv4Addr::LOCALHOST, port), -3560 BindOpts::default().set_is_required(false), -3561 )? -3562 .bind() -3563 .await; -3564 -3565 assert!(matches!( -3566 res, -3567 Err(BindError::CreateQuicEndpoint { -3568 source: io_error, -3569 .. -3570 }) -3571 if io_error.kind() == io::ErrorKind::Other && io_error.to_string() == "no valid address available" -3572 )); -3573 Ok(()) -3574 } -3575 -3576 /// Bind with prefix len 0 but set the route as non-default. -3577 #[tokio::test] -3578 #[traced_test] -3579 async fn test_bind_addr_prefix_len_0_not_default() -> Result { -3580 let ep = Endpoint::builder(presets::Minimal) -3581 .bind_addr_with_opts( -3582 (Ipv4Addr::LOCALHOST, 0), -3583 BindOpts::default().set_is_default_route(false), -3584 )? -3585 .bind() -3586 .await?; -3587 let bound_sockets = ep.bound_sockets(); -3588 // The two default wildcard binds plus our additional route (which does not replace the default route -3589 // because we set is_default_route to false explicitly). -3590 assert_eq!(bound_sockets.len(), 3); -3591 assert!( -3592 bound_sockets -3593 .iter() -3594 .any(|x| x.ip() == IpAddr::V6(Ipv6Addr::UNSPECIFIED)) -3595 ); -3596 assert!( -3597 bound_sockets -3598 .iter() -3599 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) -3600 ); -3601 assert!( -3602 bound_sockets -3603 .iter() -3604 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -3605 ); -3606 Ok(()) -3607 } -3608 -3609 #[ignore = "flaky"] -3610 #[tokio::test] -3611 #[traced_test] -3612 async fn connect_via_relay_becomes_direct_and_sends_direct() -> Result { -3613 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; -3614 let qlog = Arc::new(QlogFileGroup::from_env( -3615 "connect_via_relay_becomes_direct_and_sends_direct", -3616 )); -3617 let transfer_size = 1_000_000; -3618 -3619 async fn collect_stats(mut events: PathEventStream) -> BTreeMap<TransportAddr, PathStats> { -3620 let mut stats = BTreeMap::new(); -3621 while let Some(event) = events.next().await { -3622 if let PathEvent::Closed { -3623 remote_addr, -3624 last_stats, -3625 .. -3626 } = event -3627 { -3628 stats.insert(remote_addr, *last_stats); -3629 } -3630 } -3631 stats -3632 } -3633 -3634 let client = Endpoint::builder(presets::Minimal) -3635 .relay_mode(RelayMode::Custom(relay_map.clone())) -3636 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3637 .transport_config(qlog.create("client")?) -3638 .bind() -3639 .await?; -3640 let server = Endpoint::builder(presets::Minimal) -3641 .relay_mode(RelayMode::Custom(relay_map)) -3642 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3643 .transport_config(qlog.create("server")?) -3644 .alpns(vec![TEST_ALPN.to_vec()]) -3645 .bind() -3646 .await?; -3647 let server_addr = EndpointAddr::new(server.id()).with_relay_url(relay_url); -3648 let server_task = tokio::spawn(async move { -3649 let incoming = server.accept().await.anyerr()?; -3650 let conn = incoming.await.anyerr()?; -3651 let stats_task = tokio::spawn(collect_stats(conn.path_events())); -3652 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -3653 let msg = recv.read_to_end(transfer_size).await.anyerr()?; -3654 send.write_all(&msg).await.anyerr()?; -3655 send.finish().anyerr()?; -3656 conn.closed().await; -3657 let stats = stats_task.await.expect("stats task panicked"); -3658 Ok::<_, Error>(stats) -3659 }); -3660 -3661 let conn = client.connect(server_addr, TEST_ALPN).await?; -3662 let client_stats_task = tokio::spawn(collect_stats(conn.path_events())); -3663 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -3664 send.write_all(&vec![42u8; transfer_size]).await.anyerr()?; -3665 send.finish().anyerr()?; -3666 recv.read_to_end(transfer_size).await.anyerr()?; -3667 conn.close(0u32.into(), b"thanks, bye!"); -3668 client.close().await; -3669 let client_stats = client_stats_task.await.expect("stats task panicked"); -3670 let server_stats = server_task.await.anyerr()??; -3671 -3672 info!("client stats: {client_stats:#?}"); -3673 info!("server stats: {server_stats:#?}"); -3674 -3675 let client_total_relay_tx = client_stats -3676 .iter() -3677 .filter(|(remote, _stats)| remote.is_relay()) -3678 .map(|(_, stats)| stats.udp_tx.bytes) -3679 .sum::<u64>(); -3680 let client_total_relay_rx = client_stats -3681 .iter() -3682 .filter(|(remote, _stats)| remote.is_relay()) -3683 .map(|(_, stats)| stats.udp_rx.bytes) -3684 .sum::<u64>(); -3685 let server_total_relay_tx = server_stats -3686 .iter() -3687 .filter(|(remote, _stats)| remote.is_relay()) -3688 .map(|(_, stats)| stats.udp_tx.bytes) -3689 .sum::<u64>(); -3690 let server_total_relay_rx = server_stats -3691 .iter() -3692 .filter(|(remote, _stats)| remote.is_relay()) -3693 .map(|(_, stats)| stats.udp_rx.bytes) -3694 .sum::<u64>(); -3695 -3696 info!(?client_total_relay_tx, "total"); -3697 info!(?client_total_relay_rx, "total"); -3698 info!(?server_total_relay_tx, "total"); -3699 info!(?server_total_relay_rx, "total"); -3700 -3701 // We should send/receive only the minorty of traffic via the relay. -3702 assert!(client_total_relay_tx < transfer_size as u64 / 2); -3703 assert!(client_total_relay_rx < transfer_size as u64 / 2); -3704 assert!(server_total_relay_tx < transfer_size as u64 / 2); -3705 assert!(server_total_relay_rx < transfer_size as u64 / 2); -3706 -3707 Ok(()) -3708 } -3709 -3710 /// Tests that correct logs are emitted when connecting two endpoints with same secret keys to a relay. -3711 #[tokio::test] -3712 #[traced_test] -3713 async fn same_endpoint_id_relay() -> Result { -3714 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; -3715 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); -3716 let secret_key = SecretKey::from_bytes(&rng.random()); -3717 -3718 let client = Endpoint::builder(presets::Minimal) -3719 .relay_mode(RelayMode::Custom(relay_map.clone())) -3720 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3721 .bind() -3722 .instrument(error_span!("ep-client")) -3723 .await?; -3724 -3725 info!("client {}", client.id()); -3726 -3727 // bind ep1 and wait until connected to relay. -3728 let ep1 = Endpoint::builder(presets::Minimal) -3729 .relay_mode(RelayMode::Custom(relay_map.clone())) -3730 .secret_key(secret_key.clone()) -3731 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3732 .alpns(vec![TEST_ALPN.to_vec()]) -3733 .bind() -3734 .instrument(error_span!("ep1")) -3735 .await?; -3736 info!("ep1 bound {:?}", ep1.id()); -3737 ep1.online().await; -3738 info!("ep1 online"); -3739 -3740 let addr = EndpointAddr::new(secret_key.public()).with_relay_url(relay_url.clone()); -3741 -3742 tokio::try_join!( -3743 async { -3744 let conn = client.connect(addr.clone(), TEST_ALPN).await?; -3745 let reason = conn.closed().await; -3746 assert!(is_application_closed(&reason, 1)); -3747 n0_error::Ok(()) -3748 }, -3749 async { -3750 let conn = ep1.accept().await.unwrap().await?; -3751 conn.close(1u32.into(), b"bye"); -3752 n0_error::Ok(()) -3753 } -3754 )?; -3755 info!("client connected to ep1"); -3756 -3757 // now start second endpoint with same secret key -3758 let ep2 = Endpoint::builder(presets::Minimal) -3759 .relay_mode(RelayMode::Custom(relay_map)) -3760 .secret_key(secret_key.clone()) -3761 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3762 .alpns(vec![TEST_ALPN.to_vec()]) -3763 .bind() -3764 .instrument(error_span!("ep2")) -3765 .await?; -3766 info!("ep2 bound {:?}", ep2.id()); -3767 ep2.online().await; -3768 println!("ep2 online"); -3769 -3770 // `online` does not mean that the connection to the home relay was *established*, -3771 // only that the home relay was *chosen* based on the net report probes. -3772 // We need to wait for the connection to be established though, to be sure that new packets -3773 // will be routed to the new endpoint and not to the old endpoint anymore. -3774 // We don't expose being connected to the home relay on the endpoint currently, -3775 // so we resort to log assertions. -3776 // TODO(Frando): Replace once we add a proper API for this. -3777 let expected_log_line = format!( -3778 "ep2:endpoint{{id={}}}:relay-actor:active-relay{{url={relay_url}}}:connected: iroh::_events::relay::connected", -3779 ep2.id().fmt_short() -3780 ); -3781 tokio::time::timeout(Duration::from_secs(5), async { -3782 while !logs_contain(&expected_log_line) { -3783 tokio::time::sleep(Duration::from_millis(10)).await -3784 } -3785 }) -3786 .await -3787 .std_context("relay connection did not establish in time")?; -3788 -3789 tokio::try_join!( -3790 async { -3791 let conn = client.connect(addr.clone(), TEST_ALPN).await?; -3792 let reason = conn.closed().await; -3793 assert!(is_application_closed(&reason, 1)); -3794 n0_error::Ok(()) -3795 }, -3796 async { -3797 let conn = ep2.accept().await.unwrap().await?; -3798 conn.close(1u32.into(), b"bye"); -3799 n0_error::Ok(()) -3800 } -3801 )?; -3802 println!("client connected to ep2"); -3803 -3804 // assert that ep1 did not receive a connection -3805 assert!(now_or_never(ep1.accept()).is_none()); -3806 -3807 // We assert that we get the warn log once for endpoint 1, and not at all for endpoint 2. -3808 logs_assert(|logs| { -3809 let expected_line = |line: &str| { -3810 line.contains("WARN") && line.contains("Another endpoint connected with the same endpoint id. No more messages will be received") -3811 }; -3812 let count_line_ep1 = logs -3813 .iter() -3814 .filter(|line| line.contains(":ep1:") && expected_line(line)) -3815 .count(); -3816 let count_line_ep2 = logs +3342 assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s"); +3343 Ok(()) +3344 } +3345 +3346 #[tokio::test] +3347 async fn test_custom_relay() -> Result { +3348 let _ep = Endpoint::builder(presets::Minimal) +3349 .relay_mode(RelayMode::custom([RelayUrl::from_str( +3350 "https://use1-1.relay.n0.iroh.link.", +3351 )?])) +3352 .bind() +3353 .await?; +3354 +3355 let relays = RelayMap::try_from_iter([ +3356 "https://use1-1.relay.n0.iroh.link/", +3357 "https://euc1-1.relay.n0.iroh.link/", +3358 ])?; +3359 let _ep = Endpoint::builder(presets::Minimal) +3360 .relay_mode(RelayMode::Custom(relays)) +3361 .bind() +3362 .await?; +3363 +3364 Ok(()) +3365 } +3366 +3367 /// Testing bind_addr: Clear IP transports and add single IPv4 bind +3368 #[tokio::test] +3369 #[traced_test] +3370 async fn test_bind_addr_clear() -> Result { +3371 let ep = Endpoint::builder(presets::Minimal) +3372 .clear_ip_transports() +3373 .bind_addr((Ipv4Addr::LOCALHOST, 0))? +3374 .bind() +3375 .await?; +3376 let bound_sockets = ep.bound_sockets(); +3377 assert_eq!(bound_sockets.len(), 1); +3378 assert_eq!(bound_sockets[0].ip(), IpAddr::V4(Ipv4Addr::LOCALHOST)); +3379 ep.close().await; +3380 Ok(()) +3381 } +3382 +3383 /// Testing bind_addr: Do not clear IP transports and add single non-default IPv4 bind +3384 /// +3385 /// This will bind two sockets: default wildcard bind for IPv6, and our +3386 /// manually-added IPv4 bind. +3387 #[tokio::test] +3388 #[traced_test] +3389 async fn test_bind_addr_no_clear() -> Result { +3390 let ep = Endpoint::builder(presets::Minimal) +3391 .bind_addr((Ipv4Addr::LOCALHOST, 0))? +3392 .bind() +3393 .await?; +3394 let bound_sockets = ep.bound_sockets(); +3395 assert_eq!(bound_sockets.len(), 2); +3396 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); +3397 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +3398 // Test that our manually added socket is there +3399 assert!( +3400 bound_sockets +3401 .iter() +3402 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3403 ); +3404 ep.close().await; +3405 Ok(()) +3406 } +3407 +3408 // Testing bind_addr: Do not clear IP transports and add single default IPv4 bind. +3409 // +3410 // This replaces the default IPv4 bind added by the builder, +3411 // but keeps the default wildcard IPv6 bind. +3412 #[tokio::test] +3413 #[traced_test] +3414 async fn test_bind_addr_default() -> Result { +3415 let ep = Endpoint::builder(presets::Minimal) +3416 .bind_addr_with_opts( +3417 (Ipv4Addr::LOCALHOST, 0), +3418 BindOpts::default().set_is_default_route(true), +3419 )? +3420 .bind() +3421 .await?; +3422 let bound_sockets = ep.bound_sockets(); +3423 assert_eq!(bound_sockets.len(), 2); +3424 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); +3425 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +3426 assert!( +3427 bound_sockets +3428 .iter() +3429 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3430 ); +3431 ep.close().await; +3432 drop(ep); +3433 +3434 Ok(()) +3435 } +3436 +3437 /// Testing bind_addr: Do not clear IP transports and add single IPv4 bind with a non-zero prefix len +3438 /// +3439 /// This will bind three sockets: default wildcard bind for IPv4 and IPv6, and our +3440 /// manually-added IPv4 bind. +3441 #[tokio::test] +3442 #[traced_test] +3443 async fn test_bind_addr_nonzero_prefix() -> Result { +3444 let ep = Endpoint::builder(presets::Minimal) +3445 .bind_addr_with_opts( +3446 (Ipv4Addr::LOCALHOST, 0), +3447 BindOpts::default().set_prefix_len(32), +3448 )? +3449 .bind() +3450 .await?; +3451 let bound_sockets = ep.bound_sockets(); +3452 assert_eq!(bound_sockets.len(), 3); +3453 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 2); +3454 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +3455 // Test that the default wildcard socket is there +3456 assert!( +3457 bound_sockets +3458 .iter() +3459 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) +3460 ); +3461 // Test that our manually added socket is there +3462 assert!( +3463 bound_sockets +3464 .iter() +3465 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3466 ); +3467 ep.close().await; +3468 Ok(()) +3469 } +3470 +3471 /// Bind on an unusable port with the default opts. +3472 /// +3473 /// Binding the endpoint fails with an AddrInUse error. +3474 #[tokio::test] +3475 #[traced_test] +3476 async fn test_bind_addr_badport() -> Result { +3477 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3478 let port = socket.local_addr()?.port(); +3479 +3480 let res = Endpoint::builder(presets::Minimal) +3481 .clear_ip_transports() +3482 .bind_addr((Ipv4Addr::LOCALHOST, port))? +3483 .bind() +3484 .await; +3485 +3486 assert!(matches!( +3487 res, +3488 Err(BindError::Sockets { +3489 source: io_error, +3490 .. +3491 }) +3492 if io_error.kind() == io::ErrorKind::AddrInUse +3493 )); +3494 Ok(()) +3495 } +3496 +3497 /// Bind a non-default route on an unusable port, but set is_required = false. +3498 /// +3499 /// Binding the endpoint succeeds. +3500 #[tokio::test] +3501 #[traced_test] +3502 async fn test_bind_addr_badport_notrequired() -> Result { +3503 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3504 let port = socket.local_addr()?.port(); +3505 +3506 let ep = Endpoint::builder(presets::Minimal) +3507 .bind_addr_with_opts( +3508 (Ipv4Addr::LOCALHOST, port), +3509 BindOpts::default() +3510 .set_prefix_len(32) +3511 .set_is_required(false), +3512 )? +3513 .bind() +3514 .await?; +3515 let bound_sockets = ep.bound_sockets(); +3516 // just the default wildcard binds +3517 assert_eq!(bound_sockets.len(), 2); +3518 // our requested bind addr is not included because it failed to bind +3519 assert!( +3520 !bound_sockets +3521 .iter() +3522 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3523 ); +3524 Ok(()) +3525 } +3526 +3527 /// Bind on a default route on an unusable port, but set is_required = false. +3528 /// +3529 /// Binding the endpoint succeeds. +3530 #[tokio::test] +3531 #[traced_test] +3532 async fn test_bind_addr_badport_default_notrequired() -> Result { +3533 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3534 let port = socket.local_addr()?.port(); +3535 +3536 let ep = Endpoint::builder(presets::Minimal) +3537 .bind_addr_with_opts( +3538 (Ipv4Addr::LOCALHOST, port), +3539 BindOpts::default().set_is_required(false), +3540 )? +3541 .bind() +3542 .await?; +3543 let bound_sockets = ep.bound_sockets(); +3544 // just the IPv6 default, but no IPv4 bind at all because we replaced the default +3545 // with a bind with an unusable port and set it to not be required. +3546 assert_eq!(bound_sockets.len(), 1); +3547 assert!(bound_sockets[0].is_ipv6()); +3548 Ok(()) +3549 } +3550 +3551 /// Bind on an unusable port, with is_required = false, and no other transports. +3552 /// +3553 /// Binding the endpoint fails with "no valid address available". +3554 #[tokio::test] +3555 #[traced_test] +3556 async fn test_bind_addr_badport_notrequired_no_other_transports() -> Result { +3557 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3558 let port = socket.local_addr()?.port(); +3559 +3560 let res = Endpoint::builder(presets::Minimal) +3561 .clear_ip_transports() +3562 .bind_addr_with_opts( +3563 (Ipv4Addr::LOCALHOST, port), +3564 BindOpts::default().set_is_required(false), +3565 )? +3566 .bind() +3567 .await; +3568 +3569 assert!(matches!( +3570 res, +3571 Err(BindError::CreateQuicEndpoint { +3572 source: io_error, +3573 .. +3574 }) +3575 if io_error.kind() == io::ErrorKind::Other && io_error.to_string() == "no valid address available" +3576 )); +3577 Ok(()) +3578 } +3579 +3580 /// Bind with prefix len 0 but set the route as non-default. +3581 #[tokio::test] +3582 #[traced_test] +3583 async fn test_bind_addr_prefix_len_0_not_default() -> Result { +3584 let ep = Endpoint::builder(presets::Minimal) +3585 .bind_addr_with_opts( +3586 (Ipv4Addr::LOCALHOST, 0), +3587 BindOpts::default().set_is_default_route(false), +3588 )? +3589 .bind() +3590 .await?; +3591 let bound_sockets = ep.bound_sockets(); +3592 // The two default wildcard binds plus our additional route (which does not replace the default route +3593 // because we set is_default_route to false explicitly). +3594 assert_eq!(bound_sockets.len(), 3); +3595 assert!( +3596 bound_sockets +3597 .iter() +3598 .any(|x| x.ip() == IpAddr::V6(Ipv6Addr::UNSPECIFIED)) +3599 ); +3600 assert!( +3601 bound_sockets +3602 .iter() +3603 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) +3604 ); +3605 assert!( +3606 bound_sockets +3607 .iter() +3608 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3609 ); +3610 Ok(()) +3611 } +3612 +3613 #[ignore = "flaky"] +3614 #[tokio::test] +3615 #[traced_test] +3616 async fn connect_via_relay_becomes_direct_and_sends_direct() -> Result { +3617 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; +3618 let qlog = Arc::new(QlogFileGroup::from_env( +3619 "connect_via_relay_becomes_direct_and_sends_direct", +3620 )); +3621 let transfer_size = 1_000_000; +3622 +3623 async fn collect_stats(mut events: PathEventStream) -> BTreeMap<TransportAddr, PathStats> { +3624 let mut stats = BTreeMap::new(); +3625 while let Some(event) = events.next().await { +3626 if let PathEvent::Closed { +3627 remote_addr, +3628 last_stats, +3629 .. +3630 } = event +3631 { +3632 stats.insert(remote_addr, *last_stats); +3633 } +3634 } +3635 stats +3636 } +3637 +3638 let client = Endpoint::builder(presets::Minimal) +3639 .relay_mode(RelayMode::Custom(relay_map.clone())) +3640 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3641 .transport_config(qlog.create("client")?) +3642 .bind() +3643 .await?; +3644 let server = Endpoint::builder(presets::Minimal) +3645 .relay_mode(RelayMode::Custom(relay_map)) +3646 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3647 .transport_config(qlog.create("server")?) +3648 .alpns(vec![TEST_ALPN.to_vec()]) +3649 .bind() +3650 .await?; +3651 let server_addr = EndpointAddr::new(server.id()).with_relay_url(relay_url); +3652 let server_task = tokio::spawn(async move { +3653 let incoming = server.accept().await.anyerr()?; +3654 let conn = incoming.await.anyerr()?; +3655 let stats_task = tokio::spawn(collect_stats(conn.path_events())); +3656 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +3657 let msg = recv.read_to_end(transfer_size).await.anyerr()?; +3658 send.write_all(&msg).await.anyerr()?; +3659 send.finish().anyerr()?; +3660 conn.closed().await; +3661 let stats = stats_task.await.expect("stats task panicked"); +3662 Ok::<_, Error>(stats) +3663 }); +3664 +3665 let conn = client.connect(server_addr, TEST_ALPN).await?; +3666 let client_stats_task = tokio::spawn(collect_stats(conn.path_events())); +3667 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +3668 send.write_all(&vec![42u8; transfer_size]).await.anyerr()?; +3669 send.finish().anyerr()?; +3670 recv.read_to_end(transfer_size).await.anyerr()?; +3671 conn.close(0u32.into(), b"thanks, bye!"); +3672 client.close().await; +3673 let client_stats = client_stats_task.await.expect("stats task panicked"); +3674 let server_stats = server_task.await.anyerr()??; +3675 +3676 info!("client stats: {client_stats:#?}"); +3677 info!("server stats: {server_stats:#?}"); +3678 +3679 let client_total_relay_tx = client_stats +3680 .iter() +3681 .filter(|(remote, _stats)| remote.is_relay()) +3682 .map(|(_, stats)| stats.udp_tx.bytes) +3683 .sum::<u64>(); +3684 let client_total_relay_rx = client_stats +3685 .iter() +3686 .filter(|(remote, _stats)| remote.is_relay()) +3687 .map(|(_, stats)| stats.udp_rx.bytes) +3688 .sum::<u64>(); +3689 let server_total_relay_tx = server_stats +3690 .iter() +3691 .filter(|(remote, _stats)| remote.is_relay()) +3692 .map(|(_, stats)| stats.udp_tx.bytes) +3693 .sum::<u64>(); +3694 let server_total_relay_rx = server_stats +3695 .iter() +3696 .filter(|(remote, _stats)| remote.is_relay()) +3697 .map(|(_, stats)| stats.udp_rx.bytes) +3698 .sum::<u64>(); +3699 +3700 info!(?client_total_relay_tx, "total"); +3701 info!(?client_total_relay_rx, "total"); +3702 info!(?server_total_relay_tx, "total"); +3703 info!(?server_total_relay_rx, "total"); +3704 +3705 // We should send/receive only the minorty of traffic via the relay. +3706 assert!(client_total_relay_tx < transfer_size as u64 / 2); +3707 assert!(client_total_relay_rx < transfer_size as u64 / 2); +3708 assert!(server_total_relay_tx < transfer_size as u64 / 2); +3709 assert!(server_total_relay_rx < transfer_size as u64 / 2); +3710 +3711 Ok(()) +3712 } +3713 +3714 /// Tests that correct logs are emitted when connecting two endpoints with same secret keys to a relay. +3715 #[tokio::test] +3716 #[traced_test] +3717 async fn same_endpoint_id_relay() -> Result { +3718 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; +3719 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +3720 let secret_key = SecretKey::from_bytes(&rng.random()); +3721 +3722 let client = Endpoint::builder(presets::Minimal) +3723 .relay_mode(RelayMode::Custom(relay_map.clone())) +3724 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3725 .bind() +3726 .instrument(error_span!("ep-client")) +3727 .await?; +3728 +3729 info!("client {}", client.id()); +3730 +3731 // bind ep1 and wait until connected to relay. +3732 let ep1 = Endpoint::builder(presets::Minimal) +3733 .relay_mode(RelayMode::Custom(relay_map.clone())) +3734 .secret_key(secret_key.clone()) +3735 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3736 .alpns(vec![TEST_ALPN.to_vec()]) +3737 .bind() +3738 .instrument(error_span!("ep1")) +3739 .await?; +3740 info!("ep1 bound {:?}", ep1.id()); +3741 ep1.online().await; +3742 info!("ep1 online"); +3743 +3744 let addr = EndpointAddr::new(secret_key.public()).with_relay_url(relay_url.clone()); +3745 +3746 tokio::try_join!( +3747 async { +3748 let conn = client.connect(addr.clone(), TEST_ALPN).await?; +3749 let reason = conn.closed().await; +3750 assert!(is_application_closed(&reason, 1)); +3751 n0_error::Ok(()) +3752 }, +3753 async { +3754 let conn = ep1.accept().await.unwrap().await?; +3755 conn.close(1u32.into(), b"bye"); +3756 n0_error::Ok(()) +3757 } +3758 )?; +3759 info!("client connected to ep1"); +3760 +3761 // now start second endpoint with same secret key +3762 let ep2 = Endpoint::builder(presets::Minimal) +3763 .relay_mode(RelayMode::Custom(relay_map)) +3764 .secret_key(secret_key.clone()) +3765 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3766 .alpns(vec![TEST_ALPN.to_vec()]) +3767 .bind() +3768 .instrument(error_span!("ep2")) +3769 .await?; +3770 info!("ep2 bound {:?}", ep2.id()); +3771 ep2.online().await; +3772 println!("ep2 online"); +3773 +3774 // `online` does not mean that the connection to the home relay was *established*, +3775 // only that the home relay was *chosen* based on the net report probes. +3776 // We need to wait for the connection to be established though, to be sure that new packets +3777 // will be routed to the new endpoint and not to the old endpoint anymore. +3778 // We don't expose being connected to the home relay on the endpoint currently, +3779 // so we resort to log assertions. +3780 // TODO(Frando): Replace once we add a proper API for this. +3781 let expected_log_line = format!( +3782 "ep2:endpoint{{id={}}}:relay-actor:active-relay{{url={relay_url}}}:connected: iroh::_events::relay::connected", +3783 ep2.id().fmt_short() +3784 ); +3785 tokio::time::timeout(Duration::from_secs(5), async { +3786 while !logs_contain(&expected_log_line) { +3787 tokio::time::sleep(Duration::from_millis(10)).await +3788 } +3789 }) +3790 .await +3791 .std_context("relay connection did not establish in time")?; +3792 +3793 tokio::try_join!( +3794 async { +3795 let conn = client.connect(addr.clone(), TEST_ALPN).await?; +3796 let reason = conn.closed().await; +3797 assert!(is_application_closed(&reason, 1)); +3798 n0_error::Ok(()) +3799 }, +3800 async { +3801 let conn = ep2.accept().await.unwrap().await?; +3802 conn.close(1u32.into(), b"bye"); +3803 n0_error::Ok(()) +3804 } +3805 )?; +3806 println!("client connected to ep2"); +3807 +3808 // assert that ep1 did not receive a connection +3809 assert!(now_or_never(ep1.accept()).is_none()); +3810 +3811 // We assert that we get the warn log once for endpoint 1, and not at all for endpoint 2. +3812 logs_assert(|logs| { +3813 let expected_line = |line: &str| { +3814 line.contains("WARN") && line.contains("Another endpoint connected with the same endpoint id. No more messages will be received") +3815 }; +3816 let count_line_ep1 = logs 3817 .iter() -3818 .filter(|line| line.contains(":ep2:") && expected_line(line)) +3818 .filter(|line| line.contains(":ep1:") && expected_line(line)) 3819 .count(); -3820 if count_line_ep1 == 1 && count_line_ep2 == 0 { -3821 Ok(()) -3822 } else { -3823 Err("Logs don't match expectations".to_string()) -3824 } -3825 }); -3826 tokio::join!(ep1.close(), ep2.close(), client.close()); -3827 Ok(()) -3828 } -3829 -3830 fn is_application_closed(close_reason: &ConnectionError, code: u32) -> bool { -3831 matches!( -3832 close_reason, -3833 ConnectionError::ApplicationClosed(f) if f.error_code ==code.into() -3834 ) -3835 } -3836 -3837 #[tokio::test] -3838 #[traced_test] -3839 async fn test_closed_endpoint_behaviour() -> Result { -3840 // create endpoint -3841 // call endpoint.close -3842 // ensure methods behave in the expected way -3843 info!("Creating endpoint"); -3844 let ep = Endpoint::builder(presets::N0).bind().await?; -3845 let closed = ep.closed(); -3846 info!("Closing endpoint"); -3847 let now = Instant::now(); -3848 ep.close().await; -3849 info!("Endpoint closed in {:?}", now.elapsed()); -3850 -3851 // Assert that the `closed` cancellation token is now cancelled -3852 assert_eq!(now_or_never(closed), Some(())); -3853 -3854 info!("Set ALPNS fails silently"); -3855 ep.set_alpns(vec![b"test".into()]); -3856 -3857 info!("Insert Relay returns None"); -3858 let relay_config = crate::defaults::staging::default_na_east_relay(); -3859 assert!( -3860 ep.insert_relay("localhost:300".parse()?, Arc::new(relay_config)) -3861 .await -3862 .is_none() -3863 ); -3864 -3865 info!("Remove Relay returns None"); -3866 assert!(ep.remove_relay(&"localhost:300".parse()?).await.is_none()); -3867 -3868 info!("Connecting"); -3869 let mut rng = ChaCha8Rng::seed_from_u64(41); -3870 let ep_id = SecretKey::from_bytes(&rng.random()).public(); +3820 let count_line_ep2 = logs +3821 .iter() +3822 .filter(|line| line.contains(":ep2:") && expected_line(line)) +3823 .count(); +3824 if count_line_ep1 == 1 && count_line_ep2 == 0 { +3825 Ok(()) +3826 } else { +3827 Err("Logs don't match expectations".to_string()) +3828 } +3829 }); +3830 tokio::join!(ep1.close(), ep2.close(), client.close()); +3831 Ok(()) +3832 } +3833 +3834 fn is_application_closed(close_reason: &ConnectionError, code: u32) -> bool { +3835 matches!( +3836 close_reason, +3837 ConnectionError::ApplicationClosed(f) if f.error_code ==code.into() +3838 ) +3839 } +3840 +3841 #[tokio::test] +3842 #[traced_test] +3843 async fn test_closed_endpoint_behaviour() -> Result { +3844 // create endpoint +3845 // call endpoint.close +3846 // ensure methods behave in the expected way +3847 info!("Creating endpoint"); +3848 let ep = Endpoint::builder(presets::N0).bind().await?; +3849 let closed = ep.closed(); +3850 info!("Closing endpoint"); +3851 let now = Instant::now(); +3852 ep.close().await; +3853 info!("Endpoint closed in {:?}", now.elapsed()); +3854 +3855 // Assert that the `closed` cancellation token is now cancelled +3856 assert_eq!(now_or_never(closed), Some(())); +3857 +3858 info!("Set ALPNS fails silently"); +3859 ep.set_alpns(vec![b"test".into()]); +3860 +3861 info!("Insert Relay returns None"); +3862 let relay_config = crate::defaults::staging::default_na_east_relay(); +3863 assert!( +3864 ep.insert_relay("localhost:300".parse()?, Arc::new(relay_config)) +3865 .await +3866 .is_none() +3867 ); +3868 +3869 info!("Remove Relay returns None"); +3870 assert!(ep.remove_relay(&"localhost:300".parse()?).await.is_none()); 3871 -3872 // should likely be an error that states that the -3873 // endpoint is closed instead: -3874 if let ConnectError::Connect { source, .. } = ep.connect(ep_id, b"test").await.unwrap_err() -3875 { -3876 assert!(matches!( -3877 source, -3878 ConnectWithOptsError::EndpointClosed { .. } -3879 )); -3880 } else { -3881 panic!("unexpected error for connect"); -3882 } -3883 -3884 info!("Accepting!"); -3885 assert!(ep.accept().await.is_none()); -3886 -3887 // this should work -3888 info!("Addr: {:?}", ep.addr()); -3889 -3890 // create watchers to verify they terminate after the endpoint is dropped. -3891 let mut addrs = ep.watch_addr().stream(); -3892 -3893 #[cfg(feature = "unstable-net-report")] -3894 let mut net_reports = { -3895 let net_reports = ep.net_report().stream(); +3872 info!("Connecting"); +3873 let mut rng = ChaCha8Rng::seed_from_u64(41); +3874 let ep_id = SecretKey::from_bytes(&rng.random()).public(); +3875 +3876 // should likely be an error that states that the +3877 // endpoint is closed instead: +3878 if let ConnectError::Connect { source, .. } = ep.connect(ep_id, b"test").await.unwrap_err() +3879 { +3880 assert!(matches!( +3881 source, +3882 ConnectWithOptsError::EndpointClosed { .. } +3883 )); +3884 } else { +3885 panic!("unexpected error for connect"); +3886 } +3887 +3888 info!("Accepting!"); +3889 assert!(ep.accept().await.is_none()); +3890 +3891 // this should work +3892 info!("Addr: {:?}", ep.addr()); +3893 +3894 // create watchers to verify they terminate after the endpoint is dropped. +3895 let mut addrs = ep.watch_addr().stream(); 3896 -3897 // returns None -3898 let net_report = ep.net_report().get(); -3899 info!("last Net report {net_report:?}"); -3900 net_reports -3901 }; -3902 -3903 // this should work -3904 let sockets = ep.bound_sockets(); -3905 info!("Sockets: {sockets:?}"); +3897 #[cfg(feature = "unstable-net-report")] +3898 let mut net_reports = { +3899 let net_reports = ep.net_report().stream(); +3900 +3901 // returns None +3902 let net_report = ep.net_report().get(); +3903 info!("last Net report {net_report:?}"); +3904 net_reports +3905 }; 3906 -3907 // these should return errors -3908 assert!(ep.dns_resolver().is_err()); -3909 assert!(ep.address_lookup().is_err()); +3907 // this should work +3908 let sockets = ep.bound_sockets(); +3909 info!("Sockets: {sockets:?}"); 3910 -3911 #[cfg(feature = "metrics")] -3912 { -3913 // this should work -3914 let metrics = ep.metrics(); -3915 info!("Metrics: {metrics:?}"); -3916 } -3917 -3918 // this should return none -3919 assert!(ep.remote_info(ep_id).await.is_none()); -3920 -3921 // this should fail silently -3922 ep.network_change().await; -3923 -3924 // this should fail silently -3925 ep.set_user_data_for_address_lookup(Some( -3926 UserData::try_from("TEST".to_string()).expect("valid string"), -3927 )); -3928 drop(ep); -3929 // now that the endpoint is dropped, all watchers should terminate. -3930 tokio::time::timeout(Duration::from_secs(1), async { -3931 while let Some(addr) = addrs.next().await { -3932 info!("Addrs stream: {addr:?}"); -3933 } -3934 -3935 #[cfg(feature = "unstable-net-report")] -3936 while let Some(net_report) = net_reports.next().await { -3937 info!("Net report stream: {net_report:?}"); -3938 } -3939 }) -3940 .await -3941 .expect("watchers not closed"); -3942 -3943 info!("Done!"); -3944 Ok(()) -3945 } +3911 // these should return errors +3912 assert!(ep.dns_resolver().is_err()); +3913 assert!(ep.address_lookup().is_err()); +3914 +3915 #[cfg(feature = "metrics")] +3916 { +3917 // this should work +3918 let metrics = ep.metrics(); +3919 info!("Metrics: {metrics:?}"); +3920 } +3921 +3922 // this should return none +3923 assert!(ep.remote_info(ep_id).await.is_none()); +3924 +3925 // this should fail silently +3926 ep.network_change().await; +3927 +3928 // this should fail silently +3929 ep.set_user_data_for_address_lookup(Some( +3930 UserData::try_from("TEST".to_string()).expect("valid string"), +3931 )); +3932 drop(ep); +3933 // now that the endpoint is dropped, all watchers should terminate. +3934 tokio::time::timeout(Duration::from_secs(1), async { +3935 while let Some(addr) = addrs.next().await { +3936 info!("Addrs stream: {addr:?}"); +3937 } +3938 +3939 #[cfg(feature = "unstable-net-report")] +3940 while let Some(net_report) = net_reports.next().await { +3941 info!("Net report stream: {net_report:?}"); +3942 } +3943 }) +3944 .await +3945 .expect("watchers not closed"); 3946 -3947 #[tokio::test] -3948 #[traced_test] -3949 async fn test_closed_endpoint_unpolled_accept_fut() -> Result { -3950 info!("Creating endpoint"); -3951 let ep = Endpoint::builder(presets::N0).bind().await?; -3952 -3953 info!("Get accept future"); -3954 let accept_fut = ep.accept(); -3955 -3956 info!("Closing endpoint"); -3957 let now = Instant::now(); -3958 tokio::time::timeout(Duration::from_secs(5), ep.close()) -3959 .await -3960 .expect("Endpoint closes in a reasonable time"); -3961 info!("Endpoint closed in {:?}", now.elapsed()); -3962 -3963 info!("Accept future returns None after the endpoint has closed"); -3964 let incoming = accept_fut.await; -3965 assert!(incoming.is_none()); -3966 Ok(()) -3967 } -3968 -3969 #[tokio::test] -3970 #[traced_test] -3971 async fn test_closed_endpoint_polled_accept_fut() -> Result { -3972 info!("Creating endpoint"); -3973 let ep = Endpoint::builder(presets::N0).bind().await?; -3974 -3975 info!("Run an accept task"); -3976 let ep2 = ep.clone(); -3977 let accept_task = tokio::spawn(async move { -3978 info!("Waiting on Accept"); -3979 let res = ep2.accept().await; -3980 info!("Accept await has returned"); -3981 res -3982 }); -3983 -3984 // Try to ensure the accept future is polled at least once. -3985 tokio::time::sleep(Duration::from_millis(10)).await; -3986 -3987 info!("Closing the endpoint"); -3988 tokio::time::timeout(Duration::from_secs(5), ep.close()) -3989 .await -3990 .expect("Endpoint closes in a reasonable time"); -3991 info!("Endpoint closed"); -3992 -3993 info!("Await the accept task"); -3994 let incoming = accept_task.await.expect("accept task panicked"); -3995 assert!(incoming.is_none()); +3947 info!("Done!"); +3948 Ok(()) +3949 } +3950 +3951 #[tokio::test] +3952 #[traced_test] +3953 async fn test_closed_endpoint_unpolled_accept_fut() -> Result { +3954 info!("Creating endpoint"); +3955 let ep = Endpoint::builder(presets::N0).bind().await?; +3956 +3957 info!("Get accept future"); +3958 let accept_fut = ep.accept(); +3959 +3960 info!("Closing endpoint"); +3961 let now = Instant::now(); +3962 tokio::time::timeout(Duration::from_secs(5), ep.close()) +3963 .await +3964 .expect("Endpoint closes in a reasonable time"); +3965 info!("Endpoint closed in {:?}", now.elapsed()); +3966 +3967 info!("Accept future returns None after the endpoint has closed"); +3968 let incoming = accept_fut.await; +3969 assert!(incoming.is_none()); +3970 Ok(()) +3971 } +3972 +3973 #[tokio::test] +3974 #[traced_test] +3975 async fn test_closed_endpoint_polled_accept_fut() -> Result { +3976 info!("Creating endpoint"); +3977 let ep = Endpoint::builder(presets::N0).bind().await?; +3978 +3979 info!("Run an accept task"); +3980 let ep2 = ep.clone(); +3981 let accept_task = tokio::spawn(async move { +3982 info!("Waiting on Accept"); +3983 let res = ep2.accept().await; +3984 info!("Accept await has returned"); +3985 res +3986 }); +3987 +3988 // Try to ensure the accept future is polled at least once. +3989 tokio::time::sleep(Duration::from_millis(10)).await; +3990 +3991 info!("Closing the endpoint"); +3992 tokio::time::timeout(Duration::from_secs(5), ep.close()) +3993 .await +3994 .expect("Endpoint closes in a reasonable time"); +3995 info!("Endpoint closed"); 3996 -3997 Ok(()) -3998 } -3999 -4000 #[tokio::test] -4001 #[traced_test] -4002 async fn test_endpoint_online_add_relay() -> Result { -4003 let ep = Endpoint::builder(presets::Minimal) -4004 .relay_mode(RelayMode::Custom(RelayMap::empty())) -4005 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -4006 .bind() -4007 .await?; -4008 // should not come online without relays. -4009 let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await; -4010 assert!(res.is_err()); -4011 -4012 // should come online after a relay is added. -4013 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; -4014 ep.insert_relay(relay_url.clone(), relay_map.get(&relay_url).unwrap()) -4015 .await; -4016 let res = tokio::time::timeout(Duration::from_millis(1000), ep.online()).await; -4017 assert!(res.is_ok()); -4018 -4019 // online should still return after endpoint close, if the endpoint was last online -4020 let ep_clone = ep.clone(); -4021 let task = tokio::task::spawn(async move { -4022 tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await -4023 }); -4024 ep.close().await; -4025 let res = task.await.unwrap(); -4026 assert!(res.is_ok()); -4027 Ok(()) -4028 } -4029 -4030 #[tokio::test] -4031 #[traced_test] -4032 async fn test_endpoint_online_close() -> Result { -4033 let ep = Endpoint::bind(presets::Minimal).await?; -4034 // should not come online without relays. -4035 let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await; -4036 assert!(res.is_err()); -4037 -4038 // online should remain pending after the endpoint is closed. -4039 let ep_clone = ep.clone(); -4040 let task = tokio::task::spawn(async move { -4041 tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await -4042 }); -4043 ep.close().await; -4044 let res = task.await.unwrap(); -4045 assert!(res.is_err()); -4046 Ok(()) -4047 } -4048 -4049 /// Verifies that an endpoint configured with [`RelayConfig::with_auth_token`] -4050 /// is admitted to a relay whose access control checks the token only when -4051 /// the token matches. -4052 #[tokio::test] -4053 #[traced_test] -4054 async fn test_endpoint_relay_auth_token() -> Result { -4055 const TOKEN: &str = "valid-token"; -4056 -4057 /// Admits a connection only if it carries the expected auth token. -4058 #[derive(Debug)] -4059 struct TokenAccess(&'static str); +3997 info!("Await the accept task"); +3998 let incoming = accept_task.await.expect("accept task panicked"); +3999 assert!(incoming.is_none()); +4000 +4001 Ok(()) +4002 } +4003 +4004 #[tokio::test] +4005 #[traced_test] +4006 async fn test_endpoint_online_add_relay() -> Result { +4007 let ep = Endpoint::builder(presets::Minimal) +4008 .relay_mode(RelayMode::Custom(RelayMap::empty())) +4009 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +4010 .bind() +4011 .await?; +4012 // should not come online without relays. +4013 let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await; +4014 assert!(res.is_err()); +4015 +4016 // should come online after a relay is added. +4017 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; +4018 ep.insert_relay(relay_url.clone(), relay_map.get(&relay_url).unwrap()) +4019 .await; +4020 let res = tokio::time::timeout(Duration::from_millis(1000), ep.online()).await; +4021 assert!(res.is_ok()); +4022 +4023 // online should still return after endpoint close, if the endpoint was last online +4024 let ep_clone = ep.clone(); +4025 let task = tokio::task::spawn(async move { +4026 tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await +4027 }); +4028 ep.close().await; +4029 let res = task.await.unwrap(); +4030 assert!(res.is_ok()); +4031 Ok(()) +4032 } +4033 +4034 #[tokio::test] +4035 #[traced_test] +4036 async fn test_endpoint_online_close() -> Result { +4037 let ep = Endpoint::bind(presets::Minimal).await?; +4038 // should not come online without relays. +4039 let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await; +4040 assert!(res.is_err()); +4041 +4042 // online should remain pending after the endpoint is closed. +4043 let ep_clone = ep.clone(); +4044 let task = tokio::task::spawn(async move { +4045 tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await +4046 }); +4047 ep.close().await; +4048 let res = task.await.unwrap(); +4049 assert!(res.is_err()); +4050 Ok(()) +4051 } +4052 +4053 /// Verifies that an endpoint configured with [`RelayConfig::with_auth_token`] +4054 /// is admitted to a relay whose access control checks the token only when +4055 /// the token matches. +4056 #[tokio::test] +4057 #[traced_test] +4058 async fn test_endpoint_relay_auth_token() -> Result { +4059 const TOKEN: &str = "valid-token"; 4060 -4061 impl iroh_relay::server::AccessControl for TokenAccess { -4062 async fn on_connect(&self, request: &iroh_relay::server::ClientRequest) -> Access { -4063 if request.auth_token().as_deref() == Some(self.0) { -4064 Access::Allow -4065 } else { -4066 Access::Deny { reason: None } -4067 } -4068 } -4069 } -4070 -4071 let access = Arc::new(TokenAccess(TOKEN)); -4072 let (_relay_map, relay_url, _guard) = run_relay_server_with_access(false, access).await?; -4073 -4074 // Wrong token: the connection attempt fails and last_error reports -4075 // the relay-side denial. -4076 let bad_map: RelayMap = RelayConfig::new(relay_url.clone(), None) -4077 .with_auth_token("wrong-token") -4078 .into(); -4079 let bad_ep = Endpoint::builder(presets::Minimal) -4080 .relay_mode(RelayMode::Custom(bad_map)) -4081 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -4082 .bind() -4083 .await?; -4084 let mut stream = bad_ep.home_relay_status().stream(); -4085 let auth_err: String = tokio::time::timeout(Duration::from_secs(5), async { -4086 while let Some(status) = stream.next().await { -4087 if let Some(err) = status.iter().filter_map(|s| s.last_error()).next() { -4088 return format!("{err:#}"); -4089 } -4090 } -4091 panic!("home relay stream ended"); -4092 }) -4093 .await -4094 .std_context("waiting for auth error")?; -4095 assert!( -4096 auth_err.contains("not authorized"), -4097 "expected 'not authorized' in error, got: {auth_err}" -4098 ); -4099 -4100 // Correct token: the endpoint reaches the connected state. -4101 let good_map: RelayMap = RelayConfig::new(relay_url, None) -4102 .with_auth_token(TOKEN) -4103 .into(); -4104 let good_ep = Endpoint::builder(presets::Minimal) -4105 .relay_mode(RelayMode::Custom(good_map)) -4106 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -4107 .bind() -4108 .await?; -4109 tokio::time::timeout(Duration::from_secs(5), good_ep.online()) -4110 .await -4111 .std_context("waiting for endpoint to come online")?; -4112 -4113 Ok(()) -4114 } -4115}
\ No newline at end of file +4061 /// Admits a connection only if it carries the expected auth token. +4062 #[derive(Debug)] +4063 struct TokenAccess(&'static str); +4064 +4065 impl iroh_relay::server::AccessControl for TokenAccess { +4066 async fn on_connect(&self, request: &iroh_relay::server::ClientRequest) -> Access { +4067 if request.auth_token().as_deref() == Some(self.0) { +4068 Access::Allow +4069 } else { +4070 Access::Deny { reason: None } +4071 } +4072 } +4073 } +4074 +4075 let access = Arc::new(TokenAccess(TOKEN)); +4076 let (_relay_map, relay_url, _guard) = run_relay_server_with_access(false, access).await?; +4077 +4078 // Wrong token: the connection attempt fails and last_error reports +4079 // the relay-side denial. +4080 let bad_map: RelayMap = RelayConfig::new(relay_url.clone(), None) +4081 .with_auth_token("wrong-token") +4082 .into(); +4083 let bad_ep = Endpoint::builder(presets::Minimal) +4084 .relay_mode(RelayMode::Custom(bad_map)) +4085 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +4086 .bind() +4087 .await?; +4088 let mut stream = bad_ep.home_relay_status().stream(); +4089 let auth_err: String = tokio::time::timeout(Duration::from_secs(5), async { +4090 while let Some(status) = stream.next().await { +4091 if let Some(err) = status.iter().filter_map(|s| s.last_error()).next() { +4092 return format!("{err:#}"); +4093 } +4094 } +4095 panic!("home relay stream ended"); +4096 }) +4097 .await +4098 .std_context("waiting for auth error")?; +4099 assert!( +4100 auth_err.contains("not authorized"), +4101 "expected 'not authorized' in error, got: {auth_err}" +4102 ); +4103 +4104 // Correct token: the endpoint reaches the connected state. +4105 let good_map: RelayMap = RelayConfig::new(relay_url, None) +4106 .with_auth_token(TOKEN) +4107 .into(); +4108 let good_ep = Endpoint::builder(presets::Minimal) +4109 .relay_mode(RelayMode::Custom(good_map)) +4110 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +4111 .bind() +4112 .await?; +4113 tokio::time::timeout(Duration::from_secs(5), good_ep.online()) +4114 .await +4115 .std_context("waiting for endpoint to come online")?; +4116 +4117 Ok(()) +4118 } +4119}
\ No newline at end of file