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