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