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