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;
37/// Unified IPN notification bus ([`Notify`] / [`watch_ipn_bus`](Runtime::watch_ipn_bus)), mirroring
38/// Go `ipn` `LocalBackend.WatchNotifications` / the `WatchIPNBus` LocalAPI.
39pub mod ipn_bus;
40mod magic_dns;
41pub use magic_dns::DnsQueryResult;
42mod multiderp;
43mod netstack_actor;
44mod packetfilter;
45pub mod peer_tracker;
46mod peerapi;
47mod peerapi_doh;
48mod route_updater;
49/// Stored Serve config + accept-loop runtime (`tsnet`'s `Get/SetServeConfig` + serving runtime).
50pub mod serve;
51mod src_filter;
52/// Netmap status snapshot, WhoIs, and watcher types.
53pub mod status;
54/// Taildrop peer-to-peer file transfer store.
55pub mod taildrop;
56pub mod taildrop_send;
57/// Tailnet-Lock (TKA) chain-sync orchestration: bootstrap + offer/send driver (the runtime layer
58/// that bridges the `ts_control` sync RPCs and the `ts_tka` chain logic).
59mod tka_sync;
60#[cfg(feature = "tun")]
61mod tun_actor;
62
63pub use device_state::{DeviceState, RegistrationError};
64pub(crate) use env::Env;
65pub use error::{Error, ErrorKind};
66pub use ipn_bus::{IpnBusWatcher, Notify, NotifyWatchOpt};
67pub use status::{FileTarget, NetcheckReport, RegionLatency, Status, StatusNode, WhoIs};
68pub use ts_dataplane::{CaptureHook, CapturePath};
69
70use crate::peer_tracker::PeerTracker;
71
72/// The runtime for a tailscale device.
73pub struct Runtime {
74    /// Reference to the control actor.
75    pub control: ActorRef<ControlRunner>,
76    dataplane: ActorRef<DataplaneActor>,
77    /// Reference to the direct (disco/UDP underlay) manager, retained so [`Runtime::rebind`] can
78    /// ask it to re-bind the underlay socket on a network/link change.
79    direct: ActorRef<DirectManager>,
80    /// Reference to the application netstack actor. `None` in TUN transport mode, where there is
81    /// no userspace application netstack (the application data path is a real kernel TUN device).
82    netstack: Option<WeakActorRef<NetstackActor>>,
83    /// Reference to the peer tracker for peer lookups.
84    pub peer_tracker: WeakActorRef<PeerTracker>,
85    /// Fallback TCP handler registry, bound to the application netstack. `None` in TUN transport
86    /// mode (no application netstack exists to attach it to).
87    fallback_tcp: Option<fallback_tcp::FallbackTcpManager>,
88    /// Reference to the MagicDNS responder, retained so [`Runtime::query_dns`] can run a query
89    /// through the live `100.100.100.100` forward path. `None` in TUN transport mode (no
90    /// `MagicDnsActor` is spawned there — TUN-mode MagicDNS is an in-packet intercept, not an actor).
91    magic_dns: Option<ActorRef<magic_dns::MagicDnsActor>>,
92    /// Reference to the forwarder actor, retained so [`Runtime::set_advertise_routes`] can push a
93    /// new accept/dial route table onto the running forwarder (the local half of advertising
94    /// routes). Without this the strong ref would drop after the startup `GetChannel` and the
95    /// forwarder would be reachable only via the message bus.
96    forwarder: ActorRef<ForwarderActor>,
97    /// Reference to the multiderp manager, retained so [`Runtime::status`] can resolve each
98    /// relayed peer's DERP region id to its region **code** (`ipnstate.PeerStatus.Relay`). Without
99    /// this the strong ref would drop after startup (it is cloned into the direct manager + route
100    /// updater) and the region-code map would be unreachable.
101    multiderp: ActorRef<Multiderp>,
102    env: Env,
103    shutdown: watch::Sender<bool>,
104    /// Sender side of the exit-node selector `watch` cell. Held privately here (not on the cloned
105    /// `Env`, which keeps only the read side) so that only `Runtime::set_exit_node` can mutate the
106    /// selection; the route updater and source filter re-read it via [`Env::exit_node`].
107    exit_node_tx: watch::Sender<Option<ts_control::ExitNodeSelector>>,
108    /// Sender side of the accept-routes preference `watch` cell. Held privately here (same rationale
109    /// as [`exit_node_tx`](Self::exit_node_tx)) so that only [`Runtime::set_accept_routes`] can
110    /// toggle it; the route updater and source filter re-read it via [`Env::accept_routes`].
111    accept_routes_tx: watch::Sender<bool>,
112    /// Sender side of the accept-dns preference `watch` cell. Held privately here (same rationale as
113    /// [`accept_routes_tx`](Self::accept_routes_tx)) so that only [`Runtime::set_accept_dns`] can
114    /// toggle it; the MagicDNS responder re-reads it via [`Env::accept_dns`] when it rebuilds its
115    /// view (the republish that `set_accept_dns` triggers).
116    accept_dns_tx: watch::Sender<bool>,
117    /// Receiver mirroring the *active* (resolved + fail-closed) exit node's stable id, fed by the
118    /// route updater. Read by [`Runtime::status`] / [`Runtime::active_exit_node`] to report which
119    /// exit node traffic is actually egressing through (vs. the merely-configured selector).
120    active_exit_rx: watch::Receiver<Option<ts_control::StableNodeId>>,
121    /// Receiver for the device connection-state cell, fed by the control runner. Read by
122    /// [`Runtime::watch_state`] and [`Runtime::wait_until_running`].
123    state_rx: watch::Receiver<DeviceState>,
124    /// Receiver for the retained peer-capability grants, fed by the packet-filter updater. Read by
125    /// [`Runtime::whois`] to resolve the flow-scoped cap map (Go `apitype.WhoIsResponse.CapMap`).
126    cap_grants_rx: watch::Receiver<packetfilter::CapGrants>,
127    /// Live advertised-route preference (explicit subnet routes + the exit-node flag), seeded from
128    /// the startup config. [`Runtime::set_advertise_routes`] and [`set_advertise_exit_node`] each
129    /// mutate their part under this lock then re-send the composed set, so the two compose.
130    advertise: std::sync::Mutex<AdvertiseState>,
131}
132
133impl Runtime {
134    /// Spawn a new runtime with the given parameters for connecting to a tailnet.
135    pub async fn spawn(
136        config: ts_control::Config,
137        auth_key: Option<String>,
138        keys: ts_keys::NodeState,
139    ) -> Result<Self, Error> {
140        let (shutdown_tx, shutdown_rx) = watch::channel(false);
141
142        // The exit-node selector, accept-routes, and accept-dns preferences are live `watch` cells so
143        // `Device::set_exit_node` / `set_accept_routes` / `set_accept_dns` can change them at runtime.
144        // `new_with_runtime_txs` returns each `Sender` (mutation capability) grouped in `pref_cells`
145        // so they are retained privately on the `Runtime`, while only the `Receiver`s (the readers'
146        // contract) live on the cloned `Env`. Initial values come from `ForwarderConfig`.
147        let (env, pref_cells) = Env::new_with_runtime_txs(
148            keys,
149            shutdown_rx,
150            env::ForwarderConfig::from_control_config(&config),
151        );
152
153        // Both userspace netstacks (application + forwarder) share one netstack config. Honor the
154        // per-deployment TCP buffer knob when set, otherwise fall back to the netstack default.
155        let netstack_config = netstack_config_from(config.tcp_buffer_size);
156
157        let dataplane = DataplaneActor::spawn(env.clone());
158
159        let (netstack_id, netstack_up, netstack_down) =
160            dataplane.ask(dataplane::NewOverlayTransport).await?;
161
162        // A second overlay transport feeds the dedicated any-IP forwarder netstack. Inbound packets
163        // for advertised subnet routes / the exit-node default route are routed here (see
164        // `route_updater`), keeping forwarded flows off the application netstack.
165        let (forwarder_id, forwarder_up, forwarder_down) =
166            dataplane.ask(dataplane::NewOverlayTransport).await?;
167
168        let multiderp = Multiderp::spawn((env.clone(), dataplane.clone()));
169
170        // Spawn the direct (disco) underlay manager before the route updater. Its `on_start`
171        // binds the UDP socket and registers its transport synchronously, so by the time the
172        // route updater asks it for the direct transport id it is guaranteed to be available.
173        let direct = DirectManager::spawn((env.clone(), dataplane.clone(), multiderp.clone()));
174
175        // Spawn the forwarder before the route updater. Its `on_start` builds the forwarder
176        // netstack, enables any-IP acceptance, and starts the per-port accept loops synchronously,
177        // so by the time the route updater begins delivering advertised prefixes to
178        // `forwarder_id` the netstack is already draining its transport.
179        let forwarder = ForwarderActor::spawn((
180            env.clone(),
181            netstack_config.clone(),
182            forwarder_up,
183            forwarder_down,
184        ));
185        // Force `on_start` to finish (any-IP enabled, accept loops live) before the route updater
186        // can route the first inbound flow to `forwarder_id`: an `ask` blocks until the actor has
187        // started.
188        //
189        // The forwarder netstack's overlay `Channel` is reused by the TUN application path for
190        // recursive / exit-node-DoH MagicDNS forwarding (TUN mode has no application netstack of its
191        // own, but the forwarder netstack runs in both modes and egresses over the overlay — the
192        // anti-leak property `forward_query`/`forward_doh` require). Only the `tun` Tun arm consumes
193        // it, so it is unused when the `tun` feature is off — allow that without warn-as-error.
194        #[cfg_attr(not(feature = "tun"), allow(unused_variables))]
195        let (forwarder_channel,) = forwarder.ask(forwarder_actor::GetChannel).await?;
196
197        // The route updater is the single authoritative resolver of the active (resolved,
198        // fail-closed) exit node; it publishes the resolved stable id into this watch cell so
199        // `Runtime::status` can report which exit is actually engaged (not just configured).
200        let (active_exit_tx, active_exit_rx) = watch::channel(None);
201        route_updater::RouteUpdater::spawn((
202            multiderp.clone(),
203            direct.clone(),
204            env.clone(),
205            netstack_id,
206            forwarder_id,
207            active_exit_tx,
208        ));
209        // The packet-filter updater also surfaces the retained cap-grants (for flow-scoped WhoIs)
210        // through a `watch` cell whose receiver the `Runtime` holds — the bus has no replay, so a
211        // `watch` is how `Runtime::whois` reads the current grants on demand.
212        let (cap_grants_tx, cap_grants_rx) = watch::channel(Default::default());
213        packetfilter::PacketfilterUpdater::spawn((env.clone(), cap_grants_tx));
214        src_filter::SourceFilterUpdater::spawn(env.clone());
215        let peer_tracker = PeerTracker::spawn(env.clone()).downgrade();
216
217        // Select the application data path from the transport mode. The forwarder/egress path
218        // above is UNCHANGED in both modes — TUN mode only swaps the application data path, never
219        // the forwarder. `config` is moved into `ControlRunner::spawn` below, so branch on a
220        // borrow and clone the small `TunConfig` where needed before the move.
221        //
222        // - Netstack (the default, and the only reachable arm when the `tun` feature is off):
223        //   spawn the application netstack + MagicDNS responder + fallback-TCP registry, all on
224        //   the `netstack_up`/`netstack_down` overlay seam.
225        // - Tun: spawn `TunActor` on that same overlay seam instead; no application netstack and
226        //   no MagicDNS responder exist, and `netstack`/`fallback_tcp` are `None`.
227        // - Tun requested but built without the `tun` feature: hard-error (a config/build
228        //   mismatch knowable at spawn time). NEVER silently fall back to netstack.
229        let (netstack, fallback_tcp, magic_dns) = match &config.transport_mode {
230            ts_control::TransportMode::Netstack => {
231                let netstack = NetstackActor::spawn((
232                    env.clone(),
233                    netstack_config,
234                    netstack_up,
235                    netstack_down,
236                ));
237
238                // Fetch the netstack channel while we still hold the strong ActorRef, then spawn
239                // the MagicDNS responder on it. Its ActorRef is retained on `Runtime` so
240                // `query_dns` can drive the live forward path; the serve loop itself is owned by the
241                // actor's internal JoinSet.
242                let (channel,) = netstack.ask(netstack_actor::GetChannel).await?;
243                // The fallback-TCP registry attaches to the application netstack — the same one
244                // that carries the embedder's explicit `Device::tcp_listen` sockets — so a
245                // fallback handler sees exactly the inbound flows no explicit listener matched.
246                let fallback_tcp = fallback_tcp::FallbackTcpManager::new(channel.clone());
247                let magic_dns = magic_dns::MagicDnsActor::spawn((env.clone(), channel));
248
249                (
250                    Some(netstack.downgrade()),
251                    Some(fallback_tcp),
252                    Some(magic_dns),
253                )
254            }
255
256            #[cfg(feature = "tun")]
257            ts_control::TransportMode::Tun(tun_cfg) => {
258                // Reuse the same `netstack_up`/`netstack_down` overlay-transport pair that would
259                // have fed the netstack — it is just the application-side overlay seam (the name
260                // is historical). No NetstackActor / MagicDnsActor is spawned.
261                tun_actor::TunActor::spawn((
262                    env.clone(),
263                    tun_cfg.clone(),
264                    netstack_up,
265                    netstack_down,
266                    // Reuse the forwarder netstack's overlay `Channel` for recursive / exit-node-DoH
267                    // MagicDNS forwarding in the TUN datapath (TUN mode has no application netstack
268                    // Channel of its own). Egresses over the overlay — anti-leak preserved.
269                    //
270                    // Host-route gating (subnet routes gated on `--accept-routes`, the host `/0` from
271                    // the selected exit peer) is no longer snapshotted here: `TunActor` reads the live
272                    // `Env` cells (`accept_routes`/`exit_node`) on every host-FIB apply — both the
273                    // device-build path and the `PeerState` re-apply path — and folds the union of
274                    // peers' AllowedIPs (see `tun_actor::host_routes_from_node`). A runtime
275                    // `set_accept_routes` / `set_exit_node` toggle re-broadcasts the peer state, so the
276                    // host routing table is re-steered live (no device rebuild needed).
277                    forwarder_channel.clone(),
278                ));
279
280                (None, None, None)
281            }
282
283            #[cfg(not(feature = "tun"))]
284            ts_control::TransportMode::Tun(_) => {
285                return Err(Error {
286                    kind: ErrorKind::TunUnavailable,
287                    target_actor: None,
288                    message_ty: None,
289                });
290            }
291        };
292
293        // Device connection-state cell. Created here (not inside the actor) so the control runner's
294        // `on_start` can publish `Failed`/`NeedsLogin` and still return `Err` without the sender
295        // being tied to a `Self` that never gets constructed on a hard registration failure.
296        let (state_tx, state_rx) = watch::channel(DeviceState::Connecting);
297
298        // Seed the live advertised-route preference from the startup config before `config` moves
299        // into the control runner, so the runtime setters compose against the configured baseline.
300        let advertise = std::sync::Mutex::new(AdvertiseState {
301            routes: config.advertise_routes.clone(),
302            exit_node: config.advertise_exit_node,
303        });
304
305        let control = ControlRunner::spawn(control_runner::Params {
306            config,
307            auth_key,
308            env: env.clone(),
309            state_tx,
310        });
311
312        Ok(Self {
313            control,
314            dataplane,
315            direct,
316            peer_tracker,
317            fallback_tcp,
318            magic_dns,
319            forwarder,
320            multiderp,
321            netstack,
322            env,
323            shutdown: shutdown_tx,
324            exit_node_tx: pref_cells.exit_node,
325            accept_routes_tx: pref_cells.accept_routes,
326            accept_dns_tx: pref_cells.accept_dns,
327            active_exit_rx,
328            state_rx,
329            cap_grants_rx,
330            advertise,
331        })
332    }
333
334    /// Register a fallback TCP handler consulted for every inbound TCP flow that matches no
335    /// explicit listener (`tsnet.Server.RegisterFallbackTCPHandler` parity).
336    ///
337    /// The returned [`fallback_tcp::FallbackTcpHandle`] deregisters the handler when dropped. See
338    /// [`fallback_tcp`] for the dispatch contract and anti-leak guarantees.
339    ///
340    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
341    /// application netstack to attach a fallback handler to.
342    pub fn register_fallback_tcp_handler(
343        &self,
344        cb: Arc<
345            dyn Fn(core::net::SocketAddr, core::net::SocketAddr) -> fallback_tcp::FallbackDecision
346                + Send
347                + Sync,
348        >,
349    ) -> Result<fallback_tcp::FallbackTcpHandle, Error> {
350        Ok(self
351            .fallback_tcp
352            .as_ref()
353            .ok_or(Error {
354                kind: ErrorKind::UnsupportedInTunMode,
355                target_actor: None,
356                message_ty: None,
357            })?
358            .register(cb))
359    }
360
361    /// Get a channel to send commands to the netstack.
362    ///
363    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
364    /// application netstack.
365    pub async fn channel(&self) -> Result<Channel, Error> {
366        let (channel,) = self
367            .netstack
368            .as_ref()
369            .ok_or(Error {
370                kind: ErrorKind::UnsupportedInTunMode,
371                target_actor: None,
372                message_ty: None,
373            })?
374            .upgrade()
375            .ok_or(Error {
376                kind: ErrorKind::ActorGone,
377                target_actor: None,
378                message_ty: None,
379            })?
380            .ask(netstack_actor::GetChannel)
381            .await?;
382
383        Ok(channel)
384    }
385
386    /// Resolve `name` for `qtype` through the live MagicDNS responder (the `100.100.100.100`
387    /// forward path), returning the raw DNS response, its RCODE, and the upstream resolver(s)
388    /// consulted (analogue of Go `LocalClient.QueryDNS`).
389    ///
390    /// This drives the *real* responder — the same `decide`/forward logic an on-the-wire query
391    /// hits — so the answer and its anti-leak posture (a tailnet-suffix name never egresses; a
392    /// recursive forward delegates to the active exit node's DoH; only IPv4 upstreams are dialed)
393    /// match exactly what a tailnet client observes. `qtype` is the raw RFC 1035 TYPE (`1`=A,
394    /// `28`=AAAA, `12`=PTR, or any other).
395    ///
396    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where MagicDNS is an
397    /// in-packet intercept on the host's own resolver rather than an actor that can be queried, and
398    /// [`ErrorKind::ActorGone`] if the responder has shut down.
399    pub async fn query_dns(
400        &self,
401        name: &str,
402        qtype: u16,
403    ) -> Result<magic_dns::DnsQueryResult, Error> {
404        let result = self
405            .magic_dns
406            .as_ref()
407            .ok_or(Error {
408                kind: ErrorKind::UnsupportedInTunMode,
409                target_actor: None,
410                message_ty: None,
411            })?
412            .ask(magic_dns::Query {
413                name: name.to_owned(),
414                qtype,
415            })
416            .await?;
417
418        Ok(result)
419    }
420
421    /// The Taildrop file store, if Taildrop is enabled (`taildrop_dir` configured and the store
422    /// initialized). `None` when disabled — fail-closed. Shared with the peerAPI Taildrop server so
423    /// the embedder's read APIs and the receive path see the same on-disk store.
424    pub fn taildrop_store(&self) -> Option<Arc<crate::taildrop::TaildropStore>> {
425        self.env.taildrop_store.clone()
426    }
427
428    /// The shared Funnel ingress slot the peerAPI `/v0/ingress` route reads per connection.
429    ///
430    /// `Device::listen_funnel` installs a [`FunnelManager`](crate::funnel::FunnelManager)'s sink here
431    /// to make the route live (the peerAPI server is already running from startup). Returns a clone of
432    /// the runtime-lifetime `Arc` so the device can write the slot without restarting the server. See
433    /// [`crate::funnel`] for the ingress data path.
434    pub fn funnel_ingress_slot(&self) -> crate::funnel::FunnelIngressSlot {
435        self.env.funnel_ingress.clone()
436    }
437
438    /// The shared "Funnel ingress listener active" flag (the same `Arc` the control session reads to
439    /// set `HostInfo.IngressEnabled`). `Device::listen_funnel` flips it `true` while a funnel listener
440    /// is up so control routes Funnel traffic to this node; clearing it advertises no live endpoint.
441    pub fn ingress_active_flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
442        self.env.ingress_active.clone()
443    }
444
445    /// Install (`Some`) or clear (`None`) the debug packet-capture hook on the running dataplane.
446    /// `Some(hook)` tees every plaintext packet crossing the datapath to `hook` until it is cleared;
447    /// `None` stops capture. Mirrors Go `tstun.Wrapper.InstallCaptureHook` / `ClearCaptureSink`.
448    pub async fn install_capture(
449        &self,
450        hook: Option<ts_dataplane::CaptureHook>,
451    ) -> Result<(), Error> {
452        self.dataplane
453            .ask(dataplane::InstallCapture { hook })
454            .await
455            .map_err(Into::into)
456    }
457
458    /// Re-bind the underlay UDP socket after a network/link change (Wi-Fi switch, sleep/wake). The
459    /// embedder's own link monitor calls this (the engine owns the socket re-bind; the embedder owns
460    /// OS netmon). Re-binds the socket (same-port-preferred, IPv4-only invariant preserved) and
461    /// resets the now-stale local NAT mapping — clearing learned reflexive addresses and every
462    /// confirmed direct path while keeping candidate endpoints, so peers re-probe over the new socket
463    /// and relay over DERP (never a direct host dial) until a path re-confirms. Peers, control, the
464    /// netmap, disco state, and DERP are untouched. A no-op when the underlay is inert (bind failed
465    /// at startup, DERP-only). Mirrors Go magicsock `Conn.Rebind` + `resetEndpointStates`.
466    pub async fn rebind(&self) -> Result<(), Error> {
467        self.direct.ask(direct::Rebind).await.map_err(Error::from)
468    }
469
470    /// A snapshot of the local netmap: this node plus every known peer.
471    ///
472    /// Combines the self node held by the control runner with the peer set held by the peer
473    /// tracker. Mirrors tsnet's `LocalClient::Status`.
474    ///
475    /// `self_node` is `None` until the first netmap update has been received from control. Peer
476    /// entries carry no online/user/capability data (see the [`status`] module docs for that gap).
477    pub async fn status(&self) -> Result<Status, Error> {
478        let self_node_domain = self.control.ask(control_runner::SelfNode).await?;
479        // The MagicDNS suffix is the self node's FQDN minus its host label — already split into
480        // `Node.tailnet` at decode time (Go derives it the same way in `NetworkMap.MagicDNSSuffix`).
481        // Capture it before the domain `Node` is mapped away into a `StatusNode`.
482        let magic_dns_suffix = self_node_domain.as_ref().and_then(|n| n.tailnet.clone());
483        let self_node = self_node_domain.as_ref().map(StatusNode::from_node);
484
485        let peers_with_ids = self
486            .peer_tracker
487            .upgrade()
488            .ok_or(Error {
489                kind: ErrorKind::ActorGone,
490                target_actor: None,
491                message_ty: None,
492            })?
493            .ask(peer_tracker::GetStatus)
494            .await?;
495
496        // Join per-peer connectivity (Go `PeerStatus.CurAddr`): one batched query to the direct
497        // manager for every peer's current trusted direct endpoint, then fill `cur_addr` on each
498        // `StatusNode`. A peer absent from the map is relayed via DERP (`cur_addr = None`). This is a
499        // live snapshot — the direct path can expire/re-confirm between calls (matches Go's snapshot
500        // semantics). The `watch_netmap` stream intentionally carries no connectivity (it is a netmap
501        // watch, not a path-state watch, and does not re-fire on direct↔relay flips).
502        let ids: Vec<ts_transport::PeerId> = peers_with_ids.iter().map(|(id, _)| *id).collect();
503        let best_addrs = self
504            .direct
505            .ask(direct::BestAddrs { ids: ids.clone() })
506            .await
507            .unwrap_or_default();
508
509        // For the peers with NO direct path (relayed via DERP), resolve the region CODE they relay
510        // through (Go `PeerStatus.Relay`). One batched ask to multiderp; `cur_addr` and `relay` are
511        // mutually exclusive for a routed peer, mirroring Go's empty-vs-set strings.
512        let relay_ids: Vec<ts_transport::PeerId> = ids
513            .into_iter()
514            .filter(|id| !best_addrs.contains_key(id))
515            .collect();
516        let relay_codes = if relay_ids.is_empty() {
517            Default::default()
518        } else {
519            self.multiderp
520                .ask(multiderp::RelayCodesForPeers { ids: relay_ids })
521                .await
522                .unwrap_or_default()
523        };
524
525        let peers = peers_with_ids
526            .into_iter()
527            .map(|(id, mut node)| match best_addrs.get(&id).copied() {
528                Some(addr) => {
529                    node.cur_addr = Some(addr);
530                    node
531                }
532                None => {
533                    node.relay = relay_codes.get(&id).cloned();
534                    node
535                }
536            })
537            .collect();
538
539        Ok(Status {
540            self_node,
541            peers,
542            active_exit_node: self.active_exit_node(),
543            magic_dns_suffix,
544        })
545    }
546
547    /// List the tailnet peers this node can Taildrop a file *to* (Go LocalAPI `FileTargets`).
548    ///
549    /// Mirrors the upstream send-path filter (`feature/taildrop` `Extension::FileTargets`): a peer
550    /// qualifies when it advertises a reachable peerAPI **and** is either owned by the same user as
551    /// this node **or** explicitly granted the file-sharing-target capability. The whole list is
552    /// gated on this node holding the file-sharing capability (control sets it when the admin enables
553    /// Taildrop) — absent that, an empty list (fail-closed, not an error, matching how the receive
554    /// store returns empty when disabled). Results are sorted by the peer's MagicDNS name.
555    ///
556    /// Targets are listed regardless of current online state (upstream's `FileTargets` does not gate
557    /// on online either; an offline target's send will simply time out). The self node is never
558    /// included. Returns empty before the first netmap.
559    ///
560    /// Divergence from Go: the upstream filter also excludes `tvOS` peers, which this fork cannot
561    /// reproduce (the domain node carries no OS string); the impact is negligible — the actual send
562    /// fail-closes if such a peer refused the transfer.
563    pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
564        // Node-level gate: this node must hold the file-sharing capability (Taildrop enabled by the
565        // admin). Read it off the self node's cap map, like Go's `hasCapFileSharing()`.
566        let self_node = self.control.ask(control_runner::SelfNode).await?;
567        let Some(self_node) = self_node else {
568            return Ok(Vec::new()); // no netmap yet
569        };
570        if !self_node.can_share_files() {
571            return Ok(Vec::new()); // Taildrop not enabled for the tailnet — fail-closed
572        }
573        let self_user_id = self_node.user_id;
574
575        let peers = self
576            .peer_tracker
577            .upgrade()
578            .ok_or(Error {
579                kind: ErrorKind::ActorGone,
580                target_actor: None,
581                message_ty: None,
582            })?
583            .ask(peer_tracker::AllPeers)
584            .await?;
585
586        // Eligibility + ordering live in `build_file_targets` (pure, unit-tested in `status`).
587        Ok(status::build_file_targets(peers, self_user_id))
588    }
589
590    /// The stable id of the exit node traffic is currently egressing through, or `None` if none is
591    /// engaged. This is the route updater's resolved + fail-closed answer (see
592    /// [`Status::active_exit_node`](crate::status::Status::active_exit_node)): it differs from the
593    /// configured [`exit_node`](Self::exit_node) selector, which may name a peer that is absent or
594    /// no longer advertising a default route (in which case egress is dropped and this returns
595    /// `None`).
596    pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
597        self.active_exit_rx.borrow().clone()
598    }
599
600    /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
601    ///
602    /// Returns the signed JWT, or the token RPC's own [`ts_control::IdTokenError`]. The kameo
603    /// delegated-reply send error is flattened: a handler error carries the real `IdTokenError`,
604    /// any other send failure (actor shutdown / mailbox closed) is surfaced as
605    /// [`ts_control::IdTokenError::NetworkError`].
606    pub async fn fetch_id_token(
607        &self,
608        audience: String,
609    ) -> Result<String, ts_control::IdTokenError> {
610        self.control
611            .ask(control_runner::FetchIdToken { audience })
612            .await
613            .map_err(flatten_send_err)
614    }
615
616    /// Log this node out of the tailnet: deregister it by expiring its current node key.
617    ///
618    /// Forwards to the control runner, which re-POSTs `/machine/register` with a past expiry over a
619    /// fresh Noise channel. This is a control-plane state change only — it does NOT shut the runtime
620    /// down (the caller follows with [`graceful_shutdown`](Self::graceful_shutdown)) and does not
621    /// touch the on-disk node key. The kameo delegated-reply send error is flattened the same way as
622    /// [`fetch_id_token`](Self::fetch_id_token): a handler error carries the real
623    /// [`ts_control::LogoutError`]; any other send failure (actor shutdown / mailbox closed) is
624    /// surfaced as [`ts_control::LogoutError::NetworkError`].
625    pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
626        self.control
627            .ask(control_runner::Logout)
628            .await
629            .map_err(flatten_logout_send_err)
630    }
631
632    /// Publish a `TXT` DNS record for this node via control's `/machine/set-dns` (Go
633    /// `LocalClient.SetDNS`).
634    ///
635    /// Forwards to the control runner, which POSTs the record over a fresh Noise channel. The kameo
636    /// delegated-reply send error is flattened the same way as [`fetch_id_token`](Self::fetch_id_token):
637    /// a handler error carries the real [`ts_control::SetDnsError`]; any other send failure (actor
638    /// shutdown / mailbox closed) is surfaced as [`ts_control::SetDnsError::NetworkError`].
639    pub async fn set_dns(
640        &self,
641        name: String,
642        value: String,
643    ) -> Result<(), ts_control::SetDnsError> {
644        self.control
645            .ask(control_runner::SetDns { name, value })
646            .await
647            .map_err(flatten_set_dns_send_err)
648    }
649
650    /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` (`acme` feature).
651    ///
652    /// Mirrors [`fetch_id_token`](Self::fetch_id_token): forwards to the control runner, which runs
653    /// the client-side ACME DNS-01 flow on a spawned task and publishes the challenge TXT via the
654    /// node's set-dns RPC. The kameo delegated-reply send error is flattened — a handler error
655    /// carries the real [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox
656    /// closed) is surfaced as a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control
657    /// plane 501s on set-dns.
658    #[cfg(feature = "acme")]
659    pub async fn get_certificate(
660        &self,
661        name: String,
662    ) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
663        self.control
664            .ask(control_runner::GetCertificate { name })
665            .await
666            .map_err(flatten_cert_send_err)
667    }
668
669    /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` and return the
670    /// **PEM pair** `(cert_chain_pem, key_pem)` — the analog of Go's
671    /// `LocalClient.CertPairWithValidity`, for writing the daemon's on-disk `.crt` + `.key`
672    /// (`tnet cert`). `acme` feature.
673    ///
674    /// Same issuance as [`get_certificate`](Self::get_certificate) (one client-side ACME DNS-01
675    /// order, challenge published via the node's set-dns RPC) — only the result shape differs: this
676    /// returns the leaf+chain PEM and the leaf-key PEM instead of the opaque
677    /// [`CertifiedKey`](ts_control::tls::CertifiedKey). The second element is the **leaf private
678    /// key** PEM; it is never logged anywhere on this path.
679    ///
680    /// **`min_validity` (honest "always fresh").** Go's `CertPairWithValidity` reuses a cached cert
681    /// when it has at least `min_validity` of its lifetime left, and re-issues otherwise. This fork
682    /// has **no cert cache** — every call performs a fresh issuance — so `min_validity` is accepted
683    /// for signature compatibility but does not change behavior: a freshly issued cert (full
684    /// lifetime) trivially satisfies any `min_validity`. A reuse cache is separate future work; this
685    /// does NOT fake one.
686    ///
687    /// Mirrors [`get_certificate`](Self::get_certificate)'s error handling: the kameo
688    /// delegated-reply send error is flattened — a handler error carries the real
689    /// [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox closed) collapses
690    /// to a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control plane 501s on set-dns.
691    #[cfg(feature = "acme")]
692    pub async fn cert_pair(
693        &self,
694        name: String,
695        min_validity: Option<Duration>,
696    ) -> Result<(String, String), ts_control::CertError> {
697        // No cert cache exists in this fork (every issuance is fresh), so `min_validity` is honored
698        // trivially by always issuing a full-lifetime cert. Bound (unused beyond this contract) so
699        // the parameter is explicitly accounted for rather than silently ignored.
700        let _ = min_validity;
701        self.control
702            .ask(control_runner::GetCertPair { name })
703            .await
704            .map_err(flatten_cert_send_err)
705    }
706
707    /// Resolve which node owns a tailnet source address.
708    ///
709    /// Maps the destination IP of `addr` to its owning node. Mirrors tsnet's `LocalClient::WhoIs`.
710    /// Returns `None` if no peer holds that tailnet IP.
711    ///
712    /// The returned [`WhoIs`] additionally carries the **flow-scoped** peer-capability grants
713    /// ([`WhoIs::cap_map`], Go `apitype.WhoIsResponse.CapMap`): the caps control's packet-filter
714    /// application rules authorize for traffic from THIS node (the flow source) to `addr` (the
715    /// destination). Empty when no grant matches. (The node-level cap map rides
716    /// [`WhoIs::capabilities`].)
717    pub async fn whois(&self, addr: core::net::SocketAddr) -> Result<Option<WhoIs>, Error> {
718        let whois = self
719            .peer_tracker
720            .upgrade()
721            .ok_or(Error {
722                kind: ErrorKind::ActorGone,
723                target_actor: None,
724                message_ty: None,
725            })?
726            .ask(peer_tracker::Whois { addr })
727            .await?;
728
729        let Some(mut whois) = whois else {
730            return Ok(None);
731        };
732
733        // Fill the flow-scoped cap map: src = this node's own tailnet IP (of the dst's family),
734        // dst = the queried address. A grant applies when its source matches the flow source — `src`
735        // ∈ its src prefixes OR this node holds one of its source node-caps — AND `dst` ∈ its dst
736        // prefixes (Go `Filter.CapsWithValues`). Resolve our own IP + cap map from the self node; if
737        // it isn't known yet, leave the map empty (no grants resolvable without a source).
738        let dst = addr.ip();
739        if let Some(self_node) = self.control.ask(control_runner::SelfNode).await? {
740            let src: core::net::IpAddr = if dst.is_ipv6() {
741                self_node.tailnet_address.ipv6.addr().into()
742            } else {
743                self_node.tailnet_address.ipv4.addr().into()
744            };
745            let grants = self.cap_grants_rx.borrow();
746            whois.cap_map = ts_packetfilter_state::caps_for(&grants, src, dst, |cap| {
747                self_node.has_node_attr(cap)
748            });
749        }
750
751        Ok(Some(whois))
752    }
753
754    /// The current direct-path status to the peer holding tailnet IP `dst`: its confirmed direct UDP
755    /// endpoint and that path's last-measured RTT, or `None` when there is no direct path right now
756    /// (the peer is relayed via DERP, is unknown, or has no disco key).
757    ///
758    /// The latency is the RTT of the most recent disco ping/pong that confirmed the path — a live
759    /// snapshot up to one probe interval stale, NOT a fresh on-demand round-trip (that is a separate,
760    /// heavier capability). Mirrors the direct-path latency Go surfaces for `ipnstate.PeerStatus`.
761    pub async fn direct_path(
762        &self,
763        dst: core::net::IpAddr,
764    ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
765        let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
766            kind: ErrorKind::ActorGone,
767            target_actor: None,
768            message_ty: None,
769        })?;
770
771        // Resolve the tailnet IP to its node, then to its disco key. No node / no disco key ⇒ no
772        // direct path is possible (a peer with no disco key can only be reached via DERP).
773        let Some(node) = peer_tracker
774            .ask(peer_tracker::PeerByTailnetIp { ip: dst })
775            .await?
776        else {
777            return Ok(None);
778        };
779        let Some(disco) = node.disco_key else {
780            return Ok(None);
781        };
782
783        self.direct
784            .ask(direct::DirectPathLatency { disco })
785            .await
786            .map_err(Into::into)
787    }
788
789    /// Send a disco ping to the peer holding tailnet IP `dst` **now** and await the pong, returning
790    /// the fresh round-trip latency and the endpoint that answered, or `None` if no pong arrives
791    /// within `timeout` (or the peer is unknown / has no disco key / no candidate path). This is the
792    /// true on-demand `PingType::Disco` (Go `tailscale ping`), as opposed to
793    /// [`direct_path`](Self::direct_path) which reports the last periodic probe's RTT.
794    ///
795    /// The ping round-trip is awaited OFF the direct manager's mailbox (we take a `MagicSock` handle
796    /// and await on it directly), so a slow/timing-out ping never blocks the actor.
797    pub async fn ping_disco(
798        &self,
799        dst: core::net::IpAddr,
800        timeout: Duration,
801    ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
802        let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
803            kind: ErrorKind::ActorGone,
804            target_actor: None,
805            message_ty: None,
806        })?;
807
808        let Some(node) = peer_tracker
809            .ask(peer_tracker::PeerByTailnetIp { ip: dst })
810            .await?
811        else {
812            return Ok(None);
813        };
814        let Some(disco) = node.disco_key else {
815            return Ok(None);
816        };
817
818        // Cheap synchronous handle fetch, then await the ping OFF the actor mailbox.
819        let Some(sock) = self.direct.ask(direct::SockHandle).await? else {
820            return Ok(None);
821        };
822        // A `ping_now` error is an underlay UDP send failure (not an actor problem); surface it as a
823        // reply-level error. A timed-out / unanswered ping is `Ok(None)`, not an error.
824        sock.ping_now(&disco, timeout).await.map_err(|_| Error {
825            kind: ErrorKind::ReplyErr,
826            target_actor: None,
827            message_ty: None,
828        })
829    }
830
831    /// Change the selected exit node at runtime (the equivalent of Go `tsnet`'s
832    /// `LocalClient.EditPrefs(ExitNodeID/ExitNodeIP)`), without recreating the device.
833    ///
834    /// Updates the live exit-node selector, then asks the peer tracker to re-broadcast the current
835    /// peer set so the route updater and source filter re-resolve the new selector immediately.
836    /// `None` clears the exit node (internet-bound traffic is then dropped, fail-closed, unless this
837    /// node egresses directly). The selection is re-resolved against the live peer set, so passing a
838    /// selector for a peer not yet in the netmap simply takes effect once that peer appears.
839    pub async fn set_exit_node(
840        &self,
841        selector: Option<ts_control::ExitNodeSelector>,
842    ) -> Result<(), Error> {
843        // Update the live cell every reader borrows from. `send_replace` keeps the value current
844        // even with no active receivers (none can have dropped while the runtime is up, but it is
845        // the right non-failing primitive here).
846        self.exit_node_tx.send_replace(selector);
847
848        // Trigger an immediate re-resolution: the route updater (outbound routes + DoH delegation)
849        // and the source filter (inbound validation) both recompute on an `Arc<PeerState>`, so a
850        // re-broadcast applies the new exit without waiting for the next netmap update.
851        self.peer_tracker
852            .upgrade()
853            .ok_or(Error {
854                kind: ErrorKind::ActorGone,
855                target_actor: None,
856                message_ty: None,
857            })?
858            .ask(peer_tracker::RepublishState)
859            .await
860            .map_err(Into::into)
861    }
862
863    /// The currently-selected exit node, or `None` if none is selected.
864    pub fn exit_node(&self) -> Option<ts_control::ExitNodeSelector> {
865        self.env.exit_node()
866    }
867
868    /// Toggle whether this node accepts peer-advertised subnet routes at runtime (the equivalent of
869    /// Go `tsnet`'s `LocalClient.EditPrefs(RouteAll)` / `tailscale set --accept-routes`), without
870    /// recreating the device.
871    ///
872    /// `accept-routes` is a purely **local** preference — unlike advertised routes it is never
873    /// reported to control (no `Hostinfo` / MapRequest side), so this only re-runs the local
874    /// route/source-filter recompute, mirroring [`set_exit_node`](Self::set_exit_node) rather than
875    /// [`set_advertise_routes`](Self::set_advertise_routes). Updates the live cell, then asks the peer
876    /// tracker to re-broadcast the current peer set so the route updater (outbound routes) and the
877    /// source filter (inbound validation) re-filter against the new value immediately: turning it on
878    /// installs newly-accepted subnet routes (and widens the source filter to match); turning it off
879    /// removes them from BOTH in lock-step (never accepting a source for a route no longer installed).
880    /// Self routes and the exit-node default `/0` are unaffected (the latter is gated by the exit-node
881    /// selection, not this flag).
882    ///
883    /// In TUN transport mode the host routing table is also re-steered live: the `RepublishState`
884    /// kicked below re-broadcasts the peer set to the `TunActor`, whose `PeerState` handler re-reads
885    /// `accept_routes` (and the exit selection) from `Env` and re-applies the host routes — so the
886    /// toggle takes effect without rebuilding the device (the apply is an idempotent add-new/
887    /// remove-gone diff). The exit-node default `/0` is still keyed on the exit selection, not this flag.
888    pub async fn set_accept_routes(&self, accept: bool) -> Result<(), Error> {
889        // Update the live cell every reader borrows from (same primitive/rationale as set_exit_node).
890        self.accept_routes_tx.send_replace(accept);
891
892        // Trigger an immediate re-filter: the route updater and source filter both recompute on an
893        // `Arc<PeerState>`, so a re-broadcast applies the new preference without waiting for the next
894        // netmap update. Both re-read the same live cell, so the outbound route set and the inbound
895        // source filter stay coupled (the anti-leak invariant).
896        self.peer_tracker
897            .upgrade()
898            .ok_or(Error {
899                kind: ErrorKind::ActorGone,
900                target_actor: None,
901                message_ty: None,
902            })?
903            .ask(peer_tracker::RepublishState)
904            .await
905            .map_err(Into::into)
906    }
907
908    /// Whether this node currently accepts peer-advertised subnet routes (`--accept-routes`).
909    pub fn accept_routes(&self) -> bool {
910        self.env.accept_routes()
911    }
912
913    /// Toggle whether this node accepts the tailnet's DNS configuration at runtime (the equivalent of
914    /// Go `tsnet`'s `LocalClient.EditPrefs(CorpDNS)` / `tailscale set --accept-dns`), without
915    /// recreating the device.
916    ///
917    /// Like [`set_accept_routes`](Self::set_accept_routes), `accept-dns` is a purely **local**
918    /// preference — it is never reported to control (no `Hostinfo` / MapRequest side), so this only
919    /// re-runs the local MagicDNS view rebuild. Updates the live cell, then asks the peer tracker to
920    /// re-broadcast the current peer set; the resulting `PeerState` rebuild re-applies the gate on the
921    /// MagicDNS responder (and the peerAPI DoH server that shares its view). When `false`, the
922    /// responder ignores the control-pushed DNS config and answers every query `REFUSED`, mirroring Go
923    /// applying an empty `dns.Config` when `CorpDNS` is off; flipping it back to `true` restores
924    /// serving from the still-current config (the real config is never destroyed — only gated at the
925    /// read site), so the OFF→ON restore is automatic.
926    pub async fn set_accept_dns(&self, accept: bool) -> Result<(), Error> {
927        // Update the live cell every reader borrows from (same primitive/rationale as set_accept_routes).
928        self.accept_dns_tx.send_replace(accept);
929
930        // Trigger an immediate view rebuild: the MagicDNS responder re-reads `Env::accept_dns()` when
931        // it handles a `PeerState`, so a re-broadcast re-applies the gate on both the netstack
932        // responder and the peerAPI DoH server (which share the view) without waiting for the next
933        // control/peer update. Mirrors `set_accept_routes`'s republish.
934        self.peer_tracker
935            .upgrade()
936            .ok_or(Error {
937                kind: ErrorKind::ActorGone,
938                target_actor: None,
939                message_ty: None,
940            })?
941            .ask(peer_tracker::RepublishState)
942            .await
943            .map_err(Into::into)
944    }
945
946    /// Whether this node currently accepts the tailnet's DNS configuration (`--accept-dns` / `CorpDNS`).
947    pub fn accept_dns(&self) -> bool {
948        self.env.accept_dns()
949    }
950
951    /// Change the set of subnet routes this node advertises at runtime (Go `tailscale set
952    /// --advertise-routes`). Applies BOTH halves together so the wire and the data path agree:
953    ///
954    /// 1. **Wire** — re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
955    ///    (so control grants the node the subnet-router role for exactly these prefixes).
956    /// 2. **Local** — swap the forwarder's accept/dial route table (so the node actually forwards the
957    ///    prefixes it advertises). New flows see the new set; in-flight flows keep their routing.
958    ///
959    /// `routes` is filtered to the IPv4-only, deduplicated set this fork can honor (IPv6 prefixes are
960    /// dropped under the IPv6-off posture — we never advertise a route we won't forward), so the wire
961    /// and forwarder are fed the identical final set. This sets the explicit subnet prefixes only; it
962    /// does NOT touch the exit-node `0.0.0.0/0` advertisement (a separate concern).
963    pub async fn set_advertise_routes(&self, routes: Vec<ipnet::IpNet>) -> Result<(), Error> {
964        // Update the explicit-subnet part of the live preference, keep the exit-node flag, and
965        // re-send the composed set. Composes with `set_advertise_exit_node` (neither clobbers the
966        // other's contribution to `Hostinfo.RoutableIPs`).
967        let composed = {
968            let mut adv = self.advertise.lock().unwrap_or_else(|p| p.into_inner());
969            adv.routes = routes;
970            compose_advertised_routes(adv.routes.clone(), adv.exit_node)
971        };
972        self.apply_advertised_routes(composed).await
973    }
974
975    /// Advertise (or stop advertising) this node as an **exit node** — the `0.0.0.0/0` default route
976    /// (Go `tailscale set --advertise-exit-node`). Composes with
977    /// [`set_advertise_routes`](Self::set_advertise_routes): toggling the exit node re-sends the
978    /// explicit subnet routes plus (when `enable`) `0.0.0.0/0`, so the two preferences are
979    /// independent. Like `set_advertise_routes`, this both re-advertises `Hostinfo.RoutableIPs` to
980    /// control AND updates the forwarder's accept/dial set, applied together. Control still gates
981    /// whether the advertised exit node is actually *usable* by peers (this only advertises it).
982    pub async fn set_advertise_exit_node(&self, enable: bool) -> Result<(), Error> {
983        let composed = {
984            let mut adv = self.advertise.lock().unwrap_or_else(|p| p.into_inner());
985            adv.exit_node = enable;
986            compose_advertised_routes(adv.routes.clone(), adv.exit_node)
987        };
988        self.apply_advertised_routes(composed).await
989    }
990
991    /// Push a freshly-composed advertised-route set to BOTH halves: the forwarder's accept/dial
992    /// table (local) FIRST — so the node forwards a prefix before control grants it, never the
993    /// reverse — then re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
994    /// (wire). `composed` is already filtered + exit-node-folded by [`compose_advertised_routes`].
995    async fn apply_advertised_routes(&self, composed: Vec<ipnet::IpNet>) -> Result<(), Error> {
996        self.forwarder
997            .ask(forwarder_actor::UpdateRoutes {
998                routes: composed.clone(),
999            })
1000            .await?;
1001        self.control
1002            .ask(control_runner::SetAdvertiseRoutes { routes: composed })
1003            .await
1004            .map_err(Into::into)
1005    }
1006
1007    /// Change this node's hostname at runtime (Go `tailscale set --hostname`), re-reporting
1008    /// `Hostinfo.Hostname` to control on the live map-poll connection. Hostname is display-only
1009    /// (control reflects it in the netmap), so there is no dataplane half. The new value is also
1010    /// what a subsequent re-registration reports, so it persists across a reconnect.
1011    pub async fn set_hostname(&self, hostname: String) -> Result<(), Error> {
1012        self.control
1013            .ask(control_runner::SetHostname { hostname })
1014            .await
1015            .map_err(Into::into)
1016    }
1017
1018    /// Subscribe to netmap peer-change events: the **narrow** peer-set view.
1019    ///
1020    /// Returns a [`watch::Receiver`] whose value is the current set of peer [`StatusNode`]s,
1021    /// updated on every netmap state update from control. Await
1022    /// [`watch::Receiver::changed`](tokio::sync::watch::Receiver::changed) to react to peers
1023    /// joining, leaving, or changing. For the unified Go-`WatchIPNBus` feed that merges this with
1024    /// device-state and the interactive-login URL, see [`watch_ipn_bus`](Self::watch_ipn_bus); this
1025    /// method is the peer-only projection of the same underlying cell.
1026    pub async fn watch_netmap(&self) -> Result<watch::Receiver<Vec<StatusNode>>, Error> {
1027        self.peer_tracker
1028            .upgrade()
1029            .ok_or(Error {
1030                kind: ErrorKind::ActorGone,
1031                target_actor: None,
1032                message_ty: None,
1033            })?
1034            .ask(peer_tracker::WatchNetmap)
1035            .await
1036            .map_err(Into::into)
1037    }
1038
1039    /// The current device connection-[`DeviceState`].
1040    pub fn device_state(&self) -> DeviceState {
1041        self.state_rx.borrow().clone()
1042    }
1043
1044    /// Watch the device connection-[`DeviceState`] (`Connecting` → `Running` / `NeedsLogin` /
1045    /// `Expired` / `Failed`).
1046    ///
1047    /// Returns a [`watch::Receiver`]; await
1048    /// [`changed`](tokio::sync::watch::Receiver::changed) to react push-style to control connection
1049    /// transitions instead of polling [`status`](Self::status). The initial value is the current
1050    /// state. Note: a transient per-reconnect dip back to `Connecting` is **not** currently
1051    /// emitted (control transparently reconnects below this layer); the state reflects registration
1052    /// outcome and node-key expiry.
1053    pub fn watch_state(&self) -> watch::Receiver<DeviceState> {
1054        self.state_rx.clone()
1055    }
1056
1057    /// Wait until the device finishes registering, returning a typed outcome.
1058    ///
1059    /// Resolves `Ok(())` once the device reaches [`DeviceState::Running`]. Returns a typed
1060    /// [`RegistrationError`] otherwise — the actionable distinction between "retry", "re-pair", and
1061    /// "drive interactive login" that replaces polling [`ipv4_addr`](Self::ipv4_addr) in a loop:
1062    /// - `AuthRejected` — bad/expired/unknown auth key. **Permanent** (re-pair).
1063    /// - `NeedsLogin(url)` — interactive authorization required (no usable auth key). **Not
1064    ///   permanent**: the runtime keeps retrying and will reach `Running` once the user authorizes
1065    ///   the URL. An **auth-key** caller should treat this as a failure; an **interactive** caller
1066    ///   should ignore this return and instead drive the flow via [`watch_state`](Self::watch_state)
1067    ///   (this method returns the URL eagerly rather than blocking for the whole login).
1068    /// - `NetworkUnreachable` — control unreachable. **Transient** (retry).
1069    /// - `Timeout` — no settled state within `timeout`.
1070    ///
1071    /// `KeyExpired` is not produced by this initial wait (a node key expires only *after* it has
1072    /// come up); observe post-registration expiry via [`watch_state`](Self::watch_state).
1073    /// `timeout` of `None` waits indefinitely for a settled state.
1074    pub async fn wait_until_running(
1075        &self,
1076        timeout: Option<Duration>,
1077    ) -> Result<(), RegistrationError> {
1078        device_state::wait_for_running(self.state_rx.clone(), timeout).await
1079    }
1080
1081    /// Subscribe to the unified IPN notification bus (Go `ipn` `WatchIPNBus` /
1082    /// `LocalBackend.WatchNotifications`).
1083    ///
1084    /// Returns an [`IpnBusWatcher`]; await [`next`](IpnBusWatcher::next) to receive [`Notify`]
1085    /// events that coalesce device-[`DeviceState`] changes (including the interactive-login URL as
1086    /// `browse_to_url`) and netmap peer-set changes into one feed. `mask`
1087    /// ([`NotifyWatchOpt`]) selects which current-state fields are front-loaded as an initial
1088    /// snapshot on subscribe (`INITIAL_STATE` / `INITIAL_NETMAP`), exactly like Go's
1089    /// `NotifyInitialState` / `NotifyInitialNetMap`.
1090    ///
1091    /// This composes the same `watch` cells as [`watch_state`](Self::watch_state),
1092    /// [`watch_netmap`](Self::watch_netmap), and `pop_browser_url` — one source of truth, so the
1093    /// merged feed cannot diverge from those narrow views. Besides the registration-time login URL
1094    /// (carried by `NeedsLogin`), `browse_to_url` also streams the mid-session
1095    /// `MapResponse.PopBrowserURL` (re-auth / consent on an already-running node). Delivery is
1096    /// best-effort/lossy (a bounded per-watcher buffer; a notification is dropped rather than
1097    /// blocking the runtime if a slow consumer's buffer fills), matching Go's bus. The stream ends
1098    /// (`next` returns `None`) on runtime shutdown or when the watcher is dropped.
1099    pub async fn watch_ipn_bus(&self, mask: NotifyWatchOpt) -> Result<IpnBusWatcher, Error> {
1100        // The peer-set cell lives on the peer-tracker actor; obtain a receiver the same way
1101        // `watch_netmap` does. State + shutdown cells are held here.
1102        let peer_rx = self
1103            .peer_tracker
1104            .upgrade()
1105            .ok_or(Error {
1106                kind: ErrorKind::ActorGone,
1107                target_actor: None,
1108                message_ty: None,
1109            })?
1110            .ask(peer_tracker::WatchNetmap)
1111            .await?;
1112        // The running-node consent-URL cell lives on the control runner; obtain its receiver the
1113        // same way (the control actor ref is strong, so no upgrade needed).
1114        let browser_rx = self.control.ask(control_runner::WatchBrowserUrl).await?;
1115        Ok(ipn_bus::spawn_watcher(
1116            mask,
1117            self.state_rx.clone(),
1118            peer_rx,
1119            browser_rx,
1120            self.shutdown.subscribe(),
1121        ))
1122    }
1123
1124    /// Attempt to shut down the runtime gracefully.
1125    ///
1126    /// Returns false if the shutdown timed out. It is still shut down if it timed out, just
1127    /// more violently and with possible resource leaks.
1128    pub async fn graceful_shutdown(self, timeout: Option<Duration>) -> bool {
1129        self.shutdown.send_replace(true);
1130
1131        async fn _shutdown_all(runtime: Runtime) {
1132            // See the note in `Drop` for why we only need to stop these actors to bring down the
1133            // whole runtime.
1134
1135            let _ignore = runtime.control.stop_gracefully().await;
1136            let _ignore = runtime.dataplane.stop_gracefully().await;
1137            let _ignore = runtime.env.bus.stop_gracefully().await;
1138
1139            tokio::join![
1140                runtime.control.wait_for_shutdown(),
1141                runtime.dataplane.wait_for_shutdown(),
1142                runtime.env.bus.wait_for_shutdown(),
1143            ];
1144        }
1145
1146        let fut = _shutdown_all(self);
1147
1148        match timeout {
1149            Some(timeout) => tokio::time::timeout(timeout, fut).await.is_ok(),
1150            None => {
1151                fut.await;
1152                true
1153            }
1154        }
1155    }
1156}
1157
1158impl Drop for Runtime {
1159    fn drop(&mut self) {
1160        // We must have already run `graceful_shutdown`: on the happy path, this does nothing, but
1161        // if it timed out, we need to make sure the actors are dead so we don't leak them and their
1162        // dependents.
1163        if *self.shutdown.borrow() {
1164            self.control.kill();
1165            self.dataplane.kill();
1166            self.env.bus.kill();
1167            return;
1168        }
1169
1170        self.shutdown.send_replace(true);
1171
1172        // Actors shut down when the last ActorRef to them is dropped (as nothing can send them
1173        // messages anymore). If we don't hold an ActorRef in Runtime, in general the only thing
1174        // that has one is the MessageBus, which each actor subscribes to for a subset of messages.
1175        // Hence, if we shut down the bus, most actors die as well.
1176
1177        // First shut down the actors we have an ActorRef to:
1178        try_shutdown(&self.control);
1179        try_shutdown(&self.dataplane);
1180
1181        // Then shutdown the message bus, stopping the rest of the actors:
1182        try_shutdown(&self.env.bus);
1183    }
1184}
1185
1186fn try_shutdown(a: &ActorRef<impl kameo::Actor>) {
1187    if let Err(e) = a.mailbox_sender().try_send(Signal::Stop) {
1188        tracing::error!(error = %e, "graceful shutdown failed, killing actor");
1189        a.kill();
1190    }
1191}
1192
1193/// Build the netstack config shared by both userspace netstacks (application + forwarder) from the
1194/// per-deployment `tcp_buffer_size` knob.
1195///
1196/// `None` keeps the netstack default (256 KiB/direction); `Some(n)` overrides it (e.g. a smaller
1197/// window on a memory-constrained exit node forwarding many concurrent flows — see
1198/// [`netstack::netcore::Config::tcp_buffer_size`]). Factored out of [`Runtime::spawn`] so the
1199/// None-default / Some-override mapping is unit-testable without standing up the actor system.
1200fn netstack_config_from(tcp_buffer_size: Option<usize>) -> netstack::netcore::Config {
1201    let mut c = netstack::netcore::Config::default();
1202    if let Some(tcp_buffer_size) = tcp_buffer_size {
1203        c.tcp_buffer_size = tcp_buffer_size;
1204    }
1205    c
1206}
1207
1208/// Filter a requested advertise-route set to the IPv4-only, deduplicated set this fork can honor,
1209/// mirroring [`ts_control::Config::advertised_routes`] so a runtime `set_advertise_routes` feeds the
1210/// wire (control grant) and the forwarder (accept/dial table) the identical final set. IPv6 prefixes
1211/// are dropped under the IPv6-off posture — we never advertise a route we won't forward. Order is
1212/// preserved (first occurrence wins). Factored out so the filter is unit-testable without an actor.
1213fn filter_advertise_routes(routes: Vec<ipnet::IpNet>) -> Vec<ipnet::IpNet> {
1214    let mut filtered: Vec<ipnet::IpNet> = Vec::new();
1215    for net in routes {
1216        if matches!(net, ipnet::IpNet::V4(_)) {
1217            if !filtered.contains(&net) {
1218                filtered.push(net);
1219            }
1220        } else {
1221            tracing::warn!(prefix = %net, "dropping IPv6 advertise route (IPv6-off posture)");
1222        }
1223    }
1224    filtered
1225}
1226
1227/// Compose the final advertised-route set from the explicit subnet `routes` and the exit-node flag,
1228/// mirroring [`ts_control::Config::advertised_routes`]: the IPv4-only, deduplicated subnet prefixes,
1229/// plus `0.0.0.0/0` appended when `exit_node` is set. This is the single source of truth both
1230/// runtime advertise mutators (`set_advertise_routes`, `set_advertise_exit_node`) feed, so the two
1231/// compose instead of clobbering. Factored out so the composition is unit-testable without an actor.
1232fn compose_advertised_routes(routes: Vec<ipnet::IpNet>, exit_node: bool) -> Vec<ipnet::IpNet> {
1233    let mut filtered = filter_advertise_routes(routes);
1234    if exit_node {
1235        let default_v4 = ipnet::IpNet::V4(
1236            ipnet::Ipv4Net::new(core::net::Ipv4Addr::UNSPECIFIED, 0)
1237                .expect("0.0.0.0/0 is a valid prefix"),
1238        );
1239        if !filtered.contains(&default_v4) {
1240            filtered.push(default_v4);
1241        }
1242    }
1243    filtered
1244}
1245
1246/// The runtime's live advertised-route preference: the explicit subnet routes plus whether this node
1247/// advertises itself as an exit node. Held behind a `Mutex` on the [`Runtime`] so
1248/// [`Runtime::set_advertise_routes`] and [`Runtime::set_advertise_exit_node`] each mutate their own
1249/// part and re-send the composed set — they compose rather than clobber (Go `EditPrefs` keeps
1250/// `AdvertiseRoutes` and the exit-node advertisement as independent prefs that both feed
1251/// `Hostinfo.RoutableIPs`).
1252#[derive(Debug, Default, Clone)]
1253struct AdvertiseState {
1254    /// The explicit subnet prefixes (pre-filter; the last value passed to `set_advertise_routes`).
1255    routes: Vec<ipnet::IpNet>,
1256    /// Whether this node advertises the exit-node default route (`0.0.0.0/0`).
1257    exit_node: bool,
1258}
1259
1260/// Flatten a kameo delegated-reply [`SendError`] for the id-token RPC into the RPC's own
1261/// [`ts_control::IdTokenError`].
1262///
1263/// A [`SendError::HandlerError`](kameo::error::SendError::HandlerError) carries the real
1264/// `IdTokenError` produced by the handler and is surfaced verbatim. Any other send failure (actor
1265/// not running / stopped, mailbox full, send timeout) is a delivery problem rather than an RPC
1266/// result, so it collapses to a transient [`ts_control::IdTokenError::NetworkError`]. Factored out
1267/// of [`Runtime::fetch_id_token`] so this mapping is unit-testable without standing up an actor.
1268fn flatten_send_err<M>(
1269    e: kameo::error::SendError<M, ts_control::IdTokenError>,
1270) -> ts_control::IdTokenError {
1271    match e {
1272        kameo::error::SendError::HandlerError(err) => err,
1273        _ => ts_control::IdTokenError::NetworkError,
1274    }
1275}
1276
1277/// Flatten a kameo `SendError` from the `Logout` ask into a [`ts_control::LogoutError`].
1278///
1279/// A `HandlerError` carries the real `LogoutError` from the control RPC and is surfaced verbatim;
1280/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
1281/// problem, not a logout result — collapses to the transient [`ts_control::LogoutError::NetworkError`]
1282/// (logout is idempotent, so a retry after a delivery failure is safe). Factored out of
1283/// [`Runtime::logout`] so the mapping is unit-testable without standing up an actor.
1284fn flatten_logout_send_err<M>(
1285    e: kameo::error::SendError<M, ts_control::LogoutError>,
1286) -> ts_control::LogoutError {
1287    match e {
1288        kameo::error::SendError::HandlerError(err) => err,
1289        _ => ts_control::LogoutError::NetworkError,
1290    }
1291}
1292
1293/// Flatten a kameo `SendError` from the `SetDns` ask into a [`ts_control::SetDnsError`].
1294///
1295/// A `HandlerError` carries the real `SetDnsError` from the set-dns RPC and is surfaced verbatim;
1296/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
1297/// problem, not a publish result — collapses to the transient
1298/// [`ts_control::SetDnsError::NetworkError`]. Factored out of [`Runtime::set_dns`] so the mapping is
1299/// unit-testable without standing up an actor.
1300fn flatten_set_dns_send_err<M>(
1301    e: kameo::error::SendError<M, ts_control::SetDnsError>,
1302) -> ts_control::SetDnsError {
1303    match e {
1304        kameo::error::SendError::HandlerError(err) => err,
1305        _ => ts_control::SetDnsError::NetworkError,
1306    }
1307}
1308
1309/// Flatten a kameo `SendError` from the `GetCertificate` / `GetCertPair` ask into a
1310/// [`ts_control::CertError`].
1311///
1312/// A `HandlerError` carries the real `CertError` produced by the ACME issuance and is surfaced
1313/// verbatim. `CertError` has no transient-network variant, so any other send failure (actor not
1314/// running / stopped, mailbox full, send timeout) — a delivery problem rather than an issuance
1315/// result — collapses to a [`ts_control::CertError::Io`]. Generic over the message type, so it
1316/// serves both [`Runtime::get_certificate`] and [`Runtime::cert_pair`]; factored out so the mapping
1317/// is unit-testable without standing up an actor.
1318#[cfg(feature = "acme")]
1319fn flatten_cert_send_err<M>(
1320    e: kameo::error::SendError<M, ts_control::CertError>,
1321) -> ts_control::CertError {
1322    match e {
1323        kameo::error::SendError::HandlerError(err) => err,
1324        _ => ts_control::CertError::Io(std::io::Error::other(
1325            "control runner unavailable for certificate issuance",
1326        )),
1327    }
1328}
1329
1330#[cfg(test)]
1331mod tests {
1332    use super::*;
1333
1334    /// `None` must leave the netstack's own default TCP window in place (the 256 KiB throughput
1335    /// default), and must not silently coerce to some other value.
1336    #[test]
1337    fn netstack_config_none_uses_netstack_default() {
1338        let default = netstack::netcore::Config::default();
1339        let built = netstack_config_from(None);
1340        assert_eq!(
1341            built.tcp_buffer_size, default.tcp_buffer_size,
1342            "None must inherit the netstack default TCP buffer size"
1343        );
1344    }
1345
1346    /// `Some(n)` must override the TCP window (the memory-vs-throughput knob exit-node operators
1347    /// reach for), reaching the config that both netstacks are built from.
1348    #[test]
1349    fn netstack_config_some_overrides_buffer() {
1350        let built = netstack_config_from(Some(64 * 1024));
1351        assert_eq!(
1352            built.tcp_buffer_size,
1353            64 * 1024,
1354            "Some(n) must override the TCP buffer size that both netstacks use"
1355        );
1356    }
1357
1358    /// `set_advertise_routes` must feed the wire and the forwarder the IDENTICAL filtered set:
1359    /// IPv4-only (IPv6 dropped under the IPv6-off posture), deduplicated, order preserved.
1360    #[test]
1361    fn filter_advertise_routes_keeps_v4_dedups_drops_v6() {
1362        let v4a: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
1363        let v4b: ipnet::IpNet = "192.168.1.0/24".parse().unwrap();
1364        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1365
1366        // Mixed input with a duplicate v4 and a v6 prefix.
1367        let out = filter_advertise_routes(vec![v4a, v6, v4b, v4a]);
1368
1369        assert_eq!(
1370            out,
1371            vec![v4a, v4b],
1372            "v6 dropped, duplicate v4 collapsed, first-occurrence order preserved"
1373        );
1374    }
1375
1376    /// An all-IPv6 request filters to empty (we never advertise a route we won't forward) rather
1377    /// than erroring — clearing the advertised set is a legitimate outcome.
1378    #[test]
1379    fn filter_advertise_routes_all_v6_is_empty() {
1380        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1381        assert!(filter_advertise_routes(vec![v6]).is_empty());
1382    }
1383
1384    /// `compose_advertised_routes` folds the exit-node `0.0.0.0/0` onto the filtered subnet routes
1385    /// when (and only when) the exit-node flag is set — so `set_advertise_routes` and
1386    /// `set_advertise_exit_node` compose. The two preferences are independent.
1387    #[test]
1388    fn compose_advertised_routes_folds_exit_node() {
1389        let subnet: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
1390        let default_v4: ipnet::IpNet = "0.0.0.0/0".parse().unwrap();
1391
1392        // Exit node off: just the (filtered) subnet routes.
1393        assert_eq!(
1394            compose_advertised_routes(vec![subnet], false),
1395            vec![subnet],
1396            "exit-node off ⇒ no default route"
1397        );
1398        // Exit node on: subnet routes PLUS 0.0.0.0/0.
1399        assert_eq!(
1400            compose_advertised_routes(vec![subnet], true),
1401            vec![subnet, default_v4],
1402            "exit-node on ⇒ 0.0.0.0/0 appended"
1403        );
1404        // Exit node on with NO subnet routes: just the default route.
1405        assert_eq!(
1406            compose_advertised_routes(vec![], true),
1407            vec![default_v4],
1408            "exit-node alone advertises only 0.0.0.0/0"
1409        );
1410        // Idempotent: an explicit 0.0.0.0/0 already in the routes isn't duplicated by the fold.
1411        assert_eq!(
1412            compose_advertised_routes(vec![default_v4], true),
1413            vec![default_v4],
1414            "the exit-node fold dedups against an explicit default route"
1415        );
1416    }
1417
1418    /// A `HandlerError` carries the real `IdTokenError` from the RPC handler and must pass through
1419    /// verbatim, not be flattened to a generic network error. Using an `Internal(_)` payload (not
1420    /// `NetworkError`) makes the passthrough observable: a buggy flatten that always returned
1421    /// `NetworkError` would fail this assertion.
1422    #[test]
1423    fn flatten_send_err_handler_error_passes_through() {
1424        // Build an `Internal(_)` payload via the public `From<Utf8Error>` conversion (no extra
1425        // deps): it is distinct from the `_ => NetworkError` fallback, so a buggy flatten that
1426        // always returned `NetworkError` would fail this assertion.
1427        // Route the invalid bytes through a runtime Vec so the `invalid_from_utf8` lint (which only
1428        // fires on compile-time-known literals) doesn't flag this intentional bad input.
1429        let bytes = vec![0xffu8, 0xfe];
1430        let utf8_err = core::str::from_utf8(&bytes).unwrap_err();
1431        let inner = ts_control::IdTokenError::from(utf8_err);
1432        assert!(matches!(inner, ts_control::IdTokenError::Internal(_)));
1433        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1434            kameo::error::SendError::HandlerError(inner.clone());
1435        assert_eq!(flatten_send_err(e), inner);
1436    }
1437
1438    /// A non-handler send failure (actor stopped) is a delivery problem, not an RPC result, so it
1439    /// must collapse to a transient `NetworkError`.
1440    #[test]
1441    fn flatten_send_err_actor_stopped_is_network_error() {
1442        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1443            kameo::error::SendError::ActorStopped;
1444        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1445    }
1446
1447    /// `ActorNotRunning` (the message bounces back undelivered) is likewise a delivery failure and
1448    /// must map to a transient `NetworkError`.
1449    #[test]
1450    fn flatten_send_err_actor_not_running_is_network_error() {
1451        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1452            kameo::error::SendError::ActorNotRunning(control_runner::FetchIdToken {
1453                audience: "sts.amazonaws.com".to_string(),
1454            });
1455        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1456    }
1457
1458    /// A `HandlerError` from the logout RPC carries the real `LogoutError` and must pass through
1459    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1460    /// passthrough observable.
1461    #[test]
1462    fn flatten_logout_send_err_handler_error_passes_through() {
1463        let inner = ts_control::LogoutError::Internal(ts_control::LogoutInternalErrorKind::Http);
1464        assert!(matches!(inner, ts_control::LogoutError::Internal(_)));
1465        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1466            kameo::error::SendError::HandlerError(inner.clone());
1467        assert_eq!(flatten_logout_send_err(e), inner);
1468    }
1469
1470    /// A non-handler send failure (actor stopped) is a delivery problem, not a logout result, and
1471    /// collapses to a transient `NetworkError` (logout is idempotent, so a retry is safe).
1472    #[test]
1473    fn flatten_logout_send_err_actor_stopped_is_network_error() {
1474        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1475            kameo::error::SendError::ActorStopped;
1476        assert_eq!(
1477            flatten_logout_send_err(e),
1478            ts_control::LogoutError::NetworkError
1479        );
1480    }
1481
1482    /// A `HandlerError` from the set-dns RPC carries the real `SetDnsError` and must pass through
1483    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1484    /// passthrough observable.
1485    #[test]
1486    fn flatten_set_dns_send_err_handler_error_passes_through() {
1487        let inner = ts_control::SetDnsError::Internal(ts_control::SetDnsInternalErrorKind::Http);
1488        assert!(matches!(inner, ts_control::SetDnsError::Internal(_)));
1489        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
1490            kameo::error::SendError::HandlerError(inner.clone());
1491        assert_eq!(flatten_set_dns_send_err(e), inner);
1492    }
1493
1494    /// A non-handler send failure (actor stopped) is a delivery problem, not a publish result, and
1495    /// collapses to a transient `NetworkError`.
1496    #[test]
1497    fn flatten_set_dns_send_err_actor_stopped_is_network_error() {
1498        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
1499            kameo::error::SendError::ActorStopped;
1500        assert_eq!(
1501            flatten_set_dns_send_err(e),
1502            ts_control::SetDnsError::NetworkError
1503        );
1504    }
1505}