Keep the selected exit ready and report idle tunnels in 1.0.5

Read the exit network and endpoint from the published routing choice.
Start a normal WireGuard exchange at 120 seconds for that tunnel even
when idle. BoringTun keeps the current key usable during the exchange
and owns retry and expiry. Switching or clearing the route also moves
or removes the renewal policy.

Show Idle in the tray, on Android and in CLI status after 30 seconds
without IP traffic on a previously established tunnel. Keep key changes
and keepalives out of activity, and keep waiting packets, missing paths
and transport errors visible. Preserve queued flow tags when a native
keepalive occupies a slot and drain pending IP on key confirmation.

Bump the local status IPC to 26 and update the workspace, Android and
Nix versions. Upgrade the daemon and desktop clients together. Mesh
protocols, key lifetimes and persistent storage remain compatible.

On macOS arm64 the initial workspace run passed 602 tests. A separate
181-second two-agent test observed renewal only in the selected mesh
and delivered its first internet packet after idle. Formatting and
strict workspace Clippy passed on the release sources. The maintainer
requested publication without waiting for another full test run.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 16:57:10 +02:00
1 parent e3e6089d0b
commit 6a0a87e76c
25 files changed
+506 -130

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-android"
version = "1.0.4"
version = "1.0.5"
description = "Android VPN client and egui views for tsunagi."
edition.workspace = true
rust-version.workspace = true
@@ -16,7 +16,7 @@ name = "vpn_source_probe"
crate-type = ["cdylib"]
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.4" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.5" }
tsunagi-ui = { path = "../tsunagi-ui" }
tsunagi-core = { path = "../tsunagi-core" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-awg"
version = "1.0.4"
version = "1.0.5"
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
edition.workspace = true
rust-version.workspace = true
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-core"
version = "1.0.4"
version = "1.0.5"
description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view."
readme = "../../README.md"
keywords = ["mesh", "p2p", "iroh", "networking"]
+2 -1
View File
@@ -511,7 +511,8 @@ impl Agent {
.tun_factory
.as_ref()
.map(|_| Arc::new(Sink(Arc::downgrade(&inner))) as Arc<dyn PacketSink>);
let context = PluginContext::new(plugin_tx, inner.identity.endpoint_id(), sink);
let context =
PluginContext::new(plugin_tx, inner.identity.endpoint_id(), sink, &inner.routes);
if let Some(tunnel) = &inner.config.tunnel {
tunnel.attach(context);
}
+14 -3
View File
@@ -15,7 +15,7 @@ pub mod relay;
pub mod routing;
pub mod transport;
use std::sync::Arc;
use std::sync::{Arc, Weak};
use iroh::EndpointId;
use tokio::sync::mpsc;
@@ -176,6 +176,7 @@ pub struct PluginContext {
/// Where decrypted packets go. Absent when nothing is carrying traffic,
/// in which case a protocol still runs and its packets are discarded.
sink: Option<Arc<dyn PacketSink>>,
routes: Weak<crate::overlay::RoutingTable>,
}
impl PluginContext {
@@ -183,14 +184,23 @@ impl PluginContext {
sender: mpsc::Sender<PluginRequest>,
local: EndpointId,
sink: Option<Arc<dyn PacketSink>>,
routes: &Arc<crate::overlay::RoutingTable>,
) -> Self {
Self {
sender: Some(sender),
local: Some(local),
sink,
routes: Arc::downgrade(routes),
}
}
/// The peer whose tunnel should stay ready for traffic even while idle.
/// Only the locally selected internet exit in its own network qualifies.
pub fn warm_peer(&self, network: NetworkId) -> Option<EndpointId> {
let (selected, peer) = self.routes.upgrade()?.exit_via()?;
(selected == network).then_some(peer)
}
/// Where to hand a decrypted packet.
///
/// Always answers: with no interface to write to, the packets are
@@ -208,15 +218,15 @@ impl PluginContext {
sender: None,
local: None,
sink: None,
routes: Weak::new(),
}
}
/// A context configured with a custom packet sink.
pub fn with_sink(sink: Arc<dyn PacketSink>) -> Self {
Self {
sender: None,
local: None,
sink: Some(sink),
..Self::detached()
}
}
@@ -231,6 +241,7 @@ impl PluginContext {
sender: Some(sender),
local: Some(local),
sink,
..Self::detached()
}
}
+6 -4
View File
@@ -940,10 +940,12 @@ pub struct OverlayPeerReport {
pub public_key: String,
/// The overlay address the network agreed it holds.
pub address: Option<String>,
/// Seconds since the last WireGuard handshake.
///
/// `None` means the tunnel has never handshaken and cannot carry traffic.
/// Seconds since the last WireGuard handshake while its session key is usable.
pub handshake_secs_ago: Option<u64>,
/// An established tunnel has no recent or pending IP traffic. An expired
/// key on a tunnel required to stay warm is reported as waiting instead.
#[serde(default)]
pub idle: bool,
/// Packets encrypted and sent to this peer.
pub tx_packets: u64,
/// Packets decrypted from this peer.
@@ -1145,7 +1147,7 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
///
/// Bump it whenever [`Request`], [`Response`] or anything they contain
/// changes shape.
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 25]);
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 26]);
/// Reads one request off an accepted stream, answers it, writes the response.
///
+30 -1
View File
@@ -383,7 +383,10 @@ impl RoutingTable {
///
/// Choosing another exit replaces the previous one under the table's write lock.
pub fn exit_via(&self) -> Option<(NetworkId, EndpointId)> {
exit_via(&self.read())
self.selected_exit
.load()
.as_ref()
.map(|exit| (exit.route.network, exit.route.peer))
}
/// Whether a default route is selected and the local source valid in that network.
@@ -857,6 +860,32 @@ mod tests {
const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34);
#[test]
fn tunnel_warming_follows_the_selected_membership_on_restore_switch_and_off() {
let table = Arc::new(RoutingTable::new());
let (tx, _rx) = tokio::sync::mpsc::channel(1);
let context = crate::dataplane::PluginContext::new(tx, peer(1), None, &table);
let (a, b) = (network("left"), network("right"));
let exit = peer(2);
table.set_network(a, with_exit(false, Some(exit))).unwrap();
table.set_network(b, NetworkRoutes::default()).unwrap();
assert_eq!(context.warm_peer(a), Some(exit));
assert_eq!(context.warm_peer(b), None);
let select = |via| ExitPolicy { offer: true, via };
table.set_exit(b, select(Some(exit)));
assert_eq!(context.warm_peer(a), None);
assert_eq!(context.warm_peer(b), Some(exit));
table.set_exit(b, select(None));
assert_eq!(
context.warm_peer(b),
None,
"offering an exit does not select one"
);
table.set_exit(a, select(Some(exit)));
table.remove_network(a);
assert_eq!(context.warm_peer(a), None);
}
#[test]
fn refreshing_either_networks_addresses_preserves_the_last_exit_choice() {
let table = RoutingTable::new();
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-runtime"
version = "1.0.4"
version = "1.0.5"
description = "Built-in mesh transports and status reporting for native tsunagi agents."
edition.workspace = true
rust-version.workspace = true
@@ -8,11 +8,11 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.4" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.4" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.4" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.4" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.5" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.5" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.5" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.5" }
tokio.workspace = true
tracing.workspace = true
+1
View File
@@ -35,6 +35,7 @@ pub fn networks(
address: peer.overlay_address_v4.map(|a| a.to_string()),
handshake_secs_ago: tunnel
.and_then(|t| t.health.since_handshake.map(|s| s.as_secs())),
idle: tunnel.is_some_and(|t| t.health.idle),
tx_packets: tunnel.map_or(0, |t| t.stats.tx_packets),
rx_packets: tunnel.map_or(0, |t| t.stats.rx_packets),
tx_bytes: tunnel.map_or(0, |t| t.stats.tx_bytes),
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-tcp-tls"
version = "1.0.4"
version = "1.0.5"
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
edition.workspace = true
rust-version.workspace = true
@@ -8,7 +8,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
rustls = "0.23"
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-tray"
version = "1.0.4"
version = "1.0.5"
description = "Tray application to manage a running tsunagi agent."
edition.workspace = true
rust-version.workspace = true
@@ -16,7 +16,7 @@ tsunagi-ui = { path = "../tsunagi-ui" }
# The agent control client and the report types: the GUI is a thin client over
# the same local control interface the CLI uses, so it reuses these directly
# and never re-implements the protocol.
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
# Native, lightweight GUI — no web engine. eframe re-exports egui.
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] }
# Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI).
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-ui"
version = "1.0.4"
version = "1.0.5"
description = "Shared egui widgets for the tray and Android clients."
edition.workspace = true
rust-version.workspace = true
+9 -5
View File
@@ -4,6 +4,7 @@ use tsunagi::agent::{DATA_CONNECTING, DATA_DISABLED};
#[derive(Copy, Clone, PartialEq, Eq)]
pub(super) enum Channel {
Ready,
Idle,
Waiting,
Error,
Offline,
@@ -19,11 +20,9 @@ impl Device<'_> {
Some(DATA_DISABLED) => Channel::Disabled,
Some(DATA_CONNECTING) => Channel::Waiting,
Some(_) => Channel::Error,
None if self.overlay.is_some_and(|p| p.is_up())
&& !matches!(self.path, None | Some(DataPathReport::None)) =>
{
Channel::Ready
}
None if matches!(self.path, None | Some(DataPathReport::None)) => Channel::Waiting,
None if self.overlay.is_some_and(|p| p.idle) => Channel::Idle,
None if self.overlay.is_some_and(|p| p.is_up()) => Channel::Ready,
None => Channel::Waiting,
}
}
@@ -31,6 +30,7 @@ impl Device<'_> {
match self.channel() {
Channel::Offline => "Offline · peer unreachable",
Channel::Ready => "Ready · encrypted data channel available",
Channel::Idle => "Idle · online, no recent IP traffic",
Channel::Waiting => "Waiting for the encrypted data channel",
Channel::Disabled => "Control only · data transports disabled locally",
Channel::Error => self.data_error.unwrap_or("Data channel error"),
@@ -41,6 +41,7 @@ impl Channel {
pub(super) fn label(self) -> &'static str {
match self {
Self::Ready => "Ready",
Self::Idle => "Idle",
Self::Waiting => "Waiting",
Self::Error => "Error",
Self::Offline => "Offline",
@@ -52,6 +53,8 @@ impl Channel {
match (self, ui.visuals().dark_mode) {
(Self::Ready, true) => Color32::from_rgb(100, 210, 136),
(Self::Ready, false) => Color32::from_rgb(25, 120, 61),
(Self::Idle, true) => Color32::from_rgb(145, 176, 200),
(Self::Idle, false) => Color32::from_rgb(64, 99, 125),
(Self::Waiting, true) => Color32::from_rgb(244, 190, 85),
(Self::Waiting, false) => Color32::from_rgb(150, 94, 8),
(Self::Error, true) => Color32::from_rgb(255, 129, 116),
@@ -67,6 +70,7 @@ impl Channel {
let color = self.color(ui);
let glyph = match self {
Self::Ready => icon::CHECK_CIRCLE,
Self::Idle => icon::MOON,
Self::Error => icon::WARNING,
Self::Offline => icon::MINUS_CIRCLE,
Self::Disabled => icon::PAUSE_CIRCLE,
+20 -7
View File
@@ -29,6 +29,7 @@ fn keyboard_focus_explains_an_icon_and_the_shared_font_contains_the_status_glyph
icon::WARNING,
icon::MINUS_CIRCLE,
icon::PAUSE_CIRCLE,
icon::MOON,
icon::SIGN_OUT,
icon::FINGERPRINT,
icon::HASH,
@@ -163,6 +164,7 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
("charlie", "error"),
("delta", "offline"),
("echo", "control only"),
("foxtrot", "idle"),
] {
net.members.push(MemberReport {
endpoint_id: id.into(),
@@ -189,14 +191,24 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
});
}
}
net.overlay = Some(OverlayReport {
peers: vec![OverlayPeerReport {
endpoint_id: "alpha".into(),
handshake_secs_ago: Some(2),
tx_bytes: 2048,
rx_bytes: 512,
let mut overlay_peers = vec![OverlayPeerReport {
endpoint_id: "alpha".into(),
handshake_secs_ago: Some(2),
tx_bytes: 2048,
rx_bytes: 512,
..Default::default()
}];
// Only the reachable peer with a healthy path may show Idle. A problem
// or an offline observation takes precedence over quiet IP counters.
overlay_peers.extend(["bravo", "charlie", "delta", "echo", "foxtrot"].map(|id| {
OverlayPeerReport {
endpoint_id: id.into(),
idle: true,
..Default::default()
}],
}
}));
net.overlay = Some(OverlayReport {
peers: overlay_peers,
..Default::default()
});
let draw = |size, time, events| {
@@ -232,6 +244,7 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
"bytes (TX / RX)",
"2.0 kB / 512 B",
"Ready",
"Idle",
"Waiting",
"Error",
"Offline",
+2 -2
View File
@@ -3,7 +3,7 @@ name = "tsunagi-wg-quic"
# Its own version, and deliberately separate from the wire version it
# negotiates: a release here does not stop it talking to a peer on an older
# build, because what peers compare is `ANNOUNCEMENT_VERSION`.
version = "1.0.4"
version = "1.0.5"
description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
edition.workspace = true
rust-version.workspace = true
@@ -11,7 +11,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
iroh.workspace = true
tokio.workspace = true
serde.workspace = true
+240 -48
View File
@@ -32,7 +32,7 @@ use std::collections::{HashMap, VecDeque};
use std::net::Ipv4Addr;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration;
use std::time::{Duration, Instant};
use boringtun::noise::{Tunn, TunnResult};
use bytes::Bytes;
@@ -41,7 +41,7 @@ use tokio::task::JoinHandle;
use tsunagi::dataplane::routing::{FlowId, flow::ip_flow};
use tsunagi::dataplane::transport::{SharedLink, TransportError};
use tsunagi::dataplane::{PacketSink, PluginError};
use tsunagi::dataplane::{PacketSink, PluginContext, PluginError};
use tsunagi::identity::NetworkId;
use crate::keys::{WgPublicKey, WgSecretKey};
@@ -52,6 +52,11 @@ use crate::keys::{WgPublicKey, WgSecretKey};
/// drives handshakes, rekeying and keepalives.
const TIMER_INTERVAL: Duration = Duration::from_millis(250);
/// Start renewing the selected exit at WireGuard's normal rekey age. The
/// current key can still carry data for a minute while its successor is agreed.
const WARM_REKEY_AFTER: Duration = Duration::from_secs(120);
const IDLE_AFTER: Duration = Duration::from_secs(30);
/// Scratch space for one encapsulate or decapsulate call.
const SCRATCH: usize = 4096;
@@ -60,10 +65,13 @@ const SCRATCH: usize = 4096;
struct FlowTunnel {
tunn: Tunn,
queued: VecDeque<(FlowId, usize)>,
/// First usable session or most recent IP payload. Keepalives and later
/// handshakes leave this alone, including when the current key expires.
last_activity: Option<Instant>,
}
fn is_data(result: &TunnResult<'_>) -> bool {
matches!(result, TunnResult::WriteToNetwork(bytes) if bytes.starts_with(&[4, 0, 0, 0]))
fn carries_ip(frame: &[u8]) -> bool {
frame.len() > crate::plugin::WIREGUARD_OVERHEAD as usize && frame.starts_with(&[4, 0, 0, 0])
}
impl FlowTunnel {
@@ -74,7 +82,11 @@ impl FlowTunnel {
flow: FlowId,
) -> (TunnResult<'a>, FlowId) {
let result = self.tunn.encapsulate(packet, scratch);
if is_data(&result) {
if packet.is_empty() {
return (result, 0);
}
if matches!(&result, TunnResult::WriteToNetwork(out) if carries_ip(out)) {
self.last_activity = Some(Instant::now());
return (result, flow);
}
// MAX_QUEUE_DEPTH in boringtun 0.7: the newest packet is dropped at 256.
@@ -89,32 +101,83 @@ impl FlowTunnel {
packet: &[u8],
scratch: &'a mut [u8],
) -> (TunnResult<'a>, FlowId, Option<usize>) {
// Empty input asks BoringTun to drain its FIFO. Wait for a usable key
// so a failed drain cannot reorder IP packets among queued keepalives.
if packet.is_empty() && self.tunn.time_since_last_handshake().is_none() {
return (TunnResult::Done, 0, None);
}
let result = self.tunn.decapsulate(None, packet, scratch);
let (mut flow, mut plaintext_len) = (0, None);
if packet.is_empty() {
if is_data(&result) {
if let Some((tag, len)) = self.queued.pop_front() {
flow = tag;
plaintext_len = Some(len);
match &result {
TunnResult::WriteToNetwork(out) if carries_ip(out) => {
if let Some((tag, len)) = self.queued.pop_front() {
flow = tag;
plaintext_len = Some(len);
}
}
} else if let Some(pending) = self.queued.pop_front() {
// Without a session, draining pops the oldest IP packet and
// encapsulate queues it again at the back.
self.queued.push_back(pending);
// An internal keepalive may occupy a slot in the bounded
// FIFO. Discard tags for IP packets BoringTun could not queue.
TunnResult::Done => self.queued.clear(),
_ => {}
}
}
if matches!(
result,
TunnResult::WriteToTunnelV4(..) | TunnResult::WriteToTunnelV6(..)
) || plaintext_len.is_some()
|| (self.last_activity.is_none() && self.tunn.time_since_last_handshake().is_some())
{
self.last_activity = Some(Instant::now());
}
(result, flow, plaintext_len)
}
fn update_timers<'a>(&mut self, scratch: &'a mut [u8]) -> TunnResult<'a> {
let result = self.tunn.update_timers(scratch);
if matches!(
result,
TunnResult::Err(boringtun::noise::errors::WireGuardError::ConnectionExpired)
) {
self.queued.clear();
fn health(&self, now: Instant, keep_warm: bool) -> PeerHealth {
let since_handshake = self.tunn.time_since_last_handshake();
let idle = self.queued.is_empty()
&& (!keep_warm || since_handshake.is_some())
&& self
.last_activity
.is_some_and(|at| now.duration_since(at) >= IDLE_AFTER);
PeerHealth {
since_handshake,
idle,
}
}
fn update_timers(
&mut self,
scratch: &mut [u8],
refresh_after: Option<Duration>,
) -> Option<usize> {
match self.tunn.update_timers(scratch) {
TunnResult::WriteToNetwork(out) => return Some(out.len()),
TunnResult::Err(boringtun::noise::errors::WireGuardError::ConnectionExpired) => {
if !self.queued.is_empty() {
// BoringTun gave up on pending IP packets. Keep reporting
// a waiting tunnel until a new session actually succeeds.
self.last_activity = None;
self.queued.clear();
}
}
TunnResult::Err(err) => tracing::trace!(?err, "wireguard timer produced an error"),
_ => {}
}
let after = refresh_after?;
if self
.tunn
.time_since_last_handshake()
.is_some_and(|age| age < after)
{
return None;
}
// An in-flight exchange and its retries remain under BoringTun's
// timers. Asking without forcing never restarts one.
match self.tunn.format_handshake_initiation(scratch, false) {
TunnResult::WriteToNetwork(out) => Some(out.len()),
_ => None,
}
result
}
}
@@ -164,15 +227,14 @@ pub struct PeerStats {
/// Whether a peer's tunnel has completed a handshake.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PeerHealth {
/// Time since the last successful WireGuard handshake.
///
/// `None` means no handshake has completed yet, so the tunnel is not
/// carrying traffic. This is reported as it is, never guessed.
/// Age of the last handshake while a usable WireGuard session exists.
pub since_handshake: Option<Duration>,
/// A previously established tunnel with no recent or queued IP traffic.
pub idle: bool,
}
impl PeerHealth {
/// Whether the tunnel has ever completed a handshake.
/// Whether the tunnel currently has a usable session key.
pub fn is_up(&self) -> bool {
self.since_handshake.is_some()
}
@@ -227,14 +289,12 @@ impl Peer {
}
}
fn health(&self) -> PeerHealth {
fn health(&self, keep_warm: bool) -> PeerHealth {
let guard = match self.tunn.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
PeerHealth {
since_handshake: guard.tunn.time_since_last_handshake(),
}
guard.health(Instant::now(), keep_warm)
}
}
@@ -259,6 +319,7 @@ pub struct PeerSummary {
struct Inner {
network: NetworkId,
context: PluginContext,
private_key: WgSecretKey,
peers: RwLock<HashMap<WgPublicKey, Arc<Peer>>>,
/// Where decrypted packets go.
@@ -292,11 +353,20 @@ impl WireguardDevice {
/// leave through the sink. Which address belongs to whom, and therefore
/// where a packet should go, is decided above this.
pub fn start(network: NetworkId, private_key: WgSecretKey, sink: Arc<dyn PacketSink>) -> Self {
Self::start_with_context(network, private_key, PluginContext::with_sink(sink))
}
pub(crate) fn start_with_context(
network: NetworkId,
private_key: WgSecretKey,
context: PluginContext,
) -> Self {
let inner = Arc::new(Inner {
network,
private_key,
peers: RwLock::new(HashMap::new()),
sink,
sink: context.packet_sink(),
context,
next_index: AtomicU32::new(1),
});
@@ -336,7 +406,7 @@ impl WireguardDevice {
let (result, selected_flow) = tunn.encapsulate(packet, &mut scratch, flow);
match result {
TunnResult::WriteToNetwork(out) => {
Some((out.len(), selected_flow, out.starts_with(&[4, 0, 0, 0])))
Some((out.len(), selected_flow, carries_ip(out)))
}
// No session yet, so nothing to send. Counted as dropped
// rather than reported: the handshake is in flight and the
@@ -394,6 +464,7 @@ impl WireguardDevice {
tunn: Mutex::new(FlowTunnel {
tunn,
queued: VecDeque::new(),
last_activity: None,
}),
link,
counters: Arc::new(PeerCounters {
@@ -442,6 +513,7 @@ impl WireguardDevice {
/// A snapshot of every peer.
pub fn peers(&self) -> Vec<PeerSummary> {
let warm_peer = self.inner.context.warm_peer(self.inner.network);
let mut peers: Vec<PeerSummary> = read_lock(&self.inner.peers)
.values()
.map(|peer| {
@@ -453,7 +525,7 @@ impl WireguardDevice {
endpoint_id: peer.endpoint_id,
public_key: peer.public_key,
overlay_address_v4: overlay_v4,
health: peer.health(),
health: peer.health(warm_peer == Some(peer.endpoint_id)),
stats: peer.stats(),
path: peer.link.path_description(),
max_datagram: peer.link.max_datagram_size(),
@@ -546,14 +618,14 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
// any packets that were queued while the session was coming up.
let mut input: Option<&[u8]> = Some(&datagram);
loop {
let outcome = {
let (outcome, drain_pending) = {
let mut tunn = match peer.tunn.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
let (result, flow, plaintext_len) =
tunn.decapsulate(input.unwrap_or(&[]), &mut scratch);
match result {
let outcome = match result {
TunnResult::WriteToNetwork(out) => {
Outcome::ToNetwork(out.len(), flow, plaintext_len)
}
@@ -567,7 +639,8 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
tracing::trace!(?err, "wireguard decapsulation failed");
Outcome::Failed
}
}
};
(outcome, input.is_some() && !tunn.queued.is_empty())
};
match outcome {
@@ -595,7 +668,6 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
peer.counters
.rx_bytes
.fetch_add(len as u64, Ordering::Relaxed);
break;
}
Outcome::Failed => {
peer.counters
@@ -603,8 +675,14 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
.fetch_add(1, Ordering::Relaxed);
break;
}
Outcome::Done => break,
Outcome::Done => {}
}
// A responder can first confirm its key on an incoming keepalive
// or IP packet. Flush waiting application traffic on that path too.
if !drain_pending {
break;
}
input = None;
}
}
}
@@ -620,24 +698,20 @@ enum Outcome {
async fn drive_timers(inner: Arc<Inner>) {
let mut ticker = tokio::time::interval(TIMER_INTERVAL);
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut scratch = vec![0u8; SCRATCH];
loop {
ticker.tick().await;
let warm_peer = inner.context.warm_peer(inner.network);
let peers: Vec<Arc<Peer>> = read_lock(&inner.peers).values().cloned().collect();
for peer in peers {
let mut scratch = vec![0u8; SCRATCH];
let len = {
let mut tunn = match peer.tunn.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
match tunn.update_timers(&mut scratch) {
TunnResult::WriteToNetwork(out) => Some(out.len()),
TunnResult::Err(err) => {
tracing::trace!(?err, "wireguard timer produced an error");
None
}
_ => None,
}
let refresh_after =
(warm_peer == Some(peer.endpoint_id)).then_some(WARM_REKEY_AFTER);
tunn.update_timers(&mut scratch, refresh_after)
};
if let Some(len) = len {
send_to_peer(&peer, &scratch[..len]);
@@ -662,6 +736,7 @@ mod flow_tests {
None,
),
queued: VecDeque::new(),
last_activity: None,
}
}
fn wire(result: TunnResult<'_>) -> Vec<u8> {
@@ -671,6 +746,123 @@ mod flow_tests {
}
}
fn establish(a: &mut FlowTunnel, b: &mut FlowTunnel, scratch: &mut [u8]) {
let hello = wire(a.tunn.format_handshake_initiation(scratch, false));
let response = wire(b.decapsulate(&hello, scratch).0);
let confirmation = wire(a.decapsulate(&response, scratch).0);
let _ = b.decapsulate(&confirmation, scratch);
}
#[test]
fn only_a_due_warm_tunnel_rekeys_and_the_old_key_carries_data_during_the_exchange() {
let ak = WgSecretKey::from_bytes(&[1; 32]);
let bk = WgSecretKey::from_bytes(&[2; 32]);
let (mut a, mut b) = (tunnel(&ak, &bk), tunnel(&bk, &ak));
let mut scratch = [0u8; SCRATCH];
establish(&mut a, &mut b, &mut scratch);
assert!(a.update_timers(&mut scratch, None).is_none());
assert!(
a.update_timers(&mut scratch, Some(WARM_REKEY_AFTER))
.is_none()
);
// Make the renewal due now, then withhold its response. BoringTun still
// owns both generations of keys and its normal retry timer.
let len = a.update_timers(&mut scratch, Some(Duration::ZERO)).unwrap();
let hello = scratch[..len].to_vec();
assert_eq!(&hello[..4], &[1, 0, 0, 0]);
assert!(
a.update_timers(&mut scratch, Some(Duration::ZERO))
.is_none()
);
let mut ip = [0u8; 20];
ip[0] = 0x45;
ip[2..4].copy_from_slice(&20u16.to_be_bytes());
for generation in 0..2 {
ip[19] = generation;
let ciphertext = wire(a.encapsulate(&ip, &mut scratch, 7).0);
assert!(matches!(b.decapsulate(&ciphertext, &mut scratch).0,
TunnResult::WriteToTunnelV4(bytes, _) if bytes == ip));
if generation == 0 {
let reply = wire(b.decapsulate(&hello, &mut scratch).0);
let confirmation = wire(a.decapsulate(&reply, &mut scratch).0);
let _ = b.decapsulate(&confirmation, &mut scratch);
}
}
assert!(a.queued.is_empty());
}
#[test]
fn idle_survives_background_handshakes_but_never_hides_pending_ip_or_a_cold_exit() {
let ak = WgSecretKey::from_bytes(&[1; 32]);
let bk = WgSecretKey::from_bytes(&[2; 32]);
let (mut a, mut b) = (tunnel(&ak, &bk), tunnel(&bk, &ak));
let mut scratch = [0u8; SCRATCH];
assert!(!a.health(Instant::now() + IDLE_AFTER, false).idle);
establish(&mut a, &mut b, &mut scratch);
assert!(!a.health(Instant::now(), false).idle);
let activity = (a.last_activity, b.last_activity);
let idle_at = Instant::now() + IDLE_AFTER;
assert!(a.health(idle_at, true).idle);
establish(&mut a, &mut b, &mut scratch);
assert_eq!((a.last_activity, b.last_activity), activity);
assert!(a.health(idle_at, true).idle);
assert!(b.health(idle_at, false).idle);
let mut ip = [0u8; 20];
ip[0] = 0x45;
ip[2..4].copy_from_slice(&20u16.to_be_bytes());
let ciphertext = wire(a.encapsulate(&ip, &mut scratch, 7).0);
let _ = b.decapsulate(&ciphertext, &mut scratch);
assert!(!a.health(Instant::now(), false).idle);
assert!(!b.health(Instant::now(), false).idle);
assert!(a.last_activity > activity.0 && b.last_activity > activity.1);
// Discard BoringTun's session keys to exercise an idle tunnel with no
// usable key and the first IP packet that has to wait for a new one.
a.tunn
.set_static_private(ak.to_static_secret(), ak.public().into_x25519(), None);
let idle_at = Instant::now() + IDLE_AFTER;
assert!(a.health(idle_at, false).idle);
assert!(!a.health(idle_at, true).idle);
let _ = a.encapsulate(&ip, &mut scratch, 7);
assert!(!a.health(idle_at, false).idle);
}
#[test]
fn draining_a_queued_keepalive_preserves_ip_flow_tags_and_eventually_goes_idle() {
let ak = WgSecretKey::from_bytes(&[1; 32]);
let bk = WgSecretKey::from_bytes(&[2; 32]);
let (mut a, mut b) = (tunnel(&ak, &bk), tunnel(&bk, &ak));
let mut scratch = [0u8; SCRATCH];
// This is what BoringTun's persistent keepalive timer does with no key.
let hello = wire(a.tunn.encapsulate(&[], &mut scratch));
let mut ip = [0u8; 20];
ip[0] = 0x45;
ip[2..4].copy_from_slice(&20u16.to_be_bytes());
for flow in 1..=256 {
let _ = a.encapsulate(&ip, &mut scratch, flow);
}
let reply = wire(b.decapsulate(&hello, &mut scratch).0);
let _ = a.decapsulate(&reply, &mut scratch);
let (keepalive, flow, bytes) = a.decapsulate(&[], &mut scratch);
assert_eq!(
wire(keepalive).len(),
crate::plugin::WIREGUARD_OVERHEAD as usize
);
assert_eq!((flow, bytes), (0, None));
for expected in 1..=255 {
let (data, flow, bytes) = a.decapsulate(&[], &mut scratch);
assert!(carries_ip(&wire(data)));
assert_eq!((flow, bytes), (expected, Some(ip.len())));
}
assert!(matches!(
a.decapsulate(&[], &mut scratch).0,
TunnResult::Done
));
assert!(a.health(Instant::now() + IDLE_AFTER, false).idle);
}
#[test]
fn flow_tags_survive_pending_queue_overflow_handshake_and_encryption() {
let ak = WgSecretKey::from_bytes(&[1; 32]);
@@ -716,7 +908,7 @@ mod flow_tests {
TunnResult::Done
));
let (result, flow) = a.encapsulate(&packet, &mut scratch, 12345);
assert!(is_data(&result));
assert!(carries_ip(&wire(result)));
assert_eq!(flow, 12345);
}
}
+6 -12
View File
@@ -35,7 +35,6 @@ use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tsunagi::BoxFuture;
use tsunagi::dataplane::PacketSink;
use tsunagi::dataplane::transport::SharedLink;
use tsunagi::dataplane::{IpPlugin, PluginCapability, PluginContext, PluginError};
use tsunagi::identity::NetworkId;
@@ -213,8 +212,6 @@ struct Worker {
store: WgKeyStore,
shared: Mutex<Shared>,
context: OnceLock<PluginContext>,
/// Where decrypted packets go, once the agent has attached one.
sink: OnceLock<Arc<dyn PacketSink>>,
}
impl std::fmt::Debug for Worker {
@@ -315,7 +312,6 @@ impl WireguardPlugin {
store,
shared: Mutex::new(Shared::default()),
context: OnceLock::new(),
sink: OnceLock::new(),
});
let (commands, receiver) = mpsc::channel(64);
@@ -473,13 +469,12 @@ impl Worker {
}
};
let sink = match self.sink.get() {
Some(sink) => Arc::clone(sink),
// Not attached to an agent: the protocol still runs, and its
// packets have nowhere to go.
None => Arc::new(tsunagi::dataplane::DiscardPackets) as Arc<dyn PacketSink>,
};
let device = Arc::new(WireguardDevice::start(network, key, sink));
let context = self
.context
.get()
.cloned()
.unwrap_or_else(PluginContext::detached);
let device = Arc::new(WireguardDevice::start_with_context(network, key, context));
let mut shared = self.lock_shared();
if let Some(state) = shared.networks.get_mut(&network) {
@@ -668,7 +663,6 @@ impl IpPlugin for WireguardPlugin {
if let Some(local) = context.local_endpoint_id() {
let _ = self.worker.local_id.set(local);
}
let _ = self.worker.sink.set(context.packet_sink());
let _ = self.worker.context.set(context);
}
+90 -6
View File
@@ -310,22 +310,106 @@ async fn switching_the_exit_between_networks_keeps_both_overlays_reachable() {
live.peer.agent.shutdown().await;
}
#[tokio::test]
async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() {
async fn shared_nodes() -> (Node, Node) {
let discovery = SharedMemoryDiscovery::new();
let client = Node::open(TempDir::new().unwrap(), &discovery, "client", None).await;
let dir = TempDir::new().unwrap();
let config = tsunagi::testing::config_with(dir.path(), &discovery);
let peer = Node::start(dir, "shared", config).await;
(client, peer)
}
async fn shared_networks<'a>(client: &Node, peer: &'a Node) -> [ExitNetwork<'a>; 2] {
// Fixed credentials keep the two automatically derived /24s distinct.
let mut meshes = Vec::new();
for (name, secret) in [("shared-left", [1; 32]), ("shared-right", [2; 32])] {
let join = |name, secret| {
let credentials = (
NetworkName::new(name).unwrap(),
NetworkSecret::from_bytes(secret).unwrap(),
);
meshes.push(ExitNetwork::join(&client, &peer, credentials).await);
}
ExitNetwork::join(client, peer, credentials)
};
[
join("shared-left", [1; 32]).await,
join("shared-right", [2; 32]).await,
]
}
#[tokio::test]
#[ignore = "observes a full 180-second WireGuard key lifetime on real clocks"]
async fn only_the_selected_exit_stays_keyed_through_idle_expiry() {
let (client, peer) = shared_nodes().await;
let [chosen, other] = shared_networks(&client, &peer).await;
client
.agent
.set_exit_via(chosen.id, Some(peer.id()))
.await
.unwrap();
let tunnel = |network| {
client
.plugin
.overview(network)
.unwrap()
.peers
.into_iter()
.find(|p| p.endpoint_id == peer.id())
.unwrap()
.tunnel
.unwrap()
};
let epoch = tunnel(chosen.id).stats.counter_epoch;
let mut old_key_seen = false;
tokio::time::timeout(Duration::from_secs(210), async {
let mut poll = tokio::time::interval(Duration::from_millis(500));
loop {
poll.tick().await;
let warm = tunnel(chosen.id);
let cold = tunnel(other.id);
assert_eq!(warm.stats.counter_epoch, epoch);
let warm_age = warm
.health
.since_handshake
.expect("usable exit key throughout idle");
assert_eq!((warm.stats.tx_bytes, warm.stats.rx_bytes), (0, 0));
assert_eq!((cold.stats.tx_bytes, cold.stats.rx_bytes), (0, 0));
if cold
.health
.since_handshake
.is_some_and(|age| age >= Duration::from_secs(150))
{
old_key_seen = true;
}
if old_key_seen && !cold.health.is_up() {
assert!(
warm_age < Duration::from_secs(90),
"exit key renewed before expiry"
);
assert!(warm.health.idle && cold.health.idle);
break;
}
}
})
.await
.expect("unselected peer's unused session expired");
let packet = ipv4_packet(chosen.client_addr, INTERNET, b"first IP packet after idle");
client.tun().await.push_from_os(packet.clone());
assert_eq!(next(&chosen.peer_tun).await, packet);
assert!(!tunnel(chosen.id).health.idle);
client
.agent
.set_exit_via(other.id, Some(peer.id()))
.await
.unwrap();
client.wait_for_tunnels(other.id, 1).await;
assert!(tunnel(other.id).health.idle, "warming sends no IP payload");
client.agent.shutdown().await;
peer.agent.shutdown().await;
}
#[tokio::test]
async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() {
let (client, peer) = shared_nodes().await;
let meshes = shared_networks(&client, &peer).await;
let tun = client.tun().await;
for (chosen, other) in [(&meshes[0], &meshes[1]), (&meshes[1], &meshes[0])] {
client
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-wireguard"
version = "1.0.4"
version = "1.0.5"
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
edition.workspace = true
rust-version.workspace = true
@@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0"
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
serde.workspace = true
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi"
version = "1.0.4"
version = "1.0.5"
description = "The tsunagi command line agent."
edition.workspace = true
rust-version.workspace = true
@@ -12,11 +12,11 @@ name = "tsng"
path = "src/main.rs"
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.4" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.4" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.4" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.4" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.5" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.5", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.5" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.5" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.5" }
iroh.workspace = true
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
tracing.workspace = true
+42 -6
View File
@@ -3884,12 +3884,17 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
),
Some(DataPathReport::None) | None => ("connected · no data path yet".to_string(), false),
};
let idle = data_path_good && row.data_error.is_none() && row.tunnel.is_some_and(|t| t.idle);
let show_counters = tunnel_up || idle;
let mut detail = String::new();
if let Some(v4) = row.overlay_address_v4 {
detail.push_str(&format!("{v4:<15} "));
}
detail.push_str(&path);
if idle {
detail.push_str(" · idle");
}
if let Some(rtt) = row.data_rtt_ms {
detail.push_str(&format!(" data RTT {rtt}ms"));
}
@@ -3906,7 +3911,7 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
}
detail.extend(taken);
let health = if !data_path_good || row.data_error.is_some() || (has_overlay && !tunnel_up) {
let health = if !data_path_good || row.data_error.is_some() || (has_overlay && !show_counters) {
Health::Degraded
} else {
Health::Good
@@ -3916,12 +3921,12 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
if let Some(reason) = row.data_error {
out = out.with_note(reason.to_owned());
}
if !tunnel_up && let Some(path) = row.data_transport_detail {
if !show_counters && let Some(path) = row.data_transport_detail {
out = out.with_note(path.to_owned());
}
if let Some(tunnel) = row.tunnel {
out = out.with_note(match tunnel.handshake_secs_ago {
Some(_) => format!(
out = out.with_note(if show_counters {
format!(
"tx {} rx {} · IP bytes ↑{} ↓{}{} · {}",
tunnel.tx_packets,
tunnel.rx_packets,
@@ -3933,8 +3938,9 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
String::new()
},
row.data_transport_detail.unwrap_or(&tunnel.path)
),
None => "encrypted data channel is not ready yet".into(),
)
} else {
"encrypted data channel is not ready yet".into()
});
}
out
@@ -5773,6 +5779,36 @@ mod status_tests {
);
}
#[test]
fn an_idle_peer_keeps_its_counters_and_a_missing_route_is_still_degraded() {
let mut network = network_after_a_peer_returned();
let mut quiet = tunnel(ONLINE, None);
quiet.idle = true;
network.overlay = Some(overlay(vec![quiet]));
for (path, health) in [
(
tsunagi::ipc::DataPathReport::Direct {
transport: "wg".into(),
},
Health::Good,
),
(tsunagi::ipc::DataPathReport::None, Health::Degraded),
] {
network.peers[0].path = path.clone();
network.members[1].path = path;
let mut report = report::Report::new();
report.push(network_section(&network, OWN, false));
let text = report.render(false);
assert_eq!(report.worst(), health, "{text}");
if health == Health::Good {
assert!(
text.contains("idle") && text.contains("tx 32 rx 887"),
"{text}"
);
}
}
}
#[test]
fn handshake_failures_with_nobody_connected_point_at_the_secret() {
// The classic symptom of one member being given a different secret.