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