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 Self {
694 id: value.id,
695 stable_id: StableId(value.stable_id.0.to_string()),
696
697 hostname: hostname.to_owned(),
698 user_id: value.user,
699 tailnet,
700
701 tags: value
702 .tags
703 .as_ref()
704 .map(|x| x.iter().map(|x| x.to_string()).collect())
705 .unwrap_or_default(),
706
707 tailnet_address: TailnetAddress {
708 ipv4: value.addresses.0,
709 ipv6: value.addresses.1,
710 },
711 node_key: value.key,
712 node_key_expiry: value.key_expiry,
713 key_signature: value.key_signature.to_vec(),
714 machine_key: value.machine,
715 disco_key: value.disco_key,
716
717 accepted_routes: value
718 .allowed_ips
719 .clone()
720 .unwrap_or_else(|| vec![value.addresses.0.into(), value.addresses.1.into()]),
721 underlay_addresses: value.endpoints.clone(),
722
723 // legacy_derp_string is still in practical use as of 3/2026
724 #[allow(deprecated)]
725 derp_region: value
726 .home_derp
727 .or(value.legacy_derp_string)
728 .or_else(|| value.host_info.net_info.as_ref()?.preferred_derp)
729 .map(|x| ts_derp::RegionId(x.into())),
730
731 cap: value.cap,
732 cap_map,
733 peerapi_port,
734 peerapi_dns_proxy,
735 is_wireguard_only: value.is_wireguard_only,
736 exit_node_dns_resolvers: value
737 .exit_node_dns_resolvers
738 .iter()
739 .filter_map(Resolver::from_serde)
740 .collect(),
741 peer_relay: value.host_info.peer_relay,
742 service_vips,
743 }
744 }
745}
746
747/// Display-friendly identity for the user that owns a [`Node`], resolved from the netmap's
748/// `UserProfiles` table (Go `tailcfg.UserProfile`). Owned counterpart of the borrow-bound
749/// [`ts_control_serde::UserProfile`]. Keyed by [`UserProfile::id`] (== [`Node::user_id`]).
750#[derive(Debug, Clone, PartialEq, Eq)]
751pub struct UserProfile {
752 /// The integer id of the Tailscale user this profile describes (matches [`Node::user_id`]).
753 pub id: ts_control_serde::UserId,
754 /// An email-ish login name for display (e.g. `alice@example.com` / `alice@github`). May be
755 /// empty if control sent none.
756 pub login_name: String,
757 /// The user's display name (e.g. `Alice Smith`), if the IdP provided one.
758 pub display_name: Option<String>,
759}
760
761impl From<&ts_control_serde::UserProfile<'_>> for UserProfile {
762 fn from(value: &ts_control_serde::UserProfile) -> Self {
763 Self {
764 id: value.id,
765 login_name: value.login_name.to_string(),
766 display_name: value.display_name.map(str::to_string),
767 }
768 }
769}
770
771impl UserProfile {
772 /// The best human-facing label for this user: the login name when present, else the display
773 /// name, else `None`. This is what a `WhoIs` surfaces as the owning user.
774 pub fn best_label(&self) -> Option<String> {
775 if !self.login_name.is_empty() {
776 Some(self.login_name.clone())
777 } else {
778 self.display_name.clone()
779 }
780 }
781}
782
783#[cfg(test)]
784mod tests {
785 use super::*;
786
787 /// The wire `Node.User` id must be carried onto the domain `Node.user_id` by the `From` impl
788 /// (the field the runtime joins against the netmap `UserProfiles` table for `WhoIs.user`).
789 /// Guards against the `From` impl wiring the wrong serde field or dropping it.
790 #[test]
791 fn from_wire_node_carries_user_id() {
792 let mut wire = ts_control_serde::Node {
793 user: 4242,
794 ..Default::default()
795 };
796 wire.name = "host.tail.ts.net.";
797 let domain: Node = (&wire).into();
798 assert_eq!(domain.user_id, 4242);
799
800 // Default (no owner / tagged node) stays 0.
801 let tagged = ts_control_serde::Node::default();
802 assert_eq!(Node::from(&tagged).user_id, 0);
803 }
804
805 #[test]
806 fn key_expiry_semantics() {
807 let now: DateTime<Utc> = "2026-06-05T00:00:00Z".parse().unwrap();
808 let past: DateTime<Utc> = "2020-01-01T00:00:00Z".parse().unwrap();
809 let future: DateTime<Utc> = "2099-01-01T00:00:00Z".parse().unwrap();
810
811 let mut n = node("h", Some("t.ts.net"));
812
813 // No expiry set => never expired (Go zero-value semantics).
814 n.node_key_expiry = None;
815 assert!(!n.key_expired(now));
816 assert_eq!(n.key_expiry(), None);
817
818 // Future expiry => not yet expired.
819 n.node_key_expiry = Some(future);
820 assert!(!n.key_expired(now));
821 assert_eq!(n.key_expiry(), Some(future));
822
823 // Past expiry => expired.
824 n.node_key_expiry = Some(past);
825 assert!(n.key_expired(now));
826 }
827
828 #[test]
829 fn key_expiry_unix_agrees_with_chrono() {
830 // The chrono-free variants (`key_expired_at_unix` / `key_expiry_unix`) must agree with the
831 // chrono variants for the same none/future/past cases (Unix seconds of the same instants).
832 let now: DateTime<Utc> = "2026-06-05T00:00:00Z".parse().unwrap();
833 let past: DateTime<Utc> = "2020-01-01T00:00:00Z".parse().unwrap();
834 let future: DateTime<Utc> = "2099-01-01T00:00:00Z".parse().unwrap();
835 let now_unix = now.timestamp();
836
837 let mut n = node("h", Some("t.ts.net"));
838
839 // No expiry => never expired; the unix accessor reports `None`.
840 n.node_key_expiry = None;
841 assert_eq!(n.key_expired(now), n.key_expired_at_unix(now_unix));
842 assert!(!n.key_expired_at_unix(now_unix));
843 assert_eq!(n.key_expiry_unix(), None);
844
845 // Future expiry => not yet expired; unix accessor matches the chrono timestamp.
846 n.node_key_expiry = Some(future);
847 assert_eq!(n.key_expired(now), n.key_expired_at_unix(now_unix));
848 assert!(!n.key_expired_at_unix(now_unix));
849 assert_eq!(n.key_expiry_unix(), Some(future.timestamp()));
850
851 // Past expiry => expired; unix accessor matches the chrono timestamp.
852 n.node_key_expiry = Some(past);
853 assert_eq!(n.key_expired(now), n.key_expired_at_unix(now_unix));
854 assert!(n.key_expired_at_unix(now_unix));
855 assert_eq!(n.key_expiry_unix(), Some(past.timestamp()));
856 }
857
858 #[test]
859 fn key_expiry_boundary_is_not_expired() {
860 // A key whose expiry exactly equals `now` is NOT expired: the code uses strict `<`, matching
861 // Go's `Before`. Both the chrono and chrono-free variants must agree at the boundary.
862 let now: DateTime<Utc> = "2026-06-05T00:00:00Z".parse().unwrap();
863 let now_unix = now.timestamp();
864
865 let mut n = node("h", Some("t.ts.net"));
866 n.node_key_expiry = Some(now);
867
868 assert!(!n.key_expired(now));
869 assert!(!n.key_expired_at_unix(now_unix));
870 }
871
872 #[test]
873 fn is_peer_relay_returns_field() {
874 let mut n = node("h", Some("t.ts.net"));
875
876 n.peer_relay = true;
877 assert!(n.is_peer_relay());
878
879 n.peer_relay = false;
880 assert!(!n.is_peer_relay());
881 }
882
883 fn node(hostname: &str, tailnet: Option<&str>) -> Node {
884 Node {
885 id: 1,
886 stable_id: StableId("n1".to_string()),
887 hostname: hostname.to_string(),
888 user_id: 0,
889 tailnet: tailnet.map(str::to_string),
890 tags: vec![],
891 tailnet_address: TailnetAddress {
892 ipv4: "100.64.0.1/32".parse().unwrap(),
893 ipv6: "fd7a::1/128".parse().unwrap(),
894 },
895 node_key: [0u8; 32].into(),
896 node_key_expiry: None,
897 key_signature: vec![],
898 machine_key: None,
899 disco_key: None,
900 accepted_routes: vec![],
901 underlay_addresses: vec![],
902 derp_region: None,
903 cap: CapabilityVersion::default(),
904 cap_map: NodeCapMap::new(),
905 peerapi_port: None,
906 peerapi_dns_proxy: false,
907 is_wireguard_only: false,
908 exit_node_dns_resolvers: vec![],
909 peer_relay: false,
910 service_vips: Default::default(),
911 }
912 }
913
914 #[test]
915 fn matches_name_is_case_and_trailing_dot_insensitive() {
916 let n = node("MyHost", Some("tail-scale.ts.net"));
917
918 // bare hostname, any case
919 assert!(n.matches_name("myhost"));
920 assert!(n.matches_name("MYHOST"));
921 assert!(n.matches_name("MyHost"));
922
923 // fqdn, any case, with and without trailing dot
924 assert!(n.matches_name("myhost.tail-scale.ts.net"));
925 assert!(n.matches_name("MYHOST.TAIL-SCALE.TS.NET"));
926 assert!(n.matches_name("myhost.tail-scale.ts.net."));
927 assert!(n.matches_name("MyHost.Tail-Scale.TS.NET."));
928
929 // wrong host / wrong tailnet must not match
930 assert!(!n.matches_name("other"));
931 assert!(!n.matches_name("myhost.other.ts.net"));
932 }
933
934 #[test]
935 fn matches_name_no_tailnet() {
936 let n = node("solo", None);
937 assert!(n.matches_name("solo"));
938 assert!(n.matches_name("SOLO."));
939 assert!(!n.matches_name("solo.ts.net"));
940 }
941
942 #[test]
943 fn is_tailscale_ip_ranges() {
944 // CGNAT v4
945 assert!(is_tailscale_ip("100.64.0.1".parse().unwrap()));
946 assert!(is_tailscale_ip("100.127.255.254".parse().unwrap()));
947 // ChromeOS carve-out is excluded
948 assert!(!is_tailscale_ip("100.115.92.5".parse().unwrap()));
949 // outside CGNAT
950 assert!(!is_tailscale_ip("10.0.0.1".parse().unwrap()));
951 assert!(!is_tailscale_ip("100.128.0.1".parse().unwrap()));
952 // Tailscale ULA v6
953 assert!(is_tailscale_ip("fd7a:115c:a1e0::1".parse().unwrap()));
954 assert!(!is_tailscale_ip("fd00::1".parse().unwrap()));
955 }
956
957 /// Taildrop SSRF guard (defense-in-depth). `Device::send_file` rejects an upload destination
958 /// unless `is_tailscale_ip(peer.peerapi_addr().ip())` holds. `Device::send_file` itself needs a
959 /// live runtime (it goes through `self.channel()`), so it can't be unit-tested here; instead we
960 /// test the exact composition the guard relies on — `is_tailscale_ip ∘ peerapi_addr` — against a
961 /// `Node` whose `tailnet_address.ipv4` has been corrupted to a non-CGNAT (public) address. A
962 /// well-formed peer always has a CGNAT 100.64.0.0/10 address, but the guard exists to catch a
963 /// malformed/hostile node; this proves it would reject one.
964 #[test]
965 fn taildrop_ssrf_guard_rejects_non_cgnat_peerapi_addr() {
966 let mut n = node("evil", Some("ts.net"));
967 // Corrupt the peer to a public, non-CGNAT address and advertise a peerAPI port so
968 // `peerapi_addr` returns `Some(_)`.
969 n.tailnet_address.ipv4 = "1.2.3.4/32".parse().unwrap();
970 n.peerapi_port = Some(443);
971
972 let addr = n
973 .peerapi_addr()
974 .expect("peerapi_addr yields Some with a port set");
975 assert_eq!(addr.ip(), Ipv4Addr::new(1, 2, 3, 4));
976 // The guard `if !is_tailscale_ip(dst.ip()) { return Err(BadRequest) }` WOULD reject this.
977 assert!(
978 !is_tailscale_ip(addr.ip()),
979 "SSRF guard must reject a peer whose peerAPI addr is not a Tailscale CGNAT IP"
980 );
981
982 // Conversely, a well-formed CGNAT peer passes the guard.
983 let mut good = node("friend", Some("ts.net"));
984 good.peerapi_port = Some(443);
985 let good_addr = good.peerapi_addr().expect("peerapi_addr yields Some");
986 assert!(is_tailscale_ip(good_addr.ip()));
987 }
988
989 #[test]
990 fn is_subnet_route_distinguishes_self_from_subnet() {
991 let n = node("host", Some("ts.net"));
992
993 // The node's own /32 and /128 are self-addresses, not subnet routes.
994 assert!(!n.is_subnet_route(&"100.64.0.1/32".parse().unwrap()));
995 assert!(!n.is_subnet_route(&"fd7a::1/128".parse().unwrap()));
996 // A different single Tailscale IP is still a self-address (Tailscale-assigned host).
997 assert!(!n.is_subnet_route(&"100.64.5.5/32".parse().unwrap()));
998 // A LAN /24 the node advertises is a subnet route.
999 assert!(n.is_subnet_route(&"192.168.1.0/24".parse().unwrap()));
1000 // A single non-Tailscale host IP counts as a subnet route.
1001 assert!(n.is_subnet_route(&"8.8.8.8/32".parse().unwrap()));
1002 // The default route is treated as a subnet route.
1003 assert!(n.is_subnet_route(&"0.0.0.0/0".parse().unwrap()));
1004 assert!(n.is_subnet_route(&"::/0".parse().unwrap()));
1005 }
1006
1007 #[test]
1008 fn routes_to_install_gates_subnets_on_accept_routes() {
1009 let mut n = node("host", Some("ts.net"));
1010 let self4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
1011 let self6: ipnet::IpNet = "fd7a::1/128".parse().unwrap();
1012 let subnet: ipnet::IpNet = "192.168.1.0/24".parse().unwrap();
1013 n.accepted_routes = vec![self4, self6, subnet];
1014
1015 // accept_routes off: only the self addresses are installed.
1016 let off: Vec<_> = n.routes_to_install(false, None).copied().collect();
1017 assert_eq!(off, vec![self4, self6]);
1018
1019 // accept_routes on: the advertised subnet is installed too.
1020 let on: Vec<_> = n.routes_to_install(true, None).copied().collect();
1021 assert_eq!(on, vec![self4, self6, subnet]);
1022 }
1023
1024 #[test]
1025 fn routes_to_install_default_route_only_for_selected_exit_node() {
1026 let mut n = node("host", Some("ts.net"));
1027 n.stable_id = StableId("exit1".to_string());
1028 let self4: ipnet::IpNet = "100.64.0.1/32".parse().unwrap();
1029 let default4: ipnet::IpNet = "0.0.0.0/0".parse().unwrap();
1030 let default6: ipnet::IpNet = "::/0".parse().unwrap();
1031 n.accepted_routes = vec![self4, default4, default6];
1032
1033 // No exit node selected: default routes are excluded even with accept_routes on
1034 // (fail-closed — internet-bound traffic has no overlay route and is dropped).
1035 let none_off: Vec<_> = n.routes_to_install(false, None).copied().collect();
1036 assert_eq!(none_off, vec![self4]);
1037 let none_on: Vec<_> = n.routes_to_install(true, None).copied().collect();
1038 assert_eq!(none_on, vec![self4]);
1039
1040 // A *different* peer selected as exit node: this peer still gets no default route.
1041 let other = StableId("exit2".to_string());
1042 let other_sel: Vec<_> = n.routes_to_install(false, Some(&other)).copied().collect();
1043 assert_eq!(other_sel, vec![self4]);
1044
1045 // This peer selected as the exit node: its default routes are installed.
1046 let me = StableId("exit1".to_string());
1047 let sel: Vec<_> = n.routes_to_install(false, Some(&me)).copied().collect();
1048 assert_eq!(sel, vec![self4, default4, default6]);
1049 }
1050
1051 fn exit_node_with(id: &str, ipv4: &str, hostname: &str, tailnet: Option<&str>) -> Node {
1052 let mut n = node(hostname, tailnet);
1053 n.stable_id = StableId(id.to_string());
1054 n.tailnet_address.ipv4 = format!("{ipv4}/32").parse().unwrap();
1055 n
1056 }
1057
1058 #[test]
1059 fn exit_node_selector_resolves_by_id_ip_and_name() {
1060 let a = exit_node_with("nA", "100.64.0.5", "alpha", Some("ts.net"));
1061 let b = exit_node_with("nB", "100.64.0.6", "beta", Some("ts.net"));
1062 let peers = [a, b];
1063 let it = || peers.iter();
1064
1065 // By stable id.
1066 assert_eq!(
1067 ExitNodeSelector::StableId(StableId("nB".into())).resolve(it()),
1068 Some(StableId("nB".into()))
1069 );
1070 // By tailnet IP.
1071 assert_eq!(
1072 ExitNodeSelector::Ip("100.64.0.5".parse().unwrap()).resolve(it()),
1073 Some(StableId("nA".into()))
1074 );
1075 // By MagicDNS name (fqdn, case-insensitive).
1076 assert_eq!(
1077 ExitNodeSelector::Name("BETA.ts.net".into()).resolve(it()),
1078 Some(StableId("nB".into()))
1079 );
1080 // By bare hostname.
1081 assert_eq!(
1082 ExitNodeSelector::Name("alpha".into()).resolve(it()),
1083 Some(StableId("nA".into()))
1084 );
1085 // Unresolvable selector => None (fail-closed at the call site).
1086 assert_eq!(
1087 ExitNodeSelector::Ip("100.64.0.99".parse().unwrap()).resolve(it()),
1088 None
1089 );
1090 assert_eq!(ExitNodeSelector::Name("ghost".into()).resolve(it()), None);
1091 }
1092
1093 #[test]
1094 fn exit_node_selector_resolution_is_deterministic_on_ties() {
1095 // Two peers sharing a name (transient netmap state): the smallest stable id wins, so the
1096 // outbound table and inbound source filter — which resolve independently — agree.
1097 let a = exit_node_with("nZ", "100.64.0.5", "dup", Some("ts.net"));
1098 let b = exit_node_with("nA", "100.64.0.6", "dup", Some("ts.net"));
1099 let peers = [a, b];
1100
1101 assert_eq!(
1102 ExitNodeSelector::Name("dup".into()).resolve(peers.iter()),
1103 Some(StableId("nA".into())),
1104 "smallest stable id wins the tie"
1105 );
1106 // Order of iteration must not change the result.
1107 assert_eq!(
1108 ExitNodeSelector::Name("dup".into()).resolve(peers.iter().rev()),
1109 Some(StableId("nA".into()))
1110 );
1111 }
1112
1113 #[test]
1114 fn peerapi_doh_url_requires_port_and_capability() {
1115 let mut n = node("exit", Some("ts.net"));
1116 n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1117
1118 // No peerAPI port advertised: cannot proxy DNS.
1119 n.peerapi_port = None;
1120 n.cap = CapabilityVersion::V130;
1121 assert_eq!(n.peerapi_doh_url(), None);
1122
1123 // Port advertised but capability too old and no explicit service: cannot proxy.
1124 n.peerapi_port = Some(8080);
1125 n.cap = CapabilityVersion::V25;
1126 n.peerapi_dns_proxy = false;
1127 assert_eq!(n.peerapi_doh_url(), None);
1128
1129 // Port + new-enough capability: yields the DoH URL on the IPv4 address.
1130 n.cap = CapabilityVersion::V26;
1131 assert_eq!(
1132 n.peerapi_doh_url().as_deref(),
1133 Some("http://100.64.0.5:8080/dns-query")
1134 );
1135
1136 // Port + explicit peerapi-dns-proxy service, even with an old capability.
1137 n.cap = CapabilityVersion::V25;
1138 n.peerapi_dns_proxy = true;
1139 assert_eq!(
1140 n.peerapi_doh_url().as_deref(),
1141 Some("http://100.64.0.5:8080/dns-query")
1142 );
1143
1144 // WireGuard-only peers never run a peerAPI: no DoH URL even with a port.
1145 n.is_wireguard_only = true;
1146 assert_eq!(n.peerapi_doh_url(), None);
1147 }
1148
1149 #[test]
1150 fn peerapi_doh_addr_matches_url_gate() {
1151 let mut n = node("exit", Some("ts.net"));
1152 n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1153 n.peerapi_port = Some(8080);
1154 n.cap = CapabilityVersion::V26;
1155
1156 // The addr form the DoH client dials is the same gated endpoint as the URL.
1157 assert_eq!(
1158 n.peerapi_doh_addr(),
1159 Some("100.64.0.5:8080".parse().unwrap())
1160 );
1161 // And it composes into exactly the URL form.
1162 assert_eq!(
1163 n.peerapi_doh_url().as_deref(),
1164 Some("http://100.64.0.5:8080/dns-query")
1165 );
1166
1167 // Gated off the same way: no port => no addr.
1168 n.peerapi_port = None;
1169 assert_eq!(n.peerapi_doh_addr(), None);
1170 }
1171
1172 #[test]
1173 fn peerapi_addr_returns_addr_when_advertised() {
1174 let mut n = node("peer", Some("ts.net"));
1175 n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1176 n.peerapi_port = Some(8089);
1177
1178 // Not gated on the DNS-proxy capability: a plain advertised peerAPI port is enough.
1179 assert_eq!(n.peerapi_addr(), Some("100.64.0.5:8089".parse().unwrap()));
1180 }
1181
1182 #[test]
1183 fn peerapi_addr_none_when_no_port() {
1184 let mut n = node("peer", Some("ts.net"));
1185 n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1186 n.peerapi_port = None;
1187
1188 assert_eq!(n.peerapi_addr(), None);
1189 }
1190
1191 #[test]
1192 fn peerapi_addr_none_for_wireguard_only() {
1193 let mut n = node("peer", Some("ts.net"));
1194 n.tailnet_address.ipv4 = "100.64.0.5/32".parse().unwrap();
1195 n.peerapi_port = Some(8089);
1196 n.is_wireguard_only = true;
1197
1198 // WireGuard-only peers run no peerAPI, even with a port set.
1199 assert_eq!(n.peerapi_addr(), None);
1200 }
1201
1202 #[test]
1203 fn peerapi_from_services_extracts_v4_port_and_dns_proxy_flag() {
1204 use ts_control_serde::{Service, ServiceProto};
1205
1206 let services = [
1207 Service {
1208 proto: ServiceProto::PeerApi4,
1209 port: 8080,
1210 description: "peerapi",
1211 },
1212 Service {
1213 proto: ServiceProto::PeerApi6,
1214 port: 9090,
1215 description: "peerapi6",
1216 },
1217 Service {
1218 proto: ServiceProto::PeerApiDnsProxy,
1219 port: 1,
1220 description: "dns",
1221 },
1222 ];
1223 let (port, dns_proxy) = peerapi_from_services(Some(&services));
1224 assert_eq!(port, Some(8080), "only the IPv4 peerAPI port is taken");
1225 assert!(dns_proxy);
1226
1227 // No services at all.
1228 assert_eq!(peerapi_from_services(None), (None, false));
1229 }
1230
1231 #[test]
1232 fn exit_node_selector_parses_ip_vs_name() {
1233 assert_eq!(
1234 "100.64.0.5".parse::<ExitNodeSelector>().unwrap(),
1235 ExitNodeSelector::Ip("100.64.0.5".parse().unwrap())
1236 );
1237 assert_eq!(
1238 "fd7a::5".parse::<ExitNodeSelector>().unwrap(),
1239 ExitNodeSelector::Ip("fd7a::5".parse().unwrap())
1240 );
1241 assert_eq!(
1242 "my-exit.ts.net".parse::<ExitNodeSelector>().unwrap(),
1243 ExitNodeSelector::Name("my-exit.ts.net".into())
1244 );
1245 }
1246}