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

Generated
+10 -10
View File
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]] [[package]]
name = "tsunagi" name = "tsunagi"
version = "1.0.4" version = "1.0.5"
dependencies = [ dependencies = [
"anstream", "anstream",
"anstyle", "anstyle",
@@ -6320,7 +6320,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-android" name = "tsunagi-android"
version = "1.0.4" version = "1.0.5"
dependencies = [ dependencies = [
"bytes", "bytes",
"egui", "egui",
@@ -6344,7 +6344,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-awg" name = "tsunagi-awg"
version = "1.0.4" version = "1.0.5"
dependencies = [ dependencies = [
"bytes", "bytes",
"iroh", "iroh",
@@ -6359,7 +6359,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-core" name = "tsunagi-core"
version = "1.0.4" version = "1.0.5"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"bytes", "bytes",
@@ -6402,7 +6402,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-runtime" name = "tsunagi-runtime"
version = "1.0.4" version = "1.0.5"
dependencies = [ dependencies = [
"tokio", "tokio",
"tracing", "tracing",
@@ -6415,7 +6415,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-tcp-tls" name = "tsunagi-tcp-tls"
version = "1.0.4" version = "1.0.5"
dependencies = [ dependencies = [
"bytes", "bytes",
"caps", "caps",
@@ -6435,7 +6435,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-tray" name = "tsunagi-tray"
version = "1.0.4" version = "1.0.5"
dependencies = [ dependencies = [
"eframe", "eframe",
"egui-phosphor", "egui-phosphor",
@@ -6451,7 +6451,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-ui" name = "tsunagi-ui"
version = "1.0.4" version = "1.0.5"
dependencies = [ dependencies = [
"egui", "egui",
"egui-phosphor", "egui-phosphor",
@@ -6461,7 +6461,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-wg-quic" name = "tsunagi-wg-quic"
version = "1.0.4" version = "1.0.5"
dependencies = [ dependencies = [
"boringtun", "boringtun",
"bytes", "bytes",
@@ -6488,7 +6488,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-wireguard" name = "tsunagi-wireguard"
version = "1.0.4" version = "1.0.5"
dependencies = [ dependencies = [
"boringtun", "boringtun",
"bytes", "bytes",
+1 -1
View File
@@ -24,7 +24,7 @@ android {
targetSdk 35 targetSdk 35
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger() versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.4') versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.5')
ndk { abiFilters abi } ndk { abiFilters abi }
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-android" name = "tsunagi-android"
version = "1.0.4" version = "1.0.5"
description = "Android VPN client and egui views for tsunagi." description = "Android VPN client and egui views for tsunagi."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -16,7 +16,7 @@ name = "vpn_source_probe"
crate-type = ["cdylib"] crate-type = ["cdylib"]
[dependencies] [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-ui = { path = "../tsunagi-ui" }
tsunagi-core = { path = "../tsunagi-core" } tsunagi-core = { path = "../tsunagi-core" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-awg" name = "tsunagi-awg"
version = "1.0.4" version = "1.0.5"
description = "Ephemeral pairwise Amnezia transport for Tsunagi." description = "Ephemeral pairwise Amnezia transport for Tsunagi."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-core" 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." 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" readme = "../../README.md"
keywords = ["mesh", "p2p", "iroh", "networking"] keywords = ["mesh", "p2p", "iroh", "networking"]
+2 -1
View File
@@ -511,7 +511,8 @@ impl Agent {
.tun_factory .tun_factory
.as_ref() .as_ref()
.map(|_| Arc::new(Sink(Arc::downgrade(&inner))) as Arc<dyn PacketSink>); .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 { if let Some(tunnel) = &inner.config.tunnel {
tunnel.attach(context); tunnel.attach(context);
} }
+14 -3
View File
@@ -15,7 +15,7 @@ pub mod relay;
pub mod routing; pub mod routing;
pub mod transport; pub mod transport;
use std::sync::Arc; use std::sync::{Arc, Weak};
use iroh::EndpointId; use iroh::EndpointId;
use tokio::sync::mpsc; use tokio::sync::mpsc;
@@ -176,6 +176,7 @@ pub struct PluginContext {
/// Where decrypted packets go. Absent when nothing is carrying traffic, /// Where decrypted packets go. Absent when nothing is carrying traffic,
/// in which case a protocol still runs and its packets are discarded. /// in which case a protocol still runs and its packets are discarded.
sink: Option<Arc<dyn PacketSink>>, sink: Option<Arc<dyn PacketSink>>,
routes: Weak<crate::overlay::RoutingTable>,
} }
impl PluginContext { impl PluginContext {
@@ -183,14 +184,23 @@ impl PluginContext {
sender: mpsc::Sender<PluginRequest>, sender: mpsc::Sender<PluginRequest>,
local: EndpointId, local: EndpointId,
sink: Option<Arc<dyn PacketSink>>, sink: Option<Arc<dyn PacketSink>>,
routes: &Arc<crate::overlay::RoutingTable>,
) -> Self { ) -> Self {
Self { Self {
sender: Some(sender), sender: Some(sender),
local: Some(local), local: Some(local),
sink, 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. /// Where to hand a decrypted packet.
/// ///
/// Always answers: with no interface to write to, the packets are /// Always answers: with no interface to write to, the packets are
@@ -208,15 +218,15 @@ impl PluginContext {
sender: None, sender: None,
local: None, local: None,
sink: None, sink: None,
routes: Weak::new(),
} }
} }
/// A context configured with a custom packet sink. /// A context configured with a custom packet sink.
pub fn with_sink(sink: Arc<dyn PacketSink>) -> Self { pub fn with_sink(sink: Arc<dyn PacketSink>) -> Self {
Self { Self {
sender: None,
local: None,
sink: Some(sink), sink: Some(sink),
..Self::detached()
} }
} }
@@ -231,6 +241,7 @@ impl PluginContext {
sender: Some(sender), sender: Some(sender),
local: Some(local), local: Some(local),
sink, sink,
..Self::detached()
} }
} }
+6 -4
View File
@@ -940,10 +940,12 @@ pub struct OverlayPeerReport {
pub public_key: String, pub public_key: String,
/// The overlay address the network agreed it holds. /// The overlay address the network agreed it holds.
pub address: Option<String>, pub address: Option<String>,
/// Seconds since the last WireGuard handshake. /// Seconds since the last WireGuard handshake while its session key is usable.
///
/// `None` means the tunnel has never handshaken and cannot carry traffic.
pub handshake_secs_ago: Option<u64>, 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. /// Packets encrypted and sent to this peer.
pub tx_packets: u64, pub tx_packets: u64,
/// Packets decrypted from this peer. /// 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 /// Bump it whenever [`Request`], [`Response`] or anything they contain
/// changes shape. /// 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. /// 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. /// Choosing another exit replaces the previous one under the table's write lock.
pub fn exit_via(&self) -> Option<(NetworkId, EndpointId)> { 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. /// 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); 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] #[test]
fn refreshing_either_networks_addresses_preserves_the_last_exit_choice() { fn refreshing_either_networks_addresses_preserves_the_last_exit_choice() {
let table = RoutingTable::new(); let table = RoutingTable::new();
+6 -6
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-runtime" name = "tsunagi-runtime"
version = "1.0.4" version = "1.0.5"
description = "Built-in mesh transports and status reporting for native tsunagi agents." description = "Built-in mesh transports and status reporting for native tsunagi agents."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -8,11 +8,11 @@ license.workspace = true
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.4" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.5" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.4" } tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.5" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.4" } tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.5" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.4" } tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.5" }
tokio.workspace = true tokio.workspace = true
tracing.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()), address: peer.overlay_address_v4.map(|a| a.to_string()),
handshake_secs_ago: tunnel handshake_secs_ago: tunnel
.and_then(|t| t.health.since_handshake.map(|s| s.as_secs())), .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), tx_packets: tunnel.map_or(0, |t| t.stats.tx_packets),
rx_packets: tunnel.map_or(0, |t| t.stats.rx_packets), rx_packets: tunnel.map_or(0, |t| t.stats.rx_packets),
tx_bytes: tunnel.map_or(0, |t| t.stats.tx_bytes), tx_bytes: tunnel.map_or(0, |t| t.stats.tx_bytes),
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-tcp-tls" name = "tsunagi-tcp-tls"
version = "1.0.4" version = "1.0.5"
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic." description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -8,7 +8,7 @@ license.workspace = true
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
iroh.workspace = true iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] } tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
rustls = "0.23" rustls = "0.23"
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-tray" name = "tsunagi-tray"
version = "1.0.4" version = "1.0.5"
description = "Tray application to manage a running tsunagi agent." description = "Tray application to manage a running tsunagi agent."
edition.workspace = true edition.workspace = true
rust-version.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 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 # the same local control interface the CLI uses, so it reuses these directly
# and never re-implements the protocol. # 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. # Native, lightweight GUI — no web engine. eframe re-exports egui.
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] } 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). # Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI).
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-ui" name = "tsunagi-ui"
version = "1.0.4" version = "1.0.5"
description = "Shared egui widgets for the tray and Android clients." description = "Shared egui widgets for the tray and Android clients."
edition.workspace = true edition.workspace = true
rust-version.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)] #[derive(Copy, Clone, PartialEq, Eq)]
pub(super) enum Channel { pub(super) enum Channel {
Ready, Ready,
Idle,
Waiting, Waiting,
Error, Error,
Offline, Offline,
@@ -19,11 +20,9 @@ impl Device<'_> {
Some(DATA_DISABLED) => Channel::Disabled, Some(DATA_DISABLED) => Channel::Disabled,
Some(DATA_CONNECTING) => Channel::Waiting, Some(DATA_CONNECTING) => Channel::Waiting,
Some(_) => Channel::Error, Some(_) => Channel::Error,
None if self.overlay.is_some_and(|p| p.is_up()) None if matches!(self.path, None | Some(DataPathReport::None)) => Channel::Waiting,
&& !matches!(self.path, None | Some(DataPathReport::None)) => 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,
Channel::Ready
}
None => Channel::Waiting, None => Channel::Waiting,
} }
} }
@@ -31,6 +30,7 @@ impl Device<'_> {
match self.channel() { match self.channel() {
Channel::Offline => "Offline · peer unreachable", Channel::Offline => "Offline · peer unreachable",
Channel::Ready => "Ready · encrypted data channel available", Channel::Ready => "Ready · encrypted data channel available",
Channel::Idle => "Idle · online, no recent IP traffic",
Channel::Waiting => "Waiting for the encrypted data channel", Channel::Waiting => "Waiting for the encrypted data channel",
Channel::Disabled => "Control only · data transports disabled locally", Channel::Disabled => "Control only · data transports disabled locally",
Channel::Error => self.data_error.unwrap_or("Data channel error"), Channel::Error => self.data_error.unwrap_or("Data channel error"),
@@ -41,6 +41,7 @@ impl Channel {
pub(super) fn label(self) -> &'static str { pub(super) fn label(self) -> &'static str {
match self { match self {
Self::Ready => "Ready", Self::Ready => "Ready",
Self::Idle => "Idle",
Self::Waiting => "Waiting", Self::Waiting => "Waiting",
Self::Error => "Error", Self::Error => "Error",
Self::Offline => "Offline", Self::Offline => "Offline",
@@ -52,6 +53,8 @@ impl Channel {
match (self, ui.visuals().dark_mode) { match (self, ui.visuals().dark_mode) {
(Self::Ready, true) => Color32::from_rgb(100, 210, 136), (Self::Ready, true) => Color32::from_rgb(100, 210, 136),
(Self::Ready, false) => Color32::from_rgb(25, 120, 61), (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, true) => Color32::from_rgb(244, 190, 85),
(Self::Waiting, false) => Color32::from_rgb(150, 94, 8), (Self::Waiting, false) => Color32::from_rgb(150, 94, 8),
(Self::Error, true) => Color32::from_rgb(255, 129, 116), (Self::Error, true) => Color32::from_rgb(255, 129, 116),
@@ -67,6 +70,7 @@ impl Channel {
let color = self.color(ui); let color = self.color(ui);
let glyph = match self { let glyph = match self {
Self::Ready => icon::CHECK_CIRCLE, Self::Ready => icon::CHECK_CIRCLE,
Self::Idle => icon::MOON,
Self::Error => icon::WARNING, Self::Error => icon::WARNING,
Self::Offline => icon::MINUS_CIRCLE, Self::Offline => icon::MINUS_CIRCLE,
Self::Disabled => icon::PAUSE_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::WARNING,
icon::MINUS_CIRCLE, icon::MINUS_CIRCLE,
icon::PAUSE_CIRCLE, icon::PAUSE_CIRCLE,
icon::MOON,
icon::SIGN_OUT, icon::SIGN_OUT,
icon::FINGERPRINT, icon::FINGERPRINT,
icon::HASH, icon::HASH,
@@ -163,6 +164,7 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
("charlie", "error"), ("charlie", "error"),
("delta", "offline"), ("delta", "offline"),
("echo", "control only"), ("echo", "control only"),
("foxtrot", "idle"),
] { ] {
net.members.push(MemberReport { net.members.push(MemberReport {
endpoint_id: id.into(), 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 { let mut overlay_peers = vec![OverlayPeerReport {
peers: vec![OverlayPeerReport { endpoint_id: "alpha".into(),
endpoint_id: "alpha".into(), handshake_secs_ago: Some(2),
handshake_secs_ago: Some(2), tx_bytes: 2048,
tx_bytes: 2048, rx_bytes: 512,
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() ..Default::default()
}], }
}));
net.overlay = Some(OverlayReport {
peers: overlay_peers,
..Default::default() ..Default::default()
}); });
let draw = |size, time, events| { 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)", "bytes (TX / RX)",
"2.0 kB / 512 B", "2.0 kB / 512 B",
"Ready", "Ready",
"Idle",
"Waiting", "Waiting",
"Error", "Error",
"Offline", "Offline",
+2 -2
View File
@@ -3,7 +3,7 @@ name = "tsunagi-wg-quic"
# Its own version, and deliberately separate from the wire version it # 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 # negotiates: a release here does not stop it talking to a peer on an older
# build, because what peers compare is `ANNOUNCEMENT_VERSION`. # 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." description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -11,7 +11,7 @@ license.workspace = true
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
iroh.workspace = true iroh.workspace = true
tokio.workspace = true tokio.workspace = true
serde.workspace = true serde.workspace = true
+240 -48
View File
@@ -32,7 +32,7 @@ use std::collections::{HashMap, VecDeque};
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock}; use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration; use std::time::{Duration, Instant};
use boringtun::noise::{Tunn, TunnResult}; use boringtun::noise::{Tunn, TunnResult};
use bytes::Bytes; use bytes::Bytes;
@@ -41,7 +41,7 @@ use tokio::task::JoinHandle;
use tsunagi::dataplane::routing::{FlowId, flow::ip_flow}; use tsunagi::dataplane::routing::{FlowId, flow::ip_flow};
use tsunagi::dataplane::transport::{SharedLink, TransportError}; use tsunagi::dataplane::transport::{SharedLink, TransportError};
use tsunagi::dataplane::{PacketSink, PluginError}; use tsunagi::dataplane::{PacketSink, PluginContext, PluginError};
use tsunagi::identity::NetworkId; use tsunagi::identity::NetworkId;
use crate::keys::{WgPublicKey, WgSecretKey}; use crate::keys::{WgPublicKey, WgSecretKey};
@@ -52,6 +52,11 @@ use crate::keys::{WgPublicKey, WgSecretKey};
/// drives handshakes, rekeying and keepalives. /// drives handshakes, rekeying and keepalives.
const TIMER_INTERVAL: Duration = Duration::from_millis(250); 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. /// Scratch space for one encapsulate or decapsulate call.
const SCRATCH: usize = 4096; const SCRATCH: usize = 4096;
@@ -60,10 +65,13 @@ const SCRATCH: usize = 4096;
struct FlowTunnel { struct FlowTunnel {
tunn: Tunn, tunn: Tunn,
queued: VecDeque<(FlowId, usize)>, 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 { fn carries_ip(frame: &[u8]) -> bool {
matches!(result, TunnResult::WriteToNetwork(bytes) if bytes.starts_with(&[4, 0, 0, 0])) frame.len() > crate::plugin::WIREGUARD_OVERHEAD as usize && frame.starts_with(&[4, 0, 0, 0])
} }
impl FlowTunnel { impl FlowTunnel {
@@ -74,7 +82,11 @@ impl FlowTunnel {
flow: FlowId, flow: FlowId,
) -> (TunnResult<'a>, FlowId) { ) -> (TunnResult<'a>, FlowId) {
let result = self.tunn.encapsulate(packet, scratch); 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); return (result, flow);
} }
// MAX_QUEUE_DEPTH in boringtun 0.7: the newest packet is dropped at 256. // MAX_QUEUE_DEPTH in boringtun 0.7: the newest packet is dropped at 256.
@@ -89,32 +101,83 @@ impl FlowTunnel {
packet: &[u8], packet: &[u8],
scratch: &'a mut [u8], scratch: &'a mut [u8],
) -> (TunnResult<'a>, FlowId, Option<usize>) { ) -> (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 result = self.tunn.decapsulate(None, packet, scratch);
let (mut flow, mut plaintext_len) = (0, None); let (mut flow, mut plaintext_len) = (0, None);
if packet.is_empty() { if packet.is_empty() {
if is_data(&result) { match &result {
if let Some((tag, len)) = self.queued.pop_front() { TunnResult::WriteToNetwork(out) if carries_ip(out) => {
flow = tag; if let Some((tag, len)) = self.queued.pop_front() {
plaintext_len = Some(len); flow = tag;
plaintext_len = Some(len);
}
} }
} else if let Some(pending) = self.queued.pop_front() { // An internal keepalive may occupy a slot in the bounded
// Without a session, draining pops the oldest IP packet and // FIFO. Discard tags for IP packets BoringTun could not queue.
// encapsulate queues it again at the back. TunnResult::Done => self.queued.clear(),
self.queued.push_back(pending); _ => {}
} }
} }
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) (result, flow, plaintext_len)
} }
fn update_timers<'a>(&mut self, scratch: &'a mut [u8]) -> TunnResult<'a> { fn health(&self, now: Instant, keep_warm: bool) -> PeerHealth {
let result = self.tunn.update_timers(scratch); let since_handshake = self.tunn.time_since_last_handshake();
if matches!( let idle = self.queued.is_empty()
result, && (!keep_warm || since_handshake.is_some())
TunnResult::Err(boringtun::noise::errors::WireGuardError::ConnectionExpired) && self
) { .last_activity
self.queued.clear(); .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. /// Whether a peer's tunnel has completed a handshake.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PeerHealth { pub struct PeerHealth {
/// Time since the last successful WireGuard handshake. /// Age of the last handshake while a usable WireGuard session exists.
///
/// `None` means no handshake has completed yet, so the tunnel is not
/// carrying traffic. This is reported as it is, never guessed.
pub since_handshake: Option<Duration>, pub since_handshake: Option<Duration>,
/// A previously established tunnel with no recent or queued IP traffic.
pub idle: bool,
} }
impl PeerHealth { 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 { pub fn is_up(&self) -> bool {
self.since_handshake.is_some() 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() { let guard = match self.tunn.lock() {
Ok(guard) => guard, Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(), Err(poisoned) => poisoned.into_inner(),
}; };
PeerHealth { guard.health(Instant::now(), keep_warm)
since_handshake: guard.tunn.time_since_last_handshake(),
}
} }
} }
@@ -259,6 +319,7 @@ pub struct PeerSummary {
struct Inner { struct Inner {
network: NetworkId, network: NetworkId,
context: PluginContext,
private_key: WgSecretKey, private_key: WgSecretKey,
peers: RwLock<HashMap<WgPublicKey, Arc<Peer>>>, peers: RwLock<HashMap<WgPublicKey, Arc<Peer>>>,
/// Where decrypted packets go. /// Where decrypted packets go.
@@ -292,11 +353,20 @@ impl WireguardDevice {
/// leave through the sink. Which address belongs to whom, and therefore /// leave through the sink. Which address belongs to whom, and therefore
/// where a packet should go, is decided above this. /// where a packet should go, is decided above this.
pub fn start(network: NetworkId, private_key: WgSecretKey, sink: Arc<dyn PacketSink>) -> Self { 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 { let inner = Arc::new(Inner {
network, network,
private_key, private_key,
peers: RwLock::new(HashMap::new()), peers: RwLock::new(HashMap::new()),
sink, sink: context.packet_sink(),
context,
next_index: AtomicU32::new(1), next_index: AtomicU32::new(1),
}); });
@@ -336,7 +406,7 @@ impl WireguardDevice {
let (result, selected_flow) = tunn.encapsulate(packet, &mut scratch, flow); let (result, selected_flow) = tunn.encapsulate(packet, &mut scratch, flow);
match result { match result {
TunnResult::WriteToNetwork(out) => { 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 // No session yet, so nothing to send. Counted as dropped
// rather than reported: the handshake is in flight and the // rather than reported: the handshake is in flight and the
@@ -394,6 +464,7 @@ impl WireguardDevice {
tunn: Mutex::new(FlowTunnel { tunn: Mutex::new(FlowTunnel {
tunn, tunn,
queued: VecDeque::new(), queued: VecDeque::new(),
last_activity: None,
}), }),
link, link,
counters: Arc::new(PeerCounters { counters: Arc::new(PeerCounters {
@@ -442,6 +513,7 @@ impl WireguardDevice {
/// A snapshot of every peer. /// A snapshot of every peer.
pub fn peers(&self) -> Vec<PeerSummary> { 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) let mut peers: Vec<PeerSummary> = read_lock(&self.inner.peers)
.values() .values()
.map(|peer| { .map(|peer| {
@@ -453,7 +525,7 @@ impl WireguardDevice {
endpoint_id: peer.endpoint_id, endpoint_id: peer.endpoint_id,
public_key: peer.public_key, public_key: peer.public_key,
overlay_address_v4: overlay_v4, overlay_address_v4: overlay_v4,
health: peer.health(), health: peer.health(warm_peer == Some(peer.endpoint_id)),
stats: peer.stats(), stats: peer.stats(),
path: peer.link.path_description(), path: peer.link.path_description(),
max_datagram: peer.link.max_datagram_size(), 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. // any packets that were queued while the session was coming up.
let mut input: Option<&[u8]> = Some(&datagram); let mut input: Option<&[u8]> = Some(&datagram);
loop { loop {
let outcome = { let (outcome, drain_pending) = {
let mut tunn = match peer.tunn.lock() { let mut tunn = match peer.tunn.lock() {
Ok(guard) => guard, Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(), Err(poisoned) => poisoned.into_inner(),
}; };
let (result, flow, plaintext_len) = let (result, flow, plaintext_len) =
tunn.decapsulate(input.unwrap_or(&[]), &mut scratch); tunn.decapsulate(input.unwrap_or(&[]), &mut scratch);
match result { let outcome = match result {
TunnResult::WriteToNetwork(out) => { TunnResult::WriteToNetwork(out) => {
Outcome::ToNetwork(out.len(), flow, plaintext_len) 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"); tracing::trace!(?err, "wireguard decapsulation failed");
Outcome::Failed Outcome::Failed
} }
} };
(outcome, input.is_some() && !tunn.queued.is_empty())
}; };
match outcome { match outcome {
@@ -595,7 +668,6 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
peer.counters peer.counters
.rx_bytes .rx_bytes
.fetch_add(len as u64, Ordering::Relaxed); .fetch_add(len as u64, Ordering::Relaxed);
break;
} }
Outcome::Failed => { Outcome::Failed => {
peer.counters peer.counters
@@ -603,8 +675,14 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
.fetch_add(1, Ordering::Relaxed); .fetch_add(1, Ordering::Relaxed);
break; 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>) { async fn drive_timers(inner: Arc<Inner>) {
let mut ticker = tokio::time::interval(TIMER_INTERVAL); let mut ticker = tokio::time::interval(TIMER_INTERVAL);
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut scratch = vec![0u8; SCRATCH];
loop { loop {
ticker.tick().await; ticker.tick().await;
let warm_peer = inner.context.warm_peer(inner.network);
let peers: Vec<Arc<Peer>> = read_lock(&inner.peers).values().cloned().collect(); let peers: Vec<Arc<Peer>> = read_lock(&inner.peers).values().cloned().collect();
for peer in peers { for peer in peers {
let mut scratch = vec![0u8; SCRATCH];
let len = { let len = {
let mut tunn = match peer.tunn.lock() { let mut tunn = match peer.tunn.lock() {
Ok(guard) => guard, Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(), Err(poisoned) => poisoned.into_inner(),
}; };
match tunn.update_timers(&mut scratch) { let refresh_after =
TunnResult::WriteToNetwork(out) => Some(out.len()), (warm_peer == Some(peer.endpoint_id)).then_some(WARM_REKEY_AFTER);
TunnResult::Err(err) => { tunn.update_timers(&mut scratch, refresh_after)
tracing::trace!(?err, "wireguard timer produced an error");
None
}
_ => None,
}
}; };
if let Some(len) = len { if let Some(len) = len {
send_to_peer(&peer, &scratch[..len]); send_to_peer(&peer, &scratch[..len]);
@@ -662,6 +736,7 @@ mod flow_tests {
None, None,
), ),
queued: VecDeque::new(), queued: VecDeque::new(),
last_activity: None,
} }
} }
fn wire(result: TunnResult<'_>) -> Vec<u8> { 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] #[test]
fn flow_tags_survive_pending_queue_overflow_handshake_and_encryption() { fn flow_tags_survive_pending_queue_overflow_handshake_and_encryption() {
let ak = WgSecretKey::from_bytes(&[1; 32]); let ak = WgSecretKey::from_bytes(&[1; 32]);
@@ -716,7 +908,7 @@ mod flow_tests {
TunnResult::Done TunnResult::Done
)); ));
let (result, flow) = a.encapsulate(&packet, &mut scratch, 12345); let (result, flow) = a.encapsulate(&packet, &mut scratch, 12345);
assert!(is_data(&result)); assert!(carries_ip(&wire(result)));
assert_eq!(flow, 12345); assert_eq!(flow, 12345);
} }
} }
+6 -12
View File
@@ -35,7 +35,6 @@ use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle; use tokio::task::JoinHandle;
use tsunagi::BoxFuture; use tsunagi::BoxFuture;
use tsunagi::dataplane::PacketSink;
use tsunagi::dataplane::transport::SharedLink; use tsunagi::dataplane::transport::SharedLink;
use tsunagi::dataplane::{IpPlugin, PluginCapability, PluginContext, PluginError}; use tsunagi::dataplane::{IpPlugin, PluginCapability, PluginContext, PluginError};
use tsunagi::identity::NetworkId; use tsunagi::identity::NetworkId;
@@ -213,8 +212,6 @@ struct Worker {
store: WgKeyStore, store: WgKeyStore,
shared: Mutex<Shared>, shared: Mutex<Shared>,
context: OnceLock<PluginContext>, context: OnceLock<PluginContext>,
/// Where decrypted packets go, once the agent has attached one.
sink: OnceLock<Arc<dyn PacketSink>>,
} }
impl std::fmt::Debug for Worker { impl std::fmt::Debug for Worker {
@@ -315,7 +312,6 @@ impl WireguardPlugin {
store, store,
shared: Mutex::new(Shared::default()), shared: Mutex::new(Shared::default()),
context: OnceLock::new(), context: OnceLock::new(),
sink: OnceLock::new(),
}); });
let (commands, receiver) = mpsc::channel(64); let (commands, receiver) = mpsc::channel(64);
@@ -473,13 +469,12 @@ impl Worker {
} }
}; };
let sink = match self.sink.get() { let context = self
Some(sink) => Arc::clone(sink), .context
// Not attached to an agent: the protocol still runs, and its .get()
// packets have nowhere to go. .cloned()
None => Arc::new(tsunagi::dataplane::DiscardPackets) as Arc<dyn PacketSink>, .unwrap_or_else(PluginContext::detached);
}; let device = Arc::new(WireguardDevice::start_with_context(network, key, context));
let device = Arc::new(WireguardDevice::start(network, key, sink));
let mut shared = self.lock_shared(); let mut shared = self.lock_shared();
if let Some(state) = shared.networks.get_mut(&network) { 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() { if let Some(local) = context.local_endpoint_id() {
let _ = self.worker.local_id.set(local); let _ = self.worker.local_id.set(local);
} }
let _ = self.worker.sink.set(context.packet_sink());
let _ = self.worker.context.set(context); 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; live.peer.agent.shutdown().await;
} }
#[tokio::test] async fn shared_nodes() -> (Node, Node) {
async fn selecting_a_shared_peer_uses_only_the_chosen_membership_for_exit() {
let discovery = SharedMemoryDiscovery::new(); let discovery = SharedMemoryDiscovery::new();
let client = Node::open(TempDir::new().unwrap(), &discovery, "client", None).await; let client = Node::open(TempDir::new().unwrap(), &discovery, "client", None).await;
let dir = TempDir::new().unwrap(); let dir = TempDir::new().unwrap();
let config = tsunagi::testing::config_with(dir.path(), &discovery); let config = tsunagi::testing::config_with(dir.path(), &discovery);
let peer = Node::start(dir, "shared", config).await; 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. // Fixed credentials keep the two automatically derived /24s distinct.
let mut meshes = Vec::new(); let join = |name, secret| {
for (name, secret) in [("shared-left", [1; 32]), ("shared-right", [2; 32])] {
let credentials = ( let credentials = (
NetworkName::new(name).unwrap(), NetworkName::new(name).unwrap(),
NetworkSecret::from_bytes(secret).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; let tun = client.tun().await;
for (chosen, other) in [(&meshes[0], &meshes[1]), (&meshes[1], &meshes[0])] { for (chosen, other) in [(&meshes[0], &meshes[1]), (&meshes[1], &meshes[0])] {
client client
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-wireguard" name = "tsunagi-wireguard"
version = "1.0.4" version = "1.0.5"
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi." description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0"
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.5" }
iroh.workspace = true iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] } tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
serde.workspace = true serde.workspace = true
+6 -6
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi" name = "tsunagi"
version = "1.0.4" version = "1.0.5"
description = "The tsunagi command line agent." description = "The tsunagi command line agent."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -12,11 +12,11 @@ name = "tsng"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.4" } tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.5" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4", features = ["tun-device", "dns-publish"] } tsunagi-core = { path = "../tsunagi-core", version = "1.0.5", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.4" } tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.5" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.4" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.5" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.4" } tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.5" }
iroh.workspace = true iroh.workspace = true
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] } tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
tracing.workspace = true 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), 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(); let mut detail = String::new();
if let Some(v4) = row.overlay_address_v4 { if let Some(v4) = row.overlay_address_v4 {
detail.push_str(&format!("{v4:<15} ")); detail.push_str(&format!("{v4:<15} "));
} }
detail.push_str(&path); detail.push_str(&path);
if idle {
detail.push_str(" · idle");
}
if let Some(rtt) = row.data_rtt_ms { if let Some(rtt) = row.data_rtt_ms {
detail.push_str(&format!(" data RTT {rtt}ms")); detail.push_str(&format!(" data RTT {rtt}ms"));
} }
@@ -3906,7 +3911,7 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
} }
detail.extend(taken); 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 Health::Degraded
} else { } else {
Health::Good Health::Good
@@ -3916,12 +3921,12 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
if let Some(reason) = row.data_error { if let Some(reason) = row.data_error {
out = out.with_note(reason.to_owned()); 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()); out = out.with_note(path.to_owned());
} }
if let Some(tunnel) = row.tunnel { if let Some(tunnel) = row.tunnel {
out = out.with_note(match tunnel.handshake_secs_ago { out = out.with_note(if show_counters {
Some(_) => format!( format!(
"tx {} rx {} · IP bytes ↑{} ↓{}{} · {}", "tx {} rx {} · IP bytes ↑{} ↓{}{} · {}",
tunnel.tx_packets, tunnel.tx_packets,
tunnel.rx_packets, tunnel.rx_packets,
@@ -3933,8 +3938,9 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
String::new() String::new()
}, },
row.data_transport_detail.unwrap_or(&tunnel.path) 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 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] #[test]
fn handshake_failures_with_nobody_connected_point_at_the_secret() { fn handshake_failures_with_nobody_connected_point_at_the_secret() {
// The classic symptom of one member being given a different secret. // The classic symptom of one member being given a different secret.
+9
View File
@@ -238,6 +238,15 @@ modifying the source files. Corrupt legacy databases are hard errors. Old
internal channel; contradictory values are rejected. Interface MTU is selected internal channel; contradictory values are rejected. Interface MTU is selected
once with `--mtu`, independent of carrier selection. once with `--mtu`, independent of carrier selection.
The client renews the selected exit peer's session key at 120 seconds, even
when no IP traffic is flowing. The current key can carry packets during the
exchange. Changing the exit moves this behavior to the new network and peer.
The device list shows **Idle** after an established tunnel has had 30 seconds
without IP traffic. Handshakes and keepalives do not restart this interval.
Pending IP packets, a missing path, or a selected exit waiting for a usable
key still show **Waiting**. A reported transport failure shows **Error**.
User traffic counters count original IP bytes once when the encrypted frame is User traffic counters count original IP bytes once when the encrypted frame is
accepted by the logical transport, and once when decrypted on receipt. They do accepted by the logical transport, and once when decrypted on receipt. They do
not promise remote delivery. They exclude carrier overhead, handshakes, not promise remote delivery. They exclude carrier overhead, handshakes,
+1 -1
View File
@@ -34,7 +34,7 @@ let
in in
rustPlatform.buildRustPackage { rustPlatform.buildRustPackage {
pname = if withTray then "tsunagi" else "tsunagi-cli"; pname = if withTray then "tsunagi" else "tsunagi-cli";
version = "1.0.4"; version = "1.0.5";
src = lib.cleanSource ../.; src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock; cargoLock.lockFile = ../Cargo.lock;