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