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_keys::{DiscoPublicKey, NodePublicKey};
17use ts_transport::PeerId;
18
19use crate::{
20    Error, dataplane::PeerDiscoKeyAdvertisement, direct::DiscoKeyObserved, env::Env,
21    status::StatusNode,
22};
23
24mod peer_db;
25
26pub use peer_db::{DiscoKeyMatch, PeerDb};
27
28/// Whether `key` is the all-zero disco key, which Go spells `key.DiscoPublic.IsZero()` and treats
29/// everywhere as "this peer has no disco key" rather than as a usable key.
30fn disco_key_is_zero(key: &DiscoPublicKey) -> bool {
31    key.to_bytes() == [0u8; DiscoPublicKey::KEY_LEN_BYTES]
32}
33
34/// Normalize a disco key as it arrives from control: the all-zero key means "absent", exactly as
35/// Go's `IsZero()` checks in `endpoint.updateDiscoKey` read it.
36fn disco_key_from_control(key: Option<DiscoPublicKey>) -> Option<DiscoPublicKey> {
37    key.filter(|k| !disco_key_is_zero(k))
38}
39
40/// The two disco keys a peer can present, and which of them is currently active — Go
41/// [`magicsock.endpointDisco`] (`wgengine/magicsock/endpoint.go`).
42///
43/// A peer's disco key reaches us from two independent sources: **control**, in a netmap node or a
44/// `PeersChangedPatch`, and the **peer itself**, in a TSMP disco-key advertisement carried inside
45/// the WireGuard tunnel. Go keeps both side by side on the endpoint, and so do we, because control
46/// is the slower of the two: an advertisement exists precisely to cover the window where control has
47/// not caught up with the peer's current key, so collapsing the two into one field would let the
48/// next map poll overwrite a freshly-learned key with control's stale one — losing the feature's own
49/// motivating case.
50///
51/// Only one key is active for sending at a time ([`key`](Self::key)). That active key is what the
52/// peer db carries in [`Node::disco_key`], which is this fork's live lookup for every direct-path
53/// consumer (`direct::DiscoPeerLookup` resolves against it, and `PeerDb`'s disco index is built from
54/// it) — the stand-in for Go's per-endpoint `disco` pointer.
55///
56/// [`magicsock.endpointDisco`]: https://github.com/tailscale/tailscale/blob/49e148c4a30b4f8098f69468fd27a7021d85ea02/wgengine/magicsock/endpoint.go
57#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
58struct EndpointDisco {
59    /// The key learned from control (Go `endpointDisco.controlKey`).
60    control: Option<DiscoPublicKey>,
61    /// The key learned from a TSMP advertisement (Go `endpointDisco.tsmpKey`).
62    tsmp: Option<DiscoPublicKey>,
63    /// Whether [`tsmp`](Self::tsmp) is the active key (Go `endpointDisco.tsmpActive`).
64    tsmp_active: bool,
65}
66
67impl EndpointDisco {
68    /// The key currently regarded as active — Go `endpointDisco.key()`.
69    fn key(&self) -> Option<DiscoPublicKey> {
70        if self.tsmp_active {
71            self.tsmp
72        } else {
73            self.control
74        }
75    }
76
77    /// The control-learned key, active or not — Go `endpointDisco.keyFromControl()`.
78    fn key_from_control(&self) -> Option<DiscoPublicKey> {
79        self.control
80    }
81
82    /// The TSMP-learned key, active or not — Go `endpointDisco.keyFromTSMP()`.
83    fn key_from_tsmp(&self) -> Option<DiscoPublicKey> {
84        self.tsmp
85    }
86
87    /// Replace the control-learned key, leaving any TSMP-learned key in place — Go
88    /// [`endpoint.updateDiscoKey`].
89    ///
90    /// Control's key is always recorded in control's own slot, but it takes the *active* slot only
91    /// if no TSMP-learned key already holds it: Go `epDisco.tsmpActive = old.tsmpActive ||
92    /// key.IsZero()`. A key the peer told us itself is better evidence than a control server that
93    /// is, by construction, the slower of the two sources — so control changing its mind no longer
94    /// preempts an active TSMP key. Upstream returns to control's key when disco is actually
95    /// *received* under it (`endpoint.checkAndUpdateDiscoKey`), not when control asserts it.
96    ///
97    /// An absent (Go: zero) control key still hands the slot to the TSMP key, if there is one. When
98    /// there is neither key, the caller drops the whole entry ([`is_empty`](Self::is_empty)) — which
99    /// is what stops an active TSMP slot with no TSMP key in it outliving this call, exactly as Go
100    /// nils the endpoint's `disco` pointer in the same case.
101    ///
102    /// [`endpoint.updateDiscoKey`]: https://github.com/tailscale/tailscale/blob/9ea7cba44591e0cd840c6c94d23274dd222059bf/wgengine/magicsock/endpoint.go
103    fn update_from_control(&mut self, key: Option<DiscoPublicKey>) {
104        self.control = key;
105        self.tsmp_active = self.tsmp_active || key.is_none();
106    }
107
108    /// Replace the TSMP-learned key, leaving the control-learned key in place — Go
109    /// `endpoint.updateTSMPDiscoKey`.
110    fn update_from_tsmp(&mut self, key: Option<DiscoPublicKey>) {
111        self.tsmp = key;
112        self.tsmp_active = key.is_some();
113    }
114
115    /// The peer's other known key: the slot that is not active, when it holds a key that differs
116    /// from the active one.
117    ///
118    /// This is what makes ingress under the peer's *other* key resolvable
119    /// ([`PeerDb::set_inactive_disco_key`]). `None` when the inactive slot is empty or holds the
120    /// same key as the active one — there is no second key to accept in either case.
121    fn inactive_key(&self) -> Option<DiscoPublicKey> {
122        let inactive = if self.tsmp_active {
123            self.control
124        } else {
125            self.tsmp
126        };
127
128        inactive.filter(|k| Some(*k) != self.key())
129    }
130
131    /// Accept `key` as this peer's, switching the active slot to it when it is the currently
132    /// *inactive* one — Go [`endpoint.checkAndUpdateDiscoKey`].
133    ///
134    /// Called with the sender key of a disco frame we have opened, which proves the sender holds
135    /// that key's private half. Receiving under a key is therefore demonstrative: it is what the
136    /// peer is actually using, so upstream makes it the key we send to as well.
137    ///
138    /// Returns `None` when `key` belongs to **neither** slot — the refusal that is the whole
139    /// security value of the check, and the reason this is not simply "trust whatever key opened".
140    /// Otherwise `Some(changed)`, where `changed` reports whether the active key moved (and so
141    /// whether the direct path built under the old one has to be invalidated).
142    ///
143    /// [`endpoint.checkAndUpdateDiscoKey`]: https://github.com/tailscale/tailscale/blob/9ea7cba44591e0cd840c6c94d23274dd222059bf/wgengine/magicsock/endpoint.go
144    fn check_and_update(&mut self, key: DiscoPublicKey) -> Option<bool> {
145        if self.key() == Some(key) {
146            return Some(false);
147        }
148
149        // Not the active key. Go's compare-and-swap on `tsmpActive`: whichever slot holds it
150        // becomes the active one. Control's slot is tried first only for determinism — the two
151        // holding the same key is already handled by the equality check above.
152        if self.control == Some(key) {
153            self.tsmp_active = false;
154            return Some(true);
155        }
156        if self.tsmp == Some(key) {
157            self.tsmp_active = true;
158            return Some(true);
159        }
160
161        None
162    }
163
164    /// No key material from either source — Go nils out the endpoint's `disco` pointer here.
165    fn is_empty(&self) -> bool {
166        self.control.is_none() && self.tsmp.is_none()
167    }
168}
169
170/// Actor that tracks peer delta updates and emits new states.
171pub struct PeerTracker {
172    peer_db: PeerDb,
173    seen_state_update: bool,
174    pending_requests: Vec<Pending>,
175    /// Latest peer snapshot, published on every netmap update so embedders can watch for peer
176    /// changes ([`WatchNetmap`]).
177    peer_watch: watch::Sender<Vec<StatusNode>>,
178    /// Accumulated netmap user profiles (`MapResponse.UserProfiles`), keyed by user id, joined
179    /// against a node's [`Node::user_id`](ts_control::Node::user_id) to resolve the owning user's
180    /// login/display name for a [`WhoIs`](crate::status::WhoIs). Control sends these incrementally
181    /// (only new/changed profiles per response), so this map **accumulates** across updates rather
182    /// than being replaced — a peer upserted in one response may reference a profile delivered in an
183    /// earlier one.
184    user_profiles: HashMap<UserId, UserProfile>,
185    /// Per-peer disco-key provenance ([`EndpointDisco`]), keyed by the peer's node key.
186    ///
187    /// Go keeps this on the magicsock `endpoint`, which the peer map keys by node key; here the peer
188    /// db stores control's [`Node`] verbatim, so the second key (and which of the two is active)
189    /// lives beside it. Keying by node key reproduces Go's lifetime exactly: the state is dropped
190    /// when the peer leaves the netmap, and a peer that ROTATES its node key gets a fresh entry —
191    /// Go builds it a new endpoint, so a key learned over TSMP under the old node key is never
192    /// carried onto the new one. [`prune_endpoint_disco`](PeerTracker::prune_endpoint_disco) does
193    /// the dropping.
194    endpoint_disco: HashMap<NodePublicKey, EndpointDisco>,
195    /// Tailnet-Lock (TKA) authority enforced at the peer-trust chokepoint, matching Go
196    /// `tkaFilterNetmapLocked`. Read on demand from a [`watch`] cell the control runner owns: when it
197    /// holds `Some` (a verified lock has been synced from control), enforcement is **active** — every
198    /// upserted peer must present a `key_signature` this authority authorizes, or it is dropped
199    /// (fail-closed), exactly as Go drops peers with a missing or failing signature. When it holds
200    /// `None` (no lock, or the lock was disabled) enforcement is **inactive** and every peer is
201    /// upserted, identical to pre-TKA behavior and to Go's `b.tka == nil` early return.
202    ///
203    /// A `watch::Receiver` (not the bus) is the transport on purpose: the authority is a single
204    /// security-critical state cell, and `watch` is last-write-wins, never-dropped, and ordered by
205    /// the control runner's own writes — so a disable (`None`) can never be reordered behind or
206    /// silently dropped before a stale `Some` (which a best-effort broadcast bus could do, leaving a
207    /// defunct lock enforcing forever). The control runner is the sole writer; we only ever read.
208    ///
209    /// The authority always passes through `VerifiedAumChain::verify` before the control runner
210    /// publishes it, so enforcement only engages on a chain we have cryptographically verified.
211    /// Connectivity now depends on `ts_tka` verifying genuinely-good signatures correctly (see
212    /// SECURITY.md). Self is structurally never filtered here (the self node never enters `peer_db` —
213    /// it is routed to the control runner's `self_node` cell), so a node cannot lock itself out of
214    /// its own netmap.
215    tka_authority: watch::Receiver<Option<Arc<ts_tka::Authority>>>,
216    env: Env,
217}
218
219impl PeerTracker {
220    fn peer_by_name_opt(&self, name: &str) -> Option<&Node> {
221        // Canonicalization (case + trailing dot) is handled inside the name index lookup.
222        self.peer_db.get(&name).map(|(_id, node)| node)
223    }
224
225    fn peer_by_tailnet_ip_opt(&self, ip: IpAddr) -> Option<&Node> {
226        self.peer_db.get(&ip).map(|(_id, node)| node)
227    }
228
229    /// Build the peer entries for a [`Status`](crate::Status) snapshot from the current peer db.
230    ///
231    /// Connectivity fields (`cur_addr`/`relay`) are left at their `from_node` defaults (`None`) here:
232    /// this is the live-watch/hot path and must stay magicsock-free and synchronous. The explicit
233    /// [`GetStatus`] snapshot enriches them ([`status_peers_with_ids`](Self::status_peers_with_ids)).
234    fn status_peers(&self) -> Vec<StatusNode> {
235        self.peer_db
236            .peers()
237            .values()
238            .map(StatusNode::from_node)
239            .collect()
240    }
241
242    /// Like [`status_peers`](Self::status_peers) but pairs each entry with its [`PeerId`], so the
243    /// caller can join per-peer connectivity (the direct manager's `best_addrs`, keyed by `PeerId`)
244    /// onto the `StatusNode` before returning it. Order is unspecified (a `HashMap` walk).
245    fn status_peers_with_ids(&self) -> Vec<(PeerId, StatusNode)> {
246        self.peer_db
247            .peers()
248            .iter()
249            .map(|(id, node)| (*id, StatusNode::from_node(node)))
250            .collect()
251    }
252
253    fn whois_opt(&self, addr: std::net::SocketAddr) -> Option<crate::status::WhoIs> {
254        let ip = crate::status::whois_addr(addr);
255        let node = self.peer_by_tailnet_ip_opt(ip).cloned()?;
256        // Join the node's owning user id against the accumulated UserProfiles table to resolve a
257        // login/display name. `None` when control sent no profile for that user (e.g. tagged nodes
258        // with no human owner, or a profile not yet delivered).
259        let user = self.resolve_user(node.user_id);
260        Some(crate::status::WhoIs::from_node_with_user(node, user))
261    }
262
263    /// Resolve a user id to its best display label from the accumulated profile table.
264    fn resolve_user(&self, user_id: UserId) -> Option<String> {
265        self.user_profiles
266            .get(&user_id)
267            .and_then(UserProfile::best_label)
268    }
269
270    /// Whether `node` may be admitted to the peer db under Tailnet Lock, matching Go
271    /// `tkaFilterNetmapLocked`'s per-peer verdict (drop unsigned / failed-signature peers).
272    ///
273    /// This consults the live [`tka_authority`](Self::tka_authority) cell on each call (one `borrow`,
274    /// held only for the duration of the verdict). For a `Full` resync — which checks every peer —
275    /// prefer [`tka_authority_snapshot`](Self::tka_authority_snapshot) +
276    /// [`tka_snapshot_admits`](Self::tka_snapshot_admits) to borrow once and verify each peer a single
277    /// time; this method is the convenience wrapper for the single-peer (`Delta`/patch) sites.
278    ///
279    /// Fail-closed and gated:
280    /// - No authority ⇒ no lock synced ⇒ always admit (Go's `b.tka == nil` early return; identical to
281    ///   pre-TKA behavior).
282    /// - **Empty trusted-key state** ⇒ always admit (logged at `error!` — see
283    ///   [`tka_snapshot_admits`](Self::tka_snapshot_admits) for the full rationale).
284    /// - Authority present + peer carries a `key_signature` the authority authorizes for the peer's
285    ///   node key ⇒ admit.
286    /// - Authority present + signature missing or unauthorized/invalid ⇒ **drop** (Go drops peers
287    ///   with a missing signature or failed `NodeKeyAuthorized` under tailnet lock).
288    fn tka_admits(&self, node: &Node) -> bool {
289        // Single-peer sites (`Delta`/patch) only need the admit bool; the rotation details are used
290        // exclusively by the cross-peer `Full` filter (rotation obsolescence is whole-netmap).
291        Self::tka_snapshot_admits(self.tka_authority.borrow().as_deref(), node).admitted
292    }
293
294    /// Borrow the current TKA authority once (cloning the cheap `Arc`) for a batch verdict. Returns
295    /// `None` when no lock is synced (admit-all). Used by the `Full` path so a netmap of N peers
296    /// reads the cell once and runs at most one signature verify per peer (not two).
297    fn tka_authority_snapshot(&self) -> Option<Arc<ts_tka::Authority>> {
298        self.tka_authority.borrow().clone()
299    }
300
301    /// The per-peer Tailnet-Lock verdict against an already-borrowed `authority` snapshot. Factored
302    /// out so both the single-peer [`tka_admits`](Self::tka_admits) and the `Full` batch path share
303    /// one verdict implementation (no divergence) while the batch path verifies each peer exactly
304    /// once.
305    ///
306    /// Returns whether the peer is admitted AND, for an admitted peer signed by a rotation chain, the
307    /// [`RotationDetails`](ts_tka::RotationDetails) of that chain — so the `Full` path can run the
308    /// cross-peer rotation filter (Go's `rotationTracker`) without a second verify per peer. A peer
309    /// that is dropped, unsigned, or signed by a non-rotation chain carries `rotation == None`.
310    ///
311    /// Never logs key/signature bytes — only the `stable_id` and the `TkaError` Display (static
312    /// descriptors). One documented parity gap remains vs Go (in PARITY_ROADMAP): no
313    /// `UnsignedPeerAPIOnly` *admission* exemption — Go admits such a peer unsigned under an active
314    /// lock, we drop it (stricter, the safe direction). [`Node::unsigned_peer_api_only`] is now
315    /// carried, and the routes half of upstream's treatment is enforced at decode
316    /// (`ts_control::Node`'s `From` impl clamps such a peer's accepted routes to its own addresses,
317    /// unconditionally, whether or not a lock is active); only the admission carve-out is deferred.
318    fn tka_snapshot_admits(authority: Option<&ts_tka::Authority>, node: &Node) -> TkaVerdict {
319        let Some(auth) = authority else {
320            return TkaVerdict::admit();
321        };
322
323        // Brick-guard: an authority with no trusted keys would drop every peer. A verified chain is
324        // structurally guaranteed ≥1 key (genesis rejects an empty key set, and the last key cannot
325        // be removed), so reaching here means a `ts_tka` invariant was violated — admit rather than
326        // black-hole the whole netmap, and log at `error!` because it signals a real bug, not an
327        // expected runtime input. This is OUR fail-safe, not a Go behavior. NOTE: it only catches the
328        // empty-keyset shape; a non-empty authority that authorizes none of the offered peers still
329        // (correctly) drops them — that is what a lock that revoked everyone means. The
330        // "authorized-zero-peers" isolation case is surfaced separately by the caller.
331        if auth.state().keys.is_empty() {
332            tracing::error!(
333                "TKA: authority has an empty trusted-key set (verified chains never do — likely a \
334                 ts_tka bug); not enforcing (admitting all) to avoid isolating the node"
335            );
336            return TkaVerdict::admit();
337        }
338
339        if node.key_signature.is_empty() {
340            tracing::warn!(
341                stable_id = ?node.stable_id,
342                "TKA: dropping unsigned peer under tailnet lock"
343            );
344            return TkaVerdict::drop();
345        }
346
347        match auth.node_key_authorized_with_details(&node.node_key.to_bytes(), &node.key_signature)
348        {
349            Ok(rotation) => {
350                tracing::debug!(stable_id = ?node.stable_id, "TKA: peer node-key authorized");
351                TkaVerdict {
352                    admitted: true,
353                    rotation,
354                }
355            }
356            Err(e) => {
357                tracing::warn!(
358                    stable_id = ?node.stable_id,
359                    error = %e,
360                    "TKA: dropping peer with unauthorized node key"
361                );
362                TkaVerdict::drop()
363            }
364        }
365    }
366
367    /// The **keep** verdict for a whole batch of peers under `authority` — one complete Go
368    /// `tkaFilterNetmapLocked` pass (`ipn/ipnlocal/tailnet-lock.go`, v1.100.0), in Go's order:
369    ///
370    /// 1. the per-peer signature verdict ([`tka_snapshot_admits`](Self::tka_snapshot_admits)), then
371    /// 2. the cross-peer rotation filter (Go `rotationTracker`): a peer presenting a node key that a
372    ///    newer rotation has superseded — or a tied clone of one — is dropped even though its own
373    ///    signature verifies. That is whole-batch by nature (one peer's chain obsoletes another's
374    ///    key), which is why it lives here and not in the per-peer verdict.
375    ///
376    /// Factored out because two call sites must agree exactly on what "admitted" means: the `Full`
377    /// netmap upsert in [`apply_peer_update`](Self::apply_peer_update), and
378    /// [`tka_reevaluate_peer_db`](Self::tka_reevaluate_peer_db), which re-runs the same pass over the
379    /// peers already in the db when a freshly-synced authority is installed. A divergence between
380    /// them would be a peer admitted by one path and dropped by the other.
381    ///
382    /// `authority` is borrowed once and each peer verified exactly once (the ed25519 verify is the
383    /// expensive part). Returns one `bool` per input node, in input order; `None` authority ⇒ all
384    /// `true` (no lock synced ⇒ admit all, Go's `b.tka == nil` early return).
385    fn tka_keep_verdicts(authority: Option<&ts_tka::Authority>, nodes: &[&Node]) -> Vec<bool> {
386        let verdicts = nodes
387            .iter()
388            .map(|node| Self::tka_snapshot_admits(authority, node))
389            .collect::<Vec<_>>();
390
391        let mut rotation = RotationTracker::default();
392        for (node, verdict) in nodes.iter().zip(&verdicts) {
393            if verdict.admitted
394                && let Some(details) = &verdict.rotation
395            {
396                rotation.add(node.node_key.to_bytes().to_vec(), details);
397            }
398        }
399        let obsolete = rotation.obsolete_keys();
400
401        nodes
402            .iter()
403            .zip(&verdicts)
404            .map(|(node, v)| {
405                // `contains` takes `&[u8]` (HashSet<Vec<u8>> borrows as a slice) — no alloc.
406                v.admitted && !obsolete.contains(&node.node_key.to_bytes()[..])
407            })
408            .collect()
409    }
410}
411
412/// The outcome of a per-peer Tailnet-Lock check: whether the peer is admitted, plus (for an admitted
413/// peer signed by a rotation chain) the chain's [`RotationDetails`](ts_tka::RotationDetails) so the
414/// `Full` path can run the cross-peer rotation filter from the SAME verify pass (no second verify).
415struct TkaVerdict {
416    admitted: bool,
417    rotation: Option<ts_tka::RotationDetails>,
418}
419
420impl TkaVerdict {
421    /// Admitted, no rotation details (no lock / brick-guard / non-rotation signature).
422    fn admit() -> Self {
423        Self {
424            admitted: true,
425            rotation: None,
426        }
427    }
428    /// Dropped.
429    fn drop() -> Self {
430        Self {
431            admitted: false,
432            rotation: None,
433        }
434    }
435}
436
437/// Cross-peer rotation-obsolescence tracker, mirroring Go `ipnlocal.rotationTracker`. Fed the
438/// [`RotationDetails`](ts_tka::RotationDetails) of every admitted, rotation-signed peer in a `Full`
439/// netmap; [`obsolete_keys`](Self::obsolete_keys) then returns the node keys to drop on top of the
440/// per-peer verdict. Two rules (Go `tkaFilterNetmapLocked` + `rotationTracker.obsoleteKeys`):
441///
442/// 1. Every prior node key named in any rotation chain is obsolete (a newer chain rotated it away).
443/// 2. Among `Direct`-rooted chains sharing one wrapping pubkey (a clone signal), only the
444///    longest-chain peer survives; if the two longest are tied, ALL in that group are dropped (we
445///    cannot tell which is the latest, so reject for safety). `Credential`-rooted chains are exempt
446///    from rule 2 — several nodes can legitimately join under one reusable auth key (same wrapping
447///    pubkey), so sharing it is not a clone signal there. (Rule 1 still applies to them.)
448///
449/// Node keys are tracked as raw `Vec<u8>` (the verified 32-byte node-public bytes).
450#[derive(Default)]
451struct RotationTracker {
452    obsolete: HashSet<Vec<u8>>,
453    by_wrapping_key: HashMap<Vec<u8>, Vec<SigRotation>>,
454}
455
456/// One admitted peer's rotation entry within a wrapping-key group.
457struct SigRotation {
458    node_key: Vec<u8>,
459    num_prev_keys: usize,
460}
461
462impl RotationTracker {
463    /// Record an admitted peer `node_key` and its rotation `details` (Go `addRotationDetails`).
464    fn add(&mut self, node_key: Vec<u8>, details: &ts_tka::RotationDetails) {
465        // Rule 1: every prior key is obsolete — applied for ALL chains (incl. credential-rooted),
466        // matching Go's ungated `obsolete.AddSlice(d.PrevNodeKeys)`.
467        self.obsolete.extend(details.prev_node_keys.iter().cloned());
468        // Rule 2 (clone-uniqueness) is gated to Direct-rooted chains only.
469        if details.initial_sig_kind != ts_tka::SigKind::Direct {
470            return;
471        }
472        self.by_wrapping_key
473            .entry(details.initial_wrapping_pubkey.clone())
474            .or_default()
475            .push(SigRotation {
476                node_key,
477                num_prev_keys: details.prev_node_keys.len(),
478            });
479    }
480
481    /// Compute the full obsolete node-key set (Go `rotationTracker.obsoleteKeys`). Processes each
482    /// wrapping-key group, mutating the shared `obsolete` set as it goes (so a key obsoleted by one
483    /// group is seen as obsolete by later groups via the `retain` below — Go's
484    /// `slices.DeleteFunc(... Contains)`). Group iteration order (a `HashMap` drain) is
485    /// nondeterministic, but the result is order-INDEPENDENT: this only ever *inserts* into
486    /// `obsolete` (never removes), and rule 1 already obsoleted every prior key before this loop, so
487    /// the final set is a union that does not depend on which group runs first (as in Go).
488    fn obsolete_keys(mut self) -> HashSet<Vec<u8>> {
489        // Drain only the group map so the loop can mutate `self.obsolete` without aliasing it; the
490        // shared `obsolete` set itself is NOT drained, preserving the cross-group visibility above.
491        let groups: Vec<Vec<SigRotation>> = self.by_wrapping_key.drain().map(|(_k, v)| v).collect();
492        for mut group in groups {
493            // Drop entries already obsoleted (rotated away) by another chain.
494            group.retain(|rd| !self.obsolete.contains(&rd.node_key));
495            if group.is_empty() {
496                continue;
497            }
498            // Longest chain (most prior keys) is the newest ⇒ the survivor; sort decreasing.
499            // `sort_by_key` is stable (like Go's `SortStableFunc`); `Reverse` gives descending order.
500            group.sort_by_key(|rd| core::cmp::Reverse(rd.num_prev_keys));
501            if group.len() >= 2 && group[0].num_prev_keys == group[1].num_prev_keys {
502                // Tie for longest ⇒ cannot disambiguate the latest ⇒ drop the WHOLE group.
503                tracing::warn!(
504                    "TKA: multiple peers share a wrapping key with equal rotation depth; dropping all (cannot determine the latest)"
505                );
506                for rd in &group {
507                    self.obsolete.insert(rd.node_key.clone());
508                }
509            } else {
510                // Only the longest-chain peer survives; the rest are obsolete.
511                for rd in &group[1..] {
512                    self.obsolete.insert(rd.node_key.clone());
513                }
514            }
515        }
516        self.obsolete
517    }
518}
519
520impl kameo::Actor for PeerTracker {
521    /// `(env, tka_authority)`: the bus/keys env, plus the read end of the control runner's TKA
522    /// enforcement-authority cell (Go `tkaFilterNetmapLocked`). The control runner is the sole
523    /// writer; it publishes the verified `Authority` after a successful `/machine/tka/sync` and
524    /// `None` when the lock is disabled. A `watch` cell (not a bus message) so the latest value is
525    /// always readable on demand, never dropped, and never reordered (see the control runner's
526    /// `tka_authority` cell).
527    type Args = (Env, watch::Receiver<Option<Arc<ts_tka::Authority>>>);
528    type Error = Error;
529
530    async fn on_start(
531        (env, tka_authority): Self::Args,
532        slf: ActorRef<Self>,
533    ) -> Result<Self, Self::Error> {
534        env.subscribe::<Arc<ts_control::StateUpdate>>(&slf).await?;
535        env.subscribe::<PeerDiscoKeyAdvertisement>(&slf).await?;
536        env.subscribe::<DiscoKeyObserved>(&slf).await?;
537
538        // Re-filter the peer db whenever the enforcement authority changes. Go gets this for free:
539        // `SetControlClientStatus` runs `tkaSyncIfNeeded` and `tkaFilterNetmapLocked` back to back
540        // over one netmap. Here the sync is asynchronous, so the peers admitted before the authority
541        // arrived need a second pass — see `tka_reevaluate_peer_db`. `changed()` resolves on every
542        // write to the cell (enable, re-sync, disable); the task ends when the control runner drops
543        // the sender (shutdown) or the tracker itself is gone.
544        //
545        // A **weak** ref on purpose: the runtime holds only a `WeakActorRef` to the peer tracker, so
546        // a strong one parked in this task would keep the actor's mailbox alive past shutdown.
547        let mut authority_changes = tka_authority.clone();
548        let notify = slf.downgrade();
549        tokio::spawn(async move {
550            while authority_changes.changed().await.is_ok() {
551                let Some(tracker) = notify.upgrade() else {
552                    break; // the peer tracker is gone; nothing left to re-filter
553                };
554                if tracker.tell(TkaAuthorityChanged).await.is_err() {
555                    break; // the peer tracker stopped
556                }
557            }
558        });
559
560        let (peer_watch, _) = watch::channel(Vec::new());
561
562        Ok(Self {
563            peer_db: PeerDb::default(),
564            pending_requests: Default::default(),
565            seen_state_update: false,
566            peer_watch,
567            user_profiles: HashMap::new(),
568            endpoint_disco: HashMap::new(),
569            // The cell starts `None` (no lock synced ⇒ enforcement inactive, admit all, matching
570            // Go's `b.tka == nil`); the control runner flips it to `Some` on the first sync.
571            tka_authority,
572            env,
573        })
574    }
575}
576
577enum Pending {
578    PeerByName(PeerByName, ReplySender<Option<Node>>),
579    AcceptedRoute(PeerByAcceptedRoute, ReplySender<Vec<Node>>),
580    TailnetIp(PeerByTailnetIp, ReplySender<Option<Node>>),
581    Status(ReplySender<Vec<(PeerId, StatusNode)>>),
582    WhoIs(Whois, ReplySender<Option<crate::status::WhoIs>>),
583}
584
585// For messages with arguments, a struct is generated with the args as fields. They aren't
586// documented, and we can't apply attributes directly to the fields. Hence, wrap in a module where
587// docs are turned off everywhere.
588#[allow(missing_docs)]
589mod msg_impl {
590    use std::net::IpAddr;
591
592    use kameo::prelude::DelegatedReply;
593
594    use super::*;
595
596    #[kameo::messages]
597    impl PeerTracker {
598        /// Lookup a peer by name.
599        ///
600        /// Waits until we've received at least one peer update from control.
601        #[message(ctx)]
602        pub async fn peer_by_name(
603            &mut self,
604            ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
605            name: String,
606        ) -> DelegatedReply<Option<Node>> {
607            let (deleg, sender) = ctx.reply_sender();
608            let Some(sender) = sender else { return deleg };
609
610            if !self.seen_state_update {
611                tracing::debug!(query = name, "no peer state seen yet, queueing request");
612
613                self.pending_requests
614                    .push(Pending::PeerByName(PeerByName { name }, sender));
615
616                return deleg;
617            }
618
619            sender.send(self.peer_by_name_opt(&name).cloned());
620
621            deleg
622        }
623
624        /// Lookup all peers that accept packets addressed to the given IP.
625        ///
626        /// This includes the peer's tailnet address and any subnet routes it provides. Only
627        /// the peers with the most specific subnet route match that covers `ip` will be
628        /// returned.
629        ///
630        /// E.g., suppose:
631        ///
632        /// - We're querying for `10.1.2.3`
633        /// - `PeerA` and `PeerB` have accepted routes for `10.1.2.0/24`
634        /// - `PeerC` has an accepted route for `10.1.0.0/16`
635        ///
636        /// Only `PeerA` and `PeerB` will be returned, since they have the most specific
637        /// prefix match.
638        #[message(ctx)]
639        pub fn peer_by_accepted_route(
640            &mut self,
641            ctx: &mut Context<Self, DelegatedReply<Vec<Node>>>,
642            ip: IpAddr,
643        ) -> DelegatedReply<Vec<Node>> {
644            let (deleg, sender) = ctx.reply_sender();
645            let Some(sender) = sender else { return deleg };
646
647            if !self.seen_state_update {
648                tracing::debug!(query = %ip, "no peer state seen yet, queueing request");
649
650                self.pending_requests
651                    .push(Pending::AcceptedRoute(PeerByAcceptedRoute { ip }, sender));
652
653                return deleg;
654            }
655
656            sender.send(
657                self.peer_db
658                    .get_route(ip.into())
659                    .map(|(_id, node)| node.clone())
660                    .collect(),
661            );
662
663            deleg
664        }
665
666        /// Lookup the peer that has the given tailnet IP address.
667        #[message(ctx)]
668        pub fn peer_by_tailnet_ip(
669            &mut self,
670            ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
671            ip: IpAddr,
672        ) -> DelegatedReply<Option<Node>> {
673            let (deleg, sender) = ctx.reply_sender();
674            let Some(sender) = sender else { return deleg };
675
676            if !self.seen_state_update {
677                tracing::debug!(query = %ip, "no peer state seen yet, queueing request");
678
679                self.pending_requests
680                    .push(Pending::TailnetIp(PeerByTailnetIp { ip }, sender));
681
682                return deleg;
683            }
684
685            sender.send(self.peer_by_tailnet_ip_opt(ip).cloned());
686
687            deleg
688        }
689
690        /// Build the peer entries of a [`Status`](crate::Status) snapshot, each paired with its
691        /// [`PeerId`] so [`Runtime::status`](crate::Runtime::status) can join per-peer connectivity
692        /// (`cur_addr`/`relay`) from the direct manager before returning. The self node is *not*
693        /// included here (it lives in the control runner); `Runtime::status` combines both and drops
694        /// the ids.
695        ///
696        /// Waits until we've received at least one peer update from control.
697        #[message(ctx)]
698        pub fn get_status(
699            &mut self,
700            ctx: &mut Context<Self, DelegatedReply<Vec<(PeerId, StatusNode)>>>,
701        ) -> DelegatedReply<Vec<(PeerId, StatusNode)>> {
702            let (deleg, sender) = ctx.reply_sender();
703            let Some(sender) = sender else { return deleg };
704
705            if !self.seen_state_update {
706                tracing::debug!("no peer state seen yet, queueing status request");
707                self.pending_requests.push(Pending::Status(sender));
708                return deleg;
709            }
710
711            sender.send(self.status_peers_with_ids());
712
713            deleg
714        }
715
716        /// Return every known peer's full domain [`Node`] (not the lossy [`StatusNode`]).
717        ///
718        /// Used by [`Runtime::file_targets`](crate::Runtime::file_targets), which needs the full node
719        /// (peerAPI address, owning user id, cap map) to compute Taildrop send targets. The self node
720        /// is not included (it lives in the control runner). Returns empty before the first netmap —
721        /// the natural "not connected yet" analog (an immediate answer, no queueing needed: callers
722        /// that need a populated list await `Running` first).
723        #[message]
724        pub fn all_peers(&self) -> Vec<Node> {
725            self.peer_db.peers().values().cloned().collect()
726        }
727
728        /// Resolve which node owns a tailnet source address.
729        ///
730        /// Maps the source IP of `addr` to the owning node via the tailnet-IP index, returning a
731        /// [`WhoIs`](crate::WhoIs). The port is ignored (a tailnet IP uniquely identifies a node).
732        ///
733        /// The resulting [`WhoIs`](crate::WhoIs) carries no user/login or capability data: this
734        /// fork's domain [`Node`] does not retain those wire fields. See the
735        /// [`status`](crate::status) module docs for the gap.
736        ///
737        /// Waits until we've received at least one peer update from control.
738        #[message(ctx)]
739        pub fn whois(
740            &mut self,
741            ctx: &mut Context<Self, DelegatedReply<Option<crate::status::WhoIs>>>,
742            addr: std::net::SocketAddr,
743        ) -> DelegatedReply<Option<crate::status::WhoIs>> {
744            let (deleg, sender) = ctx.reply_sender();
745            let Some(sender) = sender else { return deleg };
746
747            if !self.seen_state_update {
748                tracing::debug!(query = %addr, "no peer state seen yet, queueing whois request");
749                self.pending_requests
750                    .push(Pending::WhoIs(Whois { addr }, sender));
751                return deleg;
752            }
753
754            sender.send(self.whois_opt(addr));
755
756            deleg
757        }
758
759        /// Subscribe to netmap peer-change events.
760        ///
761        /// Returns a [`watch::Receiver`] whose value is the current set of peer
762        /// [`StatusNode`]s, updated on every netmap state update from control. Embedders can await
763        /// changes via [`watch::Receiver::changed`] to react to peers joining, leaving, or changing.
764        ///
765        /// The receiver's initial value is the peer set at subscription time (empty before the
766        /// first netmap update). This is a peer-only view; combine with the self node from
767        /// [`Runtime::status`](crate::Runtime::status) when a full snapshot is needed.
768        #[message(derive(Clone))]
769        pub fn watch_netmap(&self) -> watch::Receiver<Vec<StatusNode>> {
770            self.peer_watch.subscribe()
771        }
772    }
773}
774
775pub use msg_impl::*;
776
777#[derive(Debug, Clone)]
778pub(crate) struct PeerState {
779    #[allow(unused)]
780    pub deletions: HashSet<PeerId>,
781    #[allow(unused)]
782    pub upserts: HashSet<PeerId>,
783    pub peers: Arc<PeerDb>,
784}
785
786impl Message<Arc<ts_control::StateUpdate>> for PeerTracker {
787    type Reply = ();
788
789    async fn handle(
790        &mut self,
791        msg: Arc<ts_control::StateUpdate>,
792        _ctx: &mut Context<Self, Self::Reply>,
793    ) {
794        // Accumulate user profiles first — control sends them incrementally and a response may
795        // carry profiles with no peer delta (or peers that reference a profile from an earlier
796        // response), so this must happen before the no-peer-update early return below.
797        for profile in &msg.user_profiles {
798            self.user_profiles.insert(profile.id, profile.clone());
799        }
800
801        // Apply the standalone online/last-seen delta maps (channels C/D, `MapResponse.OnlineChange`
802        // / `PeerSeenChange`). These arrive keyed by control node id and may ride a response that
803        // carries NO `peer_update` (a bare online flip is the common case), so they must be applied
804        // *before* the no-peer-update early return — otherwise online status freezes at the last
805        // full-node/patch value. Each entry only ever *sets* a value (never back to unknown).
806        // Wall clock for a `PeerSeenChange: true` (Go uses `clock.Now()`). chrono is built without
807        // its `clock` feature in this workspace, so derive it from `SystemTime` the same way the
808        // control runner / ssh-policy paths do (unix secs → `DateTime::from_timestamp`).
809        let now = std::time::SystemTime::now()
810            .duration_since(std::time::UNIX_EPOCH)
811            .ok()
812            .and_then(|d| chrono::DateTime::from_timestamp(d.as_secs() as i64, d.subsec_nanos()))
813            .unwrap_or_default();
814        let liveness_changed =
815            self.apply_liveness_changes(&msg.online_change, &msg.peer_seen_change, now);
816
817        if msg.peer_update.is_none() && msg.peer_patches.is_empty() {
818            // No peer set or patch this response. If a liveness delta still mutated the netmap,
819            // publish the refreshed snapshot so watchers (and `GetStatus`) see the new online state.
820            if liveness_changed {
821                self.service_pending_requests();
822                self.peer_watch.send_replace(self.status_peers());
823                if let Err(e) = self
824                    .env
825                    .publish(Arc::new(PeerState {
826                        upserts: HashSet::default(),
827                        deletions: HashSet::default(),
828                        peers: Arc::new(self.peer_db.clone()),
829                    }))
830                    .await
831                {
832                    tracing::error!(error = %e, "publishing liveness-only peer state update");
833                }
834            }
835            return;
836        }
837
838        // Apply the whole-node peer set (if any) FIRST, then the field-level patches on top —
839        // mirroring Go's `controlclient` order (`Peers*` then `PeersChangedPatch`). A response may
840        // carry either, both, or (with a liveness-only delta) neither. Merge the upsert/deletion sets
841        // so the published `PeerState` reflects every node touched by both passes; a node both
842        // upserted by the set and patched stays in `upserts` (the patch removes it from `deletions`).
843        let (mut upserts, mut deletions) = msg
844            .peer_update
845            .as_ref()
846            .map(|u| self.apply_peer_update(u))
847            .unwrap_or_default();
848
849        if !msg.peer_patches.is_empty() {
850            let (patch_upserts, patch_deletions) = self.apply_peer_patches(&msg.peer_patches);
851            // A patch can evict a node the set just upserted (TKA rejection after key rotation), or
852            // re-admit/patch one not in the set — reconcile so each id lands in exactly one set.
853            for id in &patch_upserts {
854                deletions.remove(id);
855            }
856            for id in &patch_deletions {
857                upserts.remove(id);
858            }
859            upserts.extend(patch_upserts);
860            deletions.extend(patch_deletions);
861        }
862
863        tracing::debug!(
864            n_upsert = upserts.len(),
865            n_delete = deletions.len(),
866            peer_count = self.peer_db.peers().len(),
867            "new peer state"
868        );
869
870        self.service_pending_requests();
871
872        // Publish the latest peer snapshot to netmap watchers. `send_replace` keeps the receiver's
873        // value current even when there are no subscribers, so a late subscriber sees fresh state.
874        self.peer_watch.send_replace(self.status_peers());
875
876        if let Err(e) = self
877            .env
878            .publish(Arc::new(PeerState {
879                upserts,
880                deletions,
881                peers: Arc::new(self.peer_db.clone()),
882            }))
883            .await
884        {
885            tracing::error!(error = %e, "publishing peer state update");
886        }
887    }
888}
889
890impl Message<PeerDiscoKeyAdvertisement> for PeerTracker {
891    type Reply = ();
892
893    async fn handle(
894        &mut self,
895        msg: PeerDiscoKeyAdvertisement,
896        _ctx: &mut Context<Self, Self::Reply>,
897    ) {
898        if !self.learn_disco_key(msg.peer, msg.key) {
899            return;
900        }
901
902        // The key changed, so republish: the direct-path machinery resolves a peer's disco key out
903        // of the published `PeerState` snapshot (`direct::DiscoPeerLookup`), which is the whole
904        // point of learning it — it is what lets disco reach this peer without waiting for a
905        // netmap update. Go does the equivalent by writing the key straight into the magicsock
906        // endpoint and re-keying its peer map.
907        self.peer_watch.send_replace(self.status_peers());
908
909        if let Err(e) = self
910            .env
911            .publish(Arc::new(PeerState {
912                upserts: HashSet::from_iter([msg.peer]),
913                deletions: HashSet::default(),
914                peers: Arc::new(self.peer_db.clone()),
915            }))
916            .await
917        {
918            tracing::error!(error = %e, "publishing peer state after a TSMP disco-key advertisement");
919        }
920    }
921}
922
923impl Message<DiscoKeyObserved> for PeerTracker {
924    type Reply = ();
925
926    async fn handle(&mut self, msg: DiscoKeyObserved, _ctx: &mut Context<Self, Self::Reply>) {
927        if !self.observe_disco_key(msg.peer, msg.key) {
928            return;
929        }
930
931        // The active key moved, so republish. This is the *same* channel a TSMP advertisement and a
932        // netmap disco-key change use, and it is what makes the direct manager invalidate the
933        // trusted path built under the old key: it diffs consecutive snapshots
934        // (`direct::disco_key_rotations`) and calls `MagicSock::changed_active_disco` — this fork's
935        // `endpoint.changedActiveDiscoLocked`, which Go likewise reaches from
936        // `checkAndUpdateDiscoKey`. Keeping the switch and the invalidation on one path is why the
937        // switch is done here rather than on the packet path that spotted it.
938        self.peer_watch.send_replace(self.status_peers());
939
940        if let Err(e) = self
941            .env
942            .publish(Arc::new(PeerState {
943                upserts: HashSet::from_iter([msg.peer]),
944                deletions: HashSet::default(),
945                peers: Arc::new(self.peer_db.clone()),
946            }))
947            .await
948        {
949            tracing::error!(error = %e, "publishing peer state after a disco active-key switch");
950        }
951    }
952}
953
954/// Internal self-message: the Tailnet-Lock enforcement-authority cell changed — the control runner
955/// installed a freshly-synced [`Authority`](ts_tka::Authority) after a `/machine/tka/sync`, or
956/// cleared it because the lock was disabled. Sent by the watch task
957/// [`on_start`](kameo::Actor::on_start) spawns, so the peer db is re-filtered the moment enforcement
958/// changes instead of at whatever later `Full` netmap happens to arrive.
959#[derive(Debug, Clone, Copy)]
960pub(crate) struct TkaAuthorityChanged;
961
962impl Message<TkaAuthorityChanged> for PeerTracker {
963    type Reply = ();
964
965    async fn handle(&mut self, _msg: TkaAuthorityChanged, _ctx: &mut Context<Self, Self::Reply>) {
966        let deletions = self.tka_reevaluate_peer_db();
967        if deletions.is_empty() {
968            // The common case: enforcement is inactive, or every admitted peer still verifies.
969            return;
970        }
971
972        // An evicted peer must lose its data path, not just its db row, so republish the snapshot
973        // the `Arc<PeerState>` subscribers (route updater, source filter, dataplane) resolve
974        // against — the same publish the netmap handler does after a peer set changes.
975        self.peer_watch.send_replace(self.status_peers());
976
977        if let Err(e) = self
978            .env
979            .publish(Arc::new(PeerState {
980                upserts: HashSet::default(),
981                deletions,
982                peers: Arc::new(self.peer_db.clone()),
983            }))
984            .await
985        {
986            tracing::error!(error = %e, "publishing peer state after a TKA authority change");
987        }
988    }
989}
990
991/// Ask the peer tracker to re-broadcast its current peer snapshot on the bus, without any peer
992/// change. Sent after a runtime preference change so the route updater and source filter (both
993/// `Arc<PeerState>` subscribers) re-resolve against the new value immediately, rather than waiting
994/// for the next netmap update: `Device::set_exit_node` (new exit-node selector) and
995/// `Device::set_accept_routes` (new accept-routes flag) both send it.
996#[derive(Debug, Clone, Copy)]
997pub struct RepublishState;
998
999impl Message<RepublishState> for PeerTracker {
1000    type Reply = ();
1001
1002    async fn handle(&mut self, _msg: RepublishState, _ctx: &mut Context<Self, Self::Reply>) {
1003        // An empty upsert/deletion set: this is a re-broadcast of the unchanged peer set, not a
1004        // delta. Subscribers recompute their routes/filters against the current peers and the
1005        // (just-updated) runtime preferences (exit-node selector, accept-routes flag).
1006        if let Err(e) = self
1007            .env
1008            .publish(Arc::new(PeerState {
1009                upserts: HashSet::default(),
1010                deletions: HashSet::default(),
1011                peers: Arc::new(self.peer_db.clone()),
1012            }))
1013            .await
1014        {
1015            tracing::error!(error = %e, "re-publishing peer state after a runtime preference change");
1016        }
1017    }
1018}
1019
1020impl PeerTracker {
1021    /// Learn a peer's disco key from a TSMP disco-key advertisement, returning whether the
1022    /// advertisement was applied.
1023    ///
1024    /// Go [`magicsock.Conn.HandleDiscoKeyAdvertisement`], reduced to the state this fork keeps:
1025    /// Go stores the learned key on the magicsock endpoint and re-keys its peer map, whereas here
1026    /// the peer db's `disco_key` (and its disco index) *is* the live lookup every direct-path
1027    /// consumer reads. The key is recorded in the peer's [`EndpointDisco`] TSMP slot — never on top
1028    /// of control's — and the peer db then carries whichever of the two is active, so the next
1029    /// netmap cannot silently undo it ([`upsert_from_control`](Self::upsert_from_control)).
1030    ///
1031    /// The three refusals are Go's, in Go's order:
1032    ///
1033    /// 1. **A zero key is never learned.** Go checks it twice — `tstun` publishes only
1034    ///    `if !Key.IsZero()`, and `HandleDiscoKeyAdvertisement` rejects it again. The dataplane
1035    ///    already dropped it here too; this is the second check, kept because the cost of getting
1036    ///    it wrong is a peer bound to an unusable key.
1037    /// 2. **An unknown peer is ignored** (Go: "endpoint not found for node"). An advertisement
1038    ///    never creates a peer — only control does — so one that arrives before or after the
1039    ///    peer's netmap entry is a no-op, exactly like a `PeersChangedPatch` for an unknown node.
1040    /// 3. **An unchanged key is a no-op**, so a peer re-advertising the key we already hold costs
1041    ///    no upsert and no republish (Go counts this as
1042    ///    `magicsock_tsmp_disco_key_advertisement_unchanged` and returns). "Unchanged" is measured
1043    ///    against the **TSMP-learned** key (Go compares `epDisco.keyFromTSMP()`), NOT against the
1044    ///    effective one: an advertisement that merely restates what control already told us is new
1045    ///    information — it is the peer itself confirming the key — so it is recorded as the active
1046    ///    TSMP key and survives control later dropping or contradicting it.
1047    ///
1048    /// The tailnet-lock gate is deliberately *not* re-run: unlike a `PeersChangedPatch`, an
1049    /// advertisement cannot touch the node key or its TKA signature — only the disco key — so the
1050    /// peer-trust decision that admitted this node is unchanged by definition.
1051    ///
1052    /// [`magicsock.Conn.HandleDiscoKeyAdvertisement`]: https://github.com/tailscale/tailscale/blob/49e148c4a30b4f8098f69468fd27a7021d85ea02/wgengine/magicsock/magicsock.go
1053    fn learn_disco_key(&mut self, peer: PeerId, key: DiscoPublicKey) -> bool {
1054        if disco_key_is_zero(&key) {
1055            tracing::debug!(?peer, "TSMP-advertised disco key is the zero key; ignoring");
1056            return false;
1057        }
1058
1059        let Some((_id, existing)) = self.peer_db.get(&peer) else {
1060            tracing::debug!(
1061                ?peer,
1062                "TSMP disco-key advertisement for unknown peer; ignoring"
1063            );
1064            return false;
1065        };
1066
1067        let node_key = existing.node_key;
1068        if self
1069            .endpoint_disco
1070            .get(&node_key)
1071            .and_then(EndpointDisco::key_from_tsmp)
1072            == Some(key)
1073        {
1074            tracing::trace!(?peer, "TSMP-advertised disco key is unchanged");
1075            return false;
1076        }
1077
1078        let node = existing.clone();
1079        let disco = self.endpoint_disco.entry(node_key).or_default();
1080        disco.update_from_tsmp(Some(key));
1081        let disco = *disco;
1082        self.store_disco(&node, disco);
1083
1084        tracing::info!(
1085            ?peer,
1086            stable_id = ?node.stable_id,
1087            %key,
1088            "learned peer disco key from a TSMP advertisement"
1089        );
1090
1091        true
1092    }
1093
1094    /// Write a peer's resolved disco state onto the peer db.
1095    ///
1096    /// The node lands carrying the **effective** key ([`EndpointDisco::key`]), which is what the
1097    /// disco index — and so every *send* path — resolves against, and the peer's other known key
1098    /// (if any) is registered as its inactive ingress key so a frame arriving under it still
1099    /// attributes to this peer ([`PeerDb::peer_by_known_disco_key`]).
1100    ///
1101    /// Every disco-key writer goes through here — control, a TSMP advertisement, and an
1102    /// active-slot switch on receive — so the two cannot drift apart on which key is which.
1103    fn store_disco(&mut self, node: &Node, disco: EndpointDisco) -> PeerId {
1104        let effective = disco.key();
1105
1106        let id = if effective == node.disco_key {
1107            self.peer_db.upsert(node)
1108        } else {
1109            let mut node = node.clone();
1110            node.disco_key = effective;
1111            self.peer_db.upsert(&node)
1112        };
1113
1114        self.peer_db
1115            .set_inactive_disco_key(id, disco.inactive_key());
1116
1117        id
1118    }
1119
1120    /// Apply the sender key of an inbound disco frame to this peer's two-slot disco state — the
1121    /// `ts_runtime` half of Go [`endpoint.checkAndUpdateDiscoKey`].
1122    ///
1123    /// A peer mid-rotation keeps sending disco under the key it has not yet switched away from.
1124    /// Upstream accepts either of the two keys it knows for the peer and, when the one received is
1125    /// the currently-inactive one, makes it active: receiving under a key is proof of what the peer
1126    /// is using, and is stronger evidence than what control last said. Without this a rotation
1127    /// costs the peer its direct path until control catches up or the peer re-advertises.
1128    ///
1129    /// Returns whether the active key changed, so the caller can republish — which is how the
1130    /// direct manager learns to invalidate the trusted path built under the old key (Go's
1131    /// `changedActiveDiscoLocked`, reached here through the same snapshot diff every other
1132    /// disco-key transition uses).
1133    ///
1134    /// The refusals, all of which leave the peer db untouched:
1135    ///
1136    /// 1. **An unknown peer**, exactly as for a TSMP advertisement.
1137    /// 2. **A peer with no disco key material at all** (Go: `epDisco == nil` ⇒ `false`).
1138    /// 3. **A key belonging to neither slot.** This is the one that carries the security value:
1139    ///    a peer must not be able to move itself onto a key nobody told us about, so a third key
1140    ///    is refused even though the frame that carried it opened correctly.
1141    ///
1142    /// [`endpoint.checkAndUpdateDiscoKey`]: https://github.com/tailscale/tailscale/blob/9ea7cba44591e0cd840c6c94d23274dd222059bf/wgengine/magicsock/endpoint.go
1143    fn observe_disco_key(&mut self, peer: PeerId, key: DiscoPublicKey) -> bool {
1144        let Some((_id, existing)) = self.peer_db.get(&peer) else {
1145            tracing::debug!(?peer, "disco received for an unknown peer; ignoring");
1146            return false;
1147        };
1148
1149        let node = existing.clone();
1150        let Some(disco) = self.endpoint_disco.get_mut(&node.node_key) else {
1151            // Go's `epDisco == nil`: the peer has no key from either source, so there is nothing
1152            // this key could match and nothing to switch to.
1153            tracing::debug!(
1154                ?peer,
1155                "disco received for a peer with no known disco key; ignoring"
1156            );
1157            return false;
1158        };
1159
1160        let Some(changed) = disco.check_and_update(key) else {
1161            tracing::debug!(
1162                ?peer,
1163                %key,
1164                "refusing disco under a key that is neither of the peer's known disco keys"
1165            );
1166            return false;
1167        };
1168
1169        if !changed {
1170            return false;
1171        }
1172
1173        let disco = *disco;
1174        self.store_disco(&node, disco);
1175
1176        tracing::info!(
1177            ?peer,
1178            stable_id = ?node.stable_id,
1179            %key,
1180            "peer is sending disco under its other known key; making that key active"
1181        );
1182
1183        true
1184    }
1185
1186    /// Upsert a control-sourced [`Node`] into the peer db, resolving its disco key against anything
1187    /// this peer has told us over TSMP first.
1188    ///
1189    /// Every node built from control goes through here — `Full`, `Delta { upsert }`, and a
1190    /// `PeersChangedPatch` — so the three cannot diverge on which of the two keys wins. This is the
1191    /// disco half of Go [`endpoint.updateFromNode`]: control's key is written through
1192    /// [`EndpointDisco::update_from_control`] **only when it differs from what control last said**
1193    /// (Go's `if discoKey != n.DiscoKey()` guard, which compares `keyFromControl()`, never the
1194    /// effective key). So a netmap that merely restates the key control already sent leaves an
1195    /// active TSMP key alone — which is the entire point of the advertisement, whose motivating case
1196    /// is a peer whose key control has not caught up with. Control genuinely changing its mind is
1197    /// *recorded* in control's slot, but it does not take the active slot back from a TSMP-learned
1198    /// key: upstream switches back only when disco is received under control's key
1199    /// (`endpoint.checkAndUpdateDiscoKey`). See [`EndpointDisco::update_from_control`].
1200    ///
1201    /// The node lands in the db carrying the *effective* key ([`EndpointDisco::key`]), so the disco
1202    /// index and every send path resolve against the key we would actually send to; the other known
1203    /// key is registered for ingress attribution ([`store_disco`](Self::store_disco)).
1204    ///
1205    /// [`endpoint.updateFromNode`]: https://github.com/tailscale/tailscale/blob/49e148c4a30b4f8098f69468fd27a7021d85ea02/wgengine/magicsock/endpoint.go
1206    fn upsert_from_control(&mut self, node: &Node) -> PeerId {
1207        let node_key = node.node_key;
1208        let from_control = disco_key_from_control(node.disco_key);
1209
1210        let disco = self.endpoint_disco.entry(node_key).or_default();
1211        if disco.key_from_control() != from_control {
1212            disco.update_from_control(from_control);
1213        }
1214        let disco = *disco;
1215
1216        // No key material from either source: Go nils the endpoint's `disco` pointer, so a peer
1217        // that has never had a disco key costs us no entry either.
1218        if disco.is_empty() {
1219            self.endpoint_disco.remove(&node_key);
1220        }
1221
1222        self.store_disco(node, disco)
1223    }
1224
1225    /// The disco key control last gave us for `node_key` — Go `endpointDisco.keyFromControl()`.
1226    fn control_disco_key(&self, node_key: &NodePublicKey) -> Option<DiscoPublicKey> {
1227        self.endpoint_disco
1228            .get(node_key)
1229            .and_then(EndpointDisco::key_from_control)
1230    }
1231
1232    /// Drop [`EndpointDisco`] state for node keys the peer db no longer holds.
1233    ///
1234    /// Go gets this for free: the two keys live on the magicsock `endpoint`, which the peer map keys
1235    /// by node key and deletes when the peer leaves the netmap — and a peer that rotates its node
1236    /// key gets a brand-new endpoint, so a TSMP-learned key is not carried across a rotation. Here
1237    /// the state is a side table, so every control update prunes it to get the same lifetime.
1238    fn prune_endpoint_disco(&mut self) {
1239        if self.endpoint_disco.is_empty() {
1240            return;
1241        }
1242
1243        let peers = &self.peer_db;
1244        self.endpoint_disco
1245            .retain(|node_key, _| peers.has(node_key).is_some());
1246    }
1247
1248    /// Apply a single [`PeerUpdate`](ts_control::PeerUpdate) to the peer db, enforcing the
1249    /// Tailnet-Lock peer-trust chokepoint ([`tka_admits`](Self::tka_admits)) at every upsert site.
1250    ///
1251    /// This is the **single source of truth** for the peer-trust enforcement loop: the actor's
1252    /// netmap [`handle`](Message::handle) calls it, and so do the TKA enforcement tests, so the two
1253    /// real upsert sites (`Full` and `Delta { upsert }`) cannot diverge from what is tested.
1254    ///
1255    /// Returns `(upserts, deletions)` — the [`PeerId`]s touched — for downstream bookkeeping.
1256    fn apply_peer_update(
1257        &mut self,
1258        peer_update: &ts_control::PeerUpdate,
1259    ) -> (HashSet<PeerId>, HashSet<PeerId>) {
1260        let mut upserts = HashSet::default();
1261        let mut deletions = HashSet::default();
1262
1263        match peer_update {
1264            ts_control::PeerUpdate::Full(new_nodes) => {
1265                tracing::trace!("full peer update");
1266
1267                // Borrow the authority ONCE for the whole batch and verify each peer EXACTLY once
1268                // (Go runs `tkaFilterNetmapLocked` once over the assembled netmap; an earlier draft
1269                // verified every peer twice — once for `retained_ids`, once in the upsert loop —
1270                // doubling the ed25519 cost on the hot resync path). `tka_keep_verdicts` is that one
1271                // pass — per-peer signature verdict AND the cross-peer rotation filter — and is
1272                // shared verbatim with `tka_reevaluate_peer_db`, so the netmap path and the
1273                // authority-install path cannot drift apart on what "admitted" means.
1274                //
1275                // The result is a per-NODE keep vector (not a stable_id set), which drives both the
1276                // `retain` (evict revoked peers, keyed by stable_id) and the upsert loop. Judging
1277                // each node by its own verdict means a node whose signature fails is never admitted
1278                // on the strength of a different node that happens to share its stable_id.
1279                //
1280                // Revocation evicts: a peer re-included with a now-invalid/missing signature under an
1281                // active authority fails its verdict, so it is excluded from `retained_ids` and
1282                // `retain` drops the stale (previously-admitted) entry. With no authority the snapshot
1283                // is `None`, so every node passes — byte-for-byte the pre-TKA behavior (no regression).
1284                let authority = self.tka_authority_snapshot();
1285                let node_refs = new_nodes.iter().collect::<Vec<&Node>>();
1286                let keep = Self::tka_keep_verdicts(authority.as_deref(), &node_refs);
1287
1288                // `retained_ids` is the set of stable_ids that survive (drives `retain` to evict the
1289                // rest). It must agree with what the upsert loop below will leave in the db. Control
1290                // should never send two distinct nodes with the same `stable_id` in one `Full`, but if
1291                // it does, `peer_db.upsert` is last-writer-wins on `stable_id`, so the db ends holding
1292                // the LAST kept node for that id. Build `retained_ids` from kept nodes only — a
1293                // stable_id is retained iff at least one of its (possibly duplicate) nodes is kept, so
1294                // the upsert loop's last-kept node lands and `retain` never evicts a just-upserted id.
1295                let retained_ids = new_nodes
1296                    .iter()
1297                    .zip(keep.iter().copied())
1298                    .filter(|(_, k)| *k)
1299                    .map(|(node, _)| &node.stable_id)
1300                    .collect::<HashSet<_>>();
1301
1302                // Isolation diagnostic: an ACTIVE lock that authorized none of the offered peers
1303                // leaves this node with no peers — surface it loudly so a self-lockout (vs an attack)
1304                // is diagnosable. `authority.is_some()` means a real keyed lock (the empty-keyset
1305                // brick-guard admits-all, so it never reaches here with zero retained).
1306                if authority.is_some() && !new_nodes.is_empty() && retained_ids.is_empty() {
1307                    tracing::error!(
1308                        offered = new_nodes.len(),
1309                        "TKA: active lock authorized ZERO of the offered peers; node is isolated \
1310                         (verify the lock state, or disable tailnet lock to recover)"
1311                    );
1312                }
1313
1314                self.peer_db.retain(|id, peer| {
1315                    let retain = retained_ids.contains(&peer.stable_id);
1316
1317                    if !retain {
1318                        deletions.insert(id);
1319                    }
1320
1321                    retain
1322                });
1323
1324                for (node, k) in new_nodes.iter().zip(keep.iter().copied()) {
1325                    if !k {
1326                        continue; // fail-CLOSED: rejected by tailnet lock or rotation-obsolete (above)
1327                    }
1328                    let peer_id = self.upsert_from_control(node);
1329                    upserts.insert(peer_id);
1330                }
1331            }
1332
1333            ts_control::PeerUpdate::Delta { remove, upsert } => {
1334                tracing::trace!("delta peer update");
1335
1336                for peer in upsert {
1337                    if !self.tka_admits(peer) {
1338                        // fail-CLOSED: do not upsert a peer rejected by tailnet lock. If the peer is
1339                        // ALREADY in the db (a delta re-upserting an existing peer whose signature is
1340                        // now invalid — e.g. revoked between syncs), evict the stale entry rather than
1341                        // leaving an unverified peer admitted; Go re-filters the whole netmap each map
1342                        // response, so a now-unsigned peer would not survive there either.
1343                        if let Some((id, _)) = self.peer_db.remove(&peer.stable_id) {
1344                            tracing::warn!(
1345                                stable_id = ?peer.stable_id,
1346                                "TKA: delta re-upsert rejected; evicting now-unauthorized peer"
1347                            );
1348                            deletions.insert(id);
1349                        }
1350                        continue;
1351                    }
1352                    let id = self.upsert_from_control(peer);
1353
1354                    upserts.insert(id);
1355                }
1356
1357                for peer in remove {
1358                    let Some((id, _node)) = self.peer_db.remove(peer) else {
1359                        // A benign, expected race: the peer may already be gone (dropped in a prior
1360                        // `Full`, or fail-closed by TKA — whose now-"unknown" ids commonly reappear in
1361                        // a trailing `peers_removed`). Go treats an unknown removal as a no-op; log at
1362                        // debug, not error, to avoid false-alarm noise on a healthy node (matches the
1363                        // unknown-node handling in `apply_peer_patches`).
1364                        tracing::debug!(
1365                            control_node_id = peer,
1366                            "removed peer was unknown; ignoring"
1367                        );
1368                        continue;
1369                    };
1370
1371                    deletions.insert(id);
1372                }
1373            }
1374        }
1375
1376        self.prune_endpoint_disco();
1377
1378        (upserts, deletions)
1379    }
1380
1381    /// Re-run the Tailnet-Lock filter over the peers **already in the peer db**, evicting the ones
1382    /// the current authority does not admit. Returns the evicted [`PeerId`]s (empty when nothing
1383    /// changed, which is the overwhelmingly common case).
1384    ///
1385    /// # Why this exists (a Go-ordering gap, not an extra feature)
1386    /// Go filters the very netmap that announced the lock: `SetControlClientStatus`
1387    /// (`ipn/ipnlocal/local.go`, v1.100.0) calls `tkaSyncIfNeeded` and then, a few lines later,
1388    /// `tkaFilterNetmapLocked(st.NetMap)` — synchronously, on the same `st.NetMap`, in one pass. So
1389    /// the peers announced alongside `TKAEnabled` are checked by the authority that sync just built.
1390    ///
1391    /// Here the sync is a spawned task (`control_runner`'s `maybe_sync_tka`), so the ordering is
1392    /// inverted: the netmap that carried the `TkaStatus` reaches the peer db *before* the authority
1393    /// exists, and is admitted with enforcement inactive. Without this pass those peers stay
1394    /// admitted — unauthorized ones included — until control happens to send another `Full`, which on
1395    /// a steady map poll may be never. That is the whole initial peer set escaping a lock the node
1396    /// really did sync, so this runs the moment the authority is installed ([`TkaAuthorityChanged`])
1397    /// and brings the db back in line.
1398    ///
1399    /// No authority (nothing synced yet, or the lock was disabled) ⇒ no eviction: enforcement is
1400    /// inactive and every peer is admitted, exactly Go's `b.tka == nil` early return. A peer dropped
1401    /// while the lock was active is **not** resurrected by a later disable — the db no longer holds
1402    /// it and this fork keeps no shadow copy of filtered nodes (Go's `b.tka.filtered`); it returns on
1403    /// the next netmap that re-includes it. That is the safe direction: more restrictive, and
1404    /// connectivity-only.
1405    fn tka_reevaluate_peer_db(&mut self) -> HashSet<PeerId> {
1406        let Some(authority) = self.tka_authority_snapshot() else {
1407            return HashSet::default();
1408        };
1409
1410        // Verdicts first, under an immutable borrow of the db; the eviction below needs `&mut`.
1411        let evicted: HashSet<PeerId> = {
1412            let entries = self
1413                .peer_db
1414                .peers()
1415                .iter()
1416                .map(|(id, node)| (*id, node))
1417                .collect::<Vec<(PeerId, &Node)>>();
1418            let nodes = entries
1419                .iter()
1420                .map(|(_, node)| *node)
1421                .collect::<Vec<&Node>>();
1422            let keep = Self::tka_keep_verdicts(Some(&authority), &nodes);
1423            entries
1424                .iter()
1425                .zip(keep)
1426                .filter_map(|((id, _), keep)| (!keep).then_some(*id))
1427                .collect()
1428        };
1429
1430        if evicted.is_empty() {
1431            return evicted;
1432        }
1433
1434        tracing::warn!(
1435            n_evicted = evicted.len(),
1436            peer_count = self.peer_db.peers().len(),
1437            "TKA: re-filtered the peer db against the newly installed lock authority; evicted \
1438             already-admitted peers"
1439        );
1440        self.peer_db.retain(|id, _| !evicted.contains(&id));
1441        self.prune_endpoint_disco();
1442        evicted
1443    }
1444
1445    /// Apply field-level peer patches (`MapResponse.PeersChangedPatch`), returning the upserted /
1446    /// deleted [`PeerId`]s.
1447    ///
1448    /// This is a SEPARATE channel from [`apply_peer_update`](Self::apply_peer_update): Go's
1449    /// `controlclient` applies the whole-node `Peers*` set first and then `PeersChangedPatch`, so a
1450    /// response that carries both has the peer set applied first (by the caller) and these patches
1451    /// applied second, on top of the freshly-synced nodes. A patch only mutates a peer already in the
1452    /// netmap; an unknown node id is ignored (the wire contract — a patch never creates a node).
1453    fn apply_peer_patches(
1454        &mut self,
1455        patches: &[ts_control::PeerChange],
1456    ) -> (HashSet<PeerId>, HashSet<PeerId>) {
1457        let mut upserts = HashSet::default();
1458        let mut deletions = HashSet::default();
1459
1460        tracing::trace!(n = patches.len(), "peer patch update");
1461
1462        for patch in patches {
1463            // Clone the current node, apply the present fields, and re-upsert through the same path
1464            // as a delta so indexes/routes stay consistent.
1465            let Some((_id, existing)) = self.peer_db.get(&patch.id) else {
1466                tracing::debug!(
1467                    control_node_id = patch.id,
1468                    "peer patch for unknown node; ignoring"
1469                );
1470                continue;
1471            };
1472
1473            let mut node = existing.clone();
1474            if let Some(endpoints) = &patch.underlay_addresses {
1475                node.underlay_addresses = endpoints.clone();
1476            }
1477            if let Some(derp) = patch.derp_region {
1478                node.derp_region = Some(derp);
1479            }
1480            if let Some(cap) = patch.cap {
1481                node.cap = cap;
1482            }
1483            if let Some(cap_map) = &patch.cap_map {
1484                node.cap_map = cap_map.clone();
1485            }
1486            // The db entry carries the EFFECTIVE disco key, which may have been learned over TSMP,
1487            // so restate what CONTROL last said before folding the patch in. Otherwise a patch that
1488            // says nothing about the disco key would hand a TSMP-learned key back as if control had
1489            // sent it, and `upsert_from_control` would write it into control's slot — losing the key
1490            // control actually gave us, on a patch that never mentioned the disco key at all.
1491            node.disco_key = self.control_disco_key(&node.node_key);
1492            if let Some(disco_key) = patch.disco_key {
1493                node.disco_key = Some(disco_key);
1494            }
1495            if let Some(expiry) = patch.node_key_expiry {
1496                node.node_key_expiry = Some(expiry);
1497            }
1498            // Online/last-seen liveness deltas (`PeerChange.Online`/`LastSeen`) — the dominant
1499            // channel by which peer online transitions arrive mid-session. A patch only ever *sets*
1500            // a value (never patches back to unknown), so apply when present.
1501            if let Some(online) = patch.online {
1502                node.online = Some(online);
1503            }
1504            if let Some(last_seen) = patch.last_seen {
1505                node.last_seen = Some(last_seen);
1506            }
1507            // Key rotation: a patch may swap the node key (and its TKA signature). Apply both
1508            // together so the trust gate below verifies the new signature against the new key, never
1509            // a mismatched pair.
1510            if let Some(node_key) = patch.node_key {
1511                node.node_key = node_key;
1512            }
1513            if let Some(sig) = &patch.key_signature {
1514                node.key_signature = sig.clone();
1515            }
1516
1517            // Re-run the tailnet-lock gate on the patched node: a patch that rotates the key must
1518            // satisfy the active authority, exactly like a `Delta` upsert, or it would be a
1519            // trust-enforcement bypass. fail-CLOSED — if the patched node is no longer admitted,
1520            // evict it rather than keep the stale (now-unverified) entry.
1521            if !self.tka_admits(&node) {
1522                if let Some((id, _)) = self.peer_db.remove(&patch.id) {
1523                    tracing::warn!(
1524                        control_node_id = patch.id,
1525                        "peer patch rejected by tailnet lock; evicting peer"
1526                    );
1527                    deletions.insert(id);
1528                }
1529                continue;
1530            }
1531
1532            let id = self.upsert_from_control(&node);
1533            upserts.insert(id);
1534        }
1535
1536        self.prune_endpoint_disco();
1537
1538        (upserts, deletions)
1539    }
1540
1541    /// Apply the standalone online/last-seen delta maps (`MapResponse.OnlineChange` /
1542    /// `PeerSeenChange`, channels C/D) onto the retained netmap. Returns `true` if any node was
1543    /// actually mutated (so the caller knows whether to re-publish).
1544    ///
1545    /// Mirrors Go `controlclient/map.go:updatePeersStateFromResponse` (the two channels are
1546    /// semantically DISTINCT and must not be conflated):
1547    /// - `OnlineChange` (channel C) is the sole driver of a peer's `online` flag (`mut.Online = v`).
1548    /// - `PeerSeenChange` (channel D) is the sole driver of `last_seen`: `true ⇒ LastSeen = now`,
1549    ///   `false ⇒ LastSeen = nil` (cleared). It NEVER touches `online` — "not seen recently" is not
1550    ///   the same as "offline", which only `OnlineChange` asserts.
1551    ///
1552    /// Each entry is keyed by control node id and applies to a peer already in the netmap; an unknown
1553    /// node id is ignored (these maps never create a node). `now` is the wall-clock timestamp for a
1554    /// `PeerSeenChange: true` (Go uses `clock.Now()`); the caller passes it so this stays a pure
1555    /// function of its inputs. Returns `true` if any node was actually mutated.
1556    fn apply_liveness_changes(
1557        &mut self,
1558        online_change: &std::collections::BTreeMap<ts_control::NodeId, bool>,
1559        peer_seen_change: &std::collections::BTreeMap<ts_control::NodeId, bool>,
1560        now: chrono::DateTime<chrono::Utc>,
1561    ) -> bool {
1562        let mut changed = false;
1563
1564        // Channel C — direct online flips (the only writer of `online`).
1565        for (&node_id, &online) in online_change {
1566            if let Some((_pid, existing)) = self.peer_db.get(&node_id)
1567                && existing.online != Some(online)
1568            {
1569                let mut node = existing.clone();
1570                node.online = Some(online);
1571                self.peer_db.upsert(&node);
1572                changed = true;
1573            }
1574        }
1575
1576        // Channel D — peer-seen flips (the only writer of `last_seen`; never touches `online`).
1577        // `true` ⇒ last-seen is now; `false` ⇒ last-seen cleared (Go map.go:820-830).
1578        for (&node_id, &seen) in peer_seen_change {
1579            let new_last_seen = if seen { Some(now) } else { None };
1580            if let Some((_pid, existing)) = self.peer_db.get(&node_id)
1581                && existing.last_seen != new_last_seen
1582            {
1583                let mut node = existing.clone();
1584                node.last_seen = new_last_seen;
1585                self.peer_db.upsert(&node);
1586                changed = true;
1587            }
1588        }
1589
1590        changed
1591    }
1592
1593    /// Test-only constructor: build a [`PeerTracker`] with a chosen initial TKA authority without
1594    /// going through the actor `on_start` path. Returns the tracker plus the **`watch::Sender`** for
1595    /// its enforcement-authority cell, so a test can drive the exact enable/disable transitions the
1596    /// control runner drives at runtime (`tx.send_replace(Some(..))` ⇒ enforce, `tx.send_replace(None)`
1597    /// ⇒ clear). The initial `Some` exercises the fail-closed chokepoint
1598    /// ([`tka_admits`](Self::tka_admits)); `None` is the no-lock admit-all path. The returned sender
1599    /// must be kept alive for the tracker to read updated values.
1600    #[cfg(test)]
1601    fn for_test(
1602        env: Env,
1603        tka_authority: Option<ts_tka::Authority>,
1604    ) -> (Self, watch::Sender<Option<Arc<ts_tka::Authority>>>) {
1605        let (peer_watch, _) = watch::channel(Vec::new());
1606        let (tka_tx, tka_rx) = watch::channel(tka_authority.map(Arc::new));
1607        let tracker = Self {
1608            peer_db: PeerDb::default(),
1609            seen_state_update: false,
1610            pending_requests: Vec::new(),
1611            peer_watch,
1612            user_profiles: HashMap::new(),
1613            endpoint_disco: HashMap::new(),
1614            tka_authority: tka_rx,
1615            env,
1616        };
1617        (tracker, tka_tx)
1618    }
1619
1620    fn service_pending_requests(&mut self) {
1621        if self.seen_state_update {
1622            return;
1623        }
1624
1625        self.seen_state_update = true;
1626
1627        if !self.pending_requests.is_empty() {
1628            tracing::debug!(
1629                n_pending = self.pending_requests.len(),
1630                "state update received, servicing pending requests"
1631            );
1632        }
1633
1634        for req in core::mem::take(&mut self.pending_requests) {
1635            match req {
1636                Pending::PeerByName(PeerByName { name }, reply) => {
1637                    reply.send(self.peer_by_name_opt(&name).cloned());
1638                }
1639                Pending::TailnetIp(PeerByTailnetIp { ip }, reply) => {
1640                    reply.send(self.peer_by_tailnet_ip_opt(ip).cloned());
1641                }
1642                Pending::AcceptedRoute(PeerByAcceptedRoute { ip }, reply) => {
1643                    reply.send(
1644                        self.peer_db
1645                            .get_route(ip.into())
1646                            .map(|(_id, node)| node.clone())
1647                            .collect(),
1648                    );
1649                }
1650                Pending::Status(reply) => {
1651                    reply.send(self.status_peers_with_ids());
1652                }
1653                Pending::WhoIs(Whois { addr }, reply) => {
1654                    reply.send(self.whois_opt(addr));
1655                }
1656            }
1657        }
1658    }
1659}
1660
1661#[cfg(test)]
1662mod tka_tests {
1663    //! Tailnet-Lock (TKA) enforcement tests for the peer-trust chokepoint.
1664    //!
1665    //! These exercise [`PeerTracker::tka_admits`] and the `tka_admits ⇒ upsert` loop the netmap
1666    //! handler runs. The test [`ts_tka::Authority`] is built with [`ts_tka::Authority::from_state`]
1667    //! over a known Ed25519 trusted key, and the signed node-key signature CBOR is produced through
1668    //! `ts_tka`'s public `cbor` encoder + `aum_hash` (the exact same canonical bytes `ts_tka`'s own
1669    //! `direct_signature_verifies_end_to_end` test signs, with no new crypto vectors invented and no
1670    //! private `ts_tka` API used).
1671
1672    use ed25519_dalek::{Signer, SigningKey};
1673    use ts_control::{Node, StableNodeId, TailnetAddress};
1674    use ts_tka::{
1675        AumHash, Authority, Key, KeyKind, State,
1676        cbor::{self, Value},
1677    };
1678
1679    use super::*;
1680
1681    /// `SigKind::Direct` wire value (Go `SigKind`; `ts_tka::SigKind::Direct = 1`).
1682    const SIG_KIND_DIRECT: u64 = 1;
1683
1684    /// The 32-byte node key used across the signed-peer fixtures.
1685    const NODE_KEY_BYTES: [u8; 32] = [7u8; 32];
1686
1687    /// Build a real [`Env`] for the tracker. Only the bus/keys/shutdown plumbing matters here; the
1688    /// TKA gate reads neither, so the forwarding preferences are all benign defaults.
1689    pub(super) fn test_env() -> Env {
1690        let (_shutdown_tx, shutdown_rx) = watch::channel(false);
1691        Env::new(
1692            ts_keys::NodeState::generate(),
1693            shutdown_rx,
1694            crate::env::ForwarderConfig {
1695                accept_routes: false,
1696                accept_dns: true,
1697                exit_node: None,
1698                forward_routes: Vec::new(),
1699                forward_tcp_ports: Vec::new(),
1700                forward_udp_ports: Vec::new(),
1701                forward_all_ports: false,
1702                forward_exit_egress: false,
1703                block_incoming: false,
1704                exit_proxy: None,
1705                peerapi_port: None,
1706                taildrop_dir: None,
1707                enable_ipv6: false,
1708                wireguard_listen_port: None,
1709                network_monitor: false,
1710                persistent_keepalive_interval: None,
1711                ingress_active: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
1712            },
1713        )
1714    }
1715
1716    /// A minimal peer [`Node`] carrying `node_key` and the given `key_signature`.
1717    pub(super) fn peer_node(stable_id: &str, node_key: [u8; 32], key_signature: Vec<u8>) -> Node {
1718        Node {
1719            id: 1,
1720            stable_id: StableNodeId(stable_id.to_string()),
1721            hostname: stable_id.to_string(),
1722            user_id: 0,
1723            tailnet: Some("ts.net".to_string()),
1724            tags: Vec::new(),
1725            addresses: vec![
1726                "100.64.0.1/32".parse().unwrap(),
1727                "fd7a:115c:a1e0::1/128".parse().unwrap(),
1728            ],
1729            tailnet_address: TailnetAddress {
1730                ipv4: "100.64.0.1/32".parse().unwrap(),
1731                ipv6: "fd7a:115c:a1e0::1/128".parse().unwrap(),
1732            },
1733            node_key: node_key.into(),
1734            node_key_expiry: None,
1735            online: None,
1736            last_seen: None,
1737            key_signature,
1738            machine_key: None,
1739            disco_key: None,
1740            accepted_routes: Vec::new(),
1741            underlay_addresses: Vec::new(),
1742            derp_region: None,
1743            cap: Default::default(),
1744            cap_map: Default::default(),
1745            peerapi_port: None,
1746            peerapi_dns_proxy: false,
1747            is_wireguard_only: false,
1748            exit_node_dns_resolvers: Vec::new(),
1749            peer_relay: false,
1750            ssh_host_keys: Vec::new(),
1751            service_vips: Default::default(),
1752            unsigned_peer_api_only: false,
1753        }
1754    }
1755
1756    /// Encode a `Direct` [`ts_tka::NodeKeySignature`] CBOR exactly as `ts_tka`'s private `to_cbor`
1757    /// does (int-map keys: 1=kind, 2=pubkey, 3=key_id, 4=signature; empty byte fields omitted),
1758    /// using only the crate's *public* `cbor` encoder. `signature` of `None` produces the
1759    /// signing-digest preimage (the `SigHash` form).
1760    fn direct_sig_cbor(node_key: &[u8], key_id: &[u8], signature: Option<&[u8]>) -> Vec<u8> {
1761        let mut pairs = alloc_pairs(node_key, key_id);
1762        if let Some(sig) = signature {
1763            pairs.push((4, Some(Value::Bytes(sig.to_vec()))));
1764        }
1765        cbor::int_map(pairs).to_vec()
1766    }
1767
1768    fn alloc_pairs(node_key: &[u8], key_id: &[u8]) -> Vec<(u64, Option<Value>)> {
1769        vec![
1770            (1, Some(Value::Uint(SIG_KIND_DIRECT))),
1771            (2, Some(Value::Bytes(node_key.to_vec()))),
1772            (3, Some(Value::Bytes(key_id.to_vec()))),
1773        ]
1774    }
1775
1776    /// Build a TKA [`Authority`] that trusts `signing.verifying_key()`, plus a valid `Direct`
1777    /// node-key signature CBOR authorizing [`NODE_KEY_BYTES`] under it.
1778    fn authority_and_valid_sig() -> (Authority, Vec<u8>) {
1779        // A fixed, known Ed25519 trusted key (mirrors ts_tka's own end-to-end test seed).
1780        let signing = SigningKey::from_bytes(&[42u8; 32]);
1781        let trusted_pub = signing.verifying_key().to_bytes().to_vec();
1782
1783        let authority = Authority::from_state(
1784            AumHash([0; 32]),
1785            State {
1786                keys: vec![Key {
1787                    kind: KeyKind::Ed25519,
1788                    votes: 1,
1789                    public: trusted_pub.clone(),
1790                }],
1791            },
1792        );
1793
1794        // SigHash preimage = canonical CBOR with the signature field omitted; sign its blake2s hash.
1795        let preimage = direct_sig_cbor(&NODE_KEY_BYTES, &trusted_pub, None);
1796        let sig_hash = ts_tka::aum_hash(&preimage).0;
1797        let signature = signing.sign(&sig_hash).to_bytes().to_vec();
1798
1799        let signed_cbor = direct_sig_cbor(&NODE_KEY_BYTES, &trusted_pub, Some(&signature));
1800        // Sanity: the authority accepts the signature we just built (same path the gate uses).
1801        assert!(
1802            authority
1803                .node_key_authorized(&NODE_KEY_BYTES, &signed_cbor)
1804                .is_ok()
1805        );
1806
1807        (authority, signed_cbor)
1808    }
1809
1810    #[tokio::test]
1811    async fn tka_inactive_upserts_all_peers() {
1812        // No authority ⇒ enforcement inactive ⇒ both a signed and an unsigned peer are admitted.
1813        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
1814
1815        let signed = peer_node("signed", [1u8; 32], vec![0xde, 0xad, 0xbe, 0xef]);
1816        let unsigned = peer_node("unsigned", [2u8; 32], vec![]);
1817
1818        assert!(tracker.tka_admits(&signed));
1819        assert!(tracker.tka_admits(&unsigned));
1820
1821        tracker.peer_db.upsert(&signed);
1822        tracker.peer_db.upsert(&unsigned);
1823        assert_eq!(tracker.peer_db.peers().len(), 2);
1824    }
1825
1826    #[tokio::test]
1827    async fn tka_active_rejects_unsigned_peer() {
1828        // Authority present + peer presents no signature ⇒ rejected (fail-closed), not in peer_db.
1829        let (authority, _sig) = authority_and_valid_sig();
1830        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
1831
1832        let unsigned = peer_node("unsigned", NODE_KEY_BYTES, vec![]);
1833        assert!(!tracker.tka_admits(&unsigned));
1834
1835        // Mirror the handler's `if !tka_admits { continue }` loop.
1836        if tracker.tka_admits(&unsigned) {
1837            tracker.peer_db.upsert(&unsigned);
1838        }
1839        assert_eq!(tracker.peer_db.peers().len(), 0);
1840        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
1841    }
1842
1843    #[tokio::test]
1844    async fn tka_active_rejects_unsigned_peer_api_only_peer() {
1845        // `UnsignedPeerAPIOnly` buys NO admission exemption here: Go admits such a peer unsigned
1846        // under an active lock (peerAPI-only, no network access), this fork drops it like any other
1847        // unsigned peer. Pins the documented parity gap (`docs/PARITY_ROADMAP.md`, and the
1848        // `ts_control::Node::unsigned_peer_api_only` field docs) so implementing the carve-out has
1849        // to update the prose that promises no peerAPI access today.
1850        let (authority, _sig) = authority_and_valid_sig();
1851        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
1852
1853        let mut peer_api_only = peer_node("peerapi-only", NODE_KEY_BYTES, vec![]);
1854        peer_api_only.unsigned_peer_api_only = true;
1855
1856        assert!(
1857            !tracker.tka_admits(&peer_api_only),
1858            "unsigned_peer_api_only must not exempt a peer from the tailnet-lock admission gate"
1859        );
1860
1861        // Mirror the handler's `if !tka_admits { continue }` loop: nothing reaches the peer db, so
1862        // the peer is not reachable for peerAPI either.
1863        if tracker.tka_admits(&peer_api_only) {
1864            tracker.peer_db.upsert(&peer_api_only);
1865        }
1866        assert_eq!(tracker.peer_db.peers().len(), 0);
1867        assert!(tracker.peer_db.get(&peer_api_only.node_key).is_none());
1868    }
1869
1870    #[tokio::test]
1871    async fn tka_active_rejects_bad_signature() {
1872        // Authority present + a signature that fails to verify ⇒ rejected, not in peer_db.
1873        let (authority, mut sig) = authority_and_valid_sig();
1874        // Tamper the last byte (the trailing signature byte) so verification fails.
1875        let last = sig.len() - 1;
1876        sig[last] ^= 0xff;
1877
1878        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
1879        let bad = peer_node("bad", NODE_KEY_BYTES, sig);
1880        assert!(!tracker.tka_admits(&bad));
1881
1882        if tracker.tka_admits(&bad) {
1883            tracker.peer_db.upsert(&bad);
1884        }
1885        assert_eq!(tracker.peer_db.peers().len(), 0);
1886    }
1887
1888    #[tokio::test]
1889    async fn tka_active_admits_authorized_peer() {
1890        // Authority present + correctly-signed node key ⇒ admitted and upserted.
1891        let (authority, sig) = authority_and_valid_sig();
1892        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
1893
1894        let good = peer_node("good", NODE_KEY_BYTES, sig);
1895        assert!(tracker.tka_admits(&good));
1896
1897        if tracker.tka_admits(&good) {
1898            tracker.peer_db.upsert(&good);
1899        }
1900        assert_eq!(tracker.peer_db.peers().len(), 1);
1901        assert!(tracker.peer_db.get(&good.node_key).is_some());
1902    }
1903
1904    // ---------------------------------------------------------------------------------------------
1905    // Tests that drive REAL `PeerUpdate`s through the shared handler body
1906    // ([`PeerTracker::apply_peer_update`], the single source of truth the actor's netmap `handle`
1907    // also calls), so the two real upsert sites (`Full` and `Delta { upsert }`) are exercised via
1908    // the actual enforcement path — not by hand-mirroring `if !tka_admits { continue }`.
1909    // ---------------------------------------------------------------------------------------------
1910
1911    #[tokio::test]
1912    async fn tka_active_delta_upsert_rejects_unauthorized() {
1913        // Drive a real `Delta { upsert }` whose peer carries no signature. The Delta upsert site
1914        // must reject it under an active authority ⇒ not present in peer_db after the handler runs.
1915        let (authority, _sig) = authority_and_valid_sig();
1916        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
1917
1918        let unsigned = peer_node("unsigned", NODE_KEY_BYTES, vec![]);
1919        let update = ts_control::PeerUpdate::Delta {
1920            upsert: vec![unsigned.clone()],
1921            remove: Vec::new(),
1922        };
1923
1924        tracker.apply_peer_update(&update);
1925
1926        assert_eq!(tracker.peer_db.peers().len(), 0);
1927        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
1928    }
1929
1930    #[tokio::test]
1931    async fn tka_active_delta_upsert_admits_authorized() {
1932        // Drive a real `Delta { upsert }` with a correctly-signed peer ⇒ present in peer_db.
1933        let (authority, sig) = authority_and_valid_sig();
1934        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
1935
1936        let good = peer_node("good", NODE_KEY_BYTES, sig);
1937        let update = ts_control::PeerUpdate::Delta {
1938            upsert: vec![good.clone()],
1939            remove: Vec::new(),
1940        };
1941
1942        tracker.apply_peer_update(&update);
1943
1944        assert_eq!(tracker.peer_db.peers().len(), 1);
1945        assert!(tracker.peer_db.get(&good.node_key).is_some());
1946    }
1947
1948    #[tokio::test]
1949    async fn tka_active_full_admits_only_authorized_in_mixed_batch() {
1950        // Drive a real `Full` carrying a MIX of authorized + unauthorized peers. Only the
1951        // correctly-signed peer survives the Full upsert site; the unsigned and bad-sig peers are
1952        // dropped fail-closed.
1953        let (authority, sig) = authority_and_valid_sig();
1954        // A bad-sig variant of the same authorized signature (tamper the trailing byte).
1955        let mut bad_sig = sig.clone();
1956        let last = bad_sig.len() - 1;
1957        bad_sig[last] ^= 0xff;
1958
1959        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
1960
1961        // Only the authorized peer carries NODE_KEY_BYTES (the key the authority signed); the
1962        // rejected peers use distinct node keys so the survivor is unambiguous.
1963        let good = peer_node("good", NODE_KEY_BYTES, sig);
1964        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
1965        let bad = peer_node("bad", [9u8; 32], bad_sig);
1966
1967        let update =
1968            ts_control::PeerUpdate::Full(vec![good.clone(), unsigned.clone(), bad.clone()]);
1969
1970        tracker.apply_peer_update(&update);
1971
1972        assert_eq!(tracker.peer_db.peers().len(), 1);
1973        assert!(tracker.peer_db.get(&good.node_key).is_some());
1974        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
1975        assert!(tracker.peer_db.get(&bad.node_key).is_none());
1976    }
1977
1978    /// End-to-end through the REAL enforcement-authority transport (the `watch` cell the control
1979    /// runner writes), not a direct field poke: writing `Some(authority)` flips enforcement on so a
1980    /// mixed batch drops the unsigned/bad peers, and a subsequent `None` (lock disabled) clears
1981    /// enforcement so a peer DROPPED while enforced is re-admitted. Exercises the exact `borrow`-based
1982    /// read path `tka_admits` uses — a broken receiver wiring would pass every for_test-field test but
1983    /// fail here.
1984    #[tokio::test]
1985    async fn tka_authority_watch_enables_then_clears_enforcement() {
1986        let (authority, sig) = authority_and_valid_sig();
1987        let mut bad_sig = sig.clone();
1988        let last = bad_sig.len() - 1;
1989        bad_sig[last] ^= 0xff;
1990
1991        let (mut tracker, tka_tx) = PeerTracker::for_test(test_env(), None);
1992
1993        // 1) No authority yet ⇒ admit-all (Go b.tka == nil).
1994        let good = peer_node("good", NODE_KEY_BYTES, sig.clone());
1995        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
1996        let bad = peer_node("bad", [9u8; 32], bad_sig);
1997        let batch = ts_control::PeerUpdate::Full(vec![good.clone(), unsigned.clone(), bad.clone()]);
1998        tracker.apply_peer_update(&batch);
1999        assert_eq!(tracker.peer_db.peers().len(), 3, "no lock ⇒ admit all");
2000
2001        // 2) Publish the verified authority over the watch cell (exactly what the control runner does
2002        //    on a successful sync) ⇒ enforcement ON. A re-applied Full now drops unsigned + bad.
2003        tka_tx.send_replace(Some(Arc::new(authority)));
2004        tracker.apply_peer_update(&batch);
2005        assert_eq!(
2006            tracker.peer_db.peers().len(),
2007            1,
2008            "lock active ⇒ only the signed peer survives"
2009        );
2010        assert!(tracker.peer_db.get(&good.node_key).is_some());
2011        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
2012        assert!(tracker.peer_db.get(&bad.node_key).is_none());
2013
2014        // 3) Lock disabled (None) ⇒ enforcement cleared ⇒ a peer that was DROPPED while enforced is
2015        //    re-admitted by a fresh netmap. Assert the specific previously-dropped key returns (not
2016        //    merely a count), so this proves the drop→clear→re-admit transition, not "admit-all-fresh".
2017        tka_tx.send_replace(None);
2018        tracker.apply_peer_update(&batch);
2019        assert_eq!(
2020            tracker.peer_db.peers().len(),
2021            3,
2022            "lock disabled ⇒ admit all again"
2023        );
2024        assert!(
2025            tracker.peer_db.get(&unsigned.node_key).is_some(),
2026            "the peer dropped under enforcement must come back once the lock is cleared"
2027        );
2028        assert!(tracker.peer_db.get(&bad.node_key).is_some());
2029    }
2030
2031    /// The ordering gap this closes. A peer admitted BEFORE the lock synced must be re-checked the
2032    /// moment the authority is installed — not left in the db until control happens to send another
2033    /// `Full`. Go never has this problem: `SetControlClientStatus` runs `tkaSyncIfNeeded` and then
2034    /// `tkaFilterNetmapLocked(st.NetMap)` on the SAME netmap in one pass, so the netmap that
2035    /// announced the lock is itself filtered. Here the sync is a spawned task, so the netmap lands
2036    /// first and `tka_reevaluate_peer_db` is what restores Go's ordering.
2037    ///
2038    /// Note this test applies NO second netmap: the eviction must come from the authority install
2039    /// alone, which is exactly what was missing before.
2040    #[tokio::test]
2041    async fn tka_authority_install_reevaluates_already_admitted_peers() {
2042        let (authority, sig) = authority_and_valid_sig();
2043        let mut bad_sig = sig.clone();
2044        let last = bad_sig.len() - 1;
2045        bad_sig[last] ^= 0xff;
2046
2047        let (mut tracker, tka_tx) = PeerTracker::for_test(test_env(), None);
2048
2049        // 1) A netmap arrives while nothing is synced ⇒ enforcement inactive ⇒ all three admitted.
2050        let good = peer_node("good", NODE_KEY_BYTES, sig);
2051        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2052        let bad = peer_node("bad", [9u8; 32], bad_sig);
2053        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![
2054            good.clone(),
2055            unsigned.clone(),
2056            bad.clone(),
2057        ]));
2058        assert_eq!(tracker.peer_db.peers().len(), 3, "no lock yet ⇒ admit all");
2059        let unsigned_id = tracker
2060            .peer_db
2061            .get(&unsigned.node_key)
2062            .expect("unsigned peer admitted while no lock is synced")
2063            .0;
2064        let bad_id = tracker
2065            .peer_db
2066            .get(&bad.node_key)
2067            .expect("bad-sig peer admitted while no lock is synced")
2068            .0;
2069
2070        // 2) The sync completes and the control runner installs the verified authority.
2071        tka_tx.send_replace(Some(Arc::new(authority)));
2072        let evicted = tracker.tka_reevaluate_peer_db();
2073
2074        assert_eq!(
2075            evicted,
2076            HashSet::from_iter([unsigned_id, bad_id]),
2077            "the unsigned and bad-signature peers are the ones reported evicted"
2078        );
2079        assert_eq!(tracker.peer_db.peers().len(), 1);
2080        assert!(
2081            tracker.peer_db.get(&good.node_key).is_some(),
2082            "the authorized peer stays admitted"
2083        );
2084        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
2085        assert!(tracker.peer_db.get(&bad.node_key).is_none());
2086
2087        // 3) Idempotent: a second pass over the now-clean db evicts nobody.
2088        assert!(tracker.tka_reevaluate_peer_db().is_empty());
2089    }
2090
2091    /// With no authority the re-evaluation evicts nobody — enforcement is inactive and every peer is
2092    /// admitted, exactly Go's `b.tka == nil` early return. Covers both "never synced" and "the lock
2093    /// was disabled after enforcing", the two ways the cell holds `None`.
2094    #[tokio::test]
2095    async fn tka_reevaluate_without_authority_evicts_nothing() {
2096        let (authority, sig) = authority_and_valid_sig();
2097        let (mut tracker, tka_tx) = PeerTracker::for_test(test_env(), None);
2098
2099        let good = peer_node("good", NODE_KEY_BYTES, sig);
2100        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2101        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![
2102            good.clone(),
2103            unsigned.clone(),
2104        ]));
2105
2106        // Never synced.
2107        assert!(tracker.tka_reevaluate_peer_db().is_empty());
2108        assert_eq!(tracker.peer_db.peers().len(), 2);
2109
2110        // Enforced, then disabled: the disable must not evict the peer the lock had authorized, and
2111        // must not start dropping the unsigned one either.
2112        tka_tx.send_replace(Some(Arc::new(authority)));
2113        assert_eq!(tracker.tka_reevaluate_peer_db().len(), 1);
2114        tka_tx.send_replace(None);
2115        assert!(tracker.tka_reevaluate_peer_db().is_empty());
2116        assert!(tracker.peer_db.get(&good.node_key).is_some());
2117    }
2118
2119    /// The re-evaluation runs the WHOLE Go `tkaFilterNetmapLocked` pass, not just the per-peer
2120    /// signature check: a peer presenting a node key that a newer rotation superseded is evicted too,
2121    /// even though its own `Direct` signature still verifies against the authority. Both peers are
2122    /// already in the db when the authority lands, so the cross-peer rotation filter has to run over
2123    /// the db contents — which is why `tka_keep_verdicts` is shared with the `Full` path rather than
2124    /// re-derived here.
2125    #[tokio::test]
2126    async fn tka_reevaluate_applies_the_cross_peer_rotation_filter() {
2127        use ed25519_dalek::SigningKey;
2128        use ts_tka::NodeKeySignature;
2129
2130        let trusted = SigningKey::from_bytes(&[42u8; 32]);
2131        let authority = Authority::from_state(
2132            AumHash([0; 32]),
2133            State {
2134                keys: vec![Key {
2135                    kind: KeyKind::Ed25519,
2136                    votes: 1,
2137                    public: trusted.verifying_key().to_bytes().to_vec(),
2138                }],
2139            },
2140        );
2141        // `stale` holds the pivot key with a valid Direct signature; `rotated` holds a key whose
2142        // rotation chain rotated the pivot key AWAY, which obsoletes `stale`.
2143        let pivot = SigningKey::from_bytes(&[9u8; 32]);
2144        let pivot_pub: [u8; 32] = pivot.verifying_key().to_bytes();
2145        let stale = peer_node(
2146            "stale",
2147            pivot_pub,
2148            NodeKeySignature::sign_direct(&pivot_pub, &trusted).serialize(),
2149        );
2150        let new_key = [4u8; 32];
2151        let rotated = peer_node(
2152            "rotated",
2153            new_key,
2154            NodeKeySignature::sign_rotation(&new_key, &trusted, &pivot).serialize(),
2155        );
2156
2157        // Both admitted while nothing is synced.
2158        let (mut tracker, tka_tx) = PeerTracker::for_test(test_env(), None);
2159        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![
2160            stale.clone(),
2161            rotated.clone(),
2162        ]));
2163        assert_eq!(tracker.peer_db.peers().len(), 2, "no lock yet ⇒ admit all");
2164
2165        tka_tx.send_replace(Some(Arc::new(authority)));
2166        let evicted = tracker.tka_reevaluate_peer_db();
2167
2168        assert_eq!(
2169            evicted.len(),
2170            1,
2171            "only the rotation-obsolete peer is evicted"
2172        );
2173        assert!(
2174            tracker.peer_db.get(&rotated.node_key).is_some(),
2175            "the freshly-rotated peer stays"
2176        );
2177        assert!(
2178            tracker.peer_db.get(&stale.node_key).is_none(),
2179            "the peer whose key a rotation superseded is evicted, though its own signature verifies"
2180        );
2181    }
2182
2183    /// A `StateUpdate` carrying nothing but a `Full` peer set — the netmap shape the live-actor test
2184    /// publishes on the bus.
2185    fn netmap_with_peers(peers: Vec<Node>) -> ts_control::StateUpdate {
2186        ts_control::StateUpdate {
2187            session_handle: None,
2188            seq: 0,
2189            keep_alive: false,
2190            derp: None,
2191            node: None,
2192            peer_update: Some(ts_control::PeerUpdate::Full(peers)),
2193            peer_patches: Vec::new(),
2194            user_profiles: Vec::new(),
2195            ping: None,
2196            packetfilter: None,
2197            cap_grants: None,
2198            pop_browser_url: None,
2199            dial_plan: None,
2200            dns_config: None,
2201            ssh_policy: None,
2202            tka: None,
2203            online_change: Default::default(),
2204            peer_seen_change: Default::default(),
2205        }
2206    }
2207
2208    /// Poll a live [`PeerTracker`] until it holds exactly `want` peers, bounded by a timeout so a
2209    /// broken wiring fails the test instead of hanging the suite.
2210    async fn await_peer_count(tracker: &ActorRef<PeerTracker>, want: usize) -> Vec<Node> {
2211        let settled = tokio::time::timeout(std::time::Duration::from_secs(10), async {
2212            loop {
2213                let peers = tracker.ask(AllPeers).await.expect("peer tracker is alive");
2214                if peers.len() == want {
2215                    return peers;
2216                }
2217                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
2218            }
2219        })
2220        .await;
2221        settled.unwrap_or_else(|_| panic!("peer tracker never settled at {want} peer(s)"))
2222    }
2223
2224    /// End-to-end through the LIVE actor, which is the only thing that proves the wiring: the peer
2225    /// tracker watches its own enforcement cell, so the control runner's `send_replace` re-filters
2226    /// the peer db with no further netmap. If the watch task were never spawned (or the message not
2227    /// handled) the unsigned peer would stay admitted forever — a hole every `for_test` unit test
2228    /// above would still pass over, because they call the re-evaluation by hand.
2229    #[tokio::test]
2230    async fn tka_authority_change_refilters_through_the_live_actor() {
2231        use kameo::actor::Spawn as _;
2232
2233        let (authority, sig) = authority_and_valid_sig();
2234        let env = test_env();
2235        let (tka_tx, tka_rx) = watch::channel(None);
2236        let tracker = PeerTracker::spawn((env.clone(), tka_rx));
2237
2238        // Await one reply first: the actor's `on_start` (which registers it on the bus) has then
2239        // completed, so the netmap published below cannot race the subscription.
2240        assert!(
2241            tracker
2242                .ask(AllPeers)
2243                .await
2244                .expect("peer tracker started")
2245                .is_empty()
2246        );
2247
2248        let good = peer_node("good", NODE_KEY_BYTES, sig);
2249        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2250        env.publish(Arc::new(netmap_with_peers(vec![
2251            good.clone(),
2252            unsigned.clone(),
2253        ])))
2254        .await
2255        .expect("publish netmap");
2256
2257        // No lock synced ⇒ both peers land.
2258        await_peer_count(&tracker, 2).await;
2259
2260        // The control runner installs the verified authority. No netmap follows.
2261        tka_tx.send_replace(Some(Arc::new(authority)));
2262
2263        let peers = await_peer_count(&tracker, 1).await;
2264        assert_eq!(
2265            peers[0].stable_id, good.stable_id,
2266            "only the authorized peer survives the authority install"
2267        );
2268    }
2269
2270    /// Degenerate input: two DISTINCT nodes sharing one `stable_id` in a single `Full`, one with a
2271    /// valid signature and one unsigned, under an active lock. Each node is judged by its OWN verdict
2272    /// (the per-node `admits` vector), so the unsigned node is never admitted on the strength of its
2273    /// signed twin. The single-verify `Full` refactor keeps this per-node semantics (a stable_id-set
2274    /// alone would have admitted whichever node was upserted last). Malformed control input; asserted
2275    /// only to lock the verdict-per-node behavior against regression.
2276    #[tokio::test]
2277    async fn tka_full_duplicate_stable_id_judges_each_node_on_its_own_signature() {
2278        let (authority, sig) = authority_and_valid_sig();
2279        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2280
2281        // Both carry stable_id "dup"; the signed one authorizes NODE_KEY_BYTES, the other is unsigned
2282        // and uses a different node key. Order them unsigned-last so a last-writer-wins stable_id set
2283        // would (wrongly) leave the unsigned node's key in the db.
2284        let signed = peer_node("dup", NODE_KEY_BYTES, sig);
2285        let unsigned = peer_node("dup", [8u8; 32], vec![]);
2286        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![
2287            signed.clone(),
2288            unsigned.clone(),
2289        ]));
2290
2291        // The unsigned node's own verdict failed, so its key must NOT be present, regardless of the
2292        // shared stable_id. (The signed twin retained the stable_id; the db holds the signed key.)
2293        assert!(
2294            tracker.peer_db.get(&unsigned.node_key).is_none(),
2295            "a node whose own signature fails must not be admitted via a stable_id twin"
2296        );
2297        assert!(tracker.peer_db.get(&signed.node_key).is_some());
2298    }
2299
2300    /// Full-path consistency under two KEPT nodes sharing a `stable_id`: `peer_db.upsert` is
2301    /// last-writer-wins on `stable_id`, so the db ends holding exactly one node for that id (the last
2302    /// kept), and `retain` never evicts that just-upserted id (`retained_ids` contains the shared id
2303    /// because at least one of its nodes was kept). No lock here, so both nodes are "kept". This pins
2304    /// the published-state invariant the whole-surface audit flagged: `retain` and the upsert loop
2305    /// agree on the surviving stable_id. Malformed control input; asserted for robustness.
2306    #[tokio::test]
2307    async fn tka_full_duplicate_stable_id_both_kept_is_consistent() {
2308        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2309        let first = peer_node("dup", [1u8; 32], vec![]);
2310        let last = peer_node("dup", [2u8; 32], vec![]);
2311        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![
2312            first.clone(),
2313            last.clone(),
2314        ]));
2315
2316        // Exactly one db entry for the shared stable_id, holding the LAST node (upsert is
2317        // last-writer-wins on stable_id); the first node's key was transparently superseded.
2318        assert_eq!(
2319            tracker.peer_db.peers().len(),
2320            1,
2321            "one entry for the shared stable_id"
2322        );
2323        assert!(
2324            tracker.peer_db.get(&last.node_key).is_some(),
2325            "the db holds the last-upserted node for the shared id"
2326        );
2327        assert!(
2328            tracker.peer_db.get(&first.node_key).is_none(),
2329            "the first node's key was superseded by the last at the shared id"
2330        );
2331    }
2332
2333    /// A peer admitted in one `Full`, then in a later `Full` presenting a key that a co-resident
2334    /// peer's rotation chain has rotated away, is EVICTED — the cross-peer rotation filter applies on
2335    /// every resync, not only at first admission. Exercises the rotation filter through two
2336    /// sequential `Full` updates with real signing.
2337    #[tokio::test]
2338    async fn tka_full_rotation_obsolete_evicts_on_resync() {
2339        use ed25519_dalek::SigningKey;
2340        use ts_tka::NodeKeySignature;
2341
2342        let trusted = SigningKey::from_bytes(&[42u8; 32]);
2343        let trusted_pub = trusted.verifying_key().to_bytes().to_vec();
2344        let authority = Authority::from_state(
2345            AumHash([0; 32]),
2346            State {
2347                keys: vec![Key {
2348                    kind: KeyKind::Ed25519,
2349                    votes: 1,
2350                    public: trusted_pub.clone(),
2351                }],
2352            },
2353        );
2354        let pivot = SigningKey::from_bytes(&[9u8; 32]);
2355        let pivot_pub: [u8; 32] = pivot.verifying_key().to_bytes();
2356
2357        // First Full: the soon-to-be-stale peer presents the pivot key with a valid Direct sig.
2358        let stale_sig = NodeKeySignature::sign_direct(&pivot_pub, &trusted).serialize();
2359        let stale_peer = peer_node("stale", pivot_pub, stale_sig);
2360        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2361        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![stale_peer.clone()]));
2362        assert!(
2363            tracker.peer_db.get(&stale_peer.node_key).is_some(),
2364            "the stale peer is admitted while no rotation has superseded it yet"
2365        );
2366
2367        // Second Full: a freshly-rotated peer (whose chain rotated AWAY the pivot key) joins, and the
2368        // stale peer is re-included. The rotation filter now obsoletes the pivot key ⇒ stale evicted.
2369        let new_key = [4u8; 32];
2370        let new_sig = NodeKeySignature::sign_rotation(&new_key, &trusted, &pivot).serialize();
2371        let new_peer = peer_node("rotated", new_key, new_sig);
2372        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![
2373            new_peer.clone(),
2374            stale_peer.clone(),
2375        ]));
2376        assert!(
2377            tracker.peer_db.get(&new_peer.node_key).is_some(),
2378            "the freshly-rotated peer is admitted"
2379        );
2380        assert!(
2381            tracker.peer_db.get(&stale_peer.node_key).is_none(),
2382            "the stale peer is EVICTED on the resync once a rotation supersedes its key"
2383        );
2384    }
2385
2386    /// The empty-trusted-key-state brick-guard: an authority with no keys must NOT drop the whole
2387    /// netmap (a `ts_tka` invariant violation / replayer edge). A verified chain always carries ≥1
2388    /// key, so this never weakens a genuine lock — it only prevents a black-hole. Uses ≥2 peers
2389    /// (one signed, one unsigned) to prove it admits **all**, not accidentally just one.
2390    #[tokio::test]
2391    async fn tka_empty_keyset_authority_admits_all() {
2392        use ts_tka::{AumHash, Authority, State};
2393        let empty_auth = Authority::from_state(AumHash([0u8; 32]), State { keys: Vec::new() });
2394        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(empty_auth));
2395        let signed = peer_node("signed", [7u8; 32], vec![0xde, 0xad]);
2396        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2397        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![
2398            signed.clone(),
2399            unsigned.clone(),
2400        ]));
2401        assert_eq!(
2402            tracker.peer_db.peers().len(),
2403            2,
2404            "an empty-keyset authority must admit ALL peers (brick-guard), not enforce"
2405        );
2406    }
2407
2408    /// Signature-replay / `NodeKeyMismatch`: a structurally-valid signature that authorizes
2409    /// `NODE_KEY_BYTES` must NOT admit a DIFFERENT node key carrying that same signature blob. This is
2410    /// the highest-value bypass — if the sig↔node-key binding in `verify_signature` were dropped, this
2411    /// is the only test that would catch it (the other "bad" peers only flip a byte ⇒ `BadSignature`).
2412    #[tokio::test]
2413    async fn tka_active_rejects_valid_sig_for_wrong_node_key() {
2414        let (authority, sig) = authority_and_valid_sig();
2415        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2416
2417        // The signature authorizes NODE_KEY_BYTES; attach it to an imposter with a different key.
2418        let imposter = peer_node("imposter", [0x55u8; 32], sig);
2419        assert!(
2420            !tracker.tka_admits(&imposter),
2421            "a signature bound to one node key must not authorize a different node key"
2422        );
2423        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![imposter.clone()]));
2424        assert!(tracker.peer_db.get(&imposter.node_key).is_none());
2425    }
2426
2427    /// `UntrustedKey`: a signature produced by a well-formed Ed25519 key that is NOT in the
2428    /// authority's trusted-key state must be rejected — distinct from a tampered-byte `BadSignature`.
2429    #[tokio::test]
2430    async fn tka_active_rejects_sig_from_untrusted_key() {
2431        use ed25519_dalek::{Signer, SigningKey};
2432        let (authority, _sig) = authority_and_valid_sig();
2433        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2434
2435        // Sign a valid CBOR with a DIFFERENT key (not the one the authority trusts). The key_id in
2436        // the signature names this untrusted key, so `get_key` misses ⇒ UntrustedKey.
2437        let rogue = SigningKey::from_bytes(&[99u8; 32]);
2438        let rogue_pub = rogue.verifying_key().to_bytes().to_vec();
2439        let preimage = direct_sig_cbor(&NODE_KEY_BYTES, &rogue_pub, None);
2440        let sig_hash = ts_tka::aum_hash(&preimage).0;
2441        let signature = rogue.sign(&sig_hash).to_bytes().to_vec();
2442        let rogue_cbor = direct_sig_cbor(&NODE_KEY_BYTES, &rogue_pub, Some(&signature));
2443
2444        let peer = peer_node("rogue-signed", NODE_KEY_BYTES, rogue_cbor);
2445        assert!(
2446            !tracker.tka_admits(&peer),
2447            "a signature from a key outside the trusted set must be rejected"
2448        );
2449        // Drive the real upsert path too (match the sibling replay test's depth): an untrusted-key
2450        // signature must keep the peer out of the db, not merely fail the verdict in isolation.
2451        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer.clone()]));
2452        assert!(tracker.peer_db.get(&peer.node_key).is_none());
2453    }
2454
2455    /// Bus-enable analogue for `Delta`: enforcement engaged via the watch cell must also gate a
2456    /// `Delta { upsert }` (not only `Full`). Closes the "authority arrived over the transport AND the
2457    /// next update is a Delta" combination.
2458    #[tokio::test]
2459    async fn tka_watch_enable_enforces_delta_upsert() {
2460        let (authority, sig) = authority_and_valid_sig();
2461        let (mut tracker, tka_tx) = PeerTracker::for_test(test_env(), None);
2462        tka_tx.send_replace(Some(Arc::new(authority)));
2463
2464        let good = peer_node("good", NODE_KEY_BYTES, sig);
2465        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2466        tracker.apply_peer_update(&ts_control::PeerUpdate::Delta {
2467            remove: vec![],
2468            upsert: vec![good.clone(), unsigned.clone()],
2469        });
2470        assert!(tracker.peer_db.get(&good.node_key).is_some());
2471        assert!(
2472            tracker.peer_db.get(&unsigned.node_key).is_none(),
2473            "delta upsert under an active lock must drop the unsigned peer"
2474        );
2475    }
2476
2477    /// A `Delta` re-upsert of an ALREADY-ADMITTED peer whose signature is now invalid must EVICT the
2478    /// stale entry (revocation-via-delta), not leave it admitted. Go re-filters the whole netmap each
2479    /// response, so a now-unsigned peer would not survive there either.
2480    #[tokio::test]
2481    async fn tka_delta_reupsert_with_invalid_sig_evicts_existing() {
2482        let (authority, sig) = authority_and_valid_sig();
2483        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2484
2485        // Admit the signed peer.
2486        let good = peer_node("good", NODE_KEY_BYTES, sig.clone());
2487        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![good.clone()]));
2488        assert!(tracker.peer_db.get(&good.node_key).is_some());
2489
2490        // Re-upsert the SAME stable_id (now with no signature) via a delta ⇒ evicted, not retained.
2491        let revoked = peer_node("good", NODE_KEY_BYTES, vec![]);
2492        tracker.apply_peer_update(&ts_control::PeerUpdate::Delta {
2493            remove: vec![],
2494            upsert: vec![revoked],
2495        });
2496        assert!(
2497            tracker.peer_db.get(&good.node_key).is_none(),
2498            "a delta re-upsert that fails the lock must evict the previously-admitted peer"
2499        );
2500    }
2501
2502    #[tokio::test]
2503    async fn tka_full_resync_revocation_behavior() {
2504        // Revocation-on-resync: admit a peer, then re-include the SAME stable_id in a `Full` with a
2505        // now-invalid signature. Per the Logic review finding, the pre-fix `retain` kept the stale
2506        // (previously-admitted) entry because membership was decided purely by stable_id.
2507        //
2508        // FIXED (not merely documented): the `Full` `retain` now keys on `tka_admits`-passing
2509        // stable_ids, so a peer whose re-included signature no longer verifies under the active
2510        // authority is EVICTED. This test asserts eviction. The inactive (authority=None) path is
2511        // provably unchanged — `tka_admits` always returns `true` there, so the retained set equals
2512        // the set of re-included stable_ids exactly (see `tka_inactive_full_resync_keeps_*`).
2513        let (authority, sig) = authority_and_valid_sig();
2514        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2515
2516        // 1) Admit the peer with a valid signature via a real `Full`.
2517        let good = peer_node("revoked", NODE_KEY_BYTES, sig.clone());
2518        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![good.clone()]));
2519        assert_eq!(tracker.peer_db.peers().len(), 1);
2520        assert!(tracker.peer_db.get(&good.node_key).is_some());
2521
2522        // 2) Re-sync the SAME stable_id, but with a now-invalid signature (tamper trailing byte).
2523        let mut bad_sig = sig;
2524        let last = bad_sig.len() - 1;
2525        bad_sig[last] ^= 0xff;
2526        let revoked = peer_node("revoked", NODE_KEY_BYTES, bad_sig);
2527        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![revoked.clone()]));
2528
2529        // Eviction: the stale entry is dropped because its re-included signature fails the gate.
2530        assert_eq!(tracker.peer_db.peers().len(), 0);
2531        assert!(tracker.peer_db.get(&revoked.node_key).is_none());
2532    }
2533
2534    #[tokio::test]
2535    async fn tka_inactive_full_resync_keeps_reincluded_peer() {
2536        // Guard the inactive (authority=None) path against the revocation fix: with no authority,
2537        // a peer re-included in a `Full` survives regardless of its signature bytes — byte-for-byte
2538        // pre-TKA behavior, proving the `Full` `retain` change does not regress the always-taken
2539        // branch this wave.
2540        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2541
2542        let peer = peer_node("p", NODE_KEY_BYTES, vec![0xde, 0xad]);
2543        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer.clone()]));
2544        assert_eq!(tracker.peer_db.peers().len(), 1);
2545
2546        // Re-sync the same stable_id with garbage signature bytes; inactive enforcement keeps it.
2547        let resynced = peer_node("p", NODE_KEY_BYTES, vec![0x00]);
2548        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![resynced.clone()]));
2549        assert_eq!(tracker.peer_db.peers().len(), 1);
2550        assert!(tracker.peer_db.get(&resynced.node_key).is_some());
2551    }
2552
2553    /// A `Patch` for a peer already in the netmap merges only the fields it carries — here new UDP
2554    /// endpoints and a new home DERP — leaving the rest of the node intact. This is the fix for
2555    /// dropped `peers_changed_patch`: without it the netmap keeps stale endpoints and the peer can
2556    /// never re-handshake after it moves.
2557    #[tokio::test]
2558    async fn patch_merges_endpoints_and_derp_into_existing_peer() {
2559        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2560
2561        // Seed a peer (id == 1, per `peer_node`) with no endpoints / no DERP.
2562        let peer = peer_node("mover", [1u8; 32], vec![]);
2563        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer.clone()]));
2564        let (_pid, before) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
2565        assert!(before.underlay_addresses.is_empty());
2566        assert!(before.derp_region.is_none());
2567
2568        // Patch in fresh reachability (the idle-peer-reconnect case).
2569        let new_ep: std::net::SocketAddr = "203.0.113.7:41641".parse().unwrap();
2570        let patch = ts_control::PeerChange {
2571            id: 1,
2572            derp_region: Some(ts_derp::RegionId(core::num::NonZeroU32::new(5).unwrap())),
2573            cap: None,
2574            cap_map: None,
2575            underlay_addresses: Some(vec![new_ep]),
2576            node_key: None,
2577            key_signature: None,
2578            disco_key: None,
2579            node_key_expiry: None,
2580            online: None,
2581            last_seen: None,
2582        };
2583        let (upserts, deletions) = tracker.apply_peer_patches(std::slice::from_ref(&patch));
2584
2585        assert_eq!(upserts.len(), 1);
2586        assert_eq!(deletions.len(), 0);
2587        // Same peer, now carrying the patched endpoint + DERP; node key untouched.
2588        assert_eq!(tracker.peer_db.peers().len(), 1);
2589        let (_pid, after) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
2590        assert_eq!(after.underlay_addresses, vec![new_ep]);
2591        assert_eq!(
2592            after.derp_region,
2593            Some(ts_derp::RegionId(core::num::NonZeroU32::new(5).unwrap()))
2594        );
2595        assert_eq!(after.node_key, peer.node_key);
2596    }
2597
2598    /// Regression for `tsr-5u0`: when a whole-node set (`Delta`/`Full`) and a patch co-occur in one
2599    /// response, the patch is applied *on top of* the node the set just upserted — mirroring the
2600    /// handler's apply-order (peer set first, then `peer_patches`). Before the fix the patch shared
2601    /// the single `peer_update` slot and the co-occurring set silently dropped it, so a peer brought
2602    /// in by the delta kept stale (empty) reachability.
2603    #[tokio::test]
2604    async fn patch_applies_on_top_of_co_occurring_delta() {
2605        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2606
2607        // The whole-node delta upserts a brand-new peer (id == 1) with no reachability.
2608        let peer = peer_node("mover", [1u8; 32], vec![]);
2609        let (set_upserts, _) = tracker.apply_peer_update(&ts_control::PeerUpdate::Delta {
2610            upsert: vec![peer.clone()],
2611            remove: vec![],
2612        });
2613        assert_eq!(set_upserts.len(), 1, "delta upserts the new peer");
2614
2615        // The patch from the SAME response then sets that peer's endpoints + DERP. This is exactly
2616        // the consumer order the handler runs (apply_peer_update then apply_peer_patches).
2617        let new_ep: std::net::SocketAddr = "203.0.113.7:41641".parse().unwrap();
2618        let patch = ts_control::PeerChange {
2619            id: 1,
2620            derp_region: Some(ts_derp::RegionId(core::num::NonZeroU32::new(7).unwrap())),
2621            cap: None,
2622            cap_map: None,
2623            underlay_addresses: Some(vec![new_ep]),
2624            node_key: None,
2625            key_signature: None,
2626            disco_key: None,
2627            node_key_expiry: None,
2628            online: None,
2629            last_seen: None,
2630        };
2631        let (patch_upserts, patch_deletions) =
2632            tracker.apply_peer_patches(std::slice::from_ref(&patch));
2633
2634        assert_eq!(
2635            patch_upserts.len(),
2636            1,
2637            "patch re-upserts the just-added peer"
2638        );
2639        assert_eq!(patch_deletions.len(), 0);
2640        // The peer added by the delta now carries the patched reachability — the patch was NOT lost.
2641        let (_pid, after) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
2642        assert_eq!(after.underlay_addresses, vec![new_ep]);
2643        assert_eq!(
2644            after.derp_region,
2645            Some(ts_derp::RegionId(core::num::NonZeroU32::new(7).unwrap()))
2646        );
2647    }
2648
2649    /// A `Patch` whose node id is not in the current netmap is ignored (the wire contract: a patch
2650    /// never creates a node). No upsert, no deletion, peer set unchanged.
2651    #[tokio::test]
2652    async fn patch_for_unknown_node_is_ignored() {
2653        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2654        let known = peer_node("known", [1u8; 32], vec![]); // id == 1
2655        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![known]));
2656
2657        let patch = ts_control::PeerChange {
2658            id: 999, // not in the netmap
2659            derp_region: None,
2660            cap: None,
2661            cap_map: None,
2662            underlay_addresses: Some(vec!["198.51.100.9:1".parse().unwrap()]),
2663            node_key: None,
2664            key_signature: None,
2665            disco_key: None,
2666            node_key_expiry: None,
2667            online: None,
2668            last_seen: None,
2669        };
2670        let (upserts, deletions) = tracker.apply_peer_patches(std::slice::from_ref(&patch));
2671
2672        assert_eq!(upserts.len(), 0);
2673        assert_eq!(deletions.len(), 0);
2674        assert_eq!(tracker.peer_db.peers().len(), 1);
2675        assert!(tracker.peer_db.get(&(999 as ts_control::NodeId)).is_none());
2676    }
2677
2678    /// An expiry-only `Patch` updates `node_key_expiry` on the matching peer (Go
2679    /// `PeerChange.KeyExpiry`), rather than being silently dropped until the next full resync.
2680    #[tokio::test]
2681    async fn patch_updates_node_key_expiry() {
2682        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2683        let peer = peer_node("expiring", [1u8; 32], vec![]); // id == 1, node_key_expiry: None
2684        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]));
2685
2686        let expiry = "2027-01-01T00:00:00Z"
2687            .parse::<chrono::DateTime<chrono::Utc>>()
2688            .unwrap();
2689        let patch = ts_control::PeerChange {
2690            id: 1,
2691            derp_region: None,
2692            cap: None,
2693            cap_map: None,
2694            underlay_addresses: None,
2695            node_key: None,
2696            key_signature: None,
2697            disco_key: None,
2698            node_key_expiry: Some(expiry),
2699            online: None,
2700            last_seen: None,
2701        };
2702        tracker.apply_peer_patches(std::slice::from_ref(&patch));
2703
2704        let (_pid, after) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
2705        assert_eq!(after.node_key_expiry, Some(expiry));
2706    }
2707
2708    /// Channel B: a `PeerChange.online` patch flips a peer's online state without a full node.
2709    #[tokio::test]
2710    async fn patch_updates_online() {
2711        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2712        let peer = peer_node("p", [1u8; 32], vec![]); // id == 1, online: None
2713        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]));
2714        assert_eq!(
2715            tracker
2716                .peer_db
2717                .get(&(1 as ts_control::NodeId))
2718                .unwrap()
2719                .1
2720                .online,
2721            None
2722        );
2723
2724        let mut patch = ts_control::PeerChange {
2725            id: 1,
2726            derp_region: None,
2727            cap: None,
2728            cap_map: None,
2729            underlay_addresses: None,
2730            node_key: None,
2731            key_signature: None,
2732            disco_key: None,
2733            node_key_expiry: None,
2734            online: Some(true),
2735            last_seen: None,
2736        };
2737        tracker.apply_peer_patches(std::slice::from_ref(&patch));
2738        assert_eq!(
2739            tracker
2740                .peer_db
2741                .get(&(1 as ts_control::NodeId))
2742                .unwrap()
2743                .1
2744                .online,
2745            Some(true),
2746            "PeerChange.online=Some(true) marks the peer online"
2747        );
2748
2749        // A subsequent patch flips it offline.
2750        patch.online = Some(false);
2751        tracker.apply_peer_patches(std::slice::from_ref(&patch));
2752        assert_eq!(
2753            tracker
2754                .peer_db
2755                .get(&(1 as ts_control::NodeId))
2756                .unwrap()
2757                .1
2758                .online,
2759            Some(false)
2760        );
2761    }
2762
2763    /// Channel C/D (Go `map.go:updatePeersStateFromResponse`): `online_change` is the sole driver of
2764    /// `online`; `peer_seen_change` is the sole driver of `last_seen` (true ⇒ now, false ⇒ cleared)
2765    /// and must NEVER touch `online`. Both apply to a peer already in the netmap and ignore unknown
2766    /// ids. This pins the fix for the prior bug where channel D wrote `online=false` (conflating
2767    /// "not seen recently" with "offline" — distinct signals in Go).
2768    #[tokio::test]
2769    async fn liveness_change_maps_apply_online() {
2770        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2771        let peer = peer_node("p", [1u8; 32], vec![]); // id == 1
2772        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]));
2773        // A fixed timestamp (chrono is built without its `clock` feature, so no `Utc::now()`).
2774        let now = chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap();
2775
2776        // Channel C: online_change sets online=true.
2777        let mut online_change = std::collections::BTreeMap::new();
2778        online_change.insert(1 as ts_control::NodeId, true);
2779        online_change.insert(999 as ts_control::NodeId, true); // unknown id — ignored
2780        let changed = tracker.apply_liveness_changes(&online_change, &Default::default(), now);
2781        assert!(changed);
2782        assert_eq!(
2783            tracker
2784                .peer_db
2785                .get(&(1 as ts_control::NodeId))
2786                .unwrap()
2787                .1
2788                .online,
2789            Some(true)
2790        );
2791
2792        // Channel D: peer_seen_change=true sets last_seen=now and leaves online UNTOUCHED.
2793        let mut seen_true = std::collections::BTreeMap::new();
2794        seen_true.insert(1 as ts_control::NodeId, true);
2795        let changed = tracker.apply_liveness_changes(&Default::default(), &seen_true, now);
2796        assert!(changed);
2797        {
2798            let (_id, node) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
2799            assert_eq!(
2800                node.last_seen,
2801                Some(now),
2802                "peer_seen_change=true sets last_seen=now"
2803            );
2804            assert_eq!(
2805                node.online,
2806                Some(true),
2807                "channel D must NOT touch online (still true from channel C)"
2808            );
2809        }
2810
2811        // Channel D: peer_seen_change=false clears last_seen, still leaving online untouched.
2812        let mut seen_false = std::collections::BTreeMap::new();
2813        seen_false.insert(1 as ts_control::NodeId, false);
2814        let changed = tracker.apply_liveness_changes(&Default::default(), &seen_false, now);
2815        assert!(changed);
2816        {
2817            let (_id, node) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
2818            assert_eq!(
2819                node.last_seen, None,
2820                "peer_seen_change=false clears last_seen"
2821            );
2822            assert_eq!(node.online, Some(true), "channel D must NOT mark offline");
2823        }
2824        assert_eq!(
2825            tracker.peer_db.peers().len(),
2826            1,
2827            "the node is retained, not removed"
2828        );
2829
2830        // No-op when nothing matches / changes.
2831        assert!(!tracker.apply_liveness_changes(&Default::default(), &Default::default(), now));
2832    }
2833
2834    /// Security: a `Patch` that rotates the node key must re-satisfy the tailnet-lock authority,
2835    /// exactly like a `Delta` upsert. A key-rotation patch whose new signature does NOT verify
2836    /// evicts the peer (fail-closed) rather than leaving a now-unverified entry — closing what would
2837    /// otherwise be a trust-enforcement bypass via the patch path.
2838    #[tokio::test]
2839    async fn patch_key_rotation_failing_tka_evicts_peer() {
2840        let (authority, sig) = authority_and_valid_sig();
2841        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2842
2843        // Admit a correctly-signed peer (id == 1).
2844        let good = peer_node("rotator", NODE_KEY_BYTES, sig.clone());
2845        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![good.clone()]));
2846        assert_eq!(tracker.peer_db.peers().len(), 1);
2847
2848        // Patch a new node key whose signature is garbage under the active authority.
2849        let patch = ts_control::PeerChange {
2850            id: 1,
2851            derp_region: None,
2852            cap: None,
2853            cap_map: None,
2854            underlay_addresses: None,
2855            node_key: Some([0x33u8; 32].into()),
2856            key_signature: Some(vec![0x00, 0x01, 0x02]),
2857            disco_key: None,
2858            node_key_expiry: None,
2859            online: None,
2860            last_seen: None,
2861        };
2862        let (upserts, deletions) = tracker.apply_peer_patches(std::slice::from_ref(&patch));
2863
2864        assert_eq!(upserts.len(), 0);
2865        assert_eq!(deletions.len(), 1);
2866        assert_eq!(tracker.peer_db.peers().len(), 0);
2867    }
2868
2869    /// A node's `user_id` joins against the accumulated UserProfiles table to resolve the owning
2870    /// user's login name in `WhoIs.user`. With no matching profile, `user` is `None` (the
2871    /// pre-existing behavior); once a profile arrives, the same node resolves to its login. This
2872    /// proves the accumulate-then-join path the netmap handler builds.
2873    fn profile(id: ts_control::UserId, login: &str) -> ts_control::UserProfile {
2874        ts_control::UserProfile {
2875            id,
2876            login_name: login.to_string(),
2877            display_name: None,
2878        }
2879    }
2880
2881    #[tokio::test]
2882    async fn whois_resolves_user_from_accumulated_profiles() {
2883        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2884
2885        // A peer owned by user id 42 at 100.64.0.1 (the peer_node fixture's address).
2886        let mut peer = peer_node("p", NODE_KEY_BYTES, Vec::new());
2887        peer.user_id = 42;
2888        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]));
2889        let addr = "100.64.0.1:0".parse().unwrap();
2890
2891        // No profile yet: the node resolves but its owner is unknown.
2892        let who = tracker.whois_opt(addr).expect("peer is known");
2893        assert_eq!(who.user, None);
2894
2895        // Profile for a DIFFERENT user must not match.
2896        tracker
2897            .user_profiles
2898            .insert(7, profile(7, "someone-else@example.com"));
2899        assert_eq!(tracker.whois_opt(addr).unwrap().user, None);
2900
2901        // The owning user's profile arrives (as the netmap handler would accumulate it): now the
2902        // login resolves.
2903        tracker
2904            .user_profiles
2905            .insert(42, profile(42, "alice@example.com"));
2906        assert_eq!(
2907            tracker.whois_opt(addr).unwrap().user,
2908            Some("alice@example.com".to_string())
2909        );
2910    }
2911
2912    /// `UserProfile::best_label` prefers the login name, falling back to display name, else `None`.
2913    #[test]
2914    fn user_profile_best_label_prefers_login() {
2915        assert_eq!(
2916            profile(1, "alice@example.com").best_label(),
2917            Some("alice@example.com".to_string())
2918        );
2919        let display_only = ts_control::UserProfile {
2920            id: 2,
2921            login_name: String::new(),
2922            display_name: Some("Bob".to_string()),
2923        };
2924        assert_eq!(display_only.best_label(), Some("Bob".to_string()));
2925        let empty = ts_control::UserProfile {
2926            id: 3,
2927            login_name: String::new(),
2928            display_name: None,
2929        };
2930        assert_eq!(empty.best_label(), None);
2931    }
2932
2933    // ----- tsr-jo1: RotationTracker (Go ipnlocal.rotationTracker.obsoleteKeys) -----
2934
2935    /// A `RotationDetails` for a `Direct`-rooted chain with the given prior keys + wrapping key.
2936    fn rot_details(
2937        prev: &[&[u8]],
2938        wrapping: &[u8],
2939        kind: ts_tka::SigKind,
2940    ) -> ts_tka::RotationDetails {
2941        ts_tka::RotationDetails {
2942            prev_node_keys: prev.iter().map(|p| p.to_vec()).collect(),
2943            initial_sig_kind: kind,
2944            initial_wrapping_pubkey: wrapping.to_vec(),
2945        }
2946    }
2947
2948    /// Rule 1: every prior node key named by any rotation chain is obsolete, regardless of the
2949    /// chain's root kind (Go's ungated `obsolete.AddSlice(d.PrevNodeKeys)`).
2950    #[test]
2951    fn rotation_tracker_prev_keys_always_obsolete() {
2952        let mut t = RotationTracker::default();
2953        // A Direct-rooted chain that rotated away OLD1, and a Credential-rooted one that rotated OLD2.
2954        t.add(
2955            b"newA".to_vec(),
2956            &rot_details(&[b"OLD1"], b"wrapA", ts_tka::SigKind::Direct),
2957        );
2958        t.add(
2959            b"newB".to_vec(),
2960            &rot_details(&[b"OLD2"], b"wrapB", ts_tka::SigKind::Credential),
2961        );
2962        let obsolete = t.obsolete_keys();
2963        assert!(
2964            obsolete.contains(b"OLD1".as_slice()),
2965            "Direct chain's prior key obsolete"
2966        );
2967        assert!(
2968            obsolete.contains(b"OLD2".as_slice()),
2969            "Credential chain's prior key obsolete too (rule 1 is ungated)"
2970        );
2971        // The current keys themselves are not obsolete (only one peer per wrapping key here).
2972        assert!(!obsolete.contains(b"newA".as_slice()));
2973        assert!(!obsolete.contains(b"newB".as_slice()));
2974    }
2975
2976    /// Rule 2: among `Direct`-rooted chains sharing a wrapping key, only the longest survives; the
2977    /// shorter (older) clone's key is obsolete.
2978    #[test]
2979    fn rotation_tracker_unequal_chain_keeps_longest() {
2980        let mut t = RotationTracker::default();
2981        // Same wrapping key; "long" has 2 prior keys, "short" has 1 ⇒ "short" is the older clone.
2982        t.add(
2983            b"long".to_vec(),
2984            &rot_details(&[b"p1", b"p2"], b"wrap", ts_tka::SigKind::Direct),
2985        );
2986        t.add(
2987            b"short".to_vec(),
2988            &rot_details(&[b"q1"], b"wrap", ts_tka::SigKind::Direct),
2989        );
2990        let obsolete = t.obsolete_keys();
2991        assert!(
2992            obsolete.contains(b"short".as_slice()),
2993            "the shorter-chain clone is obsolete"
2994        );
2995        assert!(
2996            !obsolete.contains(b"long".as_slice()),
2997            "the longest-chain peer survives"
2998        );
2999    }
3000
3001    /// Rule 2 tie: two `Direct`-rooted chains sharing a wrapping key with EQUAL chain length cannot
3002    /// be disambiguated ⇒ BOTH are dropped (Go's safety branch).
3003    #[test]
3004    fn rotation_tracker_equal_chain_drops_both() {
3005        let mut t = RotationTracker::default();
3006        t.add(
3007            b"cloneA".to_vec(),
3008            &rot_details(&[b"p1"], b"wrap", ts_tka::SigKind::Direct),
3009        );
3010        t.add(
3011            b"cloneB".to_vec(),
3012            &rot_details(&[b"p2"], b"wrap", ts_tka::SigKind::Direct),
3013        );
3014        let obsolete = t.obsolete_keys();
3015        assert!(
3016            obsolete.contains(b"cloneA".as_slice()),
3017            "tied clone A dropped"
3018        );
3019        assert!(
3020            obsolete.contains(b"cloneB".as_slice()),
3021            "tied clone B dropped"
3022        );
3023    }
3024
3025    /// `Credential`-rooted chains sharing a wrapping key are EXEMPT from rule 2 (reusable-authkey
3026    /// carve-out): both are kept even with equal chain length.
3027    #[test]
3028    fn rotation_tracker_credential_root_clones_both_kept() {
3029        let mut t = RotationTracker::default();
3030        t.add(
3031            b"credA".to_vec(),
3032            &rot_details(&[b"p1"], b"wrap", ts_tka::SigKind::Credential),
3033        );
3034        t.add(
3035            b"credB".to_vec(),
3036            &rot_details(&[b"p2"], b"wrap", ts_tka::SigKind::Credential),
3037        );
3038        let obsolete = t.obsolete_keys();
3039        assert!(
3040            !obsolete.contains(b"credA".as_slice()),
3041            "credential-rooted clone A kept"
3042        );
3043        assert!(
3044            !obsolete.contains(b"credB".as_slice()),
3045            "credential-rooted clone B kept"
3046        );
3047    }
3048
3049    /// A peer that another chain already rotated away does not also act as a surviving clone: it is
3050    /// removed from its wrapping-key group before the longest-survivor pick (Go's `DeleteFunc`).
3051    #[test]
3052    fn rotation_tracker_already_obsolete_peer_not_a_survivor() {
3053        let mut t = RotationTracker::default();
3054        // "victim" is rotated away by "rotator" (different wrapping key), AND shares wrapping key
3055        // "w" with "other". Because "victim" is already obsolete, only "other" is in play for "w" and
3056        // survives (no spurious tie-drop of "other").
3057        t.add(
3058            b"rotator".to_vec(),
3059            &rot_details(&[b"victim"], b"wRot", ts_tka::SigKind::Direct),
3060        );
3061        t.add(
3062            b"victim".to_vec(),
3063            &rot_details(&[b"x"], b"w", ts_tka::SigKind::Direct),
3064        );
3065        t.add(
3066            b"other".to_vec(),
3067            &rot_details(&[b"y"], b"w", ts_tka::SigKind::Direct),
3068        );
3069        let obsolete = t.obsolete_keys();
3070        assert!(
3071            obsolete.contains(b"victim".as_slice()),
3072            "victim rotated away by rotator"
3073        );
3074        assert!(
3075            !obsolete.contains(b"other".as_slice()),
3076            "other survives — victim was removed from the group before the tie check"
3077        );
3078    }
3079
3080    /// Empty tracker (no rotation-signed peers) ⇒ no obsolete keys (the non-rotation netmap path).
3081    #[test]
3082    fn rotation_tracker_empty_is_noop() {
3083        let t = RotationTracker::default();
3084        assert!(t.obsolete_keys().is_empty());
3085    }
3086
3087    /// End-to-end through the real `Full` path: a peer presenting a freshly-rotated key (a Rotation
3088    /// chain) is admitted, while a second peer still presenting the rotated-AWAY pivot key — even with
3089    /// that key's own still-valid Direct signature — is DROPPED by the cross-peer rotation filter.
3090    /// This is the gap closed here: Go `tkaFilterNetmapLocked` drops the stale clone; we used to admit
3091    /// it. Uses real `ts_tka` signing (`sign_direct` + `sign_rotation`) so the whole
3092    /// verify → details → filter pipeline runs.
3093    ///
3094    /// Construction: the trusted key signs an inner `Direct` over the PIVOT keypair's public key; the
3095    /// pivot key then signs an outer `Rotation` authorizing `new_key`. That chain's `prev_node_keys`
3096    /// names the pivot pubkey — so a peer presenting the pivot pubkey as its node key is the
3097    /// rotated-away key the filter must drop.
3098    #[tokio::test]
3099    async fn tka_full_drops_rotated_away_key_e2e() {
3100        use ed25519_dalek::SigningKey;
3101        use ts_tka::NodeKeySignature;
3102
3103        let trusted = SigningKey::from_bytes(&[42u8; 32]);
3104        let trusted_pub = trusted.verifying_key().to_bytes().to_vec();
3105        let authority = Authority::from_state(
3106            AumHash([0; 32]),
3107            State {
3108                keys: vec![Key {
3109                    kind: KeyKind::Ed25519,
3110                    votes: 1,
3111                    public: trusted_pub.clone(),
3112                }],
3113            },
3114        );
3115
3116        // The rotation pivot: a keypair whose public key the inner Direct authorizes and whose
3117        // private key signs the outer rotation wrap. This pivot pubkey IS the key being rotated away.
3118        let pivot = SigningKey::from_bytes(&[9u8; 32]);
3119        let pivot_pub: [u8; 32] = pivot.verifying_key().to_bytes();
3120
3121        let new_key = [4u8; 32]; // the freshly-rotated node key
3122
3123        // Fresh peer: a Rotation chain authorizing `new_key`, inner Direct over the pivot signed by
3124        // trusted, outer wrap signed by the pivot. Its prev_node_keys names `pivot_pub`.
3125        let new_sig = NodeKeySignature::sign_rotation(&new_key, &trusted, &pivot).serialize();
3126        let new_peer = peer_node("rotated", new_key, new_sig);
3127
3128        // Stale peer: still presents the pivot pubkey (the rotated-away key) with its own valid
3129        // Direct signature — valid in isolation, but obsoleted by the fresh peer's rotation chain.
3130        let stale_sig = NodeKeySignature::sign_direct(&pivot_pub, &trusted).serialize();
3131        let stale_peer = peer_node("stale", pivot_pub, stale_sig);
3132
3133        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
3134        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![
3135            new_peer.clone(),
3136            stale_peer.clone(),
3137        ]));
3138
3139        assert!(
3140            tracker.peer_db.get(&new_peer.node_key).is_some(),
3141            "the freshly-rotated peer is admitted"
3142        );
3143        assert!(
3144            tracker.peer_db.get(&stale_peer.node_key).is_none(),
3145            "the peer presenting the rotated-away key is dropped (Go tkaFilterNetmapLocked)"
3146        );
3147    }
3148}
3149
3150#[cfg(test)]
3151mod tsmp_disco_key_tests {
3152    //! Receive side of the TSMP disco-key advertisement, at the point the key is *learned*.
3153    //!
3154    //! These exercise [`PeerTracker::learn_disco_key`] — the fork's stand-in for Go
3155    //! `magicsock.Conn.HandleDiscoKeyAdvertisement` — which is the single place an advertisement
3156    //! reaches peer state. The wire decode and the "consumed, not delivered" drop are covered in
3157    //! `ts_packet::tsmp` and `ts_dataplane` respectively.
3158
3159    use ts_keys::DiscoPublicKey;
3160
3161    use super::{
3162        tka_tests::{peer_node, test_env},
3163        *,
3164    };
3165
3166    /// The key a peer advertises, and a second one for the re-advertise case.
3167    const ADVERTISED: [u8; 32] = [0xa5u8; 32];
3168    const READVERTISED: [u8; 32] = [0x5au8; 32];
3169    /// The (staler) key control has for that same peer, and the one control eventually catches up
3170    /// to.
3171    const FROM_CONTROL: [u8; 32] = [0xc0u8; 32];
3172    const CONTROL_CAUGHT_UP: [u8; 32] = [0x0cu8; 32];
3173
3174    /// The node key of the single peer these tests use.
3175    const PEER_NODE_KEY: [u8; 32] = [1u8; 32];
3176
3177    /// A tracker holding one peer with no disco key yet, plus that peer's [`PeerId`].
3178    fn tracker_with_peer() -> (PeerTracker, PeerId) {
3179        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3180        let node = peer_node("peer", PEER_NODE_KEY, Vec::new());
3181        let id = tracker.peer_db.upsert(&node);
3182        (tracker, id)
3183    }
3184
3185    /// The peer as CONTROL describes it: the same node, carrying whatever disco key the netmap says
3186    /// it has (`None` for a peer control has no disco key for at all).
3187    fn node_from_control(disco_key: Option<[u8; 32]>) -> Node {
3188        let mut node = peer_node("peer", PEER_NODE_KEY, Vec::new());
3189        node.disco_key = disco_key.map(DiscoPublicKey::from);
3190        node
3191    }
3192
3193    /// A netmap `Full` carrying just this peer, as control currently describes it.
3194    fn control_full(disco_key: Option<[u8; 32]>) -> ts_control::PeerUpdate {
3195        ts_control::PeerUpdate::Full(vec![node_from_control(disco_key)])
3196    }
3197
3198    /// A tracker whose single peer arrived through the netmap carrying `disco_key`, exactly as the
3199    /// actor's handler applies it. Returns the peer's [`PeerId`] too.
3200    fn tracker_with_control_peer(disco_key: Option<[u8; 32]>) -> (PeerTracker, PeerId) {
3201        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3202        let node = node_from_control(disco_key);
3203        tracker.apply_peer_update(&control_full(disco_key));
3204        let id = tracker
3205            .peer_db
3206            .has(&node.node_key)
3207            .expect("control delivered it");
3208        (tracker, id)
3209    }
3210
3211    /// The disco key the peer db currently holds for `peer` — the effective key every direct-path
3212    /// consumer resolves against.
3213    fn effective_key(tracker: &PeerTracker, peer: PeerId) -> Option<DiscoPublicKey> {
3214        tracker
3215            .peer_db
3216            .get(&peer)
3217            .expect("peer still present")
3218            .1
3219            .disco_key
3220    }
3221
3222    /// The happy path: an advertised key is applied to the peer AND lands in the disco index, which
3223    /// is what the direct-path machinery (`direct::DiscoPeerLookup`) reads. Re-advertising the same
3224    /// key is a no-op; advertising a different one replaces it, retracting the old index entry.
3225    #[tokio::test]
3226    async fn advertisement_learns_the_peers_disco_key() {
3227        let (mut tracker, peer) = tracker_with_peer();
3228        let key = DiscoPublicKey::from(ADVERTISED);
3229
3230        assert!(
3231            tracker.learn_disco_key(peer, key),
3232            "a first advertisement changes the peer db"
3233        );
3234        assert_eq!(
3235            tracker
3236                .peer_db
3237                .get(&peer)
3238                .expect("peer still present")
3239                .1
3240                .disco_key,
3241            Some(key),
3242            "the advertised disco key is learned"
3243        );
3244        assert_eq!(
3245            tracker.peer_db.has(&key),
3246            Some(peer),
3247            "and is reachable through the disco index the direct path resolves against"
3248        );
3249
3250        assert!(
3251            !tracker.learn_disco_key(peer, key),
3252            "re-advertising the same key is a no-op (Go counts it 'unchanged' and returns)"
3253        );
3254
3255        let rotated = DiscoPublicKey::from(READVERTISED);
3256        assert!(tracker.learn_disco_key(peer, rotated));
3257        assert_eq!(
3258            tracker
3259                .peer_db
3260                .get(&peer)
3261                .expect("peer still present")
3262                .1
3263                .disco_key,
3264            Some(rotated),
3265            "a later advertisement replaces the key without a netmap update"
3266        );
3267        assert_eq!(tracker.peer_db.has(&rotated), Some(peer));
3268        assert_eq!(
3269            tracker.peer_db.has(&key),
3270            None,
3271            "the superseded key no longer resolves to the peer"
3272        );
3273    }
3274
3275    /// The refusals, each of which must leave the peer db untouched: the zero key is never learned,
3276    /// and an advertisement never creates a peer.
3277    #[tokio::test]
3278    async fn refused_advertisements_change_nothing() {
3279        let (mut tracker, peer) = tracker_with_peer();
3280
3281        assert!(
3282            !tracker.learn_disco_key(peer, DiscoPublicKey::from([0u8; 32])),
3283            "the zero key is never learned"
3284        );
3285        assert_eq!(
3286            tracker
3287                .peer_db
3288                .get(&peer)
3289                .expect("peer still present")
3290                .1
3291                .disco_key,
3292            None,
3293            "a zero-key advertisement must not bind the peer to an unusable key"
3294        );
3295
3296        // An advertisement for a peer control has never told us about. Go logs "endpoint not found
3297        // for node" and returns; it must not conjure a peer into existence.
3298        let unknown = PeerId(4242);
3299        assert_eq!(tracker.peer_db.get(&unknown), None, "precondition");
3300        assert!(
3301            !tracker.learn_disco_key(unknown, DiscoPublicKey::from(ADVERTISED)),
3302            "an advertisement for an unknown peer is ignored"
3303        );
3304        assert_eq!(
3305            tracker.peer_db.peers().len(),
3306            1,
3307            "an advertisement never creates a peer — only control does"
3308        );
3309        assert_eq!(
3310            tracker.peer_db.has(&DiscoPublicKey::from(ADVERTISED)),
3311            None,
3312            "and never indexes a key against a peer that does not exist"
3313        );
3314    }
3315
3316    /// The feature's motivating case, end to end: the peer told us a key control has not caught up
3317    /// with, and then control polls again with the SAME stale key it had before. The advertisement
3318    /// must survive.
3319    ///
3320    /// Go keeps the two keys apart on the endpoint (`endpointDisco.controlKey` /
3321    /// `tsmpKey`), and `updateFromNode` only rewrites the control side when control's key actually
3322    /// changed — so a netmap restating the old key never touches the active TSMP key. With a single
3323    /// field the next map poll silently reverted the peer to control's stale key, which is precisely
3324    /// the state the advertisement exists to escape.
3325    #[tokio::test]
3326    async fn netmap_restating_controls_stale_key_keeps_the_tsmp_key() {
3327        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
3328        let advertised = DiscoPublicKey::from(ADVERTISED);
3329        assert_eq!(
3330            effective_key(&tracker, peer),
3331            Some(DiscoPublicKey::from(FROM_CONTROL)),
3332            "precondition: the peer starts on the key control gave us"
3333        );
3334
3335        assert!(tracker.learn_disco_key(peer, advertised));
3336        assert_eq!(effective_key(&tracker, peer), Some(advertised));
3337
3338        // Control polls again, still behind: a `Full` resync, then a `Delta` re-upsert, both
3339        // carrying the key control already sent.
3340        tracker.apply_peer_update(&control_full(Some(FROM_CONTROL)));
3341        assert_eq!(
3342            effective_key(&tracker, peer),
3343            Some(advertised),
3344            "a Full restating control's stale key must not undo the TSMP-learned key"
3345        );
3346        tracker.apply_peer_update(&ts_control::PeerUpdate::Delta {
3347            upsert: vec![node_from_control(Some(FROM_CONTROL))],
3348            remove: vec![],
3349        });
3350        assert_eq!(
3351            effective_key(&tracker, peer),
3352            Some(advertised),
3353            "and neither must a Delta re-upsert of the same node"
3354        );
3355        assert_eq!(
3356            tracker.peer_db.has(&advertised),
3357            Some(peer),
3358            "the direct path still resolves the peer by the key it advertised"
3359        );
3360        assert_eq!(
3361            tracker.peer_db.has(&DiscoPublicKey::from(FROM_CONTROL)),
3362            None,
3363            "and control's superseded key does not resolve to it"
3364        );
3365
3366        // Control finally changes its mind. The new key is recorded in control's slot, but the key
3367        // the peer itself told us stays active — upstream returns to control's key only when disco
3368        // is received under it (`endpoint.checkAndUpdateDiscoKey`).
3369        tracker.apply_peer_update(&control_full(Some(CONTROL_CAUGHT_UP)));
3370        assert_eq!(
3371            effective_key(&tracker, peer),
3372            Some(advertised),
3373            "a control-side key change must not preempt an active TSMP-learned key"
3374        );
3375        assert_eq!(
3376            tracker.control_disco_key(&PEER_NODE_KEY.into()),
3377            Some(DiscoPublicKey::from(CONTROL_CAUGHT_UP)),
3378            "but control's new key IS recorded in control's slot"
3379        );
3380    }
3381
3382    /// An advertisement that merely restates the key control already gave us is still *new*
3383    /// information — it is the peer itself confirming the key — so Go records it as the TSMP key and
3384    /// makes it active. Its "unchanged" early return compares `epDisco.keyFromTSMP()`, the
3385    /// TSMP-learned key specifically, never the effective one.
3386    ///
3387    /// The observable consequence, asserted here: once the peer has confirmed the key, control
3388    /// dropping it (a netmap node with no disco key) leaves the confirmed key in place instead of
3389    /// blinding the direct path.
3390    #[tokio::test]
3391    async fn advertisement_restating_controls_key_is_recorded_as_the_tsmp_key() {
3392        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
3393        let key = DiscoPublicKey::from(FROM_CONTROL);
3394
3395        assert!(
3396            tracker.learn_disco_key(peer, key),
3397            "an advertisement of the key control already sent is recorded, not dropped"
3398        );
3399        assert_eq!(
3400            tracker
3401                .endpoint_disco
3402                .get(&PEER_NODE_KEY.into())
3403                .and_then(EndpointDisco::key_from_tsmp),
3404            Some(key),
3405            "it lands in the TSMP slot (Go epDisco.tsmpKey), not only in control's"
3406        );
3407        assert!(
3408            !tracker.learn_disco_key(peer, key),
3409            "re-advertising it now IS unchanged, and is refused"
3410        );
3411
3412        // Control drops the peer's disco key. The key the peer itself confirmed stays active.
3413        tracker.apply_peer_update(&control_full(None));
3414        assert_eq!(
3415            effective_key(&tracker, peer),
3416            Some(key),
3417            "a control key going away hands the active slot to the TSMP-learned key"
3418        );
3419        assert_eq!(tracker.peer_db.has(&key), Some(peer));
3420    }
3421
3422    /// A `PeersChangedPatch` is a control write like any other: one that says nothing about the
3423    /// disco key must leave an active TSMP key alone, and one that carries a new key is control
3424    /// catching up, so it wins.
3425    ///
3426    /// The patch path is the subtle one — it starts from the db node, which carries the *effective*
3427    /// key, so without re-deriving what control last said it would hand the TSMP key back as if
3428    /// control had sent it.
3429    #[tokio::test]
3430    async fn patch_without_a_disco_key_leaves_the_tsmp_key_active() {
3431        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
3432        let advertised = DiscoPublicKey::from(ADVERTISED);
3433        assert!(tracker.learn_disco_key(peer, advertised));
3434
3435        // A reachability-only patch (the idle-peer-reconnect case) for the same node.
3436        let endpoint: std::net::SocketAddr = "203.0.113.9:41641".parse().unwrap();
3437        let mut patch = ts_control::PeerChange {
3438            id: 1,
3439            derp_region: None,
3440            cap: None,
3441            cap_map: None,
3442            underlay_addresses: Some(vec![endpoint]),
3443            node_key: None,
3444            key_signature: None,
3445            disco_key: None,
3446            node_key_expiry: None,
3447            online: None,
3448            last_seen: None,
3449        };
3450        tracker.apply_peer_patches(std::slice::from_ref(&patch));
3451        assert_eq!(
3452            effective_key(&tracker, peer),
3453            Some(advertised),
3454            "a patch that never mentions the disco key must not revert it to control's"
3455        );
3456        assert_eq!(
3457            tracker
3458                .peer_db
3459                .get(&peer)
3460                .expect("peer still present")
3461                .1
3462                .underlay_addresses,
3463            vec![endpoint],
3464            "and the patch it DID carry still applied"
3465        );
3466
3467        // Now control changes the key through the patch channel. Same rule as the netmap path: the
3468        // key lands in control's slot, and the active TSMP key is left alone.
3469        patch.disco_key = Some(DiscoPublicKey::from(CONTROL_CAUGHT_UP));
3470        tracker.apply_peer_patches(std::slice::from_ref(&patch));
3471        assert_eq!(
3472            effective_key(&tracker, peer),
3473            Some(advertised),
3474            "a patch carrying a new disco key does not preempt the active TSMP-learned key either"
3475        );
3476        assert_eq!(
3477            tracker.control_disco_key(&PEER_NODE_KEY.into()),
3478            Some(DiscoPublicKey::from(CONTROL_CAUGHT_UP)),
3479            "the patched key is still recorded as what control now says"
3480        );
3481    }
3482
3483    /// The rule this whole pair of slots exists to express: once the peer has told us its key over
3484    /// TSMP, control changing its mind is *recorded* but does not take the active slot back — Go
3485    /// `endpoint.updateDiscoKey`'s `epDisco.tsmpActive = old.tsmpActive || key.IsZero()`.
3486    ///
3487    /// Control is the slower source; a key the peer sent us itself is the better evidence. Upstream
3488    /// hands the slot back only when disco is actually *received* under control's key
3489    /// (`endpoint.checkAndUpdateDiscoKey`). Here the peer re-advertising is the path back, and it is
3490    /// asserted at the end so the sticky rule cannot be read as "the TSMP key is now permanent".
3491    #[tokio::test]
3492    async fn a_control_key_change_does_not_preempt_an_active_tsmp_key() {
3493        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
3494        let advertised = DiscoPublicKey::from(ADVERTISED);
3495        let caught_up = DiscoPublicKey::from(CONTROL_CAUGHT_UP);
3496        assert!(tracker.learn_disco_key(peer, advertised));
3497
3498        tracker.apply_peer_update(&control_full(Some(CONTROL_CAUGHT_UP)));
3499        assert_eq!(
3500            effective_key(&tracker, peer),
3501            Some(advertised),
3502            "the TSMP-learned key stays active across a control-side change"
3503        );
3504        assert_eq!(
3505            tracker.peer_db.has(&advertised),
3506            Some(peer),
3507            "so the direct path still resolves the peer by the key it advertised"
3508        );
3509        assert_eq!(
3510            tracker.peer_db.has(&caught_up),
3511            None,
3512            "and control's new key is not what we send to"
3513        );
3514        assert_eq!(
3515            tracker.control_disco_key(&PEER_NODE_KEY.into()),
3516            Some(caught_up),
3517            "control's new key is recorded all the same — it is not discarded, just not active"
3518        );
3519
3520        // Control changing its mind a second time, and then dropping the key entirely, changes
3521        // nothing about which key is active.
3522        tracker.apply_peer_update(&control_full(Some(FROM_CONTROL)));
3523        tracker.apply_peer_update(&control_full(None));
3524        assert_eq!(
3525            effective_key(&tracker, peer),
3526            Some(advertised),
3527            "neither a second control change nor control dropping the key moves the active slot"
3528        );
3529
3530        // The peer itself is what moves it: it advertises the key control had been trying to give
3531        // us, and that advertisement is what we act on.
3532        assert!(tracker.learn_disco_key(peer, caught_up));
3533        assert_eq!(
3534            effective_key(&tracker, peer),
3535            Some(caught_up),
3536            "a peer re-advertising moves the active key, because the peer is the evidence"
3537        );
3538    }
3539
3540    /// The sticky flag must not strand a peer that never had a TSMP key: control sending nothing
3541    /// leaves no key material at all, and the key control sends next must become the active one.
3542    ///
3543    /// This is the case Go covers by nil-ing the endpoint's `disco` pointer when both keys are
3544    /// zero; here [`PeerTracker::upsert_from_control`] drops the entry, so the "no control key means
3545    /// the TSMP slot is active" flag cannot survive to shadow a later control key with nothing.
3546    #[tokio::test]
3547    async fn a_first_control_key_is_active_even_after_control_sent_none() {
3548        let (mut tracker, peer) = tracker_with_control_peer(None);
3549        assert_eq!(effective_key(&tracker, peer), None, "precondition");
3550        assert!(
3551            tracker.endpoint_disco.is_empty(),
3552            "a peer with no key material from either source costs no entry"
3553        );
3554
3555        tracker.apply_peer_update(&control_full(Some(FROM_CONTROL)));
3556        assert_eq!(
3557            effective_key(&tracker, peer),
3558            Some(DiscoPublicKey::from(FROM_CONTROL)),
3559            "control's first key is active — there is no TSMP key for it to defer to"
3560        );
3561        assert_eq!(
3562            tracker.peer_db.has(&DiscoPublicKey::from(FROM_CONTROL)),
3563            Some(peer)
3564        );
3565    }
3566
3567    /// The TSMP-learned key lives exactly as long as Go's endpoint does: it is dropped when the peer
3568    /// leaves the netmap, and it is not carried across a node-key rotation (Go builds the rotated
3569    /// peer a brand-new endpoint, with a brand-new `endpointDisco`).
3570    #[tokio::test]
3571    async fn tsmp_key_does_not_outlive_the_peer_or_its_node_key() {
3572        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
3573        assert!(tracker.learn_disco_key(peer, DiscoPublicKey::from(ADVERTISED)));
3574
3575        // The peer leaves the netmap, then comes back on control's key.
3576        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![]));
3577        assert!(tracker.peer_db.peers().is_empty());
3578        assert!(
3579            tracker.endpoint_disco.is_empty(),
3580            "the departed peer's disco state goes with it"
3581        );
3582        tracker.apply_peer_update(&control_full(Some(FROM_CONTROL)));
3583        let readded = node_from_control(Some(FROM_CONTROL));
3584        let peer = tracker.peer_db.has(&readded.node_key).expect("re-added");
3585        assert_eq!(
3586            effective_key(&tracker, peer),
3587            Some(DiscoPublicKey::from(FROM_CONTROL)),
3588            "a peer that left and rejoined starts from control's key again"
3589        );
3590
3591        // Learn a key again, then rotate the node key underneath it.
3592        assert!(tracker.learn_disco_key(peer, DiscoPublicKey::from(READVERTISED)));
3593        let mut rotated = node_from_control(Some(FROM_CONTROL));
3594        rotated.node_key = [2u8; 32].into();
3595        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![rotated.clone()]));
3596        let peer = tracker
3597            .peer_db
3598            .has(&rotated.node_key)
3599            .expect("rotated peer");
3600        assert_eq!(
3601            effective_key(&tracker, peer),
3602            Some(DiscoPublicKey::from(FROM_CONTROL)),
3603            "a key learned under the old node key is not carried onto the new one"
3604        );
3605        assert_eq!(
3606            tracker.endpoint_disco.len(),
3607            1,
3608            "and the old node key's state is pruned"
3609        );
3610    }
3611
3612    /// How the peer db resolves `key` for an inbound disco frame: the peer it belongs to and which
3613    /// of that peer's two slots it matched.
3614    fn ingress_match(
3615        tracker: &PeerTracker,
3616        key: DiscoPublicKey,
3617    ) -> Option<(PeerId, peer_db::DiscoKeyMatch)> {
3618        tracker
3619            .peer_db
3620            .peer_by_known_disco_key(&key)
3621            .map(|(id, _node, matched)| (id, matched))
3622    }
3623
3624    /// The bead's case, end to end: the peer advertised K2 over TSMP so we send to K2, but it is
3625    /// still sending disco under the K1 control gave us. That frame must resolve to the peer, and
3626    /// receiving under K1 must make K1 the key we send to — because it is demonstrably what the
3627    /// peer uses.
3628    ///
3629    /// Go: every inbound disco comparison goes through `endpoint.checkAndUpdateDiscoKey`, which
3630    /// accepts either slot and compare-and-swaps `tsmpActive` when the key seen is the inactive one.
3631    #[tokio::test]
3632    async fn disco_under_the_inactive_key_is_accepted_and_makes_that_key_active() {
3633        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
3634        let from_control = DiscoPublicKey::from(FROM_CONTROL);
3635        let advertised = DiscoPublicKey::from(ADVERTISED);
3636
3637        assert!(tracker.learn_disco_key(peer, advertised));
3638        assert_eq!(
3639            effective_key(&tracker, peer),
3640            Some(advertised),
3641            "precondition: we are sending to the TSMP-learned key"
3642        );
3643        assert_eq!(
3644            ingress_match(&tracker, from_control),
3645            Some((peer, peer_db::DiscoKeyMatch::Inactive)),
3646            "control's key is still the peer's other known key, and still resolves on ingress"
3647        );
3648
3649        // Disco arrives under control's key: accepted, and it becomes the active one.
3650        assert!(
3651            tracker.observe_disco_key(peer, from_control),
3652            "receiving under the inactive key switches the active key"
3653        );
3654        assert_eq!(
3655            effective_key(&tracker, peer),
3656            Some(from_control),
3657            "we now send to the key the peer is demonstrably using"
3658        );
3659        assert_eq!(
3660            tracker.peer_db.has(&from_control),
3661            Some(peer),
3662            "and it is the key the send-side disco index carries"
3663        );
3664        assert_eq!(
3665            ingress_match(&tracker, from_control),
3666            Some((peer, peer_db::DiscoKeyMatch::Active))
3667        );
3668        assert_eq!(
3669            ingress_match(&tracker, advertised),
3670            Some((peer, peer_db::DiscoKeyMatch::Inactive)),
3671            "the TSMP key is retained in the other slot, so ingress under it still resolves"
3672        );
3673
3674        assert!(
3675            !tracker.observe_disco_key(peer, from_control),
3676            "a second frame under the now-active key changes nothing (and forces no republish)"
3677        );
3678
3679        // And it switches back: the peer resumes sending under the key it advertised.
3680        assert!(tracker.observe_disco_key(peer, advertised));
3681        assert_eq!(effective_key(&tracker, peer), Some(advertised));
3682        assert_eq!(
3683            ingress_match(&tracker, from_control),
3684            Some((peer, peer_db::DiscoKeyMatch::Inactive))
3685        );
3686    }
3687
3688    /// The refusal that is the whole security value of the check: a key belonging to NEITHER slot
3689    /// is rejected, leaving the peer on the key it was on. Plus the two other refusals Go has —
3690    /// an unknown peer, and a peer with no disco key material at all (`epDisco == nil`).
3691    #[tokio::test]
3692    async fn disco_under_a_key_in_neither_slot_is_refused() {
3693        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
3694        let from_control = DiscoPublicKey::from(FROM_CONTROL);
3695        let advertised = DiscoPublicKey::from(ADVERTISED);
3696        let third = DiscoPublicKey::from(READVERTISED);
3697
3698        assert!(tracker.learn_disco_key(peer, advertised));
3699
3700        assert!(
3701            !tracker.observe_disco_key(peer, third),
3702            "a third key is refused: a peer must not move itself onto a key nobody told us about"
3703        );
3704        assert_eq!(
3705            effective_key(&tracker, peer),
3706            Some(advertised),
3707            "and the peer stays on the key it was on"
3708        );
3709        assert_eq!(
3710            ingress_match(&tracker, third),
3711            None,
3712            "the refused key never becomes resolvable"
3713        );
3714        assert_eq!(
3715            ingress_match(&tracker, from_control),
3716            Some((peer, peer_db::DiscoKeyMatch::Inactive)),
3717            "the two real slots are untouched"
3718        );
3719
3720        // An unknown peer: like a TSMP advertisement, this never creates one.
3721        assert!(!tracker.observe_disco_key(PeerId(4242), from_control));
3722        assert_eq!(tracker.peer_db.peers().len(), 1);
3723
3724        // A peer with no disco key from either source — Go returns false on `epDisco == nil`.
3725        let (mut bare, bare_peer) = tracker_with_control_peer(None);
3726        assert_eq!(effective_key(&bare, bare_peer), None, "precondition");
3727        assert!(
3728            !bare.observe_disco_key(bare_peer, from_control),
3729            "a peer with no known disco key has no slot for this key to match"
3730        );
3731        assert_eq!(effective_key(&bare, bare_peer), None);
3732    }
3733
3734    /// A peer that has only ever had one key registers no inactive key at all, so the second index
3735    /// stays empty and an inbound frame under any other key is refused.
3736    #[tokio::test]
3737    async fn a_single_key_peer_has_no_second_slot() {
3738        let (tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
3739        let from_control = DiscoPublicKey::from(FROM_CONTROL);
3740
3741        assert_eq!(
3742            ingress_match(&tracker, from_control),
3743            Some((peer, peer_db::DiscoKeyMatch::Active))
3744        );
3745        assert_eq!(
3746            ingress_match(&tracker, DiscoPublicKey::from(ADVERTISED)),
3747            None,
3748            "no second key was ever learned, so nothing else resolves to this peer"
3749        );
3750    }
3751
3752    /// An advertisement that merely restates control's key must not leave the peer with the same
3753    /// key in both slots pretending to be two — `inactive_key` reports `None` when the inactive
3754    /// slot holds the active key, so ingress sees exactly one key.
3755    #[tokio::test]
3756    async fn the_same_key_in_both_slots_is_one_key() {
3757        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
3758        let from_control = DiscoPublicKey::from(FROM_CONTROL);
3759
3760        assert!(tracker.learn_disco_key(peer, from_control));
3761        assert_eq!(
3762            tracker
3763                .endpoint_disco
3764                .get(&PEER_NODE_KEY.into())
3765                .and_then(EndpointDisco::inactive_key),
3766            None,
3767            "both slots hold the same key, so there is no second key"
3768        );
3769        assert_eq!(
3770            ingress_match(&tracker, from_control),
3771            Some((peer, peer_db::DiscoKeyMatch::Active))
3772        );
3773        assert!(
3774            !tracker.observe_disco_key(peer, from_control),
3775            "and receiving under it is a no-op, not a switch"
3776        );
3777    }
3778
3779    /// A peer that leaves the netmap takes BOTH its keys with it: the inactive-key index must not
3780    /// keep attributing frames to a peer that is gone.
3781    #[tokio::test]
3782    async fn a_departed_peer_stops_resolving_under_either_key() {
3783        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
3784        let advertised = DiscoPublicKey::from(ADVERTISED);
3785        assert!(tracker.learn_disco_key(peer, advertised));
3786        assert!(ingress_match(&tracker, DiscoPublicKey::from(FROM_CONTROL)).is_some());
3787
3788        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![]));
3789        assert_eq!(ingress_match(&tracker, advertised), None);
3790        assert_eq!(
3791            ingress_match(&tracker, DiscoPublicKey::from(FROM_CONTROL)),
3792            None,
3793            "the inactive key is retracted with the peer, not left dangling"
3794        );
3795    }
3796}