Skip to main content

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, 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 text of every health warning currently raised (Go `ipnstate.Status.Health`). Empty when
55    /// healthy. Today the one warning this runtime raises is Go's `invalid-packet-filter`: control
56    /// sent a packet filter granting an unlocked (tailnet-lock-unsigned) peer access, so this node is
57    /// rejecting all inbound packets.
58    pub health: Vec<String>,
59}
60
61/// A single node entry in a [`Status`] snapshot.
62///
63/// Analogous to tsnet's `ipnstate.PeerStatus`.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct StatusNode {
66    /// The node's stable id (stable across re-registration).
67    pub stable_id: StableNodeId,
68    /// A display name for the node: its fqdn if a tailnet component is known, else its bare
69    /// hostname.
70    pub display_name: String,
71    /// The node's tailnet IPv4 address: the **first** IPv4 prefix control assigned it (the identity
72    /// projection the overlay, MagicDNS and exit-node selection reason about). See
73    /// [`tailscale_ips`](Self::tailscale_ips) for every address control assigned.
74    pub ipv4: IpAddr,
75    /// The node's tailnet IPv6 address: the **first** IPv6 prefix control assigned it. See
76    /// [`tailscale_ips`](Self::tailscale_ips) for every address control assigned.
77    pub ipv6: IpAddr,
78    /// Every tailnet address control assigned this node (Go `ipnstate.PeerStatus.TailscaleIPs`), in
79    /// wire order.
80    ///
81    /// Normally the same two addresses as [`ipv4`](Self::ipv4) / [`ipv6`](Self::ipv6), but
82    /// `tailcfg.Node.Addresses` is a variable-length list: an IPv6-off tailnet assigns only the v4
83    /// prefix, and nothing in the protocol stops control assigning more than one prefix of a family.
84    /// Built from the domain [`Node::addresses`](ts_control::Node::addresses), keeping each
85    /// single-IP prefix's address exactly as Go's status builder does
86    /// (`ipn/ipnlocal/local.go`). This — not the first-of-family pair — is what
87    /// [`is_router`](Self::is_router) asks "is this route one of my own addresses?" of.
88    pub tailscale_ips: Vec<IpAddr>,
89    /// Whether the node is online, if known (`ipnstate.PeerStatus.Online`). Tri-state: `Some(true)`
90    /// connected to control, `Some(false)` offline, `None` unknown (control sent no online status or
91    /// the local node lacks permission to know). Reflects control's liveness state, retained from the
92    /// netmap node + its online deltas — `None` is *unknown*, never fabricated to `false`.
93    pub online: Option<bool>,
94    /// When control last saw this node online (`ipnstate.PeerStatus.LastSeen`). Per Go, only
95    /// meaningful while the node is not currently online. `None` when unknown or never seen.
96    pub last_seen: Option<chrono::DateTime<chrono::Utc>>,
97    /// The routes this node accepts traffic for (its own `/32` and `/128`, plus any advertised
98    /// subnet routes and possibly the exit-node default route).
99    pub allowed_routes: Vec<ipnet::IpNet>,
100    /// Whether this node advertises a default route (`0.0.0.0/0` or `::/0`), making it eligible to
101    /// be selected as an exit node.
102    pub is_exit_node: bool,
103    /// The current trusted direct UDP endpoint for this peer, if a direct path is confirmed right now
104    /// (Go `ipnstate.PeerStatus.CurAddr`). `Some` ⇒ traffic to this peer flows directly to this
105    /// address; `None` ⇒ it relays via DERP (see [`relay`](Self::relay)). Mutually exclusive with a
106    /// `relay` for a routed peer, mirroring Go's empty-vs-set `CurAddr`/`Relay` strings. A live
107    /// snapshot — the direct path can expire/re-confirm between calls. Always `None` for the self node
108    /// and a whois lookup (no path to oneself; whois is an ownership query).
109    pub cur_addr: Option<SocketAddr>,
110    /// The DERP region code this peer relays through when there is **no** direct path (Go
111    /// `ipnstate.PeerStatus.Relay`, e.g. `"nyc"`). `Some` ⇔ [`cur_addr`](Self::cur_addr) is `None`
112    /// and the peer's home DERP region is known; `None` when a direct path is confirmed, or the
113    /// region code is unknown. Carries the region **code**, not its numeric id.
114    pub relay: Option<String>,
115    /// The node's advertised SSH host public keys in known_hosts format (Go
116    /// `ipnstate.PeerStatus.SSH_HostKeys`), used by `tailscale ssh` to pin the peer's host key.
117    /// Mirrors the domain [`Node::ssh_host_keys`](ts_control::Node::ssh_host_keys); empty when
118    /// control advertised none (never fabricated).
119    pub ssh_host_keys: Vec<String>,
120    /// Whether this node's key has expired (Go `ipnstate.PeerStatus.Expired`).
121    ///
122    /// Set either by control on the wire or by this node's own expiry pass
123    /// ([`ts_control::ExpiryManager::flag_expired_peer`]) once the node's key expiry has passed —
124    /// judged against control's clock, not this host's. An expired peer is deliberately still
125    /// listed: it keeps its identity so a watcher can tell "expired" apart from "gone", but it has
126    /// no endpoints, no home DERP, and a broken node key, so nothing routes to it and a peerAPI
127    /// dial to it is refused ([`ts_control::PEER_KEY_EXPIRED`]).
128    pub expired: bool,
129}
130
131/// Whether `prefix` covers exactly one address (a `/32` or a `/128`) — Go `netip.Prefix.IsSingleIP`.
132fn is_single_ip(prefix: &ipnet::IpNet) -> bool {
133    let host_prefix = match prefix {
134        ipnet::IpNet::V4(_) => 32,
135        ipnet::IpNet::V6(_) => 128,
136    };
137    prefix.prefix_len() == host_prefix
138}
139
140impl StatusNode {
141    /// Report whether this node is a **router**: it routes addresses besides its own. An exit
142    /// node, a subnet router and an app connector are all routers.
143    ///
144    /// Mirrors Go's `ipnstate.PeerStatus.IsRouter` (`ipn/ipnstate/ipnstate.go`, added upstream in
145    /// `8d830599b` alongside `tailcfg.Node.IsRouter`, which
146    /// [`Node::is_router`](ts_control::Node::is_router) mirrors): a route in
147    /// [`allowed_routes`](Self::allowed_routes) that is not a single host IP, or that is a host IP
148    /// other than one of this node's own [`tailscale_ips`](Self::tailscale_ips), makes the node a
149    /// router. Upstream spells both as *methods*, not wire fields — control sends nothing new for
150    /// this, so it is a pure projection of the netmap a peer already gave us.
151    ///
152    /// The comparison is against the **whole** [`tailscale_ips`](Self::tailscale_ips) list, as Go's
153    /// `slices.Contains(ps.TailscaleIPs, r.Addr())` is, and not against the first-of-family
154    /// [`ipv4`](Self::ipv4)/[`ipv6`](Self::ipv6) pair. A node control handed two prefixes of one
155    /// family would otherwise have the second read as a routed address and be misreported as a
156    /// router — the same narrowing [`Node::is_router`](ts_control::Node::is_router) had.
157    ///
158    /// Strictly wider than [`is_exit_node`](Self::is_exit_node), which asks only about the default
159    /// route: every exit node is a router, but a subnet router advertising no `/0` is not an exit
160    /// node.
161    pub fn is_router(&self) -> bool {
162        self.allowed_routes.iter().any(|route| {
163            // Not a single host IP, or a host IP that is not one of this node's own addresses.
164            !is_single_ip(route) || !self.tailscale_ips.contains(&route.addr())
165        })
166    }
167
168    /// Build a [`StatusNode`] from a domain [`Node`].
169    pub fn from_node(node: &Node) -> Self {
170        let is_exit_node = node
171            .accepted_routes
172            .iter()
173            .any(|route| route.prefix_len() == 0);
174
175        Self {
176            stable_id: node.stable_id.clone(),
177            display_name: node
178                .fqdn_opt(false)
179                .unwrap_or_else(|| node.hostname.clone()),
180            ipv4: node.tailnet_address.ipv4.addr().into(),
181            ipv6: node.tailnet_address.ipv6.addr().into(),
182            // Go's status builder fills `PeerStatus.TailscaleIPs` from the node's whole
183            // `Node.Addresses` list, keeping the address of each single-IP prefix
184            // (`ipn/ipnlocal/local.go`). Take the same list, not the first-of-family pair above:
185            // `is_router` compares against it.
186            tailscale_ips: node
187                .addresses
188                .iter()
189                .filter(|prefix| is_single_ip(prefix))
190                .map(|prefix| prefix.addr())
191                .collect(),
192            online: node.online,
193            last_seen: node.last_seen,
194            allowed_routes: node.accepted_routes.clone(),
195            is_exit_node,
196            // A bare `Node` carries no live path state, so connectivity is unknown here. The peer
197            // tracker overwrites these in `status_peers` by joining against the direct manager; the
198            // self node and whois lookups (which also use `from_node`) correctly keep `None`.
199            cur_addr: None,
200            relay: None,
201            ssh_host_keys: node.ssh_host_keys.clone(),
202            expired: node.expired,
203        }
204    }
205}
206
207/// The result of a [`Runtime::whois`](crate::Runtime::whois) lookup: the node that owns a tailnet
208/// source address, plus its user and capabilities.
209///
210/// Analogous to tsnet's `apitype.WhoIsResponse`.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub struct WhoIs {
213    /// The node that owns the queried source IP.
214    pub node: Node,
215    /// The profile of the user that owns the node — Go `apitype.WhoIsResponse.UserProfile`.
216    ///
217    /// Resolved by joining the node's owning user id against the netmap's `UserProfiles` table
218    /// (accumulated by the [`PeerTracker`](crate::peer_tracker::PeerTracker) across delta updates).
219    /// `None` when control sent no profile for that user — a tagged node with no human owner, or a
220    /// profile not yet delivered. Carries the whole profile rather than one flattened label so an
221    /// embedder can authorise on [`UserProfile::groups`], which is the one owner attribute a node
222    /// cannot re-derive locally; [`user`](Self::user) is still there for the display case.
223    pub user_profile: Option<UserProfile>,
224    /// The node's **node-level** capability map (Go `Node.CapMap` — node attributes like
225    /// `can-funnel`), as `(capability, args)` pairs, populated from the domain
226    /// [`Node`]'s `cap_map`, sorted by capability name. Distinct from
227    /// [`cap_map`](Self::cap_map), which is the flow-scoped *peer-capability* grants.
228    pub capabilities: Vec<(String, Vec<String>)>,
229    /// The **flow-scoped** peer-capability grants for the queried `src -> dst` flow — Go
230    /// `apitype.WhoIsResponse.CapMap` (`tailcfg.PeerCapMap`). The grants control's packet-filter
231    /// application rules authorize for traffic from this node to the queried address, keyed by
232    /// capability name with raw-JSON values. Empty when no grant matches the flow (or no scoped
233    /// query was made). Distinct from the node-level [`capabilities`](Self::capabilities).
234    pub cap_map: BTreeMap<String, Vec<String>>,
235}
236
237impl WhoIs {
238    /// Build a [`WhoIs`] from the owning node and its resolved owner profile (if the netmap's
239    /// `UserProfiles` table mapped the node's owning user id to one; `None` when control sent no
240    /// profile — e.g. a tagged node with no human owner).
241    ///
242    /// `capabilities` is the node-level cap map; `cap_map` (the flow-scoped grants) is filled
243    /// separately by [`Runtime::whois`](crate::Runtime::whois) and defaults to empty here.
244    pub(crate) fn from_node_with_profile(node: Node, user_profile: Option<UserProfile>) -> Self {
245        let capabilities = node
246            .cap_map
247            .iter()
248            .map(|(cap, args)| (cap.clone(), args.clone()))
249            .collect();
250        Self {
251            node,
252            user_profile,
253            capabilities,
254            cap_map: BTreeMap::new(),
255        }
256    }
257
258    /// The best human-facing label for the owning user: the profile's login name when present,
259    /// else its display name, else `None` (no profile, or a profile with neither).
260    ///
261    /// This is the flattened view [`user_profile`](Self::user_profile) replaced; use the profile
262    /// itself for anything but display.
263    pub fn user(&self) -> Option<String> {
264        self.user_profile.as_ref().and_then(UserProfile::best_label)
265    }
266
267    /// The groups control reported for the owning user — Go
268    /// `apitype.WhoIsResponse.UserProfile.Groups`. SCIM groups (e.g. `engineering@example.com`) or
269    /// tailnet-policy group names (e.g. `group:eng`).
270    ///
271    /// The authorisation shortcut: `whois.user_groups().iter().any(|g| g == "group:eng")`.
272    ///
273    /// **Empty** both when there is no profile at all and when control reported no groups — which
274    /// includes every control server that does not send the field. An empty list is therefore
275    /// "control told this node nothing", not a proof of non-membership: fail closed on it (deny),
276    /// never treat it as a negative assertion.
277    pub fn user_groups(&self) -> &[String] {
278        self.user_profile
279            .as_ref()
280            .map_or(&[], |profile| profile.groups.as_slice())
281    }
282}
283
284/// Resolve which node owns a tailnet source address, used by WhoIs.
285pub(crate) fn whois_addr(addr: SocketAddr) -> IpAddr {
286    addr.ip()
287}
288
289/// A measured-latency entry for one DERP region in a [`NetcheckReport`].
290#[derive(Debug, Clone, PartialEq, Eq)]
291pub struct RegionLatency {
292    /// The DERP region id (Go `tailcfg.DERPRegionID`).
293    pub region_id: u32,
294    /// The measured round-trip latency to the region's closest DERP node.
295    pub latency: std::time::Duration,
296}
297
298/// A snapshot of this node's latest network conditions report — the Rust analog of Go's
299/// `netcheck.Report` as `tailscale netcheck` surfaces it.
300///
301/// ## Surfaced subset (do not fabricate)
302/// Go's `netcheck.Report` also carries UDP/IPv4/IPv6 reachability, port-mapping support
303/// (UPnP/PMP/PCP), `MappingVariesByDestIP`, global-address discovery, etc. This fork's net-report
304/// path measures only **DERP-region latency** (the data that drives home-region selection), so the
305/// report carries exactly that — the preferred (lowest-latency) region and the per-region latency
306/// map — rather than inventing fields we never probe. Empty before the first measurement.
307#[derive(Debug, Clone, PartialEq, Eq, Default, kameo::Reply)]
308pub struct NetcheckReport {
309    /// The id of the preferred DERP region — the lowest-latency region this node measured, the one it
310    /// homes to (Go `Report.PreferredDERP`). `None` before the first measurement / when no region
311    /// was reachable.
312    pub preferred_derp: Option<u32>,
313    /// Per-region measured latencies, sorted by latency ascending (Go `Report.RegionLatency`, here as
314    /// an ordered list). The first entry, when present, is the [`preferred_derp`](Self::preferred_derp)
315    /// region.
316    pub region_latencies: Vec<RegionLatency>,
317}
318
319impl NetcheckReport {
320    /// Build a report from the latest DERP-region measurements (the `RegionResult` set the latency
321    /// measurer produces). `results` is expected sorted by latency ascending (the measurer's
322    /// `RegionResult` `Ord` sorts on latency first), so the first entry is the preferred region; we
323    /// do not re-sort beyond trusting that contract for `preferred_derp`, but the list is emitted in
324    /// the order given. An empty `results` yields the default (no preferred region, empty list).
325    pub(crate) fn from_region_results(results: &[ts_netcheck::RegionResult]) -> NetcheckReport {
326        let region_latencies: Vec<RegionLatency> = results
327            .iter()
328            .map(|r| RegionLatency {
329                // `ts_derp::RegionId` is a `NonZeroU32` newtype (its `.0` is the public inner).
330                region_id: r.id.0.get(),
331                latency: r.latency,
332            })
333            .collect();
334        NetcheckReport {
335            preferred_derp: region_latencies.first().map(|r| r.region_id),
336            region_latencies,
337        }
338    }
339}
340
341/// A tailnet peer this node can send a Taildrop file *to*, plus the peerAPI base URL to reach it.
342///
343/// Analogous to tsnet's `apitype.FileTarget`. The set is produced by
344/// [`Runtime::file_targets`](crate::Runtime::file_targets) (exposed as `Device::file_targets`).
345#[derive(Debug, Clone, PartialEq, Eq)]
346pub struct FileTarget {
347    /// The target peer's node record — pass straight to the Taildrop send path
348    /// (`Device::send_file`), which re-derives the same peerAPI address.
349    pub node: Node,
350    /// The `http://ip:port` base URL of the peer's peerAPI, with no trailing path — the exact shape
351    /// of Go's `apitype.FileTarget.PeerAPIURL`. Derived from
352    /// [`Node::peerapi_addr`](ts_control::Node::peerapi_addr).
353    pub peerapi_url: String,
354}
355
356/// Compute the sorted Taildrop send-target list from the peer set, given the local node's owning
357/// user id. The pure core of [`Runtime::file_targets`](crate::Runtime::file_targets) — separated out
358/// so the eligibility + ordering rules are unit-testable without spinning up the actor graph (the
359/// node-level file-sharing gate is applied by the caller before this runs).
360///
361/// A peer is a target when it advertises a reachable peerAPI (Go `PeerAPIBase(p) != ""`) **and** is
362/// either owned by `self_user_id` **or** carries the file-sharing-target capability — Go's two-way
363/// OR. Sorted by MagicDNS name (Go sorts by `Node.Name`), falling back to the bare hostname.
364pub(crate) fn build_file_targets(peers: Vec<Node>, self_user_id: UserId) -> Vec<FileTarget> {
365    let mut targets: Vec<FileTarget> = peers
366        .into_iter()
367        .filter_map(|peer| {
368            // Must advertise a reachable peerAPI (Go `PeerAPIBase(p) != ""`).
369            let addr = peer.peerapi_addr()?;
370            // Same owner OR explicitly an ACL file-sharing target (Go's two-way OR).
371            let eligible = peer.user_id == self_user_id || peer.is_file_sharing_target();
372            if !eligible {
373                return None;
374            }
375            Some(FileTarget {
376                peerapi_url: format!("http://{addr}"),
377                node: peer,
378            })
379        })
380        .collect();
381    // Sort by MagicDNS name (Go sorts by `Node.Name`), bare hostname as the fallback key.
382    targets.sort_by(|a, b| {
383        let name = |t: &FileTarget| {
384            t.node
385                .fqdn_opt(false)
386                .unwrap_or_else(|| t.node.hostname.clone())
387        };
388        name(a).cmp(&name(b))
389    });
390    targets
391}
392
393#[cfg(test)]
394mod tests {
395    use ts_control::{Node, StableNodeId, TailnetAddress};
396
397    use super::*;
398
399    fn node(stable: &str, hostname: &str, tailnet: Option<&str>, ipv4: &str) -> Node {
400        Node {
401            id: 1,
402            stable_id: StableNodeId(stable.to_string()),
403            hostname: hostname.to_string(),
404            user_id: 0,
405            tailnet: tailnet.map(str::to_string),
406            tags: vec![],
407            addresses: vec![
408                format!("{ipv4}/32").parse().unwrap(),
409                "fd7a::1/128".parse().unwrap(),
410            ],
411            tailnet_address: TailnetAddress {
412                ipv4: format!("{ipv4}/32").parse().unwrap(),
413                ipv6: "fd7a::1/128".parse().unwrap(),
414            },
415            node_key: [0u8; 32].into(),
416            node_key_expiry: None,
417            expired: false,
418            online: None,
419            last_seen: None,
420            key_signature: vec![],
421            machine_key: None,
422            disco_key: None,
423            accepted_routes: vec![],
424            underlay_addresses: vec![],
425            derp_region: None,
426            cap: Default::default(),
427            cap_map: Default::default(),
428            peerapi_port: None,
429            peerapi_dns_proxy: false,
430            is_wireguard_only: false,
431            exit_node_dns_resolvers: vec![],
432            peer_relay: false,
433            ssh_host_keys: vec![],
434            service_vips: Default::default(),
435            unsigned_peer_api_only: false,
436        }
437    }
438
439    #[test]
440    fn status_node_display_name_prefers_fqdn() {
441        let with_tailnet = node("n1", "host", Some("ts.net"), "100.64.0.1");
442        assert_eq!(
443            StatusNode::from_node(&with_tailnet).display_name,
444            "host.ts.net"
445        );
446
447        let bare = node("n2", "solo", None, "100.64.0.2");
448        assert_eq!(StatusNode::from_node(&bare).display_name, "solo");
449    }
450
451    #[test]
452    fn status_node_addresses_and_online_surfaced() {
453        let n = node("n1", "host", Some("ts.net"), "100.64.0.7");
454        let s = StatusNode::from_node(&n);
455
456        assert_eq!(s.ipv4, "100.64.0.7".parse::<IpAddr>().unwrap());
457        assert_eq!(s.ipv6, "fd7a::1".parse::<IpAddr>().unwrap());
458        // A node with no online data surfaces `None` (unknown) — never a fabricated `false`.
459        assert_eq!(s.online, None);
460        assert_eq!(s.last_seen, None);
461
462        // A node whose domain online state is known surfaces it through StatusNode (no longer
463        // hardwired to None).
464        let mut online = node("n2", "up", Some("ts.net"), "100.64.0.8");
465        online.online = Some(true);
466        assert_eq!(StatusNode::from_node(&online).online, Some(true));
467
468        let mut offline = node("n3", "down", Some("ts.net"), "100.64.0.9");
469        offline.online = Some(false);
470        assert_eq!(StatusNode::from_node(&offline).online, Some(false));
471    }
472
473    #[test]
474    fn status_node_carries_ssh_host_keys() {
475        // Absent on the domain node → empty on StatusNode (never fabricated).
476        let bare = node("n1", "host", Some("ts.net"), "100.64.0.1");
477        assert!(StatusNode::from_node(&bare).ssh_host_keys.is_empty());
478
479        // Present → mirrored verbatim (the keys `tailscale ssh` pins).
480        let mut with_keys = node("n2", "host", Some("ts.net"), "100.64.0.2");
481        with_keys.ssh_host_keys = vec!["ssh-ed25519 AAAAC3Nz host".to_string()];
482        assert_eq!(
483            StatusNode::from_node(&with_keys).ssh_host_keys,
484            vec!["ssh-ed25519 AAAAC3Nz host".to_string()]
485        );
486    }
487
488    #[test]
489    fn status_node_detects_exit_node() {
490        let mut not_exit = node("n1", "a", Some("ts.net"), "100.64.0.1");
491        not_exit.accepted_routes = vec!["100.64.0.1/32".parse().unwrap()];
492        assert!(!StatusNode::from_node(&not_exit).is_exit_node);
493
494        let mut exit = node("n2", "b", Some("ts.net"), "100.64.0.2");
495        exit.accepted_routes = vec![
496            "100.64.0.2/32".parse().unwrap(),
497            "0.0.0.0/0".parse().unwrap(),
498        ];
499        assert!(StatusNode::from_node(&exit).is_exit_node);
500
501        let mut exit6 = node("n3", "c", Some("ts.net"), "100.64.0.3");
502        exit6.accepted_routes = vec!["::/0".parse().unwrap()];
503        assert!(StatusNode::from_node(&exit6).is_exit_node);
504    }
505
506    /// Ported from upstream's `TestPeerStatusIsRouter` (`ipn/ipnstate/ipnstate_test.go`,
507    /// `8d830599b`), and cross-checked against [`ts_control::Node::is_router`] the way upstream's
508    /// `TestNodeIsRouter` cross-checks the two definitions: a peer is a router exactly when its
509    /// allowed routes reach past its own tailnet addresses. Both the present and the absent case
510    /// are pinned — a plain peer must keep answering `false`.
511    #[test]
512    fn status_node_is_router_reports_routes_beyond_own_addresses() {
513        let self4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
514        let self6: ipnet::IpNet = "fd7a:115c:a1e0::1/128".parse().unwrap();
515
516        let cases: &[(&str, Vec<ipnet::IpNet>, bool)] = &[
517            ("empty", vec![], false),
518            ("plain-ipv4", vec![self4], false),
519            ("plain-ipv6", vec![self6], false),
520            ("plain-ipv4-ipv6", vec![self4, self6], false),
521            (
522                "exit-node-ipv4",
523                vec![self4, "0.0.0.0/0".parse().unwrap()],
524                true,
525            ),
526            ("exit-node-ipv6", vec![self6, "::/0".parse().unwrap()], true),
527            (
528                "subnet-router-ipv4",
529                vec![self4, "192.0.2.0/24".parse().unwrap()],
530                true,
531            ),
532            (
533                "subnet-router-ipv6",
534                vec![self6, "2001:db8::/32".parse().unwrap()],
535                true,
536            ),
537            (
538                "subnet-router-ipv4-ipv6",
539                vec![
540                    self4,
541                    self6,
542                    "192.0.2.0/24".parse().unwrap(),
543                    "2001:db8::/32".parse().unwrap(),
544                ],
545                true,
546            ),
547            // No Tailscale-range exception, matching Go: another peer's /32 is a routed address.
548            (
549                "other-tailnet-host",
550                vec![self4, "100.64.5.5/32".parse().unwrap()],
551                true,
552            ),
553        ];
554
555        for (name, allowed, want) in cases {
556            let mut n = node("n1", "host", Some("ts.net"), "100.64.0.1");
557            n.addresses = vec![self4, self6];
558            n.tailnet_address.ipv6 = "fd7a:115c:a1e0::1/128".parse().unwrap();
559            n.accepted_routes = allowed.clone();
560
561            let s = StatusNode::from_node(&n);
562            assert_eq!(s.is_router(), *want, "{name}");
563            // The status projection and the domain node must agree, as upstream asserts of
564            // `ipnstate.PeerStatus.IsRouter` against `tailcfg.Node.IsRouter`.
565            assert_eq!(
566                s.is_router(),
567                n.is_router(),
568                "{name}: domain/status disagree"
569            );
570        }
571    }
572
573    /// Go's `PeerStatus.IsRouter` tests each allowed prefix against the node's **whole**
574    /// `TailscaleIPs` slice, so every address control assigned is "its own". `Node.Addresses` is a
575    /// variable-length list, not a v4/v6 pair, so a tailnet may hand a node more than one prefix of
576    /// a family; such a node must not be reported as a router on account of the extra one — which
577    /// comparing only against the first-of-family `ipv4`/`ipv6` pair does. The sibling
578    /// `ts_control::Node::is_router` case is pinned in `ts_control`; this pins the status
579    /// projection, which carries the same list one level up.
580    #[test]
581    fn status_node_is_router_tests_every_assigned_address_not_only_the_first_of_each_family() {
582        let first4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
583        let second4: ipnet::IpNet = "100.64.0.9/32".parse().unwrap();
584        let first6: ipnet::IpNet = "fd7a:115c:a1e0::1/128".parse().unwrap();
585        let second6: ipnet::IpNet = "fd7a:115c:a1e0::9/128".parse().unwrap();
586
587        let mut n = node("n1", "host", Some("ts.net"), "100.64.0.1");
588        n.addresses = vec![first4, second4, first6, second6];
589        n.tailnet_address.ipv6 = "fd7a:115c:a1e0::1/128".parse().unwrap();
590        // With `AllowedIPs` absent, control's routes for a node are exactly its addresses.
591        n.accepted_routes = n.addresses.clone();
592
593        let s = StatusNode::from_node(&n);
594
595        // The identity projection is still the first prefix of each family...
596        assert_eq!(s.ipv4, first4.addr());
597        assert_eq!(s.ipv6, first6.addr());
598        // ...and every assigned address is carried, as Go's `TailscaleIPs` is.
599        assert_eq!(
600            s.tailscale_ips,
601            vec![first4.addr(), second4.addr(), first6.addr(), second6.addr()]
602        );
603        assert!(
604            !s.is_router(),
605            "a node whose routes are exactly its own assigned addresses is not a router"
606        );
607        assert_eq!(s.is_router(), n.is_router(), "domain/status disagree");
608
609        // Either second-of-family address on its own is still not a routed address.
610        for extra in [second4, second6] {
611            let mut one = n.clone();
612            one.accepted_routes = vec![extra];
613            let s = StatusNode::from_node(&one);
614            assert!(
615                !s.is_router(),
616                "{extra} is one of this node's own addresses"
617            );
618            assert_eq!(s.is_router(), one.is_router(), "domain/status disagree");
619        }
620
621        // The predicate still fires for a route that does reach past every assigned address.
622        let mut router = n.clone();
623        router.accepted_routes.push("192.0.2.0/24".parse().unwrap());
624        assert!(
625            StatusNode::from_node(&router).is_router(),
626            "a real subnet route makes it a router"
627        );
628    }
629
630    /// An IPv6-off tailnet assigns a node only its IPv4 prefix, and the domain model fills the
631    /// missing family with an unspecified placeholder. `TailscaleIPs` must carry what control
632    /// actually assigned — not the placeholder — and the node must still not read as a router.
633    #[test]
634    fn status_node_tailscale_ips_omits_the_unassigned_family_placeholder() {
635        let only4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
636
637        let mut n = node("n1", "host", Some("ts.net"), "100.64.0.1");
638        n.addresses = vec![only4];
639        n.tailnet_address.ipv6 = "::/128".parse().unwrap();
640        n.accepted_routes = vec![only4];
641
642        let s = StatusNode::from_node(&n);
643        assert_eq!(s.tailscale_ips, vec![only4.addr()]);
644        assert!(!s.is_router(), "its own /32 is not a routed address");
645        assert!(
646            s.ipv6.is_unspecified(),
647            "the unassigned family stays a placeholder on the identity projection"
648        );
649    }
650
651    /// `from_node` carries NO live connectivity: a bare domain `Node` has no path state, so
652    /// `cur_addr`/`relay` default to `None`. `Runtime::status` overwrites `cur_addr` by joining the
653    /// direct manager's `best_addrs`; the self node and whois (which also use `from_node`) keep
654    /// `None`. This pins the default so the enrichment seam stays the single source of connectivity.
655    #[test]
656    fn status_node_from_node_has_no_connectivity_by_default() {
657        let n = node("n1", "host", Some("ts.net"), "100.64.0.7");
658        let s = StatusNode::from_node(&n);
659        assert_eq!(s.cur_addr, None, "a bare Node has no direct endpoint");
660        assert_eq!(s.relay, None, "a bare Node has no resolved relay");
661    }
662
663    #[test]
664    fn whois_caps_empty_when_node_has_none() {
665        // A node with no cap_map surfaces empty capabilities (not fabricated), and no user unless a
666        // profile was joined in.
667        let n = node("n1", "host", Some("ts.net"), "100.64.0.9");
668        let whois = WhoIs::from_node_with_profile(n.clone(), None);
669
670        assert_eq!(whois.node, n);
671        assert_eq!(whois.user_profile, None);
672        assert_eq!(whois.user(), None);
673        assert!(whois.user_groups().is_empty());
674        assert!(whois.capabilities.is_empty());
675    }
676
677    #[test]
678    fn whois_populates_capabilities_from_cap_map() {
679        // WhoIs surfaces the domain Node's cap_map verbatim, sorted by capability name (BTreeMap).
680        let mut n = node("n1", "host", Some("ts.net"), "100.64.0.9");
681        n.cap_map
682            .insert("https://tailscale.com/cap/is-admin".to_string(), vec![]);
683        n.cap_map.insert(
684            "cap/ssh".to_string(),
685            vec!["root".to_string(), "ubuntu".to_string()],
686        );
687        let whois = WhoIs::from_node_with_profile(n, None);
688
689        // BTreeMap iteration is sorted: "cap/ssh" < "https://…".
690        assert_eq!(
691            whois.capabilities,
692            vec![
693                (
694                    "cap/ssh".to_string(),
695                    vec!["root".to_string(), "ubuntu".to_string()]
696                ),
697                ("https://tailscale.com/cap/is-admin".to_string(), vec![]),
698            ]
699        );
700    }
701
702    #[test]
703    fn whois_from_node_with_profile_sets_profile_and_caps() {
704        let mut n = node("n1", "host", Some("ts.net"), "100.64.0.9");
705        n.cap_map.insert("cap/x".to_string(), vec!["y".to_string()]);
706        let profile = UserProfile {
707            id: 42,
708            login_name: "alice@example.com".to_string(),
709            display_name: Some("Alice Smith".to_string()),
710            groups: vec!["group:eng".to_string(), "sre@example.com".to_string()],
711        };
712        let whois = WhoIs::from_node_with_profile(n, Some(profile.clone()));
713
714        assert_eq!(whois.user_profile, Some(profile));
715        // The flattened label the pre-widening `user` field carried is still what `user()` answers.
716        assert_eq!(whois.user(), Some("alice@example.com".to_string()));
717        assert_eq!(whois.user_groups(), ["group:eng", "sre@example.com"]);
718        assert_eq!(
719            whois.capabilities,
720            vec![("cap/x".to_string(), vec!["y".to_string()])]
721        );
722    }
723
724    /// A profile control sent with no `Groups` still resolves — the profile is present, the group
725    /// list is merely empty. The absent case must never collapse to "no profile", because an
726    /// embedder distinguishes "control named this owner but reported no groups" (deny, with a
727    /// known owner) from "control named no owner at all".
728    #[test]
729    fn whois_with_a_groupless_profile_keeps_the_profile_and_reports_no_groups() {
730        let n = node("n1", "host", Some("ts.net"), "100.64.0.9");
731        let whois = WhoIs::from_node_with_profile(
732            n,
733            Some(UserProfile {
734                id: 42,
735                login_name: "alice@example.com".to_string(),
736                display_name: None,
737                groups: Vec::new(),
738            }),
739        );
740
741        assert!(whois.user_profile.is_some(), "the profile itself survives");
742        assert_eq!(whois.user(), Some("alice@example.com".to_string()));
743        assert!(whois.user_groups().is_empty());
744    }
745
746    /// Build a peer with a reachable peerAPI on `ipv4`, owned by `user`.
747    fn peer_with_peerapi(stable: &str, hostname: &str, ipv4: &str, user: UserId) -> Node {
748        let mut n = node(stable, hostname, Some("ts.net"), ipv4);
749        n.user_id = user;
750        n.peerapi_port = Some(8089);
751        n
752    }
753
754    #[test]
755    fn file_targets_includes_same_owner_peer_with_peerapi() {
756        let peer = peer_with_peerapi("p1", "host", "100.64.0.5", 42);
757        let targets = build_file_targets(vec![peer], 42);
758
759        assert_eq!(targets.len(), 1);
760        assert_eq!(targets[0].peerapi_url, "http://100.64.0.5:8089");
761        assert_eq!(targets[0].node.hostname, "host");
762    }
763
764    #[test]
765    fn file_targets_includes_cross_owner_peer_with_target_cap() {
766        // Different owner, but carries the file-sharing-target cap → still a target (Go's OR).
767        let mut peer = peer_with_peerapi("p1", "host", "100.64.0.5", 99);
768        peer.cap_map
769            .insert("tailscale.com/cap/file-sharing-target".to_string(), vec![]);
770        let targets = build_file_targets(vec![peer], 42);
771
772        assert_eq!(
773            targets.len(),
774            1,
775            "cross-owner peer with the target cap qualifies"
776        );
777    }
778
779    #[test]
780    fn file_targets_excludes_cross_owner_peer_without_cap() {
781        // Different owner and no target cap → excluded.
782        let peer = peer_with_peerapi("p1", "host", "100.64.0.5", 99);
783        let targets = build_file_targets(vec![peer], 42);
784
785        assert!(
786            targets.is_empty(),
787            "a different owner without the cap is not a target"
788        );
789    }
790
791    #[test]
792    fn file_targets_excludes_peer_without_peerapi() {
793        // Same owner, but advertises no peerAPI (no port) → excluded (Go `PeerAPIBase(p) == ""`).
794        let mut peer = peer_with_peerapi("p1", "host", "100.64.0.5", 42);
795        peer.peerapi_port = None;
796        let targets = build_file_targets(vec![peer], 42);
797
798        assert!(
799            targets.is_empty(),
800            "a peer with no peerAPI cannot be a Taildrop target"
801        );
802    }
803
804    #[test]
805    fn file_targets_sorted_by_magic_dns_name() {
806        // Insert out of order; expect sorted by fqdn ("alpha.ts.net" < "zeta.ts.net").
807        let zeta = peer_with_peerapi("p2", "zeta", "100.64.0.6", 42);
808        let alpha = peer_with_peerapi("p1", "alpha", "100.64.0.5", 42);
809        let targets = build_file_targets(vec![zeta, alpha], 42);
810
811        let names: Vec<_> = targets.iter().map(|t| t.node.hostname.clone()).collect();
812        assert_eq!(names, vec!["alpha", "zeta"]);
813    }
814
815    fn region_result(id: u32, latency_ms: u64) -> ts_netcheck::RegionResult {
816        ts_netcheck::RegionResult {
817            latency: std::time::Duration::from_millis(latency_ms),
818            id: ts_derp::RegionId(std::num::NonZeroU32::new(id).unwrap()),
819            latency_map_key: format!("{id}-v4"),
820            connected_remote: "1.2.3.4:443".parse().unwrap(),
821        }
822    }
823
824    #[test]
825    fn netcheck_report_preferred_is_first_region() {
826        // The measurer hands results sorted by latency ascending, so the first is the preferred
827        // (home) region and every region is surfaced.
828        let results = [
829            region_result(5, 12),
830            region_result(9, 40),
831            region_result(2, 88),
832        ];
833        let report = NetcheckReport::from_region_results(&results);
834        assert_eq!(
835            report.preferred_derp,
836            Some(5),
837            "lowest-latency region is preferred"
838        );
839        assert_eq!(report.region_latencies.len(), 3);
840        assert_eq!(report.region_latencies[0].region_id, 5);
841        assert_eq!(
842            report.region_latencies[0].latency,
843            std::time::Duration::from_millis(12)
844        );
845        // Order is preserved as given (latency-ascending from the measurer).
846        let ids: Vec<u32> = report
847            .region_latencies
848            .iter()
849            .map(|r| r.region_id)
850            .collect();
851        assert_eq!(ids, vec![5, 9, 2]);
852    }
853
854    #[test]
855    fn netcheck_report_empty_when_no_measurements() {
856        // Before any measurement (or when none was reachable): no preferred region, empty list — not
857        // a fabricated value.
858        let report = NetcheckReport::from_region_results(&[]);
859        assert_eq!(report, NetcheckReport::default());
860        assert_eq!(report.preferred_derp, None);
861        assert!(report.region_latencies.is_empty());
862    }
863}