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