Skip to main content

ts_runtime/
lib.rs

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