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;
30/// DNS over TCP for the MagicDNS service IP: the transport a stub resolver retries on when a UDP
31/// answer comes back truncated. Only the TUN application data path serves it today, so it is
32/// compiled with `tun`.
33#[cfg(feature = "tun")]
34mod dns_over_tcp;
35mod env;
36mod error;
37/// Exit-node suggestion algorithm (the classic DERP-region-latency path, Go
38/// `suggestExitNodeUsingDERP`) and its result/error types.
39pub mod exit_node_suggest;
40/// Fallback TCP handler registry (`tsnet.Server.RegisterFallbackTCPHandler` parity).
41pub mod fallback_tcp;
42mod forwarder_actor;
43/// Client-side Funnel ingress termination (`tsnet`'s `ListenFunnel` data path).
44pub mod funnel;
45/// Unified IPN notification bus ([`Notify`] / [`watch_ipn_bus`](Runtime::watch_ipn_bus)), mirroring
46/// Go `ipn` `LocalBackend.WatchNotifications` / the `WatchIPNBus` LocalAPI.
47pub mod ipn_bus;
48mod magic_dns;
49pub use magic_dns::DnsQueryResult;
50mod multiderp;
51/// OS network-link-change supervisor (opt-in `network-monitor` feature): re-binds + re-probes
52/// connectivity on a link change. Compiled out entirely when the feature is off.
53#[cfg(feature = "network-monitor")]
54mod netmon;
55mod netstack_actor;
56mod packetfilter;
57pub mod peer_tracker;
58mod peerapi;
59mod peerapi_doh;
60#[cfg(feature = "portmapper")]
61mod portmap;
62mod route_updater;
63mod security;
64/// Stored Serve config + accept-loop runtime (`tsnet`'s `Get/SetServeConfig` + serving runtime).
65pub mod serve;
66mod src_filter;
67/// Netmap status snapshot, WhoIs, and watcher types.
68pub mod status;
69/// Taildrop peer-to-peer file transfer store.
70pub mod taildrop;
71pub mod taildrop_send;
72/// Tailnet-Lock (TKA) chain-sync orchestration: bootstrap + offer/send driver (the runtime layer
73/// that bridges the `ts_control` sync RPCs and the `ts_tka` chain logic).
74mod tka_sync;
75#[cfg(feature = "tun")]
76mod tun_actor;
77
78pub use device_state::{DeviceState, RegistrationError};
79pub(crate) use env::Env;
80pub use error::{Error, ErrorKind};
81pub use exit_node_suggest::{ExitNodeSuggestion, SuggestExitNodeError};
82pub use ipn_bus::{IpnBusWatcher, Notify, NotifyWatchOpt};
83pub use status::{FileTarget, NetcheckReport, RegionLatency, Status, StatusNode, WhoIs};
84pub use tka_sync::TkaLogEntry;
85pub use ts_control::{PortMapFacets, StunFacts};
86pub use ts_dataplane::{CaptureHook, CapturePath};
87
88use crate::peer_tracker::PeerTracker;
89
90/// The runtime for a tailscale device.
91pub struct Runtime {
92    /// Reference to the control actor.
93    pub control: ActorRef<ControlRunner>,
94    dataplane: ActorRef<DataplaneActor>,
95    /// Reference to the direct (disco/UDP underlay) manager, retained so [`Runtime::rebind`] can
96    /// ask it to re-bind the underlay socket on a network/link change.
97    direct: ActorRef<DirectManager>,
98    /// Reference to the application netstack actor. `None` in TUN transport mode, where there is
99    /// no userspace application netstack (the application data path is a real kernel TUN device).
100    netstack: Option<WeakActorRef<NetstackActor>>,
101    /// Reference to the peer tracker for peer lookups.
102    pub peer_tracker: WeakActorRef<PeerTracker>,
103    /// Fallback TCP handler registry, bound to the application netstack. `None` in TUN transport
104    /// mode (no application netstack exists to attach it to).
105    fallback_tcp: Option<fallback_tcp::FallbackTcpManager>,
106    /// Reference to the MagicDNS responder, retained so [`Runtime::query_dns`] can run a query
107    /// through the live `100.100.100.100` forward path. `None` in TUN transport mode (no
108    /// `MagicDnsActor` is spawned there — TUN-mode MagicDNS is an in-packet intercept, not an actor).
109    magic_dns: Option<ActorRef<magic_dns::MagicDnsActor>>,
110    /// Reference to the forwarder actor, retained so [`Runtime::set_advertise_routes`] can push a
111    /// new accept/dial route table onto the running forwarder (the local half of advertising
112    /// routes). Without this the strong ref would drop after the startup `GetChannel` and the
113    /// forwarder would be reachable only via the message bus.
114    forwarder: ActorRef<ForwarderActor>,
115    /// Reference to the multiderp manager, retained so [`Runtime::status`] can resolve each
116    /// relayed peer's DERP region id to its region **code** (`ipnstate.PeerStatus.Relay`). Without
117    /// this the strong ref would drop after startup (it is cloned into the direct manager + route
118    /// updater) and the region-code map would be unreachable.
119    multiderp: ActorRef<Multiderp>,
120    env: Env,
121    shutdown: watch::Sender<bool>,
122    _security: security::SecurityGuard,
123    /// Sender side of the exit-node selector `watch` cell. Held privately here (not on the cloned
124    /// `Env`, which keeps only the read side) so that only `Runtime::set_exit_node` can mutate the
125    /// selection; the route updater and source filter re-read it via [`Env::exit_node`].
126    exit_node_tx: watch::Sender<Option<ts_control::ExitNodeSelector>>,
127    /// Sender side of the accept-routes preference `watch` cell. Held privately here (same rationale
128    /// as [`exit_node_tx`](Self::exit_node_tx)) so that only [`Runtime::set_accept_routes`] can
129    /// toggle it; the route updater and source filter re-read it via [`Env::accept_routes`].
130    accept_routes_tx: watch::Sender<bool>,
131    /// Sender side of the accept-dns preference `watch` cell. Held privately here (same rationale as
132    /// [`accept_routes_tx`](Self::accept_routes_tx)) so that only [`Runtime::set_accept_dns`] can
133    /// toggle it; the MagicDNS responder re-reads it via [`Env::accept_dns`] when it rebuilds its
134    /// view (the republish that `set_accept_dns` triggers).
135    accept_dns_tx: watch::Sender<bool>,
136    /// Receiver mirroring the *active* (resolved + fail-closed) exit node's stable id, fed by the
137    /// route updater. Read by [`Runtime::status`] / [`Runtime::active_exit_node`] to report which
138    /// exit node traffic is actually egressing through (vs. the merely-configured selector).
139    active_exit_rx: watch::Receiver<Option<ts_control::StableNodeId>>,
140    /// Receiver for the device connection-state cell, fed by the control runner. Read by
141    /// [`Runtime::watch_state`] and [`Runtime::wait_until_running`].
142    state_rx: watch::Receiver<DeviceState>,
143    /// Receiver for the retained peer-capability grants, fed by the packet-filter updater. Read by
144    /// [`Runtime::whois`] to resolve the flow-scoped cap map (Go `apitype.WhoIsResponse.CapMap`).
145    cap_grants_rx: watch::Receiver<packetfilter::CapGrants>,
146    /// Receiver for the invalid-packet-filter health flag, fed by the packet-filter updater. Read by
147    /// [`Runtime::status`] to fill [`Status::health`].
148    invalid_filter_rx: packetfilter::InvalidPacketFilterRx,
149    /// Live advertised-route preference (explicit subnet routes + the exit-node flag), seeded from
150    /// the startup config. [`Runtime::set_advertise_routes`] and [`set_advertise_exit_node`] each
151    /// mutate their part under this lock then re-send the composed set, so the two compose.
152    advertise: std::sync::Mutex<AdvertiseState>,
153    /// The most recent exit-node suggestion's stable id (Go `LocalBackend.lastSuggestedExitNode`),
154    /// remembered across calls so [`Runtime::suggest_exit_node`] can apply *stickiness* — if the
155    /// previously-suggested node is still an eligible candidate in the winning region it is kept, to
156    /// avoid the suggestion flapping between equally-good ties on each call. `None` until the first
157    /// suggestion. Held behind a `Mutex` (same rationale as [`advertise`](Self::advertise): a
158    /// cheap, infrequently-touched bit of mutable runtime state, not worth an actor round-trip).
159    prev_suggestion: std::sync::Mutex<Option<ts_control::StableNodeId>>,
160    /// Background task that periodically reaps abandoned taildrop `.partial` files (Go
161    /// `feature/taildrop/delete.go` `fileDeleter`). `None` when no taildrop store is configured.
162    /// Aborted on [`Drop`] so it cannot outlive the runtime (the `reauth_bridge` pattern).
163    taildrop_reaper: Option<tokio::task::JoinHandle<()>>,
164    /// The opt-in OS network-link-change supervisor (`network-monitor` feature + the
165    /// `Config::network_monitor` flag). Retained so the actor — and thus the
166    /// `LinkMonitorHandle` it holds, which aborts the monitor's watcher task on drop — lives for the
167    /// device's life and is torn down when the runtime drops. `None` when the flag is off. Only
168    /// present when built with the `network-monitor` feature.
169    #[cfg(feature = "network-monitor")]
170    #[allow(dead_code)]
171    netmon_supervisor: Option<ActorRef<netmon::NetmonSupervisor>>,
172    /// The NAT port mapper's client, when it runs, behind its release guard:
173    /// [`graceful_shutdown`](Self::graceful_shutdown) closes it (bounded, deletes acknowledged),
174    /// and dropping the guard, which every drop of the runtime does, sends one unacknowledged
175    /// delete per rule with no runtime needed (a no-op after the close).
176    #[cfg(feature = "portmapper")]
177    portmap: portmap::PortmapRelease,
178}
179
180/// The port mapper's state, for status lines (Go's netcheck `portmap=` plus the mapping).
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct PortMapStatus {
183    /// The NetInfo facets as sent to control.
184    pub facets: ts_control::PortMapFacets,
185    /// The current mapping's external address, if one is held (advertised or not).
186    pub external: Option<core::net::SocketAddrV4>,
187    /// The protocol holding it (`"pmp"` or `"pcp"`).
188    pub proto: Option<&'static str>,
189    /// Whether the mapping is offered to peers.
190    pub advertised: bool,
191}
192
193impl PortMapStatus {
194    /// Go's `portmap=` summary, e.g. `active-_MC`.
195    pub fn summary(&self) -> String {
196        self.facets.summary()
197    }
198}
199
200/// How long [`Runtime::graceful_shutdown`] gives the port mapper to release its router rules, at
201/// most (always within the caller's timeout).
202#[cfg(feature = "portmapper")]
203const PORTMAP_RELEASE_BUDGET: Duration = Duration::from_secs(1);
204
205/// The port mapper's share of a shutdown with `timeout`: at most [`PORTMAP_RELEASE_BUDGET`], never
206/// more than `timeout`.
207#[cfg(feature = "portmapper")]
208fn portmap_budget(timeout: Option<Duration>) -> Duration {
209    timeout.map_or(PORTMAP_RELEASE_BUDGET, |t| t.min(PORTMAP_RELEASE_BUDGET))
210}
211
212/// The first step of [`Runtime::graceful_shutdown`]: close the port mapper within its budget.
213#[cfg(feature = "portmapper")]
214async fn close_portmap(pm: Option<&Arc<dyn ts_portmapper::PortMapper>>, timeout: Option<Duration>) {
215    if let Some(pm) = pm {
216        pm.close(portmap_budget(timeout)).await;
217    }
218}
219
220impl Runtime {
221    /// Spawn a new runtime with the given parameters for connecting to a tailnet.
222    pub async fn spawn(
223        config: ts_control::Config,
224        auth_key: Option<String>,
225        keys: ts_keys::NodeState,
226    ) -> Result<Self, Error> {
227        let (shutdown_tx, shutdown_rx) = watch::channel(false);
228
229        // The exit-node selector, accept-routes, and accept-dns preferences are live `watch` cells so
230        // `Device::set_exit_node` / `set_accept_routes` / `set_accept_dns` can change them at runtime.
231        // `new_with_runtime_txs` returns each `Sender` (mutation capability) grouped in `pref_cells`
232        // so they are retained privately on the `Runtime`, while only the `Receiver`s (the readers'
233        // contract) live on the cloned `Env`. Initial values come from `ForwarderConfig`.
234        // Environment knobs are read once, here (Go caches its `envknob`s too).
235        let mut forwarding = env::ForwarderConfig::from_control_config(&config);
236        forwarding.apply_env_knobs(|k| std::env::var(k).ok());
237        let (env, pref_cells) = Env::new_with_runtime_txs(keys, shutdown_rx, forwarding);
238
239        let mut security = security::SecurityGuard::new(shutdown_tx.clone());
240        security.watch(&env.bus);
241        security.ready(&env.bus).await?;
242
243        // Both userspace netstacks (application + forwarder) share one netstack config. Honor the
244        // per-deployment TCP buffer knob, and set the netstack MTU to the overlay/tunnel MTU so the
245        // advertised MSS fits the tunnel — leaving it at the netstack's generic 1500 default would
246        // emit over-1280 segments into the WireGuard path. The MTU comes from a `Tun` transport's
247        // `TunConfig` when one is configured (so the netstack and the TUN agree), else the 1280
248        // overlay default (the `Netstack` userspace mode — the common case — has no per-OS MTU knob,
249        // but the tailnet overlay MTU is still 1280).
250        let configured_mtu = match &config.transport_mode {
251            ts_control::TransportMode::Tun(tun_cfg) => tun_cfg.mtu,
252            ts_control::TransportMode::Netstack => None,
253        };
254        let netstack_config = netstack_config_from(config.tcp_buffer_size, configured_mtu);
255
256        let dataplane = DataplaneActor::spawn(env.clone());
257        security.watch(&dataplane);
258        security.ready(&dataplane).await?;
259        security.packet_pump(dataplane.ask(dataplane::PacketPumpAbortHandle).await?);
260
261        let (netstack_id, netstack_up, netstack_down) =
262            dataplane.ask(dataplane::NewOverlayTransport).await?;
263
264        // A second overlay transport feeds the dedicated any-IP forwarder netstack. Inbound packets
265        // for advertised subnet routes / the exit-node default route are routed here (see
266        // `route_updater`), keeping forwarded flows off the application netstack.
267        let (forwarder_id, forwarder_up, forwarder_down) =
268            dataplane.ask(dataplane::NewOverlayTransport).await?;
269
270        // The selected DERP home region (Go `report.PreferredDERP`): the control runner is the sole
271        // writer (it applies the netcheck `bestRecent` + hysteresis smoothing), and `Multiderp`
272        // reads it to drive the local home relay — so the relay follows the SAME smoothed home the
273        // runner advertises to control, instead of picking it from the raw per-cycle latency minimum
274        // (which flapped on jitter and could disagree with the advertised home). Created here so it
275        // outlives both actors; `None` until the first home is chosen.
276        let (home_region_tx, home_region_rx) = watch::channel::<Option<ts_derp::RegionId>>(None);
277
278        let multiderp = Multiderp::spawn((env.clone(), dataplane.clone(), home_region_rx));
279        security.watch(&multiderp);
280        security.ready(&multiderp).await?;
281
282        // Spawn the direct (disco) underlay manager before the route updater. Its `on_start`
283        // binds the UDP socket and registers its transport synchronously, so by the time the
284        // route updater asks it for the direct transport id it is guaranteed to be available.
285        let direct = DirectManager::spawn((env.clone(), dataplane.clone(), multiderp.clone()));
286        security.watch(&direct);
287        security.ready(&direct).await?;
288        #[cfg(feature = "portmapper")]
289        let portmap = portmap::PortmapRelease::new(direct.ask(direct::PortmapClient).await?);
290
291        // Spawn the forwarder before the route updater. Its `on_start` builds the forwarder
292        // netstack, enables any-IP acceptance, and starts the per-port accept loops synchronously,
293        // so by the time the route updater begins delivering advertised prefixes to
294        // `forwarder_id` the netstack is already draining its transport.
295        let forwarder = ForwarderActor::spawn((
296            env.clone(),
297            netstack_config.clone(),
298            forwarder_up,
299            forwarder_down,
300        ));
301        security.watch(&forwarder);
302        security.ready(&forwarder).await?;
303        // Force `on_start` to finish (any-IP enabled, accept loops live) before the route updater
304        // can route the first inbound flow to `forwarder_id`: an `ask` blocks until the actor has
305        // started.
306        //
307        // The forwarder netstack's overlay `Channel` is reused by the TUN application path for
308        // recursive / exit-node-DoH MagicDNS forwarding (TUN mode has no application netstack of its
309        // own, but the forwarder netstack runs in both modes and egresses over the overlay — the
310        // anti-leak property `forward_query`/`forward_doh` require). Only the `tun` Tun arm consumes
311        // it, so it is unused when the `tun` feature is off — allow that without warn-as-error.
312        #[cfg_attr(not(feature = "tun"), allow(unused_variables))]
313        let (forwarder_channel,) = forwarder.ask(forwarder_actor::GetChannel).await?;
314
315        // The route updater is the single authoritative resolver of the active (resolved,
316        // fail-closed) exit node; it publishes the resolved stable id into this watch cell so
317        // `Runtime::status` can report which exit is actually engaged (not just configured).
318        let (active_exit_tx, active_exit_rx) = watch::channel(None);
319        let route_updater = route_updater::RouteUpdater::spawn((
320            multiderp.clone(),
321            direct.clone(),
322            env.clone(),
323            netstack_id,
324            forwarder_id,
325            active_exit_tx,
326        ));
327        security.watch(&route_updater);
328        security.ready(&route_updater).await?;
329        // The packet-filter updater also surfaces the retained cap-grants (for flow-scoped WhoIs)
330        // through a `watch` cell whose receiver the `Runtime` holds — the bus has no replay, so a
331        // `watch` is how `Runtime::whois` reads the current grants on demand.
332        let (cap_grants_tx, cap_grants_rx) = watch::channel(Default::default());
333        // The live compiled filter for the peerAPI DoH source gate. Created here — before either
334        // actor spawns — so the updater (sole writer) and the MagicDNS responder (reader, which
335        // hands the receiver to its peerAPI server task) share one cell no matter which `on_start`
336        // runs first. The gate is fail-closed, so a filter that never reaches it means refusing
337        // peers control's ACL admits. The bus has no replay for late readers (see
338        // `packetfilter::LiveFilterRx`).
339        let (live_filter_tx, live_filter_rx) = watch::channel(None);
340        let (invalid_filter_tx, invalid_filter_rx) = watch::channel(false);
341        let packetfilter = packetfilter::PacketfilterUpdater::spawn((
342            env.clone(),
343            cap_grants_tx,
344            live_filter_tx,
345            invalid_filter_tx,
346        ));
347        security.watch(&packetfilter);
348        security.ready(&packetfilter).await?;
349        let source_filter = src_filter::SourceFilterUpdater::spawn(env.clone());
350        security.watch(&source_filter);
351        security.ready(&source_filter).await?;
352        // TKA enforcement-authority cell (Go `tkaFilterNetmapLocked`). Created here — before both
353        // actors spawn — so the control runner (sole writer, `Sender`) and the peer tracker (reader,
354        // `Receiver`) share one `watch` cell. A `watch` (not a bus message) is the transport for this
355        // security-critical state: last-write-wins, never dropped under load, ordered by the control
356        // runner's writes, so a disable (`None`) can never be reordered behind or dropped before a
357        // stale `Some`. `None` = no lock synced / disabled (admit all).
358        let (tka_authority_tx, tka_authority_rx) =
359            watch::channel::<Option<std::sync::Arc<ts_tka::Authority>>>(None);
360        let peer_tracker = PeerTracker::spawn((env.clone(), tka_authority_rx));
361        security.watch(&peer_tracker);
362        security.ready(&peer_tracker).await?;
363
364        // Select the application data path from the transport mode. The forwarder/egress path
365        // above is UNCHANGED in both modes — TUN mode only swaps the application data path, never
366        // the forwarder. `config` is moved into `ControlRunner::spawn` below, so branch on a
367        // borrow and clone the small `TunConfig` where needed before the move.
368        //
369        // - Netstack (the default, and the only reachable arm when the `tun` feature is off):
370        //   spawn the application netstack + MagicDNS responder + fallback-TCP registry, all on
371        //   the `netstack_up`/`netstack_down` overlay seam.
372        // - Tun: spawn `TunActor` on that same overlay seam instead; no application netstack and
373        //   no MagicDNS responder exist, and `netstack`/`fallback_tcp` are `None`.
374        // - Tun requested but built without the `tun` feature: hard-error (a config/build
375        //   mismatch knowable at spawn time). NEVER silently fall back to netstack.
376        let (netstack, fallback_tcp, magic_dns) = match &config.transport_mode {
377            ts_control::TransportMode::Netstack => {
378                let netstack = NetstackActor::spawn((
379                    env.clone(),
380                    netstack_config,
381                    netstack_up,
382                    netstack_down,
383                ));
384
385                security.watch(&netstack);
386                security.ready(&netstack).await?;
387                // Fetch the netstack channel while we still hold the strong ActorRef, then spawn
388                // the MagicDNS responder on it. Its ActorRef is retained on `Runtime` so
389                // `query_dns` can drive the live forward path; the serve loop itself is owned by the
390                // actor's internal JoinSet.
391                let (channel,) = netstack.ask(netstack_actor::GetChannel).await?;
392                // The fallback-TCP registry attaches to the application netstack — the same one
393                // that carries the embedder's explicit `Device::tcp_listen` sockets — so a
394                // fallback handler sees exactly the inbound flows no explicit listener matched.
395                let fallback_tcp = fallback_tcp::FallbackTcpManager::new(channel.clone());
396                let magic_dns =
397                    magic_dns::MagicDnsActor::spawn((env.clone(), channel, live_filter_rx));
398                security.watch(&magic_dns);
399                security.ready(&magic_dns).await?;
400
401                (
402                    Some(netstack.downgrade()),
403                    Some(fallback_tcp),
404                    Some(magic_dns),
405                )
406            }
407
408            #[cfg(feature = "tun")]
409            ts_control::TransportMode::Tun(tun_cfg) => {
410                // Reuse the same `netstack_up`/`netstack_down` overlay-transport pair that would
411                // have fed the netstack — it is just the application-side overlay seam (the name
412                // is historical). No NetstackActor / MagicDnsActor is spawned.
413                let tun = tun_actor::TunActor::spawn((
414                    env.clone(),
415                    tun_cfg.clone(),
416                    netstack_up,
417                    netstack_down,
418                    // Reuse the forwarder netstack's overlay `Channel` for recursive / exit-node-DoH
419                    // MagicDNS forwarding in the TUN datapath (TUN mode has no application netstack
420                    // Channel of its own). Egresses over the overlay — anti-leak preserved.
421                    //
422                    // Host-route gating (subnet routes gated on `--accept-routes`, the host `/0` from
423                    // the selected exit peer) is no longer snapshotted here: `TunActor` reads the live
424                    // `Env` cells (`accept_routes`/`exit_node`) on every host-FIB apply — both the
425                    // device-build path and the `PeerState` re-apply path — and folds the union of
426                    // peers' AllowedIPs (see `tun_actor::host_routes_from_node`). A runtime
427                    // `set_accept_routes` / `set_exit_node` toggle re-broadcasts the peer state, so the
428                    // host routing table is re-steered live (no device rebuild needed).
429                    forwarder_channel.clone(),
430                ));
431                security.watch(&tun);
432                security.ready(&tun).await?;
433
434                (None, None, None)
435            }
436
437            #[cfg(not(feature = "tun"))]
438            ts_control::TransportMode::Tun(_) => {
439                return Err(Error {
440                    kind: ErrorKind::TunUnavailable,
441                    target_actor: None,
442                    message_ty: None,
443                });
444            }
445        };
446
447        // Device connection-state cell. Created here (not inside the actor) so the control runner's
448        // `on_start` can publish `Failed`/`NeedsLogin` and still return `Err` without the sender
449        // being tied to a `Self` that never gets constructed on a hard registration failure.
450        let (state_tx, state_rx) = watch::channel(DeviceState::Connecting);
451
452        // Seed the live advertised-route preference from the startup config before `config` moves
453        // into the control runner, so the runtime setters compose against the configured baseline.
454        let advertise = std::sync::Mutex::new(AdvertiseState {
455            routes: config.advertise_routes.clone(),
456            exit_node: config.advertise_exit_node,
457        });
458
459        // This telemetry subscriber also has a bounded mailbox and multiple subscriptions.
460        // Starting it after control publishes could deadlock its second Register behind
461        // delivery to its first subscription while on_start cannot drain its mailbox.
462        let latency = derp_latency::DerpLatencyMeasurer::spawn(env.clone());
463        security.watch(&latency);
464        security.ready(&latency).await?;
465
466        // Every security subscriber is now registered. Control on_start may replay a cached
467        // map immediately; spawning it earlier would lose state even with guaranteed delivery.
468        // Control self-messages (stream pump and TKA sync results), so keep its mailbox
469        // unbounded too. Publishers never wait for broker handling or subscriber capacity.
470        // A stalled handler can accumulate inputs; supervision covers death, not stalls.
471        let control = ControlRunner::spawn_with_mailbox(
472            control_runner::Params {
473                config,
474                auth_key,
475                env: env.clone(),
476                state_tx,
477                tka_authority: tka_authority_tx,
478                home_region: home_region_tx,
479            },
480            kameo::mailbox::unbounded(),
481        );
482
483        security.watch(&control);
484
485        // Spawn the taildrop partial-reaper if a store is configured; it sweeps abandoned `.partial`
486        // files every `DELETE_DELAY` and exits on shutdown (the handle is aborted in `Drop`).
487        let taildrop_reaper = env.taildrop_store.as_ref().map(|store| {
488            crate::taildrop::spawn_partial_reaper(store.clone(), shutdown_tx.subscribe())
489        });
490
491        // Opt-in OS network-link monitor (`Config::network_monitor`, default off). When enabled it
492        // spawns a `NetmonSupervisor` that, on a coalesced link change, asks the direct manager to
493        // rebind + re-probe and republishes `MeasureNow` for a re-netcheck — the auto-recovery a
494        // real `tailscaled` performs and the engine otherwise leaves to the embedder. When the flag
495        // is off this is a complete no-op: zero extra threads/sockets, byte-for-byte today's
496        // behavior. The manual `Device::rebind` path is unchanged either way.
497        //
498        // Feature gating is strict and never silent: with the `network-monitor` feature ON the
499        // supervisor (and its `ts_netmon` dep) compile in and spawn when the flag is set; with the
500        // feature OFF, setting the flag is a HARD error at spawn (mirrors the `TransportMode::Tun`
501        // without-`tun`-feature error above), so a build that cannot honor the request fails loudly
502        // rather than booting a node that silently won't auto-recover.
503        #[cfg(feature = "network-monitor")]
504        let netmon_supervisor = if env.network_monitor {
505            // Slice (a): no OS event-source backend is wired yet (the Linux netlink / macOS
506            // PF_ROUTE backends are later slices), so the supervisor runs against a `NoopLinkMonitor`
507            // — it is live and correctly shaped (it will react the moment a real backend feeds it),
508            // it just never sees a synthetic/OS event in this build. Production end-to-end reaction
509            // is proven in the integration test via a `ManualLinkMonitor`.
510            let monitor: std::sync::Arc<dyn ts_netmon::LinkMonitor> =
511                std::sync::Arc::new(ts_netmon::NoopLinkMonitor);
512            Some(netmon::NetmonSupervisor::spawn(
513                netmon::NetmonSupervisorArgs {
514                    monitor,
515                    direct: direct.clone(),
516                    env: env.clone(),
517                },
518            ))
519        } else {
520            None
521        };
522
523        #[cfg(not(feature = "network-monitor"))]
524        if env.network_monitor {
525            // The flag is set but this build cannot honor it. Fail loudly (never a silent no-op).
526            return Err(Error {
527                kind: ErrorKind::NetworkMonitorUnavailable,
528                target_actor: None,
529                message_ty: None,
530            });
531        }
532
533        Ok(Self {
534            control,
535            dataplane,
536            direct,
537            peer_tracker: peer_tracker.downgrade(),
538            fallback_tcp,
539            magic_dns,
540            forwarder,
541            multiderp,
542            netstack,
543            env,
544            shutdown: shutdown_tx,
545            _security: security,
546            exit_node_tx: pref_cells.exit_node,
547            accept_routes_tx: pref_cells.accept_routes,
548            accept_dns_tx: pref_cells.accept_dns,
549            active_exit_rx,
550            state_rx,
551            cap_grants_rx,
552            invalid_filter_rx,
553            advertise,
554            prev_suggestion: std::sync::Mutex::new(None),
555            taildrop_reaper,
556            #[cfg(feature = "network-monitor")]
557            netmon_supervisor,
558            #[cfg(feature = "portmapper")]
559            portmap,
560        })
561    }
562
563    /// The port mapper's state, or `None` when it does not run (disabled, or a build without the
564    /// `portmapper` feature).
565    pub fn port_map_status(&self) -> Option<PortMapStatus> {
566        #[cfg(feature = "portmapper")]
567        {
568            let pm = self.portmap.get()?;
569            let state = pm.subscribe().borrow().clone();
570            Some(PortMapStatus {
571                facets: portmap::facets(&state),
572                external: state.mapping.map(|m| m.external),
573                proto: state.mapping.map(|m| match m.proto {
574                    ts_portmapper::oneshot::Proto::Pmp => "pmp",
575                    ts_portmapper::oneshot::Proto::Pcp => "pcp",
576                }),
577                advertised: state.advertised().is_some(),
578            })
579        }
580        #[cfg(not(feature = "portmapper"))]
581        None
582    }
583
584    /// Register a fallback TCP handler consulted for every inbound TCP flow that matches no
585    /// explicit listener (`tsnet.Server.RegisterFallbackTCPHandler` parity).
586    ///
587    /// The returned [`fallback_tcp::FallbackTcpHandle`] deregisters the handler when dropped. See
588    /// [`fallback_tcp`] for the dispatch contract and anti-leak guarantees.
589    ///
590    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
591    /// application netstack to attach a fallback handler to.
592    pub fn register_fallback_tcp_handler(
593        &self,
594        cb: Arc<
595            dyn Fn(core::net::SocketAddr, core::net::SocketAddr) -> fallback_tcp::FallbackDecision
596                + Send
597                + Sync,
598        >,
599    ) -> Result<fallback_tcp::FallbackTcpHandle, Error> {
600        Ok(self
601            .fallback_tcp
602            .as_ref()
603            .ok_or(Error {
604                kind: ErrorKind::UnsupportedInTunMode,
605                target_actor: None,
606                message_ty: None,
607            })?
608            .register(cb))
609    }
610
611    /// Get a channel to send commands to the netstack.
612    ///
613    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
614    /// application netstack.
615    pub async fn channel(&self) -> Result<Channel, Error> {
616        let (channel,) = self
617            .netstack
618            .as_ref()
619            .ok_or(Error {
620                kind: ErrorKind::UnsupportedInTunMode,
621                target_actor: None,
622                message_ty: None,
623            })?
624            .upgrade()
625            .ok_or(Error {
626                kind: ErrorKind::ActorGone,
627                target_actor: None,
628                message_ty: None,
629            })?
630            .ask(netstack_actor::GetChannel)
631            .await?;
632
633        Ok(channel)
634    }
635
636    /// Resolve `name` for `qtype` through the live MagicDNS responder (the `100.100.100.100`
637    /// forward path), returning the raw DNS response, its RCODE, and the upstream resolver(s)
638    /// consulted (analogue of Go `LocalClient.QueryDNS`).
639    ///
640    /// This drives the *real* responder — the same `decide`/forward logic an on-the-wire query
641    /// hits — so the answer and its anti-leak posture (a tailnet-suffix name never egresses; a
642    /// recursive forward delegates to the active exit node's DoH; only IPv4 upstreams are dialed)
643    /// match exactly what a tailnet client observes. `qtype` is the raw RFC 1035 TYPE (`1`=A,
644    /// `28`=AAAA, `12`=PTR, or any other).
645    ///
646    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where MagicDNS is an
647    /// in-packet intercept on the host's own resolver rather than an actor that can be queried, and
648    /// [`ErrorKind::ActorGone`] if the responder has shut down.
649    pub async fn query_dns(
650        &self,
651        name: &str,
652        qtype: u16,
653    ) -> Result<magic_dns::DnsQueryResult, Error> {
654        let result = self
655            .magic_dns
656            .as_ref()
657            .ok_or(Error {
658                kind: ErrorKind::UnsupportedInTunMode,
659                target_actor: None,
660                message_ty: None,
661            })?
662            .ask(magic_dns::Query {
663                name: name.to_owned(),
664                qtype,
665            })
666            .await?;
667
668        Ok(result)
669    }
670
671    /// The Taildrop file store, if Taildrop is enabled (`taildrop_dir` configured and the store
672    /// initialized). `None` when disabled — fail-closed. Shared with the peerAPI Taildrop server so
673    /// the embedder's read APIs and the receive path see the same on-disk store.
674    pub fn taildrop_store(&self) -> Option<Arc<crate::taildrop::TaildropStore>> {
675        self.env.taildrop_store.clone()
676    }
677
678    /// The shared Funnel ingress slot the peerAPI `/v0/ingress` route reads per connection.
679    ///
680    /// `Device::listen_funnel` installs a [`FunnelManager`](crate::funnel::FunnelManager)'s sink here
681    /// to make the route live (the peerAPI server is already running from startup). Returns a clone of
682    /// the runtime-lifetime `Arc` so the device can write the slot without restarting the server. See
683    /// [`crate::funnel`] for the ingress data path.
684    pub fn funnel_ingress_slot(&self) -> crate::funnel::FunnelIngressSlot {
685        self.env.funnel_ingress.clone()
686    }
687
688    /// The shared "Funnel ingress listener active" flag (the same `Arc` the control session reads to
689    /// set `HostInfo.IngressEnabled`). `Device::listen_funnel` flips it `true` while a funnel listener
690    /// is up so control routes Funnel traffic to this node; clearing it advertises no live endpoint.
691    pub fn ingress_active_flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
692        self.env.ingress_active.clone()
693    }
694
695    /// Install (`Some`) or clear (`None`) the debug packet-capture hook on the running dataplane.
696    /// `Some(hook)` tees every plaintext packet crossing the datapath to `hook` until it is cleared;
697    /// `None` stops capture. Mirrors Go `tstun.Wrapper.InstallCaptureHook` / `ClearCaptureSink`.
698    pub async fn install_capture(
699        &self,
700        hook: Option<ts_dataplane::CaptureHook>,
701    ) -> Result<(), Error> {
702        self.dataplane
703            .ask(dataplane::InstallCapture { hook })
704            .await
705            .map_err(Into::into)
706    }
707
708    /// Re-bind the underlay UDP socket after a network/link change (Wi-Fi switch, sleep/wake). The
709    /// embedder's own link monitor calls this (the engine owns the socket re-bind; the embedder owns
710    /// OS netmon). Re-binds the socket (same-port-preferred, IPv4-only invariant preserved) and
711    /// resets the now-stale local NAT mapping — clearing learned reflexive addresses and every
712    /// confirmed direct path while keeping candidate endpoints, so peers re-probe over the new socket
713    /// and relay over DERP (never a direct host dial) until a path re-confirms. Peers, control, the
714    /// netmap, disco state, and DERP are untouched. A no-op when the underlay is inert (bind failed
715    /// at startup, DERP-only). Mirrors Go magicsock `Conn.Rebind` + `resetEndpointStates`.
716    pub async fn rebind(&self) -> Result<(), Error> {
717        self.direct.ask(direct::Rebind).await.map_err(Error::from)
718    }
719
720    /// Force an immediate STUN / endpoint re-probe **without** rebinding the underlay socket —
721    /// Go magicsock's `Conn.ReSTUN`. Asks the `DirectManager` to run one STUN sweep now (re-learn
722    /// our reflexive/public address) while leaving the socket, its NAT mapping, learned paths, peers,
723    /// control, and DERP untouched. Lighter than [`rebind`](Self::rebind): no socket swap, no
724    /// re-ping. A no-op when the underlay is inert (bind failed at startup, DERP-only). No control
725    /// round-trip.
726    pub async fn re_stun(&self) -> Result<(), Error> {
727        self.direct.ask(direct::ReStun).await.map_err(Error::from)
728    }
729
730    /// A snapshot of the local netmap: this node plus every known peer.
731    ///
732    /// Combines the self node held by the control runner with the peer set held by the peer
733    /// tracker. Mirrors tsnet's `LocalClient::Status`.
734    ///
735    /// `self_node` is `None` until the first netmap update has been received from control. Peer
736    /// entries carry no online/user/capability data (see the [`status`] module docs for that gap).
737    pub async fn status(&self) -> Result<Status, Error> {
738        let self_node_domain = self.control.ask(control_runner::SelfNode).await?;
739        // The MagicDNS suffix is the self node's FQDN minus its host label — already split into
740        // `Node.tailnet` at decode time (Go derives it the same way in `NetworkMap.MagicDNSSuffix`).
741        // Capture it before the domain `Node` is mapped away into a `StatusNode`.
742        let magic_dns_suffix = self_node_domain.as_ref().and_then(|n| n.tailnet.clone());
743        let self_node = self_node_domain.as_ref().map(StatusNode::from_node);
744
745        let peers_with_ids = self
746            .peer_tracker
747            .upgrade()
748            .ok_or(Error {
749                kind: ErrorKind::ActorGone,
750                target_actor: None,
751                message_ty: None,
752            })?
753            .ask(peer_tracker::GetStatus)
754            .await?;
755
756        // Join per-peer connectivity (Go `PeerStatus.CurAddr`): one batched query to the direct
757        // manager for every peer's current trusted direct endpoint, then fill `cur_addr` on each
758        // `StatusNode`. A peer absent from the map is relayed via DERP (`cur_addr = None`). This is a
759        // live snapshot — the direct path can expire/re-confirm between calls (matches Go's snapshot
760        // semantics). The `watch_netmap` stream intentionally carries no connectivity (it is a netmap
761        // watch, not a path-state watch, and does not re-fire on direct↔relay flips).
762        let ids: Vec<ts_transport::PeerId> = peers_with_ids.iter().map(|(id, _)| *id).collect();
763        let best_addrs = self
764            .direct
765            .ask(direct::BestAddrs { ids: ids.clone() })
766            .await
767            .unwrap_or_default();
768
769        // For the peers with NO direct path (relayed via DERP), resolve the region CODE they relay
770        // through (Go `PeerStatus.Relay`). One batched ask to multiderp; `cur_addr` and `relay` are
771        // mutually exclusive for a routed peer, mirroring Go's empty-vs-set strings.
772        let relay_ids: Vec<ts_transport::PeerId> = ids
773            .into_iter()
774            .filter(|id| !best_addrs.contains_key(id))
775            .collect();
776        let relay_codes = if relay_ids.is_empty() {
777            Default::default()
778        } else {
779            self.multiderp
780                .ask(multiderp::RelayCodesForPeers { ids: relay_ids })
781                .await
782                .unwrap_or_default()
783        };
784
785        let peers = peers_with_ids
786            .into_iter()
787            .map(|(id, mut node)| match best_addrs.get(&id).copied() {
788                Some(addr) => {
789                    node.cur_addr = Some(addr);
790                    node
791                }
792                None => {
793                    node.relay = relay_codes.get(&id).cloned();
794                    node
795                }
796            })
797            .collect();
798
799        let control_connected = self.control.ask(control_runner::ControlConnected).await?;
800        Ok(Status {
801            self_node,
802            peers,
803            active_exit_node: self.active_exit_node(),
804            magic_dns_suffix,
805            health: status::health_warnings(*self.invalid_filter_rx.borrow(), control_connected),
806        })
807    }
808
809    /// Suggest a reasonably good exit node to use, from the current netmap + recent DERP latency
810    /// (Go `LocalBackend.SuggestExitNode`). The Phase-1 classic DERP-region-latency path; see the
811    /// [`exit_node_suggest`] module for the algorithm, scope, and the IPv4-only parity deviation.
812    ///
813    /// Gathers the inputs the way [`status`](Self::status) and [`file_targets`](Self::file_targets)
814    /// do — from the control runner, the latest [`NetcheckReport`]'s preferred DERP region plus the
815    /// recent per-region latencies (both immediate, non-blocking borrows), and every peer
816    /// [`Node`](ts_control::Node) from the peer tracker — then runs the pure algorithm with the
817    /// production uniform-random selectors (`random_region` / `random_node`). The returned
818    /// suggestion's id is remembered in the runtime's `prev_suggestion` cell so the next call is
819    /// *sticky* (Go `lastSuggestedExitNode`).
820    ///
821    /// Returns `Ok(None)` when no peer is an eligible candidate (Go's empty response), and
822    /// `Err(`[`SuggestExitNodeError::NoPreferredDerp`]`)` when there is no netcheck report yet (Go's
823    /// `ErrNoPreferredDERP`, "try again later").
824    pub async fn suggest_exit_node(
825        &self,
826    ) -> Result<Result<Option<ExitNodeSuggestion>, SuggestExitNodeError>, Error> {
827        use ts_control::NODE_ATTR_SUGGEST_EXIT_NODE;
828
829        // The two netcheck inputs Go's `suggestExitNode` takes. First the preferred DERP region from
830        // the latest report (Go `MagicConn().GetLastNetcheckReport().PreferredDERP`): an immediate
831        // borrow of the control runner's published measurement (the value `Device::netcheck`
832        // surfaces), used only as the "have we netchecked at all yet" precondition.
833        let report = self.control.ask(control_runner::Netcheck).await?;
834
835        // Then the *ranking* input: the lowest latency seen per region over the retained measurement
836        // history (Go `netcheck.Client.RecentRegionLatency()`). Deliberately NOT the latest report's
837        // own latency list — every measurement this fork makes is partial (`complete_threshold`), so
838        // ranking on one report leaves a distant candidate's region unmeasured and collapses the
839        // suggestion to a uniform random pick. See `exit_node_suggest`'s module docs.
840        let region_latency = self
841            .control
842            .ask(control_runner::RecentRegionLatency)
843            .await?;
844
845        // Every known peer (Go reads the netmap peers via `AppendMatchingPeers`); the domain `Node`
846        // retains the cap map, home DERP region, online state, and accepted routes the predicate
847        // needs.
848        let peers = self
849            .peer_tracker
850            .upgrade()
851            .ok_or(Error {
852                kind: ErrorKind::ActorGone,
853                target_actor: None,
854                message_ty: None,
855            })?
856            .ask(peer_tracker::AllPeers)
857            .await?;
858
859        // Project each peer into the algorithm's candidate inputs. The eligibility predicate runs
860        // inside the pure function, so every peer is passed (self is naturally absent from the peer
861        // set). `derp_region`/`online`/`cap_map`/`accepted_routes` map straight off the domain node;
862        // the exit-route check is the fork's family-agnostic `prefix_len == 0` (IPv4-only parity —
863        // see `exit_node_suggest::suggest_exit_node`).
864        let candidates: Vec<exit_node_suggest::ExitNodeCandidate> = peers
865            .iter()
866            .map(|peer| exit_node_suggest::ExitNodeCandidate {
867                stable_id: peer.stable_id.clone(),
868                name: peer
869                    .fqdn_opt(false)
870                    .unwrap_or_else(|| peer.hostname.clone()),
871                derp_region: peer.derp_region,
872                online: peer.online,
873                advertises_exit_route: peer
874                    .accepted_routes
875                    .iter()
876                    .any(|route| route.prefix_len() == 0),
877                has_suggest_cap: peer.has_node_attr(NODE_ATTR_SUGGEST_EXIT_NODE),
878            })
879            .collect();
880
881        // Read the sticky previous suggestion, run the pure algorithm with the production
882        // uniform-random selectors, then update the sticky value to the new result. This mirrors Go
883        // `suggestExitNodeLocked` (`ipn/ipnlocal/local.go`), which assigns `b.lastSuggestedExitNode =
884        // res.ID` on **every** no-error return — INCLUDING the empty/no-candidate result, where it
885        // clears the sticky id to "". So a successful suggestion sets stickiness, an empty result
886        // CLEARS it (a peer that dropped out of candidacy stops being preferred), and only an `Err`
887        // (`NoPreferredDerp` — no netcheck yet) returns before the assignment and leaves it untouched.
888        let prev = self.prev_suggestion.lock().unwrap().clone();
889        let outcome = exit_node_suggest::suggest_exit_node(
890            report.preferred_derp,
891            &region_latency,
892            &candidates,
893            prev.as_ref(),
894            &exit_node_suggest::random_region,
895            &exit_node_suggest::random_node,
896        );
897        *self.prev_suggestion.lock().unwrap() = exit_node_suggest::next_sticky(prev, &outcome);
898        Ok(outcome)
899    }
900
901    /// List the tailnet peers this node can Taildrop a file *to* (Go LocalAPI `FileTargets`).
902    ///
903    /// Mirrors the upstream send-path filter (`feature/taildrop` `Extension::FileTargets`): a peer
904    /// qualifies when it advertises a reachable peerAPI **and** is either owned by the same user as
905    /// this node **or** explicitly granted the file-sharing-target capability. The whole list is
906    /// gated on this node holding the file-sharing capability (control sets it when the admin enables
907    /// Taildrop) — absent that, an empty list (fail-closed, not an error, matching how the receive
908    /// store returns empty when disabled). Results are sorted by the peer's MagicDNS name.
909    ///
910    /// Targets are listed regardless of current online state (upstream's `FileTargets` does not gate
911    /// on online either; an offline target's send will simply time out). The self node is never
912    /// included. Returns empty before the first netmap.
913    ///
914    /// Divergence from Go: the upstream filter also excludes `tvOS` peers, which this fork cannot
915    /// reproduce (the domain node carries no OS string); the impact is negligible — the actual send
916    /// fail-closes if such a peer refused the transfer.
917    pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
918        // Node-level gate: this node must hold the file-sharing capability (Taildrop enabled by the
919        // admin). Read it off the self node's cap map, like Go's `hasCapFileSharing()`.
920        let self_node = self.control.ask(control_runner::SelfNode).await?;
921        let Some(self_node) = self_node else {
922            return Ok(Vec::new()); // no netmap yet
923        };
924        if !self_node.can_share_files() {
925            return Ok(Vec::new()); // Taildrop not enabled for the tailnet — fail-closed
926        }
927        let self_user_id = self_node.user_id;
928
929        let peers = self
930            .peer_tracker
931            .upgrade()
932            .ok_or(Error {
933                kind: ErrorKind::ActorGone,
934                target_actor: None,
935                message_ty: None,
936            })?
937            .ask(peer_tracker::AllPeers)
938            .await?;
939
940        // Eligibility + ordering live in `build_file_targets` (pure, unit-tested in `status`).
941        Ok(status::build_file_targets(peers, self_user_id))
942    }
943
944    /// The stable id of the exit node traffic is currently egressing through, or `None` if none is
945    /// engaged. This is the route updater's resolved + fail-closed answer (see
946    /// [`Status::active_exit_node`](crate::status::Status::active_exit_node)): it differs from the
947    /// configured [`exit_node`](Self::exit_node) selector, which may name a peer that is absent or
948    /// no longer advertising a default route (in which case egress is dropped and this returns
949    /// `None`).
950    pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
951        self.active_exit_rx.borrow().clone()
952    }
953
954    /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
955    ///
956    /// Returns the signed JWT, or the token RPC's own [`ts_control::IdTokenError`]. The kameo
957    /// delegated-reply send error is flattened: a handler error carries the real `IdTokenError`,
958    /// any other send failure (actor shutdown / mailbox closed) is surfaced as
959    /// [`ts_control::IdTokenError::NetworkError`].
960    pub async fn fetch_id_token(
961        &self,
962        audience: String,
963    ) -> Result<String, ts_control::IdTokenError> {
964        self.control
965            .ask(control_runner::FetchIdToken { audience })
966            .await
967            .map_err(flatten_send_err)
968    }
969
970    /// Log this node out of the tailnet: deregister it by expiring its current node key.
971    ///
972    /// Forwards to the control runner, which re-POSTs `/machine/register` with a past expiry over a
973    /// fresh Noise channel. This is a control-plane state change only — it does NOT shut the runtime
974    /// down (the caller follows with [`graceful_shutdown`](Self::graceful_shutdown)) and does not
975    /// touch the on-disk node key. The kameo delegated-reply send error is flattened the same way as
976    /// `fetch_id_token`: a handler error carries the real
977    /// [`ts_control::LogoutError`]; any other send failure (actor shutdown / mailbox closed) is
978    /// surfaced as [`ts_control::LogoutError::NetworkError`].
979    pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
980        self.control
981            .ask(control_runner::Logout)
982            .await
983            .map_err(flatten_logout_send_err)
984    }
985
986    /// Publish a `TXT` DNS record for this node via control's `/machine/set-dns` (Go
987    /// `LocalClient.SetDNS`).
988    ///
989    /// Forwards to the control runner, which POSTs the record over a fresh Noise channel. The kameo
990    /// delegated-reply send error is flattened the same way as `fetch_id_token`:
991    /// a handler error carries the real [`ts_control::SetDnsError`]; any other send failure (actor
992    /// shutdown / mailbox closed) is surfaced as [`ts_control::SetDnsError::NetworkError`].
993    pub async fn set_dns(
994        &self,
995        name: String,
996        value: String,
997    ) -> Result<(), ts_control::SetDnsError> {
998        self.control
999            .ask(control_runner::SetDns { name, value })
1000            .await
1001            .map_err(flatten_set_dns_send_err)
1002    }
1003
1004    /// Sign `node_key` with this node's network-lock key and submit the signature to control
1005    /// (Go `tka.sign` Direct case → `/machine/tka/sign`).
1006    ///
1007    /// Submits only — the local [`Authority`](ts_tka::Authority) is **not** mutated here; it advances
1008    /// via the existing verified-sync path. A handler error carries the real [`ts_control::TkaSyncError`];
1009    /// any other send failure (actor shutdown / mailbox closed) is surfaced as
1010    /// [`ts_control::TkaSyncError::NetworkError`].
1011    pub async fn tka_sign(&self, node_key: [u8; 32]) -> Result<(), ts_control::TkaSyncError> {
1012        self.control
1013            .ask(control_runner::TkaSign { node_key })
1014            .await
1015            .map_err(flatten_tka_send_err)
1016    }
1017
1018    /// Disable Tailnet Lock by presenting the `disablement_secret` to control (Go `tka.disable` →
1019    /// `/machine/tka/disable`), targeting the current authority head.
1020    ///
1021    /// Submits only — the local [`Authority`](ts_tka::Authority) is **not** mutated here. A handler
1022    /// error carries the real [`ts_control::TkaSyncError`] (incl.
1023    /// [`Unsupported`](ts_control::TkaSyncError::Unsupported) when there is no known TKA head to
1024    /// disable); any other send failure collapses to
1025    /// [`NetworkError`](ts_control::TkaSyncError::NetworkError).
1026    pub async fn tka_disable(
1027        &self,
1028        disablement_secret: Vec<u8>,
1029    ) -> Result<(), ts_control::TkaSyncError> {
1030        self.control
1031            .ask(control_runner::TkaDisable { disablement_secret })
1032            .await
1033            .map_err(flatten_tka_send_err)
1034    }
1035
1036    /// Initialize Tailnet Lock with this node as the sole initial trusted key, gated by
1037    /// `disablement_secret` (Go `tka` init → `/machine/tka/init/{begin,finish}`).
1038    ///
1039    /// Submits only — does not seed the local [`Authority`](ts_tka::Authority); the node picks up the
1040    /// new lock via the existing verified netmap-sync. A handler error carries the real
1041    /// [`ts_control::TkaSyncError`] ([`Unsupported`](ts_control::TkaSyncError::Unsupported) if
1042    /// control needs other nodes re-signed — the single-node "lock yourself in" subset only); any
1043    /// other send failure collapses to [`NetworkError`](ts_control::TkaSyncError::NetworkError).
1044    pub async fn tka_init(
1045        &self,
1046        disablement_secret: Vec<u8>,
1047    ) -> Result<(), ts_control::TkaSyncError> {
1048        self.control
1049            .ask(control_runner::TkaInit { disablement_secret })
1050            .await
1051            .map_err(flatten_tka_send_err)
1052    }
1053
1054    /// Read up to `limit` entries of the Tailnet-Lock update-chain log, head-first (Go
1055    /// `NetworkLockLog`). A **pure local read** of the synced AUM chain — no control round-trip — so
1056    /// the only failure is a kameo send error (actor gone / mailbox), surfaced as a coarse [`Error`]
1057    /// like the other local-read paths (`status`/`tka_status`), not a [`ts_control::TkaSyncError`].
1058    /// Returns an empty `Vec` when no lock is synced.
1059    pub async fn tka_log(&self, limit: usize) -> Result<Vec<TkaLogEntry>, Error> {
1060        self.control
1061            .ask(control_runner::TkaLog { limit })
1062            .await
1063            .map_err(Error::from)
1064    }
1065
1066    /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` (`acme` feature).
1067    ///
1068    /// Mirrors `fetch_id_token`: forwards to the control runner, which runs
1069    /// the client-side ACME DNS-01 flow on a spawned task and publishes the challenge TXT via the
1070    /// node's set-dns RPC. The kameo delegated-reply send error is flattened — a handler error
1071    /// carries the real [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox
1072    /// closed) is surfaced as a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control
1073    /// plane 501s on set-dns.
1074    #[cfg(feature = "acme")]
1075    pub async fn get_certificate(
1076        &self,
1077        name: String,
1078    ) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
1079        self.control
1080            .ask(control_runner::GetCertificate { name })
1081            .await
1082            .map_err(flatten_cert_send_err)
1083    }
1084
1085    /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` and return the
1086    /// **PEM pair** `(cert_chain_pem, key_pem)` — the analog of Go's
1087    /// `LocalClient.CertPairWithValidity`, for writing the daemon's on-disk `.crt` + `.key`
1088    /// (`tnet cert`). `acme` feature.
1089    ///
1090    /// Same issuance as [`get_certificate`](Self::get_certificate) (one client-side ACME DNS-01
1091    /// order, challenge published via the node's set-dns RPC) — only the result shape differs: this
1092    /// returns the leaf+chain PEM and the leaf-key PEM instead of the opaque
1093    /// [`CertifiedKey`](ts_control::tls::CertifiedKey). The second element is the **leaf private
1094    /// key** PEM; it is never logged anywhere on this path.
1095    ///
1096    /// **`min_validity` (honest "always fresh").** Go's `CertPairWithValidity` reuses a cached cert
1097    /// when it has at least `min_validity` of its lifetime left, and re-issues otherwise. This fork
1098    /// has **no cert cache** — every call performs a fresh issuance — so `min_validity` is accepted
1099    /// for signature compatibility but does not change behavior: a freshly issued cert (full
1100    /// lifetime) trivially satisfies any `min_validity`. A reuse cache is separate future work; this
1101    /// does NOT fake one.
1102    ///
1103    /// Mirrors [`get_certificate`](Self::get_certificate)'s error handling: the kameo
1104    /// delegated-reply send error is flattened — a handler error carries the real
1105    /// [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox closed) collapses
1106    /// to a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control plane 501s on set-dns.
1107    #[cfg(feature = "acme")]
1108    pub async fn cert_pair(
1109        &self,
1110        name: String,
1111        min_validity: Option<Duration>,
1112    ) -> Result<(String, String), ts_control::CertError> {
1113        // No cert cache exists in this fork (every issuance is fresh), so `min_validity` is honored
1114        // trivially by always issuing a full-lifetime cert. Bound (unused beyond this contract) so
1115        // the parameter is explicitly accounted for rather than silently ignored.
1116        let _ = min_validity;
1117        self.control
1118            .ask(control_runner::GetCertPair { name })
1119            .await
1120            .map_err(flatten_cert_send_err)
1121    }
1122
1123    /// Resolve which node owns a tailnet source address.
1124    ///
1125    /// Maps the destination IP of `addr` to its owning node. Mirrors tsnet's `LocalClient::WhoIs`.
1126    /// Returns `None` if no peer holds that tailnet IP.
1127    ///
1128    /// The returned [`WhoIs`] additionally carries the **flow-scoped** peer-capability grants
1129    /// ([`WhoIs::cap_map`], Go `apitype.WhoIsResponse.CapMap`): the caps control's packet-filter
1130    /// application rules authorize for traffic from THIS node (the flow source) to `addr` (the
1131    /// destination). Empty when no grant matches. (The node-level cap map rides
1132    /// [`WhoIs::capabilities`].)
1133    pub async fn whois(&self, addr: core::net::SocketAddr) -> Result<Option<WhoIs>, Error> {
1134        let whois = self
1135            .peer_tracker
1136            .upgrade()
1137            .ok_or(Error {
1138                kind: ErrorKind::ActorGone,
1139                target_actor: None,
1140                message_ty: None,
1141            })?
1142            .ask(peer_tracker::Whois { addr })
1143            .await?;
1144
1145        let Some(mut whois) = whois else {
1146            return Ok(None);
1147        };
1148
1149        // Fill the flow-scoped cap map: src = this node's own tailnet IP (of the dst's family),
1150        // dst = the queried address. A grant applies when its source matches the flow source — `src`
1151        // ∈ its src prefixes OR this node holds one of its source node-caps — AND `dst` ∈ its dst
1152        // prefixes (Go `Filter.CapsWithValues`). Resolve our own IP + cap map from the self node; if
1153        // it isn't known yet, leave the map empty (no grants resolvable without a source).
1154        let dst = addr.ip();
1155        if let Some(self_node) = self.control.ask(control_runner::SelfNode).await? {
1156            let src: core::net::IpAddr = if dst.is_ipv6() {
1157                self_node.tailnet_address.ipv6.addr().into()
1158            } else {
1159                self_node.tailnet_address.ipv4.addr().into()
1160            };
1161            let grants = self.cap_grants_rx.borrow();
1162            whois.cap_map = ts_packetfilter_state::caps_for(&grants, src, dst, |cap| {
1163                self_node.has_node_attr(cap)
1164            });
1165        }
1166
1167        Ok(Some(whois))
1168    }
1169
1170    /// The current direct-path status to the peer holding tailnet IP `dst`: its confirmed direct UDP
1171    /// endpoint and that path's last-measured RTT, or `None` when there is no direct path right now
1172    /// (the peer is relayed via DERP, is unknown, or has no disco key).
1173    ///
1174    /// The latency is the RTT of the most recent disco ping/pong that confirmed the path — a live
1175    /// snapshot up to one probe interval stale, NOT a fresh on-demand round-trip (that is a separate,
1176    /// heavier capability). Mirrors the direct-path latency Go surfaces for `ipnstate.PeerStatus`.
1177    pub async fn direct_path(
1178        &self,
1179        dst: core::net::IpAddr,
1180    ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
1181        let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
1182            kind: ErrorKind::ActorGone,
1183            target_actor: None,
1184            message_ty: None,
1185        })?;
1186
1187        // Resolve the tailnet IP to its node, then to its disco key. No node / no disco key ⇒ no
1188        // direct path is possible (a peer with no disco key can only be reached via DERP).
1189        let Some(node) = peer_tracker
1190            .ask(peer_tracker::PeerByTailnetIp { ip: dst })
1191            .await?
1192        else {
1193            return Ok(None);
1194        };
1195        let Some(disco) = node.disco_key else {
1196            return Ok(None);
1197        };
1198
1199        self.direct
1200            .ask(direct::DirectPathLatency { disco })
1201            .await
1202            .map_err(Into::into)
1203    }
1204
1205    /// Send a disco ping to the peer holding tailnet IP `dst` **now** and await the pong, returning
1206    /// the fresh round-trip latency and the endpoint that answered, or `None` if no pong arrives
1207    /// within `timeout` (or the peer is unknown / has no disco key / no candidate path). This is the
1208    /// true on-demand `PingType::Disco` (Go `tailscale ping`), as opposed to
1209    /// [`direct_path`](Self::direct_path) which reports the last periodic probe's RTT.
1210    ///
1211    /// The ping round-trip is awaited OFF the direct manager's mailbox (we take a `MagicSock` handle
1212    /// and await on it directly), so a slow/timing-out ping never blocks the actor.
1213    pub async fn ping_disco(
1214        &self,
1215        dst: core::net::IpAddr,
1216        timeout: Duration,
1217    ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
1218        let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
1219            kind: ErrorKind::ActorGone,
1220            target_actor: None,
1221            message_ty: None,
1222        })?;
1223
1224        let Some(node) = peer_tracker
1225            .ask(peer_tracker::PeerByTailnetIp { ip: dst })
1226            .await?
1227        else {
1228            return Ok(None);
1229        };
1230        let Some(disco) = node.disco_key else {
1231            return Ok(None);
1232        };
1233
1234        // Cheap synchronous handle fetch, then await the ping OFF the actor mailbox.
1235        let Some(sock) = self.direct.ask(direct::SockHandle).await? else {
1236            return Ok(None);
1237        };
1238        // A `ping_now` error is an underlay UDP send failure (not an actor problem); surface it as a
1239        // reply-level error. A timed-out / unanswered ping is `Ok(None)`, not an error.
1240        sock.ping_now(&disco, timeout).await.map_err(|_| Error {
1241            kind: ErrorKind::ReplyErr,
1242            target_actor: None,
1243            message_ty: None,
1244        })
1245    }
1246
1247    /// Change the selected exit node at runtime (the equivalent of Go `tsnet`'s
1248    /// `LocalClient.EditPrefs(ExitNodeID/ExitNodeIP)`), without recreating the device.
1249    ///
1250    /// Updates the live exit-node selector, then asks the peer tracker to re-broadcast the current
1251    /// peer set so the route updater and source filter re-resolve the new selector immediately.
1252    /// `None` clears the exit node (internet-bound traffic is then dropped, fail-closed, unless this
1253    /// node egresses directly). The selection is re-resolved against the live peer set, so passing a
1254    /// selector for a peer not yet in the netmap simply takes effect once that peer appears.
1255    pub async fn set_exit_node(
1256        &self,
1257        selector: Option<ts_control::ExitNodeSelector>,
1258    ) -> Result<(), Error> {
1259        // Update the live cell every reader borrows from. `send_replace` keeps the value current
1260        // even with no active receivers (none can have dropped while the runtime is up, but it is
1261        // the right non-failing primitive here).
1262        self.exit_node_tx.send_replace(selector);
1263
1264        // Trigger an immediate re-resolution: the route updater (outbound routes + DoH delegation)
1265        // and the source filter (inbound validation) both recompute on an `Arc<PeerState>`, so a
1266        // re-broadcast applies the new exit without waiting for the next netmap update.
1267        self.peer_tracker
1268            .upgrade()
1269            .ok_or(Error {
1270                kind: ErrorKind::ActorGone,
1271                target_actor: None,
1272                message_ty: None,
1273            })?
1274            .ask(peer_tracker::RepublishState)
1275            .await
1276            .map_err(Into::into)
1277    }
1278
1279    /// The currently-selected exit node, or `None` if none is selected.
1280    pub fn exit_node(&self) -> Option<ts_control::ExitNodeSelector> {
1281        self.env.exit_node()
1282    }
1283
1284    /// Toggle whether this node accepts peer-advertised subnet routes at runtime (the equivalent of
1285    /// Go `tsnet`'s `LocalClient.EditPrefs(RouteAll)` / `tailscale set --accept-routes`), without
1286    /// recreating the device.
1287    ///
1288    /// `accept-routes` is a purely **local** preference — unlike advertised routes it is never
1289    /// reported to control (no `Hostinfo` / MapRequest side), so this only re-runs the local
1290    /// route/source-filter recompute, mirroring [`set_exit_node`](Self::set_exit_node) rather than
1291    /// [`set_advertise_routes`](Self::set_advertise_routes). Updates the live cell, then asks the peer
1292    /// tracker to re-broadcast the current peer set so the route updater (outbound routes) and the
1293    /// source filter (inbound validation) re-filter against the new value immediately: turning it on
1294    /// installs newly-accepted subnet routes (and widens the source filter to match); turning it off
1295    /// removes them from BOTH in lock-step (never accepting a source for a route no longer installed).
1296    /// Self routes and the exit-node default `/0` are unaffected (the latter is gated by the exit-node
1297    /// selection, not this flag).
1298    ///
1299    /// In TUN transport mode the host routing table is also re-steered live: the `RepublishState`
1300    /// kicked below re-broadcasts the peer set to the `TunActor`, whose `PeerState` handler re-reads
1301    /// `accept_routes` (and the exit selection) from `Env` and re-applies the host routes — so the
1302    /// toggle takes effect without rebuilding the device (the apply is an idempotent add-new/
1303    /// remove-gone diff). The exit-node default `/0` is still keyed on the exit selection, not this flag.
1304    pub async fn set_accept_routes(&self, accept: bool) -> Result<(), Error> {
1305        // Update the live cell every reader borrows from (same primitive/rationale as set_exit_node).
1306        self.accept_routes_tx.send_replace(accept);
1307
1308        // Trigger an immediate re-filter: the route updater and source filter both recompute on an
1309        // `Arc<PeerState>`, so a re-broadcast applies the new preference without waiting for the next
1310        // netmap update. Both re-read the same live cell, so the outbound route set and the inbound
1311        // source filter stay coupled (the anti-leak invariant).
1312        self.peer_tracker
1313            .upgrade()
1314            .ok_or(Error {
1315                kind: ErrorKind::ActorGone,
1316                target_actor: None,
1317                message_ty: None,
1318            })?
1319            .ask(peer_tracker::RepublishState)
1320            .await
1321            .map_err(Into::into)
1322    }
1323
1324    /// Whether this node currently accepts peer-advertised subnet routes (`--accept-routes`).
1325    pub fn accept_routes(&self) -> bool {
1326        self.env.accept_routes()
1327    }
1328
1329    /// Toggle whether this node accepts the tailnet's DNS configuration at runtime (the equivalent of
1330    /// Go `tsnet`'s `LocalClient.EditPrefs(CorpDNS)` / `tailscale set --accept-dns`), without
1331    /// recreating the device.
1332    ///
1333    /// Like [`set_accept_routes`](Self::set_accept_routes), `accept-dns` is a purely **local**
1334    /// preference — it is never reported to control (no `Hostinfo` / MapRequest side), so this only
1335    /// re-runs the local MagicDNS view rebuild. Updates the live cell, then asks the peer tracker to
1336    /// re-broadcast the current peer set; the resulting `PeerState` rebuild re-applies the gate on the
1337    /// MagicDNS responder (and the peerAPI DoH server that shares its view). When `false`, the
1338    /// responder ignores the control-pushed DNS config and answers every query `REFUSED`, mirroring Go
1339    /// applying an empty `dns.Config` when `CorpDNS` is off; flipping it back to `true` restores
1340    /// serving from the still-current config (the real config is never destroyed — only gated at the
1341    /// read site), so the OFF→ON restore is automatic.
1342    pub async fn set_accept_dns(&self, accept: bool) -> Result<(), Error> {
1343        // Update the live cell every reader borrows from (same primitive/rationale as set_accept_routes).
1344        self.accept_dns_tx.send_replace(accept);
1345
1346        // Trigger an immediate view rebuild: the MagicDNS responder re-reads `Env::accept_dns()` when
1347        // it handles a `PeerState`, so a re-broadcast re-applies the gate on both the netstack
1348        // responder and the peerAPI DoH server (which share the view) without waiting for the next
1349        // control/peer update. Mirrors `set_accept_routes`'s republish.
1350        self.peer_tracker
1351            .upgrade()
1352            .ok_or(Error {
1353                kind: ErrorKind::ActorGone,
1354                target_actor: None,
1355                message_ty: None,
1356            })?
1357            .ask(peer_tracker::RepublishState)
1358            .await
1359            .map_err(Into::into)
1360    }
1361
1362    /// Whether this node currently accepts the tailnet's DNS configuration (`--accept-dns` / `CorpDNS`).
1363    pub fn accept_dns(&self) -> bool {
1364        self.env.accept_dns()
1365    }
1366
1367    /// Change the set of subnet routes this node advertises at runtime (Go `tailscale set
1368    /// --advertise-routes`). Applies BOTH halves together so the wire and the data path agree:
1369    ///
1370    /// 1. **Wire** — re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
1371    ///    (so control grants the node the subnet-router role for exactly these prefixes).
1372    /// 2. **Local** — swap the forwarder's accept/dial route table (so the node actually forwards the
1373    ///    prefixes it advertises). New flows see the new set; in-flight flows keep their routing.
1374    ///
1375    /// `routes` is filtered to the IPv4-only, deduplicated set this fork can honor (IPv6 prefixes are
1376    /// dropped under the IPv6-off posture — we never advertise a route we won't forward), so the wire
1377    /// and forwarder are fed the identical final set. This sets the explicit subnet prefixes only; it
1378    /// does NOT touch the exit-node `0.0.0.0/0` advertisement (a separate concern).
1379    pub async fn set_advertise_routes(&self, routes: Vec<ipnet::IpNet>) -> Result<(), Error> {
1380        // Update the explicit-subnet part of the live preference, keep the exit-node flag, and
1381        // re-send the composed set. Composes with `set_advertise_exit_node` (neither clobbers the
1382        // other's contribution to `Hostinfo.RoutableIPs`).
1383        let composed = {
1384            let mut adv = self.advertise.lock().unwrap_or_else(|p| p.into_inner());
1385            adv.routes = routes;
1386            compose_advertised_routes(adv.routes.clone(), adv.exit_node)
1387        };
1388        self.apply_advertised_routes(composed).await
1389    }
1390
1391    /// Advertise (or stop advertising) this node as an **exit node** — the `0.0.0.0/0` + `::/0`
1392    /// default-route pair (Go `tailscale set --advertise-exit-node`). Composes with
1393    /// [`set_advertise_routes`](Self::set_advertise_routes): toggling the exit node re-sends the
1394    /// explicit subnet routes plus (when `enable`) the default-route pair, so the two preferences are
1395    /// independent. Like `set_advertise_routes`, this both re-advertises `Hostinfo.RoutableIPs` to
1396    /// control AND updates the forwarder's accept/dial set, applied together. Control still gates
1397    /// whether the advertised exit node is actually *usable* by peers (this only advertises it).
1398    pub async fn set_advertise_exit_node(&self, enable: bool) -> Result<(), Error> {
1399        let composed = {
1400            let mut adv = self.advertise.lock().unwrap_or_else(|p| p.into_inner());
1401            adv.exit_node = enable;
1402            compose_advertised_routes(adv.routes.clone(), adv.exit_node)
1403        };
1404        self.apply_advertised_routes(composed).await
1405    }
1406
1407    /// Push a freshly-composed advertised-route set to BOTH halves: the forwarder's accept/dial
1408    /// table (local) FIRST — so the node forwards a prefix before control grants it, never the
1409    /// reverse — then re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
1410    /// (wire). `composed` is already filtered + exit-node-folded by [`compose_advertised_routes`].
1411    async fn apply_advertised_routes(&self, composed: Vec<ipnet::IpNet>) -> Result<(), Error> {
1412        self.forwarder
1413            .ask(forwarder_actor::UpdateRoutes {
1414                routes: composed.clone(),
1415            })
1416            .await?;
1417        self.control
1418            .ask(control_runner::SetAdvertiseRoutes { routes: composed })
1419            .await
1420            .map_err(Into::into)
1421    }
1422
1423    /// Change this node's hostname at runtime (Go `tailscale set --hostname`), re-reporting
1424    /// `Hostinfo.Hostname` to control on the live map-poll connection. Hostname is display-only
1425    /// (control reflects it in the netmap), so there is no dataplane half. The new value is also
1426    /// what a subsequent re-registration reports, so it persists across a reconnect.
1427    pub async fn set_hostname(&self, hostname: String) -> Result<(), Error> {
1428        self.control
1429            .ask(control_runner::SetHostname { hostname })
1430            .await
1431            .map_err(Into::into)
1432    }
1433
1434    /// Subscribe to netmap peer-change events: the **narrow** peer-set view.
1435    ///
1436    /// Returns a [`watch::Receiver`] whose value is the current set of peer [`StatusNode`]s,
1437    /// updated on every netmap state update from control. Await
1438    /// [`watch::Receiver::changed`](tokio::sync::watch::Receiver::changed) to react to peers
1439    /// joining, leaving, or changing. For the unified Go-`WatchIPNBus` feed that merges this with
1440    /// device-state and the interactive-login URL, see [`watch_ipn_bus`](Self::watch_ipn_bus); this
1441    /// method is the peer-only projection of the same underlying cell.
1442    pub async fn watch_netmap(&self) -> Result<watch::Receiver<Vec<StatusNode>>, Error> {
1443        self.peer_tracker
1444            .upgrade()
1445            .ok_or(Error {
1446                kind: ErrorKind::ActorGone,
1447                target_actor: None,
1448                message_ty: None,
1449            })?
1450            .ask(peer_tracker::WatchNetmap)
1451            .await
1452            .map_err(Into::into)
1453    }
1454
1455    /// The current device connection-[`DeviceState`].
1456    pub fn device_state(&self) -> DeviceState {
1457        self.state_rx.borrow().clone()
1458    }
1459
1460    /// Watch the device connection-[`DeviceState`] (`Connecting` → `Running` / `NeedsLogin` /
1461    /// `Expired` / `Failed`).
1462    ///
1463    /// Returns a [`watch::Receiver`]; await
1464    /// [`changed`](tokio::sync::watch::Receiver::changed) to react push-style to control connection
1465    /// transitions instead of polling [`status`](Self::status). The initial value is the current
1466    /// state. Note: a transient per-reconnect dip back to `Connecting` is **not** currently
1467    /// emitted (control transparently reconnects below this layer); the state reflects registration
1468    /// outcome and node-key expiry.
1469    pub fn watch_state(&self) -> watch::Receiver<DeviceState> {
1470        self.state_rx.clone()
1471    }
1472
1473    /// Wait until the device finishes registering, returning a typed outcome.
1474    ///
1475    /// Resolves `Ok(())` once the device reaches [`DeviceState::Running`]. Returns a typed
1476    /// [`RegistrationError`] otherwise — the actionable distinction between "retry", "re-pair", and
1477    /// "drive interactive login" that replaces polling the device's `ipv4_addr` in a loop:
1478    /// - `AuthRejected` — bad/expired/unknown auth key. **Permanent** (re-pair).
1479    /// - `NeedsLogin(url)` — interactive authorization required (no usable auth key). **Not
1480    ///   permanent**: the runtime keeps retrying and will reach `Running` once the user authorizes
1481    ///   the URL. An **auth-key** caller should treat this as a failure; an **interactive** caller
1482    ///   should ignore this return and instead drive the flow via [`watch_state`](Self::watch_state)
1483    ///   (this method returns the URL eagerly rather than blocking for the whole login).
1484    /// - `NetworkUnreachable` — control unreachable. **Transient** (retry).
1485    /// - `Timeout` — no settled state within `timeout`.
1486    ///
1487    /// `KeyExpired` is not produced by this initial wait (a node key expires only *after* it has
1488    /// come up); observe post-registration expiry via [`watch_state`](Self::watch_state).
1489    /// `timeout` of `None` waits indefinitely for a settled state.
1490    pub async fn wait_until_running(
1491        &self,
1492        timeout: Option<Duration>,
1493    ) -> Result<(), RegistrationError> {
1494        device_state::wait_for_running(self.state_rx.clone(), timeout).await
1495    }
1496
1497    /// Subscribe to the unified IPN notification bus (Go `ipn` `WatchIPNBus` /
1498    /// `LocalBackend.WatchNotifications`).
1499    ///
1500    /// Returns an [`IpnBusWatcher`]; await [`next`](IpnBusWatcher::next) to receive [`Notify`]
1501    /// events that coalesce device-[`DeviceState`] changes (including the interactive-login URL as
1502    /// `browse_to_url`) and netmap changes (the peer set, or this node alone) into one feed. `mask`
1503    /// ([`NotifyWatchOpt`]) selects which current-state fields are front-loaded as an initial
1504    /// snapshot on subscribe (`INITIAL_STATE` / `INITIAL_NETMAP`), exactly like Go's
1505    /// `NotifyInitialState` / `NotifyInitialNetMap`.
1506    ///
1507    /// This composes the same `watch` cells as [`watch_state`](Self::watch_state),
1508    /// [`watch_netmap`](Self::watch_netmap), and `pop_browser_url` — one source of truth, so the
1509    /// merged feed cannot diverge from those narrow views. Besides the registration-time login URL
1510    /// (carried by `NeedsLogin`), `browse_to_url` also streams the mid-session
1511    /// `MapResponse.PopBrowserURL` (re-auth / consent on an already-running node). Delivery is
1512    /// best-effort/lossy (a bounded per-watcher buffer; a notification is dropped rather than
1513    /// blocking the runtime if a slow consumer's buffer fills), matching Go's bus. The stream ends
1514    /// (`next` returns `None`) on runtime shutdown or when the watcher is dropped.
1515    pub async fn watch_ipn_bus(&self, mask: NotifyWatchOpt) -> Result<IpnBusWatcher, Error> {
1516        // The peer-set cell lives on the peer-tracker actor; obtain a receiver the same way
1517        // `watch_netmap` does. State + shutdown cells are held here.
1518        let peer_rx = self
1519            .peer_tracker
1520            .upgrade()
1521            .ok_or(Error {
1522                kind: ErrorKind::ActorGone,
1523                target_actor: None,
1524                message_ty: None,
1525            })?
1526            .ask(peer_tracker::WatchNetmap)
1527            .await?;
1528        // The running-node consent-URL cell lives on the control runner; obtain its receiver the
1529        // same way (the control actor ref is strong, so no upgrade needed).
1530        let browser_rx = self.control.ask(control_runner::WatchBrowserUrl).await?;
1531        // The self-node cell also lives on the control runner. A change to it alone (no peer
1532        // change) still ticks `net_map`, as Go's `Notify.SelfChange` does.
1533        let self_rx = self.control.ask(control_runner::WatchSelfNode).await?;
1534        Ok(ipn_bus::spawn_watcher(
1535            mask,
1536            self.state_rx.clone(),
1537            peer_rx,
1538            browser_rx,
1539            self_rx,
1540            self.shutdown.subscribe(),
1541        ))
1542    }
1543
1544    /// Attempt to shut down the runtime gracefully.
1545    ///
1546    /// Returns false if the shutdown timed out. It is still shut down if it timed out, just
1547    /// more violently and with possible resource leaks.
1548    pub async fn graceful_shutdown(self, timeout: Option<Duration>) -> bool {
1549        self.shutdown.send_replace(true);
1550        // The port mapper's release is the first step of the timed shutdown (`close_portmap`):
1551        // `close` stops new mapping work before it awaits anything, then deletes its router rules
1552        // over its own LAN sockets (never the underlay socket). Its budget is at most 1 s and
1553        // never more than `timeout`, so the whole shutdown stays within `timeout`.
1554        async fn _shutdown_all(runtime: Runtime, timeout: Option<Duration>) {
1555            #[cfg(feature = "portmapper")]
1556            runtime.portmap.close(timeout).await;
1557            #[cfg(not(feature = "portmapper"))]
1558            let _ = timeout;
1559
1560            // See the note in `Drop` for why we only need to stop these actors to bring down the
1561            // whole runtime.
1562
1563            let _ignore = runtime.control.stop_gracefully().await;
1564            let _ignore = runtime.dataplane.stop_gracefully().await;
1565            let _ignore = runtime.env.bus.stop_gracefully().await;
1566
1567            tokio::join![
1568                runtime.control.wait_for_shutdown(),
1569                runtime.dataplane.wait_for_shutdown(),
1570                runtime.env.bus.wait_for_shutdown(),
1571            ];
1572        }
1573
1574        let fut = _shutdown_all(self, timeout);
1575
1576        match timeout {
1577            Some(timeout) => tokio::time::timeout(timeout, fut).await.is_ok(),
1578            None => {
1579                fut.await;
1580                true
1581            }
1582        }
1583    }
1584}
1585
1586impl Drop for Runtime {
1587    fn drop(&mut self) {
1588        // Best-effort release of the port mapper's router rules first: one unacknowledged delete
1589        // per rule, no runtime and no reply wait. A no-op after `graceful_shutdown` closed it.
1590        // (The guard does the same when it is dropped, so no path out of here skips it.)
1591        #[cfg(feature = "portmapper")]
1592        self.portmap.release_now();
1593
1594        // Stop the taildrop reaper so it cannot outlive the runtime (the `reauth_bridge` pattern). It
1595        // also self-exits when `shutdown` flips below, but aborting is immediate and covers the
1596        // already-shutdown early-return path too.
1597        if let Some(reaper) = self.taildrop_reaper.take() {
1598            reaper.abort();
1599        }
1600
1601        // We must have already run `graceful_shutdown`: on the happy path, this does nothing, but
1602        // if it timed out, we need to make sure the actors are dead so we don't leak them and their
1603        // dependents.
1604        if *self.shutdown.borrow() {
1605            self.control.kill();
1606            self.dataplane.kill();
1607            self.env.bus.kill();
1608            return;
1609        }
1610
1611        self.shutdown.send_replace(true);
1612
1613        // The security guard retains supervised actors until it can kill them independently of
1614        // full mailboxes. Its Drop also aborts the packet pump and all remaining supervised actors.
1615        // Stop the control/dataplane/bus here for the graceful-shutdown path.
1616
1617        // First shut down the actors we have an ActorRef to:
1618        try_shutdown(&self.control);
1619        try_shutdown(&self.dataplane);
1620
1621        // Then shut down the message bus; the guard cancels its subscribers on Drop.
1622        try_shutdown(&self.env.bus);
1623    }
1624}
1625
1626fn try_shutdown(a: &ActorRef<impl kameo::Actor>) {
1627    if let Err(e) = a.mailbox_sender().try_send(Signal::Stop) {
1628        tracing::error!(error = %e, "graceful shutdown failed, killing actor");
1629        a.kill();
1630    }
1631}
1632
1633/// Tailscale's overlay MTU. The userspace netstacks MUST advertise an MSS that fits this so they
1634/// never hand the WireGuard encrypt path an IP packet larger than the tunnel can carry (the netstack
1635/// has no PMTU discovery and nothing re-segments between it and the 1280-MTU TUN). This is the same
1636/// default the TUN device uses (`tun_config_from_control`); both are derived from this value so the
1637/// netstack and the TUN always agree.
1638///
1639/// This is the **inner** IP-packet budget. The WireGuard transport header (a 16-byte
1640/// `TransportDataHeader` + the 16-byte AEAD tag = 32 bytes) is added by `TransmitSession::encrypt`
1641/// *after* the netstack produces the inner packet, and the outer UDP/IP headers ride on top of that.
1642/// So do NOT subtract the WireGuard overhead here — that would be a double-subtraction that
1643/// under-fills the tunnel and diverges from the TUN's MTU. The assert below documents that the outer
1644/// datagram still fits a conventional 1500-byte physical path with margin (1280 + 32 WG + 8 UDP +
1645/// 20 outer-IP = 1340).
1646const DEFAULT_OVERLAY_MTU: u16 = 1280;
1647
1648const _: () = assert!(
1649    DEFAULT_OVERLAY_MTU as usize + 32 + 8 + 20 <= 1500,
1650    "inner overlay MTU + WireGuard(32) + UDP(8) + outer-IP(20) must fit a 1500-byte physical path"
1651);
1652
1653/// Build the netstack config shared by both userspace netstacks (application + forwarder) from the
1654/// per-deployment `tcp_buffer_size` and `mtu` knobs.
1655///
1656/// `tcp_buffer_size`: `None` keeps the netstack default (256 KiB/direction); `Some(n)` overrides it
1657/// (e.g. a smaller window on a memory-constrained exit node forwarding many concurrent flows — see
1658/// [`netstack::netcore::Config::tcp_buffer_size`]).
1659///
1660/// `mtu`: the overlay/tunnel MTU. `None` (and a stray `0`) falls back to [`DEFAULT_OVERLAY_MTU`]
1661/// (1280), exactly as the TUN device does, so the netstack's advertised MSS fits the tunnel. Leaving
1662/// this at the netstack's generic 1500 default (the prior behavior) made smoltcp advertise MSS ~1460
1663/// and segment to ~1500 B, which then overflowed the 1280 TUN — a PMTU black-hole / throughput cliff.
1664///
1665/// Factored out of [`Runtime::spawn`] so the mapping is unit-testable without standing up the actors.
1666fn netstack_config_from(
1667    tcp_buffer_size: Option<usize>,
1668    mtu: Option<u16>,
1669) -> netstack::netcore::Config {
1670    let mut c = netstack::netcore::Config::default();
1671    if let Some(tcp_buffer_size) = tcp_buffer_size {
1672        c.tcp_buffer_size = tcp_buffer_size;
1673    }
1674    // `0` is not a usable MTU; treat it like `None` and fall back to the overlay default, mirroring
1675    // the TUN's `and_then(NonZeroU16::new).unwrap_or(1280)`.
1676    let mtu = mtu.filter(|&m| m != 0).unwrap_or(DEFAULT_OVERLAY_MTU);
1677    c.mtu = usize::from(mtu);
1678    c
1679}
1680
1681/// Filter a requested advertise-route set to the IPv4-only, deduplicated set this fork can honor,
1682/// mirroring [`ts_control::Config::advertised_routes`] so a runtime `set_advertise_routes` feeds the
1683/// wire (control grant) and the forwarder (accept/dial table) the identical final set. IPv6 prefixes
1684/// are dropped under the IPv6-off posture — we never advertise a route we won't forward. Order is
1685/// preserved (first occurrence wins). Factored out so the filter is unit-testable without an actor.
1686fn filter_advertise_routes(routes: Vec<ipnet::IpNet>) -> Vec<ipnet::IpNet> {
1687    let mut filtered: Vec<ipnet::IpNet> = Vec::new();
1688    for net in routes {
1689        if matches!(net, ipnet::IpNet::V4(_)) {
1690            if !filtered.contains(&net) {
1691                filtered.push(net);
1692            }
1693        } else {
1694            tracing::warn!(prefix = %net, "dropping IPv6 advertise route (IPv6-off posture)");
1695        }
1696    }
1697    filtered
1698}
1699
1700/// Compose the final advertised-route set from the explicit subnet `routes` and the exit-node flag,
1701/// mirroring [`ts_control::Config::advertised_routes`]: the IPv4-only, deduplicated subnet prefixes,
1702/// plus the exit-node pair `0.0.0.0/0` + `::/0` appended when `exit_node` is set. This is the
1703/// single source of truth both runtime advertise mutators (`set_advertise_routes`,
1704/// `set_advertise_exit_node`) feed, so the two compose instead of clobbering. Factored out so the composition is unit-testable without an actor.
1705fn compose_advertised_routes(routes: Vec<ipnet::IpNet>, exit_node: bool) -> Vec<ipnet::IpNet> {
1706    let mut filtered = filter_advertise_routes(routes);
1707    if exit_node {
1708        for net in ts_control::exit_node_routes() {
1709            if !filtered.contains(&net) {
1710                filtered.push(net);
1711            }
1712        }
1713    }
1714    filtered
1715}
1716
1717/// The runtime's live advertised-route preference: the explicit subnet routes plus whether this node
1718/// advertises itself as an exit node. Held behind a `Mutex` on the [`Runtime`] so
1719/// [`Runtime::set_advertise_routes`] and [`Runtime::set_advertise_exit_node`] each mutate their own
1720/// part and re-send the composed set — they compose rather than clobber (Go `EditPrefs` keeps
1721/// `AdvertiseRoutes` and the exit-node advertisement as independent prefs that both feed
1722/// `Hostinfo.RoutableIPs`).
1723#[derive(Debug, Default, Clone)]
1724struct AdvertiseState {
1725    /// The explicit subnet prefixes (pre-filter; the last value passed to `set_advertise_routes`).
1726    routes: Vec<ipnet::IpNet>,
1727    /// Whether this node advertises the exit-node default routes (`0.0.0.0/0` + `::/0`).
1728    exit_node: bool,
1729}
1730
1731/// Flatten a kameo delegated-reply [`SendError`] for the id-token RPC into the RPC's own
1732/// [`ts_control::IdTokenError`].
1733///
1734/// A [`SendError::HandlerError`](kameo::error::SendError::HandlerError) carries the real
1735/// `IdTokenError` produced by the handler and is surfaced verbatim. Any other send failure (actor
1736/// not running / stopped, mailbox full, send timeout) is a delivery problem rather than an RPC
1737/// result, so it collapses to a transient [`ts_control::IdTokenError::NetworkError`]. Factored out
1738/// of [`Runtime::fetch_id_token`] so this mapping is unit-testable without standing up an actor.
1739fn flatten_send_err<M>(
1740    e: kameo::error::SendError<M, ts_control::IdTokenError>,
1741) -> ts_control::IdTokenError {
1742    match e {
1743        kameo::error::SendError::HandlerError(err) => err,
1744        _ => ts_control::IdTokenError::NetworkError,
1745    }
1746}
1747
1748/// Flatten a kameo `SendError` from the `Logout` ask into a [`ts_control::LogoutError`].
1749///
1750/// A `HandlerError` carries the real `LogoutError` from the control RPC and is surfaced verbatim;
1751/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
1752/// problem, not a logout result — collapses to the transient [`ts_control::LogoutError::NetworkError`]
1753/// (logout is idempotent, so a retry after a delivery failure is safe). Factored out of
1754/// [`Runtime::logout`] so the mapping is unit-testable without standing up an actor.
1755fn flatten_logout_send_err<M>(
1756    e: kameo::error::SendError<M, ts_control::LogoutError>,
1757) -> ts_control::LogoutError {
1758    match e {
1759        kameo::error::SendError::HandlerError(err) => err,
1760        _ => ts_control::LogoutError::NetworkError,
1761    }
1762}
1763
1764/// Flatten a kameo `SendError` from the `SetDns` ask into a [`ts_control::SetDnsError`].
1765///
1766/// A `HandlerError` carries the real `SetDnsError` from the set-dns RPC and is surfaced verbatim;
1767/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
1768/// problem, not a publish result — collapses to the transient
1769/// [`ts_control::SetDnsError::NetworkError`]. Factored out of [`Runtime::set_dns`] so the mapping is
1770/// unit-testable without standing up an actor.
1771fn flatten_set_dns_send_err<M>(
1772    e: kameo::error::SendError<M, ts_control::SetDnsError>,
1773) -> ts_control::SetDnsError {
1774    match e {
1775        kameo::error::SendError::HandlerError(err) => err,
1776        _ => ts_control::SetDnsError::NetworkError,
1777    }
1778}
1779
1780/// Flatten a kameo `SendError` from a TKA mutation ask (`TkaSign`/`TkaDisable`) into a
1781/// [`ts_control::TkaSyncError`]. A `HandlerError` carries the real RPC error; any other send failure
1782/// (actor shutdown / mailbox closed) is surfaced as the transient
1783/// [`ts_control::TkaSyncError::NetworkError`]. Generic over the message type so both share it.
1784fn flatten_tka_send_err<M>(
1785    e: kameo::error::SendError<M, ts_control::TkaSyncError>,
1786) -> ts_control::TkaSyncError {
1787    match e {
1788        kameo::error::SendError::HandlerError(err) => err,
1789        _ => ts_control::TkaSyncError::NetworkError,
1790    }
1791}
1792
1793/// Flatten a kameo `SendError` from the `GetCertificate` / `GetCertPair` ask into a
1794/// [`ts_control::CertError`].
1795///
1796/// A `HandlerError` carries the real `CertError` produced by the ACME issuance and is surfaced
1797/// verbatim. `CertError` has no transient-network variant, so any other send failure (actor not
1798/// running / stopped, mailbox full, send timeout) — a delivery problem rather than an issuance
1799/// result — collapses to a [`ts_control::CertError::Io`]. Generic over the message type, so it
1800/// serves both [`Runtime::get_certificate`] and [`Runtime::cert_pair`]; factored out so the mapping
1801/// is unit-testable without standing up an actor.
1802#[cfg(feature = "acme")]
1803fn flatten_cert_send_err<M>(
1804    e: kameo::error::SendError<M, ts_control::CertError>,
1805) -> ts_control::CertError {
1806    match e {
1807        kameo::error::SendError::HandlerError(err) => err,
1808        _ => ts_control::CertError::Io(std::io::Error::other(
1809            "control runner unavailable for certificate issuance",
1810        )),
1811    }
1812}
1813
1814#[cfg(test)]
1815mod tests {
1816    use super::*;
1817
1818    /// `None` must leave the netstack's own default TCP window in place (the 256 KiB throughput
1819    /// default), and must not silently coerce to some other value.
1820    #[test]
1821    fn netstack_config_none_uses_netstack_default() {
1822        let default = netstack::netcore::Config::default();
1823        let built = netstack_config_from(None, None);
1824        assert_eq!(
1825            built.tcp_buffer_size, default.tcp_buffer_size,
1826            "None must inherit the netstack default TCP buffer size"
1827        );
1828    }
1829
1830    #[test]
1831    fn netstack_config_mtu_defaults_to_overlay_not_generic_1500() {
1832        // The crux of the fix: with no explicit MTU, the netstack must use the 1280 overlay MTU, NOT
1833        // smoltcp's generic 1500 default — otherwise it advertises an MSS that overflows the tunnel.
1834        let built = netstack_config_from(None, None);
1835        assert_eq!(
1836            built.mtu,
1837            usize::from(DEFAULT_OVERLAY_MTU),
1838            "netstack MTU must default to the 1280 overlay MTU, not the 1500 netstack default"
1839        );
1840        assert_ne!(built.mtu, 1500, "must not leave the generic 1500 default");
1841    }
1842
1843    #[test]
1844    fn netstack_config_honors_explicit_mtu_and_rejects_zero() {
1845        // An explicit (control-supplied) MTU is honored verbatim.
1846        assert_eq!(netstack_config_from(None, Some(1400)).mtu, 1400);
1847        // A stray 0 is not a usable MTU; fall back to the overlay default (mirrors the TUN).
1848        assert_eq!(
1849            netstack_config_from(None, Some(0)).mtu,
1850            usize::from(DEFAULT_OVERLAY_MTU)
1851        );
1852    }
1853
1854    #[test]
1855    fn netstack_config_overlay_mtu_matches_tun_default() {
1856        // The netstack MTU default and the TUN MTU default must be the same value, or the two
1857        // netstacks and the TUN would disagree on the segment size budget.
1858        assert_eq!(
1859            DEFAULT_OVERLAY_MTU, 1280,
1860            "overlay MTU must match the TUN device default (tun_config_from_control)"
1861        );
1862    }
1863
1864    /// `Some(n)` must override the TCP window (the memory-vs-throughput knob exit-node operators
1865    /// reach for), reaching the config that both netstacks are built from.
1866    #[test]
1867    fn netstack_config_some_overrides_buffer() {
1868        let built = netstack_config_from(Some(64 * 1024), None);
1869        assert_eq!(
1870            built.tcp_buffer_size,
1871            64 * 1024,
1872            "Some(n) must override the TCP buffer size that both netstacks use"
1873        );
1874    }
1875
1876    /// `set_advertise_routes` must feed the wire and the forwarder the IDENTICAL filtered set:
1877    /// IPv4-only (IPv6 dropped under the IPv6-off posture), deduplicated, order preserved.
1878    #[test]
1879    fn filter_advertise_routes_keeps_v4_dedups_drops_v6() {
1880        let v4a: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
1881        let v4b: ipnet::IpNet = "192.168.1.0/24".parse().unwrap();
1882        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1883
1884        // Mixed input with a duplicate v4 and a v6 prefix.
1885        let out = filter_advertise_routes(vec![v4a, v6, v4b, v4a]);
1886
1887        assert_eq!(
1888            out,
1889            vec![v4a, v4b],
1890            "v6 dropped, duplicate v4 collapsed, first-occurrence order preserved"
1891        );
1892    }
1893
1894    /// An all-IPv6 request filters to empty (we never advertise a route we won't forward) rather
1895    /// than erroring — clearing the advertised set is a legitimate outcome.
1896    #[test]
1897    fn filter_advertise_routes_all_v6_is_empty() {
1898        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1899        assert!(filter_advertise_routes(vec![v6]).is_empty());
1900    }
1901
1902    /// `compose_advertised_routes` folds the exit-node default-route pair onto the filtered subnet routes
1903    /// when (and only when) the exit-node flag is set — so `set_advertise_routes` and
1904    /// `set_advertise_exit_node` compose. The two preferences are independent.
1905    #[test]
1906    fn compose_advertised_routes_folds_exit_node() {
1907        let subnet: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
1908        let default_v4: ipnet::IpNet = "0.0.0.0/0".parse().unwrap();
1909        let default_v6: ipnet::IpNet = "::/0".parse().unwrap();
1910
1911        // Exit node off: just the (filtered) subnet routes.
1912        assert_eq!(
1913            compose_advertised_routes(vec![subnet], false),
1914            vec![subnet],
1915            "exit-node off ⇒ no default route"
1916        );
1917        // Exit node on: subnet routes PLUS the default-route pair.
1918        assert_eq!(
1919            compose_advertised_routes(vec![subnet], true),
1920            vec![subnet, default_v4, default_v6],
1921            "exit-node on ⇒ 0.0.0.0/0 + ::/0 appended"
1922        );
1923        // Exit node on with NO subnet routes: just the default route.
1924        assert_eq!(
1925            compose_advertised_routes(vec![], true),
1926            vec![default_v4, default_v6],
1927            "exit-node alone advertises only the default-route pair"
1928        );
1929        // Idempotent: an explicit 0.0.0.0/0 already in the routes isn't duplicated by the fold.
1930        assert_eq!(
1931            compose_advertised_routes(vec![default_v4], true),
1932            vec![default_v4, default_v6],
1933            "the exit-node fold dedups against an explicit default route"
1934        );
1935    }
1936
1937    /// A `HandlerError` carries the real `IdTokenError` from the RPC handler and must pass through
1938    /// verbatim, not be flattened to a generic network error. Using an `Internal(_)` payload (not
1939    /// `NetworkError`) makes the passthrough observable: a buggy flatten that always returned
1940    /// `NetworkError` would fail this assertion.
1941    #[test]
1942    fn flatten_send_err_handler_error_passes_through() {
1943        // Build an `Internal(_)` payload via the public `From<Utf8Error>` conversion (no extra
1944        // deps): it is distinct from the `_ => NetworkError` fallback, so a buggy flatten that
1945        // always returned `NetworkError` would fail this assertion.
1946        // Route the invalid bytes through a runtime Vec so the `invalid_from_utf8` lint (which only
1947        // fires on compile-time-known literals) doesn't flag this intentional bad input.
1948        let bytes = vec![0xffu8, 0xfe];
1949        let utf8_err = core::str::from_utf8(&bytes).unwrap_err();
1950        let inner = ts_control::IdTokenError::from(utf8_err);
1951        assert!(matches!(inner, ts_control::IdTokenError::Internal(_)));
1952        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1953            kameo::error::SendError::HandlerError(inner.clone());
1954        assert_eq!(flatten_send_err(e), inner);
1955    }
1956
1957    /// A non-handler send failure (actor stopped) is a delivery problem, not an RPC result, so it
1958    /// must collapse to a transient `NetworkError`.
1959    #[test]
1960    fn flatten_send_err_actor_stopped_is_network_error() {
1961        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1962            kameo::error::SendError::ActorStopped;
1963        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1964    }
1965
1966    /// `ActorNotRunning` (the message bounces back undelivered) is likewise a delivery failure and
1967    /// must map to a transient `NetworkError`.
1968    #[test]
1969    fn flatten_send_err_actor_not_running_is_network_error() {
1970        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1971            kameo::error::SendError::ActorNotRunning(control_runner::FetchIdToken {
1972                audience: "sts.amazonaws.com".to_string(),
1973            });
1974        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1975    }
1976
1977    /// A `HandlerError` from the logout RPC carries the real `LogoutError` and must pass through
1978    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1979    /// passthrough observable.
1980    #[test]
1981    fn flatten_logout_send_err_handler_error_passes_through() {
1982        let inner = ts_control::LogoutError::Internal(ts_control::LogoutInternalErrorKind::Http);
1983        assert!(matches!(inner, ts_control::LogoutError::Internal(_)));
1984        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1985            kameo::error::SendError::HandlerError(inner.clone());
1986        assert_eq!(flatten_logout_send_err(e), inner);
1987    }
1988
1989    /// A non-handler send failure (actor stopped) is a delivery problem, not a logout result, and
1990    /// collapses to a transient `NetworkError` (logout is idempotent, so a retry is safe).
1991    #[test]
1992    fn flatten_logout_send_err_actor_stopped_is_network_error() {
1993        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1994            kameo::error::SendError::ActorStopped;
1995        assert_eq!(
1996            flatten_logout_send_err(e),
1997            ts_control::LogoutError::NetworkError
1998        );
1999    }
2000
2001    /// A `HandlerError` from the set-dns RPC carries the real `SetDnsError` and must pass through
2002    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
2003    /// passthrough observable.
2004    #[test]
2005    fn flatten_set_dns_send_err_handler_error_passes_through() {
2006        let inner = ts_control::SetDnsError::Internal(ts_control::SetDnsInternalErrorKind::Http);
2007        assert!(matches!(inner, ts_control::SetDnsError::Internal(_)));
2008        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
2009            kameo::error::SendError::HandlerError(inner.clone());
2010        assert_eq!(flatten_set_dns_send_err(e), inner);
2011    }
2012
2013    /// A non-handler send failure (actor stopped) is a delivery problem, not a publish result, and
2014    /// collapses to a transient `NetworkError`.
2015    #[test]
2016    fn flatten_set_dns_send_err_actor_stopped_is_network_error() {
2017        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
2018            kameo::error::SendError::ActorStopped;
2019        assert_eq!(
2020            flatten_set_dns_send_err(e),
2021            ts_control::SetDnsError::NetworkError
2022        );
2023    }
2024
2025    /// A `HandlerError` from a TKA mutation RPC carries the real `TkaSyncError` and must pass through
2026    /// verbatim (an `Unsupported` payload makes the passthrough observable, distinct from the
2027    /// `_ => NetworkError` fallback).
2028    #[test]
2029    fn flatten_tka_send_err_handler_error_passes_through() {
2030        let e: kameo::error::SendError<control_runner::TkaSign, ts_control::TkaSyncError> =
2031            kameo::error::SendError::HandlerError(ts_control::TkaSyncError::Unsupported);
2032        assert_eq!(
2033            flatten_tka_send_err(e),
2034            ts_control::TkaSyncError::Unsupported
2035        );
2036    }
2037
2038    /// A non-handler send failure (actor stopped) collapses to a transient `NetworkError`.
2039    #[test]
2040    fn flatten_tka_send_err_actor_stopped_is_network_error() {
2041        let e: kameo::error::SendError<control_runner::TkaSign, ts_control::TkaSyncError> =
2042            kameo::error::SendError::ActorStopped;
2043        assert_eq!(
2044            flatten_tka_send_err(e),
2045            ts_control::TkaSyncError::NetworkError
2046        );
2047    }
2048
2049    /// The same flatten works for the `TkaDisable` message type (the helper is generic over `M`).
2050    #[test]
2051    fn flatten_tka_send_err_works_for_disable() {
2052        let e: kameo::error::SendError<control_runner::TkaDisable, ts_control::TkaSyncError> =
2053            kameo::error::SendError::HandlerError(ts_control::TkaSyncError::Unsupported);
2054        assert_eq!(
2055            flatten_tka_send_err(e),
2056            ts_control::TkaSyncError::Unsupported
2057        );
2058    }
2059}