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