Skip to main content

ts_runtime/
lib.rs

1#![doc = include_str!("../README.md")]
2
3extern crate ts_netstack_smoltcp as netstack;
4
5use core::time::Duration;
6use std::sync::Arc;
7
8use kameo::{
9    actor::{ActorRef, Spawn, WeakActorRef},
10    mailbox::Signal,
11};
12use netstack::netcore::Channel;
13use tokio::sync::watch;
14
15use crate::{
16    control_runner::ControlRunner, dataplane::DataplaneActor, direct::DirectManager,
17    forwarder_actor::ForwarderActor, multiderp::Multiderp, netstack_actor::NetstackActor,
18};
19
20/// Pcap stream framer for debug packet capture (`CapturePcap`).
21pub mod capture;
22/// Control runner.
23pub mod control_runner;
24mod dataplane;
25mod derp_latency;
26/// Device connection-state tracking ([`DeviceState`]) and typed registration outcome
27/// ([`RegistrationError`]).
28pub mod device_state;
29mod direct;
30mod env;
31mod error;
32/// Fallback TCP handler registry (`tsnet.Server.RegisterFallbackTCPHandler` parity).
33pub mod fallback_tcp;
34mod forwarder_actor;
35/// Client-side Funnel ingress termination (`tsnet`'s `ListenFunnel` data path).
36pub mod funnel;
37mod magic_dns;
38mod multiderp;
39mod netstack_actor;
40mod packetfilter;
41pub mod peer_tracker;
42mod peerapi;
43mod peerapi_doh;
44mod route_updater;
45/// Stored Serve config + accept-loop runtime (`tsnet`'s `Get/SetServeConfig` + serving runtime).
46pub mod serve;
47mod src_filter;
48/// Netmap status snapshot, WhoIs, and watcher types.
49pub mod status;
50/// Taildrop peer-to-peer file transfer store.
51pub mod taildrop;
52pub mod taildrop_send;
53/// Tailnet-Lock (TKA) chain-sync orchestration: bootstrap + offer/send driver (the runtime layer
54/// that bridges the `ts_control` sync RPCs and the `ts_tka` chain logic).
55mod tka_sync;
56#[cfg(feature = "tun")]
57mod tun_actor;
58
59pub use device_state::{DeviceState, RegistrationError};
60pub(crate) use env::Env;
61pub use error::{Error, ErrorKind};
62pub use status::{FileTarget, NetcheckReport, RegionLatency, Status, StatusNode, WhoIs};
63pub use ts_dataplane::{CaptureHook, CapturePath};
64
65use crate::peer_tracker::PeerTracker;
66
67/// The runtime for a tailscale device.
68pub struct Runtime {
69    /// Reference to the control actor.
70    pub control: ActorRef<ControlRunner>,
71    dataplane: ActorRef<DataplaneActor>,
72    /// Reference to the direct (disco/UDP underlay) manager, retained so [`Runtime::rebind`] can
73    /// ask it to re-bind the underlay socket on a network/link change.
74    direct: ActorRef<DirectManager>,
75    /// Reference to the application netstack actor. `None` in TUN transport mode, where there is
76    /// no userspace application netstack (the application data path is a real kernel TUN device).
77    netstack: Option<WeakActorRef<NetstackActor>>,
78    /// Reference to the peer tracker for peer lookups.
79    pub peer_tracker: WeakActorRef<PeerTracker>,
80    /// Fallback TCP handler registry, bound to the application netstack. `None` in TUN transport
81    /// mode (no application netstack exists to attach it to).
82    fallback_tcp: Option<fallback_tcp::FallbackTcpManager>,
83    /// Reference to the forwarder actor, retained so [`Runtime::set_advertise_routes`] can push a
84    /// new accept/dial route table onto the running forwarder (the local half of advertising
85    /// routes). Without this the strong ref would drop after the startup `GetChannel` and the
86    /// forwarder would be reachable only via the message bus.
87    forwarder: ActorRef<ForwarderActor>,
88    env: Env,
89    shutdown: watch::Sender<bool>,
90    /// Sender side of the exit-node selector `watch` cell. Held privately here (not on the cloned
91    /// `Env`, which keeps only the read side) so that only `Runtime::set_exit_node` can mutate the
92    /// selection; the route updater and source filter re-read it via [`Env::exit_node`].
93    exit_node_tx: watch::Sender<Option<ts_control::ExitNodeSelector>>,
94    /// Receiver mirroring the *active* (resolved + fail-closed) exit node's stable id, fed by the
95    /// route updater. Read by [`Runtime::status`] / [`Runtime::active_exit_node`] to report which
96    /// exit node traffic is actually egressing through (vs. the merely-configured selector).
97    active_exit_rx: watch::Receiver<Option<ts_control::StableNodeId>>,
98    /// Receiver for the device connection-state cell, fed by the control runner. Read by
99    /// [`Runtime::watch_state`] and [`Runtime::wait_until_running`].
100    state_rx: watch::Receiver<DeviceState>,
101}
102
103impl Runtime {
104    /// Spawn a new runtime with the given parameters for connecting to a tailnet.
105    pub async fn spawn(
106        config: ts_control::Config,
107        auth_key: Option<String>,
108        keys: ts_keys::NodeState,
109    ) -> Result<Self, Error> {
110        let (shutdown_tx, shutdown_rx) = watch::channel(false);
111
112        // The exit-node selector is a live `watch` cell so `Device::set_exit_node` can change it at
113        // runtime. `new_with_exit_tx` returns the `Sender` (mutation capability) separately so it is
114        // retained privately on the `Runtime`, while only the `Receiver` (the readers' contract)
115        // lives on the cloned `Env`. The initial value comes from `ForwarderConfig.exit_node`.
116        let (env, exit_node_tx) = Env::new_with_exit_tx(
117            keys,
118            shutdown_rx,
119            env::ForwarderConfig::from_control_config(&config),
120        );
121
122        // Both userspace netstacks (application + forwarder) share one netstack config. Honor the
123        // per-deployment TCP buffer knob when set, otherwise fall back to the netstack default.
124        let netstack_config = netstack_config_from(config.tcp_buffer_size);
125
126        let dataplane = DataplaneActor::spawn(env.clone());
127
128        let (netstack_id, netstack_up, netstack_down) =
129            dataplane.ask(dataplane::NewOverlayTransport).await?;
130
131        // A second overlay transport feeds the dedicated any-IP forwarder netstack. Inbound packets
132        // for advertised subnet routes / the exit-node default route are routed here (see
133        // `route_updater`), keeping forwarded flows off the application netstack.
134        let (forwarder_id, forwarder_up, forwarder_down) =
135            dataplane.ask(dataplane::NewOverlayTransport).await?;
136
137        let multiderp = Multiderp::spawn((env.clone(), dataplane.clone()));
138
139        // Spawn the direct (disco) underlay manager before the route updater. Its `on_start`
140        // binds the UDP socket and registers its transport synchronously, so by the time the
141        // route updater asks it for the direct transport id it is guaranteed to be available.
142        let direct = DirectManager::spawn((env.clone(), dataplane.clone(), multiderp.clone()));
143
144        // Spawn the forwarder before the route updater. Its `on_start` builds the forwarder
145        // netstack, enables any-IP acceptance, and starts the per-port accept loops synchronously,
146        // so by the time the route updater begins delivering advertised prefixes to
147        // `forwarder_id` the netstack is already draining its transport.
148        let forwarder = ForwarderActor::spawn((
149            env.clone(),
150            netstack_config.clone(),
151            forwarder_up,
152            forwarder_down,
153        ));
154        // Force `on_start` to finish (any-IP enabled, accept loops live) before the route updater
155        // can route the first inbound flow to `forwarder_id`: an `ask` blocks until the actor has
156        // started.
157        //
158        // The forwarder netstack's overlay `Channel` is reused by the TUN application path for
159        // recursive / exit-node-DoH MagicDNS forwarding (TUN mode has no application netstack of its
160        // own, but the forwarder netstack runs in both modes and egresses over the overlay — the
161        // anti-leak property `forward_query`/`forward_doh` require). Only the `tun` Tun arm consumes
162        // it, so it is unused when the `tun` feature is off — allow that without warn-as-error.
163        #[cfg_attr(not(feature = "tun"), allow(unused_variables))]
164        let (forwarder_channel,) = forwarder.ask(forwarder_actor::GetChannel).await?;
165
166        // The route updater is the single authoritative resolver of the active (resolved,
167        // fail-closed) exit node; it publishes the resolved stable id into this watch cell so
168        // `Runtime::status` can report which exit is actually engaged (not just configured).
169        let (active_exit_tx, active_exit_rx) = watch::channel(None);
170        route_updater::RouteUpdater::spawn((
171            multiderp.clone(),
172            direct.clone(),
173            env.clone(),
174            netstack_id,
175            forwarder_id,
176            active_exit_tx,
177        ));
178        packetfilter::PacketfilterUpdater::spawn(env.clone());
179        src_filter::SourceFilterUpdater::spawn(env.clone());
180        let peer_tracker = PeerTracker::spawn(env.clone()).downgrade();
181
182        // Select the application data path from the transport mode. The forwarder/egress path
183        // above is UNCHANGED in both modes — TUN mode only swaps the application data path, never
184        // the forwarder. `config` is moved into `ControlRunner::spawn` below, so branch on a
185        // borrow and clone the small `TunConfig` where needed before the move.
186        //
187        // - Netstack (the default, and the only reachable arm when the `tun` feature is off):
188        //   spawn the application netstack + MagicDNS responder + fallback-TCP registry, all on
189        //   the `netstack_up`/`netstack_down` overlay seam.
190        // - Tun: spawn `TunActor` on that same overlay seam instead; no application netstack and
191        //   no MagicDNS responder exist, and `netstack`/`fallback_tcp` are `None`.
192        // - Tun requested but built without the `tun` feature: hard-error (a config/build
193        //   mismatch knowable at spawn time). NEVER silently fall back to netstack.
194        let (netstack, fallback_tcp) = match &config.transport_mode {
195            ts_control::TransportMode::Netstack => {
196                let netstack = NetstackActor::spawn((
197                    env.clone(),
198                    netstack_config,
199                    netstack_up,
200                    netstack_down,
201                ));
202
203                // Fetch the netstack channel while we still hold the strong ActorRef, then spawn
204                // the MagicDNS responder on it. Fire-and-forget: like src_filter/route_updater,
205                // it's owned by the message bus and isn't stored on `Runtime`.
206                let (channel,) = netstack.ask(netstack_actor::GetChannel).await?;
207                // The fallback-TCP registry attaches to the application netstack — the same one
208                // that carries the embedder's explicit `Device::tcp_listen` sockets — so a
209                // fallback handler sees exactly the inbound flows no explicit listener matched.
210                let fallback_tcp = fallback_tcp::FallbackTcpManager::new(channel.clone());
211                magic_dns::MagicDnsActor::spawn((env.clone(), channel));
212
213                (Some(netstack.downgrade()), Some(fallback_tcp))
214            }
215
216            #[cfg(feature = "tun")]
217            ts_control::TransportMode::Tun(tun_cfg) => {
218                // Reuse the same `netstack_up`/`netstack_down` overlay-transport pair that would
219                // have fed the netstack — it is just the application-side overlay seam (the name
220                // is historical). No NetstackActor / MagicDnsActor is spawned.
221                tun_actor::TunActor::spawn((
222                    env.clone(),
223                    tun_cfg.clone(),
224                    netstack_up,
225                    netstack_down,
226                    // Host-route gating inputs derived from `Env`: subnet routes are only steered
227                    // into the TUN when `--accept-routes` is set, and the host `/0` only when the
228                    // embedder configured an exit node. See `tun_actor::host_routes_from_node`.
229                    tun_actor::HostRouteGating {
230                        accept_routes: env.accept_routes,
231                        exit_node_configured: env.exit_node().is_some(),
232                    },
233                    // Reuse the forwarder netstack's overlay `Channel` for recursive / exit-node-DoH
234                    // MagicDNS forwarding in the TUN datapath (TUN mode has no application netstack
235                    // Channel of its own). Egresses over the overlay — anti-leak preserved.
236                    forwarder_channel.clone(),
237                ));
238
239                (None, None)
240            }
241
242            #[cfg(not(feature = "tun"))]
243            ts_control::TransportMode::Tun(_) => {
244                return Err(Error {
245                    kind: ErrorKind::TunUnavailable,
246                    target_actor: None,
247                    message_ty: None,
248                });
249            }
250        };
251
252        // Device connection-state cell. Created here (not inside the actor) so the control runner's
253        // `on_start` can publish `Failed`/`NeedsLogin` and still return `Err` without the sender
254        // being tied to a `Self` that never gets constructed on a hard registration failure.
255        let (state_tx, state_rx) = watch::channel(DeviceState::Connecting);
256
257        let control = ControlRunner::spawn(control_runner::Params {
258            config,
259            auth_key,
260            env: env.clone(),
261            state_tx,
262        });
263
264        Ok(Self {
265            control,
266            dataplane,
267            direct,
268            peer_tracker,
269            fallback_tcp,
270            forwarder,
271            netstack,
272            env,
273            shutdown: shutdown_tx,
274            exit_node_tx,
275            active_exit_rx,
276            state_rx,
277        })
278    }
279
280    /// Register a fallback TCP handler consulted for every inbound TCP flow that matches no
281    /// explicit listener (`tsnet.Server.RegisterFallbackTCPHandler` parity).
282    ///
283    /// The returned [`fallback_tcp::FallbackTcpHandle`] deregisters the handler when dropped. See
284    /// [`fallback_tcp`] for the dispatch contract and anti-leak guarantees.
285    ///
286    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
287    /// application netstack to attach a fallback handler to.
288    pub fn register_fallback_tcp_handler(
289        &self,
290        cb: Arc<
291            dyn Fn(core::net::SocketAddr, core::net::SocketAddr) -> fallback_tcp::FallbackDecision
292                + Send
293                + Sync,
294        >,
295    ) -> Result<fallback_tcp::FallbackTcpHandle, Error> {
296        Ok(self
297            .fallback_tcp
298            .as_ref()
299            .ok_or(Error {
300                kind: ErrorKind::UnsupportedInTunMode,
301                target_actor: None,
302                message_ty: None,
303            })?
304            .register(cb))
305    }
306
307    /// Get a channel to send commands to the netstack.
308    ///
309    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
310    /// application netstack.
311    pub async fn channel(&self) -> Result<Channel, Error> {
312        let (channel,) = self
313            .netstack
314            .as_ref()
315            .ok_or(Error {
316                kind: ErrorKind::UnsupportedInTunMode,
317                target_actor: None,
318                message_ty: None,
319            })?
320            .upgrade()
321            .ok_or(Error {
322                kind: ErrorKind::ActorGone,
323                target_actor: None,
324                message_ty: None,
325            })?
326            .ask(netstack_actor::GetChannel)
327            .await?;
328
329        Ok(channel)
330    }
331
332    /// The Taildrop file store, if Taildrop is enabled (`taildrop_dir` configured and the store
333    /// initialized). `None` when disabled — fail-closed. Shared with the peerAPI Taildrop server so
334    /// the embedder's read APIs and the receive path see the same on-disk store.
335    pub fn taildrop_store(&self) -> Option<Arc<crate::taildrop::TaildropStore>> {
336        self.env.taildrop_store.clone()
337    }
338
339    /// The shared Funnel ingress slot the peerAPI `/v0/ingress` route reads per connection.
340    ///
341    /// `Device::listen_funnel` installs a [`FunnelManager`](crate::funnel::FunnelManager)'s sink here
342    /// to make the route live (the peerAPI server is already running from startup). Returns a clone of
343    /// the runtime-lifetime `Arc` so the device can write the slot without restarting the server. See
344    /// [`crate::funnel`] for the ingress data path.
345    pub fn funnel_ingress_slot(&self) -> crate::funnel::FunnelIngressSlot {
346        self.env.funnel_ingress.clone()
347    }
348
349    /// The shared "Funnel ingress listener active" flag (the same `Arc` the control session reads to
350    /// set `HostInfo.IngressEnabled`). `Device::listen_funnel` flips it `true` while a funnel listener
351    /// is up so control routes Funnel traffic to this node; clearing it advertises no live endpoint.
352    pub fn ingress_active_flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
353        self.env.ingress_active.clone()
354    }
355
356    /// Install (`Some`) or clear (`None`) the debug packet-capture hook on the running dataplane.
357    /// `Some(hook)` tees every plaintext packet crossing the datapath to `hook` until it is cleared;
358    /// `None` stops capture. Mirrors Go `tstun.Wrapper.InstallCaptureHook` / `ClearCaptureSink`.
359    pub async fn install_capture(
360        &self,
361        hook: Option<ts_dataplane::CaptureHook>,
362    ) -> Result<(), Error> {
363        self.dataplane
364            .ask(dataplane::InstallCapture { hook })
365            .await
366            .map_err(Into::into)
367    }
368
369    /// Re-bind the underlay UDP socket after a network/link change (Wi-Fi switch, sleep/wake). The
370    /// embedder's own link monitor calls this (the engine owns the socket re-bind; the embedder owns
371    /// OS netmon). Re-binds the socket (same-port-preferred, IPv4-only invariant preserved) and
372    /// resets the now-stale local NAT mapping — clearing learned reflexive addresses and every
373    /// confirmed direct path while keeping candidate endpoints, so peers re-probe over the new socket
374    /// and relay over DERP (never a direct host dial) until a path re-confirms. Peers, control, the
375    /// netmap, disco state, and DERP are untouched. A no-op when the underlay is inert (bind failed
376    /// at startup, DERP-only). Mirrors Go magicsock `Conn.Rebind` + `resetEndpointStates`.
377    pub async fn rebind(&self) -> Result<(), Error> {
378        self.direct.ask(direct::Rebind).await.map_err(Error::from)
379    }
380
381    /// A snapshot of the local netmap: this node plus every known peer.
382    ///
383    /// Combines the self node held by the control runner with the peer set held by the peer
384    /// tracker. Mirrors tsnet's `LocalClient::Status`.
385    ///
386    /// `self_node` is `None` until the first netmap update has been received from control. Peer
387    /// entries carry no online/user/capability data (see the [`status`] module docs for that gap).
388    pub async fn status(&self) -> Result<Status, Error> {
389        let self_node_domain = self.control.ask(control_runner::SelfNode).await?;
390        // The MagicDNS suffix is the self node's FQDN minus its host label — already split into
391        // `Node.tailnet` at decode time (Go derives it the same way in `NetworkMap.MagicDNSSuffix`).
392        // Capture it before the domain `Node` is mapped away into a `StatusNode`.
393        let magic_dns_suffix = self_node_domain.as_ref().and_then(|n| n.tailnet.clone());
394        let self_node = self_node_domain.as_ref().map(StatusNode::from_node);
395
396        let peers_with_ids = self
397            .peer_tracker
398            .upgrade()
399            .ok_or(Error {
400                kind: ErrorKind::ActorGone,
401                target_actor: None,
402                message_ty: None,
403            })?
404            .ask(peer_tracker::GetStatus)
405            .await?;
406
407        // Join per-peer connectivity (Go `PeerStatus.CurAddr`): one batched query to the direct
408        // manager for every peer's current trusted direct endpoint, then fill `cur_addr` on each
409        // `StatusNode`. A peer absent from the map is relayed via DERP (`cur_addr = None`). This is a
410        // live snapshot — the direct path can expire/re-confirm between calls (matches Go's snapshot
411        // semantics). The `watch_netmap` stream intentionally carries no connectivity (it is a netmap
412        // watch, not a path-state watch, and does not re-fire on direct↔relay flips).
413        let ids: Vec<ts_transport::PeerId> = peers_with_ids.iter().map(|(id, _)| *id).collect();
414        let best_addrs = self
415            .direct
416            .ask(direct::BestAddrs { ids })
417            .await
418            .unwrap_or_default();
419
420        let peers = peers_with_ids
421            .into_iter()
422            .map(|(id, mut node)| {
423                node.cur_addr = best_addrs.get(&id).copied();
424                node
425            })
426            .collect();
427
428        Ok(Status {
429            self_node,
430            peers,
431            active_exit_node: self.active_exit_node(),
432            magic_dns_suffix,
433        })
434    }
435
436    /// List the tailnet peers this node can Taildrop a file *to* (Go LocalAPI `FileTargets`).
437    ///
438    /// Mirrors the upstream send-path filter (`feature/taildrop` `Extension::FileTargets`): a peer
439    /// qualifies when it advertises a reachable peerAPI **and** is either owned by the same user as
440    /// this node **or** explicitly granted the file-sharing-target capability. The whole list is
441    /// gated on this node holding the file-sharing capability (control sets it when the admin enables
442    /// Taildrop) — absent that, an empty list (fail-closed, not an error, matching how the receive
443    /// store returns empty when disabled). Results are sorted by the peer's MagicDNS name.
444    ///
445    /// Targets are listed regardless of current online state (upstream's `FileTargets` does not gate
446    /// on online either; an offline target's send will simply time out). The self node is never
447    /// included. Returns empty before the first netmap.
448    ///
449    /// Divergence from Go: the upstream filter also excludes `tvOS` peers, which this fork cannot
450    /// reproduce (the domain node carries no OS string); the impact is negligible — the actual send
451    /// fail-closes if such a peer refused the transfer.
452    pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
453        // Node-level gate: this node must hold the file-sharing capability (Taildrop enabled by the
454        // admin). Read it off the self node's cap map, like Go's `hasCapFileSharing()`.
455        let self_node = self.control.ask(control_runner::SelfNode).await?;
456        let Some(self_node) = self_node else {
457            return Ok(Vec::new()); // no netmap yet
458        };
459        if !self_node.can_share_files() {
460            return Ok(Vec::new()); // Taildrop not enabled for the tailnet — fail-closed
461        }
462        let self_user_id = self_node.user_id;
463
464        let peers = self
465            .peer_tracker
466            .upgrade()
467            .ok_or(Error {
468                kind: ErrorKind::ActorGone,
469                target_actor: None,
470                message_ty: None,
471            })?
472            .ask(peer_tracker::AllPeers)
473            .await?;
474
475        // Eligibility + ordering live in `build_file_targets` (pure, unit-tested in `status`).
476        Ok(status::build_file_targets(peers, self_user_id))
477    }
478
479    /// The stable id of the exit node traffic is currently egressing through, or `None` if none is
480    /// engaged. This is the route updater's resolved + fail-closed answer (see
481    /// [`Status::active_exit_node`](crate::status::Status::active_exit_node)): it differs from the
482    /// configured [`exit_node`](Self::exit_node) selector, which may name a peer that is absent or
483    /// no longer advertising a default route (in which case egress is dropped and this returns
484    /// `None`).
485    pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
486        self.active_exit_rx.borrow().clone()
487    }
488
489    /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
490    ///
491    /// Returns the signed JWT, or the token RPC's own [`ts_control::IdTokenError`]. The kameo
492    /// delegated-reply send error is flattened: a handler error carries the real `IdTokenError`,
493    /// any other send failure (actor shutdown / mailbox closed) is surfaced as
494    /// [`ts_control::IdTokenError::NetworkError`].
495    pub async fn fetch_id_token(
496        &self,
497        audience: String,
498    ) -> Result<String, ts_control::IdTokenError> {
499        self.control
500            .ask(control_runner::FetchIdToken { audience })
501            .await
502            .map_err(flatten_send_err)
503    }
504
505    /// Log this node out of the tailnet: deregister it by expiring its current node key.
506    ///
507    /// Forwards to the control runner, which re-POSTs `/machine/register` with a past expiry over a
508    /// fresh Noise channel. This is a control-plane state change only — it does NOT shut the runtime
509    /// down (the caller follows with [`graceful_shutdown`](Self::graceful_shutdown)) and does not
510    /// touch the on-disk node key. The kameo delegated-reply send error is flattened the same way as
511    /// [`fetch_id_token`](Self::fetch_id_token): a handler error carries the real
512    /// [`ts_control::LogoutError`]; any other send failure (actor shutdown / mailbox closed) is
513    /// surfaced as [`ts_control::LogoutError::NetworkError`].
514    pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
515        self.control
516            .ask(control_runner::Logout)
517            .await
518            .map_err(flatten_logout_send_err)
519    }
520
521    /// Publish a `TXT` DNS record for this node via control's `/machine/set-dns` (Go
522    /// `LocalClient.SetDNS`).
523    ///
524    /// Forwards to the control runner, which POSTs the record over a fresh Noise channel. The kameo
525    /// delegated-reply send error is flattened the same way as [`fetch_id_token`](Self::fetch_id_token):
526    /// a handler error carries the real [`ts_control::SetDnsError`]; any other send failure (actor
527    /// shutdown / mailbox closed) is surfaced as [`ts_control::SetDnsError::NetworkError`].
528    pub async fn set_dns(
529        &self,
530        name: String,
531        value: String,
532    ) -> Result<(), ts_control::SetDnsError> {
533        self.control
534            .ask(control_runner::SetDns { name, value })
535            .await
536            .map_err(flatten_set_dns_send_err)
537    }
538
539    /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` (`acme` feature).
540    ///
541    /// Mirrors [`fetch_id_token`](Self::fetch_id_token): forwards to the control runner, which runs
542    /// the client-side ACME DNS-01 flow on a spawned task and publishes the challenge TXT via the
543    /// node's set-dns RPC. The kameo delegated-reply send error is flattened — a handler error
544    /// carries the real [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox
545    /// closed) is surfaced as a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control
546    /// plane 501s on set-dns.
547    #[cfg(feature = "acme")]
548    pub async fn get_certificate(
549        &self,
550        name: String,
551    ) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
552        self.control
553            .ask(control_runner::GetCertificate { name })
554            .await
555            .map_err(flatten_cert_send_err)
556    }
557
558    /// Resolve which node owns a tailnet source address.
559    ///
560    /// Maps the source IP of `addr` to its owning node. Mirrors tsnet's `LocalClient::WhoIs`.
561    /// Returns `None` if no peer holds that tailnet IP. The returned [`WhoIs`] carries no
562    /// user/login or capability data in this fork (see the [`status`] module docs).
563    pub async fn whois(&self, addr: core::net::SocketAddr) -> Result<Option<WhoIs>, Error> {
564        self.peer_tracker
565            .upgrade()
566            .ok_or(Error {
567                kind: ErrorKind::ActorGone,
568                target_actor: None,
569                message_ty: None,
570            })?
571            .ask(peer_tracker::Whois { addr })
572            .await
573            .map_err(Into::into)
574    }
575
576    /// The current direct-path status to the peer holding tailnet IP `dst`: its confirmed direct UDP
577    /// endpoint and that path's last-measured RTT, or `None` when there is no direct path right now
578    /// (the peer is relayed via DERP, is unknown, or has no disco key).
579    ///
580    /// The latency is the RTT of the most recent disco ping/pong that confirmed the path — a live
581    /// snapshot up to one probe interval stale, NOT a fresh on-demand round-trip (that is a separate,
582    /// heavier capability). Mirrors the direct-path latency Go surfaces for `ipnstate.PeerStatus`.
583    pub async fn direct_path(
584        &self,
585        dst: core::net::IpAddr,
586    ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
587        let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
588            kind: ErrorKind::ActorGone,
589            target_actor: None,
590            message_ty: None,
591        })?;
592
593        // Resolve the tailnet IP to its node, then to its disco key. No node / no disco key ⇒ no
594        // direct path is possible (a peer with no disco key can only be reached via DERP).
595        let Some(node) = peer_tracker
596            .ask(peer_tracker::PeerByTailnetIp { ip: dst })
597            .await?
598        else {
599            return Ok(None);
600        };
601        let Some(disco) = node.disco_key else {
602            return Ok(None);
603        };
604
605        self.direct
606            .ask(direct::DirectPathLatency { disco })
607            .await
608            .map_err(Into::into)
609    }
610
611    /// Send a disco ping to the peer holding tailnet IP `dst` **now** and await the pong, returning
612    /// the fresh round-trip latency and the endpoint that answered, or `None` if no pong arrives
613    /// within `timeout` (or the peer is unknown / has no disco key / no candidate path). This is the
614    /// true on-demand `PingType::Disco` (Go `tailscale ping`), as opposed to
615    /// [`direct_path`](Self::direct_path) which reports the last periodic probe's RTT.
616    ///
617    /// The ping round-trip is awaited OFF the direct manager's mailbox (we take a `MagicSock` handle
618    /// and await on it directly), so a slow/timing-out ping never blocks the actor.
619    pub async fn ping_disco(
620        &self,
621        dst: core::net::IpAddr,
622        timeout: Duration,
623    ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
624        let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
625            kind: ErrorKind::ActorGone,
626            target_actor: None,
627            message_ty: None,
628        })?;
629
630        let Some(node) = peer_tracker
631            .ask(peer_tracker::PeerByTailnetIp { ip: dst })
632            .await?
633        else {
634            return Ok(None);
635        };
636        let Some(disco) = node.disco_key else {
637            return Ok(None);
638        };
639
640        // Cheap synchronous handle fetch, then await the ping OFF the actor mailbox.
641        let Some(sock) = self.direct.ask(direct::SockHandle).await? else {
642            return Ok(None);
643        };
644        // A `ping_now` error is an underlay UDP send failure (not an actor problem); surface it as a
645        // reply-level error. A timed-out / unanswered ping is `Ok(None)`, not an error.
646        sock.ping_now(&disco, timeout).await.map_err(|_| Error {
647            kind: ErrorKind::ReplyErr,
648            target_actor: None,
649            message_ty: None,
650        })
651    }
652
653    /// Change the selected exit node at runtime (the equivalent of Go `tsnet`'s
654    /// `LocalClient.EditPrefs(ExitNodeID/ExitNodeIP)`), without recreating the device.
655    ///
656    /// Updates the live exit-node selector, then asks the peer tracker to re-broadcast the current
657    /// peer set so the route updater and source filter re-resolve the new selector immediately.
658    /// `None` clears the exit node (internet-bound traffic is then dropped, fail-closed, unless this
659    /// node egresses directly). The selection is re-resolved against the live peer set, so passing a
660    /// selector for a peer not yet in the netmap simply takes effect once that peer appears.
661    pub async fn set_exit_node(
662        &self,
663        selector: Option<ts_control::ExitNodeSelector>,
664    ) -> Result<(), Error> {
665        // Update the live cell every reader borrows from. `send_replace` keeps the value current
666        // even with no active receivers (none can have dropped while the runtime is up, but it is
667        // the right non-failing primitive here).
668        self.exit_node_tx.send_replace(selector);
669
670        // Trigger an immediate re-resolution: the route updater (outbound routes + DoH delegation)
671        // and the source filter (inbound validation) both recompute on an `Arc<PeerState>`, so a
672        // re-broadcast applies the new exit without waiting for the next netmap update.
673        self.peer_tracker
674            .upgrade()
675            .ok_or(Error {
676                kind: ErrorKind::ActorGone,
677                target_actor: None,
678                message_ty: None,
679            })?
680            .ask(peer_tracker::RepublishState)
681            .await
682            .map_err(Into::into)
683    }
684
685    /// The currently-selected exit node, or `None` if none is selected.
686    pub fn exit_node(&self) -> Option<ts_control::ExitNodeSelector> {
687        self.env.exit_node()
688    }
689
690    /// Change the set of subnet routes this node advertises at runtime (Go `tailscale set
691    /// --advertise-routes`). Applies BOTH halves together so the wire and the data path agree:
692    ///
693    /// 1. **Wire** — re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
694    ///    (so control grants the node the subnet-router role for exactly these prefixes).
695    /// 2. **Local** — swap the forwarder's accept/dial route table (so the node actually forwards the
696    ///    prefixes it advertises). New flows see the new set; in-flight flows keep their routing.
697    ///
698    /// `routes` is filtered to the IPv4-only, deduplicated set this fork can honor (IPv6 prefixes are
699    /// dropped under the IPv6-off posture — we never advertise a route we won't forward), so the wire
700    /// and forwarder are fed the identical final set. This sets the explicit subnet prefixes only; it
701    /// does NOT touch the exit-node `0.0.0.0/0` advertisement (a separate concern).
702    pub async fn set_advertise_routes(&self, routes: Vec<ipnet::IpNet>) -> Result<(), Error> {
703        // IPv4-only + dedup, mirroring `ts_control::Config::advertised_routes` so the wire grant and
704        // the forwarder accept set never disagree.
705        let filtered = filter_advertise_routes(routes);
706
707        // Local half first: start forwarding the prefixes before control grants them, so there is no
708        // window where control has granted a route the node black-holes. (The reverse order would
709        // briefly advertise a route we don't yet forward.) New flows pick up the table immediately.
710        self.forwarder
711            .ask(forwarder_actor::UpdateRoutes {
712                routes: filtered.clone(),
713            })
714            .await?;
715
716        // Wire half: re-advertise to control on the live map-poll connection.
717        self.control
718            .ask(control_runner::SetAdvertiseRoutes { routes: filtered })
719            .await
720            .map_err(Into::into)
721    }
722
723    /// Subscribe to netmap peer-change events.
724    ///
725    /// Returns a [`watch::Receiver`] whose value is the current set of peer [`StatusNode`]s,
726    /// updated on every netmap state update from control. Mirrors tsnet's `WatchIPNBus`. Await
727    /// [`watch::Receiver::changed`](tokio::sync::watch::Receiver::changed) to react to peers
728    /// joining, leaving, or changing.
729    pub async fn watch_netmap(&self) -> Result<watch::Receiver<Vec<StatusNode>>, Error> {
730        self.peer_tracker
731            .upgrade()
732            .ok_or(Error {
733                kind: ErrorKind::ActorGone,
734                target_actor: None,
735                message_ty: None,
736            })?
737            .ask(peer_tracker::WatchNetmap)
738            .await
739            .map_err(Into::into)
740    }
741
742    /// The current device connection-[`DeviceState`].
743    pub fn device_state(&self) -> DeviceState {
744        self.state_rx.borrow().clone()
745    }
746
747    /// Watch the device connection-[`DeviceState`] (`Connecting` → `Running` / `NeedsLogin` /
748    /// `Expired` / `Failed`).
749    ///
750    /// Returns a [`watch::Receiver`]; await
751    /// [`changed`](tokio::sync::watch::Receiver::changed) to react push-style to control connection
752    /// transitions instead of polling [`status`](Self::status). The initial value is the current
753    /// state. Note: a transient per-reconnect dip back to `Connecting` is **not** currently
754    /// emitted (control transparently reconnects below this layer); the state reflects registration
755    /// outcome and node-key expiry.
756    pub fn watch_state(&self) -> watch::Receiver<DeviceState> {
757        self.state_rx.clone()
758    }
759
760    /// Wait until the device finishes registering, returning a typed outcome.
761    ///
762    /// Resolves `Ok(())` once the device reaches [`DeviceState::Running`]. Returns a typed
763    /// [`RegistrationError`] otherwise — the actionable distinction between "retry", "re-pair", and
764    /// "drive interactive login" that replaces polling [`ipv4_addr`](Self::ipv4_addr) in a loop:
765    /// - `AuthRejected` — bad/expired/unknown auth key. **Permanent** (re-pair).
766    /// - `NeedsLogin(url)` — interactive authorization required (no usable auth key). **Not
767    ///   permanent**: the runtime keeps retrying and will reach `Running` once the user authorizes
768    ///   the URL. An **auth-key** caller should treat this as a failure; an **interactive** caller
769    ///   should ignore this return and instead drive the flow via [`watch_state`](Self::watch_state)
770    ///   (this method returns the URL eagerly rather than blocking for the whole login).
771    /// - `NetworkUnreachable` — control unreachable. **Transient** (retry).
772    /// - `Timeout` — no settled state within `timeout`.
773    ///
774    /// `KeyExpired` is not produced by this initial wait (a node key expires only *after* it has
775    /// come up); observe post-registration expiry via [`watch_state`](Self::watch_state).
776    /// `timeout` of `None` waits indefinitely for a settled state.
777    pub async fn wait_until_running(
778        &self,
779        timeout: Option<Duration>,
780    ) -> Result<(), RegistrationError> {
781        device_state::wait_for_running(self.state_rx.clone(), timeout).await
782    }
783
784    /// Attempt to shut down the runtime gracefully.
785    ///
786    /// Returns false if the shutdown timed out. It is still shut down if it timed out, just
787    /// more violently and with possible resource leaks.
788    pub async fn graceful_shutdown(self, timeout: Option<Duration>) -> bool {
789        self.shutdown.send_replace(true);
790
791        async fn _shutdown_all(runtime: Runtime) {
792            // See the note in `Drop` for why we only need to stop these actors to bring down the
793            // whole runtime.
794
795            let _ignore = runtime.control.stop_gracefully().await;
796            let _ignore = runtime.dataplane.stop_gracefully().await;
797            let _ignore = runtime.env.bus.stop_gracefully().await;
798
799            tokio::join![
800                runtime.control.wait_for_shutdown(),
801                runtime.dataplane.wait_for_shutdown(),
802                runtime.env.bus.wait_for_shutdown(),
803            ];
804        }
805
806        let fut = _shutdown_all(self);
807
808        match timeout {
809            Some(timeout) => tokio::time::timeout(timeout, fut).await.is_ok(),
810            None => {
811                fut.await;
812                true
813            }
814        }
815    }
816}
817
818impl Drop for Runtime {
819    fn drop(&mut self) {
820        // We must have already run `graceful_shutdown`: on the happy path, this does nothing, but
821        // if it timed out, we need to make sure the actors are dead so we don't leak them and their
822        // dependents.
823        if *self.shutdown.borrow() {
824            self.control.kill();
825            self.dataplane.kill();
826            self.env.bus.kill();
827            return;
828        }
829
830        self.shutdown.send_replace(true);
831
832        // Actors shut down when the last ActorRef to them is dropped (as nothing can send them
833        // messages anymore). If we don't hold an ActorRef in Runtime, in general the only thing
834        // that has one is the MessageBus, which each actor subscribes to for a subset of messages.
835        // Hence, if we shut down the bus, most actors die as well.
836
837        // First shut down the actors we have an ActorRef to:
838        try_shutdown(&self.control);
839        try_shutdown(&self.dataplane);
840
841        // Then shutdown the message bus, stopping the rest of the actors:
842        try_shutdown(&self.env.bus);
843    }
844}
845
846fn try_shutdown(a: &ActorRef<impl kameo::Actor>) {
847    if let Err(e) = a.mailbox_sender().try_send(Signal::Stop) {
848        tracing::error!(error = %e, "graceful shutdown failed, killing actor");
849        a.kill();
850    }
851}
852
853/// Build the netstack config shared by both userspace netstacks (application + forwarder) from the
854/// per-deployment `tcp_buffer_size` knob.
855///
856/// `None` keeps the netstack default (256 KiB/direction); `Some(n)` overrides it (e.g. a smaller
857/// window on a memory-constrained exit node forwarding many concurrent flows — see
858/// [`netstack::netcore::Config::tcp_buffer_size`]). Factored out of [`Runtime::spawn`] so the
859/// None-default / Some-override mapping is unit-testable without standing up the actor system.
860fn netstack_config_from(tcp_buffer_size: Option<usize>) -> netstack::netcore::Config {
861    let mut c = netstack::netcore::Config::default();
862    if let Some(tcp_buffer_size) = tcp_buffer_size {
863        c.tcp_buffer_size = tcp_buffer_size;
864    }
865    c
866}
867
868/// Filter a requested advertise-route set to the IPv4-only, deduplicated set this fork can honor,
869/// mirroring [`ts_control::Config::advertised_routes`] so a runtime `set_advertise_routes` feeds the
870/// wire (control grant) and the forwarder (accept/dial table) the identical final set. IPv6 prefixes
871/// are dropped under the IPv6-off posture — we never advertise a route we won't forward. Order is
872/// preserved (first occurrence wins). Factored out so the filter is unit-testable without an actor.
873fn filter_advertise_routes(routes: Vec<ipnet::IpNet>) -> Vec<ipnet::IpNet> {
874    let mut filtered: Vec<ipnet::IpNet> = Vec::new();
875    for net in routes {
876        if matches!(net, ipnet::IpNet::V4(_)) {
877            if !filtered.contains(&net) {
878                filtered.push(net);
879            }
880        } else {
881            tracing::warn!(prefix = %net, "dropping IPv6 advertise route (IPv6-off posture)");
882        }
883    }
884    filtered
885}
886
887/// Flatten a kameo delegated-reply [`SendError`] for the id-token RPC into the RPC's own
888/// [`ts_control::IdTokenError`].
889///
890/// A [`SendError::HandlerError`](kameo::error::SendError::HandlerError) carries the real
891/// `IdTokenError` produced by the handler and is surfaced verbatim. Any other send failure (actor
892/// not running / stopped, mailbox full, send timeout) is a delivery problem rather than an RPC
893/// result, so it collapses to a transient [`ts_control::IdTokenError::NetworkError`]. Factored out
894/// of [`Runtime::fetch_id_token`] so this mapping is unit-testable without standing up an actor.
895fn flatten_send_err<M>(
896    e: kameo::error::SendError<M, ts_control::IdTokenError>,
897) -> ts_control::IdTokenError {
898    match e {
899        kameo::error::SendError::HandlerError(err) => err,
900        _ => ts_control::IdTokenError::NetworkError,
901    }
902}
903
904/// Flatten a kameo `SendError` from the `Logout` ask into a [`ts_control::LogoutError`].
905///
906/// A `HandlerError` carries the real `LogoutError` from the control RPC and is surfaced verbatim;
907/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
908/// problem, not a logout result — collapses to the transient [`ts_control::LogoutError::NetworkError`]
909/// (logout is idempotent, so a retry after a delivery failure is safe). Factored out of
910/// [`Runtime::logout`] so the mapping is unit-testable without standing up an actor.
911fn flatten_logout_send_err<M>(
912    e: kameo::error::SendError<M, ts_control::LogoutError>,
913) -> ts_control::LogoutError {
914    match e {
915        kameo::error::SendError::HandlerError(err) => err,
916        _ => ts_control::LogoutError::NetworkError,
917    }
918}
919
920/// Flatten a kameo `SendError` from the `SetDns` ask into a [`ts_control::SetDnsError`].
921///
922/// A `HandlerError` carries the real `SetDnsError` from the set-dns RPC and is surfaced verbatim;
923/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
924/// problem, not a publish result — collapses to the transient
925/// [`ts_control::SetDnsError::NetworkError`]. Factored out of [`Runtime::set_dns`] so the mapping is
926/// unit-testable without standing up an actor.
927fn flatten_set_dns_send_err<M>(
928    e: kameo::error::SendError<M, ts_control::SetDnsError>,
929) -> ts_control::SetDnsError {
930    match e {
931        kameo::error::SendError::HandlerError(err) => err,
932        _ => ts_control::SetDnsError::NetworkError,
933    }
934}
935
936/// Flatten a kameo `SendError` from the `GetCertificate` ask into a [`ts_control::CertError`].
937///
938/// A `HandlerError` carries the real `CertError` produced by the ACME issuance and is surfaced
939/// verbatim. `CertError` has no transient-network variant, so any other send failure (actor not
940/// running / stopped, mailbox full, send timeout) — a delivery problem rather than an issuance
941/// result — collapses to a [`ts_control::CertError::Io`]. Factored out of
942/// [`Runtime::get_certificate`] so this mapping is unit-testable without standing up an actor.
943#[cfg(feature = "acme")]
944fn flatten_cert_send_err<M>(
945    e: kameo::error::SendError<M, ts_control::CertError>,
946) -> ts_control::CertError {
947    match e {
948        kameo::error::SendError::HandlerError(err) => err,
949        _ => ts_control::CertError::Io(std::io::Error::other(
950            "control runner unavailable for certificate issuance",
951        )),
952    }
953}
954
955#[cfg(test)]
956mod tests {
957    use super::*;
958
959    /// `None` must leave the netstack's own default TCP window in place (the 256 KiB throughput
960    /// default), and must not silently coerce to some other value.
961    #[test]
962    fn netstack_config_none_uses_netstack_default() {
963        let default = netstack::netcore::Config::default();
964        let built = netstack_config_from(None);
965        assert_eq!(
966            built.tcp_buffer_size, default.tcp_buffer_size,
967            "None must inherit the netstack default TCP buffer size"
968        );
969    }
970
971    /// `Some(n)` must override the TCP window (the memory-vs-throughput knob exit-node operators
972    /// reach for), reaching the config that both netstacks are built from.
973    #[test]
974    fn netstack_config_some_overrides_buffer() {
975        let built = netstack_config_from(Some(64 * 1024));
976        assert_eq!(
977            built.tcp_buffer_size,
978            64 * 1024,
979            "Some(n) must override the TCP buffer size that both netstacks use"
980        );
981    }
982
983    /// `set_advertise_routes` must feed the wire and the forwarder the IDENTICAL filtered set:
984    /// IPv4-only (IPv6 dropped under the IPv6-off posture), deduplicated, order preserved.
985    #[test]
986    fn filter_advertise_routes_keeps_v4_dedups_drops_v6() {
987        let v4a: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
988        let v4b: ipnet::IpNet = "192.168.1.0/24".parse().unwrap();
989        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
990
991        // Mixed input with a duplicate v4 and a v6 prefix.
992        let out = filter_advertise_routes(vec![v4a, v6, v4b, v4a]);
993
994        assert_eq!(
995            out,
996            vec![v4a, v4b],
997            "v6 dropped, duplicate v4 collapsed, first-occurrence order preserved"
998        );
999    }
1000
1001    /// An all-IPv6 request filters to empty (we never advertise a route we won't forward) rather
1002    /// than erroring — clearing the advertised set is a legitimate outcome.
1003    #[test]
1004    fn filter_advertise_routes_all_v6_is_empty() {
1005        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1006        assert!(filter_advertise_routes(vec![v6]).is_empty());
1007    }
1008
1009    /// A `HandlerError` carries the real `IdTokenError` from the RPC handler and must pass through
1010    /// verbatim, not be flattened to a generic network error. Using an `Internal(_)` payload (not
1011    /// `NetworkError`) makes the passthrough observable: a buggy flatten that always returned
1012    /// `NetworkError` would fail this assertion.
1013    #[test]
1014    fn flatten_send_err_handler_error_passes_through() {
1015        // Build an `Internal(_)` payload via the public `From<Utf8Error>` conversion (no extra
1016        // deps): it is distinct from the `_ => NetworkError` fallback, so a buggy flatten that
1017        // always returned `NetworkError` would fail this assertion.
1018        // Route the invalid bytes through a runtime Vec so the `invalid_from_utf8` lint (which only
1019        // fires on compile-time-known literals) doesn't flag this intentional bad input.
1020        let bytes = vec![0xffu8, 0xfe];
1021        let utf8_err = core::str::from_utf8(&bytes).unwrap_err();
1022        let inner = ts_control::IdTokenError::from(utf8_err);
1023        assert!(matches!(inner, ts_control::IdTokenError::Internal(_)));
1024        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1025            kameo::error::SendError::HandlerError(inner.clone());
1026        assert_eq!(flatten_send_err(e), inner);
1027    }
1028
1029    /// A non-handler send failure (actor stopped) is a delivery problem, not an RPC result, so it
1030    /// must collapse to a transient `NetworkError`.
1031    #[test]
1032    fn flatten_send_err_actor_stopped_is_network_error() {
1033        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1034            kameo::error::SendError::ActorStopped;
1035        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1036    }
1037
1038    /// `ActorNotRunning` (the message bounces back undelivered) is likewise a delivery failure and
1039    /// must map to a transient `NetworkError`.
1040    #[test]
1041    fn flatten_send_err_actor_not_running_is_network_error() {
1042        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1043            kameo::error::SendError::ActorNotRunning(control_runner::FetchIdToken {
1044                audience: "sts.amazonaws.com".to_string(),
1045            });
1046        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1047    }
1048
1049    /// A `HandlerError` from the logout RPC carries the real `LogoutError` and must pass through
1050    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1051    /// passthrough observable.
1052    #[test]
1053    fn flatten_logout_send_err_handler_error_passes_through() {
1054        let inner = ts_control::LogoutError::Internal(ts_control::LogoutInternalErrorKind::Http);
1055        assert!(matches!(inner, ts_control::LogoutError::Internal(_)));
1056        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1057            kameo::error::SendError::HandlerError(inner.clone());
1058        assert_eq!(flatten_logout_send_err(e), inner);
1059    }
1060
1061    /// A non-handler send failure (actor stopped) is a delivery problem, not a logout result, and
1062    /// collapses to a transient `NetworkError` (logout is idempotent, so a retry is safe).
1063    #[test]
1064    fn flatten_logout_send_err_actor_stopped_is_network_error() {
1065        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1066            kameo::error::SendError::ActorStopped;
1067        assert_eq!(
1068            flatten_logout_send_err(e),
1069            ts_control::LogoutError::NetworkError
1070        );
1071    }
1072
1073    /// A `HandlerError` from the set-dns RPC carries the real `SetDnsError` and must pass through
1074    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1075    /// passthrough observable.
1076    #[test]
1077    fn flatten_set_dns_send_err_handler_error_passes_through() {
1078        let inner = ts_control::SetDnsError::Internal(ts_control::SetDnsInternalErrorKind::Http);
1079        assert!(matches!(inner, ts_control::SetDnsError::Internal(_)));
1080        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
1081            kameo::error::SendError::HandlerError(inner.clone());
1082        assert_eq!(flatten_set_dns_send_err(e), inner);
1083    }
1084
1085    /// A non-handler send failure (actor stopped) is a delivery problem, not a publish result, and
1086    /// collapses to a transient `NetworkError`.
1087    #[test]
1088    fn flatten_set_dns_send_err_actor_stopped_is_network_error() {
1089        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
1090            kameo::error::SendError::ActorStopped;
1091        assert_eq!(
1092            flatten_set_dns_send_err(e),
1093            ts_control::SetDnsError::NetworkError
1094        );
1095    }
1096}