Skip to main content

ts_control/
node.rs

1//! The parsed domain [`Node`] model: a tailnet node decoded from the wire (`tailcfg.Node`).
2//!
3//! [`Node`] is the owned, validated form the rest of the fork reasons about (addresses, keys, caps,
4//! accepted routes, peerAPI/VIP services), built from the borrow-bound `ts_control_serde::Node` via
5//! the [`From`] impl. It also carries the route/exit-node/funnel predicates ([`Node::is_subnet_route`],
6//! [`Node::routes_to_install`], [`Node::can_funnel`]) and the [`ExitNodeSelector`] resolution.
7//!
8//! Fail-closed: route, funnel, and service-host gates all deny on a missing/malformed input.
9
10use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
11use std::collections::BTreeMap;
12
13use chrono::{DateTime, Utc};
14use ts_capabilityversion::CapabilityVersion;
15use ts_keys::{DiscoPublicKey, MachinePublicKey, NodePublicKey};
16
17use crate::dns::Resolver;
18
19/// An owned node-capability map (`Node.CapMap` in Go: `map[NodeCapability][]RawMessage`).
20///
21/// Keys are capability names or URLs (e.g. `"funnel"`, `"https"`, or
22/// `"https://tailscale.com/cap/funnel-ports?ports=443,8443"`); values are the raw JSON-encoded
23/// argument blobs for that capability (often empty). Stored *owned* because the wire form
24/// ([`ts_control_serde::Node::cap_map`]) borrows from the decode buffer, whereas the domain
25/// [`Node`] outlives it. Funnel gating only inspects the keys (see [`Node::can_funnel`] and
26/// [`Node::check_funnel_port`]); the values are retained for capabilities that carry argument data.
27pub type NodeCapMap = BTreeMap<String, Vec<String>>;
28
29/// Whether `addr` falls in a range Tailscale assigns to nodes: the CGNAT range for IPv4
30/// (`100.64.0.0/10`, excluding the ChromeOS VM carve-out `100.115.92.0/23`) and the Tailscale
31/// ULA for IPv6 (`fd7a:115c:a1e0::/48`).
32///
33/// Mirrors `tsaddr.IsTailscaleIP` in the Go client. Used to tell a peer's own node addresses
34/// (always single Tailscale IPs) apart from the larger subnet routes it advertises.
35pub fn is_tailscale_ip(addr: IpAddr) -> bool {
36    match addr {
37        IpAddr::V4(v4) => {
38            let cgnat = ipnet::Ipv4Net::new(Ipv4Addr::new(100, 64, 0, 0), 10).unwrap();
39            let chromeos = ipnet::Ipv4Net::new(Ipv4Addr::new(100, 115, 92, 0), 23).unwrap();
40            cgnat.contains(&v4) && !chromeos.contains(&v4)
41        }
42        IpAddr::V6(v6) => {
43            let ula = ipnet::Ipv6Net::new(Ipv6Addr::new(0xfd7a, 0x115c, 0xa1e0, 0, 0, 0, 0, 0), 48)
44                .unwrap();
45            ula.contains(&v6)
46        }
47    }
48}
49
50/// The unique id of a node.
51pub type Id = i64;
52
53/// The stable ID of a node.
54#[derive(
55    Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
56)]
57pub struct StableId(pub String);
58
59/// How this node selects which peer to use as its exit node (`--exit-node` in the Go client).
60///
61/// Mirrors the Go client's `--exit-node`, which accepts a tailnet IP, a MagicDNS name, or a stable
62/// node ID, and resolves it to a `StableNodeID` (`resolveExitNodeIPLocked`). We keep the selector
63/// *unresolved* and re-run [`ExitNodeSelector::resolve`] against the live peer set on every route
64/// rebuild, so an IP- or name-based selection follows the peer as the netmap changes (e.g. the
65/// exit node re-registers under a new stable id).
66///
67/// A selector can be parsed from a string with [`str::parse`]/[`FromStr`](core::str::FromStr),
68/// auto-detecting the variant the way the Go CLI's `--exit-node` does: a value that parses as an IP
69/// address becomes [`ExitNodeSelector::Ip`], anything else becomes [`ExitNodeSelector::Name`].
70/// Stable-id selection is available only by constructing [`ExitNodeSelector::StableId`] directly
71/// (it is not auto-detected, since a stable id is otherwise indistinguishable from a hostname).
72#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
73pub enum ExitNodeSelector {
74    /// Select the peer with this exact stable node id.
75    StableId(StableId),
76    /// Select the peer whose tailnet address is this IP.
77    Ip(IpAddr),
78    /// Select the peer matching this bare hostname or MagicDNS name (case-insensitive, optional
79    /// trailing dot), as per [`Node::matches_name`].
80    Name(String),
81}
82
83impl core::str::FromStr for ExitNodeSelector {
84    type Err = core::convert::Infallible;
85
86    /// Parse a selector from a string, auto-detecting IP vs. name (matching the Go CLI's
87    /// `--exit-node`). Parsing never fails: a non-IP string is taken as a MagicDNS name.
88    fn from_str(s: &str) -> Result<Self, Self::Err> {
89        Ok(match s.parse::<IpAddr>() {
90            Ok(ip) => ExitNodeSelector::Ip(ip),
91            Err(_) => ExitNodeSelector::Name(s.to_owned()),
92        })
93    }
94}
95
96impl ExitNodeSelector {
97    /// Resolve this selector to the stable id of the matching peer, if any, given the current set
98    /// of peers.
99    ///
100    /// Resolution is **deterministic**: if a selector somehow matches more than one peer (e.g. two
101    /// peers sharing a MagicDNS name during a transient netmap state), the peer with the smallest
102    /// [`StableId`] is chosen. This matters because both the outbound route table and the inbound
103    /// source filter resolve independently; a deterministic tiebreak guarantees they pick the
104    /// *same* peer, preserving the cryptokey-routing coupling that prevents source-spoofing.
105    ///
106    /// Returns `None` when no peer matches (a stale/typo'd selector). Callers treat `None` as
107    /// fail-closed: no peer is granted a default route, so internet-bound traffic is dropped.
108    pub fn resolve<'a>(&self, peers: impl Iterator<Item = &'a Node>) -> Option<StableId> {
109        peers
110            .filter(|node| match self {
111                ExitNodeSelector::StableId(id) => &node.stable_id == id,
112                ExitNodeSelector::Ip(ip) => node.tailnet_address.contains(*ip),
113                ExitNodeSelector::Name(name) => node.matches_name(name),
114            })
115            .map(|node| &node.stable_id)
116            .min()
117            .cloned()
118    }
119}
120
121/// A node in a tailnet.
122#[derive(Debug, Clone, PartialEq, Eq, Hash)]
123pub struct Node {
124    /// The node's id.
125    pub id: Id,
126    /// The node's stable id.
127    pub stable_id: StableId,
128
129    /// This node's hostname.
130    pub hostname: String,
131
132    /// The integer id of the user that owns this node (`Node.User` in Go). `0` when control sends
133    /// no owner (e.g. tagged/ACL nodes have no human owner). Join against the netmap's
134    /// `UserProfiles` table (accumulated by the runtime's peer tracker) to resolve a login/display
135    /// name — see the runtime `WhoIs` lookup.
136    pub user_id: ts_control_serde::UserId,
137
138    /// The tailnet this node belongs to.
139    pub tailnet: Option<String>,
140
141    /// The tags assigned to this node.
142    pub tags: Vec<String>,
143
144    /// The address of the node in the tailnet.
145    pub tailnet_address: TailnetAddress,
146
147    /// The node's [`NodePublicKey`].
148    pub node_key: NodePublicKey,
149    /// The node key's expiration.
150    pub node_key_expiry: Option<DateTime<Utc>>,
151
152    /// Whether control reports this node currently connected to the coordination server
153    /// (`tailcfg.Node.Online`, a tri-state `*bool`). `None` = unknown / no permission to know /
154    /// never been online — **do not collapse to `false`** (that would fabricate an offline status
155    /// control never asserted). Updated by full nodes AND by the delta channels (a
156    /// [`PeerChange::online`], or the `MapResponse.online_change` map).
157    pub online: Option<bool>,
158    /// When control last saw this node online (`tailcfg.Node.LastSeen`). Per Go, only meaningful
159    /// while `online` is not `Some(true)` ("not updated when Online is true"). `None` = unknown /
160    /// never online.
161    pub last_seen: Option<DateTime<Utc>>,
162
163    /// Marshalled TKA node-key signature (`tailcfg.Node.KeySignature`); empty when control sends
164    /// none. Verified against a TKA `Authority` at the peer-trust chokepoint WHEN tailnet-lock
165    /// enforcement is active.
166    pub key_signature: Vec<u8>,
167
168    /// The node's [`MachinePublicKey`], if known.
169    pub machine_key: Option<MachinePublicKey>,
170    /// The node's [`DiscoPublicKey`], if known.
171    pub disco_key: Option<DiscoPublicKey>,
172
173    /// The routes this node accepts traffic for.
174    pub accepted_routes: Vec<ipnet::IpNet>,
175    /// The underlay addresses this node is reachable on (`Endpoints` in Go).
176    pub underlay_addresses: Vec<SocketAddr>,
177
178    /// The node's advertised SSH host public keys, in known_hosts format (Go
179    /// `tailcfg.Hostinfo.SSHHostKeys`, surfaced by tsnet as `ipnstate.PeerStatus.SSH_HostKeys`).
180    /// Used by `tailscale ssh` to pin a peer's host key (TOFU). Empty when control advertised none
181    /// (the wire `Hostinfo.sshHostKeys` was absent), never fabricated. Projected from
182    /// [`ts_control_serde::HostInfo::ssh_host_keys`].
183    pub ssh_host_keys: Vec<String>,
184
185    /// The DERP region for this node, if known.
186    pub derp_region: Option<ts_derp::RegionId>,
187
188    /// This node's advertised capability version (`Node.Cap` in Go). Old control servers may not
189    /// send it, in which case it defaults to [`CapabilityVersion::default`]. Used to gate features
190    /// that require a minimum peer capability, e.g. exit-node DNS proxying (`peerCanProxyDNS`).
191    pub cap: CapabilityVersion,
192
193    /// This node's capability map (`Node.CapMap` in Go). Keys are capability names/URLs; values are
194    /// the raw JSON argument blobs (often empty). Threaded from the wire
195    /// ([`ts_control_serde::Node::cap_map`]) as an owned copy. Used to gate node-level features such
196    /// as Funnel ingress ([`Node::can_funnel`], [`Node::check_funnel_port`]).
197    pub cap_map: NodeCapMap,
198
199    /// The peerAPI port this node advertises over IPv4 (`peerapi4` service), if any.
200    ///
201    /// Derived from `HostInfo.Services`. `None` means the peer advertises no IPv4 peerAPI, so it
202    /// cannot be reached for peerAPI DoH (DNS-over-HTTPS) exit-node delegation.
203    pub peerapi_port: Option<u16>,
204
205    /// Whether this peer advertises the `peerapi-dns-proxy` service (Go `PeerAPIDNSProxy`),
206    /// indicating it will proxy DNS lookups for other nodes when used as an exit node.
207    pub peerapi_dns_proxy: bool,
208
209    /// Whether this is a non-Tailscale WireGuard-only peer (`IsWireGuardOnly` in Go). Such peers
210    /// cannot run a peerAPI DoH server, so exit-node DNS for them comes from
211    /// [`Node::exit_node_dns_resolvers`] instead.
212    pub is_wireguard_only: bool,
213
214    /// DNS resolvers to use when this WireGuard-only peer is selected as an exit node
215    /// (`ExitNodeDNSResolvers` in Go). Only meaningful when [`Node::is_wireguard_only`] is set.
216    /// Encrypted-transport resolvers are dropped (see `Resolver::from_serde`).
217    pub exit_node_dns_resolvers: Vec<Resolver>,
218
219    /// Whether this node advertises itself as a **peer relay** (Go `Hostinfo.PeerRelay`): it runs a
220    /// UDP relay server other peers can allocate relay endpoints on. This fork is a relay client
221    /// only and never sets this for itself; it is parsed off peers so a relay candidate can be
222    /// recognized. Actually *using* a relay path (the Geneve data path + allocation handshake) is
223    /// not yet implemented — see the crate docs.
224    pub peer_relay: bool,
225
226    /// Per-service virtual IP addresses of the Tailscale VIP services this node *hosts*, keyed by
227    /// `svc:<label>` service name. Parsed from the `service-host`
228    /// ([`ts_control_serde::NODE_ATTR_SERVICE_HOST`]) node-capability value
229    /// (`tailcfg.ServiceIPMappings`). These VIPs are control-assigned and also injected into the
230    /// node's `AllowedIPs`; the application netstack must accept packets for them so a
231    /// `Device::listen_service`-bound listener can answer. Empty when the
232    /// node hosts no VIP services (the common case). Per-service IP lists are deduplicated, source
233    /// order otherwise preserved. Use [`Node::service_addresses`] for the flattened set (netstack
234    /// accept list) and [`Node::service_addresses_for`] for a specific service's VIPs.
235    pub service_vips: alloc::collections::BTreeMap<String, Vec<IpAddr>>,
236}
237
238impl Node {
239    /// The fully-qualified domain name of the node.
240    ///
241    /// This is a string of the form `$HOST.$TAILNET_DOMAIN.`. For tailnets controlled by
242    /// Tailscale's control plane, this usually means `$HOST.tail1234.ts.net.`
243    ///
244    /// The `trailing_dot` parameter specifies whether to include the trailing dot in the
245    /// fqdn. This is included by the definition of FQDN, and is the way the Go codebase
246    /// formats this field, but the parameter is included to allow turning it off for use
247    /// in contexts that expect it to be absent.
248    pub fn fqdn(&self, trailing_dot: bool) -> String {
249        let dot = if trailing_dot { "." } else { "" };
250        match &self.tailnet {
251            Some(tailnet) => format!("{}.{tailnet}{dot}", self.hostname),
252            None => format!("{}{dot}", self.hostname),
253        }
254    }
255
256    /// Whether this node's key has expired as of `now`, mirroring Go's
257    /// `netmap.NetworkMap.SelfKeyExpiry` + the `!expiry.IsZero() && expiry.Before(now)` check in
258    /// `ipnlocal`. A node with no expiry ([`Node::node_key_expiry`] is `None`, the Go "zero value =
259    /// does not expire") is never expired.
260    ///
261    /// Like Go, this fork is **reactive**: it reports expiry rather than auto-rotating in the
262    /// background (Go transitions to `NeedsLogin` on expiry and re-registers via stored auth-key or
263    /// interactive login). A caller observing `true` should re-register
264    /// (`crate::tokio::register`) — supplying `RegisterRequest::old_node_key` (the prior key) and
265    /// a fresh `node_key` when rotating the key, or the same key to merely refresh.
266    pub fn key_expired(&self, now: DateTime<Utc>) -> bool {
267        match self.node_key_expiry {
268            None => false,
269            Some(expiry) => expiry < now,
270        }
271    }
272
273    /// The instant this node's key expires (`Node.KeyExpiry` in Go), or `None` if it never expires.
274    /// A caller can schedule a re-evaluation/re-auth at this time.
275    pub fn key_expiry(&self) -> Option<DateTime<Utc>> {
276        self.node_key_expiry
277    }
278
279    /// Whether this node advertises itself as a peer relay (Go `Hostinfo.PeerRelay`): it runs a UDP
280    /// relay server other peers may allocate relay endpoints on. Recognizing a relay candidate;
281    /// actually traversing a relay path is not yet implemented in this fork.
282    pub fn is_peer_relay(&self) -> bool {
283        self.peer_relay
284    }
285
286    /// The key-expiry instant as **Unix seconds**, or `None` if the key never expires. Provided for
287    /// callers (e.g. the root crate) that don't depend on `chrono`.
288    pub fn key_expiry_unix(&self) -> Option<i64> {
289        self.node_key_expiry.map(|t| t.timestamp())
290    }
291
292    /// Whether the key has expired as of `now_unix_secs` (Unix seconds). Equivalent to
293    /// [`key_expired`](Self::key_expired) for `chrono`-free callers. A key with no expiry is never
294    /// expired.
295    pub fn key_expired_at_unix(&self, now_unix_secs: i64) -> bool {
296        match self.key_expiry_unix() {
297            None => false,
298            Some(expiry) => expiry < now_unix_secs,
299        }
300    }
301
302    /// The fully-qualified domain name of the node, only returning `Some` if the tailnet
303    /// component is present.
304    ///
305    /// See [`Node::fqdn`].
306    pub fn fqdn_opt(&self, trailing_dot: bool) -> Option<String> {
307        let dot = if trailing_dot { "." } else { "" };
308        let tailnet = self.tailnet.as_deref()?;
309
310        Some(format!("{}.{tailnet}{dot}", self.hostname))
311    }
312
313    /// Report whether this node matches the given `name`.
314    ///
315    /// `name` is checked for equality with both this node's bare hostname and its fqdn. A
316    /// trailing `.` may be present. Matching is case-insensitive (DNS names are
317    /// case-insensitive), so this agrees with the canonicalized MagicDNS-name index used for
318    /// peer lookups.
319    pub fn matches_name(&self, name: &str) -> bool {
320        // Strip an optional trailing root dot, then chop our `.tailnet` suffix off the end (if it
321        // matches, case-insensitively) and compare the remainder to our hostname. If the tailnet
322        // suffix doesn't match, the final case-insensitive compare against our bare hostname fails
323        // naturally; if `name` was just the hostname, nothing is chopped and we compare directly.
324
325        let name = name.strip_suffix('.').unwrap_or(name);
326
327        let name = if let Some(tailnet) = &self.tailnet {
328            name.get(name.len().saturating_sub(tailnet.len())..)
329                .filter(|suffix| suffix.eq_ignore_ascii_case(tailnet))
330                .and_then(|_| name.get(..name.len() - tailnet.len()))
331                .and_then(|name| name.strip_suffix('.'))
332                .unwrap_or(name)
333        } else {
334            name
335        };
336
337        name.eq_ignore_ascii_case(&self.hostname)
338    }
339
340    /// Report whether this node is a **router**: it routes addresses besides its own. An exit
341    /// node, a subnet router and an app connector are all routers.
342    ///
343    /// Mirrors Go's `tailcfg.Node.IsRouter` (`tailcfg/tailcfg.go`, added upstream in `8d830599b`),
344    /// which is `true` when any prefix in `AllowedIPs` is not also one of the node's own
345    /// `Addresses`. It is a *derived predicate*, not a wire field: control sends nothing new for
346    /// it, so there is no interop surface here and no capability version to gate on.
347    ///
348    /// Deliberately **not** [`Node::is_subnet_route`] folded over [`Node::accepted_routes`]. That
349    /// predicate also excuses any single Tailscale-range IP (`100.64.0.0/10` /
350    /// `fd7a:115c:a1e0::/48`) so route installation never mistakes another peer's address for an
351    /// advertised subnet; Go's `IsRouter` makes no such exception — a `/32` that is not *this*
352    /// node's own address still makes it a router. The two must stay separate.
353    ///
354    /// The domain [`Node`] retains only the first IPv4 and first IPv6 prefix control assigned
355    /// ([`Node::tailnet_address`]), which is what control assigns in practice; a node handed two
356    /// prefixes of the same family would count the extra one as a routed address.
357    pub fn is_router(&self) -> bool {
358        self.accepted_routes.iter().any(|route| match route {
359            ipnet::IpNet::V4(v4) => *v4 != self.tailnet_address.ipv4,
360            ipnet::IpNet::V6(v6) => *v6 != self.tailnet_address.ipv6,
361        })
362    }
363
364    /// Report whether `route` is an advertised *subnet* route (as opposed to one of this node's
365    /// own tailnet addresses).
366    ///
367    /// Mirrors `cidrIsSubnet` in the Go client (`wgengine/wgcfg/nmcfg/nmcfg.go`). A route is *not*
368    /// a subnet route (i.e. it's a self-address) when it is a single host IP that is either a
369    /// Tailscale-assigned IP or exactly one of this node's [`TailnetAddress`] addresses. Everything
370    /// else — multi-IP CIDRs, and single IPs outside the Tailscale ranges — is a subnet route.
371    ///
372    /// The default route (`0.0.0.0/0` / `::/0`) is treated as a subnet route here; exit-node
373    /// handling is a separate concern.
374    pub fn is_subnet_route(&self, route: &ipnet::IpNet) -> bool {
375        let host_prefix = match route {
376            ipnet::IpNet::V4(_) => 32,
377            ipnet::IpNet::V6(_) => 128,
378        };
379
380        if route.prefix_len() != host_prefix {
381            // Any multi-IP CIDR (including the default route) is a subnet route.
382            return true;
383        }
384
385        let addr = route.addr();
386        !(is_tailscale_ip(addr) || self.tailnet_address.contains(addr))
387    }
388
389    /// The routes that should be installed for this peer, given whether this node accepts
390    /// advertised subnet routes (`--accept-routes` / `RouteAll` in the Go client) and which peer
391    /// (if any) is the selected exit node (`--exit-node` / `ExitNodeID` in the Go client).
392    ///
393    /// This node's own addresses (the peer's `/32` and `/128`) are always installed so the peer
394    /// itself stays reachable. Larger advertised subnet routes are only installed when
395    /// `accept_routes` is set; otherwise they are dropped (fail-closed). The same filtered set
396    /// governs both outbound routing to the peer and inbound source validation, exactly as
397    /// WireGuard cryptokey routing couples them in the Go client.
398    ///
399    /// The default route (`0.0.0.0/0` / `::/0`) is installed *only* for the peer whose
400    /// [`StableId`] equals `exit_node`, mirroring `nmcfg.go`'s `if allowedIP.Bits()==0 &&
401    /// peer.StableID()!=exitNode { skip }`. Exit-node use is gated behind this separate, explicit
402    /// preference (`ExitNodeID`, not `RouteAll`): conflating the two would let enabling
403    /// subnet-route acceptance silently route every packet through any peer advertising a default
404    /// route — unacceptable for a fail-closed privacy posture. When `exit_node` is `None` (the
405    /// default) no peer ever receives a `/0`, so internet-bound traffic has no overlay route and is
406    /// dropped by the userspace netstack (fail-closed, no leak). Longest-prefix-match means a peer
407    /// selected as the exit node still loses more-specific destinations to other peers; only
408    /// residual default-route traffic egresses through it.
409    pub fn routes_to_install<'a>(
410        &'a self,
411        accept_routes: bool,
412        exit_node: Option<&StableId>,
413    ) -> impl Iterator<Item = &'a ipnet::IpNet> + 'a {
414        // Computed eagerly so the returned iterator doesn't borrow `exit_node`.
415        let is_selected_exit = exit_node == Some(&self.stable_id);
416        self.accepted_routes.iter().filter(move |route| {
417            if route.prefix_len() == 0 {
418                // Default route: installed only when this peer is the selected exit node. Both the
419                // outbound route table and the inbound source filter call this, so the exit peer
420                // may legitimately source arbitrary internet IPs on return traffic — and only it.
421                return is_selected_exit;
422            }
423            accept_routes || !self.is_subnet_route(route)
424        })
425    }
426
427    /// The capability version at and above which a peer can proxy DNS for nodes using it as an exit
428    /// node (Go `tailcfg.CapabilityVersion` `peerCanProxyDNS`, introduced 2022-01-12 at V26).
429    const PEER_CAN_PROXY_DNS: CapabilityVersion = CapabilityVersion::V26;
430
431    /// The base URL of this peer's IPv4 peerAPI DoH endpoint for exit-node DNS proxying, if it can
432    /// proxy DNS. Returns e.g. `http://100.64.0.5:8080/dns-query`.
433    ///
434    /// Mirrors Go `peerAPIBase(...)+"/dns-query"` gated by `exitNodeCanProxyDNS`: a peer can proxy
435    /// DNS when it advertises an IPv4 peerAPI port **and** either advertises the explicit
436    /// `peerapi-dns-proxy` service or is new enough ([`Node::cap`] ≥ `PEER_CAN_PROXY_DNS`). A
437    /// WireGuard-only peer never runs a peerAPI, so it returns `None` here (its exit-node DNS comes
438    /// from [`Node::exit_node_dns_resolvers`] instead).
439    ///
440    /// IPv4-only by deliberate design: the tailnet dataplane in this fork binds IPv4 only, so we
441    /// never form a peerAPI URL on the peer's IPv6 address.
442    pub fn peerapi_doh_url(&self) -> Option<String> {
443        self.peerapi_doh_addr()
444            .map(|addr| format!("http://{addr}/dns-query"))
445    }
446
447    /// The IPv4 socket address (`<tailnet-ipv4>:<peerapi-port>`) of this peer's peerAPI DoH endpoint
448    /// for exit-node DNS proxying, if it can proxy DNS. Same gate as [`Node::peerapi_doh_url`]; this
449    /// is the form the DoH *client* dials (over the overlay netstack) when delegating recursive
450    /// resolution to a selected exit node. `SocketAddr`'s `Display` is `ip:port`, so
451    /// `peerapi_doh_url` formats to `http://<ip>:<port>/dns-query` over this.
452    pub fn peerapi_doh_addr(&self) -> Option<SocketAddr> {
453        if self.is_wireguard_only {
454            return None;
455        }
456        let port = self.peerapi_port?;
457        if !(self.peerapi_dns_proxy || self.cap >= Self::PEER_CAN_PROXY_DNS) {
458            return None;
459        }
460        Some(SocketAddr::new(
461            IpAddr::V4(self.tailnet_address.ipv4.addr()),
462            port,
463        ))
464    }
465
466    /// The IPv4 peerAPI socket address (`<tailnet-ipv4>:<peerapi4-port>`) of this node, if it
467    /// advertises an IPv4 peerAPI. Unlike [`Node::peerapi_doh_addr`], this is **not** gated on the
468    /// DNS-proxy capability: it is the general base for any peerAPI request to this node (e.g. a
469    /// Taildrop `PUT /v0/put/<name>` upload), mirroring Go's `peerAPIBase`/`peerAPIPorts`.
470    ///
471    /// IPv4-only by this fork's deliberate design (the tailnet dataplane binds IPv4 only, so we never
472    /// form a peerAPI URL on the peer's IPv6 address). Returns `None` for a WireGuard-only peer (which
473    /// runs no peerAPI) or a peer advertising no IPv4 peerAPI port.
474    pub fn peerapi_addr(&self) -> Option<SocketAddr> {
475        if self.is_wireguard_only {
476            return None;
477        }
478        let port = self.peerapi_port?;
479        Some(SocketAddr::new(
480            IpAddr::V4(self.tailnet_address.ipv4.addr()),
481            port,
482        ))
483    }
484
485    /// The node attribute granting HTTPS (TLS cert provisioning) for this node (Go
486    /// `tailcfg.CapabilityHTTPS`). One of the two caps [`Node::can_funnel`] requires.
487    const CAP_HTTPS: &'static str = "https";
488
489    /// The node attribute granting the ability to host Funnel ingress (Go `tailcfg.NodeAttrFunnel`).
490    /// The other cap [`Node::can_funnel`] requires.
491    const NODE_ATTR_FUNNEL: &'static str = "funnel";
492
493    /// The capability URL whose `?ports=` query enumerates the ports Funnel may listen on (Go
494    /// `tailcfg.CapabilityFunnelPorts`). The allowed ports live entirely in the *key's* query
495    /// string, not the cap value.
496    const CAP_FUNNEL_PORTS: &'static str = "https://tailscale.com/cap/funnel-ports";
497
498    /// Report whether the cap map contains `cap` as a key (Go `NodeCapMap.Contains` / `HasCap`).
499    pub fn has_node_attr(&self, cap: &str) -> bool {
500        self.cap_map.contains_key(cap)
501    }
502
503    /// Report whether this node is permitted to host Tailscale Funnel ingress.
504    ///
505    /// Mirrors Go `ipn.NodeCanFunnel`: the node must advertise BOTH `CapabilityHTTPS` (`"https"`)
506    /// AND `NodeAttrFunnel` (`"funnel"`) in its cap map. Fail-closed: a missing cap denies.
507    pub fn can_funnel(&self) -> bool {
508        self.has_node_attr(Self::CAP_HTTPS) && self.has_node_attr(Self::NODE_ATTR_FUNNEL)
509    }
510
511    /// The capability control grants the **self** node when Taildrop is enabled for the tailnet (Go
512    /// `tailcfg.CapabilityFileSharing`). Gates [`Node::can_share_files`].
513    const CAP_FILE_SHARING: &'static str = "https://tailscale.com/cap/file-sharing";
514
515    /// The capability marking a **peer** as an explicit Taildrop send target even across owners (Go
516    /// `tailcfg.PeerCapabilityFileSharingTarget`). Checked by [`Node::is_file_sharing_target`].
517    const CAP_FILE_SHARING_TARGET: &'static str = "tailscale.com/cap/file-sharing-target";
518
519    /// Report whether this node may send Taildrop files — i.e. the admin has enabled file sharing for
520    /// the tailnet (Go `self.CapMap().Contains(CapabilityFileSharing)`). Applied to the **self** node
521    /// as the node-level gate in `FileTargets`; fail-closed when the cap is absent.
522    pub fn can_share_files(&self) -> bool {
523        self.has_node_attr(Self::CAP_FILE_SHARING)
524    }
525
526    /// Report whether this **peer** is an explicit Taildrop send target via ACL caps (Go
527    /// `PeerHasCap(p, PeerCapabilityFileSharingTarget)`) — the cross-owner path that lets a peer owned
528    /// by a different user still be a valid target.
529    pub fn is_file_sharing_target(&self) -> bool {
530        self.has_node_attr(Self::CAP_FILE_SHARING_TARGET)
531    }
532
533    /// Report whether `wanted_port` is allowed for Funnel on this node.
534    ///
535    /// Mirrors Go `ipn.CheckFunnelPort`: scan the cap-map keys for one prefixed by
536    /// `Node::CAP_FUNNEL_PORTS`, URL-parse that key, read its `ports` query parameter, and match
537    /// `wanted_port` against the comma-separated list of single ports and `first-last` ranges. The
538    /// port list lives in the *key*, never the value. Fail-closed: no matching cap, an empty or
539    /// unparseable `ports` query, or a key whose non-query part isn't exactly the funnel-ports URL
540    /// all deny.
541    pub fn check_funnel_port(&self, wanted_port: u16) -> bool {
542        // Extract the `ports=` list from the first cap-map key that is the funnel-ports URL with a
543        // non-empty `ports` query. Returns `None` (deny) if the key is unparseable, the query is
544        // missing/empty, or the URL (sans query) isn't exactly the funnel-ports cap.
545        let parse_attr = |attr: &str| -> Option<String> {
546            let mut url = url::Url::parse(attr).ok()?;
547            let ports = url
548                .query_pairs()
549                .find(|(k, _)| k == "ports")
550                .map(|(_, v)| v.into_owned())?;
551            if ports.is_empty() {
552                return None;
553            }
554            url.set_query(None);
555            // Go compares `u.String()` against the bare cap; `url`'s serializer keeps a trailing
556            // `/` only if present in the input, and the funnel-ports cap has none, so a direct
557            // string compare matches Go's behavior.
558            if url.as_str() != Self::CAP_FUNNEL_PORTS {
559                return None;
560            }
561            Some(ports)
562        };
563
564        let Some(ports_str) = self
565            .cap_map
566            .keys()
567            .filter(|attr| attr.starts_with(Self::CAP_FUNNEL_PORTS))
568            .find_map(|attr| parse_attr(attr))
569        else {
570            return false;
571        };
572
573        let wanted = wanted_port.to_string();
574        for ps in ports_str.split(',') {
575            if ps.is_empty() {
576                continue;
577            }
578            match ps.split_once('-') {
579                None => {
580                    if ps == wanted {
581                        return true;
582                    }
583                }
584                Some((first, last)) => {
585                    let (Ok(fp), Ok(lp)) = (first.parse::<u16>(), last.parse::<u16>()) else {
586                        continue;
587                    };
588                    if fp <= wanted_port && wanted_port <= lp {
589                        return true;
590                    }
591                }
592            }
593        }
594        false
595    }
596
597    /// Report whether this node is permitted to host Tailscale VIP services.
598    ///
599    /// Mirrors the Go grant model: possession of the `service-host`
600    /// ([`ts_control_serde::NODE_ATTR_SERVICE_HOST`]) node-capability **and** at least one assigned
601    /// VIP address. Go additionally requires the host to be tagged
602    /// (`ErrUntaggedServiceHost`); that tag gate is enforced at
603    /// `Device::listen_service` using [`Node::tags`]. Fail-closed: no cap
604    /// or no assigned VIP denies.
605    pub fn is_service_host(&self) -> bool {
606        self.has_node_attr(ts_control_serde::NODE_ATTR_SERVICE_HOST)
607            && !self.service_vips.is_empty()
608    }
609
610    /// The control-assigned VIP addresses for one named service (`svc:<label>`), or an empty slice
611    /// if this node does not host that service. This is the exact per-service mapping (so a
612    /// multi-service co-host binds the right VIP for each service).
613    pub fn service_addresses_for(&self, service: &str) -> &[IpAddr] {
614        self.service_vips
615            .get(service)
616            .map(Vec::as_slice)
617            .unwrap_or(&[])
618    }
619
620    /// The flattened, deduplicated set of every VIP address this node hosts across all services.
621    /// Used to widen the netstack's accepted-address set so any hosted-service listener is
622    /// reachable. Per-service binding uses [`Node::service_addresses_for`] instead.
623    pub fn service_addresses(&self) -> Vec<IpAddr> {
624        let mut seen = alloc::collections::BTreeSet::new();
625        let mut out = Vec::new();
626        for addr in self.service_vips.values().flatten() {
627            if seen.insert(*addr) {
628                out.push(*addr);
629            }
630        }
631        out
632    }
633}
634
635/// Validate a Tailscale VIP service name (`tailcfg.ServiceName.Validate`): it must carry the
636/// `svc:` prefix ([`ts_control_serde::SERVICE_NAME_PREFIX`]) followed by a valid DNS label
637/// (1–63 chars, ASCII alphanumeric or `-`, not starting/ending with `-`). Returns the bare label on
638/// success. Fail-closed: anything malformed is rejected so a listener can never bind for a bogus
639/// service name.
640pub fn validate_service_name(name: &str) -> Option<&str> {
641    let label = name.strip_prefix(ts_control_serde::SERVICE_NAME_PREFIX)?;
642    if label.is_empty() || label.len() > 63 {
643        return None;
644    }
645    if label.starts_with('-') || label.ends_with('-') {
646        return None;
647    }
648    if label
649        .bytes()
650        .all(|b| b.is_ascii_alphanumeric() || b == b'-')
651    {
652        Some(label)
653    } else {
654        None
655    }
656}
657
658/// Parse the per-service VIP map this node hosts from the `service-host` node-capability value(s).
659/// Each value is the raw JSON text of a [`ts_control_serde::ServiceIpMappings`] object (svc-name ->
660/// VIP IPs); unparseable values are skipped (fail-closed: a malformed mapping contributes no VIPs).
661/// Per-service IP lists are deduplicated, source order otherwise preserved.
662fn service_vips_from_cap_map(
663    cap_map: &NodeCapMap,
664) -> alloc::collections::BTreeMap<String, Vec<IpAddr>> {
665    let mut out: alloc::collections::BTreeMap<String, Vec<IpAddr>> =
666        alloc::collections::BTreeMap::new();
667    let Some(values) = cap_map.get(ts_control_serde::NODE_ATTR_SERVICE_HOST) else {
668        return out;
669    };
670
671    for raw in values {
672        let Ok(mappings) = serde_json::from_str::<ts_control_serde::ServiceIpMappings>(raw) else {
673            continue;
674        };
675        for (name, addrs) in &mappings.0 {
676            let entry = out.entry((*name).to_string()).or_default();
677            for addr in addrs {
678                if !entry.contains(addr) {
679                    entry.push(*addr);
680                }
681            }
682        }
683    }
684    out
685}
686
687/// Collect a wire ([`ts_control_serde`]) node cap map into an owned [`NodeCapMap`].
688///
689/// Keys are copied as owned strings; each value's raw JSON text is preserved verbatim. The wire map
690/// borrows from the decode buffer, so an owned copy is required to outlive it on the domain
691/// [`Node`].
692fn cap_map_from_serde(wire: &ts_nodecapability::Map<'_>) -> NodeCapMap {
693    wire.iter()
694        .map(|(&key, values)| {
695            let owned_values = values.0.iter().map(|v| v.get().to_owned()).collect();
696            (key.to_owned(), owned_values)
697        })
698        .collect()
699}
700
701/// Extract the advertised IPv4 peerAPI port and whether the explicit `peerapi-dns-proxy` service is
702/// advertised, from a peer's `HostInfo.Services` list.
703fn peerapi_from_services(
704    services: Option<&[ts_control_serde::Service<'_>]>,
705) -> (Option<u16>, bool) {
706    use ts_control_serde::ServiceProto;
707
708    let Some(services) = services else {
709        return (None, false);
710    };
711    let mut port = None;
712    let mut dns_proxy = false;
713    for svc in services {
714        match svc.proto {
715            ServiceProto::PeerApi4 => port = Some(svc.port),
716            ServiceProto::PeerApiDnsProxy => dns_proxy = true,
717            _ => {}
718        }
719    }
720    (port, dns_proxy)
721}
722
723/// Addresses for a node within a tailnet.
724#[derive(Debug, Clone, PartialEq, Eq, Hash)]
725pub struct TailnetAddress {
726    /// The IPv4 address of the node in the tailnet.
727    pub ipv4: ipnet::Ipv4Net,
728    /// The IPv6 address of the node in the tailnet.
729    pub ipv6: ipnet::Ipv6Net,
730}
731
732impl TailnetAddress {
733    /// Report whether `addr` matches either address in this [`TailnetAddress`].
734    pub fn contains(&self, addr: IpAddr) -> bool {
735        match addr {
736            IpAddr::V4(a) => self.ipv4.addr() == a,
737            IpAddr::V6(a) => self.ipv6.addr() == a,
738        }
739    }
740}
741
742impl From<&ts_control_serde::Node<'_>> for Node {
743    fn from(value: &ts_control_serde::Node) -> Self {
744        let fqdn_without_trailing_dot = value.name.strip_suffix('.').unwrap_or(&value.name);
745
746        let (hostname, tailnet) = match fqdn_without_trailing_dot.split_once('.') {
747            Some((hostname, tailnet)) => (hostname, Some(tailnet.to_owned())),
748            None => (fqdn_without_trailing_dot, None),
749        };
750
751        let (peerapi_port, peerapi_dns_proxy) =
752            peerapi_from_services(value.host_info.services.as_deref());
753
754        let cap_map = cap_map_from_serde(&value.cap_map);
755        let service_vips = service_vips_from_cap_map(&cap_map);
756
757        // `addresses` is a variable-length `Vec<IpNet>` on the wire (Go `[]netip.Prefix`), not a
758        // fixed (v4, v6) pair: an IPv6-off tailnet assigns only a v4 prefix. Pick the first of each
759        // family. The v4 prefix is the node's tailnet identity (always present on a normal node);
760        // if somehow absent we fall back to the unspecified `0.0.0.0/32` rather than panicking.
761        // The v6 prefix is optional — when the tailnet is IPv4-only there is none, and the overlay
762        // never reads `ipv6` in that mode (gated on `enable_ipv6`); we synthesize the unspecified
763        // `::/128` placeholder so the domain `TailnetAddress` stays infallible.
764        let ipv4 = value
765            .addresses
766            .iter()
767            .find_map(|p| match p {
768                ipnet::IpNet::V4(n) => Some(*n),
769                ipnet::IpNet::V6(_) => None,
770            })
771            .unwrap_or_else(|| ipnet::Ipv4Net::new(core::net::Ipv4Addr::UNSPECIFIED, 32).unwrap());
772        let ipv6 = value
773            .addresses
774            .iter()
775            .find_map(|p| match p {
776                ipnet::IpNet::V6(n) => Some(*n),
777                ipnet::IpNet::V4(_) => None,
778            })
779            .unwrap_or_else(|| ipnet::Ipv6Net::new(core::net::Ipv6Addr::UNSPECIFIED, 128).unwrap());
780
781        Self {
782            id: value.id,
783            stable_id: StableId(value.stable_id.0.to_string()),
784
785            hostname: hostname.to_owned(),
786            user_id: value.user,
787            tailnet,
788
789            tags: value
790                .tags
791                .as_ref()
792                .map(|x| x.iter().map(|x| x.to_string()).collect())
793                .unwrap_or_default(),
794
795            tailnet_address: TailnetAddress { ipv4, ipv6 },
796            node_key: value.key,
797            node_key_expiry: value.key_expiry,
798            online: value.online,
799            last_seen: value.last_seen,
800            key_signature: value.key_signature.to_vec(),
801            machine_key: value.machine,
802            disco_key: value.disco_key,
803
804            // Per capver-112, `AllowedIPs` null/absent means "same as `addresses`". Fall back to the
805            // node's own assigned prefixes verbatim (whatever families the wire carried), not a
806            // synthesized v4+v6 pair.
807            accepted_routes: value
808                .allowed_ips
809                .clone()
810                .unwrap_or_else(|| value.addresses.clone()),
811            underlay_addresses: value.endpoints.clone(),
812
813            // legacy_derp_string is still in practical use as of 3/2026
814            #[allow(deprecated)]
815            derp_region: value
816                .home_derp
817                .or(value.legacy_derp_string)
818                .or_else(|| value.host_info.net_info.as_ref()?.preferred_derp)
819                .map(|x| ts_derp::RegionId(x.into())),
820
821            cap: value.cap,
822            cap_map,
823            peerapi_port,
824            peerapi_dns_proxy,
825            is_wireguard_only: value.is_wireguard_only,
826            exit_node_dns_resolvers: value
827                .exit_node_dns_resolvers
828                .iter()
829                .filter_map(Resolver::from_serde)
830                .collect(),
831            peer_relay: value.host_info.peer_relay,
832            // Project the advertised SSH host keys (Go `Hostinfo.SSHHostKeys`), mapping the
833            // borrowed `Option<Vec<&str>>` to owned `Vec<String>`; absent ⇒ empty (never
834            // fabricated), matching how `services`/`peer_relay` above are projected from host_info.
835            ssh_host_keys: value
836                .host_info
837                .ssh_host_keys
838                .as_ref()
839                .map(|keys| keys.iter().map(|k| k.to_string()).collect())
840                .unwrap_or_default(),
841            service_vips,
842        }
843    }
844}
845
846/// An incremental update to a single already-known peer [`Node`], carried in
847/// [`MapResponse::peers_changed_patch`][ts_control_serde::MapResponse::peers_changed_patch].
848///
849/// Control sends a patch (rather than a full node in `peers_changed`) when only a peer's
850/// reachability changes mid-session — most importantly its UDP `endpoints`
851/// and home [`derp_region`][PeerChange::derp_region] when an idle peer re-establishes connectivity.
852/// Every field is `Option`: a patch sets only the fields it carries and leaves the rest of the
853/// target node unchanged (see `PeerTracker::apply_peer_update` for the merge). Owned counterpart
854/// of the borrow-bound [`ts_control_serde::PeerChange`]; the fields that map onto a domain
855/// [`Node`] field are retained, including control's `online`/`last_seen` liveness deltas — the
856/// dominant channel by which peer online transitions are delivered (see [`Node::online`]).
857#[derive(Debug, Clone, PartialEq, Eq)]
858pub struct PeerChange {
859    /// The [`Node::id`] of the peer being mutated. If no peer with this id is in the current
860    /// netmap, the patch is ignored (the wire contract — a patch never creates a node).
861    pub id: Id,
862    /// If `Some`, the peer's new home DERP region.
863    pub derp_region: Option<ts_derp::RegionId>,
864    /// If `Some`, the peer's new advertised capability version.
865    pub cap: Option<CapabilityVersion>,
866    /// If `Some`, the peer's new capability map (replaces the prior map wholesale).
867    pub cap_map: Option<NodeCapMap>,
868    /// If `Some`, the peer's new UDP underlay endpoints (`Endpoints` in Go; replaces the prior
869    /// set). This is the field that lets magicsock re-handshake a peer that moved.
870    pub underlay_addresses: Option<Vec<SocketAddr>>,
871    /// If `Some`, the peer's new WireGuard public key (key rotation).
872    pub node_key: Option<NodePublicKey>,
873    /// If `Some`, the marshalled TKA signature over the new node key. Re-verified at the
874    /// peer-trust chokepoint when tailnet-lock enforcement is active.
875    pub key_signature: Option<Vec<u8>>,
876    /// If `Some`, the peer's new disco public key.
877    pub disco_key: Option<DiscoPublicKey>,
878    /// If `Some`, the peer's new node-key expiry (`KeyExpiry` in Go). Maps to
879    /// [`Node::node_key_expiry`]; carried so an expiry-only patch isn't lost until the next full
880    /// resync.
881    pub node_key_expiry: Option<DateTime<Utc>>,
882    /// If `Some`, the peer's new online status (`PeerChange.Online`). `None` here means "this patch
883    /// did not touch online", **not** "offline" — the merge sets [`Node::online`] only when present.
884    pub online: Option<bool>,
885    /// If `Some`, the peer's new last-seen time (`PeerChange.LastSeen`). Maps to [`Node::last_seen`].
886    pub last_seen: Option<DateTime<Utc>>,
887}
888
889impl From<&ts_control_serde::PeerChange<'_>> for PeerChange {
890    fn from(value: &ts_control_serde::PeerChange) -> Self {
891        Self {
892            id: value.node_id,
893            derp_region: value.derp_region.map(|x| ts_derp::RegionId(x.into())),
894            cap: value.cap,
895            cap_map: value.cap_map.as_ref().map(cap_map_from_serde),
896            underlay_addresses: value.endpoints.clone(),
897            node_key: value.key,
898            key_signature: value.key_signature.map(|s| s.to_vec()),
899            disco_key: value.disco_key,
900            node_key_expiry: value.key_expiry,
901            online: value.online,
902            last_seen: value.last_seen,
903        }
904    }
905}
906
907/// Display-friendly identity for the user that owns a [`Node`], resolved from the netmap's
908/// `UserProfiles` table (Go `tailcfg.UserProfile`). Owned counterpart of the borrow-bound
909/// [`ts_control_serde::UserProfile`]. Keyed by [`UserProfile::id`] (== [`Node::user_id`]).
910#[derive(Debug, Clone, PartialEq, Eq)]
911pub struct UserProfile {
912    /// The integer id of the Tailscale user this profile describes (matches [`Node::user_id`]).
913    pub id: ts_control_serde::UserId,
914    /// An email-ish login name for display (e.g. `alice@example.com` / `alice@github`). May be
915    /// empty if control sent none.
916    pub login_name: String,
917    /// The user's display name (e.g. `Alice Smith`), if the IdP provided one.
918    pub display_name: Option<String>,
919}
920
921impl From<&ts_control_serde::UserProfile<'_>> for UserProfile {
922    fn from(value: &ts_control_serde::UserProfile) -> Self {
923        Self {
924            id: value.id,
925            login_name: value.login_name.to_string(),
926            display_name: value.display_name.as_deref().map(str::to_string),
927        }
928    }
929}
930
931impl UserProfile {
932    /// The best human-facing label for this user: the login name when present, else the display
933    /// name, else `None`. This is what a `WhoIs` surfaces as the owning user.
934    pub fn best_label(&self) -> Option<String> {
935        if !self.login_name.is_empty() {
936            Some(self.login_name.clone())
937        } else {
938            self.display_name.clone()
939        }
940    }
941}
942
943#[cfg(test)]
944mod tests {
945    use super::*;
946
947    /// The wire `Node.User` id must be carried onto the domain `Node.user_id` by the `From` impl
948    /// (the field the runtime joins against the netmap `UserProfiles` table for `WhoIs.user`).
949    /// Guards against the `From` impl wiring the wrong serde field or dropping it.
950    #[test]
951    fn from_wire_node_carries_user_id() {
952        let mut wire = ts_control_serde::Node {
953            user: 4242,
954            ..Default::default()
955        };
956        wire.name = "host.tail.ts.net.".into();
957        let domain: Node = (&wire).into();
958        assert_eq!(domain.user_id, 4242);
959
960        // Default (no owner / tagged node) stays 0.
961        let tagged = ts_control_serde::Node::default();
962        assert_eq!(Node::from(&tagged).user_id, 0);
963    }
964
965    /// The wire `Hostinfo.sshHostKeys` must be projected onto the domain `Node.ssh_host_keys`
966    /// (the field `tailscale ssh` reads via `StatusNode` to pin a peer's host key). Present →
967    /// carried verbatim; absent → empty (never fabricated).
968    #[test]
969    fn from_wire_node_carries_ssh_host_keys() {
970        let wire = ts_control_serde::Node {
971            host_info: ts_control_serde::HostInfo {
972                ssh_host_keys: Some(vec![
973                    "ssh-ed25519 AAAAC3Nz host",
974                    "ecdsa-sha2-nistp256 AAAAE2Vj host",
975                ]),
976                ..Default::default()
977            },
978            ..Default::default()
979        };
980        let domain: Node = (&wire).into();
981        assert_eq!(
982            domain.ssh_host_keys,
983            vec![
984                "ssh-ed25519 AAAAC3Nz host".to_string(),
985                "ecdsa-sha2-nistp256 AAAAE2Vj host".to_string(),
986            ]
987        );
988
989        // Absent on the wire → empty Vec, not fabricated.
990        let bare = ts_control_serde::Node::default();
991        assert!(Node::from(&bare).ssh_host_keys.is_empty());
992    }
993
994    /// A node from an **IPv4-only** tailnet (IPv6-off control plane / Headscale) carries a
995    /// single-element `addresses` list. This used to fail deserialization ("invalid length 1,
996    /// expected a tuple of size 2") when `addresses` was a fixed 2-tuple; it must now parse and
997    /// derive the v4 identity, with the unused v6 a synthesized placeholder.
998    #[test]
999    fn from_wire_node_ipv4_only_addresses() {
1000        let wire = ts_control_serde::Node {
1001            addresses: vec!["100.64.0.5/32".parse().unwrap()],
1002            ..Default::default()
1003        };
1004        let domain: Node = (&wire).into();
1005        assert_eq!(
1006            domain.tailnet_address.ipv4,
1007            "100.64.0.5/32".parse().unwrap()
1008        );
1009        // No v6 on the wire → unspecified placeholder (never read in IPv4-only mode).
1010        assert_eq!(
1011            domain.tailnet_address.ipv6,
1012            ipnet::Ipv6Net::new(core::net::Ipv6Addr::UNSPECIFIED, 128).unwrap()
1013        );
1014        // AllowedIPs absent → falls back to the node's own assigned prefixes (just the v4 here).
1015        assert_eq!(
1016            domain.accepted_routes,
1017            vec!["100.64.0.5/32".parse::<ipnet::IpNet>().unwrap()]
1018        );
1019    }
1020
1021    /// A dual-stack node carries both families (any order); the domain picks the first of each.
1022    #[test]
1023    fn from_wire_node_dual_stack_addresses() {
1024        let wire = ts_control_serde::Node {
1025            addresses: vec![
1026                "100.64.0.7/32".parse().unwrap(),
1027                "fd7a:115c:a1e0::7/128".parse().unwrap(),
1028            ],
1029            ..Default::default()
1030        };
1031        let domain: Node = (&wire).into();
1032        assert_eq!(
1033            domain.tailnet_address.ipv4,
1034            "100.64.0.7/32".parse().unwrap()
1035        );
1036        assert_eq!(
1037            domain.tailnet_address.ipv6,
1038            "fd7a:115c:a1e0::7/128".parse().unwrap()
1039        );
1040    }
1041
1042    /// The deserialization regression itself: a MapResponse-style Node JSON with a 1-element
1043    /// `Addresses` array must parse (this is the exact shape the dev-Headscale sends).
1044    #[test]
1045    fn deserialize_node_with_single_address() {
1046        let json = r#"{
1047            "ID": 1,
1048            "StableID": "n1",
1049            "Name": "host.tail.ts.net.",
1050            "User": 1,
1051            "Addresses": ["100.64.0.9/32"],
1052            "Key": "nodekey:0000000000000000000000000000000000000000000000000000000000000000",
1053            "Machine": null,
1054            "DiscoKey": null,
1055            "AllowedIPs": null,
1056            "Endpoints": []
1057        }"#;
1058        let wire: ts_control_serde::Node = serde_json::from_str(json).expect("1-addr node parses");
1059        assert_eq!(wire.addresses.len(), 1);
1060        let domain: Node = (&wire).into();
1061        assert_eq!(
1062            domain.tailnet_address.ipv4,
1063            "100.64.0.9/32".parse().unwrap()
1064        );
1065    }
1066
1067    #[test]
1068    fn key_expiry_semantics() {
1069        let now: DateTime<Utc> = "2026-06-05T00:00:00Z".parse().unwrap();
1070        let past: DateTime<Utc> = "2020-01-01T00:00:00Z".parse().unwrap();
1071        let future: DateTime<Utc> = "2099-01-01T00:00:00Z".parse().unwrap();
1072
1073        let mut n = node("h", Some("t.ts.net"));
1074
1075        // No expiry set => never expired (Go zero-value semantics).
1076        n.node_key_expiry = None;
1077        assert!(!n.key_expired(now));
1078        assert_eq!(n.key_expiry(), None);
1079
1080        // Future expiry => not yet expired.
1081        n.node_key_expiry = Some(future);
1082        assert!(!n.key_expired(now));
1083        assert_eq!(n.key_expiry(), Some(future));
1084
1085        // Past expiry => expired.
1086        n.node_key_expiry = Some(past);
1087        assert!(n.key_expired(now));
1088    }
1089
1090    #[test]
1091    fn key_expiry_unix_agrees_with_chrono() {
1092        // The chrono-free variants (`key_expired_at_unix` / `key_expiry_unix`) must agree with the
1093        // chrono variants for the same none/future/past cases (Unix seconds of the same instants).
1094        let now: DateTime<Utc> = "2026-06-05T00:00:00Z".parse().unwrap();
1095        let past: DateTime<Utc> = "2020-01-01T00:00:00Z".parse().unwrap();
1096        let future: DateTime<Utc> = "2099-01-01T00:00:00Z".parse().unwrap();
1097        let now_unix = now.timestamp();
1098
1099        let mut n = node("h", Some("t.ts.net"));
1100
1101        // No expiry => never expired; the unix accessor reports `None`.
1102        n.node_key_expiry = None;
1103        assert_eq!(n.key_expired(now), n.key_expired_at_unix(now_unix));
1104        assert!(!n.key_expired_at_unix(now_unix));
1105        assert_eq!(n.key_expiry_unix(), None);
1106
1107        // Future expiry => not yet expired; unix accessor matches the chrono timestamp.
1108        n.node_key_expiry = Some(future);
1109        assert_eq!(n.key_expired(now), n.key_expired_at_unix(now_unix));
1110        assert!(!n.key_expired_at_unix(now_unix));
1111        assert_eq!(n.key_expiry_unix(), Some(future.timestamp()));
1112
1113        // Past expiry => expired; unix accessor matches the chrono timestamp.
1114        n.node_key_expiry = Some(past);
1115        assert_eq!(n.key_expired(now), n.key_expired_at_unix(now_unix));
1116        assert!(n.key_expired_at_unix(now_unix));
1117        assert_eq!(n.key_expiry_unix(), Some(past.timestamp()));
1118    }
1119
1120    #[test]
1121    fn key_expiry_boundary_is_not_expired() {
1122        // A key whose expiry exactly equals `now` is NOT expired: the code uses strict `<`, matching
1123        // Go's `Before`. Both the chrono and chrono-free variants must agree at the boundary.
1124        let now: DateTime<Utc> = "2026-06-05T00:00:00Z".parse().unwrap();
1125        let now_unix = now.timestamp();
1126
1127        let mut n = node("h", Some("t.ts.net"));
1128        n.node_key_expiry = Some(now);
1129
1130        assert!(!n.key_expired(now));
1131        assert!(!n.key_expired_at_unix(now_unix));
1132    }
1133
1134    #[test]
1135    fn is_peer_relay_returns_field() {
1136        let mut n = node("h", Some("t.ts.net"));
1137
1138        n.peer_relay = true;
1139        assert!(n.is_peer_relay());
1140
1141        n.peer_relay = false;
1142        assert!(!n.is_peer_relay());
1143    }
1144
1145    fn node(hostname: &str, tailnet: Option<&str>) -> Node {
1146        Node {
1147            id: 1,
1148            stable_id: StableId("n1".to_string()),
1149            hostname: hostname.to_string(),
1150            user_id: 0,
1151            tailnet: tailnet.map(str::to_string),
1152            tags: vec![],
1153            tailnet_address: TailnetAddress {
1154                ipv4: "100.64.0.1/32".parse().unwrap(),
1155                ipv6: "fd7a::1/128".parse().unwrap(),
1156            },
1157            node_key: [0u8; 32].into(),
1158            node_key_expiry: None,
1159            online: None,
1160            last_seen: None,
1161            key_signature: vec![],
1162            machine_key: None,
1163            disco_key: None,
1164            accepted_routes: vec![],
1165            underlay_addresses: vec![],
1166            derp_region: None,
1167            cap: CapabilityVersion::default(),
1168            cap_map: NodeCapMap::new(),
1169            peerapi_port: None,
1170            peerapi_dns_proxy: false,
1171            is_wireguard_only: false,
1172            exit_node_dns_resolvers: vec![],
1173            peer_relay: false,
1174            ssh_host_keys: vec![],
1175            service_vips: Default::default(),
1176        }
1177    }
1178
1179    #[test]
1180    fn matches_name_is_case_and_trailing_dot_insensitive() {
1181        let n = node("MyHost", Some("tail-scale.ts.net"));
1182
1183        // bare hostname, any case
1184        assert!(n.matches_name("myhost"));
1185        assert!(n.matches_name("MYHOST"));
1186        assert!(n.matches_name("MyHost"));
1187
1188        // fqdn, any case, with and without trailing dot
1189        assert!(n.matches_name("myhost.tail-scale.ts.net"));
1190        assert!(n.matches_name("MYHOST.TAIL-SCALE.TS.NET"));
1191        assert!(n.matches_name("myhost.tail-scale.ts.net."));
1192        assert!(n.matches_name("MyHost.Tail-Scale.TS.NET."));
1193
1194        // wrong host / wrong tailnet must not match
1195        assert!(!n.matches_name("other"));
1196        assert!(!n.matches_name("myhost.other.ts.net"));
1197    }
1198
1199    #[test]
1200    fn matches_name_no_tailnet() {
1201        let n = node("solo", None);
1202        assert!(n.matches_name("solo"));
1203        assert!(n.matches_name("SOLO."));
1204        assert!(!n.matches_name("solo.ts.net"));
1205    }
1206
1207    #[test]
1208    fn is_tailscale_ip_ranges() {
1209        // CGNAT v4
1210        assert!(is_tailscale_ip("100.64.0.1".parse().unwrap()));
1211        assert!(is_tailscale_ip("100.127.255.254".parse().unwrap()));
1212        // ChromeOS carve-out is excluded
1213        assert!(!is_tailscale_ip("100.115.92.5".parse().unwrap()));
1214        // outside CGNAT
1215        assert!(!is_tailscale_ip("10.0.0.1".parse().unwrap()));
1216        assert!(!is_tailscale_ip("100.128.0.1".parse().unwrap()));
1217        // Tailscale ULA v6
1218        assert!(is_tailscale_ip("fd7a:115c:a1e0::1".parse().unwrap()));
1219        assert!(!is_tailscale_ip("fd00::1".parse().unwrap()));
1220    }
1221
1222    /// Taildrop SSRF guard (defense-in-depth). `Device::send_file` rejects an upload destination
1223    /// unless `is_tailscale_ip(peer.peerapi_addr().ip())` holds. `Device::send_file` itself needs a
1224    /// live runtime (it goes through `self.channel()`), so it can't be unit-tested here; instead we
1225    /// test the exact composition the guard relies on — `is_tailscale_ip ∘ peerapi_addr` — against a
1226    /// `Node` whose `tailnet_address.ipv4` has been corrupted to a non-CGNAT (public) address. A
1227    /// well-formed peer always has a CGNAT 100.64.0.0/10 address, but the guard exists to catch a
1228    /// malformed/hostile node; this proves it would reject one.
1229    #[test]
1230    fn taildrop_ssrf_guard_rejects_non_cgnat_peerapi_addr() {
1231        let mut n = node("evil", Some("ts.net"));
1232        // Corrupt the peer to a public, non-CGNAT address and advertise a peerAPI port so
1233        // `peerapi_addr` returns `Some(_)`.
1234        n.tailnet_address.ipv4 = "1.2.3.4/32".parse().unwrap();
1235        n.peerapi_port = Some(443);
1236
1237        let addr = n
1238            .peerapi_addr()
1239            .expect("peerapi_addr yields Some with a port set");
1240        assert_eq!(addr.ip(), Ipv4Addr::new(1, 2, 3, 4));
1241        // The guard `if !is_tailscale_ip(dst.ip()) { return Err(BadRequest) }` WOULD reject this.
1242        assert!(
1243            !is_tailscale_ip(addr.ip()),
1244            "SSRF guard must reject a peer whose peerAPI addr is not a Tailscale CGNAT IP"
1245        );
1246
1247        // Conversely, a well-formed CGNAT peer passes the guard.
1248        let mut good = node("friend", Some("ts.net"));
1249        good.peerapi_port = Some(443);
1250        let good_addr = good.peerapi_addr().expect("peerapi_addr yields Some");
1251        assert!(is_tailscale_ip(good_addr.ip()));
1252    }
1253
1254    /// Ported from upstream's `TestNodeIsRouter` (`tailcfg/tailcfg_test.go`, `8d830599b`): a node
1255    /// is a router exactly when its `AllowedIPs` reach past its own `Addresses`. The absent case
1256    /// (a plain node advertising only its own addresses) is asserted alongside the present one,
1257    /// since "no routes besides my own" is the answer that must not drift.
1258    #[test]
1259    fn is_router_reports_routes_beyond_own_addresses() {
1260        let v4: ipnet::Ipv4Net = "100.64.0.1/32".parse().unwrap();
1261        let v6: ipnet::Ipv6Net = "fd7a:115c:a1e0::1/128".parse().unwrap();
1262        let self4 = ipnet::IpNet::V4(v4);
1263        let self6 = ipnet::IpNet::V6(v6);
1264
1265        let cases: &[(&str, Vec<ipnet::IpNet>, bool)] = &[
1266            ("empty", vec![], false),
1267            ("plain-ipv4", vec![self4], false),
1268            ("plain-ipv6", vec![self6], false),
1269            ("plain-ipv4-ipv6", vec![self4, self6], false),
1270            ("duplicates", vec![self4, self4], false),
1271            (
1272                "exit-node-ipv4",
1273                vec![self4, "0.0.0.0/0".parse().unwrap()],
1274                true,
1275            ),
1276            ("exit-node-ipv6", vec![self6, "::/0".parse().unwrap()], true),
1277            (
1278                "exit-node-ipv4-ipv6",
1279                vec![
1280                    self4,
1281                    self6,
1282                    "0.0.0.0/0".parse().unwrap(),
1283                    "::/0".parse().unwrap(),
1284                ],
1285                true,
1286            ),
1287            (
1288                "subnet-router-ipv4",
1289                vec![self4, "192.0.2.0/24".parse().unwrap()],
1290                true,
1291            ),
1292            (
1293                "subnet-router-ipv6",
1294                vec![self6, "2001:db8::/32".parse().unwrap()],
1295                true,
1296            ),
1297            (
1298                "subnet-router-ipv4-ipv6",
1299                vec![
1300                    self4,
1301                    self6,
1302                    "192.0.2.0/24".parse().unwrap(),
1303                    "2001:db8::/32".parse().unwrap(),
1304                ],
1305                true,
1306            ),
1307            // Go's `IsRouter` has no Tailscale-range exception: another peer's /32 is still a
1308            // routed address. This is where it parts ways with `is_subnet_route`.
1309            (
1310                "other-tailnet-host",
1311                vec![self4, "100.64.5.5/32".parse().unwrap()],
1312                true,
1313            ),
1314        ];
1315
1316        for (name, allowed, want) in cases {
1317            let mut n = node("host", Some("ts.net"));
1318            n.tailnet_address = TailnetAddress { ipv4: v4, ipv6: v6 };
1319            n.accepted_routes = allowed.clone();
1320            assert_eq!(n.is_router(), *want, "{name}");
1321        }
1322    }
1323
1324    #[test]
1325    fn is_subnet_route_distinguishes_self_from_subnet() {
1326        let n = node("host", Some("ts.net"));
1327
1328        // The node's own /32 and /128 are self-addresses, not subnet routes.
1329        assert!(!n.is_subnet_route(&"100.64.0.1/32".parse().unwrap()));
1330        assert!(!n.is_subnet_route(&"fd7a::1/128".parse().unwrap()));
1331        // A different single Tailscale IP is still a self-address (Tailscale-assigned host).
1332        assert!(!n.is_subnet_route(&"100.64.5.5/32".parse().unwrap()));
1333        // A LAN /24 the node advertises is a subnet route.
1334        assert!(n.is_subnet_route(&"192.168.1.0/24".parse().unwrap()));
1335        // A single non-Tailscale host IP counts as a subnet route.
1336        assert!(n.is_subnet_route(&"8.8.8.8/32".parse().unwrap()));
1337        // The default route is treated as a subnet route.
1338        assert!(n.is_subnet_route(&"0.0.0.0/0".parse().unwrap()));
1339        assert!(n.is_subnet_route(&"::/0".parse().unwrap()));
1340    }
1341
1342    #[test]
1343    fn routes_to_install_gates_subnets_on_accept_routes() {
1344        let mut n = node("host", Some("ts.net"));
1345        let self4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
1346        let self6: ipnet::IpNet = "fd7a::1/128".parse().unwrap();
1347        let subnet: ipnet::IpNet = "192.168.1.0/24".parse().unwrap();
1348        n.accepted_routes = vec![self4, self6, subnet];
1349
1350        // accept_routes off: only the self addresses are installed.
1351        let off: Vec<_> = n.routes_to_install(false, None).copied().collect();
1352        assert_eq!(off, vec![self4, self6]);
1353
1354        // accept_routes on: the advertised subnet is installed too.
1355        let on: Vec<_> = n.routes_to_install(true, None).copied().collect();
1356        assert_eq!(on, vec![self4, self6, subnet]);
1357    }
1358
1359    #[test]
1360    fn routes_to_install_default_route_only_for_selected_exit_node() {
1361        let mut n = node("host", Some("ts.net"));
1362        n.stable_id = StableId("exit1".to_string());
1363        let self4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
1364        let default4: ipnet::IpNet = "0.0.0.0/0".parse().unwrap();
1365        let default6: ipnet::IpNet = "::/0".parse().unwrap();
1366        n.accepted_routes = vec![self4, default4, default6];
1367
1368        // No exit node selected: default routes are excluded even with accept_routes on
1369        // (fail-closed — internet-bound traffic has no overlay route and is dropped).
1370        let none_off: Vec<_> = n.routes_to_install(false, None).copied().collect();
1371        assert_eq!(none_off, vec![self4]);
1372        let none_on: Vec<_> = n.routes_to_install(true, None).copied().collect();
1373        assert_eq!(none_on, vec![self4]);
1374
1375        // A *different* peer selected as exit node: this peer still gets no default route.
1376        let other = StableId("exit2".to_string());
1377        let other_sel: Vec<_> = n.routes_to_install(false, Some(&other)).copied().collect();
1378        assert_eq!(other_sel, vec![self4]);
1379
1380        // This peer selected as the exit node: its default routes are installed.
1381        let me = StableId("exit1".to_string());
1382        let sel: Vec<_> = n.routes_to_install(false, Some(&me)).copied().collect();
1383        assert_eq!(sel, vec![self4, default4, default6]);
1384    }
1385
1386    fn exit_node_with(id: &str, ipv4: &str, hostname: &str, tailnet: Option<&str>) -> Node {
1387        let mut n = node(hostname, tailnet);
1388        n.stable_id = StableId(id.to_string());
1389        n.tailnet_address.ipv4 = format!("{ipv4}/32").parse().unwrap();
1390        n
1391    }
1392
1393    #[test]
1394    fn exit_node_selector_resolves_by_id_ip_and_name() {
1395        let a = exit_node_with("nA", "100.64.0.5", "alpha", Some("ts.net"));
1396        let b = exit_node_with("nB", "100.64.0.6", "beta", Some("ts.net"));
1397        let peers = [a, b];
1398        let it = || peers.iter();
1399
1400        // By stable id.
1401        assert_eq!(
1402            ExitNodeSelector::StableId(StableId("nB".into())).resolve(it()),
1403            Some(StableId("nB".into()))
1404        );
1405        // By tailnet IP.
1406        assert_eq!(
1407            ExitNodeSelector::Ip("100.64.0.5".parse().unwrap()).resolve(it()),
1408            Some(StableId("nA".into()))
1409        );
1410        // By MagicDNS name (fqdn, case-insensitive).
1411        assert_eq!(
1412            ExitNodeSelector::Name("BETA.ts.net".into()).resolve(it()),
1413            Some(StableId("nB".into()))
1414        );
1415        // By bare hostname.
1416        assert_eq!(
1417            ExitNodeSelector::Name("alpha".into()).resolve(it()),
1418            Some(StableId("nA".into()))
1419        );
1420        // Unresolvable selector => None (fail-closed at the call site).
1421        assert_eq!(
1422            ExitNodeSelector::Ip("100.64.0.99".parse().unwrap()).resolve(it()),
1423            None
1424        );
1425        assert_eq!(ExitNodeSelector::Name("ghost".into()).resolve(it()), None);
1426    }
1427
1428    #[test]
1429    fn exit_node_selector_resolution_is_deterministic_on_ties() {
1430        // Two peers sharing a name (transient netmap state): the smallest stable id wins, so the
1431        // outbound table and inbound source filter — which resolve independently — agree.
1432        let a = exit_node_with("nZ", "100.64.0.5", "dup", Some("ts.net"));
1433        let b = exit_node_with("nA", "100.64.0.6", "dup", Some("ts.net"));
1434        let peers = [a, b];
1435
1436        assert_eq!(
1437            ExitNodeSelector::Name("dup".into()).resolve(peers.iter()),
1438            Some(StableId("nA".into())),
1439            "smallest stable id wins the tie"
1440        );
1441        // Order of iteration must not change the result.
1442        assert_eq!(
1443            ExitNodeSelector::Name("dup".into()).resolve(peers.iter().rev()),
1444            Some(StableId("nA".into()))
1445        );
1446    }
1447
1448    #[test]
1449    fn peerapi_doh_url_requires_port_and_capability() {
1450        let mut n = node("exit", Some("ts.net"));
1451        n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1452
1453        // No peerAPI port advertised: cannot proxy DNS.
1454        n.peerapi_port = None;
1455        n.cap = CapabilityVersion::V130;
1456        assert_eq!(n.peerapi_doh_url(), None);
1457
1458        // Port advertised but capability too old and no explicit service: cannot proxy.
1459        n.peerapi_port = Some(8080);
1460        n.cap = CapabilityVersion::V25;
1461        n.peerapi_dns_proxy = false;
1462        assert_eq!(n.peerapi_doh_url(), None);
1463
1464        // Port + new-enough capability: yields the DoH URL on the IPv4 address.
1465        n.cap = CapabilityVersion::V26;
1466        assert_eq!(
1467            n.peerapi_doh_url().as_deref(),
1468            Some("http://100.64.0.5:8080/dns-query")
1469        );
1470
1471        // Port + explicit peerapi-dns-proxy service, even with an old capability.
1472        n.cap = CapabilityVersion::V25;
1473        n.peerapi_dns_proxy = true;
1474        assert_eq!(
1475            n.peerapi_doh_url().as_deref(),
1476            Some("http://100.64.0.5:8080/dns-query")
1477        );
1478
1479        // WireGuard-only peers never run a peerAPI: no DoH URL even with a port.
1480        n.is_wireguard_only = true;
1481        assert_eq!(n.peerapi_doh_url(), None);
1482    }
1483
1484    #[test]
1485    fn peerapi_doh_addr_matches_url_gate() {
1486        let mut n = node("exit", Some("ts.net"));
1487        n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1488        n.peerapi_port = Some(8080);
1489        n.cap = CapabilityVersion::V26;
1490
1491        // The addr form the DoH client dials is the same gated endpoint as the URL.
1492        assert_eq!(
1493            n.peerapi_doh_addr(),
1494            Some("100.64.0.5:8080".parse().unwrap())
1495        );
1496        // And it composes into exactly the URL form.
1497        assert_eq!(
1498            n.peerapi_doh_url().as_deref(),
1499            Some("http://100.64.0.5:8080/dns-query")
1500        );
1501
1502        // Gated off the same way: no port => no addr.
1503        n.peerapi_port = None;
1504        assert_eq!(n.peerapi_doh_addr(), None);
1505    }
1506
1507    #[test]
1508    fn peerapi_addr_returns_addr_when_advertised() {
1509        let mut n = node("peer", Some("ts.net"));
1510        n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1511        n.peerapi_port = Some(8089);
1512
1513        // Not gated on the DNS-proxy capability: a plain advertised peerAPI port is enough.
1514        assert_eq!(n.peerapi_addr(), Some("100.64.0.5:8089".parse().unwrap()));
1515    }
1516
1517    #[test]
1518    fn peerapi_addr_none_when_no_port() {
1519        let mut n = node("peer", Some("ts.net"));
1520        n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1521        n.peerapi_port = None;
1522
1523        assert_eq!(n.peerapi_addr(), None);
1524    }
1525
1526    #[test]
1527    fn peerapi_addr_none_for_wireguard_only() {
1528        let mut n = node("peer", Some("ts.net"));
1529        n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1530        n.peerapi_port = Some(8089);
1531        n.is_wireguard_only = true;
1532
1533        // WireGuard-only peers run no peerAPI, even with a port set.
1534        assert_eq!(n.peerapi_addr(), None);
1535    }
1536
1537    #[test]
1538    fn can_share_files_gated_on_self_capability() {
1539        let mut n = node("self", Some("ts.net"));
1540        assert!(
1541            !n.can_share_files(),
1542            "no cap → file sharing not enabled (fail-closed)"
1543        );
1544        n.cap_map
1545            .insert("https://tailscale.com/cap/file-sharing".to_string(), vec![]);
1546        assert!(n.can_share_files(), "the file-sharing cap enables it");
1547    }
1548
1549    #[test]
1550    fn is_file_sharing_target_gated_on_peer_capability() {
1551        let mut n = node("peer", Some("ts.net"));
1552        assert!(
1553            !n.is_file_sharing_target(),
1554            "no cap → not an explicit target"
1555        );
1556        n.cap_map
1557            .insert("tailscale.com/cap/file-sharing-target".to_string(), vec![]);
1558        assert!(
1559            n.is_file_sharing_target(),
1560            "the file-sharing-target cap marks a cross-owner target"
1561        );
1562    }
1563
1564    #[test]
1565    fn peerapi_from_services_extracts_v4_port_and_dns_proxy_flag() {
1566        use ts_control_serde::{Service, ServiceProto};
1567
1568        let services = [
1569            Service {
1570                proto: ServiceProto::PeerApi4,
1571                port: 8080,
1572                description: "peerapi".into(),
1573            },
1574            Service {
1575                proto: ServiceProto::PeerApi6,
1576                port: 9090,
1577                description: "peerapi6".into(),
1578            },
1579            Service {
1580                proto: ServiceProto::PeerApiDnsProxy,
1581                port: 1,
1582                description: "dns".into(),
1583            },
1584        ];
1585        let (port, dns_proxy) = peerapi_from_services(Some(&services));
1586        assert_eq!(port, Some(8080), "only the IPv4 peerAPI port is taken");
1587        assert!(dns_proxy);
1588
1589        // No services at all.
1590        assert_eq!(peerapi_from_services(None), (None, false));
1591    }
1592
1593    #[test]
1594    fn exit_node_selector_parses_ip_vs_name() {
1595        assert_eq!(
1596            "100.64.0.5".parse::<ExitNodeSelector>().unwrap(),
1597            ExitNodeSelector::Ip("100.64.0.5".parse().unwrap())
1598        );
1599        assert_eq!(
1600            "fd7a::5".parse::<ExitNodeSelector>().unwrap(),
1601            ExitNodeSelector::Ip("fd7a::5".parse().unwrap())
1602        );
1603        assert_eq!(
1604            "my-exit.ts.net".parse::<ExitNodeSelector>().unwrap(),
1605            ExitNodeSelector::Name("my-exit.ts.net".into())
1606        );
1607    }
1608}