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    /// Marshalled TKA node-key signature (`tailcfg.Node.KeySignature`); empty when control sends
153    /// none. Verified against a TKA `Authority` at the peer-trust chokepoint WHEN tailnet-lock
154    /// enforcement is active.
155    pub key_signature: Vec<u8>,
156
157    /// The node's [`MachinePublicKey`], if known.
158    pub machine_key: Option<MachinePublicKey>,
159    /// The node's [`DiscoPublicKey`], if known.
160    pub disco_key: Option<DiscoPublicKey>,
161
162    /// The routes this node accepts traffic for.
163    pub accepted_routes: Vec<ipnet::IpNet>,
164    /// The underlay addresses this node is reachable on (`Endpoints` in Go).
165    pub underlay_addresses: Vec<SocketAddr>,
166
167    /// The DERP region for this node, if known.
168    pub derp_region: Option<ts_derp::RegionId>,
169
170    /// This node's advertised capability version (`Node.Cap` in Go). Old control servers may not
171    /// send it, in which case it defaults to [`CapabilityVersion::default`]. Used to gate features
172    /// that require a minimum peer capability, e.g. exit-node DNS proxying (`peerCanProxyDNS`).
173    pub cap: CapabilityVersion,
174
175    /// This node's capability map (`Node.CapMap` in Go). Keys are capability names/URLs; values are
176    /// the raw JSON argument blobs (often empty). Threaded from the wire
177    /// ([`ts_control_serde::Node::cap_map`]) as an owned copy. Used to gate node-level features such
178    /// as Funnel ingress ([`Node::can_funnel`], [`Node::check_funnel_port`]).
179    pub cap_map: NodeCapMap,
180
181    /// The peerAPI port this node advertises over IPv4 (`peerapi4` service), if any.
182    ///
183    /// Derived from `HostInfo.Services`. `None` means the peer advertises no IPv4 peerAPI, so it
184    /// cannot be reached for peerAPI DoH (DNS-over-HTTPS) exit-node delegation.
185    pub peerapi_port: Option<u16>,
186
187    /// Whether this peer advertises the `peerapi-dns-proxy` service (Go `PeerAPIDNSProxy`),
188    /// indicating it will proxy DNS lookups for other nodes when used as an exit node.
189    pub peerapi_dns_proxy: bool,
190
191    /// Whether this is a non-Tailscale WireGuard-only peer (`IsWireGuardOnly` in Go). Such peers
192    /// cannot run a peerAPI DoH server, so exit-node DNS for them comes from
193    /// [`Node::exit_node_dns_resolvers`] instead.
194    pub is_wireguard_only: bool,
195
196    /// DNS resolvers to use when this WireGuard-only peer is selected as an exit node
197    /// (`ExitNodeDNSResolvers` in Go). Only meaningful when [`Node::is_wireguard_only`] is set.
198    /// Encrypted-transport resolvers are dropped (see `Resolver::from_serde`).
199    pub exit_node_dns_resolvers: Vec<Resolver>,
200
201    /// Whether this node advertises itself as a **peer relay** (Go `Hostinfo.PeerRelay`): it runs a
202    /// UDP relay server other peers can allocate relay endpoints on. This fork is a relay client
203    /// only and never sets this for itself; it is parsed off peers so a relay candidate can be
204    /// recognized. Actually *using* a relay path (the Geneve data path + allocation handshake) is
205    /// not yet implemented — see the crate docs.
206    pub peer_relay: bool,
207
208    /// Per-service virtual IP addresses of the Tailscale VIP services this node *hosts*, keyed by
209    /// `svc:<label>` service name. Parsed from the `service-host`
210    /// ([`ts_control_serde::NODE_ATTR_SERVICE_HOST`]) node-capability value
211    /// (`tailcfg.ServiceIPMappings`). These VIPs are control-assigned and also injected into the
212    /// node's `AllowedIPs`; the application netstack must accept packets for them so a
213    /// `Device::listen_service`-bound listener can answer. Empty when the
214    /// node hosts no VIP services (the common case). Per-service IP lists are deduplicated, source
215    /// order otherwise preserved. Use [`Node::service_addresses`] for the flattened set (netstack
216    /// accept list) and [`Node::service_addresses_for`] for a specific service's VIPs.
217    pub service_vips: alloc::collections::BTreeMap<String, Vec<IpAddr>>,
218}
219
220impl Node {
221    /// The fully-qualified domain name of the node.
222    ///
223    /// This is a string of the form `$HOST.$TAILNET_DOMAIN.`. For tailnets controlled by
224    /// Tailscale's control plane, this usually means `$HOST.tail1234.ts.net.`
225    ///
226    /// The `trailing_dot` parameter specifies whether to include the trailing dot in the
227    /// fqdn. This is included by the definition of FQDN, and is the way the Go codebase
228    /// formats this field, but the parameter is included to allow turning it off for use
229    /// in contexts that expect it to be absent.
230    pub fn fqdn(&self, trailing_dot: bool) -> String {
231        let dot = if trailing_dot { "." } else { "" };
232        match &self.tailnet {
233            Some(tailnet) => format!("{}.{tailnet}{dot}", self.hostname),
234            None => format!("{}{dot}", self.hostname),
235        }
236    }
237
238    /// Whether this node's key has expired as of `now`, mirroring Go's
239    /// `netmap.NetworkMap.SelfKeyExpiry` + the `!expiry.IsZero() && expiry.Before(now)` check in
240    /// `ipnlocal`. A node with no expiry ([`Node::node_key_expiry`] is `None`, the Go "zero value =
241    /// does not expire") is never expired.
242    ///
243    /// Like Go, this fork is **reactive**: it reports expiry rather than auto-rotating in the
244    /// background (Go transitions to `NeedsLogin` on expiry and re-registers via stored auth-key or
245    /// interactive login). A caller observing `true` should re-register
246    /// (`crate::tokio::register`) — supplying `RegisterRequest::old_node_key` (the prior key) and
247    /// a fresh `node_key` when rotating the key, or the same key to merely refresh.
248    pub fn key_expired(&self, now: DateTime<Utc>) -> bool {
249        match self.node_key_expiry {
250            None => false,
251            Some(expiry) => expiry < now,
252        }
253    }
254
255    /// The instant this node's key expires (`Node.KeyExpiry` in Go), or `None` if it never expires.
256    /// A caller can schedule a re-evaluation/re-auth at this time.
257    pub fn key_expiry(&self) -> Option<DateTime<Utc>> {
258        self.node_key_expiry
259    }
260
261    /// Whether this node advertises itself as a peer relay (Go `Hostinfo.PeerRelay`): it runs a UDP
262    /// relay server other peers may allocate relay endpoints on. Recognizing a relay candidate;
263    /// actually traversing a relay path is not yet implemented in this fork.
264    pub fn is_peer_relay(&self) -> bool {
265        self.peer_relay
266    }
267
268    /// The key-expiry instant as **Unix seconds**, or `None` if the key never expires. Provided for
269    /// callers (e.g. the root crate) that don't depend on `chrono`.
270    pub fn key_expiry_unix(&self) -> Option<i64> {
271        self.node_key_expiry.map(|t| t.timestamp())
272    }
273
274    /// Whether the key has expired as of `now_unix_secs` (Unix seconds). Equivalent to
275    /// [`key_expired`](Self::key_expired) for `chrono`-free callers. A key with no expiry is never
276    /// expired.
277    pub fn key_expired_at_unix(&self, now_unix_secs: i64) -> bool {
278        match self.key_expiry_unix() {
279            None => false,
280            Some(expiry) => expiry < now_unix_secs,
281        }
282    }
283
284    /// The fully-qualified domain name of the node, only returning `Some` if the tailnet
285    /// component is present.
286    ///
287    /// See [`Node::fqdn`].
288    pub fn fqdn_opt(&self, trailing_dot: bool) -> Option<String> {
289        let dot = if trailing_dot { "." } else { "" };
290        let tailnet = self.tailnet.as_deref()?;
291
292        Some(format!("{}.{tailnet}{dot}", self.hostname))
293    }
294
295    /// Report whether this node matches the given `name`.
296    ///
297    /// `name` is checked for equality with both this node's bare hostname and its fqdn. A
298    /// trailing `.` may be present. Matching is case-insensitive (DNS names are
299    /// case-insensitive), so this agrees with the canonicalized MagicDNS-name index used for
300    /// peer lookups.
301    pub fn matches_name(&self, name: &str) -> bool {
302        // Strip an optional trailing root dot, then chop our `.tailnet` suffix off the end (if it
303        // matches, case-insensitively) and compare the remainder to our hostname. If the tailnet
304        // suffix doesn't match, the final case-insensitive compare against our bare hostname fails
305        // naturally; if `name` was just the hostname, nothing is chopped and we compare directly.
306
307        let name = name.strip_suffix('.').unwrap_or(name);
308
309        let name = if let Some(tailnet) = &self.tailnet {
310            name.get(name.len().saturating_sub(tailnet.len())..)
311                .filter(|suffix| suffix.eq_ignore_ascii_case(tailnet))
312                .and_then(|_| name.get(..name.len() - tailnet.len()))
313                .and_then(|name| name.strip_suffix('.'))
314                .unwrap_or(name)
315        } else {
316            name
317        };
318
319        name.eq_ignore_ascii_case(&self.hostname)
320    }
321
322    /// Report whether `route` is an advertised *subnet* route (as opposed to one of this node's
323    /// own tailnet addresses).
324    ///
325    /// Mirrors `cidrIsSubnet` in the Go client (`wgengine/wgcfg/nmcfg/nmcfg.go`). A route is *not*
326    /// a subnet route (i.e. it's a self-address) when it is a single host IP that is either a
327    /// Tailscale-assigned IP or exactly one of this node's [`TailnetAddress`] addresses. Everything
328    /// else — multi-IP CIDRs, and single IPs outside the Tailscale ranges — is a subnet route.
329    ///
330    /// The default route (`0.0.0.0/0` / `::/0`) is treated as a subnet route here; exit-node
331    /// handling is a separate concern.
332    pub fn is_subnet_route(&self, route: &ipnet::IpNet) -> bool {
333        let host_prefix = match route {
334            ipnet::IpNet::V4(_) => 32,
335            ipnet::IpNet::V6(_) => 128,
336        };
337
338        if route.prefix_len() != host_prefix {
339            // Any multi-IP CIDR (including the default route) is a subnet route.
340            return true;
341        }
342
343        let addr = route.addr();
344        !(is_tailscale_ip(addr) || self.tailnet_address.contains(addr))
345    }
346
347    /// The routes that should be installed for this peer, given whether this node accepts
348    /// advertised subnet routes (`--accept-routes` / `RouteAll` in the Go client) and which peer
349    /// (if any) is the selected exit node (`--exit-node` / `ExitNodeID` in the Go client).
350    ///
351    /// This node's own addresses (the peer's `/32` and `/128`) are always installed so the peer
352    /// itself stays reachable. Larger advertised subnet routes are only installed when
353    /// `accept_routes` is set; otherwise they are dropped (fail-closed). The same filtered set
354    /// governs both outbound routing to the peer and inbound source validation, exactly as
355    /// WireGuard cryptokey routing couples them in the Go client.
356    ///
357    /// The default route (`0.0.0.0/0` / `::/0`) is installed *only* for the peer whose
358    /// [`StableId`] equals `exit_node`, mirroring `nmcfg.go`'s `if allowedIP.Bits()==0 &&
359    /// peer.StableID()!=exitNode { skip }`. Exit-node use is gated behind this separate, explicit
360    /// preference (`ExitNodeID`, not `RouteAll`): conflating the two would let enabling
361    /// subnet-route acceptance silently route every packet through any peer advertising a default
362    /// route — unacceptable for a fail-closed privacy posture. When `exit_node` is `None` (the
363    /// default) no peer ever receives a `/0`, so internet-bound traffic has no overlay route and is
364    /// dropped by the userspace netstack (fail-closed, no leak). Longest-prefix-match means a peer
365    /// selected as the exit node still loses more-specific destinations to other peers; only
366    /// residual default-route traffic egresses through it.
367    pub fn routes_to_install<'a>(
368        &'a self,
369        accept_routes: bool,
370        exit_node: Option<&StableId>,
371    ) -> impl Iterator<Item = &'a ipnet::IpNet> + 'a {
372        // Computed eagerly so the returned iterator doesn't borrow `exit_node`.
373        let is_selected_exit = exit_node == Some(&self.stable_id);
374        self.accepted_routes.iter().filter(move |route| {
375            if route.prefix_len() == 0 {
376                // Default route: installed only when this peer is the selected exit node. Both the
377                // outbound route table and the inbound source filter call this, so the exit peer
378                // may legitimately source arbitrary internet IPs on return traffic — and only it.
379                return is_selected_exit;
380            }
381            accept_routes || !self.is_subnet_route(route)
382        })
383    }
384
385    /// The capability version at and above which a peer can proxy DNS for nodes using it as an exit
386    /// node (Go `tailcfg.CapabilityVersion` `peerCanProxyDNS`, introduced 2022-01-12 at V26).
387    const PEER_CAN_PROXY_DNS: CapabilityVersion = CapabilityVersion::V26;
388
389    /// The base URL of this peer's IPv4 peerAPI DoH endpoint for exit-node DNS proxying, if it can
390    /// proxy DNS. Returns e.g. `http://100.64.0.5:8080/dns-query`.
391    ///
392    /// Mirrors Go `peerAPIBase(...)+"/dns-query"` gated by `exitNodeCanProxyDNS`: a peer can proxy
393    /// DNS when it advertises an IPv4 peerAPI port **and** either advertises the explicit
394    /// `peerapi-dns-proxy` service or is new enough ([`Node::cap`] ≥ `PEER_CAN_PROXY_DNS`). A
395    /// WireGuard-only peer never runs a peerAPI, so it returns `None` here (its exit-node DNS comes
396    /// from [`Node::exit_node_dns_resolvers`] instead).
397    ///
398    /// IPv4-only by deliberate design: the tailnet dataplane in this fork binds IPv4 only, so we
399    /// never form a peerAPI URL on the peer's IPv6 address.
400    pub fn peerapi_doh_url(&self) -> Option<String> {
401        self.peerapi_doh_addr()
402            .map(|addr| format!("http://{addr}/dns-query"))
403    }
404
405    /// The IPv4 socket address (`<tailnet-ipv4>:<peerapi-port>`) of this peer's peerAPI DoH endpoint
406    /// for exit-node DNS proxying, if it can proxy DNS. Same gate as [`Node::peerapi_doh_url`]; this
407    /// is the form the DoH *client* dials (over the overlay netstack) when delegating recursive
408    /// resolution to a selected exit node. `SocketAddr`'s `Display` is `ip:port`, so
409    /// `peerapi_doh_url` formats to `http://<ip>:<port>/dns-query` over this.
410    pub fn peerapi_doh_addr(&self) -> Option<SocketAddr> {
411        if self.is_wireguard_only {
412            return None;
413        }
414        let port = self.peerapi_port?;
415        if !(self.peerapi_dns_proxy || self.cap >= Self::PEER_CAN_PROXY_DNS) {
416            return None;
417        }
418        Some(SocketAddr::new(
419            IpAddr::V4(self.tailnet_address.ipv4.addr()),
420            port,
421        ))
422    }
423
424    /// The IPv4 peerAPI socket address (`<tailnet-ipv4>:<peerapi4-port>`) of this node, if it
425    /// advertises an IPv4 peerAPI. Unlike [`Node::peerapi_doh_addr`], this is **not** gated on the
426    /// DNS-proxy capability: it is the general base for any peerAPI request to this node (e.g. a
427    /// Taildrop `PUT /v0/put/<name>` upload), mirroring Go's `peerAPIBase`/`peerAPIPorts`.
428    ///
429    /// IPv4-only by this fork's deliberate design (the tailnet dataplane binds IPv4 only, so we never
430    /// form a peerAPI URL on the peer's IPv6 address). Returns `None` for a WireGuard-only peer (which
431    /// runs no peerAPI) or a peer advertising no IPv4 peerAPI port.
432    pub fn peerapi_addr(&self) -> Option<SocketAddr> {
433        if self.is_wireguard_only {
434            return None;
435        }
436        let port = self.peerapi_port?;
437        Some(SocketAddr::new(
438            IpAddr::V4(self.tailnet_address.ipv4.addr()),
439            port,
440        ))
441    }
442
443    /// The node attribute granting HTTPS (TLS cert provisioning) for this node (Go
444    /// `tailcfg.CapabilityHTTPS`). One of the two caps [`Node::can_funnel`] requires.
445    const CAP_HTTPS: &'static str = "https";
446
447    /// The node attribute granting the ability to host Funnel ingress (Go `tailcfg.NodeAttrFunnel`).
448    /// The other cap [`Node::can_funnel`] requires.
449    const NODE_ATTR_FUNNEL: &'static str = "funnel";
450
451    /// The capability URL whose `?ports=` query enumerates the ports Funnel may listen on (Go
452    /// `tailcfg.CapabilityFunnelPorts`). The allowed ports live entirely in the *key's* query
453    /// string, not the cap value.
454    const CAP_FUNNEL_PORTS: &'static str = "https://tailscale.com/cap/funnel-ports";
455
456    /// Report whether the cap map contains `cap` as a key (Go `NodeCapMap.Contains` / `HasCap`).
457    pub fn has_node_attr(&self, cap: &str) -> bool {
458        self.cap_map.contains_key(cap)
459    }
460
461    /// Report whether this node is permitted to host Tailscale Funnel ingress.
462    ///
463    /// Mirrors Go `ipn.NodeCanFunnel`: the node must advertise BOTH `CapabilityHTTPS` (`"https"`)
464    /// AND `NodeAttrFunnel` (`"funnel"`) in its cap map. Fail-closed: a missing cap denies.
465    pub fn can_funnel(&self) -> bool {
466        self.has_node_attr(Self::CAP_HTTPS) && self.has_node_attr(Self::NODE_ATTR_FUNNEL)
467    }
468
469    /// Report whether `wanted_port` is allowed for Funnel on this node.
470    ///
471    /// Mirrors Go `ipn.CheckFunnelPort`: scan the cap-map keys for one prefixed by
472    /// `Node::CAP_FUNNEL_PORTS`, URL-parse that key, read its `ports` query parameter, and match
473    /// `wanted_port` against the comma-separated list of single ports and `first-last` ranges. The
474    /// port list lives in the *key*, never the value. Fail-closed: no matching cap, an empty or
475    /// unparseable `ports` query, or a key whose non-query part isn't exactly the funnel-ports URL
476    /// all deny.
477    pub fn check_funnel_port(&self, wanted_port: u16) -> bool {
478        // Extract the `ports=` list from the first cap-map key that is the funnel-ports URL with a
479        // non-empty `ports` query. Returns `None` (deny) if the key is unparseable, the query is
480        // missing/empty, or the URL (sans query) isn't exactly the funnel-ports cap.
481        let parse_attr = |attr: &str| -> Option<String> {
482            let mut url = url::Url::parse(attr).ok()?;
483            let ports = url
484                .query_pairs()
485                .find(|(k, _)| k == "ports")
486                .map(|(_, v)| v.into_owned())?;
487            if ports.is_empty() {
488                return None;
489            }
490            url.set_query(None);
491            // Go compares `u.String()` against the bare cap; `url`'s serializer keeps a trailing
492            // `/` only if present in the input, and the funnel-ports cap has none, so a direct
493            // string compare matches Go's behavior.
494            if url.as_str() != Self::CAP_FUNNEL_PORTS {
495                return None;
496            }
497            Some(ports)
498        };
499
500        let Some(ports_str) = self
501            .cap_map
502            .keys()
503            .filter(|attr| attr.starts_with(Self::CAP_FUNNEL_PORTS))
504            .find_map(|attr| parse_attr(attr))
505        else {
506            return false;
507        };
508
509        let wanted = wanted_port.to_string();
510        for ps in ports_str.split(',') {
511            if ps.is_empty() {
512                continue;
513            }
514            match ps.split_once('-') {
515                None => {
516                    if ps == wanted {
517                        return true;
518                    }
519                }
520                Some((first, last)) => {
521                    let (Ok(fp), Ok(lp)) = (first.parse::<u16>(), last.parse::<u16>()) else {
522                        continue;
523                    };
524                    if fp <= wanted_port && wanted_port <= lp {
525                        return true;
526                    }
527                }
528            }
529        }
530        false
531    }
532
533    /// Report whether this node is permitted to host Tailscale VIP services.
534    ///
535    /// Mirrors the Go grant model: possession of the `service-host`
536    /// ([`ts_control_serde::NODE_ATTR_SERVICE_HOST`]) node-capability **and** at least one assigned
537    /// VIP address. Go additionally requires the host to be tagged
538    /// (`ErrUntaggedServiceHost`); that tag gate is enforced at
539    /// `Device::listen_service` using [`Node::tags`]. Fail-closed: no cap
540    /// or no assigned VIP denies.
541    pub fn is_service_host(&self) -> bool {
542        self.has_node_attr(ts_control_serde::NODE_ATTR_SERVICE_HOST)
543            && !self.service_vips.is_empty()
544    }
545
546    /// The control-assigned VIP addresses for one named service (`svc:<label>`), or an empty slice
547    /// if this node does not host that service. This is the exact per-service mapping (so a
548    /// multi-service co-host binds the right VIP for each service).
549    pub fn service_addresses_for(&self, service: &str) -> &[IpAddr] {
550        self.service_vips
551            .get(service)
552            .map(Vec::as_slice)
553            .unwrap_or(&[])
554    }
555
556    /// The flattened, deduplicated set of every VIP address this node hosts across all services.
557    /// Used to widen the netstack's accepted-address set so any hosted-service listener is
558    /// reachable. Per-service binding uses [`Node::service_addresses_for`] instead.
559    pub fn service_addresses(&self) -> Vec<IpAddr> {
560        let mut seen = alloc::collections::BTreeSet::new();
561        let mut out = Vec::new();
562        for addr in self.service_vips.values().flatten() {
563            if seen.insert(*addr) {
564                out.push(*addr);
565            }
566        }
567        out
568    }
569}
570
571/// Validate a Tailscale VIP service name (`tailcfg.ServiceName.Validate`): it must carry the
572/// `svc:` prefix ([`ts_control_serde::SERVICE_NAME_PREFIX`]) followed by a valid DNS label
573/// (1–63 chars, ASCII alphanumeric or `-`, not starting/ending with `-`). Returns the bare label on
574/// success. Fail-closed: anything malformed is rejected so a listener can never bind for a bogus
575/// service name.
576pub fn validate_service_name(name: &str) -> Option<&str> {
577    let label = name.strip_prefix(ts_control_serde::SERVICE_NAME_PREFIX)?;
578    if label.is_empty() || label.len() > 63 {
579        return None;
580    }
581    if label.starts_with('-') || label.ends_with('-') {
582        return None;
583    }
584    if label
585        .bytes()
586        .all(|b| b.is_ascii_alphanumeric() || b == b'-')
587    {
588        Some(label)
589    } else {
590        None
591    }
592}
593
594/// Parse the per-service VIP map this node hosts from the `service-host` node-capability value(s).
595/// Each value is the raw JSON text of a [`ts_control_serde::ServiceIpMappings`] object (svc-name ->
596/// VIP IPs); unparseable values are skipped (fail-closed: a malformed mapping contributes no VIPs).
597/// Per-service IP lists are deduplicated, source order otherwise preserved.
598fn service_vips_from_cap_map(
599    cap_map: &NodeCapMap,
600) -> alloc::collections::BTreeMap<String, Vec<IpAddr>> {
601    let mut out: alloc::collections::BTreeMap<String, Vec<IpAddr>> =
602        alloc::collections::BTreeMap::new();
603    let Some(values) = cap_map.get(ts_control_serde::NODE_ATTR_SERVICE_HOST) else {
604        return out;
605    };
606
607    for raw in values {
608        let Ok(mappings) = serde_json::from_str::<ts_control_serde::ServiceIpMappings>(raw) else {
609            continue;
610        };
611        for (name, addrs) in &mappings.0 {
612            let entry = out.entry((*name).to_string()).or_default();
613            for addr in addrs {
614                if !entry.contains(addr) {
615                    entry.push(*addr);
616                }
617            }
618        }
619    }
620    out
621}
622
623/// Collect a wire ([`ts_control_serde`]) node cap map into an owned [`NodeCapMap`].
624///
625/// Keys are copied as owned strings; each value's raw JSON text is preserved verbatim. The wire map
626/// borrows from the decode buffer, so an owned copy is required to outlive it on the domain
627/// [`Node`].
628fn cap_map_from_serde(wire: &ts_nodecapability::Map<'_>) -> NodeCapMap {
629    wire.iter()
630        .map(|(&key, values)| {
631            let owned_values = values.0.iter().map(|v| v.get().to_owned()).collect();
632            (key.to_owned(), owned_values)
633        })
634        .collect()
635}
636
637/// Extract the advertised IPv4 peerAPI port and whether the explicit `peerapi-dns-proxy` service is
638/// advertised, from a peer's `HostInfo.Services` list.
639fn peerapi_from_services(
640    services: Option<&[ts_control_serde::Service<'_>]>,
641) -> (Option<u16>, bool) {
642    use ts_control_serde::ServiceProto;
643
644    let Some(services) = services else {
645        return (None, false);
646    };
647    let mut port = None;
648    let mut dns_proxy = false;
649    for svc in services {
650        match svc.proto {
651            ServiceProto::PeerApi4 => port = Some(svc.port),
652            ServiceProto::PeerApiDnsProxy => dns_proxy = true,
653            _ => {}
654        }
655    }
656    (port, dns_proxy)
657}
658
659/// Addresses for a node within a tailnet.
660#[derive(Debug, Clone, PartialEq, Eq, Hash)]
661pub struct TailnetAddress {
662    /// The IPv4 address of the node in the tailnet.
663    pub ipv4: ipnet::Ipv4Net,
664    /// The IPv6 address of the node in the tailnet.
665    pub ipv6: ipnet::Ipv6Net,
666}
667
668impl TailnetAddress {
669    /// Report whether `addr` matches either address in this [`TailnetAddress`].
670    pub fn contains(&self, addr: IpAddr) -> bool {
671        match addr {
672            IpAddr::V4(a) => self.ipv4.addr() == a,
673            IpAddr::V6(a) => self.ipv6.addr() == a,
674        }
675    }
676}
677
678impl From<&ts_control_serde::Node<'_>> for Node {
679    fn from(value: &ts_control_serde::Node) -> Self {
680        let fqdn_without_trailing_dot = value.name.strip_suffix('.').unwrap_or(value.name);
681
682        let (hostname, tailnet) = match fqdn_without_trailing_dot.split_once('.') {
683            Some((hostname, tailnet)) => (hostname, Some(tailnet.to_owned())),
684            None => (fqdn_without_trailing_dot, None),
685        };
686
687        let (peerapi_port, peerapi_dns_proxy) =
688            peerapi_from_services(value.host_info.services.as_deref());
689
690        let cap_map = cap_map_from_serde(&value.cap_map);
691        let service_vips = service_vips_from_cap_map(&cap_map);
692
693        // `addresses` is a variable-length `Vec<IpNet>` on the wire (Go `[]netip.Prefix`), not a
694        // fixed (v4, v6) pair: an IPv6-off tailnet assigns only a v4 prefix. Pick the first of each
695        // family. The v4 prefix is the node's tailnet identity (always present on a normal node);
696        // if somehow absent we fall back to the unspecified `0.0.0.0/32` rather than panicking.
697        // The v6 prefix is optional — when the tailnet is IPv4-only there is none, and the overlay
698        // never reads `ipv6` in that mode (gated on `enable_ipv6`); we synthesize the unspecified
699        // `::/128` placeholder so the domain `TailnetAddress` stays infallible.
700        let ipv4 = value
701            .addresses
702            .iter()
703            .find_map(|p| match p {
704                ipnet::IpNet::V4(n) => Some(*n),
705                ipnet::IpNet::V6(_) => None,
706            })
707            .unwrap_or_else(|| ipnet::Ipv4Net::new(core::net::Ipv4Addr::UNSPECIFIED, 32).unwrap());
708        let ipv6 = value
709            .addresses
710            .iter()
711            .find_map(|p| match p {
712                ipnet::IpNet::V6(n) => Some(*n),
713                ipnet::IpNet::V4(_) => None,
714            })
715            .unwrap_or_else(|| ipnet::Ipv6Net::new(core::net::Ipv6Addr::UNSPECIFIED, 128).unwrap());
716
717        Self {
718            id: value.id,
719            stable_id: StableId(value.stable_id.0.to_string()),
720
721            hostname: hostname.to_owned(),
722            user_id: value.user,
723            tailnet,
724
725            tags: value
726                .tags
727                .as_ref()
728                .map(|x| x.iter().map(|x| x.to_string()).collect())
729                .unwrap_or_default(),
730
731            tailnet_address: TailnetAddress { ipv4, ipv6 },
732            node_key: value.key,
733            node_key_expiry: value.key_expiry,
734            key_signature: value.key_signature.to_vec(),
735            machine_key: value.machine,
736            disco_key: value.disco_key,
737
738            // Per capver-112, `AllowedIPs` null/absent means "same as `addresses`". Fall back to the
739            // node's own assigned prefixes verbatim (whatever families the wire carried), not a
740            // synthesized v4+v6 pair.
741            accepted_routes: value
742                .allowed_ips
743                .clone()
744                .unwrap_or_else(|| value.addresses.clone()),
745            underlay_addresses: value.endpoints.clone(),
746
747            // legacy_derp_string is still in practical use as of 3/2026
748            #[allow(deprecated)]
749            derp_region: value
750                .home_derp
751                .or(value.legacy_derp_string)
752                .or_else(|| value.host_info.net_info.as_ref()?.preferred_derp)
753                .map(|x| ts_derp::RegionId(x.into())),
754
755            cap: value.cap,
756            cap_map,
757            peerapi_port,
758            peerapi_dns_proxy,
759            is_wireguard_only: value.is_wireguard_only,
760            exit_node_dns_resolvers: value
761                .exit_node_dns_resolvers
762                .iter()
763                .filter_map(Resolver::from_serde)
764                .collect(),
765            peer_relay: value.host_info.peer_relay,
766            service_vips,
767        }
768    }
769}
770
771/// Display-friendly identity for the user that owns a [`Node`], resolved from the netmap's
772/// `UserProfiles` table (Go `tailcfg.UserProfile`). Owned counterpart of the borrow-bound
773/// [`ts_control_serde::UserProfile`]. Keyed by [`UserProfile::id`] (== [`Node::user_id`]).
774#[derive(Debug, Clone, PartialEq, Eq)]
775pub struct UserProfile {
776    /// The integer id of the Tailscale user this profile describes (matches [`Node::user_id`]).
777    pub id: ts_control_serde::UserId,
778    /// An email-ish login name for display (e.g. `alice@example.com` / `alice@github`). May be
779    /// empty if control sent none.
780    pub login_name: String,
781    /// The user's display name (e.g. `Alice Smith`), if the IdP provided one.
782    pub display_name: Option<String>,
783}
784
785impl From<&ts_control_serde::UserProfile<'_>> for UserProfile {
786    fn from(value: &ts_control_serde::UserProfile) -> Self {
787        Self {
788            id: value.id,
789            login_name: value.login_name.to_string(),
790            display_name: value.display_name.map(str::to_string),
791        }
792    }
793}
794
795impl UserProfile {
796    /// The best human-facing label for this user: the login name when present, else the display
797    /// name, else `None`. This is what a `WhoIs` surfaces as the owning user.
798    pub fn best_label(&self) -> Option<String> {
799        if !self.login_name.is_empty() {
800            Some(self.login_name.clone())
801        } else {
802            self.display_name.clone()
803        }
804    }
805}
806
807#[cfg(test)]
808mod tests {
809    use super::*;
810
811    /// The wire `Node.User` id must be carried onto the domain `Node.user_id` by the `From` impl
812    /// (the field the runtime joins against the netmap `UserProfiles` table for `WhoIs.user`).
813    /// Guards against the `From` impl wiring the wrong serde field or dropping it.
814    #[test]
815    fn from_wire_node_carries_user_id() {
816        let mut wire = ts_control_serde::Node {
817            user: 4242,
818            ..Default::default()
819        };
820        wire.name = "host.tail.ts.net.";
821        let domain: Node = (&wire).into();
822        assert_eq!(domain.user_id, 4242);
823
824        // Default (no owner / tagged node) stays 0.
825        let tagged = ts_control_serde::Node::default();
826        assert_eq!(Node::from(&tagged).user_id, 0);
827    }
828
829    /// A node from an **IPv4-only** tailnet (IPv6-off control plane / Headscale) carries a
830    /// single-element `addresses` list. This used to fail deserialization ("invalid length 1,
831    /// expected a tuple of size 2") when `addresses` was a fixed 2-tuple; it must now parse and
832    /// derive the v4 identity, with the unused v6 a synthesized placeholder.
833    #[test]
834    fn from_wire_node_ipv4_only_addresses() {
835        let wire = ts_control_serde::Node {
836            addresses: vec!["100.64.0.5/32".parse().unwrap()],
837            ..Default::default()
838        };
839        let domain: Node = (&wire).into();
840        assert_eq!(
841            domain.tailnet_address.ipv4,
842            "100.64.0.5/32".parse().unwrap()
843        );
844        // No v6 on the wire → unspecified placeholder (never read in IPv4-only mode).
845        assert_eq!(
846            domain.tailnet_address.ipv6,
847            ipnet::Ipv6Net::new(core::net::Ipv6Addr::UNSPECIFIED, 128).unwrap()
848        );
849        // AllowedIPs absent → falls back to the node's own assigned prefixes (just the v4 here).
850        assert_eq!(
851            domain.accepted_routes,
852            vec!["100.64.0.5/32".parse::<ipnet::IpNet>().unwrap()]
853        );
854    }
855
856    /// A dual-stack node carries both families (any order); the domain picks the first of each.
857    #[test]
858    fn from_wire_node_dual_stack_addresses() {
859        let wire = ts_control_serde::Node {
860            addresses: vec![
861                "100.64.0.7/32".parse().unwrap(),
862                "fd7a:115c:a1e0::7/128".parse().unwrap(),
863            ],
864            ..Default::default()
865        };
866        let domain: Node = (&wire).into();
867        assert_eq!(
868            domain.tailnet_address.ipv4,
869            "100.64.0.7/32".parse().unwrap()
870        );
871        assert_eq!(
872            domain.tailnet_address.ipv6,
873            "fd7a:115c:a1e0::7/128".parse().unwrap()
874        );
875    }
876
877    /// The deserialization regression itself: a MapResponse-style Node JSON with a 1-element
878    /// `Addresses` array must parse (this is the exact shape the dev-Headscale sends).
879    #[test]
880    fn deserialize_node_with_single_address() {
881        let json = r#"{
882            "ID": 1,
883            "StableID": "n1",
884            "Name": "host.tail.ts.net.",
885            "User": 1,
886            "Addresses": ["100.64.0.9/32"],
887            "Key": "nodekey:0000000000000000000000000000000000000000000000000000000000000000",
888            "Machine": null,
889            "DiscoKey": null,
890            "AllowedIPs": null,
891            "Endpoints": []
892        }"#;
893        let wire: ts_control_serde::Node = serde_json::from_str(json).expect("1-addr node parses");
894        assert_eq!(wire.addresses.len(), 1);
895        let domain: Node = (&wire).into();
896        assert_eq!(
897            domain.tailnet_address.ipv4,
898            "100.64.0.9/32".parse().unwrap()
899        );
900    }
901
902    #[test]
903    fn key_expiry_semantics() {
904        let now: DateTime<Utc> = "2026-06-05T00:00:00Z".parse().unwrap();
905        let past: DateTime<Utc> = "2020-01-01T00:00:00Z".parse().unwrap();
906        let future: DateTime<Utc> = "2099-01-01T00:00:00Z".parse().unwrap();
907
908        let mut n = node("h", Some("t.ts.net"));
909
910        // No expiry set => never expired (Go zero-value semantics).
911        n.node_key_expiry = None;
912        assert!(!n.key_expired(now));
913        assert_eq!(n.key_expiry(), None);
914
915        // Future expiry => not yet expired.
916        n.node_key_expiry = Some(future);
917        assert!(!n.key_expired(now));
918        assert_eq!(n.key_expiry(), Some(future));
919
920        // Past expiry => expired.
921        n.node_key_expiry = Some(past);
922        assert!(n.key_expired(now));
923    }
924
925    #[test]
926    fn key_expiry_unix_agrees_with_chrono() {
927        // The chrono-free variants (`key_expired_at_unix` / `key_expiry_unix`) must agree with the
928        // chrono variants for the same none/future/past cases (Unix seconds of the same instants).
929        let now: DateTime<Utc> = "2026-06-05T00:00:00Z".parse().unwrap();
930        let past: DateTime<Utc> = "2020-01-01T00:00:00Z".parse().unwrap();
931        let future: DateTime<Utc> = "2099-01-01T00:00:00Z".parse().unwrap();
932        let now_unix = now.timestamp();
933
934        let mut n = node("h", Some("t.ts.net"));
935
936        // No expiry => never expired; the unix accessor reports `None`.
937        n.node_key_expiry = None;
938        assert_eq!(n.key_expired(now), n.key_expired_at_unix(now_unix));
939        assert!(!n.key_expired_at_unix(now_unix));
940        assert_eq!(n.key_expiry_unix(), None);
941
942        // Future expiry => not yet expired; unix accessor matches the chrono timestamp.
943        n.node_key_expiry = Some(future);
944        assert_eq!(n.key_expired(now), n.key_expired_at_unix(now_unix));
945        assert!(!n.key_expired_at_unix(now_unix));
946        assert_eq!(n.key_expiry_unix(), Some(future.timestamp()));
947
948        // Past expiry => expired; unix accessor matches the chrono timestamp.
949        n.node_key_expiry = Some(past);
950        assert_eq!(n.key_expired(now), n.key_expired_at_unix(now_unix));
951        assert!(n.key_expired_at_unix(now_unix));
952        assert_eq!(n.key_expiry_unix(), Some(past.timestamp()));
953    }
954
955    #[test]
956    fn key_expiry_boundary_is_not_expired() {
957        // A key whose expiry exactly equals `now` is NOT expired: the code uses strict `<`, matching
958        // Go's `Before`. Both the chrono and chrono-free variants must agree at the boundary.
959        let now: DateTime<Utc> = "2026-06-05T00:00:00Z".parse().unwrap();
960        let now_unix = now.timestamp();
961
962        let mut n = node("h", Some("t.ts.net"));
963        n.node_key_expiry = Some(now);
964
965        assert!(!n.key_expired(now));
966        assert!(!n.key_expired_at_unix(now_unix));
967    }
968
969    #[test]
970    fn is_peer_relay_returns_field() {
971        let mut n = node("h", Some("t.ts.net"));
972
973        n.peer_relay = true;
974        assert!(n.is_peer_relay());
975
976        n.peer_relay = false;
977        assert!(!n.is_peer_relay());
978    }
979
980    fn node(hostname: &str, tailnet: Option<&str>) -> Node {
981        Node {
982            id: 1,
983            stable_id: StableId("n1".to_string()),
984            hostname: hostname.to_string(),
985            user_id: 0,
986            tailnet: tailnet.map(str::to_string),
987            tags: vec![],
988            tailnet_address: TailnetAddress {
989                ipv4: "100.64.0.1/32".parse().unwrap(),
990                ipv6: "fd7a::1/128".parse().unwrap(),
991            },
992            node_key: [0u8; 32].into(),
993            node_key_expiry: None,
994            key_signature: vec![],
995            machine_key: None,
996            disco_key: None,
997            accepted_routes: vec![],
998            underlay_addresses: vec![],
999            derp_region: None,
1000            cap: CapabilityVersion::default(),
1001            cap_map: NodeCapMap::new(),
1002            peerapi_port: None,
1003            peerapi_dns_proxy: false,
1004            is_wireguard_only: false,
1005            exit_node_dns_resolvers: vec![],
1006            peer_relay: false,
1007            service_vips: Default::default(),
1008        }
1009    }
1010
1011    #[test]
1012    fn matches_name_is_case_and_trailing_dot_insensitive() {
1013        let n = node("MyHost", Some("tail-scale.ts.net"));
1014
1015        // bare hostname, any case
1016        assert!(n.matches_name("myhost"));
1017        assert!(n.matches_name("MYHOST"));
1018        assert!(n.matches_name("MyHost"));
1019
1020        // fqdn, any case, with and without trailing dot
1021        assert!(n.matches_name("myhost.tail-scale.ts.net"));
1022        assert!(n.matches_name("MYHOST.TAIL-SCALE.TS.NET"));
1023        assert!(n.matches_name("myhost.tail-scale.ts.net."));
1024        assert!(n.matches_name("MyHost.Tail-Scale.TS.NET."));
1025
1026        // wrong host / wrong tailnet must not match
1027        assert!(!n.matches_name("other"));
1028        assert!(!n.matches_name("myhost.other.ts.net"));
1029    }
1030
1031    #[test]
1032    fn matches_name_no_tailnet() {
1033        let n = node("solo", None);
1034        assert!(n.matches_name("solo"));
1035        assert!(n.matches_name("SOLO."));
1036        assert!(!n.matches_name("solo.ts.net"));
1037    }
1038
1039    #[test]
1040    fn is_tailscale_ip_ranges() {
1041        // CGNAT v4
1042        assert!(is_tailscale_ip("100.64.0.1".parse().unwrap()));
1043        assert!(is_tailscale_ip("100.127.255.254".parse().unwrap()));
1044        // ChromeOS carve-out is excluded
1045        assert!(!is_tailscale_ip("100.115.92.5".parse().unwrap()));
1046        // outside CGNAT
1047        assert!(!is_tailscale_ip("10.0.0.1".parse().unwrap()));
1048        assert!(!is_tailscale_ip("100.128.0.1".parse().unwrap()));
1049        // Tailscale ULA v6
1050        assert!(is_tailscale_ip("fd7a:115c:a1e0::1".parse().unwrap()));
1051        assert!(!is_tailscale_ip("fd00::1".parse().unwrap()));
1052    }
1053
1054    /// Taildrop SSRF guard (defense-in-depth). `Device::send_file` rejects an upload destination
1055    /// unless `is_tailscale_ip(peer.peerapi_addr().ip())` holds. `Device::send_file` itself needs a
1056    /// live runtime (it goes through `self.channel()`), so it can't be unit-tested here; instead we
1057    /// test the exact composition the guard relies on — `is_tailscale_ip ∘ peerapi_addr` — against a
1058    /// `Node` whose `tailnet_address.ipv4` has been corrupted to a non-CGNAT (public) address. A
1059    /// well-formed peer always has a CGNAT 100.64.0.0/10 address, but the guard exists to catch a
1060    /// malformed/hostile node; this proves it would reject one.
1061    #[test]
1062    fn taildrop_ssrf_guard_rejects_non_cgnat_peerapi_addr() {
1063        let mut n = node("evil", Some("ts.net"));
1064        // Corrupt the peer to a public, non-CGNAT address and advertise a peerAPI port so
1065        // `peerapi_addr` returns `Some(_)`.
1066        n.tailnet_address.ipv4 = "1.2.3.4/32".parse().unwrap();
1067        n.peerapi_port = Some(443);
1068
1069        let addr = n
1070            .peerapi_addr()
1071            .expect("peerapi_addr yields Some with a port set");
1072        assert_eq!(addr.ip(), Ipv4Addr::new(1, 2, 3, 4));
1073        // The guard `if !is_tailscale_ip(dst.ip()) { return Err(BadRequest) }` WOULD reject this.
1074        assert!(
1075            !is_tailscale_ip(addr.ip()),
1076            "SSRF guard must reject a peer whose peerAPI addr is not a Tailscale CGNAT IP"
1077        );
1078
1079        // Conversely, a well-formed CGNAT peer passes the guard.
1080        let mut good = node("friend", Some("ts.net"));
1081        good.peerapi_port = Some(443);
1082        let good_addr = good.peerapi_addr().expect("peerapi_addr yields Some");
1083        assert!(is_tailscale_ip(good_addr.ip()));
1084    }
1085
1086    #[test]
1087    fn is_subnet_route_distinguishes_self_from_subnet() {
1088        let n = node("host", Some("ts.net"));
1089
1090        // The node's own /32 and /128 are self-addresses, not subnet routes.
1091        assert!(!n.is_subnet_route(&"100.64.0.1/32".parse().unwrap()));
1092        assert!(!n.is_subnet_route(&"fd7a::1/128".parse().unwrap()));
1093        // A different single Tailscale IP is still a self-address (Tailscale-assigned host).
1094        assert!(!n.is_subnet_route(&"100.64.5.5/32".parse().unwrap()));
1095        // A LAN /24 the node advertises is a subnet route.
1096        assert!(n.is_subnet_route(&"192.168.1.0/24".parse().unwrap()));
1097        // A single non-Tailscale host IP counts as a subnet route.
1098        assert!(n.is_subnet_route(&"8.8.8.8/32".parse().unwrap()));
1099        // The default route is treated as a subnet route.
1100        assert!(n.is_subnet_route(&"0.0.0.0/0".parse().unwrap()));
1101        assert!(n.is_subnet_route(&"::/0".parse().unwrap()));
1102    }
1103
1104    #[test]
1105    fn routes_to_install_gates_subnets_on_accept_routes() {
1106        let mut n = node("host", Some("ts.net"));
1107        let self4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
1108        let self6: ipnet::IpNet = "fd7a::1/128".parse().unwrap();
1109        let subnet: ipnet::IpNet = "192.168.1.0/24".parse().unwrap();
1110        n.accepted_routes = vec![self4, self6, subnet];
1111
1112        // accept_routes off: only the self addresses are installed.
1113        let off: Vec<_> = n.routes_to_install(false, None).copied().collect();
1114        assert_eq!(off, vec![self4, self6]);
1115
1116        // accept_routes on: the advertised subnet is installed too.
1117        let on: Vec<_> = n.routes_to_install(true, None).copied().collect();
1118        assert_eq!(on, vec![self4, self6, subnet]);
1119    }
1120
1121    #[test]
1122    fn routes_to_install_default_route_only_for_selected_exit_node() {
1123        let mut n = node("host", Some("ts.net"));
1124        n.stable_id = StableId("exit1".to_string());
1125        let self4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
1126        let default4: ipnet::IpNet = "0.0.0.0/0".parse().unwrap();
1127        let default6: ipnet::IpNet = "::/0".parse().unwrap();
1128        n.accepted_routes = vec![self4, default4, default6];
1129
1130        // No exit node selected: default routes are excluded even with accept_routes on
1131        // (fail-closed — internet-bound traffic has no overlay route and is dropped).
1132        let none_off: Vec<_> = n.routes_to_install(false, None).copied().collect();
1133        assert_eq!(none_off, vec![self4]);
1134        let none_on: Vec<_> = n.routes_to_install(true, None).copied().collect();
1135        assert_eq!(none_on, vec![self4]);
1136
1137        // A *different* peer selected as exit node: this peer still gets no default route.
1138        let other = StableId("exit2".to_string());
1139        let other_sel: Vec<_> = n.routes_to_install(false, Some(&other)).copied().collect();
1140        assert_eq!(other_sel, vec![self4]);
1141
1142        // This peer selected as the exit node: its default routes are installed.
1143        let me = StableId("exit1".to_string());
1144        let sel: Vec<_> = n.routes_to_install(false, Some(&me)).copied().collect();
1145        assert_eq!(sel, vec![self4, default4, default6]);
1146    }
1147
1148    fn exit_node_with(id: &str, ipv4: &str, hostname: &str, tailnet: Option<&str>) -> Node {
1149        let mut n = node(hostname, tailnet);
1150        n.stable_id = StableId(id.to_string());
1151        n.tailnet_address.ipv4 = format!("{ipv4}/32").parse().unwrap();
1152        n
1153    }
1154
1155    #[test]
1156    fn exit_node_selector_resolves_by_id_ip_and_name() {
1157        let a = exit_node_with("nA", "100.64.0.5", "alpha", Some("ts.net"));
1158        let b = exit_node_with("nB", "100.64.0.6", "beta", Some("ts.net"));
1159        let peers = [a, b];
1160        let it = || peers.iter();
1161
1162        // By stable id.
1163        assert_eq!(
1164            ExitNodeSelector::StableId(StableId("nB".into())).resolve(it()),
1165            Some(StableId("nB".into()))
1166        );
1167        // By tailnet IP.
1168        assert_eq!(
1169            ExitNodeSelector::Ip("100.64.0.5".parse().unwrap()).resolve(it()),
1170            Some(StableId("nA".into()))
1171        );
1172        // By MagicDNS name (fqdn, case-insensitive).
1173        assert_eq!(
1174            ExitNodeSelector::Name("BETA.ts.net".into()).resolve(it()),
1175            Some(StableId("nB".into()))
1176        );
1177        // By bare hostname.
1178        assert_eq!(
1179            ExitNodeSelector::Name("alpha".into()).resolve(it()),
1180            Some(StableId("nA".into()))
1181        );
1182        // Unresolvable selector => None (fail-closed at the call site).
1183        assert_eq!(
1184            ExitNodeSelector::Ip("100.64.0.99".parse().unwrap()).resolve(it()),
1185            None
1186        );
1187        assert_eq!(ExitNodeSelector::Name("ghost".into()).resolve(it()), None);
1188    }
1189
1190    #[test]
1191    fn exit_node_selector_resolution_is_deterministic_on_ties() {
1192        // Two peers sharing a name (transient netmap state): the smallest stable id wins, so the
1193        // outbound table and inbound source filter — which resolve independently — agree.
1194        let a = exit_node_with("nZ", "100.64.0.5", "dup", Some("ts.net"));
1195        let b = exit_node_with("nA", "100.64.0.6", "dup", Some("ts.net"));
1196        let peers = [a, b];
1197
1198        assert_eq!(
1199            ExitNodeSelector::Name("dup".into()).resolve(peers.iter()),
1200            Some(StableId("nA".into())),
1201            "smallest stable id wins the tie"
1202        );
1203        // Order of iteration must not change the result.
1204        assert_eq!(
1205            ExitNodeSelector::Name("dup".into()).resolve(peers.iter().rev()),
1206            Some(StableId("nA".into()))
1207        );
1208    }
1209
1210    #[test]
1211    fn peerapi_doh_url_requires_port_and_capability() {
1212        let mut n = node("exit", Some("ts.net"));
1213        n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1214
1215        // No peerAPI port advertised: cannot proxy DNS.
1216        n.peerapi_port = None;
1217        n.cap = CapabilityVersion::V130;
1218        assert_eq!(n.peerapi_doh_url(), None);
1219
1220        // Port advertised but capability too old and no explicit service: cannot proxy.
1221        n.peerapi_port = Some(8080);
1222        n.cap = CapabilityVersion::V25;
1223        n.peerapi_dns_proxy = false;
1224        assert_eq!(n.peerapi_doh_url(), None);
1225
1226        // Port + new-enough capability: yields the DoH URL on the IPv4 address.
1227        n.cap = CapabilityVersion::V26;
1228        assert_eq!(
1229            n.peerapi_doh_url().as_deref(),
1230            Some("http://100.64.0.5:8080/dns-query")
1231        );
1232
1233        // Port + explicit peerapi-dns-proxy service, even with an old capability.
1234        n.cap = CapabilityVersion::V25;
1235        n.peerapi_dns_proxy = true;
1236        assert_eq!(
1237            n.peerapi_doh_url().as_deref(),
1238            Some("http://100.64.0.5:8080/dns-query")
1239        );
1240
1241        // WireGuard-only peers never run a peerAPI: no DoH URL even with a port.
1242        n.is_wireguard_only = true;
1243        assert_eq!(n.peerapi_doh_url(), None);
1244    }
1245
1246    #[test]
1247    fn peerapi_doh_addr_matches_url_gate() {
1248        let mut n = node("exit", Some("ts.net"));
1249        n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1250        n.peerapi_port = Some(8080);
1251        n.cap = CapabilityVersion::V26;
1252
1253        // The addr form the DoH client dials is the same gated endpoint as the URL.
1254        assert_eq!(
1255            n.peerapi_doh_addr(),
1256            Some("100.64.0.5:8080".parse().unwrap())
1257        );
1258        // And it composes into exactly the URL form.
1259        assert_eq!(
1260            n.peerapi_doh_url().as_deref(),
1261            Some("http://100.64.0.5:8080/dns-query")
1262        );
1263
1264        // Gated off the same way: no port => no addr.
1265        n.peerapi_port = None;
1266        assert_eq!(n.peerapi_doh_addr(), None);
1267    }
1268
1269    #[test]
1270    fn peerapi_addr_returns_addr_when_advertised() {
1271        let mut n = node("peer", Some("ts.net"));
1272        n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1273        n.peerapi_port = Some(8089);
1274
1275        // Not gated on the DNS-proxy capability: a plain advertised peerAPI port is enough.
1276        assert_eq!(n.peerapi_addr(), Some("100.64.0.5:8089".parse().unwrap()));
1277    }
1278
1279    #[test]
1280    fn peerapi_addr_none_when_no_port() {
1281        let mut n = node("peer", Some("ts.net"));
1282        n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1283        n.peerapi_port = None;
1284
1285        assert_eq!(n.peerapi_addr(), None);
1286    }
1287
1288    #[test]
1289    fn peerapi_addr_none_for_wireguard_only() {
1290        let mut n = node("peer", Some("ts.net"));
1291        n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1292        n.peerapi_port = Some(8089);
1293        n.is_wireguard_only = true;
1294
1295        // WireGuard-only peers run no peerAPI, even with a port set.
1296        assert_eq!(n.peerapi_addr(), None);
1297    }
1298
1299    #[test]
1300    fn peerapi_from_services_extracts_v4_port_and_dns_proxy_flag() {
1301        use ts_control_serde::{Service, ServiceProto};
1302
1303        let services = [
1304            Service {
1305                proto: ServiceProto::PeerApi4,
1306                port: 8080,
1307                description: "peerapi",
1308            },
1309            Service {
1310                proto: ServiceProto::PeerApi6,
1311                port: 9090,
1312                description: "peerapi6",
1313            },
1314            Service {
1315                proto: ServiceProto::PeerApiDnsProxy,
1316                port: 1,
1317                description: "dns",
1318            },
1319        ];
1320        let (port, dns_proxy) = peerapi_from_services(Some(&services));
1321        assert_eq!(port, Some(8080), "only the IPv4 peerAPI port is taken");
1322        assert!(dns_proxy);
1323
1324        // No services at all.
1325        assert_eq!(peerapi_from_services(None), (None, false));
1326    }
1327
1328    #[test]
1329    fn exit_node_selector_parses_ip_vs_name() {
1330        assert_eq!(
1331            "100.64.0.5".parse::<ExitNodeSelector>().unwrap(),
1332            ExitNodeSelector::Ip("100.64.0.5".parse().unwrap())
1333        );
1334        assert_eq!(
1335            "fd7a::5".parse::<ExitNodeSelector>().unwrap(),
1336            ExitNodeSelector::Ip("fd7a::5".parse().unwrap())
1337        );
1338        assert_eq!(
1339            "my-exit.ts.net".parse::<ExitNodeSelector>().unwrap(),
1340            ExitNodeSelector::Name("my-exit.ts.net".into())
1341        );
1342    }
1343}