ts_runtime/status.rs
1//! Netmap status aggregation, WhoIs lookups, and a netmap-change watcher.
2//!
3//! These surface the internal netmap state ([`ts_control::StateUpdate`], consumed by the
4//! [`PeerTracker`](crate::peer_tracker::PeerTracker)) to embedders, mirroring tsnet's
5//! `LocalClient::Status`, `WhoIs`, and `WatchIPNBus`.
6//!
7//! ## Capability / user / online surfacing (do not fabricate)
8//!
9//! tsnet's `Status`/`WhoIs` also carry per-node *online* state, the owning *user* (login/profile),
10//! and a *capability map*. Status of each in this fork:
11//! - **Capabilities** — surfaced: [`WhoIs::capabilities`] is populated from the domain
12//! [`Node`](ts_control::Node)'s `cap_map` (the control-pushed `CapMap`), which the domain model
13//! retains.
14//! - **User (login/profile)** — surfaced when the netmap provided it: [`WhoIs::user_profile`] is
15//! the owning user's whole profile (login name, display name, group membership), resolved by
16//! joining the node's owning user id against the netmap's `UserProfiles` table (accumulated by
17//! the [`PeerTracker`](crate::peer_tracker::PeerTracker) across delta updates). `None` when
18//! control sent no profile for that user. [`WhoIs::user`] flattens it to one display label and
19//! [`WhoIs::user_groups`] reaches the groups an embedder authorises on.
20//! - **Online state** — surfaced: [`StatusNode::online`] / [`StatusNode::last_seen`] reflect the
21//! domain [`Node`](ts_control::Node)'s retained `online`/`last_seen`, populated from the netmap
22//! node and its online deltas (`PeerChange`, `MapResponse.online_change`/`peer_seen_change`).
23//! `online` stays tri-state (`None` = unknown), never fabricated to `false`.
24
25use std::{
26 collections::BTreeMap,
27 net::{IpAddr, SocketAddr},
28};
29
30use ts_control::{Node, StableNodeId, StableTailnetId, UserId, UserProfile};
31
32/// A snapshot of the local netmap: this node plus every known peer.
33///
34/// Analogous to tsnet's `ipnstate.Status`. Built by [`Runtime::status`](crate::Runtime::status)
35/// from the self node held by the control runner and the peers held by the peer tracker.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Status {
38 /// This node, if a netmap has been received from control yet.
39 pub self_node: Option<StatusNode>,
40 /// Every peer currently known in the netmap.
41 pub peers: Vec<StatusNode>,
42 /// The stable id of the exit node traffic is **currently** egressing through, if any (Go's
43 /// `Status.ExitNodeStatus.ID`). This is the *resolved + fail-closed* answer from the route
44 /// updater — `None` when no exit node is configured, the configured selector matches no peer, or
45 /// the matched peer no longer advertises a default route — so it reflects what is actually
46 /// engaged, not merely what [`Config::exit_node`](ts_control::Config) requested. Find the peer's
47 /// details by matching this id against [`peers`](Status::peers).
48 pub active_exit_node: Option<StableNodeId>,
49 /// The tailnet's MagicDNS suffix (e.g. `"tail0123.ts.net"`) — Go `ipnstate.Status.MagicDNSSuffix`.
50 /// Derived (like Go's `NetworkMap.MagicDNSSuffix`) from the self node's FQDN minus its host label,
51 /// **not** from the DNS config and **not** from the tailnet `Domain` name. `None` before the first
52 /// netmap, or when the self FQDN has no tailnet component (a bare hostname).
53 pub magic_dns_suffix: Option<String>,
54 /// The tailnet this node is in (Go `ipnstate.Status.CurrentTailnet`). `Some` once a netmap
55 /// with a self node has arrived, as Go's is non-nil once there is a netmap; `None` before.
56 pub current_tailnet: Option<TailnetStatus>,
57 /// The text of every health warning currently raised (Go `ipnstate.Status.Health`). Empty when
58 /// healthy. Includes a disconnected control map poll and Go's `invalid-packet-filter`
59 /// warning for a filter granting an unlocked peer access.
60 pub health: Vec<String>,
61}
62
63impl Status {
64 /// Assemble a snapshot from the self node, the peer entries, the active exit node and the
65 /// health warnings. The self-node projections (the [`StatusNode`], the MagicDNS suffix and
66 /// [`current_tailnet`](Status::current_tailnet)) are all taken from `self_node`, as Go's
67 /// status builder takes them from the netmap's self node.
68 pub(crate) fn from_parts(
69 self_node: Option<&Node>,
70 peers: Vec<StatusNode>,
71 active_exit_node: Option<StableNodeId>,
72 health: Vec<String>,
73 ) -> Self {
74 Self {
75 self_node: self_node.map(StatusNode::from_node),
76 peers,
77 active_exit_node,
78 // The MagicDNS suffix is the self node's FQDN minus its host label — already split
79 // into `Node.tailnet` at decode time (Go derives it the same way in
80 // `NetworkMap.MagicDNSSuffix`).
81 magic_dns_suffix: self_node.and_then(|n| n.tailnet.clone()),
82 current_tailnet: TailnetStatus::from_self_node(self_node),
83 health,
84 }
85 }
86}
87
88/// The tailnet this node is a member of — Go `ipnstate.TailnetStatus`, the subset carried here.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct TailnetStatus {
91 /// The tailnet's stable, opaque identifier, as the Tailscale API names it (Go
92 /// `TailnetStatus.StableID`, from `Node.StableTailnetID` on the self node, capability version
93 /// 148). `None` when control sent none (Go's empty string), e.g. a control server older than
94 /// 148 or one that does not implement it.
95 pub stable_id: Option<StableTailnetId>,
96}
97
98impl TailnetStatus {
99 /// The tailnet status for a netmap whose self node is `self_node` (Go
100 /// `NetworkMap.StableTailnetID`): `None` without a self node, otherwise the self node's
101 /// tailnet id. Only the self node is read, as in Go.
102 pub fn from_self_node(self_node: Option<&Node>) -> Option<Self> {
103 self_node.map(|node| Self {
104 stable_id: node.stable_tailnet_id.clone(),
105 })
106 }
107}
108
109/// A single node entry in a [`Status`] snapshot.
110///
111/// Analogous to tsnet's `ipnstate.PeerStatus`.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct StatusNode {
114 /// The node's stable id (stable across re-registration).
115 pub stable_id: StableNodeId,
116 /// A display name for the node: its fqdn if a tailnet component is known, else its bare
117 /// hostname.
118 pub display_name: String,
119 /// The node's tailnet IPv4 address: the **first** IPv4 prefix control assigned it (the identity
120 /// projection the overlay, MagicDNS and exit-node selection reason about). See
121 /// [`tailscale_ips`](Self::tailscale_ips) for every address control assigned.
122 pub ipv4: IpAddr,
123 /// The node's tailnet IPv6 address: the **first** IPv6 prefix control assigned it. See
124 /// [`tailscale_ips`](Self::tailscale_ips) for every address control assigned.
125 pub ipv6: IpAddr,
126 /// Every tailnet address control assigned this node (Go `ipnstate.PeerStatus.TailscaleIPs`), in
127 /// wire order.
128 ///
129 /// Normally the same two addresses as [`ipv4`](Self::ipv4) / [`ipv6`](Self::ipv6), but
130 /// `tailcfg.Node.Addresses` is a variable-length list: an IPv6-off tailnet assigns only the v4
131 /// prefix, and nothing in the protocol stops control assigning more than one prefix of a family.
132 /// Built from the domain [`Node::addresses`](ts_control::Node::addresses), keeping each
133 /// single-IP prefix's address exactly as Go's status builder does
134 /// (`ipn/ipnlocal/local.go`). This — not the first-of-family pair — is what
135 /// [`is_router`](Self::is_router) asks "is this route one of my own addresses?" of.
136 pub tailscale_ips: Vec<IpAddr>,
137 /// Whether the node is online, if known (`ipnstate.PeerStatus.Online`). Tri-state: `Some(true)`
138 /// connected to control, `Some(false)` offline, `None` unknown (control sent no online status or
139 /// the local node lacks permission to know). Reflects control's liveness state, retained from the
140 /// netmap node + its online deltas — `None` is *unknown*, never fabricated to `false`.
141 pub online: Option<bool>,
142 /// When control last saw this node online (`ipnstate.PeerStatus.LastSeen`). Per Go, only
143 /// meaningful while the node is not currently online. `None` when unknown or never seen.
144 pub last_seen: Option<chrono::DateTime<chrono::Utc>>,
145 /// The routes this node accepts traffic for (its own `/32` and `/128`, plus any advertised
146 /// subnet routes and possibly the exit-node default route).
147 pub allowed_routes: Vec<ipnet::IpNet>,
148 /// Whether this node advertises a default route (`0.0.0.0/0` or `::/0`), making it eligible to
149 /// be selected as an exit node.
150 pub is_exit_node: bool,
151 /// The current trusted direct UDP endpoint for this peer, if a direct path is confirmed right now
152 /// (Go `ipnstate.PeerStatus.CurAddr`). `Some` ⇒ traffic to this peer flows directly to this
153 /// address; `None` ⇒ it relays via DERP (see [`relay`](Self::relay)). Mutually exclusive with a
154 /// `relay` for a routed peer, mirroring Go's empty-vs-set `CurAddr`/`Relay` strings. A live
155 /// snapshot — the direct path can expire/re-confirm between calls. Always `None` for the self node
156 /// and a whois lookup (no path to oneself; whois is an ownership query).
157 pub cur_addr: Option<SocketAddr>,
158 /// The DERP region code this peer relays through when there is **no** direct path (Go
159 /// `ipnstate.PeerStatus.Relay`, e.g. `"nyc"`). `Some` ⇔ [`cur_addr`](Self::cur_addr) is `None`
160 /// and the peer's home DERP region is known; `None` when a direct path is confirmed, or the
161 /// region code is unknown. Carries the region **code**, not its numeric id.
162 pub relay: Option<String>,
163 /// The node's advertised SSH host public keys in known_hosts format (Go
164 /// `ipnstate.PeerStatus.SSH_HostKeys`), used by `tailscale ssh` to pin the peer's host key.
165 /// Mirrors the domain [`Node::ssh_host_keys`](ts_control::Node::ssh_host_keys); empty when
166 /// control advertised none (never fabricated).
167 pub ssh_host_keys: Vec<String>,
168 /// Whether this node's key has expired (Go `ipnstate.PeerStatus.Expired`).
169 ///
170 /// Set either by control on the wire or by this node's own expiry pass
171 /// ([`ts_control::ExpiryManager::flag_expired_peer`]) once the node's key expiry has passed —
172 /// judged against control's clock, not this host's. An expired peer is deliberately still
173 /// listed: it keeps its identity so a watcher can tell "expired" apart from "gone", but it has
174 /// no endpoints, no home DERP, and a broken node key, so nothing routes to it and a peerAPI
175 /// dial to it is refused ([`ts_control::PEER_KEY_EXPIRED`]).
176 pub expired: bool,
177}
178
179/// Whether `prefix` covers exactly one address (a `/32` or a `/128`) — Go `netip.Prefix.IsSingleIP`.
180fn is_single_ip(prefix: &ipnet::IpNet) -> bool {
181 let host_prefix = match prefix {
182 ipnet::IpNet::V4(_) => 32,
183 ipnet::IpNet::V6(_) => 128,
184 };
185 prefix.prefix_len() == host_prefix
186}
187
188impl StatusNode {
189 /// Report whether this node is a **router**: it routes addresses besides its own. An exit
190 /// node, a subnet router and an app connector are all routers.
191 ///
192 /// Mirrors Go's `ipnstate.PeerStatus.IsRouter` (`ipn/ipnstate/ipnstate.go`, added upstream in
193 /// `8d830599b` alongside `tailcfg.Node.IsRouter`, which
194 /// [`Node::is_router`](ts_control::Node::is_router) mirrors): a route in
195 /// [`allowed_routes`](Self::allowed_routes) that is not a single host IP, or that is a host IP
196 /// other than one of this node's own [`tailscale_ips`](Self::tailscale_ips), makes the node a
197 /// router. Upstream spells both as *methods*, not wire fields — control sends nothing new for
198 /// this, so it is a pure projection of the netmap a peer already gave us.
199 ///
200 /// The comparison is against the **whole** [`tailscale_ips`](Self::tailscale_ips) list, as Go's
201 /// `slices.Contains(ps.TailscaleIPs, r.Addr())` is, and not against the first-of-family
202 /// [`ipv4`](Self::ipv4)/[`ipv6`](Self::ipv6) pair. A node control handed two prefixes of one
203 /// family would otherwise have the second read as a routed address and be misreported as a
204 /// router — the same narrowing [`Node::is_router`](ts_control::Node::is_router) had.
205 ///
206 /// Strictly wider than [`is_exit_node`](Self::is_exit_node), which asks only about the default
207 /// route: every exit node is a router, but a subnet router advertising no `/0` is not an exit
208 /// node.
209 pub fn is_router(&self) -> bool {
210 self.allowed_routes.iter().any(|route| {
211 // Not a single host IP, or a host IP that is not one of this node's own addresses.
212 !is_single_ip(route) || !self.tailscale_ips.contains(&route.addr())
213 })
214 }
215
216 /// Build a [`StatusNode`] from a domain [`Node`].
217 pub fn from_node(node: &Node) -> Self {
218 let is_exit_node = node
219 .accepted_routes
220 .iter()
221 .any(|route| route.prefix_len() == 0);
222
223 Self {
224 stable_id: node.stable_id.clone(),
225 display_name: node
226 .fqdn_opt(false)
227 .unwrap_or_else(|| node.hostname.clone()),
228 ipv4: node.tailnet_address.ipv4.addr().into(),
229 ipv6: node.tailnet_address.ipv6.addr().into(),
230 // Go's status builder fills `PeerStatus.TailscaleIPs` from the node's whole
231 // `Node.Addresses` list, keeping the address of each single-IP prefix
232 // (`ipn/ipnlocal/local.go`). Take the same list, not the first-of-family pair above:
233 // `is_router` compares against it.
234 tailscale_ips: node
235 .addresses
236 .iter()
237 .filter(|prefix| is_single_ip(prefix))
238 .map(|prefix| prefix.addr())
239 .collect(),
240 online: node.online,
241 last_seen: node.last_seen,
242 allowed_routes: node.accepted_routes.clone(),
243 is_exit_node,
244 // A bare `Node` carries no live path state, so connectivity is unknown here. The peer
245 // tracker overwrites these in `status_peers` by joining against the direct manager; the
246 // self node and whois lookups (which also use `from_node`) correctly keep `None`.
247 cur_addr: None,
248 relay: None,
249 ssh_host_keys: node.ssh_host_keys.clone(),
250 expired: node.expired,
251 }
252 }
253}
254
255/// The result of a [`Runtime::whois`](crate::Runtime::whois) lookup: the node that owns a tailnet
256/// source address, plus its user and capabilities.
257///
258/// Analogous to tsnet's `apitype.WhoIsResponse`.
259#[derive(Debug, Clone, PartialEq, Eq)]
260pub struct WhoIs {
261 /// The node that owns the queried source IP.
262 pub node: Node,
263 /// The profile of the user that owns the node — Go `apitype.WhoIsResponse.UserProfile`.
264 ///
265 /// Resolved by joining the node's owning user id against the netmap's `UserProfiles` table
266 /// (accumulated by the [`PeerTracker`](crate::peer_tracker::PeerTracker) across delta updates).
267 /// `None` when control sent no profile for that user — a tagged node with no human owner, or a
268 /// profile not yet delivered. Carries the whole profile rather than one flattened label so an
269 /// embedder can authorise on [`UserProfile::groups`], which is the one owner attribute a node
270 /// cannot re-derive locally; [`user`](Self::user) is still there for the display case.
271 pub user_profile: Option<UserProfile>,
272 /// The node's **node-level** capability map (Go `Node.CapMap` — node attributes like
273 /// `can-funnel`), as `(capability, args)` pairs, populated from the domain
274 /// [`Node`]'s `cap_map`, sorted by capability name. Distinct from
275 /// [`cap_map`](Self::cap_map), which is the flow-scoped *peer-capability* grants.
276 pub capabilities: Vec<(String, Vec<String>)>,
277 /// The **flow-scoped** peer-capability grants for the queried `src -> dst` flow — Go
278 /// `apitype.WhoIsResponse.CapMap` (`tailcfg.PeerCapMap`). The grants control's packet-filter
279 /// application rules authorize for traffic from this node to the queried address, keyed by
280 /// capability name with raw-JSON values. Empty when no grant matches the flow (or no scoped
281 /// query was made). Distinct from the node-level [`capabilities`](Self::capabilities).
282 pub cap_map: BTreeMap<String, Vec<String>>,
283}
284
285impl WhoIs {
286 /// Build a [`WhoIs`] from the owning node and its resolved owner profile (if the netmap's
287 /// `UserProfiles` table mapped the node's owning user id to one; `None` when control sent no
288 /// profile — e.g. a tagged node with no human owner).
289 ///
290 /// `capabilities` is the node-level cap map; `cap_map` (the flow-scoped grants) is filled
291 /// separately by [`Runtime::whois`](crate::Runtime::whois) and defaults to empty here.
292 pub(crate) fn from_node_with_profile(node: Node, user_profile: Option<UserProfile>) -> Self {
293 let capabilities = node
294 .cap_map
295 .iter()
296 .map(|(cap, args)| (cap.clone(), args.clone()))
297 .collect();
298 Self {
299 node,
300 user_profile,
301 capabilities,
302 cap_map: BTreeMap::new(),
303 }
304 }
305
306 /// The best human-facing label for the owning user: the profile's login name when present,
307 /// else its display name, else `None` (no profile, or a profile with neither).
308 ///
309 /// This is the flattened view [`user_profile`](Self::user_profile) replaced; use the profile
310 /// itself for anything but display.
311 pub fn user(&self) -> Option<String> {
312 self.user_profile.as_ref().and_then(UserProfile::best_label)
313 }
314
315 /// The groups control reported for the owning user — Go
316 /// `apitype.WhoIsResponse.UserProfile.Groups`. SCIM groups (e.g. `engineering@example.com`) or
317 /// tailnet-policy group names (e.g. `group:eng`).
318 ///
319 /// The authorisation shortcut: `whois.user_groups().iter().any(|g| g == "group:eng")`.
320 ///
321 /// **Empty** both when there is no profile at all and when control reported no groups — which
322 /// includes every control server that does not send the field. An empty list is therefore
323 /// "control told this node nothing", not a proof of non-membership: fail closed on it (deny),
324 /// never treat it as a negative assertion.
325 pub fn user_groups(&self) -> &[String] {
326 self.user_profile
327 .as_ref()
328 .map_or(&[], |profile| profile.groups.as_slice())
329 }
330}
331
332/// Resolve which node owns a tailnet source address, used by WhoIs.
333pub(crate) fn whois_addr(addr: SocketAddr) -> IpAddr {
334 addr.ip()
335}
336
337/// A measured-latency entry for one DERP region in a [`NetcheckReport`].
338#[derive(Debug, Clone, PartialEq, Eq)]
339pub struct RegionLatency {
340 /// The DERP region id (Go `tailcfg.DERPRegionID`).
341 pub region_id: u32,
342 /// The measured round-trip latency to the region's closest DERP node.
343 pub latency: std::time::Duration,
344}
345
346/// A snapshot of this node's latest network conditions report — the Rust analog of Go's
347/// `netcheck.Report` as `tailscale netcheck` surfaces it.
348///
349/// ## Surfaced subset (do not fabricate)
350/// Go's `netcheck.Report` also carries UDP/IPv4/IPv6 reachability, port-mapping support
351/// (UPnP/PMP/PCP), `MappingVariesByDestIP`, global-address discovery, etc. This fork's net-report
352/// path measures only **DERP-region latency** (the data that drives home-region selection), so the
353/// report carries exactly that — the preferred (lowest-latency) region and the per-region latency
354/// map — rather than inventing fields we never probe. Empty before the first measurement.
355#[derive(Debug, Clone, PartialEq, Eq, Default, kameo::Reply)]
356pub struct NetcheckReport {
357 /// The id of the preferred DERP region — the lowest-latency region this node measured, the one it
358 /// homes to (Go `Report.PreferredDERP`). `None` before the first measurement / when no region
359 /// was reachable.
360 pub preferred_derp: Option<u32>,
361 /// Per-region measured latencies, sorted by latency ascending (Go `Report.RegionLatency`, here as
362 /// an ordered list). The first entry, when present, is the [`preferred_derp`](Self::preferred_derp)
363 /// region.
364 pub region_latencies: Vec<RegionLatency>,
365}
366
367impl NetcheckReport {
368 /// Build a report from the latest DERP-region measurements (the `RegionResult` set the latency
369 /// measurer produces). `results` is expected sorted by latency ascending (the measurer's
370 /// `RegionResult` `Ord` sorts on latency first), so the first entry is the preferred region; we
371 /// do not re-sort beyond trusting that contract for `preferred_derp`, but the list is emitted in
372 /// the order given. An empty `results` yields the default (no preferred region, empty list).
373 pub(crate) fn from_region_results(results: &[ts_netcheck::RegionResult]) -> NetcheckReport {
374 let region_latencies: Vec<RegionLatency> = results
375 .iter()
376 .map(|r| RegionLatency {
377 // `ts_derp::RegionId` is a `NonZeroU32` newtype (its `.0` is the public inner).
378 region_id: r.id.0.get(),
379 latency: r.latency,
380 })
381 .collect();
382 NetcheckReport {
383 preferred_derp: region_latencies.first().map(|r| r.region_id),
384 region_latencies,
385 }
386 }
387}
388
389/// A tailnet peer this node can send a Taildrop file *to*, plus the peerAPI base URL to reach it.
390///
391/// Analogous to tsnet's `apitype.FileTarget`. The set is produced by
392/// [`Runtime::file_targets`](crate::Runtime::file_targets) (exposed as `Device::file_targets`).
393#[derive(Debug, Clone, PartialEq, Eq)]
394pub struct FileTarget {
395 /// The target peer's node record — pass straight to the Taildrop send path
396 /// (`Device::send_file`), which re-derives the same peerAPI address.
397 pub node: Node,
398 /// The `http://ip:port` base URL of the peer's peerAPI, with no trailing path — the exact shape
399 /// of Go's `apitype.FileTarget.PeerAPIURL`. Derived from
400 /// [`Node::peerapi_addr`](ts_control::Node::peerapi_addr).
401 pub peerapi_url: String,
402}
403
404/// Compute the sorted Taildrop send-target list from the peer set, given the local node's owning
405/// user id. The pure core of [`Runtime::file_targets`](crate::Runtime::file_targets) — separated out
406/// so the eligibility + ordering rules are unit-testable without spinning up the actor graph (the
407/// node-level file-sharing gate is applied by the caller before this runs).
408///
409/// A peer is a target when it advertises a reachable peerAPI (Go `PeerAPIBase(p) != ""`) **and** is
410/// either owned by `self_user_id` **or** carries the file-sharing-target capability — Go's two-way
411/// OR. Sorted by MagicDNS name (Go sorts by `Node.Name`), falling back to the bare hostname.
412pub(crate) fn build_file_targets(peers: Vec<Node>, self_user_id: UserId) -> Vec<FileTarget> {
413 let mut targets: Vec<FileTarget> = peers
414 .into_iter()
415 .filter_map(|peer| {
416 // Must advertise a reachable peerAPI (Go `PeerAPIBase(p) != ""`).
417 let addr = peer.peerapi_addr()?;
418 // Same owner OR explicitly an ACL file-sharing target (Go's two-way OR).
419 let eligible = peer.user_id == self_user_id || peer.is_file_sharing_target();
420 if !eligible {
421 return None;
422 }
423 Some(FileTarget {
424 peerapi_url: format!("http://{addr}"),
425 node: peer,
426 })
427 })
428 .collect();
429 // Sort by MagicDNS name (Go sorts by `Node.Name`), bare hostname as the fallback key.
430 targets.sort_by(|a, b| {
431 let name = |t: &FileTarget| {
432 t.node
433 .fqdn_opt(false)
434 .unwrap_or_else(|| t.node.hostname.clone())
435 };
436 name(a).cmp(&name(b))
437 });
438 targets
439}
440
441/// Report control liveness alongside the independently retained packet-filter warning.
442pub(crate) fn health_warnings(invalid_packet_filter: bool, control_connected: bool) -> Vec<String> {
443 let mut warnings = crate::packetfilter::health_warnings(invalid_packet_filter);
444 if !control_connected {
445 warnings.push("Disconnected from coordination server; retrying map poll".to_string());
446 }
447 warnings
448}
449
450#[cfg(test)]
451mod tests {
452 use ts_control::{Node, StableNodeId, TailnetAddress};
453
454 use super::*;
455
456 fn node(stable: &str, hostname: &str, tailnet: Option<&str>, ipv4: &str) -> Node {
457 Node {
458 id: 1,
459 stable_id: StableNodeId(stable.to_string()),
460 hostname: hostname.to_string(),
461 user_id: 0,
462 tailnet: tailnet.map(str::to_string),
463 tags: vec![],
464 addresses: vec![
465 format!("{ipv4}/32").parse().unwrap(),
466 "fd7a::1/128".parse().unwrap(),
467 ],
468 tailnet_address: TailnetAddress {
469 ipv4: format!("{ipv4}/32").parse().unwrap(),
470 ipv6: "fd7a::1/128".parse().unwrap(),
471 },
472 node_key: [0u8; 32].into(),
473 node_key_expiry: None,
474 expired: false,
475 online: None,
476 last_seen: None,
477 key_signature: vec![],
478 machine_key: None,
479 disco_key: None,
480 accepted_routes: vec![],
481 underlay_addresses: vec![],
482 derp_region: None,
483 cap: Default::default(),
484 cap_map: Default::default(),
485 peerapi_port: None,
486 peerapi_dns_proxy: false,
487 is_wireguard_only: false,
488 exit_node_dns_resolvers: vec![],
489 stable_tailnet_id: None,
490 peer_relay: false,
491 ssh_host_keys: vec![],
492 service_vips: Default::default(),
493 unsigned_peer_api_only: false,
494 }
495 }
496
497 fn self_node_with(stable_tailnet_id: Option<&str>) -> Node {
498 Node {
499 stable_tailnet_id: stable_tailnet_id.map(|id| StableTailnetId(id.to_string())),
500 ..node("nself", "self", Some("example.com"), "192.0.2.1")
501 }
502 }
503
504 /// Go `types/netmap/netmap_test.go:TestStableTailnetID`, case for case, against
505 /// [`TailnetStatus::from_self_node`] (Go `NetworkMap.StableTailnetID`). Go's `nil_map` and
506 /// `invalid_self_node` are both "no self node" here: the runtime holds the self node as an
507 /// `Option` and has no netmap without one.
508 #[test]
509 fn stable_tailnet_id_matches_go() {
510 let stable_id = |self_node: Option<&Node>| {
511 TailnetStatus::from_self_node(self_node).and_then(|tailnet| tailnet.stable_id)
512 };
513 // nil_map / invalid_self_node
514 assert_eq!(TailnetStatus::from_self_node(None), None);
515 assert_eq!(stable_id(None), None);
516 // missing_id
517 assert_eq!(stable_id(Some(&self_node_with(None))), None);
518 // populated
519 assert_eq!(
520 stable_id(Some(&self_node_with(Some("tailnet-abcd")))),
521 Some(StableTailnetId("tailnet-abcd".to_string()))
522 );
523 }
524
525 /// Go `ipn/ipnlocal/local_test.go:TestStatusStableTailnetID`, the `populated` and `missing`
526 /// cases, through [`Status::from_parts`], which `Runtime::status` returns. `current_tailnet` is
527 /// present once there is a self node (Go: non-nil `CurrentTailnet`), and carries the self
528 /// node's id or none. Go's `without_peers` subtests call `StatusWithoutPeers`
529 /// (`StatusBuilder.WantPeers = false`), which has no Rust counterpart, so that call path is
530 /// not ported; this test instead checks the builder both with peers and with an empty peer
531 /// set. The peers are decoded from wire nodes that each carry a *different* `StableTailnetID`,
532 /// which must not show up.
533 #[test]
534 fn status_stable_tailnet_id_matches_go() {
535 let peers: Vec<StatusNode> = ["tailnet-peer-1", "tailnet-peer-2"]
536 .iter()
537 .enumerate()
538 .map(|(i, id)| {
539 let json = format!(
540 r#"{{"ID": {}, "StableID": "npeer{i}", "Name": "peer{i}.example.com.",
541 "Addresses": ["192.0.2.{}/32"], "StableTailnetID": "{id}"}}"#,
542 i + 2,
543 i + 2,
544 );
545 let wire: ts_control_serde::Node = serde_json::from_str(&json).unwrap();
546 StatusNode::from_node(&Node::from(&wire))
547 })
548 .collect();
549
550 for (name, stable_id) in [("populated", Some("tailnet-abcd")), ("missing", None)] {
551 let self_node = self_node_with(stable_id);
552 for (with, peers) in [("with_peers", peers.clone()), ("no_peers", vec![])] {
553 let status = Status::from_parts(Some(&self_node), peers, None, vec![]);
554 let current = status
555 .current_tailnet
556 .unwrap_or_else(|| panic!("{name}/{with}: CurrentTailnet is nil"));
557 assert_eq!(
558 current.stable_id,
559 stable_id.map(|id| StableTailnetId(id.to_string())),
560 "{name}/{with}"
561 );
562 }
563 }
564
565 // Before the first netmap there is no current tailnet (Go: nil `CurrentTailnet`).
566 assert_eq!(
567 Status::from_parts(None, peers, None, vec![]).current_tailnet,
568 None
569 );
570 }
571
572 /// Go `ipn/ipnlocal/logauth_test.go:TestLogUploadAuthNotPublished`, for what this runtime
573 /// publishes. The netmap is decoded from Go's own node (`log-upload-auth` and `debug` in both
574 /// `Capabilities` and `CapMap`) by the live map poll's frame decoder, first as a full netmap and
575 /// then as a self-only frame carrying a refreshed token (Go's `SelfChange` netmap):
576 ///
577 /// - the installed self node (what `retain_self_node` keeps and node-attribute gates read) lacks
578 /// the cap and keeps `debug` (Go `CapMap`/`AllCaps`/`Capabilities`);
579 /// - the [`Status`] and its self [`StatusNode`] (what `Runtime::status` and the netmap watch
580 /// carry) do not contain the token;
581 /// - a [`WhoIs`] for the self node (Go `WhoIs(self)`) lists `debug` but not the cap, and does
582 /// not contain the token. `Runtime::whois` resolves peers only, so this is the builder it
583 /// would use, not the actor call.
584 #[test]
585 fn log_upload_auth_not_published_matches_go() {
586 const TOK: &str = "super-secret-log-token";
587 let frame = |token: &str| {
588 format!(
589 r#"{{"Node": {{"ID": 7, "StableID": "nself", "Name": "self.example.com.",
590 "User": 1, "Addresses": ["192.0.2.7/32"],
591 "Capabilities": ["log-upload-auth", "debug"],
592 "CapMap": {{"log-upload-auth": ["{token}"], "debug": ["keep-me"]}}}},
593 "UserProfiles": [{{"ID": 1, "LoginName": "ada@example.com"}}]}}"#
594 )
595 };
596 let mut decoder = ts_control::NetmapFrameDecoder::default();
597
598 for (name, token) in [("netmap", TOK), ("self change", "refreshed-log-token")] {
599 let update = decoder
600 .state_update(frame(token).as_bytes())
601 .expect("a decodable frame");
602 let self_node = update.node.as_ref().expect("self node");
603
604 assert!(
605 !self_node.has_node_attr(ts_control::NODE_ATTR_LOG_UPLOAD_AUTH),
606 "{name}: installed CapMap still contains log-upload-auth"
607 );
608 assert!(
609 self_node.has_node_attr("debug"),
610 "{name}: installed CapMap dropped debug"
611 );
612
613 let status = Status::from_parts(Some(self_node), vec![], None, vec![]);
614 assert!(
615 status.self_node.is_some(),
616 "{name}: status self node is nil"
617 );
618
619 let profile = update.user_profiles.first().cloned();
620 let whois = WhoIs::from_node_with_profile(self_node.clone(), profile);
621 let caps: Vec<&str> = whois
622 .capabilities
623 .iter()
624 .map(|(cap, _)| cap.as_str())
625 .collect();
626 assert_eq!(caps, ["debug"], "{name}: WhoIs capabilities");
627
628 for (what, blob) in [
629 ("update", format!("{update:?}")),
630 ("status", format!("{status:?}")),
631 ("WhoIs", format!("{whois:?}")),
632 ] {
633 assert!(
634 !blob.contains(token),
635 "{name}: {what} contains the log upload token"
636 );
637 }
638 }
639 }
640
641 /// `from_parts` keeps the projections `Runtime::status` built inline before it: the self
642 /// `StatusNode` and the MagicDNS suffix come from the self node.
643 #[test]
644 fn status_from_parts_projects_the_self_node() {
645 let self_node = self_node_with(Some("tailnet-abcd"));
646 let status = Status::from_parts(
647 Some(&self_node),
648 vec![],
649 Some(StableNodeId("nexit".to_string())),
650 vec!["warning".to_string()],
651 );
652 assert_eq!(status.self_node, Some(StatusNode::from_node(&self_node)));
653 assert_eq!(status.magic_dns_suffix.as_deref(), Some("example.com"));
654 assert_eq!(
655 status.active_exit_node,
656 Some(StableNodeId("nexit".to_string()))
657 );
658 assert_eq!(status.health, vec!["warning".to_string()]);
659
660 let empty = Status::from_parts(None, vec![], None, vec![]);
661 assert_eq!(empty.self_node, None);
662 assert_eq!(empty.magic_dns_suffix, None);
663 }
664
665 #[test]
666 fn status_node_display_name_prefers_fqdn() {
667 let with_tailnet = node("n1", "host", Some("ts.net"), "100.64.0.1");
668 assert_eq!(
669 StatusNode::from_node(&with_tailnet).display_name,
670 "host.ts.net"
671 );
672
673 let bare = node("n2", "solo", None, "100.64.0.2");
674 assert_eq!(StatusNode::from_node(&bare).display_name, "solo");
675 }
676
677 #[test]
678 fn status_node_addresses_and_online_surfaced() {
679 let n = node("n1", "host", Some("ts.net"), "100.64.0.7");
680 let s = StatusNode::from_node(&n);
681
682 assert_eq!(s.ipv4, "100.64.0.7".parse::<IpAddr>().unwrap());
683 assert_eq!(s.ipv6, "fd7a::1".parse::<IpAddr>().unwrap());
684 // A node with no online data surfaces `None` (unknown) — never a fabricated `false`.
685 assert_eq!(s.online, None);
686 assert_eq!(s.last_seen, None);
687
688 // A node whose domain online state is known surfaces it through StatusNode (no longer
689 // hardwired to None).
690 let mut online = node("n2", "up", Some("ts.net"), "100.64.0.8");
691 online.online = Some(true);
692 assert_eq!(StatusNode::from_node(&online).online, Some(true));
693
694 let mut offline = node("n3", "down", Some("ts.net"), "100.64.0.9");
695 offline.online = Some(false);
696 assert_eq!(StatusNode::from_node(&offline).online, Some(false));
697 }
698
699 #[test]
700 fn status_node_carries_ssh_host_keys() {
701 // Absent on the domain node → empty on StatusNode (never fabricated).
702 let bare = node("n1", "host", Some("ts.net"), "100.64.0.1");
703 assert!(StatusNode::from_node(&bare).ssh_host_keys.is_empty());
704
705 // Present → mirrored verbatim (the keys `tailscale ssh` pins).
706 let mut with_keys = node("n2", "host", Some("ts.net"), "100.64.0.2");
707 with_keys.ssh_host_keys = vec!["ssh-ed25519 AAAAC3Nz host".to_string()];
708 assert_eq!(
709 StatusNode::from_node(&with_keys).ssh_host_keys,
710 vec!["ssh-ed25519 AAAAC3Nz host".to_string()]
711 );
712 }
713
714 #[test]
715 fn status_node_detects_exit_node() {
716 let mut not_exit = node("n1", "a", Some("ts.net"), "100.64.0.1");
717 not_exit.accepted_routes = vec!["100.64.0.1/32".parse().unwrap()];
718 assert!(!StatusNode::from_node(¬_exit).is_exit_node);
719
720 let mut exit = node("n2", "b", Some("ts.net"), "100.64.0.2");
721 exit.accepted_routes = vec![
722 "100.64.0.2/32".parse().unwrap(),
723 "0.0.0.0/0".parse().unwrap(),
724 ];
725 assert!(StatusNode::from_node(&exit).is_exit_node);
726
727 let mut exit6 = node("n3", "c", Some("ts.net"), "100.64.0.3");
728 exit6.accepted_routes = vec!["::/0".parse().unwrap()];
729 assert!(StatusNode::from_node(&exit6).is_exit_node);
730 }
731
732 /// Ported from upstream's `TestPeerStatusIsRouter` (`ipn/ipnstate/ipnstate_test.go`,
733 /// `8d830599b`), and cross-checked against [`ts_control::Node::is_router`] the way upstream's
734 /// `TestNodeIsRouter` cross-checks the two definitions: a peer is a router exactly when its
735 /// allowed routes reach past its own tailnet addresses. Both the present and the absent case
736 /// are pinned — a plain peer must keep answering `false`.
737 #[test]
738 fn status_node_is_router_reports_routes_beyond_own_addresses() {
739 let self4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
740 let self6: ipnet::IpNet = "fd7a:115c:a1e0::1/128".parse().unwrap();
741
742 let cases: &[(&str, Vec<ipnet::IpNet>, bool)] = &[
743 ("empty", vec![], false),
744 ("plain-ipv4", vec![self4], false),
745 ("plain-ipv6", vec![self6], false),
746 ("plain-ipv4-ipv6", vec![self4, self6], false),
747 (
748 "exit-node-ipv4",
749 vec![self4, "0.0.0.0/0".parse().unwrap()],
750 true,
751 ),
752 ("exit-node-ipv6", vec![self6, "::/0".parse().unwrap()], true),
753 (
754 "subnet-router-ipv4",
755 vec![self4, "192.0.2.0/24".parse().unwrap()],
756 true,
757 ),
758 (
759 "subnet-router-ipv6",
760 vec![self6, "2001:db8::/32".parse().unwrap()],
761 true,
762 ),
763 (
764 "subnet-router-ipv4-ipv6",
765 vec![
766 self4,
767 self6,
768 "192.0.2.0/24".parse().unwrap(),
769 "2001:db8::/32".parse().unwrap(),
770 ],
771 true,
772 ),
773 // No Tailscale-range exception, matching Go: another peer's /32 is a routed address.
774 (
775 "other-tailnet-host",
776 vec![self4, "100.64.5.5/32".parse().unwrap()],
777 true,
778 ),
779 ];
780
781 for (name, allowed, want) in cases {
782 let mut n = node("n1", "host", Some("ts.net"), "100.64.0.1");
783 n.addresses = vec![self4, self6];
784 n.tailnet_address.ipv6 = "fd7a:115c:a1e0::1/128".parse().unwrap();
785 n.accepted_routes = allowed.clone();
786
787 let s = StatusNode::from_node(&n);
788 assert_eq!(s.is_router(), *want, "{name}");
789 // The status projection and the domain node must agree, as upstream asserts of
790 // `ipnstate.PeerStatus.IsRouter` against `tailcfg.Node.IsRouter`.
791 assert_eq!(
792 s.is_router(),
793 n.is_router(),
794 "{name}: domain/status disagree"
795 );
796 }
797 }
798
799 /// Go's `PeerStatus.IsRouter` tests each allowed prefix against the node's **whole**
800 /// `TailscaleIPs` slice, so every address control assigned is "its own". `Node.Addresses` is a
801 /// variable-length list, not a v4/v6 pair, so a tailnet may hand a node more than one prefix of
802 /// a family; such a node must not be reported as a router on account of the extra one — which
803 /// comparing only against the first-of-family `ipv4`/`ipv6` pair does. The sibling
804 /// `ts_control::Node::is_router` case is pinned in `ts_control`; this pins the status
805 /// projection, which carries the same list one level up.
806 #[test]
807 fn status_node_is_router_tests_every_assigned_address_not_only_the_first_of_each_family() {
808 let first4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
809 let second4: ipnet::IpNet = "100.64.0.9/32".parse().unwrap();
810 let first6: ipnet::IpNet = "fd7a:115c:a1e0::1/128".parse().unwrap();
811 let second6: ipnet::IpNet = "fd7a:115c:a1e0::9/128".parse().unwrap();
812
813 let mut n = node("n1", "host", Some("ts.net"), "100.64.0.1");
814 n.addresses = vec![first4, second4, first6, second6];
815 n.tailnet_address.ipv6 = "fd7a:115c:a1e0::1/128".parse().unwrap();
816 // With `AllowedIPs` absent, control's routes for a node are exactly its addresses.
817 n.accepted_routes = n.addresses.clone();
818
819 let s = StatusNode::from_node(&n);
820
821 // The identity projection is still the first prefix of each family...
822 assert_eq!(s.ipv4, first4.addr());
823 assert_eq!(s.ipv6, first6.addr());
824 // ...and every assigned address is carried, as Go's `TailscaleIPs` is.
825 assert_eq!(
826 s.tailscale_ips,
827 vec![first4.addr(), second4.addr(), first6.addr(), second6.addr()]
828 );
829 assert!(
830 !s.is_router(),
831 "a node whose routes are exactly its own assigned addresses is not a router"
832 );
833 assert_eq!(s.is_router(), n.is_router(), "domain/status disagree");
834
835 // Either second-of-family address on its own is still not a routed address.
836 for extra in [second4, second6] {
837 let mut one = n.clone();
838 one.accepted_routes = vec![extra];
839 let s = StatusNode::from_node(&one);
840 assert!(
841 !s.is_router(),
842 "{extra} is one of this node's own addresses"
843 );
844 assert_eq!(s.is_router(), one.is_router(), "domain/status disagree");
845 }
846
847 // The predicate still fires for a route that does reach past every assigned address.
848 let mut router = n.clone();
849 router.accepted_routes.push("192.0.2.0/24".parse().unwrap());
850 assert!(
851 StatusNode::from_node(&router).is_router(),
852 "a real subnet route makes it a router"
853 );
854 }
855
856 /// An IPv6-off tailnet assigns a node only its IPv4 prefix, and the domain model fills the
857 /// missing family with an unspecified placeholder. `TailscaleIPs` must carry what control
858 /// actually assigned — not the placeholder — and the node must still not read as a router.
859 #[test]
860 fn status_node_tailscale_ips_omits_the_unassigned_family_placeholder() {
861 let only4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
862
863 let mut n = node("n1", "host", Some("ts.net"), "100.64.0.1");
864 n.addresses = vec![only4];
865 n.tailnet_address.ipv6 = "::/128".parse().unwrap();
866 n.accepted_routes = vec![only4];
867
868 let s = StatusNode::from_node(&n);
869 assert_eq!(s.tailscale_ips, vec![only4.addr()]);
870 assert!(!s.is_router(), "its own /32 is not a routed address");
871 assert!(
872 s.ipv6.is_unspecified(),
873 "the unassigned family stays a placeholder on the identity projection"
874 );
875 }
876
877 /// `from_node` carries NO live connectivity: a bare domain `Node` has no path state, so
878 /// `cur_addr`/`relay` default to `None`. `Runtime::status` overwrites `cur_addr` by joining the
879 /// direct manager's `best_addrs`; the self node and whois (which also use `from_node`) keep
880 /// `None`. This pins the default so the enrichment seam stays the single source of connectivity.
881 #[test]
882 fn status_node_from_node_has_no_connectivity_by_default() {
883 let n = node("n1", "host", Some("ts.net"), "100.64.0.7");
884 let s = StatusNode::from_node(&n);
885 assert_eq!(s.cur_addr, None, "a bare Node has no direct endpoint");
886 assert_eq!(s.relay, None, "a bare Node has no resolved relay");
887 }
888
889 #[test]
890 fn whois_caps_empty_when_node_has_none() {
891 // A node with no cap_map surfaces empty capabilities (not fabricated), and no user unless a
892 // profile was joined in.
893 let n = node("n1", "host", Some("ts.net"), "100.64.0.9");
894 let whois = WhoIs::from_node_with_profile(n.clone(), None);
895
896 assert_eq!(whois.node, n);
897 assert_eq!(whois.user_profile, None);
898 assert_eq!(whois.user(), None);
899 assert!(whois.user_groups().is_empty());
900 assert!(whois.capabilities.is_empty());
901 }
902
903 #[test]
904 fn whois_populates_capabilities_from_cap_map() {
905 // WhoIs surfaces the domain Node's cap_map verbatim, sorted by capability name (BTreeMap).
906 let mut n = node("n1", "host", Some("ts.net"), "100.64.0.9");
907 n.cap_map
908 .insert("https://tailscale.com/cap/is-admin".to_string(), vec![]);
909 n.cap_map.insert(
910 "cap/ssh".to_string(),
911 vec!["root".to_string(), "ubuntu".to_string()],
912 );
913 let whois = WhoIs::from_node_with_profile(n, None);
914
915 // BTreeMap iteration is sorted: "cap/ssh" < "https://…".
916 assert_eq!(
917 whois.capabilities,
918 vec![
919 (
920 "cap/ssh".to_string(),
921 vec!["root".to_string(), "ubuntu".to_string()]
922 ),
923 ("https://tailscale.com/cap/is-admin".to_string(), vec![]),
924 ]
925 );
926 }
927
928 #[test]
929 fn whois_from_node_with_profile_sets_profile_and_caps() {
930 let mut n = node("n1", "host", Some("ts.net"), "100.64.0.9");
931 n.cap_map.insert("cap/x".to_string(), vec!["y".to_string()]);
932 let profile = UserProfile {
933 id: 42,
934 login_name: "alice@example.com".to_string(),
935 display_name: Some("Alice Smith".to_string()),
936 groups: vec!["group:eng".to_string(), "sre@example.com".to_string()],
937 };
938 let whois = WhoIs::from_node_with_profile(n, Some(profile.clone()));
939
940 assert_eq!(whois.user_profile, Some(profile));
941 // The flattened label the pre-widening `user` field carried is still what `user()` answers.
942 assert_eq!(whois.user(), Some("alice@example.com".to_string()));
943 assert_eq!(whois.user_groups(), ["group:eng", "sre@example.com"]);
944 assert_eq!(
945 whois.capabilities,
946 vec![("cap/x".to_string(), vec!["y".to_string()])]
947 );
948 }
949
950 /// A profile control sent with no `Groups` still resolves — the profile is present, the group
951 /// list is merely empty. The absent case must never collapse to "no profile", because an
952 /// embedder distinguishes "control named this owner but reported no groups" (deny, with a
953 /// known owner) from "control named no owner at all".
954 #[test]
955 fn whois_with_a_groupless_profile_keeps_the_profile_and_reports_no_groups() {
956 let n = node("n1", "host", Some("ts.net"), "100.64.0.9");
957 let whois = WhoIs::from_node_with_profile(
958 n,
959 Some(UserProfile {
960 id: 42,
961 login_name: "alice@example.com".to_string(),
962 display_name: None,
963 groups: Vec::new(),
964 }),
965 );
966
967 assert!(whois.user_profile.is_some(), "the profile itself survives");
968 assert_eq!(whois.user(), Some("alice@example.com".to_string()));
969 assert!(whois.user_groups().is_empty());
970 }
971
972 /// Build a peer with a reachable peerAPI on `ipv4`, owned by `user`.
973 fn peer_with_peerapi(stable: &str, hostname: &str, ipv4: &str, user: UserId) -> Node {
974 let mut n = node(stable, hostname, Some("ts.net"), ipv4);
975 n.user_id = user;
976 n.peerapi_port = Some(8089);
977 n
978 }
979
980 #[test]
981 fn file_targets_includes_same_owner_peer_with_peerapi() {
982 let peer = peer_with_peerapi("p1", "host", "100.64.0.5", 42);
983 let targets = build_file_targets(vec![peer], 42);
984
985 assert_eq!(targets.len(), 1);
986 assert_eq!(targets[0].peerapi_url, "http://100.64.0.5:8089");
987 assert_eq!(targets[0].node.hostname, "host");
988 }
989
990 #[test]
991 fn file_targets_includes_cross_owner_peer_with_target_cap() {
992 // Different owner, but carries the file-sharing-target cap → still a target (Go's OR).
993 let mut peer = peer_with_peerapi("p1", "host", "100.64.0.5", 99);
994 peer.cap_map
995 .insert("tailscale.com/cap/file-sharing-target".to_string(), vec![]);
996 let targets = build_file_targets(vec![peer], 42);
997
998 assert_eq!(
999 targets.len(),
1000 1,
1001 "cross-owner peer with the target cap qualifies"
1002 );
1003 }
1004
1005 #[test]
1006 fn file_targets_excludes_cross_owner_peer_without_cap() {
1007 // Different owner and no target cap → excluded.
1008 let peer = peer_with_peerapi("p1", "host", "100.64.0.5", 99);
1009 let targets = build_file_targets(vec![peer], 42);
1010
1011 assert!(
1012 targets.is_empty(),
1013 "a different owner without the cap is not a target"
1014 );
1015 }
1016
1017 #[test]
1018 fn file_targets_excludes_peer_without_peerapi() {
1019 // Same owner, but advertises no peerAPI (no port) → excluded (Go `PeerAPIBase(p) == ""`).
1020 let mut peer = peer_with_peerapi("p1", "host", "100.64.0.5", 42);
1021 peer.peerapi_port = None;
1022 let targets = build_file_targets(vec![peer], 42);
1023
1024 assert!(
1025 targets.is_empty(),
1026 "a peer with no peerAPI cannot be a Taildrop target"
1027 );
1028 }
1029
1030 #[test]
1031 fn file_targets_sorted_by_magic_dns_name() {
1032 // Insert out of order; expect sorted by fqdn ("alpha.ts.net" < "zeta.ts.net").
1033 let zeta = peer_with_peerapi("p2", "zeta", "100.64.0.6", 42);
1034 let alpha = peer_with_peerapi("p1", "alpha", "100.64.0.5", 42);
1035 let targets = build_file_targets(vec![zeta, alpha], 42);
1036
1037 let names: Vec<_> = targets.iter().map(|t| t.node.hostname.clone()).collect();
1038 assert_eq!(names, vec!["alpha", "zeta"]);
1039 }
1040
1041 fn region_result(id: u32, latency_ms: u64) -> ts_netcheck::RegionResult {
1042 ts_netcheck::RegionResult {
1043 latency: std::time::Duration::from_millis(latency_ms),
1044 id: ts_derp::RegionId(std::num::NonZeroU32::new(id).unwrap()),
1045 latency_map_key: format!("{id}-v4"),
1046 connected_remote: "1.2.3.4:443".parse().unwrap(),
1047 }
1048 }
1049
1050 #[test]
1051 fn netcheck_report_preferred_is_first_region() {
1052 // The measurer hands results sorted by latency ascending, so the first is the preferred
1053 // (home) region and every region is surfaced.
1054 let results = [
1055 region_result(5, 12),
1056 region_result(9, 40),
1057 region_result(2, 88),
1058 ];
1059 let report = NetcheckReport::from_region_results(&results);
1060 assert_eq!(
1061 report.preferred_derp,
1062 Some(5),
1063 "lowest-latency region is preferred"
1064 );
1065 assert_eq!(report.region_latencies.len(), 3);
1066 assert_eq!(report.region_latencies[0].region_id, 5);
1067 assert_eq!(
1068 report.region_latencies[0].latency,
1069 std::time::Duration::from_millis(12)
1070 );
1071 // Order is preserved as given (latency-ascending from the measurer).
1072 let ids: Vec<u32> = report
1073 .region_latencies
1074 .iter()
1075 .map(|r| r.region_id)
1076 .collect();
1077 assert_eq!(ids, vec![5, 9, 2]);
1078 }
1079
1080 #[test]
1081 fn netcheck_report_empty_when_no_measurements() {
1082 // Before any measurement (or when none was reachable): no preferred region, empty list — not
1083 // a fabricated value.
1084 let report = NetcheckReport::from_region_results(&[]);
1085 assert_eq!(report, NetcheckReport::default());
1086 assert_eq!(report.preferred_derp, None);
1087 assert!(report.region_latencies.is_empty());
1088 }
1089}
1090
1091#[cfg(test)]
1092mod control_health_tests {
1093 use super::health_warnings;
1094
1095 #[test]
1096 fn disconnected_control_warns_without_hiding_a_rejected_filter() {
1097 assert!(health_warnings(false, true).is_empty());
1098 let disconnected = health_warnings(false, false);
1099 assert_eq!(disconnected.len(), 1);
1100 assert!(disconnected[0].contains("Disconnected from coordination server"));
1101 let both = health_warnings(true, false);
1102 assert_eq!(both.len(), 2);
1103 assert_eq!(both[0], crate::packetfilter::INVALID_PACKET_FILTER_WARNING);
1104 assert_eq!(both[1], disconnected[0]);
1105 assert_eq!(health_warnings(true, true), vec![both[0].clone()]);
1106 }
1107}