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