geiserx_ts_runtime 0.15.0

tailscale runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Netmap status aggregation, WhoIs lookups, and a netmap-change watcher.
//!
//! These surface the internal netmap state ([`ts_control::StateUpdate`], consumed by the
//! [`PeerTracker`](crate::peer_tracker::PeerTracker)) to embedders, mirroring tsnet's
//! `LocalClient::Status`, `WhoIs`, and `WatchIPNBus`.
//!
//! ## Capability / user / online surfacing (do not fabricate)
//!
//! tsnet's `Status`/`WhoIs` also carry per-node *online* state, the owning *user* (login/profile),
//! and a *capability map*. Status of each in this fork:
//! - **Capabilities** — surfaced: [`WhoIs::capabilities`] is populated from the domain
//!   [`Node`](ts_control::Node)'s `cap_map` (the control-pushed `CapMap`), which the domain model
//!   retains.
//! - **User (login/profile)** — surfaced when the netmap provided it: [`WhoIs::user`] is the owning
//!   user's login/display name, resolved by joining the node's owning user id against the netmap's
//!   `UserProfiles` table (accumulated by the [`PeerTracker`](crate::peer_tracker::PeerTracker)
//!   across delta updates). `None` when control sent no profile for that user.
//! - **Online state** — surfaced: [`StatusNode::online`] / [`StatusNode::last_seen`] reflect the
//!   domain [`Node`](ts_control::Node)'s retained `online`/`last_seen`, populated from the netmap
//!   node and its online deltas (`PeerChange`, `MapResponse.online_change`/`peer_seen_change`).
//!   `online` stays tri-state (`None` = unknown), never fabricated to `false`.

use std::net::{IpAddr, SocketAddr};

use ts_control::{Node, StableNodeId, UserId};

/// A snapshot of the local netmap: this node plus every known peer.
///
/// Analogous to tsnet's `ipnstate.Status`. Built by [`Runtime::status`](crate::Runtime::status)
/// from the self node held by the control runner and the peers held by the peer tracker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Status {
    /// This node, if a netmap has been received from control yet.
    pub self_node: Option<StatusNode>,
    /// Every peer currently known in the netmap.
    pub peers: Vec<StatusNode>,
    /// The stable id of the exit node traffic is **currently** egressing through, if any (Go's
    /// `Status.ExitNodeStatus.ID`). This is the *resolved + fail-closed* answer from the route
    /// updater — `None` when no exit node is configured, the configured selector matches no peer, or
    /// the matched peer no longer advertises a default route — so it reflects what is actually
    /// engaged, not merely what [`Config::exit_node`](ts_control::Config) requested. Find the peer's
    /// details by matching this id against [`peers`](Status::peers).
    pub active_exit_node: Option<StableNodeId>,
    /// The tailnet's MagicDNS suffix (e.g. `"tail0123.ts.net"`) — Go `ipnstate.Status.MagicDNSSuffix`.
    /// Derived (like Go's `NetworkMap.MagicDNSSuffix`) from the self node's FQDN minus its host label,
    /// **not** from the DNS config and **not** from the tailnet `Domain` name. `None` before the first
    /// netmap, or when the self FQDN has no tailnet component (a bare hostname).
    pub magic_dns_suffix: Option<String>,
}

/// A single node entry in a [`Status`] snapshot.
///
/// Analogous to tsnet's `ipnstate.PeerStatus`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusNode {
    /// The node's stable id (stable across re-registration).
    pub stable_id: StableNodeId,
    /// A display name for the node: its fqdn if a tailnet component is known, else its bare
    /// hostname.
    pub display_name: String,
    /// The node's tailnet IPv4 address.
    pub ipv4: IpAddr,
    /// The node's tailnet IPv6 address.
    pub ipv6: IpAddr,
    /// Whether the node is online, if known (`ipnstate.PeerStatus.Online`). Tri-state: `Some(true)`
    /// connected to control, `Some(false)` offline, `None` unknown (control sent no online status or
    /// the local node lacks permission to know). Reflects control's liveness state, retained from the
    /// netmap node + its online deltas — `None` is *unknown*, never fabricated to `false`.
    pub online: Option<bool>,
    /// When control last saw this node online (`ipnstate.PeerStatus.LastSeen`). Per Go, only
    /// meaningful while the node is not currently online. `None` when unknown or never seen.
    pub last_seen: Option<chrono::DateTime<chrono::Utc>>,
    /// The routes this node accepts traffic for (its own `/32` and `/128`, plus any advertised
    /// subnet routes and possibly the exit-node default route).
    pub allowed_routes: Vec<ipnet::IpNet>,
    /// Whether this node advertises a default route (`0.0.0.0/0` or `::/0`), making it eligible to
    /// be selected as an exit node.
    pub is_exit_node: bool,
}

impl StatusNode {
    /// Build a [`StatusNode`] from a domain [`Node`].
    pub fn from_node(node: &Node) -> Self {
        let is_exit_node = node
            .accepted_routes
            .iter()
            .any(|route| route.prefix_len() == 0);

        Self {
            stable_id: node.stable_id.clone(),
            display_name: node
                .fqdn_opt(false)
                .unwrap_or_else(|| node.hostname.clone()),
            ipv4: node.tailnet_address.ipv4.addr().into(),
            ipv6: node.tailnet_address.ipv6.addr().into(),
            online: node.online,
            last_seen: node.last_seen,
            allowed_routes: node.accepted_routes.clone(),
            is_exit_node,
        }
    }
}

/// The result of a [`Runtime::whois`](crate::Runtime::whois) lookup: the node that owns a tailnet
/// source address, plus its user and capabilities.
///
/// Analogous to tsnet's `apitype.WhoIsResponse`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WhoIs {
    /// The node that owns the queried source IP.
    pub node: Node,
    /// The login/email of the user that owns the node, if known.
    ///
    /// Always `None` in this fork: the domain [`Node`](ts_control::Node) does not retain the
    /// wire-level user/login mapping (see the module-level capability/user gap note).
    pub user: Option<String>,
    /// The node's capability map, as `(capability, args)` pairs.
    ///
    /// Populated from the domain [`Node`](ts_control::Node)'s `cap_map` (the control-pushed
    /// `CapMap`), sorted by capability name (the underlying map is a `BTreeMap`). Empty when control
    /// granted the node no capabilities. Mirrors tsnet's `WhoIsResponse.CapMap`.
    pub capabilities: Vec<(String, Vec<String>)>,
}

impl WhoIs {
    /// Build a [`WhoIs`] from the owning node and its resolved owner login/display name (if the
    /// netmap's `UserProfiles` table mapped the node's owning user id to a profile; `None` when
    /// control sent no profile — e.g. a tagged node with no human owner).
    ///
    /// `capabilities` is always populated from the node's `cap_map`.
    pub(crate) fn from_node_with_user(node: Node, user: Option<String>) -> Self {
        let capabilities = node
            .cap_map
            .iter()
            .map(|(cap, args)| (cap.clone(), args.clone()))
            .collect();
        Self {
            node,
            user,
            capabilities,
        }
    }
}

/// Resolve which node owns a tailnet source address, used by WhoIs.
pub(crate) fn whois_addr(addr: SocketAddr) -> IpAddr {
    addr.ip()
}

/// A tailnet peer this node can send a Taildrop file *to*, plus the peerAPI base URL to reach it.
///
/// Analogous to tsnet's `apitype.FileTarget`. The set is produced by
/// [`Runtime::file_targets`](crate::Runtime::file_targets) (exposed as `Device::file_targets`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileTarget {
    /// The target peer's node record — pass straight to the Taildrop send path
    /// (`Device::send_file`), which re-derives the same peerAPI address.
    pub node: Node,
    /// The `http://ip:port` base URL of the peer's peerAPI, with no trailing path — the exact shape
    /// of Go's `apitype.FileTarget.PeerAPIURL`. Derived from
    /// [`Node::peerapi_addr`](ts_control::Node::peerapi_addr).
    pub peerapi_url: String,
}

/// Compute the sorted Taildrop send-target list from the peer set, given the local node's owning
/// user id. The pure core of [`Runtime::file_targets`](crate::Runtime::file_targets) — separated out
/// so the eligibility + ordering rules are unit-testable without spinning up the actor graph (the
/// node-level file-sharing gate is applied by the caller before this runs).
///
/// A peer is a target when it advertises a reachable peerAPI (Go `PeerAPIBase(p) != ""`) **and** is
/// either owned by `self_user_id` **or** carries the file-sharing-target capability — Go's two-way
/// OR. Sorted by MagicDNS name (Go sorts by `Node.Name`), falling back to the bare hostname.
pub(crate) fn build_file_targets(peers: Vec<Node>, self_user_id: UserId) -> Vec<FileTarget> {
    let mut targets: Vec<FileTarget> = peers
        .into_iter()
        .filter_map(|peer| {
            // Must advertise a reachable peerAPI (Go `PeerAPIBase(p) != ""`).
            let addr = peer.peerapi_addr()?;
            // Same owner OR explicitly an ACL file-sharing target (Go's two-way OR).
            let eligible = peer.user_id == self_user_id || peer.is_file_sharing_target();
            if !eligible {
                return None;
            }
            Some(FileTarget {
                peerapi_url: format!("http://{addr}"),
                node: peer,
            })
        })
        .collect();
    // Sort by MagicDNS name (Go sorts by `Node.Name`), bare hostname as the fallback key.
    targets.sort_by(|a, b| {
        let name = |t: &FileTarget| {
            t.node
                .fqdn_opt(false)
                .unwrap_or_else(|| t.node.hostname.clone())
        };
        name(a).cmp(&name(b))
    });
    targets
}

#[cfg(test)]
mod tests {
    use ts_control::{Node, StableNodeId, TailnetAddress};

    use super::*;

    fn node(stable: &str, hostname: &str, tailnet: Option<&str>, ipv4: &str) -> Node {
        Node {
            id: 1,
            stable_id: StableNodeId(stable.to_string()),
            hostname: hostname.to_string(),
            user_id: 0,
            tailnet: tailnet.map(str::to_string),
            tags: vec![],
            tailnet_address: TailnetAddress {
                ipv4: format!("{ipv4}/32").parse().unwrap(),
                ipv6: "fd7a::1/128".parse().unwrap(),
            },
            node_key: [0u8; 32].into(),
            node_key_expiry: None,
            online: None,
            last_seen: None,
            key_signature: vec![],
            machine_key: None,
            disco_key: None,
            accepted_routes: vec![],
            underlay_addresses: vec![],
            derp_region: None,
            cap: Default::default(),
            cap_map: Default::default(),
            peerapi_port: None,
            peerapi_dns_proxy: false,
            is_wireguard_only: false,
            exit_node_dns_resolvers: vec![],
            peer_relay: false,
            service_vips: Default::default(),
        }
    }

    #[test]
    fn status_node_display_name_prefers_fqdn() {
        let with_tailnet = node("n1", "host", Some("ts.net"), "100.64.0.1");
        assert_eq!(
            StatusNode::from_node(&with_tailnet).display_name,
            "host.ts.net"
        );

        let bare = node("n2", "solo", None, "100.64.0.2");
        assert_eq!(StatusNode::from_node(&bare).display_name, "solo");
    }

    #[test]
    fn status_node_addresses_and_online_surfaced() {
        let n = node("n1", "host", Some("ts.net"), "100.64.0.7");
        let s = StatusNode::from_node(&n);

        assert_eq!(s.ipv4, "100.64.0.7".parse::<IpAddr>().unwrap());
        assert_eq!(s.ipv6, "fd7a::1".parse::<IpAddr>().unwrap());
        // A node with no online data surfaces `None` (unknown) — never a fabricated `false`.
        assert_eq!(s.online, None);
        assert_eq!(s.last_seen, None);

        // A node whose domain online state is known surfaces it through StatusNode (no longer
        // hardwired to None).
        let mut online = node("n2", "up", Some("ts.net"), "100.64.0.8");
        online.online = Some(true);
        assert_eq!(StatusNode::from_node(&online).online, Some(true));

        let mut offline = node("n3", "down", Some("ts.net"), "100.64.0.9");
        offline.online = Some(false);
        assert_eq!(StatusNode::from_node(&offline).online, Some(false));
    }

    #[test]
    fn status_node_detects_exit_node() {
        let mut not_exit = node("n1", "a", Some("ts.net"), "100.64.0.1");
        not_exit.accepted_routes = vec!["100.64.0.1/32".parse().unwrap()];
        assert!(!StatusNode::from_node(&not_exit).is_exit_node);

        let mut exit = node("n2", "b", Some("ts.net"), "100.64.0.2");
        exit.accepted_routes = vec![
            "100.64.0.2/32".parse().unwrap(),
            "0.0.0.0/0".parse().unwrap(),
        ];
        assert!(StatusNode::from_node(&exit).is_exit_node);

        let mut exit6 = node("n3", "c", Some("ts.net"), "100.64.0.3");
        exit6.accepted_routes = vec!["::/0".parse().unwrap()];
        assert!(StatusNode::from_node(&exit6).is_exit_node);
    }

    #[test]
    fn whois_caps_empty_when_node_has_none() {
        // A node with no cap_map surfaces empty capabilities (not fabricated), and no user unless a
        // profile was joined in.
        let n = node("n1", "host", Some("ts.net"), "100.64.0.9");
        let whois = WhoIs::from_node_with_user(n.clone(), None);

        assert_eq!(whois.node, n);
        assert_eq!(whois.user, None);
        assert!(whois.capabilities.is_empty());
    }

    #[test]
    fn whois_populates_capabilities_from_cap_map() {
        // WhoIs surfaces the domain Node's cap_map verbatim, sorted by capability name (BTreeMap).
        let mut n = node("n1", "host", Some("ts.net"), "100.64.0.9");
        n.cap_map
            .insert("https://tailscale.com/cap/is-admin".to_string(), vec![]);
        n.cap_map.insert(
            "cap/ssh".to_string(),
            vec!["root".to_string(), "ubuntu".to_string()],
        );
        let whois = WhoIs::from_node_with_user(n, None);

        // BTreeMap iteration is sorted: "cap/ssh" < "https://…".
        assert_eq!(
            whois.capabilities,
            vec![
                (
                    "cap/ssh".to_string(),
                    vec!["root".to_string(), "ubuntu".to_string()]
                ),
                ("https://tailscale.com/cap/is-admin".to_string(), vec![]),
            ]
        );
    }

    #[test]
    fn whois_from_node_with_user_sets_user_and_caps() {
        let mut n = node("n1", "host", Some("ts.net"), "100.64.0.9");
        n.cap_map.insert("cap/x".to_string(), vec!["y".to_string()]);
        let whois = WhoIs::from_node_with_user(n, Some("alice@example.com".to_string()));

        assert_eq!(whois.user, Some("alice@example.com".to_string()));
        assert_eq!(
            whois.capabilities,
            vec![("cap/x".to_string(), vec!["y".to_string()])]
        );
    }

    /// Build a peer with a reachable peerAPI on `ipv4`, owned by `user`.
    fn peer_with_peerapi(stable: &str, hostname: &str, ipv4: &str, user: UserId) -> Node {
        let mut n = node(stable, hostname, Some("ts.net"), ipv4);
        n.user_id = user;
        n.peerapi_port = Some(8089);
        n
    }

    #[test]
    fn file_targets_includes_same_owner_peer_with_peerapi() {
        let peer = peer_with_peerapi("p1", "host", "100.64.0.5", 42);
        let targets = build_file_targets(vec![peer], 42);

        assert_eq!(targets.len(), 1);
        assert_eq!(targets[0].peerapi_url, "http://100.64.0.5:8089");
        assert_eq!(targets[0].node.hostname, "host");
    }

    #[test]
    fn file_targets_includes_cross_owner_peer_with_target_cap() {
        // Different owner, but carries the file-sharing-target cap → still a target (Go's OR).
        let mut peer = peer_with_peerapi("p1", "host", "100.64.0.5", 99);
        peer.cap_map
            .insert("tailscale.com/cap/file-sharing-target".to_string(), vec![]);
        let targets = build_file_targets(vec![peer], 42);

        assert_eq!(
            targets.len(),
            1,
            "cross-owner peer with the target cap qualifies"
        );
    }

    #[test]
    fn file_targets_excludes_cross_owner_peer_without_cap() {
        // Different owner and no target cap → excluded.
        let peer = peer_with_peerapi("p1", "host", "100.64.0.5", 99);
        let targets = build_file_targets(vec![peer], 42);

        assert!(
            targets.is_empty(),
            "a different owner without the cap is not a target"
        );
    }

    #[test]
    fn file_targets_excludes_peer_without_peerapi() {
        // Same owner, but advertises no peerAPI (no port) → excluded (Go `PeerAPIBase(p) == ""`).
        let mut peer = peer_with_peerapi("p1", "host", "100.64.0.5", 42);
        peer.peerapi_port = None;
        let targets = build_file_targets(vec![peer], 42);

        assert!(
            targets.is_empty(),
            "a peer with no peerAPI cannot be a Taildrop target"
        );
    }

    #[test]
    fn file_targets_sorted_by_magic_dns_name() {
        // Insert out of order; expect sorted by fqdn ("alpha.ts.net" < "zeta.ts.net").
        let zeta = peer_with_peerapi("p2", "zeta", "100.64.0.6", 42);
        let alpha = peer_with_peerapi("p1", "alpha", "100.64.0.5", 42);
        let targets = build_file_targets(vec![zeta, alpha], 42);

        let names: Vec<_> = targets.iter().map(|t| t.node.hostname.clone()).collect();
        assert_eq!(names, vec!["alpha", "zeta"]);
    }
}