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