Skip to main content

ts_runtime/peer_tracker/
mod.rs

1//! Peer delta update tracking.
2
3use std::{
4    collections::{HashMap, HashSet},
5    net::IpAddr,
6    sync::Arc,
7};
8
9use kameo::{
10    actor::ActorRef,
11    message::{Context, Message},
12    reply::ReplySender,
13};
14use tokio::sync::watch;
15use ts_control::{Node, UserId, UserProfile};
16use ts_transport::PeerId;
17
18use crate::{Error, env::Env, status::StatusNode};
19
20mod peer_db;
21
22pub use peer_db::PeerDb;
23
24/// Actor that tracks peer delta updates and emits new states.
25pub struct PeerTracker {
26    peer_db: PeerDb,
27    seen_state_update: bool,
28    pending_requests: Vec<Pending>,
29    /// Latest peer snapshot, published on every netmap update so embedders can watch for peer
30    /// changes ([`WatchNetmap`]).
31    peer_watch: watch::Sender<Vec<StatusNode>>,
32    /// Accumulated netmap user profiles (`MapResponse.UserProfiles`), keyed by user id, joined
33    /// against a node's [`Node::user_id`](ts_control::Node::user_id) to resolve the owning user's
34    /// login/display name for a [`WhoIs`](crate::status::WhoIs). Control sends these incrementally
35    /// (only new/changed profiles per response), so this map **accumulates** across updates rather
36    /// than being replaced — a peer upserted in one response may reference a profile delivered in an
37    /// earlier one.
38    user_profiles: HashMap<UserId, UserProfile>,
39    /// Tailnet-Lock (TKA) authority used to verify each peer's `key_signature` at the peer-trust
40    /// chokepoint. When `Some`, enforcement is **active**: every upserted peer must present a
41    /// signature this authority authorizes, or it is rejected (fail-closed). When `None` (always,
42    /// this wave) enforcement is **inactive** and every peer is upserted — identical to pre-TKA
43    /// behavior. There is no live `Authority` source yet: building one requires the
44    /// `/machine/tka/sync` Noise RPC + AUM-chain replayer (deferred, see SECURITY.md). The
45    /// enforcement path below is wired and unit-tested, and flips on the instant an authority is
46    /// supplied; it is explicitly gated, not a silent no-op.
47    tka_authority: Option<ts_tka::Authority>,
48    /// Tailnet-Lock authority used **observe-only** (verify-and-LOG, issue #136): the live
49    /// `Authority` synced from control (delivered over the bus via [`TkaAuthorityUpdate`]). Distinct
50    /// from [`tka_authority`](Self::tka_authority) on purpose — populating *that* would flip the
51    /// runtime to fail-closed enforcement, whereas this field only feeds
52    /// [`tka_observe_log`](Self::tka_observe_log), which logs each peer's signature verdict and
53    /// **never** drops a peer. The current posture (per SECURITY.md / PARITY_ROADMAP): verify-and-log
54    /// while the `ts_tka` crypto is unaudited and control is treated as trusted; flipping to enforce
55    /// is a separate, gated decision.
56    tka_observe: Option<ts_tka::Authority>,
57    env: Env,
58}
59
60impl PeerTracker {
61    fn peer_by_name_opt(&self, name: &str) -> Option<&Node> {
62        // Canonicalization (case + trailing dot) is handled inside the name index lookup.
63        self.peer_db.get(&name).map(|(_id, node)| node)
64    }
65
66    fn peer_by_tailnet_ip_opt(&self, ip: IpAddr) -> Option<&Node> {
67        self.peer_db.get(&ip).map(|(_id, node)| node)
68    }
69
70    /// Build the peer entries for a [`Status`](crate::Status) snapshot from the current peer db.
71    ///
72    /// Connectivity fields (`cur_addr`/`relay`) are left at their `from_node` defaults (`None`) here:
73    /// this is the live-watch/hot path and must stay magicsock-free and synchronous. The explicit
74    /// [`GetStatus`] snapshot enriches them ([`status_peers_with_ids`](Self::status_peers_with_ids)).
75    fn status_peers(&self) -> Vec<StatusNode> {
76        self.peer_db
77            .peers()
78            .values()
79            .map(StatusNode::from_node)
80            .collect()
81    }
82
83    /// Like [`status_peers`](Self::status_peers) but pairs each entry with its [`PeerId`], so the
84    /// caller can join per-peer connectivity (the direct manager's `best_addrs`, keyed by `PeerId`)
85    /// onto the `StatusNode` before returning it. Order is unspecified (a `HashMap` walk).
86    fn status_peers_with_ids(&self) -> Vec<(PeerId, StatusNode)> {
87        self.peer_db
88            .peers()
89            .iter()
90            .map(|(id, node)| (*id, StatusNode::from_node(node)))
91            .collect()
92    }
93
94    fn whois_opt(&self, addr: std::net::SocketAddr) -> Option<crate::status::WhoIs> {
95        let ip = crate::status::whois_addr(addr);
96        let node = self.peer_by_tailnet_ip_opt(ip).cloned()?;
97        // Join the node's owning user id against the accumulated UserProfiles table to resolve a
98        // login/display name. `None` when control sent no profile for that user (e.g. tagged nodes
99        // with no human owner, or a profile not yet delivered).
100        let user = self.resolve_user(node.user_id);
101        Some(crate::status::WhoIs::from_node_with_user(node, user))
102    }
103
104    /// Resolve a user id to its best display label from the accumulated profile table.
105    fn resolve_user(&self, user_id: UserId) -> Option<String> {
106        self.user_profiles
107            .get(&user_id)
108            .and_then(UserProfile::best_label)
109    }
110
111    /// Whether `node` may be admitted to the peer db under the current Tailnet-Lock posture.
112    ///
113    /// Fail-closed and gated:
114    /// - No [`tka_authority`](Self::tka_authority) ⇒ enforcement inactive ⇒ always admit (today's
115    ///   behavior; this is the always-taken branch this wave).
116    /// - Authority present + peer carries a `key_signature` that the authority authorizes for the
117    ///   peer's node key ⇒ admit.
118    /// - Authority present + signature missing or unauthorized/invalid ⇒ **reject** (Go denies
119    ///   network access to unsigned peers under tailnet lock; we do not upsert them).
120    fn tka_admits(&self, node: &Node) -> bool {
121        let Some(auth) = &self.tka_authority else {
122            return true;
123        };
124
125        if node.key_signature.is_empty() {
126            // TKA active but peer presented no signature: reject (Go denies network access to
127            // unsigned peers under tailnet lock, unless UnsignedPeerAPIOnly — out of scope here).
128            tracing::warn!(
129                stable_id = ?node.stable_id,
130                "TKA: rejecting unsigned peer under tailnet lock"
131            );
132            return false;
133        }
134
135        if let Err(e) = auth.node_key_authorized(&node.node_key.to_bytes(), &node.key_signature) {
136            tracing::warn!(
137                stable_id = ?node.stable_id,
138                error = %e,
139                "TKA: rejecting peer with unauthorized node key"
140            );
141            return false;
142        }
143
144        true
145    }
146
147    /// Verify `node`'s Tailnet-Lock signature against the **observe-only** authority and LOG the
148    /// verdict — issue #136. This is the verify-and-log seam: it returns `()` (NOT a bool), so it is
149    /// structurally impossible to wire as an admission gate, and it is called *adjacent* to each
150    /// upsert site without affecting whether the peer is admitted. Every peer is upserted exactly as
151    /// it would be with this call absent.
152    ///
153    /// A no-op when no observe authority has been synced yet. Logs `verified` / `failed` / `unsigned`
154    /// with the peer's `stable_id` and, on failure, the `TkaError` Display (static descriptors —
155    /// "bad sig len" etc.). NEVER logs the node-key or signature bytes.
156    fn tka_observe_log(&self, node: &Node) {
157        let Some(auth) = &self.tka_observe else {
158            return;
159        };
160        if node.key_signature.is_empty() {
161            tracing::info!(
162                stable_id = ?node.stable_id,
163                tka_verdict = "unsigned",
164                "TKA observe: peer presented no key-signature (advisory, NOT enforced)"
165            );
166            return;
167        }
168        match auth.node_key_authorized(&node.node_key.to_bytes(), &node.key_signature) {
169            Ok(()) => tracing::info!(
170                stable_id = ?node.stable_id,
171                tka_verdict = "verified",
172                "TKA observe: peer node-key authorized (advisory, NOT enforced)"
173            ),
174            Err(e) => tracing::warn!(
175                stable_id = ?node.stable_id,
176                tka_verdict = "failed",
177                reason = %e,
178                "TKA observe: peer key-signature did not verify (advisory, NOT enforced)"
179            ),
180        }
181    }
182}
183
184impl kameo::Actor for PeerTracker {
185    type Args = Env;
186    type Error = Error;
187
188    async fn on_start(env: Self::Args, slf: ActorRef<Self>) -> Result<Self, Self::Error> {
189        env.subscribe::<Arc<ts_control::StateUpdate>>(&slf).await?;
190        // Observe-only TKA (#136): the control runner publishes the verified `Authority` here after a
191        // successful `/machine/tka/sync`; we use it to verify-and-LOG each peer's signature, never to
192        // enforce. The bus has no replay, so the control runner re-publishes on every sync.
193        env.subscribe::<TkaAuthorityUpdate>(&slf).await?;
194
195        let (peer_watch, _) = watch::channel(Vec::new());
196
197        Ok(Self {
198            peer_db: PeerDb::default(),
199            pending_requests: Default::default(),
200            seen_state_update: false,
201            peer_watch,
202            user_profiles: HashMap::new(),
203            // No live TKA *enforcement* authority this wave (fail-closed path stays gated off; see
204            // `tka_authority`). The observe-only authority (`tka_observe`) is supplied over the bus.
205            tka_authority: None,
206            tka_observe: None,
207            env,
208        })
209    }
210}
211
212enum Pending {
213    PeerByName(PeerByName, ReplySender<Option<Node>>),
214    AcceptedRoute(PeerByAcceptedRoute, ReplySender<Vec<Node>>),
215    TailnetIp(PeerByTailnetIp, ReplySender<Option<Node>>),
216    Status(ReplySender<Vec<(PeerId, StatusNode)>>),
217    WhoIs(Whois, ReplySender<Option<crate::status::WhoIs>>),
218}
219
220// For messages with arguments, a struct is generated with the args as fields. They aren't
221// documented, and we can't apply attributes directly to the fields. Hence, wrap in a module where
222// docs are turned off everywhere.
223#[allow(missing_docs)]
224mod msg_impl {
225    use std::net::IpAddr;
226
227    use kameo::prelude::DelegatedReply;
228
229    use super::*;
230
231    #[kameo::messages]
232    impl PeerTracker {
233        /// Lookup a peer by name.
234        ///
235        /// Waits until we've received at least one peer update from control.
236        #[message(ctx)]
237        pub async fn peer_by_name(
238            &mut self,
239            ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
240            name: String,
241        ) -> DelegatedReply<Option<Node>> {
242            let (deleg, sender) = ctx.reply_sender();
243            let Some(sender) = sender else { return deleg };
244
245            if !self.seen_state_update {
246                tracing::debug!(query = name, "no peer state seen yet, queueing request");
247
248                self.pending_requests
249                    .push(Pending::PeerByName(PeerByName { name }, sender));
250
251                return deleg;
252            }
253
254            sender.send(self.peer_by_name_opt(&name).cloned());
255
256            deleg
257        }
258
259        /// Lookup all peers that accept packets addressed to the given IP.
260        ///
261        /// This includes the peer's tailnet address and any subnet routes it provides. Only
262        /// the peers with the most specific subnet route match that covers `ip` will be
263        /// returned.
264        ///
265        /// E.g., suppose:
266        ///
267        /// - We're querying for `10.1.2.3`
268        /// - `PeerA` and `PeerB` have accepted routes for `10.1.2.0/24`
269        /// - `PeerC` has an accepted route for `10.1.0.0/16`
270        ///
271        /// Only `PeerA` and `PeerB` will be returned, since they have the most specific
272        /// prefix match.
273        #[message(ctx)]
274        pub fn peer_by_accepted_route(
275            &mut self,
276            ctx: &mut Context<Self, DelegatedReply<Vec<Node>>>,
277            ip: IpAddr,
278        ) -> DelegatedReply<Vec<Node>> {
279            let (deleg, sender) = ctx.reply_sender();
280            let Some(sender) = sender else { return deleg };
281
282            if !self.seen_state_update {
283                tracing::debug!(query = %ip, "no peer state seen yet, queueing request");
284
285                self.pending_requests
286                    .push(Pending::AcceptedRoute(PeerByAcceptedRoute { ip }, sender));
287
288                return deleg;
289            }
290
291            sender.send(
292                self.peer_db
293                    .get_route(ip.into())
294                    .map(|(_id, node)| node.clone())
295                    .collect(),
296            );
297
298            deleg
299        }
300
301        /// Lookup the peer that has the given tailnet IP address.
302        #[message(ctx)]
303        pub fn peer_by_tailnet_ip(
304            &mut self,
305            ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
306            ip: IpAddr,
307        ) -> DelegatedReply<Option<Node>> {
308            let (deleg, sender) = ctx.reply_sender();
309            let Some(sender) = sender else { return deleg };
310
311            if !self.seen_state_update {
312                tracing::debug!(query = %ip, "no peer state seen yet, queueing request");
313
314                self.pending_requests
315                    .push(Pending::TailnetIp(PeerByTailnetIp { ip }, sender));
316
317                return deleg;
318            }
319
320            sender.send(self.peer_by_tailnet_ip_opt(ip).cloned());
321
322            deleg
323        }
324
325        /// Build the peer entries of a [`Status`](crate::Status) snapshot, each paired with its
326        /// [`PeerId`] so [`Runtime::status`](crate::Runtime::status) can join per-peer connectivity
327        /// (`cur_addr`/`relay`) from the direct manager before returning. The self node is *not*
328        /// included here (it lives in the control runner); `Runtime::status` combines both and drops
329        /// the ids.
330        ///
331        /// Waits until we've received at least one peer update from control.
332        #[message(ctx)]
333        pub fn get_status(
334            &mut self,
335            ctx: &mut Context<Self, DelegatedReply<Vec<(PeerId, StatusNode)>>>,
336        ) -> DelegatedReply<Vec<(PeerId, StatusNode)>> {
337            let (deleg, sender) = ctx.reply_sender();
338            let Some(sender) = sender else { return deleg };
339
340            if !self.seen_state_update {
341                tracing::debug!("no peer state seen yet, queueing status request");
342                self.pending_requests.push(Pending::Status(sender));
343                return deleg;
344            }
345
346            sender.send(self.status_peers_with_ids());
347
348            deleg
349        }
350
351        /// Return every known peer's full domain [`Node`] (not the lossy [`StatusNode`]).
352        ///
353        /// Used by [`Runtime::file_targets`](crate::Runtime::file_targets), which needs the full node
354        /// (peerAPI address, owning user id, cap map) to compute Taildrop send targets. The self node
355        /// is not included (it lives in the control runner). Returns empty before the first netmap —
356        /// the natural "not connected yet" analog (an immediate answer, no queueing needed: callers
357        /// that need a populated list await `Running` first).
358        #[message]
359        pub fn all_peers(&self) -> Vec<Node> {
360            self.peer_db.peers().values().cloned().collect()
361        }
362
363        /// Resolve which node owns a tailnet source address.
364        ///
365        /// Maps the source IP of `addr` to the owning node via the tailnet-IP index, returning a
366        /// [`WhoIs`](crate::WhoIs). The port is ignored (a tailnet IP uniquely identifies a node).
367        ///
368        /// The resulting [`WhoIs`](crate::WhoIs) carries no user/login or capability data: this
369        /// fork's domain [`Node`](ts_control::Node) does not retain those wire fields. See the
370        /// [`status`](crate::status) module docs for the gap.
371        ///
372        /// Waits until we've received at least one peer update from control.
373        #[message(ctx)]
374        pub fn whois(
375            &mut self,
376            ctx: &mut Context<Self, DelegatedReply<Option<crate::status::WhoIs>>>,
377            addr: std::net::SocketAddr,
378        ) -> DelegatedReply<Option<crate::status::WhoIs>> {
379            let (deleg, sender) = ctx.reply_sender();
380            let Some(sender) = sender else { return deleg };
381
382            if !self.seen_state_update {
383                tracing::debug!(query = %addr, "no peer state seen yet, queueing whois request");
384                self.pending_requests
385                    .push(Pending::WhoIs(Whois { addr }, sender));
386                return deleg;
387            }
388
389            sender.send(self.whois_opt(addr));
390
391            deleg
392        }
393
394        /// Subscribe to netmap peer-change events.
395        ///
396        /// Returns a [`watch::Receiver`] whose value is the current set of peer
397        /// [`StatusNode`]s, updated on every netmap state update from control. Embedders can await
398        /// changes via [`watch::Receiver::changed`] to react to peers joining, leaving, or changing.
399        ///
400        /// The receiver's initial value is the peer set at subscription time (empty before the
401        /// first netmap update). This is a peer-only view; combine with the self node from
402        /// [`Runtime::status`](crate::Runtime::status) when a full snapshot is needed.
403        #[message(derive(Clone))]
404        pub fn watch_netmap(&self) -> watch::Receiver<Vec<StatusNode>> {
405            self.peer_watch.subscribe()
406        }
407    }
408}
409
410pub use msg_impl::*;
411
412#[derive(Debug, Clone)]
413pub(crate) struct PeerState {
414    #[allow(unused)]
415    pub deletions: HashSet<PeerId>,
416    #[allow(unused)]
417    pub upserts: HashSet<PeerId>,
418    pub peers: Arc<PeerDb>,
419}
420
421impl Message<Arc<ts_control::StateUpdate>> for PeerTracker {
422    type Reply = ();
423
424    async fn handle(
425        &mut self,
426        msg: Arc<ts_control::StateUpdate>,
427        _ctx: &mut Context<Self, Self::Reply>,
428    ) {
429        // Accumulate user profiles first — control sends them incrementally and a response may
430        // carry profiles with no peer delta (or peers that reference a profile from an earlier
431        // response), so this must happen before the no-peer-update early return below.
432        for profile in &msg.user_profiles {
433            self.user_profiles.insert(profile.id, profile.clone());
434        }
435
436        // Apply the standalone online/last-seen delta maps (channels C/D, `MapResponse.OnlineChange`
437        // / `PeerSeenChange`). These arrive keyed by control node id and may ride a response that
438        // carries NO `peer_update` (a bare online flip is the common case), so they must be applied
439        // *before* the no-peer-update early return — otherwise online status freezes at the last
440        // full-node/patch value. Each entry only ever *sets* a value (never back to unknown).
441        let liveness_changed =
442            self.apply_liveness_changes(&msg.online_change, &msg.peer_seen_change);
443
444        if msg.peer_update.is_none() && msg.peer_patches.is_empty() {
445            // No peer set or patch this response. If a liveness delta still mutated the netmap,
446            // publish the refreshed snapshot so watchers (and `GetStatus`) see the new online state.
447            if liveness_changed {
448                self.service_pending_requests();
449                self.peer_watch.send_replace(self.status_peers());
450                if let Err(e) = self
451                    .env
452                    .publish(Arc::new(PeerState {
453                        upserts: HashSet::default(),
454                        deletions: HashSet::default(),
455                        peers: Arc::new(self.peer_db.clone()),
456                    }))
457                    .await
458                {
459                    tracing::error!(error = %e, "publishing liveness-only peer state update");
460                }
461            }
462            return;
463        }
464
465        // Apply the whole-node peer set (if any) FIRST, then the field-level patches on top —
466        // mirroring Go's `controlclient` order (`Peers*` then `PeersChangedPatch`). A response may
467        // carry either, both, or (with a liveness-only delta) neither. Merge the upsert/deletion sets
468        // so the published `PeerState` reflects every node touched by both passes; a node both
469        // upserted by the set and patched stays in `upserts` (the patch removes it from `deletions`).
470        let (mut upserts, mut deletions) = msg
471            .peer_update
472            .as_ref()
473            .map(|u| self.apply_peer_update(u))
474            .unwrap_or_default();
475
476        if !msg.peer_patches.is_empty() {
477            let (patch_upserts, patch_deletions) = self.apply_peer_patches(&msg.peer_patches);
478            // A patch can evict a node the set just upserted (TKA rejection after key rotation), or
479            // re-admit/patch one not in the set — reconcile so each id lands in exactly one set.
480            for id in &patch_upserts {
481                deletions.remove(id);
482            }
483            for id in &patch_deletions {
484                upserts.remove(id);
485            }
486            upserts.extend(patch_upserts);
487            deletions.extend(patch_deletions);
488        }
489
490        tracing::debug!(
491            n_upsert = upserts.len(),
492            n_delete = deletions.len(),
493            peer_count = self.peer_db.peers().len(),
494            "new peer state"
495        );
496
497        self.service_pending_requests();
498
499        // Publish the latest peer snapshot to netmap watchers. `send_replace` keeps the receiver's
500        // value current even when there are no subscribers, so a late subscriber sees fresh state.
501        self.peer_watch.send_replace(self.status_peers());
502
503        if let Err(e) = self
504            .env
505            .publish(Arc::new(PeerState {
506                upserts,
507                deletions,
508                peers: Arc::new(self.peer_db.clone()),
509            }))
510            .await
511        {
512            tracing::error!(error = %e, "publishing peer state update");
513        }
514    }
515}
516
517/// Bus message delivering the latest verified Tailnet-Lock [`Authority`](ts_tka::Authority) from the
518/// control runner (after a successful `/machine/tka/sync`) to the peer tracker for **observe-only**
519/// verify-and-logging (issue #136). Cloned onto the bus (`Authority` is `Clone`); the control runner
520/// re-publishes on every successful sync since the bus has no replay for a late subscriber.
521#[derive(Clone)]
522pub struct TkaAuthorityUpdate(pub Arc<ts_tka::Authority>);
523
524impl Message<TkaAuthorityUpdate> for PeerTracker {
525    type Reply = ();
526
527    async fn handle(&mut self, msg: TkaAuthorityUpdate, _ctx: &mut Context<Self, Self::Reply>) {
528        // Store as the OBSERVE-ONLY authority — never `tka_authority` (which would enforce). From
529        // here on, each upserted peer's signature verdict is logged; admission is unchanged.
530        tracing::info!(
531            head = %msg.0.head().to_base32(),
532            "TKA observe authority updated (verify-and-log active; not enforcing)"
533        );
534        self.tka_observe = Some((*msg.0).clone());
535    }
536}
537
538/// Ask the peer tracker to re-broadcast its current peer snapshot on the bus, without any peer
539/// change. `Device::set_exit_node` sends this after changing the exit-node selector so the route
540/// updater and source filter (both `Arc<PeerState>` subscribers) re-resolve the new selector
541/// immediately, rather than waiting for the next netmap update.
542#[derive(Debug, Clone, Copy)]
543pub struct RepublishState;
544
545impl Message<RepublishState> for PeerTracker {
546    type Reply = ();
547
548    async fn handle(&mut self, _msg: RepublishState, _ctx: &mut Context<Self, Self::Reply>) {
549        // An empty upsert/deletion set: this is a re-broadcast of the unchanged peer set, not a
550        // delta. Subscribers recompute their routes/filters against the current peers and the
551        // (just-updated) exit-node selector.
552        if let Err(e) = self
553            .env
554            .publish(Arc::new(PeerState {
555                upserts: HashSet::default(),
556                deletions: HashSet::default(),
557                peers: Arc::new(self.peer_db.clone()),
558            }))
559            .await
560        {
561            tracing::error!(error = %e, "re-publishing peer state after exit-node change");
562        }
563    }
564}
565
566impl PeerTracker {
567    /// Apply a single [`PeerUpdate`](ts_control::PeerUpdate) to the peer db, enforcing the
568    /// Tailnet-Lock peer-trust chokepoint ([`tka_admits`](Self::tka_admits)) at every upsert site.
569    ///
570    /// This is the **single source of truth** for the peer-trust enforcement loop: the actor's
571    /// netmap [`handle`](Message::handle) calls it, and so do the TKA enforcement tests, so the two
572    /// real upsert sites (`Full` and `Delta { upsert }`) cannot diverge from what is tested.
573    ///
574    /// Returns `(upserts, deletions)` — the [`PeerId`]s touched — for downstream bookkeeping.
575    fn apply_peer_update(
576        &mut self,
577        peer_update: &ts_control::PeerUpdate,
578    ) -> (HashSet<PeerId>, HashSet<PeerId>) {
579        let mut upserts = HashSet::default();
580        let mut deletions = HashSet::default();
581
582        match peer_update {
583            ts_control::PeerUpdate::Full(new_nodes) => {
584                tracing::trace!("full peer update");
585
586                // Only stable_ids that PASS the Tailnet-Lock gate survive a full re-sync. This makes
587                // revocation evict: if a peer is re-included with a now-invalid (or missing)
588                // signature under an active authority, it is excluded from `retained_ids`, so
589                // `retain` drops the stale (previously-admitted) entry rather than leaving it in the
590                // db unverified. With no authority, `tka_admits` is always `true`, so `retained_ids`
591                // is exactly the set of re-included stable_ids — the inactive path is byte-for-byte
592                // the pre-TKA behavior (no regression).
593                let retained_ids = new_nodes
594                    .iter()
595                    .filter(|node| self.tka_admits(node))
596                    .map(|x| &x.stable_id)
597                    .collect::<HashSet<_>>();
598
599                self.peer_db.retain(|id, peer| {
600                    let retain = retained_ids.contains(&peer.stable_id);
601
602                    if !retain {
603                        deletions.insert(id);
604                    }
605
606                    retain
607                });
608
609                for node in new_nodes {
610                    if !self.tka_admits(node) {
611                        continue; // fail-CLOSED: do not upsert a peer rejected by tailnet lock
612                    }
613                    self.tka_observe_log(node); // verify-and-LOG (#136); never gates admission
614                    let peer_id = self.peer_db.upsert(node);
615                    upserts.insert(peer_id);
616                }
617            }
618
619            ts_control::PeerUpdate::Delta { remove, upsert } => {
620                tracing::trace!("delta peer update");
621
622                for peer in upsert {
623                    if !self.tka_admits(peer) {
624                        continue; // fail-CLOSED: do not upsert a peer rejected by tailnet lock
625                    }
626                    self.tka_observe_log(peer); // verify-and-LOG (#136); never gates admission
627                    let id = self.peer_db.upsert(peer);
628
629                    upserts.insert(id);
630                }
631
632                for peer in remove {
633                    let Some((id, _node)) = self.peer_db.remove(peer) else {
634                        tracing::error!(control_node_id = peer, "removed peer was unknown");
635                        continue;
636                    };
637
638                    deletions.insert(id);
639                }
640            }
641        }
642
643        (upserts, deletions)
644    }
645
646    /// Apply field-level peer patches (`MapResponse.PeersChangedPatch`), returning the upserted /
647    /// deleted [`PeerId`]s.
648    ///
649    /// This is a SEPARATE channel from [`apply_peer_update`](Self::apply_peer_update): Go's
650    /// `controlclient` applies the whole-node `Peers*` set first and then `PeersChangedPatch`, so a
651    /// response that carries both has the peer set applied first (by the caller) and these patches
652    /// applied second, on top of the freshly-synced nodes. A patch only mutates a peer already in the
653    /// netmap; an unknown node id is ignored (the wire contract — a patch never creates a node).
654    fn apply_peer_patches(
655        &mut self,
656        patches: &[ts_control::PeerChange],
657    ) -> (HashSet<PeerId>, HashSet<PeerId>) {
658        let mut upserts = HashSet::default();
659        let mut deletions = HashSet::default();
660
661        tracing::trace!(n = patches.len(), "peer patch update");
662
663        for patch in patches {
664            // Clone the current node, apply the present fields, and re-upsert through the same path
665            // as a delta so indexes/routes stay consistent.
666            let Some((_id, existing)) = self.peer_db.get(&patch.id) else {
667                tracing::debug!(
668                    control_node_id = patch.id,
669                    "peer patch for unknown node; ignoring"
670                );
671                continue;
672            };
673
674            let mut node = existing.clone();
675            if let Some(endpoints) = &patch.underlay_addresses {
676                node.underlay_addresses = endpoints.clone();
677            }
678            if let Some(derp) = patch.derp_region {
679                node.derp_region = Some(derp);
680            }
681            if let Some(cap) = patch.cap {
682                node.cap = cap;
683            }
684            if let Some(cap_map) = &patch.cap_map {
685                node.cap_map = cap_map.clone();
686            }
687            if let Some(disco_key) = patch.disco_key {
688                node.disco_key = Some(disco_key);
689            }
690            if let Some(expiry) = patch.node_key_expiry {
691                node.node_key_expiry = Some(expiry);
692            }
693            // Online/last-seen liveness deltas (`PeerChange.Online`/`LastSeen`) — the dominant
694            // channel by which peer online transitions arrive mid-session. A patch only ever *sets*
695            // a value (never patches back to unknown), so apply when present.
696            if let Some(online) = patch.online {
697                node.online = Some(online);
698            }
699            if let Some(last_seen) = patch.last_seen {
700                node.last_seen = Some(last_seen);
701            }
702            // Key rotation: a patch may swap the node key (and its TKA signature). Apply both
703            // together so the trust gate below verifies the new signature against the new key, never
704            // a mismatched pair.
705            if let Some(node_key) = patch.node_key {
706                node.node_key = node_key;
707            }
708            if let Some(sig) = &patch.key_signature {
709                node.key_signature = sig.clone();
710            }
711
712            // Re-run the tailnet-lock gate on the patched node: a patch that rotates the key must
713            // satisfy the active authority, exactly like a `Delta` upsert, or it would be a
714            // trust-enforcement bypass. fail-CLOSED — if the patched node is no longer admitted,
715            // evict it rather than keep the stale (now-unverified) entry.
716            if !self.tka_admits(&node) {
717                if let Some((id, _)) = self.peer_db.remove(&patch.id) {
718                    tracing::warn!(
719                        control_node_id = patch.id,
720                        "peer patch rejected by tailnet lock; evicting peer"
721                    );
722                    deletions.insert(id);
723                }
724                continue;
725            }
726
727            self.tka_observe_log(&node); // verify-and-LOG (#136); never gates admission
728            let id = self.peer_db.upsert(&node);
729            upserts.insert(id);
730        }
731
732        (upserts, deletions)
733    }
734
735    /// Apply the standalone online/last-seen delta maps (`MapResponse.OnlineChange` /
736    /// `PeerSeenChange`, channels C/D) onto the retained netmap. Returns `true` if any node was
737    /// actually mutated (so the caller knows whether to re-publish).
738    ///
739    /// Mirrors Go's post-`peers*` application of these maps. Each entry is keyed by control node id
740    /// and only ever *sets* a value (never back to unknown). An entry for an unknown node id is
741    /// ignored (like a patch — these maps never create a node). `peer_seen_change`'s `false` ("the
742    /// peer is gone") is applied as `online = Some(false)` — the node stays in the netmap, it is
743    /// merely marked offline; the `last_seen = now` update for the `true` case is intentionally not
744    /// performed here (it needs a wall clock this actor does not hold, and `last_seen` is the
745    /// low-value half — `online` is the `tailscale status` column that matters; see the iter-5
746    /// research note §5.5).
747    fn apply_liveness_changes(
748        &mut self,
749        online_change: &std::collections::BTreeMap<ts_control::NodeId, bool>,
750        peer_seen_change: &std::collections::BTreeMap<ts_control::NodeId, bool>,
751    ) -> bool {
752        let mut changed = false;
753
754        // Channel C — direct online flips.
755        for (&node_id, &online) in online_change {
756            if let Some((_pid, existing)) = self.peer_db.get(&node_id)
757                && existing.online != Some(online)
758            {
759                let mut node = existing.clone();
760                node.online = Some(online);
761                self.peer_db.upsert(&node);
762                changed = true;
763            }
764        }
765
766        // Channel D — peer-seen flips. `false` ⇒ "the peer is gone" ⇒ mark offline (the node is
767        // retained, not removed). `true` ⇒ "seen just now"; the online half is unknown from this
768        // signal alone, so we leave `online` untouched (a `true` here does not assert connectivity to
769        // control, only recent contact) and defer the `last_seen = now` timestamp (no clock here).
770        for (&node_id, &seen) in peer_seen_change {
771            if !seen
772                && let Some((_pid, existing)) = self.peer_db.get(&node_id)
773                && existing.online != Some(false)
774            {
775                let mut node = existing.clone();
776                node.online = Some(false);
777                self.peer_db.upsert(&node);
778                changed = true;
779            }
780        }
781
782        changed
783    }
784
785    /// Test-only constructor: build a [`PeerTracker`] with chosen TKA authorities without going
786    /// through the actor `on_start` path. `tka_authority` exercises the fail-closed enforcement
787    /// chokepoint ([`tka_admits`](Self::tka_admits)); `tka_observe` exercises the observe-only
788    /// verify-and-log seam ([`tka_observe_log`](Self::tka_observe_log)).
789    #[cfg(test)]
790    fn for_test(
791        env: Env,
792        tka_authority: Option<ts_tka::Authority>,
793        tka_observe: Option<ts_tka::Authority>,
794    ) -> Self {
795        let (peer_watch, _) = watch::channel(Vec::new());
796        Self {
797            peer_db: PeerDb::default(),
798            seen_state_update: false,
799            pending_requests: Vec::new(),
800            peer_watch,
801            user_profiles: HashMap::new(),
802            tka_authority,
803            tka_observe,
804            env,
805        }
806    }
807
808    fn service_pending_requests(&mut self) {
809        if self.seen_state_update {
810            return;
811        }
812
813        self.seen_state_update = true;
814
815        if !self.pending_requests.is_empty() {
816            tracing::debug!(
817                n_pending = self.pending_requests.len(),
818                "state update received, servicing pending requests"
819            );
820        }
821
822        for req in core::mem::take(&mut self.pending_requests) {
823            match req {
824                Pending::PeerByName(PeerByName { name }, reply) => {
825                    reply.send(self.peer_by_name_opt(&name).cloned());
826                }
827                Pending::TailnetIp(PeerByTailnetIp { ip }, reply) => {
828                    reply.send(self.peer_by_tailnet_ip_opt(ip).cloned());
829                }
830                Pending::AcceptedRoute(PeerByAcceptedRoute { ip }, reply) => {
831                    reply.send(
832                        self.peer_db
833                            .get_route(ip.into())
834                            .map(|(_id, node)| node.clone())
835                            .collect(),
836                    );
837                }
838                Pending::Status(reply) => {
839                    reply.send(self.status_peers_with_ids());
840                }
841                Pending::WhoIs(Whois { addr }, reply) => {
842                    reply.send(self.whois_opt(addr));
843                }
844            }
845        }
846    }
847}
848
849#[cfg(test)]
850mod tka_tests {
851    //! Tailnet-Lock (TKA) enforcement tests for the peer-trust chokepoint.
852    //!
853    //! These exercise [`PeerTracker::tka_admits`] and the `tka_admits ⇒ upsert` loop the netmap
854    //! handler runs. The test [`ts_tka::Authority`] is built with [`ts_tka::Authority::from_state`]
855    //! over a known Ed25519 trusted key, and the signed node-key signature CBOR is produced through
856    //! `ts_tka`'s public `cbor` encoder + `aum_hash` (the exact same canonical bytes `ts_tka`'s own
857    //! `direct_signature_verifies_end_to_end` test signs, with no new crypto vectors invented and no
858    //! private `ts_tka` API used).
859
860    use ed25519_dalek::{Signer, SigningKey};
861    use ts_control::{Node, StableNodeId, TailnetAddress};
862    use ts_tka::{
863        AumHash, Authority, Key, KeyKind, State,
864        cbor::{self, Value},
865    };
866
867    use super::*;
868
869    /// `SigKind::Direct` wire value (Go `SigKind`; `ts_tka::SigKind::Direct = 1`).
870    const SIG_KIND_DIRECT: u64 = 1;
871
872    /// The 32-byte node key used across the signed-peer fixtures.
873    const NODE_KEY_BYTES: [u8; 32] = [7u8; 32];
874
875    /// Build a real [`Env`] for the tracker. Only the bus/keys/shutdown plumbing matters here; the
876    /// TKA gate reads neither, so the forwarding preferences are all benign defaults.
877    fn test_env() -> Env {
878        let (_shutdown_tx, shutdown_rx) = watch::channel(false);
879        Env::new(
880            ts_keys::NodeState::generate(),
881            shutdown_rx,
882            crate::env::ForwarderConfig {
883                accept_routes: false,
884                exit_node: None,
885                forward_routes: Vec::new(),
886                forward_tcp_ports: Vec::new(),
887                forward_udp_ports: Vec::new(),
888                forward_all_ports: false,
889                forward_exit_egress: false,
890                block_incoming: false,
891                exit_proxy: None,
892                peerapi_port: None,
893                taildrop_dir: None,
894                enable_ipv6: false,
895                persistent_keepalive_interval: None,
896                ingress_active: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
897            },
898        )
899    }
900
901    /// A minimal peer [`Node`] carrying `node_key` and the given `key_signature`.
902    fn peer_node(stable_id: &str, node_key: [u8; 32], key_signature: Vec<u8>) -> Node {
903        Node {
904            id: 1,
905            stable_id: StableNodeId(stable_id.to_string()),
906            hostname: stable_id.to_string(),
907            user_id: 0,
908            tailnet: Some("ts.net".to_string()),
909            tags: Vec::new(),
910            tailnet_address: TailnetAddress {
911                ipv4: "100.64.0.1/32".parse().unwrap(),
912                ipv6: "fd7a:115c:a1e0::1/128".parse().unwrap(),
913            },
914            node_key: node_key.into(),
915            node_key_expiry: None,
916            online: None,
917            last_seen: None,
918            key_signature,
919            machine_key: None,
920            disco_key: None,
921            accepted_routes: Vec::new(),
922            underlay_addresses: Vec::new(),
923            derp_region: None,
924            cap: Default::default(),
925            cap_map: Default::default(),
926            peerapi_port: None,
927            peerapi_dns_proxy: false,
928            is_wireguard_only: false,
929            exit_node_dns_resolvers: Vec::new(),
930            peer_relay: false,
931            service_vips: Default::default(),
932        }
933    }
934
935    /// Encode a `Direct` [`ts_tka::NodeKeySignature`] CBOR exactly as `ts_tka`'s private `to_cbor`
936    /// does (int-map keys: 1=kind, 2=pubkey, 3=key_id, 4=signature; empty byte fields omitted),
937    /// using only the crate's *public* `cbor` encoder. `signature` of `None` produces the
938    /// signing-digest preimage (the `SigHash` form).
939    fn direct_sig_cbor(node_key: &[u8], key_id: &[u8], signature: Option<&[u8]>) -> Vec<u8> {
940        let mut pairs = alloc_pairs(node_key, key_id);
941        if let Some(sig) = signature {
942            pairs.push((4, Some(Value::Bytes(sig.to_vec()))));
943        }
944        cbor::int_map(pairs).to_vec()
945    }
946
947    fn alloc_pairs(node_key: &[u8], key_id: &[u8]) -> Vec<(u64, Option<Value>)> {
948        vec![
949            (1, Some(Value::Uint(SIG_KIND_DIRECT))),
950            (2, Some(Value::Bytes(node_key.to_vec()))),
951            (3, Some(Value::Bytes(key_id.to_vec()))),
952        ]
953    }
954
955    /// Build a TKA [`Authority`] that trusts `signing.verifying_key()`, plus a valid `Direct`
956    /// node-key signature CBOR authorizing [`NODE_KEY_BYTES`] under it.
957    fn authority_and_valid_sig() -> (Authority, Vec<u8>) {
958        // A fixed, known Ed25519 trusted key (mirrors ts_tka's own end-to-end test seed).
959        let signing = SigningKey::from_bytes(&[42u8; 32]);
960        let trusted_pub = signing.verifying_key().to_bytes().to_vec();
961
962        let authority = Authority::from_state(
963            AumHash([0; 32]),
964            State {
965                keys: vec![Key {
966                    kind: KeyKind::Ed25519,
967                    votes: 1,
968                    public: trusted_pub.clone(),
969                }],
970            },
971        );
972
973        // SigHash preimage = canonical CBOR with the signature field omitted; sign its blake2s hash.
974        let preimage = direct_sig_cbor(&NODE_KEY_BYTES, &trusted_pub, None);
975        let sig_hash = ts_tka::aum_hash(&preimage).0;
976        let signature = signing.sign(&sig_hash).to_bytes().to_vec();
977
978        let signed_cbor = direct_sig_cbor(&NODE_KEY_BYTES, &trusted_pub, Some(&signature));
979        // Sanity: the authority accepts the signature we just built (same path the gate uses).
980        assert!(
981            authority
982                .node_key_authorized(&NODE_KEY_BYTES, &signed_cbor)
983                .is_ok()
984        );
985
986        (authority, signed_cbor)
987    }
988
989    #[tokio::test]
990    async fn tka_inactive_upserts_all_peers() {
991        // No authority ⇒ enforcement inactive ⇒ both a signed and an unsigned peer are admitted.
992        let mut tracker = PeerTracker::for_test(test_env(), None, None);
993
994        let signed = peer_node("signed", [1u8; 32], vec![0xde, 0xad, 0xbe, 0xef]);
995        let unsigned = peer_node("unsigned", [2u8; 32], vec![]);
996
997        assert!(tracker.tka_admits(&signed));
998        assert!(tracker.tka_admits(&unsigned));
999
1000        tracker.peer_db.upsert(&signed);
1001        tracker.peer_db.upsert(&unsigned);
1002        assert_eq!(tracker.peer_db.peers().len(), 2);
1003    }
1004
1005    #[tokio::test]
1006    async fn tka_active_rejects_unsigned_peer() {
1007        // Authority present + peer presents no signature ⇒ rejected (fail-closed), not in peer_db.
1008        let (authority, _sig) = authority_and_valid_sig();
1009        let mut tracker = PeerTracker::for_test(test_env(), Some(authority), None);
1010
1011        let unsigned = peer_node("unsigned", NODE_KEY_BYTES, vec![]);
1012        assert!(!tracker.tka_admits(&unsigned));
1013
1014        // Mirror the handler's `if !tka_admits { continue }` loop.
1015        if tracker.tka_admits(&unsigned) {
1016            tracker.peer_db.upsert(&unsigned);
1017        }
1018        assert_eq!(tracker.peer_db.peers().len(), 0);
1019        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
1020    }
1021
1022    #[tokio::test]
1023    async fn tka_active_rejects_bad_signature() {
1024        // Authority present + a signature that fails to verify ⇒ rejected, not in peer_db.
1025        let (authority, mut sig) = authority_and_valid_sig();
1026        // Tamper the last byte (the trailing signature byte) so verification fails.
1027        let last = sig.len() - 1;
1028        sig[last] ^= 0xff;
1029
1030        let mut tracker = PeerTracker::for_test(test_env(), Some(authority), None);
1031        let bad = peer_node("bad", NODE_KEY_BYTES, sig);
1032        assert!(!tracker.tka_admits(&bad));
1033
1034        if tracker.tka_admits(&bad) {
1035            tracker.peer_db.upsert(&bad);
1036        }
1037        assert_eq!(tracker.peer_db.peers().len(), 0);
1038    }
1039
1040    #[tokio::test]
1041    async fn tka_active_admits_authorized_peer() {
1042        // Authority present + correctly-signed node key ⇒ admitted and upserted.
1043        let (authority, sig) = authority_and_valid_sig();
1044        let mut tracker = PeerTracker::for_test(test_env(), Some(authority), None);
1045
1046        let good = peer_node("good", NODE_KEY_BYTES, sig);
1047        assert!(tracker.tka_admits(&good));
1048
1049        if tracker.tka_admits(&good) {
1050            tracker.peer_db.upsert(&good);
1051        }
1052        assert_eq!(tracker.peer_db.peers().len(), 1);
1053        assert!(tracker.peer_db.get(&good.node_key).is_some());
1054    }
1055
1056    // ---------------------------------------------------------------------------------------------
1057    // Tests that drive REAL `PeerUpdate`s through the shared handler body
1058    // ([`PeerTracker::apply_peer_update`], the single source of truth the actor's netmap `handle`
1059    // also calls), so the two real upsert sites (`Full` and `Delta { upsert }`) are exercised via
1060    // the actual enforcement path — not by hand-mirroring `if !tka_admits { continue }`.
1061    // ---------------------------------------------------------------------------------------------
1062
1063    #[tokio::test]
1064    async fn tka_active_delta_upsert_rejects_unauthorized() {
1065        // Drive a real `Delta { upsert }` whose peer carries no signature. The Delta upsert site
1066        // must reject it under an active authority ⇒ not present in peer_db after the handler runs.
1067        let (authority, _sig) = authority_and_valid_sig();
1068        let mut tracker = PeerTracker::for_test(test_env(), Some(authority), None);
1069
1070        let unsigned = peer_node("unsigned", NODE_KEY_BYTES, vec![]);
1071        let update = ts_control::PeerUpdate::Delta {
1072            upsert: vec![unsigned.clone()],
1073            remove: Vec::new(),
1074        };
1075
1076        tracker.apply_peer_update(&update);
1077
1078        assert_eq!(tracker.peer_db.peers().len(), 0);
1079        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
1080    }
1081
1082    #[tokio::test]
1083    async fn tka_active_delta_upsert_admits_authorized() {
1084        // Drive a real `Delta { upsert }` with a correctly-signed peer ⇒ present in peer_db.
1085        let (authority, sig) = authority_and_valid_sig();
1086        let mut tracker = PeerTracker::for_test(test_env(), Some(authority), None);
1087
1088        let good = peer_node("good", NODE_KEY_BYTES, sig);
1089        let update = ts_control::PeerUpdate::Delta {
1090            upsert: vec![good.clone()],
1091            remove: Vec::new(),
1092        };
1093
1094        tracker.apply_peer_update(&update);
1095
1096        assert_eq!(tracker.peer_db.peers().len(), 1);
1097        assert!(tracker.peer_db.get(&good.node_key).is_some());
1098    }
1099
1100    #[tokio::test]
1101    async fn tka_active_full_admits_only_authorized_in_mixed_batch() {
1102        // Drive a real `Full` carrying a MIX of authorized + unauthorized peers. Only the
1103        // correctly-signed peer survives the Full upsert site; the unsigned and bad-sig peers are
1104        // dropped fail-closed.
1105        let (authority, sig) = authority_and_valid_sig();
1106        // A bad-sig variant of the same authorized signature (tamper the trailing byte).
1107        let mut bad_sig = sig.clone();
1108        let last = bad_sig.len() - 1;
1109        bad_sig[last] ^= 0xff;
1110
1111        let mut tracker = PeerTracker::for_test(test_env(), Some(authority), None);
1112
1113        // Only the authorized peer carries NODE_KEY_BYTES (the key the authority signed); the
1114        // rejected peers use distinct node keys so the survivor is unambiguous.
1115        let good = peer_node("good", NODE_KEY_BYTES, sig);
1116        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
1117        let bad = peer_node("bad", [9u8; 32], bad_sig);
1118
1119        let update =
1120            ts_control::PeerUpdate::Full(vec![good.clone(), unsigned.clone(), bad.clone()]);
1121
1122        tracker.apply_peer_update(&update);
1123
1124        assert_eq!(tracker.peer_db.peers().len(), 1);
1125        assert!(tracker.peer_db.get(&good.node_key).is_some());
1126        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
1127        assert!(tracker.peer_db.get(&bad.node_key).is_none());
1128    }
1129
1130    #[tokio::test]
1131    async fn tka_observe_only_admits_all_peers_in_mixed_batch() {
1132        // #136 observe-only contract: with the OBSERVE authority set (and `tka_authority = None`, so
1133        // enforcement is OFF), the exact mixed batch that the fail-closed test above prunes to 1 must
1134        // instead admit ALL THREE peers. The verify-and-log seam logs each verdict (verified /
1135        // unsigned / failed) but never gates admission. This locks observe-only against a future
1136        // refactor that accidentally wires `tka_observe` into a drop path.
1137        let (authority, sig) = authority_and_valid_sig();
1138        let mut bad_sig = sig.clone();
1139        let last = bad_sig.len() - 1;
1140        bad_sig[last] ^= 0xff;
1141
1142        // Authority in the OBSERVE slot, enforcement slot empty.
1143        let mut tracker = PeerTracker::for_test(test_env(), None, Some(authority));
1144
1145        let good = peer_node("good", NODE_KEY_BYTES, sig);
1146        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
1147        let bad = peer_node("bad", [9u8; 32], bad_sig);
1148
1149        let update =
1150            ts_control::PeerUpdate::Full(vec![good.clone(), unsigned.clone(), bad.clone()]);
1151
1152        tracker.apply_peer_update(&update);
1153
1154        // ALL THREE survive — observe-only never drops a peer.
1155        assert_eq!(
1156            tracker.peer_db.peers().len(),
1157            3,
1158            "observe-only must admit every peer regardless of signature verdict"
1159        );
1160        assert!(tracker.peer_db.get(&good.node_key).is_some());
1161        assert!(tracker.peer_db.get(&unsigned.node_key).is_some());
1162        assert!(tracker.peer_db.get(&bad.node_key).is_some());
1163    }
1164
1165    #[tokio::test]
1166    async fn tka_full_resync_revocation_behavior() {
1167        // Revocation-on-resync: admit a peer, then re-include the SAME stable_id in a `Full` with a
1168        // now-invalid signature. Per the Logic review finding, the pre-fix `retain` kept the stale
1169        // (previously-admitted) entry because membership was decided purely by stable_id.
1170        //
1171        // FIXED (not merely documented): the `Full` `retain` now keys on `tka_admits`-passing
1172        // stable_ids, so a peer whose re-included signature no longer verifies under the active
1173        // authority is EVICTED. This test asserts eviction. The inactive (authority=None) path is
1174        // provably unchanged — `tka_admits` always returns `true` there, so the retained set equals
1175        // the set of re-included stable_ids exactly (see `tka_inactive_full_resync_keeps_*`).
1176        let (authority, sig) = authority_and_valid_sig();
1177        let mut tracker = PeerTracker::for_test(test_env(), Some(authority), None);
1178
1179        // 1) Admit the peer with a valid signature via a real `Full`.
1180        let good = peer_node("revoked", NODE_KEY_BYTES, sig.clone());
1181        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![good.clone()]));
1182        assert_eq!(tracker.peer_db.peers().len(), 1);
1183        assert!(tracker.peer_db.get(&good.node_key).is_some());
1184
1185        // 2) Re-sync the SAME stable_id, but with a now-invalid signature (tamper trailing byte).
1186        let mut bad_sig = sig;
1187        let last = bad_sig.len() - 1;
1188        bad_sig[last] ^= 0xff;
1189        let revoked = peer_node("revoked", NODE_KEY_BYTES, bad_sig);
1190        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![revoked.clone()]));
1191
1192        // Eviction: the stale entry is dropped because its re-included signature fails the gate.
1193        assert_eq!(tracker.peer_db.peers().len(), 0);
1194        assert!(tracker.peer_db.get(&revoked.node_key).is_none());
1195    }
1196
1197    #[tokio::test]
1198    async fn tka_inactive_full_resync_keeps_reincluded_peer() {
1199        // Guard the inactive (authority=None) path against the revocation fix: with no authority,
1200        // a peer re-included in a `Full` survives regardless of its signature bytes — byte-for-byte
1201        // pre-TKA behavior, proving the `Full` `retain` change does not regress the always-taken
1202        // branch this wave.
1203        let mut tracker = PeerTracker::for_test(test_env(), None, None);
1204
1205        let peer = peer_node("p", NODE_KEY_BYTES, vec![0xde, 0xad]);
1206        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer.clone()]));
1207        assert_eq!(tracker.peer_db.peers().len(), 1);
1208
1209        // Re-sync the same stable_id with garbage signature bytes; inactive enforcement keeps it.
1210        let resynced = peer_node("p", NODE_KEY_BYTES, vec![0x00]);
1211        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![resynced.clone()]));
1212        assert_eq!(tracker.peer_db.peers().len(), 1);
1213        assert!(tracker.peer_db.get(&resynced.node_key).is_some());
1214    }
1215
1216    /// A `Patch` for a peer already in the netmap merges only the fields it carries — here new UDP
1217    /// endpoints and a new home DERP — leaving the rest of the node intact. This is the fix for
1218    /// dropped `peers_changed_patch`: without it the netmap keeps stale endpoints and the peer can
1219    /// never re-handshake after it moves.
1220    #[tokio::test]
1221    async fn patch_merges_endpoints_and_derp_into_existing_peer() {
1222        let mut tracker = PeerTracker::for_test(test_env(), None, None);
1223
1224        // Seed a peer (id == 1, per `peer_node`) with no endpoints / no DERP.
1225        let peer = peer_node("mover", [1u8; 32], vec![]);
1226        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer.clone()]));
1227        let (_pid, before) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
1228        assert!(before.underlay_addresses.is_empty());
1229        assert!(before.derp_region.is_none());
1230
1231        // Patch in fresh reachability (the idle-peer-reconnect case).
1232        let new_ep: std::net::SocketAddr = "203.0.113.7:41641".parse().unwrap();
1233        let patch = ts_control::PeerChange {
1234            id: 1,
1235            derp_region: Some(ts_derp::RegionId(core::num::NonZeroU32::new(5).unwrap())),
1236            cap: None,
1237            cap_map: None,
1238            underlay_addresses: Some(vec![new_ep]),
1239            node_key: None,
1240            key_signature: None,
1241            disco_key: None,
1242            node_key_expiry: None,
1243            online: None,
1244            last_seen: None,
1245        };
1246        let (upserts, deletions) = tracker.apply_peer_patches(std::slice::from_ref(&patch));
1247
1248        assert_eq!(upserts.len(), 1);
1249        assert_eq!(deletions.len(), 0);
1250        // Same peer, now carrying the patched endpoint + DERP; node key untouched.
1251        assert_eq!(tracker.peer_db.peers().len(), 1);
1252        let (_pid, after) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
1253        assert_eq!(after.underlay_addresses, vec![new_ep]);
1254        assert_eq!(
1255            after.derp_region,
1256            Some(ts_derp::RegionId(core::num::NonZeroU32::new(5).unwrap()))
1257        );
1258        assert_eq!(after.node_key, peer.node_key);
1259    }
1260
1261    /// Regression for `tsr-5u0`: when a whole-node set (`Delta`/`Full`) and a patch co-occur in one
1262    /// response, the patch is applied *on top of* the node the set just upserted — mirroring the
1263    /// handler's apply-order (peer set first, then `peer_patches`). Before the fix the patch shared
1264    /// the single `peer_update` slot and the co-occurring set silently dropped it, so a peer brought
1265    /// in by the delta kept stale (empty) reachability.
1266    #[tokio::test]
1267    async fn patch_applies_on_top_of_co_occurring_delta() {
1268        let mut tracker = PeerTracker::for_test(test_env(), None, None);
1269
1270        // The whole-node delta upserts a brand-new peer (id == 1) with no reachability.
1271        let peer = peer_node("mover", [1u8; 32], vec![]);
1272        let (set_upserts, _) = tracker.apply_peer_update(&ts_control::PeerUpdate::Delta {
1273            upsert: vec![peer.clone()],
1274            remove: vec![],
1275        });
1276        assert_eq!(set_upserts.len(), 1, "delta upserts the new peer");
1277
1278        // The patch from the SAME response then sets that peer's endpoints + DERP. This is exactly
1279        // the consumer order the handler runs (apply_peer_update then apply_peer_patches).
1280        let new_ep: std::net::SocketAddr = "203.0.113.7:41641".parse().unwrap();
1281        let patch = ts_control::PeerChange {
1282            id: 1,
1283            derp_region: Some(ts_derp::RegionId(core::num::NonZeroU32::new(7).unwrap())),
1284            cap: None,
1285            cap_map: None,
1286            underlay_addresses: Some(vec![new_ep]),
1287            node_key: None,
1288            key_signature: None,
1289            disco_key: None,
1290            node_key_expiry: None,
1291            online: None,
1292            last_seen: None,
1293        };
1294        let (patch_upserts, patch_deletions) =
1295            tracker.apply_peer_patches(std::slice::from_ref(&patch));
1296
1297        assert_eq!(
1298            patch_upserts.len(),
1299            1,
1300            "patch re-upserts the just-added peer"
1301        );
1302        assert_eq!(patch_deletions.len(), 0);
1303        // The peer added by the delta now carries the patched reachability — the patch was NOT lost.
1304        let (_pid, after) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
1305        assert_eq!(after.underlay_addresses, vec![new_ep]);
1306        assert_eq!(
1307            after.derp_region,
1308            Some(ts_derp::RegionId(core::num::NonZeroU32::new(7).unwrap()))
1309        );
1310    }
1311
1312    /// A `Patch` whose node id is not in the current netmap is ignored (the wire contract: a patch
1313    /// never creates a node). No upsert, no deletion, peer set unchanged.
1314    #[tokio::test]
1315    async fn patch_for_unknown_node_is_ignored() {
1316        let mut tracker = PeerTracker::for_test(test_env(), None, None);
1317        let known = peer_node("known", [1u8; 32], vec![]); // id == 1
1318        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![known]));
1319
1320        let patch = ts_control::PeerChange {
1321            id: 999, // not in the netmap
1322            derp_region: None,
1323            cap: None,
1324            cap_map: None,
1325            underlay_addresses: Some(vec!["198.51.100.9:1".parse().unwrap()]),
1326            node_key: None,
1327            key_signature: None,
1328            disco_key: None,
1329            node_key_expiry: None,
1330            online: None,
1331            last_seen: None,
1332        };
1333        let (upserts, deletions) = tracker.apply_peer_patches(std::slice::from_ref(&patch));
1334
1335        assert_eq!(upserts.len(), 0);
1336        assert_eq!(deletions.len(), 0);
1337        assert_eq!(tracker.peer_db.peers().len(), 1);
1338        assert!(tracker.peer_db.get(&(999 as ts_control::NodeId)).is_none());
1339    }
1340
1341    /// An expiry-only `Patch` updates `node_key_expiry` on the matching peer (Go
1342    /// `PeerChange.KeyExpiry`), rather than being silently dropped until the next full resync.
1343    #[tokio::test]
1344    async fn patch_updates_node_key_expiry() {
1345        let mut tracker = PeerTracker::for_test(test_env(), None, None);
1346        let peer = peer_node("expiring", [1u8; 32], vec![]); // id == 1, node_key_expiry: None
1347        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]));
1348
1349        let expiry = "2027-01-01T00:00:00Z"
1350            .parse::<chrono::DateTime<chrono::Utc>>()
1351            .unwrap();
1352        let patch = ts_control::PeerChange {
1353            id: 1,
1354            derp_region: None,
1355            cap: None,
1356            cap_map: None,
1357            underlay_addresses: None,
1358            node_key: None,
1359            key_signature: None,
1360            disco_key: None,
1361            node_key_expiry: Some(expiry),
1362            online: None,
1363            last_seen: None,
1364        };
1365        tracker.apply_peer_patches(std::slice::from_ref(&patch));
1366
1367        let (_pid, after) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
1368        assert_eq!(after.node_key_expiry, Some(expiry));
1369    }
1370
1371    /// Channel B: a `PeerChange.online` patch flips a peer's online state without a full node.
1372    #[tokio::test]
1373    async fn patch_updates_online() {
1374        let mut tracker = PeerTracker::for_test(test_env(), None, None);
1375        let peer = peer_node("p", [1u8; 32], vec![]); // id == 1, online: None
1376        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]));
1377        assert_eq!(
1378            tracker
1379                .peer_db
1380                .get(&(1 as ts_control::NodeId))
1381                .unwrap()
1382                .1
1383                .online,
1384            None
1385        );
1386
1387        let mut patch = ts_control::PeerChange {
1388            id: 1,
1389            derp_region: None,
1390            cap: None,
1391            cap_map: None,
1392            underlay_addresses: None,
1393            node_key: None,
1394            key_signature: None,
1395            disco_key: None,
1396            node_key_expiry: None,
1397            online: Some(true),
1398            last_seen: None,
1399        };
1400        tracker.apply_peer_patches(std::slice::from_ref(&patch));
1401        assert_eq!(
1402            tracker
1403                .peer_db
1404                .get(&(1 as ts_control::NodeId))
1405                .unwrap()
1406                .1
1407                .online,
1408            Some(true),
1409            "PeerChange.online=Some(true) marks the peer online"
1410        );
1411
1412        // A subsequent patch flips it offline.
1413        patch.online = Some(false);
1414        tracker.apply_peer_patches(std::slice::from_ref(&patch));
1415        assert_eq!(
1416            tracker
1417                .peer_db
1418                .get(&(1 as ts_control::NodeId))
1419                .unwrap()
1420                .1
1421                .online,
1422            Some(false)
1423        );
1424    }
1425
1426    /// Channel C/D: the `online_change` map flips online directly; `peer_seen_change: false`
1427    /// ("the peer is gone") marks the peer offline. Both apply to a peer already in the netmap and
1428    /// ignore unknown ids.
1429    #[tokio::test]
1430    async fn liveness_change_maps_apply_online() {
1431        let mut tracker = PeerTracker::for_test(test_env(), None, None);
1432        let peer = peer_node("p", [1u8; 32], vec![]); // id == 1
1433        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]));
1434
1435        // Channel C: online_change sets online=true.
1436        let mut online_change = std::collections::BTreeMap::new();
1437        online_change.insert(1 as ts_control::NodeId, true);
1438        online_change.insert(999 as ts_control::NodeId, true); // unknown id — ignored
1439        let changed = tracker.apply_liveness_changes(&online_change, &Default::default());
1440        assert!(changed);
1441        assert_eq!(
1442            tracker
1443                .peer_db
1444                .get(&(1 as ts_control::NodeId))
1445                .unwrap()
1446                .1
1447                .online,
1448            Some(true)
1449        );
1450
1451        // Channel D: peer_seen_change=false marks the peer offline (gone), node retained.
1452        let mut peer_seen_change = std::collections::BTreeMap::new();
1453        peer_seen_change.insert(1 as ts_control::NodeId, false);
1454        let changed = tracker.apply_liveness_changes(&Default::default(), &peer_seen_change);
1455        assert!(changed);
1456        assert_eq!(
1457            tracker
1458                .peer_db
1459                .get(&(1 as ts_control::NodeId))
1460                .unwrap()
1461                .1
1462                .online,
1463            Some(false),
1464            "peer_seen_change=false marks offline (the node stays in the netmap)"
1465        );
1466        assert_eq!(
1467            tracker.peer_db.peers().len(),
1468            1,
1469            "the node is retained, not removed"
1470        );
1471
1472        // No-op when nothing matches / changes.
1473        assert!(!tracker.apply_liveness_changes(&Default::default(), &Default::default()));
1474    }
1475
1476    /// Security: a `Patch` that rotates the node key must re-satisfy the tailnet-lock authority,
1477    /// exactly like a `Delta` upsert. A key-rotation patch whose new signature does NOT verify
1478    /// evicts the peer (fail-closed) rather than leaving a now-unverified entry — closing what would
1479    /// otherwise be a trust-enforcement bypass via the patch path.
1480    #[tokio::test]
1481    async fn patch_key_rotation_failing_tka_evicts_peer() {
1482        let (authority, sig) = authority_and_valid_sig();
1483        let mut tracker = PeerTracker::for_test(test_env(), Some(authority), None);
1484
1485        // Admit a correctly-signed peer (id == 1).
1486        let good = peer_node("rotator", NODE_KEY_BYTES, sig.clone());
1487        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![good.clone()]));
1488        assert_eq!(tracker.peer_db.peers().len(), 1);
1489
1490        // Patch a new node key whose signature is garbage under the active authority.
1491        let patch = ts_control::PeerChange {
1492            id: 1,
1493            derp_region: None,
1494            cap: None,
1495            cap_map: None,
1496            underlay_addresses: None,
1497            node_key: Some([0x33u8; 32].into()),
1498            key_signature: Some(vec![0x00, 0x01, 0x02]),
1499            disco_key: None,
1500            node_key_expiry: None,
1501            online: None,
1502            last_seen: None,
1503        };
1504        let (upserts, deletions) = tracker.apply_peer_patches(std::slice::from_ref(&patch));
1505
1506        assert_eq!(upserts.len(), 0);
1507        assert_eq!(deletions.len(), 1);
1508        assert_eq!(tracker.peer_db.peers().len(), 0);
1509    }
1510
1511    /// A node's `user_id` joins against the accumulated UserProfiles table to resolve the owning
1512    /// user's login name in `WhoIs.user`. With no matching profile, `user` is `None` (the
1513    /// pre-existing behavior); once a profile arrives, the same node resolves to its login. This
1514    /// proves the accumulate-then-join path the netmap handler builds.
1515    fn profile(id: ts_control::UserId, login: &str) -> ts_control::UserProfile {
1516        ts_control::UserProfile {
1517            id,
1518            login_name: login.to_string(),
1519            display_name: None,
1520        }
1521    }
1522
1523    #[tokio::test]
1524    async fn whois_resolves_user_from_accumulated_profiles() {
1525        let mut tracker = PeerTracker::for_test(test_env(), None, None);
1526
1527        // A peer owned by user id 42 at 100.64.0.1 (the peer_node fixture's address).
1528        let mut peer = peer_node("p", NODE_KEY_BYTES, Vec::new());
1529        peer.user_id = 42;
1530        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]));
1531        let addr = "100.64.0.1:0".parse().unwrap();
1532
1533        // No profile yet: the node resolves but its owner is unknown.
1534        let who = tracker.whois_opt(addr).expect("peer is known");
1535        assert_eq!(who.user, None);
1536
1537        // Profile for a DIFFERENT user must not match.
1538        tracker
1539            .user_profiles
1540            .insert(7, profile(7, "someone-else@example.com"));
1541        assert_eq!(tracker.whois_opt(addr).unwrap().user, None);
1542
1543        // The owning user's profile arrives (as the netmap handler would accumulate it): now the
1544        // login resolves.
1545        tracker
1546            .user_profiles
1547            .insert(42, profile(42, "alice@example.com"));
1548        assert_eq!(
1549            tracker.whois_opt(addr).unwrap().user,
1550            Some("alice@example.com".to_string())
1551        );
1552    }
1553
1554    /// `UserProfile::best_label` prefers the login name, falling back to display name, else `None`.
1555    #[test]
1556    fn user_profile_best_label_prefers_login() {
1557        assert_eq!(
1558            profile(1, "alice@example.com").best_label(),
1559            Some("alice@example.com".to_string())
1560        );
1561        let display_only = ts_control::UserProfile {
1562            id: 2,
1563            login_name: String::new(),
1564            display_name: Some("Bob".to_string()),
1565        };
1566        assert_eq!(display_only.best_label(), Some("Bob".to_string()));
1567        let empty = ts_control::UserProfile {
1568            id: 3,
1569            login_name: String::new(),
1570            display_name: None,
1571        };
1572        assert_eq!(empty.best_label(), None);
1573    }
1574}