diff --git a/crates/tsunagi-core/src/agent/events.rs b/crates/tsunagi-core/src/agent/events.rs index b2938a4..aef7d77 100644 --- a/crates/tsunagi-core/src/agent/events.rs +++ b/crates/tsunagi-core/src/agent/events.rs @@ -9,7 +9,7 @@ use std::time::Duration; use iroh::EndpointId; -use crate::identity::NetworkId; +use crate::identity::{NetworkId, NetworkName}; use crate::net::TransportKind; use crate::proto::ControlMessage; use crate::proto::handshake::Role; @@ -48,8 +48,12 @@ pub enum Event { PeerDisconnected { /// The network the session belonged to. network: NetworkId, + /// Its locally configured name. + network_name: NetworkName, /// The peer. peer: EndpointId, + /// Last known name of the authenticated peer, when available. + hostname: Option, /// Why the session ended. Free of secrets. reason: String, }, diff --git a/crates/tsunagi-core/src/agent/network.rs b/crates/tsunagi-core/src/agent/network.rs index b5c97ed..31ab389 100644 --- a/crates/tsunagi-core/src/agent/network.rs +++ b/crates/tsunagi-core/src/agent/network.rs @@ -2855,13 +2855,18 @@ impl Runtime { SessionEvent::Closed { session_id, peer, - reason, + mut reason, } => { let current = self.sessions.get(&peer).map(|session| session.id); if current != Some(session_id) { return; } if let Some(session) = self.sessions.remove(&peer) { + // Read the cause before local cleanup closes a still-open connection. + if let Some(cause) = session.conn.close_reason() { + reason = + format!("{reason} ({})", super::session::describe_quic_close(cause)); + } session.abort(); session.conn.close(0u32.into(), b"session ended"); } @@ -2885,7 +2890,13 @@ impl Runtime { self.params.roster_changed.send_replace(()); self.emit(Event::PeerDisconnected { network: self.network_id, + network_name: self.params.keys.name().clone(), peer, + hostname: self + .known_hostnames + .get(&peer) + .cloned() + .or_else(|| self.state.hostname_of(&peer).map(str::to_owned)), reason, }); } diff --git a/crates/tsunagi-core/src/agent/session.rs b/crates/tsunagi-core/src/agent/session.rs index c178e48..c686340 100644 --- a/crates/tsunagi-core/src/agent/session.rs +++ b/crates/tsunagi-core/src/agent/session.rs @@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Instant; use iroh::EndpointId; -use iroh::endpoint::{Connection, RecvStream, SendStream}; +use iroh::endpoint::{Connection, ConnectionError, RecvStream, SendStream}; use tokio::sync::mpsc; use tokio::task::JoinHandle; @@ -60,6 +60,22 @@ pub(crate) enum SessionEvent { }, } +/// The transport category and code are useful in logs. Remote close text is +/// arbitrary peer-supplied data and may contain secrets or control characters. +pub(super) fn describe_quic_close(cause: ConnectionError) -> String { + match cause { + ConnectionError::ApplicationClosed(close) => { + format!("QUIC closed by peer, application code {}", close.error_code) + } + ConnectionError::ConnectionClosed(close) => { + format!("QUIC closed by peer, transport code {}", close.error_code) + } + ConnectionError::TransportError(error) => format!("QUIC transport error {}", error.code), + ConnectionError::LocallyClosed => "QUIC closed locally".to_owned(), + other => format!("QUIC: {other}"), + } +} + /// A live session, as held by the network runtime. #[derive(Debug)] pub(crate) struct Session { diff --git a/crates/tsunagi-core/tests/authentication.rs b/crates/tsunagi-core/tests/authentication.rs index 2d23e74..04dfd12 100644 --- a/crates/tsunagi-core/tests/authentication.rs +++ b/crates/tsunagi-core/tests/authentication.rs @@ -47,6 +47,79 @@ async fn open_control_stream( const LIMIT: usize = 64 * 1024; +#[tokio::test] +async fn an_authenticated_disconnect_reports_the_quic_close_code() { + let agent = TestAgent::spawn(&SharedMemoryDiscovery::new()) + .await + .unwrap(); + let (name, secret) = network("disconnect-diagnostics"); + let id = agent.agent.join_network(&name, &secret).await.unwrap(); + let member = raw_endpoint().await; + let (conn, mut send, mut recv) = open_control_stream(&member, agent.agent.local_addr()).await; + let mut events = agent.agent.subscribe(); + tsunagi::proto::handshake::initiate( + &conn, + &mut send, + &mut recv, + member.id(), + &NetworkKeys::derive(&name, &secret), + &tsunagi::Limits::default(), + ) + .await + .unwrap(); + let message = ControlMessage::Announce(tsunagi::proto::message::Announcement { + broadcast: true, + exit_node: false, + hostname: "returning-peer".into(), + capabilities: Vec::new(), + agent_version: None, + }); + write_frame( + &mut send, + &encode(&Envelope { + network_id: *id.as_bytes(), + message, + }) + .unwrap(), + LIMIT, + ) + .await + .unwrap(); + tsunagi::testing::wait_until("peer hostname is known", || async { + agent + .agent + .network_status(id) + .await + .ok()? + .peers + .into_iter() + .find(|p| { + p.endpoint_id == member.id() && p.hostname.as_deref() == Some("returning-peer") + }) + }) + .await; + conn.close(42u32.into(), b"private remote text\nsecond line"); + let (reported_network, hostname, reason) = wait_event(&mut events, |event| match event { + Event::PeerDisconnected { + network, + network_name, + peer, + hostname, + reason, + } if *network == id && *peer == member.id() => { + Some((network_name.clone(), hostname.clone(), reason.clone())) + } + _ => None, + }) + .await; + assert_eq!(reported_network, name); + assert_eq!(hostname.as_deref(), Some("returning-peer")); + assert!(reason.contains("application code 42"), "{reason}"); + assert!(!reason.contains("private remote text")); + member.close().await; + agent.agent.shutdown().await; +} + /// Sends `Hello` and reads the responder's `HelloAck`. async fn exchange_hellos( send: &mut SendStream, diff --git a/crates/tsunagi-wg-quic/src/device.rs b/crates/tsunagi-wg-quic/src/device.rs index 4f8b5b1..a3bca3a 100644 --- a/crates/tsunagi-wg-quic/src/device.rs +++ b/crates/tsunagi-wg-quic/src/device.rs @@ -264,17 +264,18 @@ impl std::fmt::Debug for Peer { } } -impl Drop for Peer { - fn drop(&mut self) { - if let Ok(mut guard) = self.task.lock() - && let Some(task) = guard.take() +impl Peer { + fn stop_reader(&self) { + if let Some(task) = self + .task + .lock() + .unwrap_or_else(|err| err.into_inner()) + .take() { task.abort(); } } -} -impl Peer { fn stats(&self) -> PeerStats { PeerStats { counter_epoch: self.counters.epoch, @@ -479,7 +480,9 @@ impl WireguardDevice { *guard = Some(task); } - write_lock(&self.inner.peers).insert(public_key, Arc::clone(&peer)); + if let Some(old) = write_lock(&self.inner.peers).insert(public_key, Arc::clone(&peer)) { + old.stop_reader(); + } // Start the handshake now instead of waiting for the next timer tick, // so the tunnel is usable as soon as the link exists. @@ -489,21 +492,28 @@ impl WireguardDevice { /// Removes a peer and stops its tunnel. pub fn remove_peer(&self, public_key: &WgPublicKey) { - // Dropping it stops the task and closes the link; there is no route - // to withdraw, because routes are not kept here. - write_lock(&self.inner.peers).remove(public_key); + if let Some(peer) = write_lock(&self.inner.peers).remove(public_key) { + peer.stop_reader(); + } } /// Removes every peer whose key is not in `keep`. pub fn retain_peers(&self, keep: &[WgPublicKey]) { - let stale: Vec = read_lock(&self.inner.peers) - .keys() - .filter(|key| !keep.contains(key)) - .copied() - .collect(); - for key in stale { - self.remove_peer(&key); - } + self.retain_links(|_, key, _| keep.contains(key)); + } + + pub(crate) fn retain_links( + &self, + keep: impl Fn(EndpointId, &WgPublicKey, &SharedLink) -> bool, + ) { + write_lock(&self.inner.peers).retain(|key, peer| { + let current = keep(peer.endpoint_id, key, &peer.link); + if !current { + // The reader owns an Arc to the peer while waiting on the link. + peer.stop_reader(); + } + current + }); } /// Whether a peer's tunnel exists. @@ -542,6 +552,7 @@ impl Drop for WireguardDevice { for task in &self.tasks { task.abort(); } + self.retain_peers(&[]); } } diff --git a/crates/tsunagi-wg-quic/src/plugin.rs b/crates/tsunagi-wg-quic/src/plugin.rs index a56c1e0..1ec6f4d 100644 --- a/crates/tsunagi-wg-quic/src/plugin.rs +++ b/crates/tsunagi-wg-quic/src/plugin.rs @@ -180,7 +180,6 @@ struct NetworkState { key: WgSecretKey, device: Option>, announcements: HashMap, - links: HashMap, /// What the network agreed, pushed in by the agent. Authoritative. allocations: HashMap, /// The range those allocations came from. @@ -190,17 +189,15 @@ struct NetworkState { #[derive(Debug, Default)] struct Shared { networks: HashMap, + // A channel can arrive before the network key is loaded. Keep the latest + // handle here so a full notification queue only delays reconciliation. + links: HashMap<(NetworkId, EndpointId), SharedLink>, } #[derive(Debug)] enum Command { Prepare(NetworkId), Sync(NetworkId), - Link { - network: NetworkId, - peer: EndpointId, - link: SharedLink, - }, Teardown(NetworkId), Stop(oneshot::Sender<()>), } @@ -348,7 +345,7 @@ impl WireguardPlugin { endpoint_id: *endpoint_id, public_key: announcement.public_key, overlay_address_v4: state.allocations.get(endpoint_id).copied(), - has_link: state.links.contains_key(endpoint_id), + has_link: shared.links.contains_key(&(network, *endpoint_id)), tunnel: tunnels.get(&announcement.public_key).cloned(), }) .collect(); @@ -440,7 +437,6 @@ impl Worker { key, device: None, announcements: HashMap::new(), - links: HashMap::new(), allocations: HashMap::new(), ipv4_range: None, }); @@ -488,25 +484,34 @@ impl Worker { /// A peer gets a tunnel once both halves have arrived: its announcement, /// which says who it is, and a link, which says packets can reach it. fn sync(&self, network: NetworkId) { - let mut shared = self.lock_shared(); - let Some(state) = shared.networks.get_mut(&network) else { + let shared = self.lock_shared(); + let Some(state) = shared.networks.get(&network) else { return; }; let Some(device) = state.device.clone() else { return; }; - let allocations = state.allocations.clone(); - let mut wanted: Vec = Vec::new(); + // Carrier changes keep the same logical link. A new control session + // gets a different link even when the peer advertises the same WG key. + device.retain_links(|peer, key, installed| { + state + .announcements + .get(&peer) + .is_some_and(|a| a.public_key == *key) + && shared + .links + .get(&(network, peer)) + .is_some_and(|current| Arc::ptr_eq(installed, current) && !current.is_closed()) + }); let mut too_small: Vec<(usize, usize)> = Vec::new(); for (endpoint_id, announcement) in &state.announcements { - let Some(link) = state.links.get(endpoint_id) else { + let Some(link) = shared.links.get(&(network, *endpoint_id)) else { continue; }; if link.is_closed() { continue; } - wanted.push(announcement.public_key); if device.has_peer(&announcement.public_key) { continue; } @@ -523,7 +528,7 @@ impl Worker { // The address comes from the agreed signed state, not from // anything this peer said and not from a derivation: that is what // makes it survive the peer being away. - let peer_v4 = allocations.get(endpoint_id).copied(); + let peer_v4 = state.allocations.get(endpoint_id).copied(); if let Err(err) = device.add_peer( *endpoint_id, @@ -535,8 +540,6 @@ impl Worker { tracing::debug!(%err, "cannot start a WireGuard tunnel"); } } - device.retain_peers(&wanted); - drop(shared); for (available, needed) in too_small { @@ -597,21 +600,13 @@ async fn run(worker: Arc, mut commands: mpsc::Receiver) { Command::Sync(network) => { pending.insert(network); } - Command::Link { network, peer, link } => { - { - let mut shared = worker.lock_shared(); - if let Some(state) = shared.networks.get_mut(&network) { - state.links.insert(peer, link); - } - } - pending.insert(network); - } Command::Teardown(network) => { pending.remove(&network); worker.teardown(network).await; continue; } Command::Stop(reply) => { + worker.lock_shared().links.clear(); for network in worker.known_networks() { worker.teardown(network).await; } @@ -765,23 +760,23 @@ impl IpPlugin for WireguardPlugin { } fn on_peer_link(&self, network: NetworkId, peer: EndpointId, link: SharedLink) { - self.nudge(Command::Link { - network, - peer, - link, - }); + self.worker + .lock_shared() + .links + .insert((network, peer), link); + self.nudge(Command::Sync(network)); } fn on_peer_gone(&self, network: NetworkId, peer: EndpointId) { let removed = { let mut shared = self.worker.lock_shared(); - match shared.networks.get_mut(&network) { - Some(state) => { - let had_link = state.links.remove(&peer).is_some(); - state.announcements.remove(&peer).is_some() || had_link - } - None => false, - } + let had_link = shared.links.remove(&(network, peer)).is_some(); + shared + .networks + .get_mut(&network) + .and_then(|state| state.announcements.remove(&peer)) + .is_some() + || had_link }; if removed { self.nudge(Command::Sync(network)); @@ -789,6 +784,10 @@ impl IpPlugin for WireguardPlugin { } fn on_network_deactivated(&self, network: NetworkId) { + self.worker + .lock_shared() + .links + .retain(|(net, _), _| *net != network); self.nudge(Command::Teardown(network)); } @@ -840,3 +839,58 @@ impl Drop for WireguardPlugin { } } } + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + use tsunagi::dataplane::relay::RelayHub; + + #[tokio::test] + async fn a_burst_of_notifications_keeps_the_latest_logical_link() { + let dir = tempfile::tempdir().unwrap(); + let plugin = WireguardPlugin::open(WireguardConfig::new(dir.path())) + .await + .unwrap(); + let id = NetworkId::from_bytes([9; 32]); + let local = iroh::SecretKey::from_bytes(&[1; 32]).public(); + let peer = iroh::SecretKey::from_bytes(&[2; 32]).public(); + let hub = RelayHub::new(id, local); + let cap = PluginCapability { + protocol: WIREGUARD_PROTOCOL.to_string(), + version: crate::ANNOUNCEMENT_VERSION, + enabled: true, + data: WgAnnouncement::new(id, &WgSecretKey::generate().public()) + .encode() + .unwrap(), + }; + // No yield: the worker cannot drain notifications or reconcile between callbacks. + for _ in 0..plugin.commands.max_capacity() { + plugin.on_network_activated(id); + } + let first = hub.link(peer, WIREGUARD_PROTOCOL); + plugin.on_peer_link(id, peer, first.clone()); + plugin.worker.prepare(id).await.unwrap(); + plugin.on_peer_capability(id, peer, &cap).unwrap(); + let epoch = || { + plugin.worker.sync(id); + plugin.overview(id).unwrap().peers[0] + .tunnel + .as_ref() + .unwrap() + .stats + .counter_epoch + }; + let original = epoch(); + plugin.on_peer_link(id, peer, first); + assert_eq!(epoch(), original, "the same logical link keeps its session"); + + plugin.on_peer_gone(id, peer); + hub.remove_peer(peer); + plugin.on_peer_capability(id, peer, &cap).unwrap(); + plugin.on_peer_link(id, peer, hub.link(peer, WIREGUARD_PROTOCOL)); + assert_ne!(epoch(), original, "reconnect within one reconcile window"); + hub.close(); + plugin.shutdown().await; + } +} diff --git a/crates/tsunagi-wg-quic/tests/wireguard.rs b/crates/tsunagi-wg-quic/tests/wireguard.rs index 0c06548..302a8db 100644 --- a/crates/tsunagi-wg-quic/tests/wireguard.rs +++ b/crates/tsunagi-wg-quic/tests/wireguard.rs @@ -1022,6 +1022,73 @@ async fn a_mesh_of_three_establishes_every_tunnel() { c.shutdown().await; } +#[tokio::test] +async fn a_quick_reconnect_with_the_same_key_restores_packet_delivery() { + let discovery = SharedMemoryDiscovery::new(); + let (name, secret) = network("wg-quick-return"); + // Let the disconnect and the next link arrive in the same reconcile window. + let a = WgAgent::spawn_with(&discovery, "ta", |config| { + config.with_reconcile(Duration::from_secs(2), Duration::from_secs(60)) + }) + .await; + let b = WgAgent::spawn(&discovery, "tb").await; + let id = a.agent.join_network(&name, &secret).await.unwrap(); + b.agent.join_network(&name, &secret).await.unwrap(); + a.wait_for_tunnels(id, 1).await; + b.wait_for_tunnels(id, 1).await; + let before = a.plugin.overview(id).unwrap().peers.remove(0); + let epoch = before.tunnel.unwrap().stats.counter_epoch; + + let mut events = a.agent.subscribe(); + b.agent.deactivate_network(id).await.unwrap(); + wait_event(&mut events, |event| match event { + Event::PeerDisconnected { network, peer, .. } + if *network == id && *peer == b.endpoint_id() => + { + Some(()) + } + _ => None, + }) + .await; + b.agent.activate_network(id).await.unwrap(); + wait_until( + "the same WG key handshakes on the replacement channel", + || async { + let overview = a.plugin.overview(id)?; + let peer = overview + .peers + .iter() + .find(|p| p.endpoint_id == b.endpoint_id())?; + let tunnel = peer.tunnel.as_ref()?; + (peer.public_key == before.public_key + && tunnel.stats.counter_epoch != epoch + && peer.is_up()) + .then_some(()) + }, + ) + .await; + b.wait_for_tunnels(id, 1).await; + + for (sender, receiver) in [(&a, &b), (&b, &a)] { + let packet = ipv4_packet( + sender.overlay(id).await, + receiver.overlay(id).await, + b"after reconnect", + ); + sender.tun(id).await.push_from_os(packet.clone()); + let received = tokio::time::timeout( + tsunagi::testing::DEADLINE, + receiver.tun(id).await.pop_to_os(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(received, packet); + } + a.shutdown().await; + b.shutdown().await; +} + #[tokio::test] async fn a_departing_peer_loses_its_tunnel() { let discovery = SharedMemoryDiscovery::new(); diff --git a/crates/tsunagi/src/main.rs b/crates/tsunagi/src/main.rs index 9505d46..eb9b0ee 100644 --- a/crates/tsunagi/src/main.rs +++ b/crates/tsunagi/src/main.rs @@ -5043,12 +5043,16 @@ fn log_event(event: &Event) { } Event::PeerDisconnected { network, + network_name, peer, + hostname, reason, } => { tracing::info!( network = %network.fmt_short(), + network_name = network_name.as_str(), peer = %peer.fmt_short(), + hostname = hostname.as_deref().map(tracing::field::debug), "Peer disconnected: {reason}" ); }