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::{ExpiryManager, 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 local wall clock as a UTC timestamp.
41///
42/// chrono is built without its `clock` feature in this workspace, so derive it from `SystemTime`
43/// the same way the control runner and the ssh-policy paths do. A clock before the Unix epoch
44/// (unrepresentable) falls back to the epoch itself, which the expiry pass then refuses as being
45/// before its hardcoded epoch — fail-safe: flag nothing rather than expire everything.
46fn local_now() -> chrono::DateTime<chrono::Utc> {
47    std::time::SystemTime::now()
48        .duration_since(std::time::UNIX_EPOCH)
49        .ok()
50        .and_then(|d| chrono::DateTime::from_timestamp(d.as_secs() as i64, d.subsec_nanos()))
51        .unwrap_or_default()
52}
53
54/// The two disco keys a peer can present, and which of them is currently active — Go
55/// [`magicsock.endpointDisco`] (`wgengine/magicsock/endpoint.go`).
56///
57/// A peer's disco key reaches us from two independent sources: **control**, in a netmap node or a
58/// `PeersChangedPatch`, and the **peer itself**, in a TSMP disco-key advertisement carried inside
59/// the WireGuard tunnel. Go keeps both side by side on the endpoint, and so do we, because control
60/// is the slower of the two: an advertisement exists precisely to cover the window where control has
61/// not caught up with the peer's current key, so collapsing the two into one field would let the
62/// next map poll overwrite a freshly-learned key with control's stale one — losing the feature's own
63/// motivating case.
64///
65/// Only one key is active for sending at a time ([`key`](Self::key)). That active key is what the
66/// peer db carries in [`Node::disco_key`], which is this fork's live lookup for every direct-path
67/// consumer (`direct::DiscoPeerLookup` resolves against it, and `PeerDb`'s disco index is built from
68/// it) — the stand-in for Go's per-endpoint `disco` pointer.
69///
70/// [`magicsock.endpointDisco`]: https://github.com/tailscale/tailscale/blob/49e148c4a30b4f8098f69468fd27a7021d85ea02/wgengine/magicsock/endpoint.go
71#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
72struct EndpointDisco {
73    /// The key learned from control (Go `endpointDisco.controlKey`).
74    control: Option<DiscoPublicKey>,
75    /// The key learned from a TSMP advertisement (Go `endpointDisco.tsmpKey`).
76    tsmp: Option<DiscoPublicKey>,
77    /// Whether [`tsmp`](Self::tsmp) is the active key (Go `endpointDisco.tsmpActive`).
78    tsmp_active: bool,
79}
80
81impl EndpointDisco {
82    /// The key currently regarded as active — Go `endpointDisco.key()`.
83    fn key(&self) -> Option<DiscoPublicKey> {
84        if self.tsmp_active {
85            self.tsmp
86        } else {
87            self.control
88        }
89    }
90
91    /// The control-learned key, active or not — Go `endpointDisco.keyFromControl()`.
92    fn key_from_control(&self) -> Option<DiscoPublicKey> {
93        self.control
94    }
95
96    /// The TSMP-learned key, active or not — Go `endpointDisco.keyFromTSMP()`.
97    fn key_from_tsmp(&self) -> Option<DiscoPublicKey> {
98        self.tsmp
99    }
100
101    /// Replace the control-learned key, leaving any TSMP-learned key in place — Go
102    /// [`endpoint.updateDiscoKey`].
103    ///
104    /// Control's key is always recorded in control's own slot, but it takes the *active* slot only
105    /// if no TSMP-learned key already holds it: Go `epDisco.tsmpActive = old.tsmpActive ||
106    /// key.IsZero()`. A key the peer told us itself is better evidence than a control server that
107    /// is, by construction, the slower of the two sources — so control changing its mind no longer
108    /// preempts an active TSMP key. Upstream returns to control's key when disco is actually
109    /// *received* under it (`endpoint.checkAndUpdateDiscoKey`), not when control asserts it.
110    ///
111    /// An absent (Go: zero) control key still hands the slot to the TSMP key, if there is one. When
112    /// there is neither key, the caller drops the whole entry ([`is_empty`](Self::is_empty)) — which
113    /// is what stops an active TSMP slot with no TSMP key in it outliving this call, exactly as Go
114    /// nils the endpoint's `disco` pointer in the same case.
115    ///
116    /// [`endpoint.updateDiscoKey`]: https://github.com/tailscale/tailscale/blob/9ea7cba44591e0cd840c6c94d23274dd222059bf/wgengine/magicsock/endpoint.go
117    fn update_from_control(&mut self, key: Option<DiscoPublicKey>) {
118        self.control = key;
119        self.tsmp_active = self.tsmp_active || key.is_none();
120    }
121
122    /// Replace the TSMP-learned key, leaving the control-learned key in place — Go
123    /// `endpoint.updateTSMPDiscoKey`.
124    fn update_from_tsmp(&mut self, key: Option<DiscoPublicKey>) {
125        self.tsmp = key;
126        self.tsmp_active = key.is_some();
127    }
128
129    /// The peer's other known key: the slot that is not active, when it holds a key that differs
130    /// from the active one.
131    ///
132    /// This is what makes ingress under the peer's *other* key resolvable
133    /// ([`PeerDb::set_inactive_disco_key`]). `None` when the inactive slot is empty or holds the
134    /// same key as the active one — there is no second key to accept in either case.
135    fn inactive_key(&self) -> Option<DiscoPublicKey> {
136        let inactive = if self.tsmp_active {
137            self.control
138        } else {
139            self.tsmp
140        };
141
142        inactive.filter(|k| Some(*k) != self.key())
143    }
144
145    /// Accept `key` as this peer's, switching the active slot to it when it is the currently
146    /// *inactive* one — Go [`endpoint.checkAndUpdateDiscoKey`].
147    ///
148    /// Called with the sender key of a disco frame we have opened, which proves the sender holds
149    /// that key's private half. Receiving under a key is therefore demonstrative: it is what the
150    /// peer is actually using, so upstream makes it the key we send to as well.
151    ///
152    /// Returns `None` when `key` belongs to **neither** slot — the refusal that is the whole
153    /// security value of the check, and the reason this is not simply "trust whatever key opened".
154    /// Otherwise `Some(changed)`, where `changed` reports whether the active key moved (and so
155    /// whether the direct path built under the old one has to be invalidated).
156    ///
157    /// [`endpoint.checkAndUpdateDiscoKey`]: https://github.com/tailscale/tailscale/blob/9ea7cba44591e0cd840c6c94d23274dd222059bf/wgengine/magicsock/endpoint.go
158    fn check_and_update(&mut self, key: DiscoPublicKey) -> Option<bool> {
159        if self.key() == Some(key) {
160            return Some(false);
161        }
162
163        // Not the active key. Go's compare-and-swap on `tsmpActive`: whichever slot holds it
164        // becomes the active one. Control's slot is tried first only for determinism — the two
165        // holding the same key is already handled by the equality check above.
166        if self.control == Some(key) {
167            self.tsmp_active = false;
168            return Some(true);
169        }
170        if self.tsmp == Some(key) {
171            self.tsmp_active = true;
172            return Some(true);
173        }
174
175        None
176    }
177
178    /// No key material from either source — Go nils out the endpoint's `disco` pointer here.
179    fn is_empty(&self) -> bool {
180        self.control.is_none() && self.tsmp.is_none()
181    }
182}
183
184/// Actor that tracks peer delta updates and emits new states.
185pub struct PeerTracker {
186    peer_db: PeerDb,
187    seen_state_update: bool,
188    pending_requests: Vec<Pending>,
189    /// Latest peer snapshot, published on every netmap update so embedders can watch for peer
190    /// changes ([`WatchNetmap`]).
191    peer_watch: watch::Sender<Vec<StatusNode>>,
192    /// Accumulated netmap user profiles (`MapResponse.UserProfiles`), keyed by user id, joined
193    /// against a node's [`Node::user_id`](ts_control::Node::user_id) to resolve the owning user's
194    /// login/display name for a [`WhoIs`](crate::status::WhoIs). Control sends these incrementally
195    /// (only new/changed profiles per response), so this map **accumulates** across updates rather
196    /// than being replaced — a peer upserted in one response may reference a profile delivered in an
197    /// earlier one.
198    user_profiles: HashMap<UserId, UserProfile>,
199    /// Per-peer disco-key provenance ([`EndpointDisco`]), keyed by the peer's node key.
200    ///
201    /// Go keeps this on the magicsock `endpoint`, which the peer map keys by node key; here the peer
202    /// db stores control's [`Node`] verbatim, so the second key (and which of the two is active)
203    /// lives beside it. Keying by node key reproduces Go's lifetime exactly: the state is dropped
204    /// when the peer leaves the netmap, and a peer that ROTATES its node key gets a fresh entry —
205    /// Go builds it a new endpoint, so a key learned over TSMP under the old node key is never
206    /// carried onto the new one. [`prune_endpoint_disco`](PeerTracker::prune_endpoint_disco) does
207    /// the dropping.
208    endpoint_disco: HashMap<NodePublicKey, EndpointDisco>,
209    /// Tailnet-Lock (TKA) authority enforced at the peer-trust chokepoint, matching Go
210    /// `tkaFilterNetmapLocked`. Read on demand from a [`watch`] cell the control runner owns: when it
211    /// holds `Some` (a verified lock has been synced from control), enforcement is **active** — every
212    /// upserted peer must present a `key_signature` this authority authorizes, or it is dropped
213    /// (fail-closed), exactly as Go drops peers with a missing or failing signature. When it holds
214    /// `None` (no lock, or the lock was disabled) enforcement is **inactive** and every peer is
215    /// upserted, identical to pre-TKA behavior and to Go's `b.tka == nil` early return.
216    ///
217    /// A `watch::Receiver` (not the bus) is the transport on purpose: the authority is a single
218    /// security-critical state cell, and `watch` is last-write-wins, never-dropped, and ordered by
219    /// the control runner's own writes — so a disable (`None`) can never be reordered behind or
220    /// silently dropped before a stale `Some` (which a best-effort broadcast bus could do, leaving a
221    /// defunct lock enforcing forever). The control runner is the sole writer; we only ever read.
222    ///
223    /// The authority always passes through `VerifiedAumChain::verify` before the control runner
224    /// publishes it, so enforcement only engages on a chain we have cryptographically verified.
225    /// Connectivity now depends on `ts_tka` verifying genuinely-good signatures correctly (see
226    /// SECURITY.md). Self is structurally never filtered here (the self node never enters `peer_db` —
227    /// it is routed to the control runner's `self_node` cell), so a node cannot lock itself out of
228    /// its own netmap.
229    tka_authority: watch::Receiver<Option<Arc<ts_tka::Authority>>>,
230    /// Node-key expiry enforcement — Go `ipnlocal.expiryManager` (`ipn/ipnlocal/expiry.go`).
231    ///
232    /// Holds the local-to-control clock delta (fed from `MapResponse.ControlTime`) and the set of
233    /// peers already flagged, and is the thing that actually rewrites an expired peer. It lives
234    /// here because the peer db is this fork's netmap: every site that installs a peer goes through
235    /// [`upsert_from_control`](PeerTracker::upsert_from_control), so putting the pass there is what
236    /// makes "no peer is ever installed unflagged" true by construction rather than by review.
237    expiry: ExpiryManager,
238    /// The most recent self node control sent, kept only so it can be folded into
239    /// [`ExpiryManager::next_peer_expiry`] exactly as Go folds in `nm.SelfNode` — this node's own
240    /// key expiry must arm the timer too. Never entered into the peer db (self is not a peer) and
241    /// never flagged here: the self-expiry *decision* is the control runner's (`expiry_action`).
242    self_node: Option<Node>,
243    /// The armed expiry timer — Go `LocalBackend.nmExpiryTimer`.
244    ///
245    /// Sleeps until the soonest future key expiry across the peers and the self node, then sends
246    /// [`ExpiryTimerFired`] so expiry is re-evaluated **when it happens** rather than whenever the
247    /// next netmap arrives. Re-armed (and the old one aborted) after every netmap and after every
248    /// firing. Aborting rather than letting a stale timer run is this fork's equivalent of Go's
249    /// `numClientStatusCalls` generation check.
250    expiry_timer: Option<tokio::task::JoinHandle<()>>,
251    env: Env,
252}
253
254impl PeerTracker {
255    fn peer_by_name_opt(&self, name: &str) -> Option<&Node> {
256        // Canonicalization (case + trailing dot) is handled inside the name index lookup.
257        self.peer_db.get(&name).map(|(_id, node)| node)
258    }
259
260    fn peer_by_tailnet_ip_opt(&self, ip: IpAddr) -> Option<&Node> {
261        self.peer_db.get(&ip).map(|(_id, node)| node)
262    }
263
264    /// Build the peer entries for a [`Status`](crate::Status) snapshot from the current peer db.
265    ///
266    /// Connectivity fields (`cur_addr`/`relay`) are left at their `from_node` defaults (`None`) here:
267    /// this is the live-watch/hot path and must stay magicsock-free and synchronous. The explicit
268    /// [`GetStatus`] snapshot enriches them ([`status_peers_with_ids`](Self::status_peers_with_ids)).
269    fn status_peers(&self) -> Vec<StatusNode> {
270        self.peer_db
271            .peers()
272            .values()
273            .map(StatusNode::from_node)
274            .collect()
275    }
276
277    /// Like [`status_peers`](Self::status_peers) but pairs each entry with its [`PeerId`], so the
278    /// caller can join per-peer connectivity (the direct manager's `best_addrs`, keyed by `PeerId`)
279    /// onto the `StatusNode` before returning it. Order is unspecified (a `HashMap` walk).
280    fn status_peers_with_ids(&self) -> Vec<(PeerId, StatusNode)> {
281        self.peer_db
282            .peers()
283            .iter()
284            .map(|(id, node)| (*id, StatusNode::from_node(node)))
285            .collect()
286    }
287
288    fn whois_opt(&self, addr: std::net::SocketAddr) -> Option<crate::status::WhoIs> {
289        let ip = crate::status::whois_addr(addr);
290        let node = self.peer_by_tailnet_ip_opt(ip).cloned()?;
291        // Join the node's owning user id against the accumulated UserProfiles table. `None` when
292        // control sent no profile for that user (e.g. tagged nodes with no human owner, or a
293        // profile not yet delivered). The whole profile is handed over, not a flattened label:
294        // `WhoIs` is what an embedder authorises on, and `UserProfile::groups` is the only owner
295        // attribute it cannot re-derive from the netmap itself.
296        let user_profile = self.resolve_user_profile(node.user_id);
297        Some(crate::status::WhoIs::from_node_with_profile(
298            node,
299            user_profile,
300        ))
301    }
302
303    /// Merge a response's `MapResponse.UserProfiles` into the accumulated table, keyed by user id.
304    ///
305    /// Control sends profiles incrementally — only new or changed ones per response — so this
306    /// **accumulates**: a profile already held for a user id that this response does not restate
307    /// stays, and one it does restate is replaced wholesale (control's newer copy wins, including
308    /// a group list that shrank).
309    fn accumulate_user_profiles(&mut self, profiles: &[UserProfile]) {
310        for profile in profiles {
311            self.user_profiles.insert(profile.id, profile.clone());
312        }
313    }
314
315    /// Resolve a user id to its profile from the accumulated profile table.
316    fn resolve_user_profile(&self, user_id: UserId) -> Option<UserProfile> {
317        self.user_profiles.get(&user_id).cloned()
318    }
319
320    /// Whether `node` may be admitted to the peer db under Tailnet Lock, matching Go
321    /// `tkaFilterNetmapLocked`'s per-peer verdict (drop unsigned / failed-signature peers).
322    ///
323    /// This consults the live [`tka_authority`](Self::tka_authority) cell on each call (one `borrow`,
324    /// held only for the duration of the verdict). For a `Full` resync — which checks every peer —
325    /// prefer [`tka_authority_snapshot`](Self::tka_authority_snapshot) +
326    /// [`tka_snapshot_admits`](Self::tka_snapshot_admits) to borrow once and verify each peer a single
327    /// time; this method is the convenience wrapper for the single-peer (`Delta`/patch) sites.
328    ///
329    /// Fail-closed and gated:
330    /// - No authority ⇒ no lock synced ⇒ always admit (Go's `b.tka == nil` early return; identical to
331    ///   pre-TKA behavior).
332    /// - **Empty trusted-key state** ⇒ always admit (logged at `error!` — see
333    ///   [`tka_snapshot_admits`](Self::tka_snapshot_admits) for the full rationale).
334    /// - Authority present + peer carries a `key_signature` the authority authorizes for the peer's
335    ///   node key ⇒ admit.
336    /// - Authority present + signature missing or unauthorized/invalid ⇒ **drop** (Go drops peers
337    ///   with a missing signature or failed `NodeKeyAuthorized` under tailnet lock).
338    fn tka_admits(&self, node: &Node) -> bool {
339        // Single-peer sites (`Delta`/patch) only need the admit bool; the rotation details are used
340        // exclusively by the cross-peer `Full` filter (rotation obsolescence is whole-netmap).
341        Self::tka_snapshot_admits(self.tka_authority.borrow().as_deref(), node).admitted
342    }
343
344    /// Borrow the current TKA authority once (cloning the cheap `Arc`) for a batch verdict. Returns
345    /// `None` when no lock is synced (admit-all). Used by the `Full` path so a netmap of N peers
346    /// reads the cell once and runs at most one signature verify per peer (not two).
347    fn tka_authority_snapshot(&self) -> Option<Arc<ts_tka::Authority>> {
348        self.tka_authority.borrow().clone()
349    }
350
351    /// The per-peer Tailnet-Lock verdict against an already-borrowed `authority` snapshot. Factored
352    /// out so both the single-peer [`tka_admits`](Self::tka_admits) and the `Full` batch path share
353    /// one verdict implementation (no divergence) while the batch path verifies each peer exactly
354    /// once.
355    ///
356    /// Returns whether the peer is admitted AND, for an admitted peer signed by a rotation chain, the
357    /// [`RotationDetails`](ts_tka::RotationDetails) of that chain — so the `Full` path can run the
358    /// cross-peer rotation filter (Go's `rotationTracker`) without a second verify per peer. A peer
359    /// that is dropped, unsigned, or signed by a non-rotation chain carries `rotation == None`.
360    ///
361    /// Never logs key/signature bytes — only the `stable_id` and the `TkaError` Display (static
362    /// descriptors). One documented parity gap remains vs Go (in PARITY_ROADMAP): no
363    /// `UnsignedPeerAPIOnly` *admission* exemption — Go admits such a peer unsigned under an active
364    /// lock, we drop it (stricter, the safe direction). [`Node::unsigned_peer_api_only`] is now
365    /// carried, and the routes half of upstream's treatment is enforced at decode
366    /// (`ts_control::Node`'s `From` impl clamps such a peer's accepted routes to its own addresses,
367    /// unconditionally, whether or not a lock is active); only the admission carve-out is deferred.
368    fn tka_snapshot_admits(authority: Option<&ts_tka::Authority>, node: &Node) -> TkaVerdict {
369        let Some(auth) = authority else {
370            return TkaVerdict::admit();
371        };
372
373        // Brick-guard: an authority with no trusted keys would drop every peer. A verified chain is
374        // structurally guaranteed ≥1 key (genesis rejects an empty key set, and the last key cannot
375        // be removed), so reaching here means a `ts_tka` invariant was violated — admit rather than
376        // black-hole the whole netmap, and log at `error!` because it signals a real bug, not an
377        // expected runtime input. This is OUR fail-safe, not a Go behavior. NOTE: it only catches the
378        // empty-keyset shape; a non-empty authority that authorizes none of the offered peers still
379        // (correctly) drops them — that is what a lock that revoked everyone means. The
380        // "authorized-zero-peers" isolation case is surfaced separately by the caller.
381        if auth.state().keys.is_empty() {
382            tracing::error!(
383                "TKA: authority has an empty trusted-key set (verified chains never do — likely a \
384                 ts_tka bug); not enforcing (admitting all) to avoid isolating the node"
385            );
386            return TkaVerdict::admit();
387        }
388
389        if node.key_signature.is_empty() {
390            tracing::warn!(
391                stable_id = ?node.stable_id,
392                "TKA: dropping unsigned peer under tailnet lock"
393            );
394            return TkaVerdict::drop();
395        }
396
397        match auth.node_key_authorized_with_details(&node.node_key.to_bytes(), &node.key_signature)
398        {
399            Ok(rotation) => {
400                tracing::debug!(stable_id = ?node.stable_id, "TKA: peer node-key authorized");
401                TkaVerdict {
402                    admitted: true,
403                    rotation,
404                }
405            }
406            Err(e) => {
407                tracing::warn!(
408                    stable_id = ?node.stable_id,
409                    error = %e,
410                    "TKA: dropping peer with unauthorized node key"
411                );
412                TkaVerdict::drop()
413            }
414        }
415    }
416
417    /// The **keep** verdict for a whole batch of peers under `authority` — one complete Go
418    /// `tkaFilterNetmapLocked` pass (`ipn/ipnlocal/tailnet-lock.go`, v1.100.0), in Go's order:
419    ///
420    /// 1. the per-peer signature verdict ([`tka_snapshot_admits`](Self::tka_snapshot_admits)), then
421    /// 2. the cross-peer rotation filter (Go `rotationTracker`): a peer presenting a node key that a
422    ///    newer rotation has superseded — or a tied clone of one — is dropped even though its own
423    ///    signature verifies. That is whole-batch by nature (one peer's chain obsoletes another's
424    ///    key), which is why it lives here and not in the per-peer verdict.
425    ///
426    /// Factored out because two call sites must agree exactly on what "admitted" means: the `Full`
427    /// netmap upsert in [`apply_peer_update`](Self::apply_peer_update), and
428    /// [`tka_reevaluate_peer_db`](Self::tka_reevaluate_peer_db), which re-runs the same pass over the
429    /// peers already in the db when a freshly-synced authority is installed. A divergence between
430    /// them would be a peer admitted by one path and dropped by the other.
431    ///
432    /// `authority` is borrowed once and each peer verified exactly once (the ed25519 verify is the
433    /// expensive part). Returns one `bool` per input node, in input order; `None` authority ⇒ all
434    /// `true` (no lock synced ⇒ admit all, Go's `b.tka == nil` early return).
435    ///
436    /// `pub(crate)` for a third caller with the same requirement: the cold-start replay of a cached
437    /// netmap ([`control_runner::load_cached_netmap`](crate::control_runner::load_cached_netmap)),
438    /// which must apply the same pass to the cached peers that the netmap they were cached from
439    /// already went through — Go replays its cached map through `setNetMapLocked`, so it runs this
440    /// very filter.
441    pub(crate) fn tka_keep_verdicts(
442        authority: Option<&ts_tka::Authority>,
443        nodes: &[&Node],
444    ) -> Vec<bool> {
445        let verdicts = nodes
446            .iter()
447            .map(|node| Self::tka_snapshot_admits(authority, node))
448            .collect::<Vec<_>>();
449
450        let mut rotation = RotationTracker::default();
451        for (node, verdict) in nodes.iter().zip(&verdicts) {
452            if verdict.admitted
453                && let Some(details) = &verdict.rotation
454            {
455                rotation.add(node.node_key.to_bytes().to_vec(), details);
456            }
457        }
458        let obsolete = rotation.obsolete_keys();
459
460        nodes
461            .iter()
462            .zip(&verdicts)
463            .map(|(node, v)| {
464                // `contains` takes `&[u8]` (HashSet<Vec<u8>> borrows as a slice) — no alloc.
465                v.admitted && !obsolete.contains(&node.node_key.to_bytes()[..])
466            })
467            .collect()
468    }
469}
470
471/// The outcome of a per-peer Tailnet-Lock check: whether the peer is admitted, plus (for an admitted
472/// peer signed by a rotation chain) the chain's [`RotationDetails`](ts_tka::RotationDetails) so the
473/// `Full` path can run the cross-peer rotation filter from the SAME verify pass (no second verify).
474struct TkaVerdict {
475    admitted: bool,
476    rotation: Option<ts_tka::RotationDetails>,
477}
478
479impl TkaVerdict {
480    /// Admitted, no rotation details (no lock / brick-guard / non-rotation signature).
481    fn admit() -> Self {
482        Self {
483            admitted: true,
484            rotation: None,
485        }
486    }
487    /// Dropped.
488    fn drop() -> Self {
489        Self {
490            admitted: false,
491            rotation: None,
492        }
493    }
494}
495
496/// Cross-peer rotation-obsolescence tracker, mirroring Go `ipnlocal.rotationTracker`. Fed the
497/// [`RotationDetails`](ts_tka::RotationDetails) of every admitted, rotation-signed peer in a `Full`
498/// netmap; [`obsolete_keys`](Self::obsolete_keys) then returns the node keys to drop on top of the
499/// per-peer verdict. Two rules (Go `tkaFilterNetmapLocked` + `rotationTracker.obsoleteKeys`):
500///
501/// 1. Every prior node key named in any rotation chain is obsolete (a newer chain rotated it away).
502/// 2. Among `Direct`-rooted chains sharing one wrapping pubkey (a clone signal), only the
503///    longest-chain peer survives; if the two longest are tied, ALL in that group are dropped (we
504///    cannot tell which is the latest, so reject for safety). `Credential`-rooted chains are exempt
505///    from rule 2 — several nodes can legitimately join under one reusable auth key (same wrapping
506///    pubkey), so sharing it is not a clone signal there. (Rule 1 still applies to them.)
507///
508/// Node keys are tracked as raw `Vec<u8>` (the verified 32-byte node-public bytes).
509#[derive(Default)]
510struct RotationTracker {
511    obsolete: HashSet<Vec<u8>>,
512    by_wrapping_key: HashMap<Vec<u8>, Vec<SigRotation>>,
513}
514
515/// One admitted peer's rotation entry within a wrapping-key group.
516struct SigRotation {
517    node_key: Vec<u8>,
518    num_prev_keys: usize,
519}
520
521impl RotationTracker {
522    /// Record an admitted peer `node_key` and its rotation `details` (Go `addRotationDetails`).
523    fn add(&mut self, node_key: Vec<u8>, details: &ts_tka::RotationDetails) {
524        // Rule 1: every prior key is obsolete — applied for ALL chains (incl. credential-rooted),
525        // matching Go's ungated `obsolete.AddSlice(d.PrevNodeKeys)`.
526        self.obsolete.extend(details.prev_node_keys.iter().cloned());
527        // Rule 2 (clone-uniqueness) is gated to Direct-rooted chains only.
528        if details.initial_sig_kind != ts_tka::SigKind::Direct {
529            return;
530        }
531        self.by_wrapping_key
532            .entry(details.initial_wrapping_pubkey.clone())
533            .or_default()
534            .push(SigRotation {
535                node_key,
536                num_prev_keys: details.prev_node_keys.len(),
537            });
538    }
539
540    /// Compute the full obsolete node-key set (Go `rotationTracker.obsoleteKeys`). Processes each
541    /// wrapping-key group, mutating the shared `obsolete` set as it goes (so a key obsoleted by one
542    /// group is seen as obsolete by later groups via the `retain` below — Go's
543    /// `slices.DeleteFunc(... Contains)`). Group iteration order (a `HashMap` drain) is
544    /// nondeterministic, but the result is order-INDEPENDENT: this only ever *inserts* into
545    /// `obsolete` (never removes), and rule 1 already obsoleted every prior key before this loop, so
546    /// the final set is a union that does not depend on which group runs first (as in Go).
547    fn obsolete_keys(mut self) -> HashSet<Vec<u8>> {
548        // Drain only the group map so the loop can mutate `self.obsolete` without aliasing it; the
549        // shared `obsolete` set itself is NOT drained, preserving the cross-group visibility above.
550        let groups: Vec<Vec<SigRotation>> = self.by_wrapping_key.drain().map(|(_k, v)| v).collect();
551        for mut group in groups {
552            // Drop entries already obsoleted (rotated away) by another chain.
553            group.retain(|rd| !self.obsolete.contains(&rd.node_key));
554            if group.is_empty() {
555                continue;
556            }
557            // Longest chain (most prior keys) is the newest ⇒ the survivor; sort decreasing.
558            // `sort_by_key` is stable (like Go's `SortStableFunc`); `Reverse` gives descending order.
559            group.sort_by_key(|rd| core::cmp::Reverse(rd.num_prev_keys));
560            if group.len() >= 2 && group[0].num_prev_keys == group[1].num_prev_keys {
561                // Tie for longest ⇒ cannot disambiguate the latest ⇒ drop the WHOLE group.
562                tracing::warn!(
563                    "TKA: multiple peers share a wrapping key with equal rotation depth; dropping all (cannot determine the latest)"
564                );
565                for rd in &group {
566                    self.obsolete.insert(rd.node_key.clone());
567                }
568            } else {
569                // Only the longest-chain peer survives; the rest are obsolete.
570                for rd in &group[1..] {
571                    self.obsolete.insert(rd.node_key.clone());
572                }
573            }
574        }
575        self.obsolete
576    }
577}
578
579impl kameo::Actor for PeerTracker {
580    /// `(env, tka_authority)`: the bus/keys env, plus the read end of the control runner's TKA
581    /// enforcement-authority cell (Go `tkaFilterNetmapLocked`). The control runner is the sole
582    /// writer; it publishes the verified `Authority` after a successful `/machine/tka/sync` and
583    /// `None` when the lock is disabled. A `watch` cell (not a bus message) so the latest value is
584    /// always readable on demand, never dropped, and never reordered (see the control runner's
585    /// `tka_authority` cell).
586    type Args = (Env, watch::Receiver<Option<Arc<ts_tka::Authority>>>);
587    type Error = Error;
588
589    async fn on_start(
590        (env, tka_authority): Self::Args,
591        slf: ActorRef<Self>,
592    ) -> Result<Self, Self::Error> {
593        env.subscribe::<Arc<ts_control::StateUpdate>>(&slf).await?;
594        env.subscribe::<PeerDiscoKeyAdvertisement>(&slf).await?;
595        env.subscribe::<DiscoKeyObserved>(&slf).await?;
596
597        // Re-filter the peer db whenever the enforcement authority changes. Go gets this for free:
598        // `SetControlClientStatus` runs `tkaSyncIfNeeded` and `tkaFilterNetmapLocked` back to back
599        // over one netmap. Here the sync is asynchronous, so the peers admitted before the authority
600        // arrived need a second pass — see `tka_reevaluate_peer_db`. `changed()` resolves on every
601        // write to the cell (enable, re-sync, disable); the task ends when the control runner drops
602        // the sender (shutdown) or the tracker itself is gone.
603        //
604        // A **weak** ref on purpose: the runtime holds only a `WeakActorRef` to the peer tracker, so
605        // a strong one parked in this task would keep the actor's mailbox alive past shutdown.
606        let mut authority_changes = tka_authority.clone();
607        let notify = slf.downgrade();
608        tokio::spawn(async move {
609            while authority_changes.changed().await.is_ok() {
610                let Some(tracker) = notify.upgrade() else {
611                    break; // the peer tracker is gone; nothing left to re-filter
612                };
613                if tracker.tell(TkaAuthorityChanged).await.is_err() {
614                    break; // the peer tracker stopped
615                }
616            }
617        });
618
619        let (peer_watch, _) = watch::channel(Vec::new());
620
621        Ok(Self {
622            peer_db: PeerDb::default(),
623            pending_requests: Default::default(),
624            seen_state_update: false,
625            peer_watch,
626            user_profiles: HashMap::new(),
627            endpoint_disco: HashMap::new(),
628            // The cell starts `None` (no lock synced ⇒ enforcement inactive, admit all, matching
629            // Go's `b.tka == nil`); the control runner flips it to `Some` on the first sync.
630            tka_authority,
631            expiry: ExpiryManager::new(),
632            self_node: None,
633            expiry_timer: None,
634            env,
635        })
636    }
637}
638
639enum Pending {
640    PeerByName(PeerByName, ReplySender<Option<Node>>),
641    AcceptedRoute(PeerByAcceptedRoute, ReplySender<Vec<Node>>),
642    TailnetIp(PeerByTailnetIp, ReplySender<Option<Node>>),
643    Status(ReplySender<Vec<(PeerId, StatusNode)>>),
644    WhoIs(Whois, ReplySender<Option<crate::status::WhoIs>>),
645}
646
647// For messages with arguments, a struct is generated with the args as fields. They aren't
648// documented, and we can't apply attributes directly to the fields. Hence, wrap in a module where
649// docs are turned off everywhere.
650#[allow(missing_docs)]
651mod msg_impl {
652    use std::net::IpAddr;
653
654    use kameo::prelude::DelegatedReply;
655
656    use super::*;
657
658    #[kameo::messages]
659    impl PeerTracker {
660        /// Lookup a peer by name.
661        ///
662        /// Waits until we've received at least one peer update from control.
663        #[message(ctx)]
664        pub async fn peer_by_name(
665            &mut self,
666            ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
667            name: String,
668        ) -> DelegatedReply<Option<Node>> {
669            let (deleg, sender) = ctx.reply_sender();
670            let Some(sender) = sender else { return deleg };
671
672            if !self.seen_state_update {
673                tracing::debug!(query = name, "no peer state seen yet, queueing request");
674
675                self.pending_requests
676                    .push(Pending::PeerByName(PeerByName { name }, sender));
677
678                return deleg;
679            }
680
681            sender.send(self.peer_by_name_opt(&name).cloned());
682
683            deleg
684        }
685
686        /// Lookup all peers that accept packets addressed to the given IP.
687        ///
688        /// This includes the peer's tailnet address and any subnet routes it provides. Only
689        /// the peers with the most specific subnet route match that covers `ip` will be
690        /// returned.
691        ///
692        /// E.g., suppose:
693        ///
694        /// - We're querying for `10.1.2.3`
695        /// - `PeerA` and `PeerB` have accepted routes for `10.1.2.0/24`
696        /// - `PeerC` has an accepted route for `10.1.0.0/16`
697        ///
698        /// Only `PeerA` and `PeerB` will be returned, since they have the most specific
699        /// prefix match.
700        #[message(ctx)]
701        pub fn peer_by_accepted_route(
702            &mut self,
703            ctx: &mut Context<Self, DelegatedReply<Vec<Node>>>,
704            ip: IpAddr,
705        ) -> DelegatedReply<Vec<Node>> {
706            let (deleg, sender) = ctx.reply_sender();
707            let Some(sender) = sender else { return deleg };
708
709            if !self.seen_state_update {
710                tracing::debug!(query = %ip, "no peer state seen yet, queueing request");
711
712                self.pending_requests
713                    .push(Pending::AcceptedRoute(PeerByAcceptedRoute { ip }, sender));
714
715                return deleg;
716            }
717
718            sender.send(
719                self.peer_db
720                    .get_route(ip.into())
721                    .map(|(_id, node)| node.clone())
722                    .collect(),
723            );
724
725            deleg
726        }
727
728        /// Lookup the peer that has the given tailnet IP address.
729        #[message(ctx)]
730        pub fn peer_by_tailnet_ip(
731            &mut self,
732            ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
733            ip: IpAddr,
734        ) -> DelegatedReply<Option<Node>> {
735            let (deleg, sender) = ctx.reply_sender();
736            let Some(sender) = sender else { return deleg };
737
738            if !self.seen_state_update {
739                tracing::debug!(query = %ip, "no peer state seen yet, queueing request");
740
741                self.pending_requests
742                    .push(Pending::TailnetIp(PeerByTailnetIp { ip }, sender));
743
744                return deleg;
745            }
746
747            sender.send(self.peer_by_tailnet_ip_opt(ip).cloned());
748
749            deleg
750        }
751
752        /// Build the peer entries of a [`Status`](crate::Status) snapshot, each paired with its
753        /// [`PeerId`] so [`Runtime::status`](crate::Runtime::status) can join per-peer connectivity
754        /// (`cur_addr`/`relay`) from the direct manager before returning. The self node is *not*
755        /// included here (it lives in the control runner); `Runtime::status` combines both and drops
756        /// the ids.
757        ///
758        /// Waits until we've received at least one peer update from control.
759        #[message(ctx)]
760        pub fn get_status(
761            &mut self,
762            ctx: &mut Context<Self, DelegatedReply<Vec<(PeerId, StatusNode)>>>,
763        ) -> DelegatedReply<Vec<(PeerId, StatusNode)>> {
764            let (deleg, sender) = ctx.reply_sender();
765            let Some(sender) = sender else { return deleg };
766
767            if !self.seen_state_update {
768                tracing::debug!("no peer state seen yet, queueing status request");
769                self.pending_requests.push(Pending::Status(sender));
770                return deleg;
771            }
772
773            sender.send(self.status_peers_with_ids());
774
775            deleg
776        }
777
778        /// Return every known peer's full domain [`Node`] (not the lossy [`StatusNode`]).
779        ///
780        /// Used by [`Runtime::file_targets`](crate::Runtime::file_targets), which needs the full node
781        /// (peerAPI address, owning user id, cap map) to compute Taildrop send targets. The self node
782        /// is not included (it lives in the control runner). Returns empty before the first netmap —
783        /// the natural "not connected yet" analog (an immediate answer, no queueing needed: callers
784        /// that need a populated list await `Running` first).
785        #[message]
786        pub fn all_peers(&self) -> Vec<Node> {
787            self.peer_db.peers().values().cloned().collect()
788        }
789
790        /// Look up a peer by its control-assigned stable node id ([`Node::stable_id`]).
791        ///
792        /// The lookup a caller holding an older [`Node`] snapshot uses to refresh it before acting
793        /// on it — notably the Taildrop send path (`tailscale::Device::send_file`), which must not
794        /// dial a peer this node has since flagged expired. `None` means the db holds no peer with
795        /// that id: either it has left the tailnet, or no netmap has arrived yet.
796        ///
797        /// Answers immediately in both cases; unlike [`PeerByName`] it does **not** queue until the
798        /// first peer update. A caller that already holds a snapshot has one to fall back on, and
799        /// blocking a send behind a netmap that may never come would be worse than answering from
800        /// what is known.
801        #[message]
802        pub fn peer_by_stable_id(&self, stable_id: ts_control::StableNodeId) -> Option<Node> {
803            self.peer_db.get(&stable_id).map(|(_id, node)| node.clone())
804        }
805
806        /// Resolve which node owns a tailnet source address.
807        ///
808        /// Maps the source IP of `addr` to the owning node via the tailnet-IP index, returning a
809        /// [`WhoIs`](crate::WhoIs). The port is ignored (a tailnet IP uniquely identifies a node).
810        ///
811        /// The resulting [`WhoIs`](crate::WhoIs) carries no user/login or capability data: this
812        /// fork's domain [`Node`] does not retain those wire fields. See the
813        /// [`status`](crate::status) module docs for the gap.
814        ///
815        /// Waits until we've received at least one peer update from control.
816        #[message(ctx)]
817        pub fn whois(
818            &mut self,
819            ctx: &mut Context<Self, DelegatedReply<Option<crate::status::WhoIs>>>,
820            addr: std::net::SocketAddr,
821        ) -> DelegatedReply<Option<crate::status::WhoIs>> {
822            let (deleg, sender) = ctx.reply_sender();
823            let Some(sender) = sender else { return deleg };
824
825            if !self.seen_state_update {
826                tracing::debug!(query = %addr, "no peer state seen yet, queueing whois request");
827                self.pending_requests
828                    .push(Pending::WhoIs(Whois { addr }, sender));
829                return deleg;
830            }
831
832            sender.send(self.whois_opt(addr));
833
834            deleg
835        }
836
837        /// Subscribe to netmap peer-change events.
838        ///
839        /// Returns a [`watch::Receiver`] whose value is the current set of peer
840        /// [`StatusNode`]s, updated on every netmap state update from control. Embedders can await
841        /// changes via [`watch::Receiver::changed`] to react to peers joining, leaving, or changing.
842        ///
843        /// The receiver's initial value is the peer set at subscription time (empty before the
844        /// first netmap update). This is a peer-only view; combine with the self node from
845        /// [`Runtime::status`](crate::Runtime::status) when a full snapshot is needed.
846        #[message(derive(Clone))]
847        pub fn watch_netmap(&self) -> watch::Receiver<Vec<StatusNode>> {
848            self.peer_watch.subscribe()
849        }
850    }
851}
852
853pub use msg_impl::*;
854
855#[derive(Debug, Clone)]
856pub(crate) struct PeerState {
857    #[allow(unused)]
858    pub deletions: HashSet<PeerId>,
859    #[allow(unused)]
860    pub upserts: HashSet<PeerId>,
861    pub peers: Arc<PeerDb>,
862    /// Control's `silent-disco` node attribute, read off the **self** node
863    /// ([`ts_control::Node::silent_disco`]) and carried with the peer snapshot so
864    /// [`crate::direct::DirectManager`] can push it onto the magicsock.
865    ///
866    /// It rides this message rather than a channel of its own because that is the shape it has
867    /// upstream: Go hands `debugFlagsLocked().heartbeatDisabled` to `endpoint.updateFromNode` while
868    /// applying the netmap, so the flag and the peer set land on the endpoints together. A snapshot
869    /// published for some other reason (a disco-key switch, an expiry, a TKA eviction) carries the
870    /// attribute's current value too, which is harmless — the push is idempotent.
871    pub silent_disco: bool,
872}
873
874impl Message<Arc<ts_control::StateUpdate>> for PeerTracker {
875    type Reply = ();
876
877    async fn handle(
878        &mut self,
879        msg: Arc<ts_control::StateUpdate>,
880        ctx: &mut Context<Self, Self::Reply>,
881    ) {
882        // Accumulate user profiles first — control sends them incrementally and a response may
883        // carry profiles with no peer delta (or peers that reference a profile from an earlier
884        // response), so this must happen before the no-peer-update early return below.
885        self.accumulate_user_profiles(&msg.user_profiles);
886
887        // Wall clock for everything below, sampled once so one response is evaluated at one
888        // instant. chrono is built without its `clock` feature in this workspace, so `local_now`
889        // derives it from `SystemTime` the same way the control runner / ssh-policy paths do.
890        let now = local_now();
891
892        // Record control's own clock BEFORE anything reads expiry — Go `onControlTime`, delivered
893        // to the expiry manager as its own event. From here on every expiry comparison is made
894        // against control's time, not this host's, so a node with a skewed clock neither expires
895        // peers early nor misses that they expired at all.
896        if let Some(control_time) = msg.control_time {
897            let delta = self.expiry.on_control_time(control_time, now);
898            if !delta.is_zero() {
899                tracing::debug!(
900                    delta_secs = delta.num_seconds(),
901                    "control's clock differs from ours; expiry is judged against control's time"
902                );
903            }
904        }
905
906        // Remember the self node so it can be folded into the next-expiry computation below, exactly as Go
907        // folds `nm.SelfNode` into `nextPeerExpiry`. Self is never a peer and is never flagged
908        // here; the runtime's own expiry decision stays with the control runner.
909        if let Some(self_node) = msg.node.as_ref() {
910            self.self_node = Some(self_node.clone());
911        }
912
913        // Apply the standalone online/last-seen delta maps (channels C/D, `MapResponse.OnlineChange`
914        // / `PeerSeenChange`). These arrive keyed by control node id and may ride a response that
915        // carries NO `peer_update` (a bare online flip is the common case), so they must be applied
916        // *before* the no-peer-update early return — otherwise online status freezes at the last
917        // full-node/patch value. Each entry only ever *sets* a value (never back to unknown).
918        // `now` (above) is also the wall clock for a `PeerSeenChange: true` (Go uses `clock.Now()`).
919        let liveness_changed =
920            self.apply_liveness_changes(&msg.online_change, &msg.peer_seen_change, now);
921
922        if msg.peer_update.is_none() && msg.peer_patches.is_empty() {
923            // No peer set or patch, so the peer expiries are unchanged — but the self node or the
924            // clock delta may have moved, so the timer still has to be re-aimed.
925            self.rearm_expiry_timer(now, ctx.actor_ref());
926
927            // No peer set or patch this response. If a liveness delta still mutated the netmap,
928            // publish the refreshed snapshot so watchers (and `GetStatus`) see the new online state.
929            if liveness_changed {
930                self.service_pending_requests();
931                self.peer_watch.send_replace(self.status_peers());
932                if let Err(e) = self
933                    .env
934                    .publish(Arc::new(PeerState {
935                        upserts: HashSet::default(),
936                        deletions: HashSet::default(),
937                        peers: Arc::new(self.peer_db.clone()),
938                        silent_disco: self.silent_disco(),
939                    }))
940                    .await
941                {
942                    tracing::error!(error = %e, "publishing liveness-only peer state update");
943                }
944            }
945            return;
946        }
947
948        // Apply the whole-node peer set (if any) FIRST, then the field-level patches on top —
949        // mirroring Go's `controlclient` order (`Peers*` then `PeersChangedPatch`). A response may
950        // carry either, both, or (with a liveness-only delta) neither. Merge the upsert/deletion sets
951        // so the published `PeerState` reflects every node touched by both passes; a node both
952        // upserted by the set and patched stays in `upserts` (the patch removes it from `deletions`).
953        let (mut upserts, mut deletions) = msg
954            .peer_update
955            .as_ref()
956            .map(|u| self.apply_peer_update(u, now))
957            .unwrap_or_default();
958
959        if !msg.peer_patches.is_empty() {
960            // `apply_peer_patch_set`, not `apply_peer_patches`: control can switch this node off
961            // the incremental path with the `disable-delta-updates` node attribute, in which case
962            // the same patches are applied as a full netmap update instead of as mutations.
963            let (patch_upserts, patch_deletions) =
964                self.apply_peer_patch_set(&msg.peer_patches, now);
965            // A patch can evict a node the set just upserted (TKA rejection after key rotation), or
966            // re-admit/patch one not in the set — reconcile so each id lands in exactly one set.
967            for id in &patch_upserts {
968                deletions.remove(id);
969            }
970            for id in &patch_deletions {
971                upserts.remove(id);
972            }
973            upserts.extend(patch_upserts);
974            deletions.extend(patch_deletions);
975        }
976
977        tracing::debug!(
978            n_upsert = upserts.len(),
979            n_delete = deletions.len(),
980            peer_count = self.peer_db.peers().len(),
981            "new peer state"
982        );
983
984        // Aim the timer at the soonest expiry in the peer set this response just installed — Go
985        // `setControlClientStatusLocked`, which stops the old timer and starts a new one on every
986        // netmap. Peers already past their expiry were flagged on the way in, so what is left is
987        // strictly in the future.
988        self.rearm_expiry_timer(now, ctx.actor_ref());
989
990        self.service_pending_requests();
991
992        // Publish the latest peer snapshot to netmap watchers. `send_replace` keeps the receiver's
993        // value current even when there are no subscribers, so a late subscriber sees fresh state.
994        self.peer_watch.send_replace(self.status_peers());
995
996        if let Err(e) = self
997            .env
998            .publish(Arc::new(PeerState {
999                upserts,
1000                deletions,
1001                peers: Arc::new(self.peer_db.clone()),
1002                silent_disco: self.silent_disco(),
1003            }))
1004            .await
1005        {
1006            tracing::error!(error = %e, "publishing peer state update");
1007        }
1008    }
1009}
1010
1011impl Message<PeerDiscoKeyAdvertisement> for PeerTracker {
1012    type Reply = ();
1013
1014    async fn handle(
1015        &mut self,
1016        msg: PeerDiscoKeyAdvertisement,
1017        _ctx: &mut Context<Self, Self::Reply>,
1018    ) {
1019        if !self.learn_disco_key(msg.peer, msg.key) {
1020            return;
1021        }
1022
1023        // The key changed, so republish: the direct-path machinery resolves a peer's disco key out
1024        // of the published `PeerState` snapshot (`direct::DiscoPeerLookup`), which is the whole
1025        // point of learning it — it is what lets disco reach this peer without waiting for a
1026        // netmap update. Go does the equivalent by writing the key straight into the magicsock
1027        // endpoint and re-keying its peer map.
1028        self.peer_watch.send_replace(self.status_peers());
1029
1030        if let Err(e) = self
1031            .env
1032            .publish(Arc::new(PeerState {
1033                upserts: HashSet::from_iter([msg.peer]),
1034                deletions: HashSet::default(),
1035                peers: Arc::new(self.peer_db.clone()),
1036                silent_disco: self.silent_disco(),
1037            }))
1038            .await
1039        {
1040            tracing::error!(error = %e, "publishing peer state after a TSMP disco-key advertisement");
1041        }
1042    }
1043}
1044
1045impl Message<DiscoKeyObserved> for PeerTracker {
1046    type Reply = ();
1047
1048    async fn handle(&mut self, msg: DiscoKeyObserved, _ctx: &mut Context<Self, Self::Reply>) {
1049        if !self.observe_disco_key(msg.peer, msg.key) {
1050            return;
1051        }
1052
1053        // The active key moved, so republish. This is the *same* channel a TSMP advertisement and a
1054        // netmap disco-key change use, and it is what makes the direct manager invalidate the
1055        // trusted path built under the old key: it diffs consecutive snapshots
1056        // (`direct::disco_key_rotations`) and calls `MagicSock::changed_active_disco` — this fork's
1057        // `endpoint.changedActiveDiscoLocked`, which Go likewise reaches from
1058        // `checkAndUpdateDiscoKey`. Keeping the switch and the invalidation on one path is why the
1059        // switch is done here rather than on the packet path that spotted it.
1060        self.peer_watch.send_replace(self.status_peers());
1061
1062        if let Err(e) = self
1063            .env
1064            .publish(Arc::new(PeerState {
1065                upserts: HashSet::from_iter([msg.peer]),
1066                deletions: HashSet::default(),
1067                peers: Arc::new(self.peer_db.clone()),
1068                silent_disco: self.silent_disco(),
1069            }))
1070            .await
1071        {
1072            tracing::error!(error = %e, "publishing peer state after a disco active-key switch");
1073        }
1074    }
1075}
1076
1077/// Internal self-message: the armed expiry timer fired — the soonest key expiry the peer set knew
1078/// about has now passed, so expiry must be re-evaluated.
1079///
1080/// This is the whole point of the timer (Go `LocalBackend.nmExpiryTimer` →
1081/// `handleNetmapExpiry`): without it a peer whose key expires between two netmaps stays fully
1082/// configured — endpoints, DERP home, live node key — until control happens to send another
1083/// response, which on a steady map poll may be a long time.
1084///
1085/// Upstream `0640312e5` had to fix this path, because the timer there closed over the netmap
1086/// captured when it was armed and reinstalling that stale copy rolled back any delta that arrived
1087/// meanwhile; the fix re-reads live peer state before reinstalling. Here the pass reads the peer db
1088/// — the live state — directly, so there is no captured copy to roll anything back.
1089#[derive(Debug, Clone, Copy)]
1090pub(crate) struct ExpiryTimerFired;
1091
1092impl Message<ExpiryTimerFired> for PeerTracker {
1093    type Reply = ();
1094
1095    async fn handle(&mut self, _msg: ExpiryTimerFired, ctx: &mut Context<Self, Self::Reply>) {
1096        let now = local_now();
1097        let upserts = self.reevaluate_expiry(now);
1098
1099        // Re-aim at the next expiry after this one, whether or not anything was flagged: a timer
1100        // that fired early (clock skew, or the slack) must not be the last one armed.
1101        self.rearm_expiry_timer(now, ctx.actor_ref());
1102
1103        if upserts.is_empty() {
1104            return;
1105        }
1106
1107        // A newly expired peer lost its endpoints, its DERP home and its node key, so the
1108        // dataplane, route updater and source filter all have to see the new snapshot — the same
1109        // publish the netmap handler does after a peer set changes.
1110        self.service_pending_requests();
1111        self.peer_watch.send_replace(self.status_peers());
1112
1113        if let Err(e) = self
1114            .env
1115            .publish(Arc::new(PeerState {
1116                upserts,
1117                deletions: HashSet::default(),
1118                peers: Arc::new(self.peer_db.clone()),
1119                silent_disco: self.silent_disco(),
1120            }))
1121            .await
1122        {
1123            tracing::error!(error = %e, "publishing peer state after a peer key expired");
1124        }
1125    }
1126}
1127
1128/// Internal self-message: the Tailnet-Lock enforcement-authority cell changed — the control runner
1129/// installed a freshly-synced [`Authority`](ts_tka::Authority) after a `/machine/tka/sync`, or
1130/// cleared it because the lock was disabled. Sent by the watch task
1131/// [`on_start`](kameo::Actor::on_start) spawns, so the peer db is re-filtered the moment enforcement
1132/// changes instead of at whatever later `Full` netmap happens to arrive.
1133#[derive(Debug, Clone, Copy)]
1134pub(crate) struct TkaAuthorityChanged;
1135
1136impl Message<TkaAuthorityChanged> for PeerTracker {
1137    type Reply = ();
1138
1139    async fn handle(&mut self, _msg: TkaAuthorityChanged, _ctx: &mut Context<Self, Self::Reply>) {
1140        let deletions = self.tka_reevaluate_peer_db();
1141        if deletions.is_empty() {
1142            // The common case: enforcement is inactive, or every admitted peer still verifies.
1143            return;
1144        }
1145
1146        // An evicted peer must lose its data path, not just its db row, so republish the snapshot
1147        // the `Arc<PeerState>` subscribers (route updater, source filter, dataplane) resolve
1148        // against — the same publish the netmap handler does after a peer set changes.
1149        self.peer_watch.send_replace(self.status_peers());
1150
1151        if let Err(e) = self
1152            .env
1153            .publish(Arc::new(PeerState {
1154                upserts: HashSet::default(),
1155                deletions,
1156                peers: Arc::new(self.peer_db.clone()),
1157                silent_disco: self.silent_disco(),
1158            }))
1159            .await
1160        {
1161            tracing::error!(error = %e, "publishing peer state after a TKA authority change");
1162        }
1163    }
1164}
1165
1166/// Ask the peer tracker to re-broadcast its current peer snapshot on the bus, without any peer
1167/// change. Sent after a runtime preference change so the route updater and source filter (both
1168/// `Arc<PeerState>` subscribers) re-resolve against the new value immediately, rather than waiting
1169/// for the next netmap update: `Device::set_exit_node` (new exit-node selector) and
1170/// `Device::set_accept_routes` (new accept-routes flag) both send it.
1171#[derive(Debug, Clone, Copy)]
1172pub struct RepublishState;
1173
1174impl Message<RepublishState> for PeerTracker {
1175    type Reply = ();
1176
1177    async fn handle(&mut self, _msg: RepublishState, _ctx: &mut Context<Self, Self::Reply>) {
1178        // An empty upsert/deletion set: this is a re-broadcast of the unchanged peer set, not a
1179        // delta. Subscribers recompute their routes/filters against the current peers and the
1180        // (just-updated) runtime preferences (exit-node selector, accept-routes flag).
1181        if let Err(e) = self
1182            .env
1183            .publish(Arc::new(PeerState {
1184                upserts: HashSet::default(),
1185                deletions: HashSet::default(),
1186                peers: Arc::new(self.peer_db.clone()),
1187                silent_disco: self.silent_disco(),
1188            }))
1189            .await
1190        {
1191            tracing::error!(error = %e, "re-publishing peer state after a runtime preference change");
1192        }
1193    }
1194}
1195
1196impl PeerTracker {
1197    /// Learn a peer's disco key from a TSMP disco-key advertisement, returning whether the
1198    /// advertisement was applied.
1199    ///
1200    /// Go [`magicsock.Conn.HandleDiscoKeyAdvertisement`], reduced to the state this fork keeps:
1201    /// Go stores the learned key on the magicsock endpoint and re-keys its peer map, whereas here
1202    /// the peer db's `disco_key` (and its disco index) *is* the live lookup every direct-path
1203    /// consumer reads. The key is recorded in the peer's [`EndpointDisco`] TSMP slot — never on top
1204    /// of control's — and the peer db then carries whichever of the two is active, so the next
1205    /// netmap cannot silently undo it ([`upsert_from_control`](Self::upsert_from_control)).
1206    ///
1207    /// The three refusals are Go's, in Go's order:
1208    ///
1209    /// 1. **A zero key is never learned.** Go checks it twice — `tstun` publishes only
1210    ///    `if !Key.IsZero()`, and `HandleDiscoKeyAdvertisement` rejects it again. The dataplane
1211    ///    already dropped it here too; this is the second check, kept because the cost of getting
1212    ///    it wrong is a peer bound to an unusable key.
1213    /// 2. **An unknown peer is ignored** (Go: "endpoint not found for node"). An advertisement
1214    ///    never creates a peer — only control does — so one that arrives before or after the
1215    ///    peer's netmap entry is a no-op, exactly like a `PeersChangedPatch` for an unknown node.
1216    /// 3. **An unchanged key is a no-op**, so a peer re-advertising the key we already hold costs
1217    ///    no upsert and no republish (Go counts this as
1218    ///    `magicsock_tsmp_disco_key_advertisement_unchanged` and returns). "Unchanged" is measured
1219    ///    against the **TSMP-learned** key (Go compares `epDisco.keyFromTSMP()`), NOT against the
1220    ///    effective one: an advertisement that merely restates what control already told us is new
1221    ///    information — it is the peer itself confirming the key — so it is recorded as the active
1222    ///    TSMP key and survives control later dropping or contradicting it.
1223    ///
1224    /// The tailnet-lock gate is deliberately *not* re-run: unlike a `PeersChangedPatch`, an
1225    /// advertisement cannot touch the node key or its TKA signature — only the disco key — so the
1226    /// peer-trust decision that admitted this node is unchanged by definition.
1227    ///
1228    /// [`magicsock.Conn.HandleDiscoKeyAdvertisement`]: https://github.com/tailscale/tailscale/blob/49e148c4a30b4f8098f69468fd27a7021d85ea02/wgengine/magicsock/magicsock.go
1229    fn learn_disco_key(&mut self, peer: PeerId, key: DiscoPublicKey) -> bool {
1230        if disco_key_is_zero(&key) {
1231            tracing::debug!(?peer, "TSMP-advertised disco key is the zero key; ignoring");
1232            return false;
1233        }
1234
1235        let Some((_id, existing)) = self.peer_db.get(&peer) else {
1236            tracing::debug!(
1237                ?peer,
1238                "TSMP disco-key advertisement for unknown peer; ignoring"
1239            );
1240            return false;
1241        };
1242
1243        let node_key = existing.node_key;
1244        if self
1245            .endpoint_disco
1246            .get(&node_key)
1247            .and_then(EndpointDisco::key_from_tsmp)
1248            == Some(key)
1249        {
1250            tracing::trace!(?peer, "TSMP-advertised disco key is unchanged");
1251            return false;
1252        }
1253
1254        let node = existing.clone();
1255        let disco = self.endpoint_disco.entry(node_key).or_default();
1256        disco.update_from_tsmp(Some(key));
1257        let disco = *disco;
1258        self.store_disco(&node, disco);
1259
1260        tracing::info!(
1261            ?peer,
1262            stable_id = ?node.stable_id,
1263            %key,
1264            "learned peer disco key from a TSMP advertisement"
1265        );
1266
1267        true
1268    }
1269
1270    /// Write a peer's resolved disco state onto the peer db.
1271    ///
1272    /// The node lands carrying the **effective** key ([`EndpointDisco::key`]), which is what the
1273    /// disco index — and so every *send* path — resolves against, and the peer's other known key
1274    /// (if any) is registered as its inactive ingress key so a frame arriving under it still
1275    /// attributes to this peer ([`PeerDb::peer_by_known_disco_key`]).
1276    ///
1277    /// Every disco-key writer goes through here — control, a TSMP advertisement, and an
1278    /// active-slot switch on receive — so the two cannot drift apart on which key is which.
1279    fn store_disco(&mut self, node: &Node, disco: EndpointDisco) -> PeerId {
1280        let effective = disco.key();
1281
1282        let id = if effective == node.disco_key {
1283            self.peer_db.upsert(node)
1284        } else {
1285            let mut node = node.clone();
1286            node.disco_key = effective;
1287            self.peer_db.upsert(&node)
1288        };
1289
1290        self.peer_db
1291            .set_inactive_disco_key(id, disco.inactive_key());
1292
1293        id
1294    }
1295
1296    /// Apply the sender key of an inbound disco frame to this peer's two-slot disco state — the
1297    /// `ts_runtime` half of Go [`endpoint.checkAndUpdateDiscoKey`].
1298    ///
1299    /// A peer mid-rotation keeps sending disco under the key it has not yet switched away from.
1300    /// Upstream accepts either of the two keys it knows for the peer and, when the one received is
1301    /// the currently-inactive one, makes it active: receiving under a key is proof of what the peer
1302    /// is using, and is stronger evidence than what control last said. Without this a rotation
1303    /// costs the peer its direct path until control catches up or the peer re-advertises.
1304    ///
1305    /// Returns whether the active key changed, so the caller can republish — which is how the
1306    /// direct manager learns to invalidate the trusted path built under the old key (Go's
1307    /// `changedActiveDiscoLocked`, reached here through the same snapshot diff every other
1308    /// disco-key transition uses).
1309    ///
1310    /// The refusals, all of which leave the peer db untouched:
1311    ///
1312    /// 1. **An unknown peer**, exactly as for a TSMP advertisement.
1313    /// 2. **A peer with no disco key material at all** (Go: `epDisco == nil` ⇒ `false`).
1314    /// 3. **A key belonging to neither slot.** This is the one that carries the security value:
1315    ///    a peer must not be able to move itself onto a key nobody told us about, so a third key
1316    ///    is refused even though the frame that carried it opened correctly.
1317    ///
1318    /// [`endpoint.checkAndUpdateDiscoKey`]: https://github.com/tailscale/tailscale/blob/9ea7cba44591e0cd840c6c94d23274dd222059bf/wgengine/magicsock/endpoint.go
1319    fn observe_disco_key(&mut self, peer: PeerId, key: DiscoPublicKey) -> bool {
1320        let Some((_id, existing)) = self.peer_db.get(&peer) else {
1321            tracing::debug!(?peer, "disco received for an unknown peer; ignoring");
1322            return false;
1323        };
1324
1325        let node = existing.clone();
1326        let Some(disco) = self.endpoint_disco.get_mut(&node.node_key) else {
1327            // Go's `epDisco == nil`: the peer has no key from either source, so there is nothing
1328            // this key could match and nothing to switch to.
1329            tracing::debug!(
1330                ?peer,
1331                "disco received for a peer with no known disco key; ignoring"
1332            );
1333            return false;
1334        };
1335
1336        let Some(changed) = disco.check_and_update(key) else {
1337            tracing::debug!(
1338                ?peer,
1339                %key,
1340                "refusing disco under a key that is neither of the peer's known disco keys"
1341            );
1342            return false;
1343        };
1344
1345        if !changed {
1346            return false;
1347        }
1348
1349        let disco = *disco;
1350        self.store_disco(&node, disco);
1351
1352        tracing::info!(
1353            ?peer,
1354            stable_id = ?node.stable_id,
1355            %key,
1356            "peer is sending disco under its other known key; making that key active"
1357        );
1358
1359        true
1360    }
1361
1362    /// Upsert a control-sourced [`Node`] into the peer db, resolving its disco key against anything
1363    /// this peer has told us over TSMP first.
1364    ///
1365    /// Every node built from control goes through here — `Full`, `Delta { upsert }`, and a
1366    /// `PeersChangedPatch` — so the three cannot diverge on which of the two keys wins. This is the
1367    /// disco half of Go [`endpoint.updateFromNode`]: control's key is written through
1368    /// [`EndpointDisco::update_from_control`] **only when it differs from what control last said**
1369    /// (Go's `if discoKey != n.DiscoKey()` guard, which compares `keyFromControl()`, never the
1370    /// effective key). So a netmap that merely restates the key control already sent leaves an
1371    /// active TSMP key alone — which is the entire point of the advertisement, whose motivating case
1372    /// is a peer whose key control has not caught up with. Control genuinely changing its mind is
1373    /// *recorded* in control's slot, but it does not take the active slot back from a TSMP-learned
1374    /// key: upstream switches back only when disco is received under control's key
1375    /// (`endpoint.checkAndUpdateDiscoKey`). See [`EndpointDisco::update_from_control`].
1376    ///
1377    /// The node lands in the db carrying the *effective* key ([`EndpointDisco::key`]), so the disco
1378    /// index and every send path resolve against the key we would actually send to; the other known
1379    /// key is registered for ingress attribution ([`store_disco`](Self::store_disco)).
1380    ///
1381    /// [`endpoint.updateFromNode`]: https://github.com/tailscale/tailscale/blob/49e148c4a30b4f8098f69468fd27a7021d85ea02/wgengine/magicsock/endpoint.go
1382    fn upsert_from_control(&mut self, node: &Node, now: chrono::DateTime<chrono::Utc>) -> PeerId {
1383        // The expiry pass, at the one site every peer install funnels through — Go
1384        // `flagExpiredPeers`, which runs over the whole netmap on the way in. A peer whose key
1385        // expiry has passed (judged against CONTROL's clock) is rewritten, never dropped: it keeps
1386        // its identity so `whois`, `status` and a peerAPI dial can all say *why* it is unreachable,
1387        // but it loses its endpoints, its home DERP and its usable node key. `None` is the ordinary
1388        // case — no transition — and costs no clone.
1389        let flagged = self.expiry.flag_expired_peer(node, now);
1390        // Log the transition, not the rewrite: control restates an expired peer unflagged on every
1391        // full netmap, so without this the line (and the reader's alarm) would repeat forever.
1392        if let Some(flagged) = flagged.as_ref().filter(|f| f.first_transition) {
1393            if flagged.peer.expired {
1394                tracing::info!(
1395                    stable_id = ?flagged.peer.stable_id,
1396                    "peer's node key has expired; clearing its endpoints and DERP home and \
1397                     breaking its node key"
1398                );
1399            } else {
1400                tracing::info!(
1401                    stable_id = ?flagged.peer.stable_id,
1402                    "peer's node-key expiry was extended; restoring its node key"
1403                );
1404            }
1405        }
1406        let node = flagged.as_ref().map_or(node, |flagged| &flagged.peer);
1407
1408        let node_key = node.node_key;
1409        let from_control = disco_key_from_control(node.disco_key);
1410
1411        let disco = self.endpoint_disco.entry(node_key).or_default();
1412        if disco.key_from_control() != from_control {
1413            disco.update_from_control(from_control);
1414        }
1415        let disco = *disco;
1416
1417        // No key material from either source: Go nils the endpoint's `disco` pointer, so a peer
1418        // that has never had a disco key costs us no entry either.
1419        if disco.is_empty() {
1420            self.endpoint_disco.remove(&node_key);
1421        }
1422
1423        self.store_disco(node, disco)
1424    }
1425
1426    /// The disco key control last gave us for `node_key` — Go `endpointDisco.keyFromControl()`.
1427    fn control_disco_key(&self, node_key: &NodePublicKey) -> Option<DiscoPublicKey> {
1428        self.endpoint_disco
1429            .get(node_key)
1430            .and_then(EndpointDisco::key_from_control)
1431    }
1432
1433    /// Drop [`EndpointDisco`] state for node keys the peer db no longer holds.
1434    ///
1435    /// Go gets this for free: the two keys live on the magicsock `endpoint`, which the peer map keys
1436    /// by node key and deletes when the peer leaves the netmap — and a peer that rotates its node
1437    /// key gets a brand-new endpoint, so a TSMP-learned key is not carried across a rotation. Here
1438    /// the state is a side table, so every control update prunes it to get the same lifetime.
1439    fn prune_endpoint_disco(&mut self) {
1440        if self.endpoint_disco.is_empty() {
1441            return;
1442        }
1443
1444        let peers = &self.peer_db;
1445        self.endpoint_disco
1446            .retain(|node_key, _| peers.has(node_key).is_some());
1447    }
1448
1449    /// Apply a single [`PeerUpdate`](ts_control::PeerUpdate) to the peer db, enforcing the
1450    /// Tailnet-Lock peer-trust chokepoint ([`tka_admits`](Self::tka_admits)) at every upsert site.
1451    ///
1452    /// This is the **single source of truth** for the peer-trust enforcement loop: the actor's
1453    /// netmap [`handle`](Message::handle) calls it, and so do the TKA enforcement tests, so the two
1454    /// real upsert sites (`Full` and `Delta { upsert }`) cannot diverge from what is tested.
1455    ///
1456    /// `now` is the local wall clock the expiry pass in
1457    /// [`upsert_from_control`](Self::upsert_from_control) judges against (after correction for
1458    /// control's clock); it is threaded in rather than read per peer so one netmap is evaluated at
1459    /// one instant.
1460    ///
1461    /// Returns `(upserts, deletions)` — the [`PeerId`]s touched — for downstream bookkeeping.
1462    fn apply_peer_update(
1463        &mut self,
1464        peer_update: &ts_control::PeerUpdate,
1465        now: chrono::DateTime<chrono::Utc>,
1466    ) -> (HashSet<PeerId>, HashSet<PeerId>) {
1467        let mut upserts = HashSet::default();
1468        let mut deletions = HashSet::default();
1469
1470        match peer_update {
1471            ts_control::PeerUpdate::Full(new_nodes) => {
1472                tracing::trace!("full peer update");
1473
1474                // Borrow the authority ONCE for the whole batch and verify each peer EXACTLY once
1475                // (Go runs `tkaFilterNetmapLocked` once over the assembled netmap; an earlier draft
1476                // verified every peer twice — once for `retained_ids`, once in the upsert loop —
1477                // doubling the ed25519 cost on the hot resync path). `tka_keep_verdicts` is that one
1478                // pass — per-peer signature verdict AND the cross-peer rotation filter — and is
1479                // shared verbatim with `tka_reevaluate_peer_db`, so the netmap path and the
1480                // authority-install path cannot drift apart on what "admitted" means.
1481                //
1482                // The result is a per-NODE keep vector (not a stable_id set), which drives both the
1483                // `retain` (evict revoked peers, keyed by stable_id) and the upsert loop. Judging
1484                // each node by its own verdict means a node whose signature fails is never admitted
1485                // on the strength of a different node that happens to share its stable_id.
1486                //
1487                // Revocation evicts: a peer re-included with a now-invalid/missing signature under an
1488                // active authority fails its verdict, so it is excluded from `retained_ids` and
1489                // `retain` drops the stale (previously-admitted) entry. With no authority the snapshot
1490                // is `None`, so every node passes — byte-for-byte the pre-TKA behavior (no regression).
1491                let authority = self.tka_authority_snapshot();
1492                let node_refs = new_nodes.iter().collect::<Vec<&Node>>();
1493                let keep = Self::tka_keep_verdicts(authority.as_deref(), &node_refs);
1494
1495                // `retained_ids` is the set of stable_ids that survive (drives `retain` to evict the
1496                // rest). It must agree with what the upsert loop below will leave in the db. Control
1497                // should never send two distinct nodes with the same `stable_id` in one `Full`, but if
1498                // it does, `peer_db.upsert` is last-writer-wins on `stable_id`, so the db ends holding
1499                // the LAST kept node for that id. Build `retained_ids` from kept nodes only — a
1500                // stable_id is retained iff at least one of its (possibly duplicate) nodes is kept, so
1501                // the upsert loop's last-kept node lands and `retain` never evicts a just-upserted id.
1502                let retained_ids = new_nodes
1503                    .iter()
1504                    .zip(keep.iter().copied())
1505                    .filter(|(_, k)| *k)
1506                    .map(|(node, _)| &node.stable_id)
1507                    .collect::<HashSet<_>>();
1508
1509                // Isolation diagnostic: an ACTIVE lock that authorized none of the offered peers
1510                // leaves this node with no peers — surface it loudly so a self-lockout (vs an attack)
1511                // is diagnosable. `authority.is_some()` means a real keyed lock (the empty-keyset
1512                // brick-guard admits-all, so it never reaches here with zero retained).
1513                if authority.is_some() && !new_nodes.is_empty() && retained_ids.is_empty() {
1514                    tracing::error!(
1515                        offered = new_nodes.len(),
1516                        "TKA: active lock authorized ZERO of the offered peers; node is isolated \
1517                         (verify the lock state, or disable tailnet lock to recover)"
1518                    );
1519                }
1520
1521                self.peer_db.retain(|id, peer| {
1522                    let retain = retained_ids.contains(&peer.stable_id);
1523
1524                    if !retain {
1525                        deletions.insert(id);
1526                    }
1527
1528                    retain
1529                });
1530
1531                for (node, k) in new_nodes.iter().zip(keep.iter().copied()) {
1532                    if !k {
1533                        continue; // fail-CLOSED: rejected by tailnet lock or rotation-obsolete (above)
1534                    }
1535                    let peer_id = self.upsert_from_control(node, now);
1536                    upserts.insert(peer_id);
1537                }
1538            }
1539
1540            ts_control::PeerUpdate::Delta { remove, upsert } => {
1541                tracing::trace!("delta peer update");
1542
1543                for peer in upsert {
1544                    if !self.tka_admits(peer) {
1545                        // fail-CLOSED: do not upsert a peer rejected by tailnet lock. If the peer is
1546                        // ALREADY in the db (a delta re-upserting an existing peer whose signature is
1547                        // now invalid — e.g. revoked between syncs), evict the stale entry rather than
1548                        // leaving an unverified peer admitted; Go re-filters the whole netmap each map
1549                        // response, so a now-unsigned peer would not survive there either.
1550                        if let Some((id, _)) = self.peer_db.remove(&peer.stable_id) {
1551                            tracing::warn!(
1552                                stable_id = ?peer.stable_id,
1553                                "TKA: delta re-upsert rejected; evicting now-unauthorized peer"
1554                            );
1555                            deletions.insert(id);
1556                        }
1557                        continue;
1558                    }
1559                    let id = self.upsert_from_control(peer, now);
1560
1561                    upserts.insert(id);
1562                }
1563
1564                for peer in remove {
1565                    let Some((id, _node)) = self.peer_db.remove(peer) else {
1566                        // A benign, expected race: the peer may already be gone (dropped in a prior
1567                        // `Full`, or fail-closed by TKA — whose now-"unknown" ids commonly reappear in
1568                        // a trailing `peers_removed`). Go treats an unknown removal as a no-op; log at
1569                        // debug, not error, to avoid false-alarm noise on a healthy node (matches the
1570                        // unknown-node handling in `apply_peer_patches`).
1571                        tracing::debug!(
1572                            control_node_id = peer,
1573                            "removed peer was unknown; ignoring"
1574                        );
1575                        continue;
1576                    };
1577
1578                    deletions.insert(id);
1579                }
1580            }
1581        }
1582
1583        self.prune_endpoint_disco();
1584
1585        (upserts, deletions)
1586    }
1587
1588    /// Re-run the Tailnet-Lock filter over the peers **already in the peer db**, evicting the ones
1589    /// the current authority does not admit. Returns the evicted [`PeerId`]s (empty when nothing
1590    /// changed, which is the overwhelmingly common case).
1591    ///
1592    /// # Why this exists (a Go-ordering gap, not an extra feature)
1593    /// Go filters the very netmap that announced the lock: `SetControlClientStatus`
1594    /// (`ipn/ipnlocal/local.go`, v1.100.0) calls `tkaSyncIfNeeded` and then, a few lines later,
1595    /// `tkaFilterNetmapLocked(st.NetMap)` — synchronously, on the same `st.NetMap`, in one pass. So
1596    /// the peers announced alongside `TKAEnabled` are checked by the authority that sync just built.
1597    ///
1598    /// Here the sync is a spawned task (`control_runner`'s `maybe_sync_tka`), so the ordering is
1599    /// inverted: the netmap that carried the `TkaStatus` reaches the peer db *before* the authority
1600    /// exists, and is admitted with enforcement inactive. Without this pass those peers stay
1601    /// admitted — unauthorized ones included — until control happens to send another `Full`, which on
1602    /// a steady map poll may be never. That is the whole initial peer set escaping a lock the node
1603    /// really did sync, so this runs the moment the authority is installed ([`TkaAuthorityChanged`])
1604    /// and brings the db back in line.
1605    ///
1606    /// No authority (nothing synced yet, or the lock was disabled) ⇒ no eviction: enforcement is
1607    /// inactive and every peer is admitted, exactly Go's `b.tka == nil` early return. A peer dropped
1608    /// while the lock was active is **not** resurrected by a later disable — the db no longer holds
1609    /// it and this fork keeps no shadow copy of filtered nodes (Go's `b.tka.filtered`); it returns on
1610    /// the next netmap that re-includes it. That is the safe direction: more restrictive, and
1611    /// connectivity-only.
1612    fn tka_reevaluate_peer_db(&mut self) -> HashSet<PeerId> {
1613        let Some(authority) = self.tka_authority_snapshot() else {
1614            return HashSet::default();
1615        };
1616
1617        // Verdicts first, under an immutable borrow of the db; the eviction below needs `&mut`.
1618        let evicted: HashSet<PeerId> = {
1619            let entries = self
1620                .peer_db
1621                .peers()
1622                .iter()
1623                // A peer this node already flagged expired is skipped: its node key is one WE
1624                // broke (`ExpiryManager::flag_expired_peer`), so re-verifying control's signature
1625                // against it would be checking our own mutation, and the peer would always be
1626                // evicted. It was admitted by the lock when it was installed, against the real key
1627                // control sent, and it has had no usable key since — so keeping the row costs no
1628                // trust and preserves the thing expiry flagging exists for: an expired peer is
1629                // FLAGGED, not dropped, so a caller can say why it is unreachable.
1630                .filter(|(_, node)| !node.expired)
1631                .map(|(id, node)| (*id, node))
1632                .collect::<Vec<(PeerId, &Node)>>();
1633            let nodes = entries
1634                .iter()
1635                .map(|(_, node)| *node)
1636                .collect::<Vec<&Node>>();
1637            let keep = Self::tka_keep_verdicts(Some(&authority), &nodes);
1638            entries
1639                .iter()
1640                .zip(keep)
1641                .filter_map(|((id, _), keep)| (!keep).then_some(*id))
1642                .collect()
1643        };
1644
1645        if evicted.is_empty() {
1646            return evicted;
1647        }
1648
1649        tracing::warn!(
1650            n_evicted = evicted.len(),
1651            peer_count = self.peer_db.peers().len(),
1652            "TKA: re-filtered the peer db against the newly installed lock authority; evicted \
1653             already-admitted peers"
1654        );
1655        self.peer_db.retain(|id, _| !evicted.contains(&id));
1656        self.prune_endpoint_disco();
1657        evicted
1658    }
1659
1660    /// Re-run the expiry pass over the peers **already in the peer db**, returning the [`PeerId`]s
1661    /// whose node changed (empty when nothing expired, the overwhelmingly common case).
1662    ///
1663    /// The timer's counterpart to the pass [`upsert_from_control`](Self::upsert_from_control) runs
1664    /// on the way in: that one catches a peer that was already expired when control handed it to
1665    /// us, this one catches a peer that expires while we sit on the same netmap.
1666    ///
1667    /// Only peers that actually transition are cloned and re-installed — the pass returns `None`
1668    /// for the rest — so a timer firing over a large peer set costs one walk and a handful of
1669    /// upserts. Re-installing goes through the ordinary upsert path so the node-key index follows
1670    /// the peer's now-broken key; the pass there is a no-op on an already-flagged peer.
1671    fn reevaluate_expiry(&mut self, now: chrono::DateTime<chrono::Utc>) -> HashSet<PeerId> {
1672        let flagged = self
1673            .peer_db
1674            .peers()
1675            .values()
1676            .filter_map(|peer| self.expiry.flag_expired_peer(peer, now))
1677            .collect::<Vec<ts_control::FlaggedPeer>>();
1678
1679        if flagged.is_empty() {
1680            return HashSet::default();
1681        }
1682
1683        tracing::info!(
1684            n = flagged.len(),
1685            "netmap expiry timer fired; peers whose node keys expired between netmaps"
1686        );
1687
1688        let mut upserts = HashSet::default();
1689        for flagged in &flagged {
1690            // `upsert_from_control` re-runs the pass, which is a no-op on the peer it just
1691            // rewrote — so the log line belongs here, where the transition is known.
1692            if flagged.first_transition && flagged.peer.expired {
1693                tracing::info!(
1694                    stable_id = ?flagged.peer.stable_id,
1695                    "peer's node key has expired; clearing its endpoints and DERP home and \
1696                     breaking its node key"
1697                );
1698            }
1699            upserts.insert(self.upsert_from_control(&flagged.peer, now));
1700        }
1701        self.prune_endpoint_disco();
1702
1703        upserts
1704    }
1705
1706    /// Whether control has asked this node to stop heartbeating its peers — the `silent-disco`
1707    /// attribute on the self node, published with every [`PeerState`] snapshot.
1708    ///
1709    /// Read off the self node this tracker last saw, which is the one the current response
1710    /// refreshed, so an attribute control grants takes effect on the netmap that granted it (the
1711    /// timing `delta_updates_disabled` already has here). No self node yet ⇒ `false` ⇒ the existing
1712    /// heartbeat cadence, which is the safe default: the cost of heartbeating a node control wanted
1713    /// quiet is a ping every 2s, while the cost of going quiet on a guess is a direct path falling
1714    /// back to DERP.
1715    fn silent_disco(&self) -> bool {
1716        self.self_node.as_ref().is_some_and(Node::silent_disco)
1717    }
1718
1719    /// Stop the armed expiry timer and arm a new one for the soonest future key expiry across the
1720    /// peer db and the self node — Go `setControlClientStatusLocked`'s `nmExpiryTimer` block.
1721    ///
1722    /// No future expiry (every peer tagged or already flagged, and no self expiry) leaves no timer
1723    /// armed; the next netmap re-decides. The delay carries upstream's
1724    /// [`EXPIRY_TIMER_SLACK_SECS`](ts_control::EXPIRY_TIMER_SLACK_SECS) of slack so the key is
1725    /// unambiguously past its expiry by the time the pass runs.
1726    ///
1727    /// The old timer is **aborted**, which is this fork's version of Go's `numClientStatusCalls`
1728    /// generation check: a task that has already been dropped cannot deliver a stale wake-up. The
1729    /// spawned task holds only a `WeakActorRef`, so it can never keep the tracker's mailbox alive
1730    /// past shutdown.
1731    fn rearm_expiry_timer(&mut self, now: chrono::DateTime<chrono::Utc>, slf: &ActorRef<Self>) {
1732        if let Some(timer) = self.expiry_timer.take() {
1733            timer.abort();
1734        }
1735
1736        let Some(next) = self.expiry.next_peer_expiry(
1737            self.peer_db.peers().values(),
1738            self.self_node.as_ref(),
1739            now,
1740        ) else {
1741            return;
1742        };
1743
1744        let delay = (next - now) + chrono::TimeDelta::seconds(ts_control::EXPIRY_TIMER_SLACK_SECS);
1745        // `next` is never before `now` (the expiry manager floors it), so the conversion holds; a
1746        // negative delta would only mean "fire immediately", which is also the safe reading.
1747        let delay = delay.to_std().unwrap_or(std::time::Duration::ZERO);
1748
1749        tracing::debug!(
1750            delay_secs = delay.as_secs(),
1751            "arming the netmap expiry timer for the next node-key expiry"
1752        );
1753
1754        let notify = slf.downgrade();
1755        self.expiry_timer = Some(tokio::spawn(async move {
1756            tokio::time::sleep(delay).await;
1757            let Some(tracker) = notify.upgrade() else {
1758                return; // the peer tracker is gone; nothing left to re-evaluate
1759            };
1760            if let Err(e) = tracker.tell(ExpiryTimerFired).await {
1761                tracing::debug!(error = %e, "peer tracker stopped before the expiry timer fired");
1762            }
1763        }));
1764    }
1765
1766    /// Apply the response's `MapResponse.PeersChangedPatch` set, choosing the incremental path or
1767    /// the fall-back-to-full one according to control's `disable-delta-updates` node attribute.
1768    ///
1769    /// This is the port of the first statement of Go `control/controlclient/map.go`'s
1770    /// `tryHandleIncrementally` — `if ms.controlKnobs != nil &&
1771    /// ms.controlKnobs.DisableDeltaUpdates.Load() { return false }` — and of what returning `false`
1772    /// there means: the map session does not reject the response and does not drop the mutations it
1773    /// carries, it declines the incremental arm so the full netmap rebuild handles the *same*
1774    /// response. So a patch-only response under the attribute is still applied, as a full update.
1775    ///
1776    /// The attribute is read off the **self** node, which the netmap handler refreshes from this
1777    /// very response before it gets here, so an attribute control granted on this response takes
1778    /// effect on the response that granted it — the same timing the netmap cache's attribute read
1779    /// has. No self node yet (nothing has carried one) reads as absent ⇒ the incremental path.
1780    fn apply_peer_patch_set(
1781        &mut self,
1782        patches: &[ts_control::PeerChange],
1783        now: chrono::DateTime<chrono::Utc>,
1784    ) -> (HashSet<PeerId>, HashSet<PeerId>) {
1785        if self
1786            .self_node
1787            .as_ref()
1788            .is_some_and(Node::delta_updates_disabled)
1789        {
1790            tracing::debug!(
1791                n = patches.len(),
1792                "control set disable-delta-updates; applying this response's peer patches as a \
1793                 full netmap update"
1794            );
1795            return self.rebuild_netmap_with_patches(patches, now);
1796        }
1797
1798        self.apply_peer_patches(patches, now)
1799    }
1800
1801    /// The fall-back-to-full arm of [`apply_peer_patch_set`](Self::apply_peer_patch_set): fold the
1802    /// patches in, then re-install the **whole** retained netmap rather than the patched nodes
1803    /// alone.
1804    ///
1805    /// Go reaches the same place by a different route because its map session keeps its own peer
1806    /// store: `HandleNonKeepAliveMapResponse` absorbs `PeersChangedPatch` into that store
1807    /// (`updateStateFromResponse`) *before* it decides how to hand the result downstream, then —
1808    /// when `tryHandleIncrementally` declines — rebuilds the netmap from the store (`ms.netmap()`,
1809    /// which re-runs `flagExpiredPeers` over every peer) and installs it whole with
1810    /// `UpdateFullNetmap`. Here the peer db *is* that store, so step one is the ordinary patch fold
1811    /// and step two is re-installing every peer through the same control-sourced upsert path, which
1812    /// is what re-runs the expiry pass over the whole netmap and puts every peer in the published
1813    /// upsert set. Upstream names the cost itself — "lots of garbage & work downstream" — and it is
1814    /// the point of the escape hatch, not a side effect of it.
1815    ///
1816    /// Nothing here evicts a peer the incremental path would have kept: the only trust gate is the
1817    /// per-patched-node one the fold already runs. Re-verifying the *whole* db against tailnet lock
1818    /// (Go's full arm re-runs `tkaFilterNetmapLocked`) is deliberately NOT done, because the nodes
1819    /// in the db are this node's own copies rather than control's pristine ones — a peer this node
1820    /// flagged expired carries a node key we broke ourselves, so its signature can no longer verify
1821    /// and re-filtering would evict it. That is the same carve-out, for the same reason, that
1822    /// [`tka_reevaluate_peer_db`](Self::tka_reevaluate_peer_db) already makes.
1823    fn rebuild_netmap_with_patches(
1824        &mut self,
1825        patches: &[ts_control::PeerChange],
1826        now: chrono::DateTime<chrono::Utc>,
1827    ) -> (HashSet<PeerId>, HashSet<PeerId>) {
1828        let (mut upserts, deletions) = self.apply_peer_patches(patches, now);
1829
1830        // Re-install the netmap the fold above just produced, whole. Cloning first keeps the db
1831        // borrow off the upsert loop; it is the "garbage" half of upstream's own description.
1832        let netmap: Vec<Node> = self.peer_db.peers().values().cloned().collect();
1833        for mut node in netmap {
1834            // The db carries the EFFECTIVE disco key, which may have been learned over TSMP, so
1835            // restate what CONTROL last said before re-installing. Without this, re-installing a
1836            // peer whose active key came from a TSMP advertisement would hand that key back as if
1837            // control had sent it, and `upsert_from_control` would write it into control's slot —
1838            // losing the key control actually gave us. Same reasoning as the patch fold's own
1839            // restatement, applied to every peer because every peer is re-installed here.
1840            node.disco_key = self.control_disco_key(&node.node_key);
1841            upserts.insert(self.upsert_from_control(&node, now));
1842        }
1843
1844        (upserts, deletions)
1845    }
1846
1847    /// Apply field-level peer patches (`MapResponse.PeersChangedPatch`), returning the upserted /
1848    /// deleted [`PeerId`]s. The incremental arm of
1849    /// [`apply_peer_patch_set`](Self::apply_peer_patch_set), and the fold both arms share.
1850    ///
1851    /// This is a SEPARATE channel from [`apply_peer_update`](Self::apply_peer_update): Go's
1852    /// `controlclient` applies the whole-node `Peers*` set first and then `PeersChangedPatch`, so a
1853    /// response that carries both has the peer set applied first (by the caller) and these patches
1854    /// applied second, on top of the freshly-synced nodes. A patch only mutates a peer already in the
1855    /// netmap; an unknown node id is ignored (the wire contract — a patch never creates a node).
1856    fn apply_peer_patches(
1857        &mut self,
1858        patches: &[ts_control::PeerChange],
1859        now: chrono::DateTime<chrono::Utc>,
1860    ) -> (HashSet<PeerId>, HashSet<PeerId>) {
1861        let mut upserts = HashSet::default();
1862        let mut deletions = HashSet::default();
1863
1864        tracing::trace!(n = patches.len(), "peer patch update");
1865
1866        for patch in patches {
1867            // Clone the current node, apply the present fields, and re-upsert through the same path
1868            // as a delta so indexes/routes stay consistent.
1869            let Some((_id, existing)) = self.peer_db.get(&patch.id) else {
1870                tracing::debug!(
1871                    control_node_id = patch.id,
1872                    "peer patch for unknown node; ignoring"
1873                );
1874                continue;
1875            };
1876
1877            let mut node = existing.clone();
1878            if let Some(endpoints) = &patch.underlay_addresses {
1879                node.underlay_addresses = endpoints.clone();
1880            }
1881            if let Some(derp) = patch.derp_region {
1882                node.derp_region = Some(derp);
1883            }
1884            if let Some(cap) = patch.cap {
1885                node.cap = cap;
1886            }
1887            if let Some(cap_map) = &patch.cap_map {
1888                node.cap_map = cap_map.clone();
1889            }
1890            // The db entry carries the EFFECTIVE disco key, which may have been learned over TSMP,
1891            // so restate what CONTROL last said before folding the patch in. Otherwise a patch that
1892            // says nothing about the disco key would hand a TSMP-learned key back as if control had
1893            // sent it, and `upsert_from_control` would write it into control's slot — losing the key
1894            // control actually gave us, on a patch that never mentioned the disco key at all.
1895            node.disco_key = self.control_disco_key(&node.node_key);
1896            if let Some(disco_key) = patch.disco_key {
1897                node.disco_key = Some(disco_key);
1898            }
1899            if let Some(expiry) = patch.node_key_expiry {
1900                node.node_key_expiry = Some(expiry);
1901            }
1902            // Online/last-seen liveness deltas (`PeerChange.Online`/`LastSeen`) — the dominant
1903            // channel by which peer online transitions arrive mid-session. A patch only ever *sets*
1904            // a value (never patches back to unknown), so apply when present.
1905            if let Some(online) = patch.online {
1906                node.online = Some(online);
1907            }
1908            if let Some(last_seen) = patch.last_seen {
1909                node.last_seen = Some(last_seen);
1910            }
1911            // Key rotation: a patch may swap the node key (and its TKA signature). Apply both
1912            // together so the trust gate below verifies the new signature against the new key, never
1913            // a mismatched pair.
1914            if let Some(node_key) = patch.node_key {
1915                node.node_key = node_key;
1916                // Control restated the key, so this node's own break of it (if the peer had
1917                // expired) no longer applies: clear the client-set flag and let the expiry pass in
1918                // `upsert_from_control` decide again against the (possibly also patched) expiry.
1919                // Go gets this for free — it patches a pristine node and re-runs `flagExpiredPeers`
1920                // over the result.
1921                node.expired = false;
1922            }
1923            if let Some(sig) = &patch.key_signature {
1924                node.key_signature = sig.clone();
1925            }
1926
1927            // Re-run the tailnet-lock gate on the patched node: a patch that rotates the key must
1928            // satisfy the active authority, exactly like a `Delta` upsert, or it would be a
1929            // trust-enforcement bypass. fail-CLOSED — if the patched node is no longer admitted,
1930            // evict it rather than keep the stale (now-unverified) entry.
1931            if !self.tka_admits(&node) {
1932                if let Some((id, _)) = self.peer_db.remove(&patch.id) {
1933                    tracing::warn!(
1934                        control_node_id = patch.id,
1935                        "peer patch rejected by tailnet lock; evicting peer"
1936                    );
1937                    deletions.insert(id);
1938                }
1939                continue;
1940            }
1941
1942            let id = self.upsert_from_control(&node, now);
1943            upserts.insert(id);
1944        }
1945
1946        self.prune_endpoint_disco();
1947
1948        (upserts, deletions)
1949    }
1950
1951    /// Apply the standalone online/last-seen delta maps (`MapResponse.OnlineChange` /
1952    /// `PeerSeenChange`, channels C/D) onto the retained netmap. Returns `true` if any node was
1953    /// actually mutated (so the caller knows whether to re-publish).
1954    ///
1955    /// Mirrors Go `controlclient/map.go:updatePeersStateFromResponse` (the two channels are
1956    /// semantically DISTINCT and must not be conflated):
1957    /// - `OnlineChange` (channel C) is the sole driver of a peer's `online` flag (`mut.Online = v`).
1958    /// - `PeerSeenChange` (channel D) is the sole driver of `last_seen`: `true ⇒ LastSeen = now`,
1959    ///   `false ⇒ LastSeen = nil` (cleared). It NEVER touches `online` — "not seen recently" is not
1960    ///   the same as "offline", which only `OnlineChange` asserts.
1961    ///
1962    /// Each entry is keyed by control node id and applies to a peer already in the netmap; an unknown
1963    /// node id is ignored (these maps never create a node). `now` is the wall-clock timestamp for a
1964    /// `PeerSeenChange: true` (Go uses `clock.Now()`); the caller passes it so this stays a pure
1965    /// function of its inputs. Returns `true` if any node was actually mutated.
1966    fn apply_liveness_changes(
1967        &mut self,
1968        online_change: &std::collections::BTreeMap<ts_control::NodeId, bool>,
1969        peer_seen_change: &std::collections::BTreeMap<ts_control::NodeId, bool>,
1970        now: chrono::DateTime<chrono::Utc>,
1971    ) -> bool {
1972        let mut changed = false;
1973
1974        // Channel C — direct online flips (the only writer of `online`).
1975        for (&node_id, &online) in online_change {
1976            if let Some((_pid, existing)) = self.peer_db.get(&node_id)
1977                && existing.online != Some(online)
1978            {
1979                let mut node = existing.clone();
1980                node.online = Some(online);
1981                self.peer_db.upsert(&node);
1982                changed = true;
1983            }
1984        }
1985
1986        // Channel D — peer-seen flips (the only writer of `last_seen`; never touches `online`).
1987        // `true` ⇒ last-seen is now; `false` ⇒ last-seen cleared (Go map.go:820-830).
1988        for (&node_id, &seen) in peer_seen_change {
1989            let new_last_seen = if seen { Some(now) } else { None };
1990            if let Some((_pid, existing)) = self.peer_db.get(&node_id)
1991                && existing.last_seen != new_last_seen
1992            {
1993                let mut node = existing.clone();
1994                node.last_seen = new_last_seen;
1995                self.peer_db.upsert(&node);
1996                changed = true;
1997            }
1998        }
1999
2000        changed
2001    }
2002
2003    /// Test-only constructor: build a [`PeerTracker`] with a chosen initial TKA authority without
2004    /// going through the actor `on_start` path. Returns the tracker plus the **`watch::Sender`** for
2005    /// its enforcement-authority cell, so a test can drive the exact enable/disable transitions the
2006    /// control runner drives at runtime (`tx.send_replace(Some(..))` ⇒ enforce, `tx.send_replace(None)`
2007    /// ⇒ clear). The initial `Some` exercises the fail-closed chokepoint
2008    /// ([`tka_admits`](Self::tka_admits)); `None` is the no-lock admit-all path. The returned sender
2009    /// must be kept alive for the tracker to read updated values.
2010    #[cfg(test)]
2011    fn for_test(
2012        env: Env,
2013        tka_authority: Option<ts_tka::Authority>,
2014    ) -> (Self, watch::Sender<Option<Arc<ts_tka::Authority>>>) {
2015        let (peer_watch, _) = watch::channel(Vec::new());
2016        let (tka_tx, tka_rx) = watch::channel(tka_authority.map(Arc::new));
2017        let tracker = Self {
2018            peer_db: PeerDb::default(),
2019            seen_state_update: false,
2020            pending_requests: Vec::new(),
2021            peer_watch,
2022            user_profiles: HashMap::new(),
2023            endpoint_disco: HashMap::new(),
2024            tka_authority: tka_rx,
2025            expiry: ExpiryManager::new(),
2026            self_node: None,
2027            expiry_timer: None,
2028            env,
2029        };
2030        (tracker, tka_tx)
2031    }
2032
2033    fn service_pending_requests(&mut self) {
2034        if self.seen_state_update {
2035            return;
2036        }
2037
2038        self.seen_state_update = true;
2039
2040        if !self.pending_requests.is_empty() {
2041            tracing::debug!(
2042                n_pending = self.pending_requests.len(),
2043                "state update received, servicing pending requests"
2044            );
2045        }
2046
2047        for req in core::mem::take(&mut self.pending_requests) {
2048            match req {
2049                Pending::PeerByName(PeerByName { name }, reply) => {
2050                    reply.send(self.peer_by_name_opt(&name).cloned());
2051                }
2052                Pending::TailnetIp(PeerByTailnetIp { ip }, reply) => {
2053                    reply.send(self.peer_by_tailnet_ip_opt(ip).cloned());
2054                }
2055                Pending::AcceptedRoute(PeerByAcceptedRoute { ip }, reply) => {
2056                    reply.send(
2057                        self.peer_db
2058                            .get_route(ip.into())
2059                            .map(|(_id, node)| node.clone())
2060                            .collect(),
2061                    );
2062                }
2063                Pending::Status(reply) => {
2064                    reply.send(self.status_peers_with_ids());
2065                }
2066                Pending::WhoIs(Whois { addr }, reply) => {
2067                    reply.send(self.whois_opt(addr));
2068                }
2069            }
2070        }
2071    }
2072}
2073
2074#[cfg(test)]
2075pub(crate) mod tka_tests {
2076    //! Tailnet-Lock (TKA) enforcement tests for the peer-trust chokepoint.
2077    //!
2078    //! These exercise [`PeerTracker::tka_admits`] and the `tka_admits ⇒ upsert` loop the netmap
2079    //! handler runs. The test [`ts_tka::Authority`] is built with [`ts_tka::Authority::from_state`]
2080    //! over a known Ed25519 trusted key, and the signed node-key signature CBOR is produced through
2081    //! `ts_tka`'s public `cbor` encoder + `aum_hash` (the exact same canonical bytes `ts_tka`'s own
2082    //! `direct_signature_verifies_end_to_end` test signs, with no new crypto vectors invented and no
2083    //! private `ts_tka` API used).
2084
2085    use ed25519_dalek::{Signer, SigningKey};
2086    use ts_control::{Node, StableNodeId, TailnetAddress};
2087    use ts_tka::{
2088        AumHash, Authority, Key, KeyKind, State,
2089        cbor::{self, Value},
2090    };
2091
2092    use super::*;
2093
2094    /// `SigKind::Direct` wire value (Go `SigKind`; `ts_tka::SigKind::Direct = 1`).
2095    const SIG_KIND_DIRECT: u64 = 1;
2096
2097    /// The 32-byte node key used across the signed-peer fixtures.
2098    const NODE_KEY_BYTES: [u8; 32] = [7u8; 32];
2099
2100    /// Build a real [`Env`] for the tracker. Only the bus/keys/shutdown plumbing matters here; the
2101    /// TKA gate reads neither, so the forwarding preferences are all benign defaults.
2102    pub(super) fn test_env() -> Env {
2103        let (_shutdown_tx, shutdown_rx) = watch::channel(false);
2104        Env::new(
2105            ts_keys::NodeState::generate(),
2106            shutdown_rx,
2107            crate::env::ForwarderConfig {
2108                accept_routes: false,
2109                accept_dns: true,
2110                exit_node: None,
2111                forward_routes: Vec::new(),
2112                forward_tcp_ports: Vec::new(),
2113                forward_udp_ports: Vec::new(),
2114                forward_all_ports: false,
2115                forward_exit_egress: false,
2116                block_incoming: false,
2117                exit_proxy: None,
2118                peerapi_port: None,
2119                taildrop_dir: None,
2120                enable_ipv6: false,
2121                wireguard_listen_port: None,
2122                network_monitor: false,
2123                persistent_keepalive_interval: None,
2124                ingress_active: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
2125            },
2126        )
2127    }
2128
2129    /// A minimal peer [`Node`] carrying `node_key` and the given `key_signature`.
2130    ///
2131    /// `pub(crate)` so the cold-start replay tests in `control_runner` build their peers the same way
2132    /// this module's TKA tests do — both run the same filter, and a second hand-rolled fixture could
2133    /// drift from it.
2134    pub(crate) fn peer_node(stable_id: &str, node_key: [u8; 32], key_signature: Vec<u8>) -> Node {
2135        Node {
2136            id: 1,
2137            stable_id: StableNodeId(stable_id.to_string()),
2138            hostname: stable_id.to_string(),
2139            user_id: 0,
2140            tailnet: Some("ts.net".to_string()),
2141            tags: Vec::new(),
2142            addresses: vec![
2143                "100.64.0.1/32".parse().unwrap(),
2144                "fd7a:115c:a1e0::1/128".parse().unwrap(),
2145            ],
2146            tailnet_address: TailnetAddress {
2147                ipv4: "100.64.0.1/32".parse().unwrap(),
2148                ipv6: "fd7a:115c:a1e0::1/128".parse().unwrap(),
2149            },
2150            node_key: node_key.into(),
2151            node_key_expiry: None,
2152            expired: false,
2153            online: None,
2154            last_seen: None,
2155            key_signature,
2156            machine_key: None,
2157            disco_key: None,
2158            accepted_routes: Vec::new(),
2159            underlay_addresses: Vec::new(),
2160            derp_region: None,
2161            cap: Default::default(),
2162            cap_map: Default::default(),
2163            peerapi_port: None,
2164            peerapi_dns_proxy: false,
2165            is_wireguard_only: false,
2166            exit_node_dns_resolvers: Vec::new(),
2167            peer_relay: false,
2168            ssh_host_keys: Vec::new(),
2169            service_vips: Default::default(),
2170            unsigned_peer_api_only: false,
2171        }
2172    }
2173
2174    /// Encode a `Direct` [`ts_tka::NodeKeySignature`] CBOR exactly as `ts_tka`'s private `to_cbor`
2175    /// does (int-map keys: 1=kind, 2=pubkey, 3=key_id, 4=signature; empty byte fields omitted),
2176    /// using only the crate's *public* `cbor` encoder. `signature` of `None` produces the
2177    /// signing-digest preimage (the `SigHash` form).
2178    fn direct_sig_cbor(node_key: &[u8], key_id: &[u8], signature: Option<&[u8]>) -> Vec<u8> {
2179        let mut pairs = alloc_pairs(node_key, key_id);
2180        if let Some(sig) = signature {
2181            pairs.push((4, Some(Value::Bytes(sig.to_vec()))));
2182        }
2183        cbor::int_map(pairs).to_vec()
2184    }
2185
2186    fn alloc_pairs(node_key: &[u8], key_id: &[u8]) -> Vec<(u64, Option<Value>)> {
2187        vec![
2188            (1, Some(Value::Uint(SIG_KIND_DIRECT))),
2189            (2, Some(Value::Bytes(node_key.to_vec()))),
2190            (3, Some(Value::Bytes(key_id.to_vec()))),
2191        ]
2192    }
2193
2194    /// Build a TKA [`Authority`] that trusts `signing.verifying_key()`, plus a valid `Direct`
2195    /// node-key signature CBOR authorizing [`NODE_KEY_BYTES`] under it.
2196    fn authority_and_valid_sig() -> (Authority, Vec<u8>) {
2197        // A fixed, known Ed25519 trusted key (mirrors ts_tka's own end-to-end test seed).
2198        let signing = SigningKey::from_bytes(&[42u8; 32]);
2199        let trusted_pub = signing.verifying_key().to_bytes().to_vec();
2200
2201        let authority = Authority::from_state(
2202            AumHash([0; 32]),
2203            State {
2204                keys: vec![Key {
2205                    kind: KeyKind::Ed25519,
2206                    votes: 1,
2207                    public: trusted_pub.clone(),
2208                }],
2209            },
2210        );
2211
2212        // SigHash preimage = canonical CBOR with the signature field omitted; sign its blake2s hash.
2213        let preimage = direct_sig_cbor(&NODE_KEY_BYTES, &trusted_pub, None);
2214        let sig_hash = ts_tka::aum_hash(&preimage).0;
2215        let signature = signing.sign(&sig_hash).to_bytes().to_vec();
2216
2217        let signed_cbor = direct_sig_cbor(&NODE_KEY_BYTES, &trusted_pub, Some(&signature));
2218        // Sanity: the authority accepts the signature we just built (same path the gate uses).
2219        assert!(
2220            authority
2221                .node_key_authorized(&NODE_KEY_BYTES, &signed_cbor)
2222                .is_ok()
2223        );
2224
2225        (authority, signed_cbor)
2226    }
2227
2228    #[tokio::test]
2229    async fn tka_inactive_upserts_all_peers() {
2230        // No authority ⇒ enforcement inactive ⇒ both a signed and an unsigned peer are admitted.
2231        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2232
2233        let signed = peer_node("signed", [1u8; 32], vec![0xde, 0xad, 0xbe, 0xef]);
2234        let unsigned = peer_node("unsigned", [2u8; 32], vec![]);
2235
2236        assert!(tracker.tka_admits(&signed));
2237        assert!(tracker.tka_admits(&unsigned));
2238
2239        tracker.peer_db.upsert(&signed);
2240        tracker.peer_db.upsert(&unsigned);
2241        assert_eq!(tracker.peer_db.peers().len(), 2);
2242    }
2243
2244    #[tokio::test]
2245    async fn tka_active_rejects_unsigned_peer() {
2246        // Authority present + peer presents no signature ⇒ rejected (fail-closed), not in peer_db.
2247        let (authority, _sig) = authority_and_valid_sig();
2248        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2249
2250        let unsigned = peer_node("unsigned", NODE_KEY_BYTES, vec![]);
2251        assert!(!tracker.tka_admits(&unsigned));
2252
2253        // Mirror the handler's `if !tka_admits { continue }` loop.
2254        if tracker.tka_admits(&unsigned) {
2255            tracker.peer_db.upsert(&unsigned);
2256        }
2257        assert_eq!(tracker.peer_db.peers().len(), 0);
2258        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
2259    }
2260
2261    #[tokio::test]
2262    async fn tka_active_rejects_unsigned_peer_api_only_peer() {
2263        // `UnsignedPeerAPIOnly` buys NO admission exemption here: Go admits such a peer unsigned
2264        // under an active lock (peerAPI-only, no network access), this fork drops it like any other
2265        // unsigned peer. Pins the documented parity gap (`docs/PARITY_ROADMAP.md`, and the
2266        // `ts_control::Node::unsigned_peer_api_only` field docs) so implementing the carve-out has
2267        // to update the prose that promises no peerAPI access today.
2268        let (authority, _sig) = authority_and_valid_sig();
2269        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2270
2271        let mut peer_api_only = peer_node("peerapi-only", NODE_KEY_BYTES, vec![]);
2272        peer_api_only.unsigned_peer_api_only = true;
2273
2274        assert!(
2275            !tracker.tka_admits(&peer_api_only),
2276            "unsigned_peer_api_only must not exempt a peer from the tailnet-lock admission gate"
2277        );
2278
2279        // Mirror the handler's `if !tka_admits { continue }` loop: nothing reaches the peer db, so
2280        // the peer is not reachable for peerAPI either.
2281        if tracker.tka_admits(&peer_api_only) {
2282            tracker.peer_db.upsert(&peer_api_only);
2283        }
2284        assert_eq!(tracker.peer_db.peers().len(), 0);
2285        assert!(tracker.peer_db.get(&peer_api_only.node_key).is_none());
2286    }
2287
2288    #[tokio::test]
2289    async fn tka_empty_keyset_authority_admits_unsigned_peer_api_only_peer() {
2290        // The other side of `tka_active_rejects_unsigned_peer_api_only_peer`: "an authority is
2291        // present" is NOT on its own enough to drop an unsigned peer. The brick-guard fires first,
2292        // so an authority carrying no trusted keys enforces nothing and admits even the peer class
2293        // a keyed lock would reject. Pins the qualifier on the
2294        // `ts_control::Node::unsigned_peer_api_only` field docs — remove the guard and this fails.
2295        use ts_tka::{AumHash, Authority, State};
2296        let empty_auth = Authority::from_state(AumHash([0u8; 32]), State { keys: Vec::new() });
2297        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(empty_auth));
2298
2299        let mut peer_api_only = peer_node("peerapi-only", NODE_KEY_BYTES, vec![]);
2300        peer_api_only.unsigned_peer_api_only = true;
2301
2302        assert!(
2303            tracker.tka_admits(&peer_api_only),
2304            "an empty-keyset authority must not enforce, not even against an unsigned peer"
2305        );
2306
2307        tracker.apply_peer_update(
2308            &ts_control::PeerUpdate::Full(vec![peer_api_only.clone()]),
2309            local_now(),
2310        );
2311        assert!(
2312            tracker.peer_db.get(&peer_api_only.node_key).is_some(),
2313            "the peer reaches the peer db, so the gate's drop is keyset-conditional"
2314        );
2315    }
2316
2317    #[tokio::test]
2318    async fn tka_active_rejects_bad_signature() {
2319        // Authority present + a signature that fails to verify ⇒ rejected, not in peer_db.
2320        let (authority, mut sig) = authority_and_valid_sig();
2321        // Tamper the last byte (the trailing signature byte) so verification fails.
2322        let last = sig.len() - 1;
2323        sig[last] ^= 0xff;
2324
2325        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2326        let bad = peer_node("bad", NODE_KEY_BYTES, sig);
2327        assert!(!tracker.tka_admits(&bad));
2328
2329        if tracker.tka_admits(&bad) {
2330            tracker.peer_db.upsert(&bad);
2331        }
2332        assert_eq!(tracker.peer_db.peers().len(), 0);
2333    }
2334
2335    #[tokio::test]
2336    async fn tka_active_admits_authorized_peer() {
2337        // Authority present + correctly-signed node key ⇒ admitted and upserted.
2338        let (authority, sig) = authority_and_valid_sig();
2339        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2340
2341        let good = peer_node("good", NODE_KEY_BYTES, sig);
2342        assert!(tracker.tka_admits(&good));
2343
2344        if tracker.tka_admits(&good) {
2345            tracker.peer_db.upsert(&good);
2346        }
2347        assert_eq!(tracker.peer_db.peers().len(), 1);
2348        assert!(tracker.peer_db.get(&good.node_key).is_some());
2349    }
2350
2351    // ---------------------------------------------------------------------------------------------
2352    // Tests that drive REAL `PeerUpdate`s through the shared handler body
2353    // ([`PeerTracker::apply_peer_update`], the single source of truth the actor's netmap `handle`
2354    // also calls), so the two real upsert sites (`Full` and `Delta { upsert }`) are exercised via
2355    // the actual enforcement path — not by hand-mirroring `if !tka_admits { continue }`.
2356    // ---------------------------------------------------------------------------------------------
2357
2358    #[tokio::test]
2359    async fn tka_active_delta_upsert_rejects_unauthorized() {
2360        // Drive a real `Delta { upsert }` whose peer carries no signature. The Delta upsert site
2361        // must reject it under an active authority ⇒ not present in peer_db after the handler runs.
2362        let (authority, _sig) = authority_and_valid_sig();
2363        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2364
2365        let unsigned = peer_node("unsigned", NODE_KEY_BYTES, vec![]);
2366        let update = ts_control::PeerUpdate::Delta {
2367            upsert: vec![unsigned.clone()],
2368            remove: Vec::new(),
2369        };
2370
2371        tracker.apply_peer_update(&update, local_now());
2372
2373        assert_eq!(tracker.peer_db.peers().len(), 0);
2374        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
2375    }
2376
2377    #[tokio::test]
2378    async fn tka_active_delta_upsert_admits_authorized() {
2379        // Drive a real `Delta { upsert }` with a correctly-signed peer ⇒ present in peer_db.
2380        let (authority, sig) = authority_and_valid_sig();
2381        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2382
2383        let good = peer_node("good", NODE_KEY_BYTES, sig);
2384        let update = ts_control::PeerUpdate::Delta {
2385            upsert: vec![good.clone()],
2386            remove: Vec::new(),
2387        };
2388
2389        tracker.apply_peer_update(&update, local_now());
2390
2391        assert_eq!(tracker.peer_db.peers().len(), 1);
2392        assert!(tracker.peer_db.get(&good.node_key).is_some());
2393    }
2394
2395    #[tokio::test]
2396    async fn tka_active_full_admits_only_authorized_in_mixed_batch() {
2397        // Drive a real `Full` carrying a MIX of authorized + unauthorized peers. Only the
2398        // correctly-signed peer survives the Full upsert site; the unsigned and bad-sig peers are
2399        // dropped fail-closed.
2400        let (authority, sig) = authority_and_valid_sig();
2401        // A bad-sig variant of the same authorized signature (tamper the trailing byte).
2402        let mut bad_sig = sig.clone();
2403        let last = bad_sig.len() - 1;
2404        bad_sig[last] ^= 0xff;
2405
2406        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2407
2408        // Only the authorized peer carries NODE_KEY_BYTES (the key the authority signed); the
2409        // rejected peers use distinct node keys so the survivor is unambiguous.
2410        let good = peer_node("good", NODE_KEY_BYTES, sig);
2411        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2412        let bad = peer_node("bad", [9u8; 32], bad_sig);
2413
2414        let update =
2415            ts_control::PeerUpdate::Full(vec![good.clone(), unsigned.clone(), bad.clone()]);
2416
2417        tracker.apply_peer_update(&update, local_now());
2418
2419        assert_eq!(tracker.peer_db.peers().len(), 1);
2420        assert!(tracker.peer_db.get(&good.node_key).is_some());
2421        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
2422        assert!(tracker.peer_db.get(&bad.node_key).is_none());
2423    }
2424
2425    /// End-to-end through the REAL enforcement-authority transport (the `watch` cell the control
2426    /// runner writes), not a direct field poke: writing `Some(authority)` flips enforcement on so a
2427    /// mixed batch drops the unsigned/bad peers, and a subsequent `None` (lock disabled) clears
2428    /// enforcement so a peer DROPPED while enforced is re-admitted. Exercises the exact `borrow`-based
2429    /// read path `tka_admits` uses — a broken receiver wiring would pass every for_test-field test but
2430    /// fail here.
2431    #[tokio::test]
2432    async fn tka_authority_watch_enables_then_clears_enforcement() {
2433        let (authority, sig) = authority_and_valid_sig();
2434        let mut bad_sig = sig.clone();
2435        let last = bad_sig.len() - 1;
2436        bad_sig[last] ^= 0xff;
2437
2438        let (mut tracker, tka_tx) = PeerTracker::for_test(test_env(), None);
2439
2440        // 1) No authority yet ⇒ admit-all (Go b.tka == nil).
2441        let good = peer_node("good", NODE_KEY_BYTES, sig.clone());
2442        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2443        let bad = peer_node("bad", [9u8; 32], bad_sig);
2444        let batch = ts_control::PeerUpdate::Full(vec![good.clone(), unsigned.clone(), bad.clone()]);
2445        tracker.apply_peer_update(&batch, local_now());
2446        assert_eq!(tracker.peer_db.peers().len(), 3, "no lock ⇒ admit all");
2447
2448        // 2) Publish the verified authority over the watch cell (exactly what the control runner does
2449        //    on a successful sync) ⇒ enforcement ON. A re-applied Full now drops unsigned + bad.
2450        tka_tx.send_replace(Some(Arc::new(authority)));
2451        tracker.apply_peer_update(&batch, local_now());
2452        assert_eq!(
2453            tracker.peer_db.peers().len(),
2454            1,
2455            "lock active ⇒ only the signed peer survives"
2456        );
2457        assert!(tracker.peer_db.get(&good.node_key).is_some());
2458        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
2459        assert!(tracker.peer_db.get(&bad.node_key).is_none());
2460
2461        // 3) Lock disabled (None) ⇒ enforcement cleared ⇒ a peer that was DROPPED while enforced is
2462        //    re-admitted by a fresh netmap. Assert the specific previously-dropped key returns (not
2463        //    merely a count), so this proves the drop→clear→re-admit transition, not "admit-all-fresh".
2464        tka_tx.send_replace(None);
2465        tracker.apply_peer_update(&batch, local_now());
2466        assert_eq!(
2467            tracker.peer_db.peers().len(),
2468            3,
2469            "lock disabled ⇒ admit all again"
2470        );
2471        assert!(
2472            tracker.peer_db.get(&unsigned.node_key).is_some(),
2473            "the peer dropped under enforcement must come back once the lock is cleared"
2474        );
2475        assert!(tracker.peer_db.get(&bad.node_key).is_some());
2476    }
2477
2478    /// The ordering gap this closes. A peer admitted BEFORE the lock synced must be re-checked the
2479    /// moment the authority is installed — not left in the db until control happens to send another
2480    /// `Full`. Go never has this problem: `SetControlClientStatus` runs `tkaSyncIfNeeded` and then
2481    /// `tkaFilterNetmapLocked(st.NetMap)` on the SAME netmap in one pass, so the netmap that
2482    /// announced the lock is itself filtered. Here the sync is a spawned task, so the netmap lands
2483    /// first and `tka_reevaluate_peer_db` is what restores Go's ordering.
2484    ///
2485    /// Note this test applies NO second netmap: the eviction must come from the authority install
2486    /// alone, which is exactly what was missing before.
2487    #[tokio::test]
2488    async fn tka_authority_install_reevaluates_already_admitted_peers() {
2489        let (authority, sig) = authority_and_valid_sig();
2490        let mut bad_sig = sig.clone();
2491        let last = bad_sig.len() - 1;
2492        bad_sig[last] ^= 0xff;
2493
2494        let (mut tracker, tka_tx) = PeerTracker::for_test(test_env(), None);
2495
2496        // 1) A netmap arrives while nothing is synced ⇒ enforcement inactive ⇒ all three admitted.
2497        let good = peer_node("good", NODE_KEY_BYTES, sig);
2498        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2499        let bad = peer_node("bad", [9u8; 32], bad_sig);
2500        tracker.apply_peer_update(
2501            &ts_control::PeerUpdate::Full(vec![good.clone(), unsigned.clone(), bad.clone()]),
2502            local_now(),
2503        );
2504        assert_eq!(tracker.peer_db.peers().len(), 3, "no lock yet ⇒ admit all");
2505        let unsigned_id = tracker
2506            .peer_db
2507            .get(&unsigned.node_key)
2508            .expect("unsigned peer admitted while no lock is synced")
2509            .0;
2510        let bad_id = tracker
2511            .peer_db
2512            .get(&bad.node_key)
2513            .expect("bad-sig peer admitted while no lock is synced")
2514            .0;
2515
2516        // 2) The sync completes and the control runner installs the verified authority.
2517        tka_tx.send_replace(Some(Arc::new(authority)));
2518        let evicted = tracker.tka_reevaluate_peer_db();
2519
2520        assert_eq!(
2521            evicted,
2522            HashSet::from_iter([unsigned_id, bad_id]),
2523            "the unsigned and bad-signature peers are the ones reported evicted"
2524        );
2525        assert_eq!(tracker.peer_db.peers().len(), 1);
2526        assert!(
2527            tracker.peer_db.get(&good.node_key).is_some(),
2528            "the authorized peer stays admitted"
2529        );
2530        assert!(tracker.peer_db.get(&unsigned.node_key).is_none());
2531        assert!(tracker.peer_db.get(&bad.node_key).is_none());
2532
2533        // 3) Idempotent: a second pass over the now-clean db evicts nobody.
2534        assert!(tracker.tka_reevaluate_peer_db().is_empty());
2535    }
2536
2537    /// With no authority the re-evaluation evicts nobody — enforcement is inactive and every peer is
2538    /// admitted, exactly Go's `b.tka == nil` early return. Covers both "never synced" and "the lock
2539    /// was disabled after enforcing", the two ways the cell holds `None`.
2540    #[tokio::test]
2541    async fn tka_reevaluate_without_authority_evicts_nothing() {
2542        let (authority, sig) = authority_and_valid_sig();
2543        let (mut tracker, tka_tx) = PeerTracker::for_test(test_env(), None);
2544
2545        let good = peer_node("good", NODE_KEY_BYTES, sig);
2546        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2547        tracker.apply_peer_update(
2548            &ts_control::PeerUpdate::Full(vec![good.clone(), unsigned.clone()]),
2549            local_now(),
2550        );
2551
2552        // Never synced.
2553        assert!(tracker.tka_reevaluate_peer_db().is_empty());
2554        assert_eq!(tracker.peer_db.peers().len(), 2);
2555
2556        // Enforced, then disabled: the disable must not evict the peer the lock had authorized, and
2557        // must not start dropping the unsigned one either.
2558        tka_tx.send_replace(Some(Arc::new(authority)));
2559        assert_eq!(tracker.tka_reevaluate_peer_db().len(), 1);
2560        tka_tx.send_replace(None);
2561        assert!(tracker.tka_reevaluate_peer_db().is_empty());
2562        assert!(tracker.peer_db.get(&good.node_key).is_some());
2563    }
2564
2565    /// The re-evaluation runs the WHOLE Go `tkaFilterNetmapLocked` pass, not just the per-peer
2566    /// signature check: a peer presenting a node key that a newer rotation superseded is evicted too,
2567    /// even though its own `Direct` signature still verifies against the authority. Both peers are
2568    /// already in the db when the authority lands, so the cross-peer rotation filter has to run over
2569    /// the db contents — which is why `tka_keep_verdicts` is shared with the `Full` path rather than
2570    /// re-derived here.
2571    #[tokio::test]
2572    async fn tka_reevaluate_applies_the_cross_peer_rotation_filter() {
2573        use ed25519_dalek::SigningKey;
2574        use ts_tka::NodeKeySignature;
2575
2576        let trusted = SigningKey::from_bytes(&[42u8; 32]);
2577        let authority = Authority::from_state(
2578            AumHash([0; 32]),
2579            State {
2580                keys: vec![Key {
2581                    kind: KeyKind::Ed25519,
2582                    votes: 1,
2583                    public: trusted.verifying_key().to_bytes().to_vec(),
2584                }],
2585            },
2586        );
2587        // `stale` holds the pivot key with a valid Direct signature; `rotated` holds a key whose
2588        // rotation chain rotated the pivot key AWAY, which obsoletes `stale`.
2589        let pivot = SigningKey::from_bytes(&[9u8; 32]);
2590        let pivot_pub: [u8; 32] = pivot.verifying_key().to_bytes();
2591        let stale = peer_node(
2592            "stale",
2593            pivot_pub,
2594            NodeKeySignature::sign_direct(&pivot_pub, &trusted).serialize(),
2595        );
2596        let new_key = [4u8; 32];
2597        let rotated = peer_node(
2598            "rotated",
2599            new_key,
2600            NodeKeySignature::sign_rotation(&new_key, &trusted, &pivot).serialize(),
2601        );
2602
2603        // Both admitted while nothing is synced.
2604        let (mut tracker, tka_tx) = PeerTracker::for_test(test_env(), None);
2605        tracker.apply_peer_update(
2606            &ts_control::PeerUpdate::Full(vec![stale.clone(), rotated.clone()]),
2607            local_now(),
2608        );
2609        assert_eq!(tracker.peer_db.peers().len(), 2, "no lock yet ⇒ admit all");
2610
2611        tka_tx.send_replace(Some(Arc::new(authority)));
2612        let evicted = tracker.tka_reevaluate_peer_db();
2613
2614        assert_eq!(
2615            evicted.len(),
2616            1,
2617            "only the rotation-obsolete peer is evicted"
2618        );
2619        assert!(
2620            tracker.peer_db.get(&rotated.node_key).is_some(),
2621            "the freshly-rotated peer stays"
2622        );
2623        assert!(
2624            tracker.peer_db.get(&stale.node_key).is_none(),
2625            "the peer whose key a rotation superseded is evicted, though its own signature verifies"
2626        );
2627    }
2628
2629    /// A `StateUpdate` carrying nothing but a `Full` peer set — the netmap shape the live-actor test
2630    /// publishes on the bus.
2631    pub(crate) fn netmap_with_peers(peers: Vec<Node>) -> ts_control::StateUpdate {
2632        ts_control::StateUpdate {
2633            session_handle: None,
2634            seq: 0,
2635            keep_alive: false,
2636            derp: None,
2637            node: None,
2638            peer_update: Some(ts_control::PeerUpdate::Full(peers)),
2639            peer_patches: Vec::new(),
2640            user_profiles: Vec::new(),
2641            ping: None,
2642            packetfilter: None,
2643            cap_grants: None,
2644            pop_browser_url: None,
2645            dial_plan: None,
2646            dns_config: None,
2647            ssh_policy: None,
2648            tka: None,
2649            online_change: Default::default(),
2650            peer_seen_change: Default::default(),
2651            control_time: None,
2652        }
2653    }
2654
2655    /// Poll a live [`PeerTracker`] until it holds exactly `want` peers, bounded by a timeout so a
2656    /// broken wiring fails the test instead of hanging the suite.
2657    pub(crate) async fn await_peer_count(
2658        tracker: &ActorRef<PeerTracker>,
2659        want: usize,
2660    ) -> Vec<Node> {
2661        let settled = tokio::time::timeout(std::time::Duration::from_secs(10), async {
2662            loop {
2663                let peers = tracker.ask(AllPeers).await.expect("peer tracker is alive");
2664                if peers.len() == want {
2665                    return peers;
2666                }
2667                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
2668            }
2669        })
2670        .await;
2671        settled.unwrap_or_else(|_| panic!("peer tracker never settled at {want} peer(s)"))
2672    }
2673
2674    /// End-to-end through the LIVE actor, which is the only thing that proves the wiring: the peer
2675    /// tracker watches its own enforcement cell, so the control runner's `send_replace` re-filters
2676    /// the peer db with no further netmap. If the watch task were never spawned (or the message not
2677    /// handled) the unsigned peer would stay admitted forever — a hole every `for_test` unit test
2678    /// above would still pass over, because they call the re-evaluation by hand.
2679    #[tokio::test]
2680    async fn tka_authority_change_refilters_through_the_live_actor() {
2681        use kameo::actor::Spawn as _;
2682
2683        let (authority, sig) = authority_and_valid_sig();
2684        let env = test_env();
2685        let (tka_tx, tka_rx) = watch::channel(None);
2686        let tracker = PeerTracker::spawn((env.clone(), tka_rx));
2687
2688        // Await one reply first: the actor's `on_start` (which registers it on the bus) has then
2689        // completed, so the netmap published below cannot race the subscription.
2690        assert!(
2691            tracker
2692                .ask(AllPeers)
2693                .await
2694                .expect("peer tracker started")
2695                .is_empty()
2696        );
2697
2698        let good = peer_node("good", NODE_KEY_BYTES, sig);
2699        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2700        env.publish(Arc::new(netmap_with_peers(vec![
2701            good.clone(),
2702            unsigned.clone(),
2703        ])))
2704        .await
2705        .expect("publish netmap");
2706
2707        // No lock synced ⇒ both peers land.
2708        await_peer_count(&tracker, 2).await;
2709
2710        // The control runner installs the verified authority. No netmap follows.
2711        tka_tx.send_replace(Some(Arc::new(authority)));
2712
2713        let peers = await_peer_count(&tracker, 1).await;
2714        assert_eq!(
2715            peers[0].stable_id, good.stable_id,
2716            "only the authorized peer survives the authority install"
2717        );
2718    }
2719
2720    /// Degenerate input: two DISTINCT nodes sharing one `stable_id` in a single `Full`, one with a
2721    /// valid signature and one unsigned, under an active lock. Each node is judged by its OWN verdict
2722    /// (the per-node `admits` vector), so the unsigned node is never admitted on the strength of its
2723    /// signed twin. The single-verify `Full` refactor keeps this per-node semantics (a stable_id-set
2724    /// alone would have admitted whichever node was upserted last). Malformed control input; asserted
2725    /// only to lock the verdict-per-node behavior against regression.
2726    #[tokio::test]
2727    async fn tka_full_duplicate_stable_id_judges_each_node_on_its_own_signature() {
2728        let (authority, sig) = authority_and_valid_sig();
2729        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2730
2731        // Both carry stable_id "dup"; the signed one authorizes NODE_KEY_BYTES, the other is unsigned
2732        // and uses a different node key. Order them unsigned-last so a last-writer-wins stable_id set
2733        // would (wrongly) leave the unsigned node's key in the db.
2734        let signed = peer_node("dup", NODE_KEY_BYTES, sig);
2735        let unsigned = peer_node("dup", [8u8; 32], vec![]);
2736        tracker.apply_peer_update(
2737            &ts_control::PeerUpdate::Full(vec![signed.clone(), unsigned.clone()]),
2738            local_now(),
2739        );
2740
2741        // The unsigned node's own verdict failed, so its key must NOT be present, regardless of the
2742        // shared stable_id. (The signed twin retained the stable_id; the db holds the signed key.)
2743        assert!(
2744            tracker.peer_db.get(&unsigned.node_key).is_none(),
2745            "a node whose own signature fails must not be admitted via a stable_id twin"
2746        );
2747        assert!(tracker.peer_db.get(&signed.node_key).is_some());
2748    }
2749
2750    /// Full-path consistency under two KEPT nodes sharing a `stable_id`: `peer_db.upsert` is
2751    /// last-writer-wins on `stable_id`, so the db ends holding exactly one node for that id (the last
2752    /// kept), and `retain` never evicts that just-upserted id (`retained_ids` contains the shared id
2753    /// because at least one of its nodes was kept). No lock here, so both nodes are "kept". This pins
2754    /// the published-state invariant the whole-surface audit flagged: `retain` and the upsert loop
2755    /// agree on the surviving stable_id. Malformed control input; asserted for robustness.
2756    #[tokio::test]
2757    async fn tka_full_duplicate_stable_id_both_kept_is_consistent() {
2758        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
2759        let first = peer_node("dup", [1u8; 32], vec![]);
2760        let last = peer_node("dup", [2u8; 32], vec![]);
2761        tracker.apply_peer_update(
2762            &ts_control::PeerUpdate::Full(vec![first.clone(), last.clone()]),
2763            local_now(),
2764        );
2765
2766        // Exactly one db entry for the shared stable_id, holding the LAST node (upsert is
2767        // last-writer-wins on stable_id); the first node's key was transparently superseded.
2768        assert_eq!(
2769            tracker.peer_db.peers().len(),
2770            1,
2771            "one entry for the shared stable_id"
2772        );
2773        assert!(
2774            tracker.peer_db.get(&last.node_key).is_some(),
2775            "the db holds the last-upserted node for the shared id"
2776        );
2777        assert!(
2778            tracker.peer_db.get(&first.node_key).is_none(),
2779            "the first node's key was superseded by the last at the shared id"
2780        );
2781    }
2782
2783    /// A peer admitted in one `Full`, then in a later `Full` presenting a key that a co-resident
2784    /// peer's rotation chain has rotated away, is EVICTED — the cross-peer rotation filter applies on
2785    /// every resync, not only at first admission. Exercises the rotation filter through two
2786    /// sequential `Full` updates with real signing.
2787    #[tokio::test]
2788    async fn tka_full_rotation_obsolete_evicts_on_resync() {
2789        use ed25519_dalek::SigningKey;
2790        use ts_tka::NodeKeySignature;
2791
2792        let trusted = SigningKey::from_bytes(&[42u8; 32]);
2793        let trusted_pub = trusted.verifying_key().to_bytes().to_vec();
2794        let authority = Authority::from_state(
2795            AumHash([0; 32]),
2796            State {
2797                keys: vec![Key {
2798                    kind: KeyKind::Ed25519,
2799                    votes: 1,
2800                    public: trusted_pub.clone(),
2801                }],
2802            },
2803        );
2804        let pivot = SigningKey::from_bytes(&[9u8; 32]);
2805        let pivot_pub: [u8; 32] = pivot.verifying_key().to_bytes();
2806
2807        // First Full: the soon-to-be-stale peer presents the pivot key with a valid Direct sig.
2808        let stale_sig = NodeKeySignature::sign_direct(&pivot_pub, &trusted).serialize();
2809        let stale_peer = peer_node("stale", pivot_pub, stale_sig);
2810        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2811        tracker.apply_peer_update(
2812            &ts_control::PeerUpdate::Full(vec![stale_peer.clone()]),
2813            local_now(),
2814        );
2815        assert!(
2816            tracker.peer_db.get(&stale_peer.node_key).is_some(),
2817            "the stale peer is admitted while no rotation has superseded it yet"
2818        );
2819
2820        // Second Full: a freshly-rotated peer (whose chain rotated AWAY the pivot key) joins, and the
2821        // stale peer is re-included. The rotation filter now obsoletes the pivot key ⇒ stale evicted.
2822        let new_key = [4u8; 32];
2823        let new_sig = NodeKeySignature::sign_rotation(&new_key, &trusted, &pivot).serialize();
2824        let new_peer = peer_node("rotated", new_key, new_sig);
2825        tracker.apply_peer_update(
2826            &ts_control::PeerUpdate::Full(vec![new_peer.clone(), stale_peer.clone()]),
2827            local_now(),
2828        );
2829        assert!(
2830            tracker.peer_db.get(&new_peer.node_key).is_some(),
2831            "the freshly-rotated peer is admitted"
2832        );
2833        assert!(
2834            tracker.peer_db.get(&stale_peer.node_key).is_none(),
2835            "the stale peer is EVICTED on the resync once a rotation supersedes its key"
2836        );
2837    }
2838
2839    /// The empty-trusted-key-state brick-guard: an authority with no keys must NOT drop the whole
2840    /// netmap (a `ts_tka` invariant violation / replayer edge). A verified chain always carries ≥1
2841    /// key, so this never weakens a genuine lock — it only prevents a black-hole. Uses ≥2 peers
2842    /// (one signed, one unsigned) to prove it admits **all**, not accidentally just one.
2843    #[tokio::test]
2844    async fn tka_empty_keyset_authority_admits_all() {
2845        use ts_tka::{AumHash, Authority, State};
2846        let empty_auth = Authority::from_state(AumHash([0u8; 32]), State { keys: Vec::new() });
2847        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(empty_auth));
2848        let signed = peer_node("signed", [7u8; 32], vec![0xde, 0xad]);
2849        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2850        tracker.apply_peer_update(
2851            &ts_control::PeerUpdate::Full(vec![signed.clone(), unsigned.clone()]),
2852            local_now(),
2853        );
2854        assert_eq!(
2855            tracker.peer_db.peers().len(),
2856            2,
2857            "an empty-keyset authority must admit ALL peers (brick-guard), not enforce"
2858        );
2859    }
2860
2861    /// Signature-replay / `NodeKeyMismatch`: a structurally-valid signature that authorizes
2862    /// `NODE_KEY_BYTES` must NOT admit a DIFFERENT node key carrying that same signature blob. This is
2863    /// the highest-value bypass — if the sig↔node-key binding in `verify_signature` were dropped, this
2864    /// is the only test that would catch it (the other "bad" peers only flip a byte ⇒ `BadSignature`).
2865    #[tokio::test]
2866    async fn tka_active_rejects_valid_sig_for_wrong_node_key() {
2867        let (authority, sig) = authority_and_valid_sig();
2868        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2869
2870        // The signature authorizes NODE_KEY_BYTES; attach it to an imposter with a different key.
2871        let imposter = peer_node("imposter", [0x55u8; 32], sig);
2872        assert!(
2873            !tracker.tka_admits(&imposter),
2874            "a signature bound to one node key must not authorize a different node key"
2875        );
2876        tracker.apply_peer_update(
2877            &ts_control::PeerUpdate::Full(vec![imposter.clone()]),
2878            local_now(),
2879        );
2880        assert!(tracker.peer_db.get(&imposter.node_key).is_none());
2881    }
2882
2883    /// `UntrustedKey`: a signature produced by a well-formed Ed25519 key that is NOT in the
2884    /// authority's trusted-key state must be rejected — distinct from a tampered-byte `BadSignature`.
2885    #[tokio::test]
2886    async fn tka_active_rejects_sig_from_untrusted_key() {
2887        use ed25519_dalek::{Signer, SigningKey};
2888        let (authority, _sig) = authority_and_valid_sig();
2889        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2890
2891        // Sign a valid CBOR with a DIFFERENT key (not the one the authority trusts). The key_id in
2892        // the signature names this untrusted key, so `get_key` misses ⇒ UntrustedKey.
2893        let rogue = SigningKey::from_bytes(&[99u8; 32]);
2894        let rogue_pub = rogue.verifying_key().to_bytes().to_vec();
2895        let preimage = direct_sig_cbor(&NODE_KEY_BYTES, &rogue_pub, None);
2896        let sig_hash = ts_tka::aum_hash(&preimage).0;
2897        let signature = rogue.sign(&sig_hash).to_bytes().to_vec();
2898        let rogue_cbor = direct_sig_cbor(&NODE_KEY_BYTES, &rogue_pub, Some(&signature));
2899
2900        let peer = peer_node("rogue-signed", NODE_KEY_BYTES, rogue_cbor);
2901        assert!(
2902            !tracker.tka_admits(&peer),
2903            "a signature from a key outside the trusted set must be rejected"
2904        );
2905        // Drive the real upsert path too (match the sibling replay test's depth): an untrusted-key
2906        // signature must keep the peer out of the db, not merely fail the verdict in isolation.
2907        tracker.apply_peer_update(
2908            &ts_control::PeerUpdate::Full(vec![peer.clone()]),
2909            local_now(),
2910        );
2911        assert!(tracker.peer_db.get(&peer.node_key).is_none());
2912    }
2913
2914    /// Bus-enable analogue for `Delta`: enforcement engaged via the watch cell must also gate a
2915    /// `Delta { upsert }` (not only `Full`). Closes the "authority arrived over the transport AND the
2916    /// next update is a Delta" combination.
2917    #[tokio::test]
2918    async fn tka_watch_enable_enforces_delta_upsert() {
2919        let (authority, sig) = authority_and_valid_sig();
2920        let (mut tracker, tka_tx) = PeerTracker::for_test(test_env(), None);
2921        tka_tx.send_replace(Some(Arc::new(authority)));
2922
2923        let good = peer_node("good", NODE_KEY_BYTES, sig);
2924        let unsigned = peer_node("unsigned", [8u8; 32], vec![]);
2925        tracker.apply_peer_update(
2926            &ts_control::PeerUpdate::Delta {
2927                remove: vec![],
2928                upsert: vec![good.clone(), unsigned.clone()],
2929            },
2930            local_now(),
2931        );
2932        assert!(tracker.peer_db.get(&good.node_key).is_some());
2933        assert!(
2934            tracker.peer_db.get(&unsigned.node_key).is_none(),
2935            "delta upsert under an active lock must drop the unsigned peer"
2936        );
2937    }
2938
2939    /// A `Delta` re-upsert of an ALREADY-ADMITTED peer whose signature is now invalid must EVICT the
2940    /// stale entry (revocation-via-delta), not leave it admitted. Go re-filters the whole netmap each
2941    /// response, so a now-unsigned peer would not survive there either.
2942    #[tokio::test]
2943    async fn tka_delta_reupsert_with_invalid_sig_evicts_existing() {
2944        let (authority, sig) = authority_and_valid_sig();
2945        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2946
2947        // Admit the signed peer.
2948        let good = peer_node("good", NODE_KEY_BYTES, sig.clone());
2949        tracker.apply_peer_update(
2950            &ts_control::PeerUpdate::Full(vec![good.clone()]),
2951            local_now(),
2952        );
2953        assert!(tracker.peer_db.get(&good.node_key).is_some());
2954
2955        // Re-upsert the SAME stable_id (now with no signature) via a delta ⇒ evicted, not retained.
2956        let revoked = peer_node("good", NODE_KEY_BYTES, vec![]);
2957        tracker.apply_peer_update(
2958            &ts_control::PeerUpdate::Delta {
2959                remove: vec![],
2960                upsert: vec![revoked],
2961            },
2962            local_now(),
2963        );
2964        assert!(
2965            tracker.peer_db.get(&good.node_key).is_none(),
2966            "a delta re-upsert that fails the lock must evict the previously-admitted peer"
2967        );
2968    }
2969
2970    #[tokio::test]
2971    async fn tka_full_resync_revocation_behavior() {
2972        // Revocation-on-resync: admit a peer, then re-include the SAME stable_id in a `Full` with a
2973        // now-invalid signature. Per the Logic review finding, the pre-fix `retain` kept the stale
2974        // (previously-admitted) entry because membership was decided purely by stable_id.
2975        //
2976        // FIXED (not merely documented): the `Full` `retain` now keys on `tka_admits`-passing
2977        // stable_ids, so a peer whose re-included signature no longer verifies under the active
2978        // authority is EVICTED. This test asserts eviction. The inactive (authority=None) path is
2979        // provably unchanged — `tka_admits` always returns `true` there, so the retained set equals
2980        // the set of re-included stable_ids exactly (see `tka_inactive_full_resync_keeps_*`).
2981        let (authority, sig) = authority_and_valid_sig();
2982        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
2983
2984        // 1) Admit the peer with a valid signature via a real `Full`.
2985        let good = peer_node("revoked", NODE_KEY_BYTES, sig.clone());
2986        tracker.apply_peer_update(
2987            &ts_control::PeerUpdate::Full(vec![good.clone()]),
2988            local_now(),
2989        );
2990        assert_eq!(tracker.peer_db.peers().len(), 1);
2991        assert!(tracker.peer_db.get(&good.node_key).is_some());
2992
2993        // 2) Re-sync the SAME stable_id, but with a now-invalid signature (tamper trailing byte).
2994        let mut bad_sig = sig;
2995        let last = bad_sig.len() - 1;
2996        bad_sig[last] ^= 0xff;
2997        let revoked = peer_node("revoked", NODE_KEY_BYTES, bad_sig);
2998        tracker.apply_peer_update(
2999            &ts_control::PeerUpdate::Full(vec![revoked.clone()]),
3000            local_now(),
3001        );
3002
3003        // Eviction: the stale entry is dropped because its re-included signature fails the gate.
3004        assert_eq!(tracker.peer_db.peers().len(), 0);
3005        assert!(tracker.peer_db.get(&revoked.node_key).is_none());
3006    }
3007
3008    #[tokio::test]
3009    async fn tka_inactive_full_resync_keeps_reincluded_peer() {
3010        // Guard the inactive (authority=None) path against the revocation fix: with no authority,
3011        // a peer re-included in a `Full` survives regardless of its signature bytes — byte-for-byte
3012        // pre-TKA behavior, proving the `Full` `retain` change does not regress the always-taken
3013        // branch this wave.
3014        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3015
3016        let peer = peer_node("p", NODE_KEY_BYTES, vec![0xde, 0xad]);
3017        tracker.apply_peer_update(
3018            &ts_control::PeerUpdate::Full(vec![peer.clone()]),
3019            local_now(),
3020        );
3021        assert_eq!(tracker.peer_db.peers().len(), 1);
3022
3023        // Re-sync the same stable_id with garbage signature bytes; inactive enforcement keeps it.
3024        let resynced = peer_node("p", NODE_KEY_BYTES, vec![0x00]);
3025        tracker.apply_peer_update(
3026            &ts_control::PeerUpdate::Full(vec![resynced.clone()]),
3027            local_now(),
3028        );
3029        assert_eq!(tracker.peer_db.peers().len(), 1);
3030        assert!(tracker.peer_db.get(&resynced.node_key).is_some());
3031    }
3032
3033    /// A `Patch` for a peer already in the netmap merges only the fields it carries — here new UDP
3034    /// endpoints and a new home DERP — leaving the rest of the node intact. This is the fix for
3035    /// dropped `peers_changed_patch`: without it the netmap keeps stale endpoints and the peer can
3036    /// never re-handshake after it moves.
3037    #[tokio::test]
3038    async fn patch_merges_endpoints_and_derp_into_existing_peer() {
3039        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3040
3041        // Seed a peer (id == 1, per `peer_node`) with no endpoints / no DERP.
3042        let peer = peer_node("mover", [1u8; 32], vec![]);
3043        tracker.apply_peer_update(
3044            &ts_control::PeerUpdate::Full(vec![peer.clone()]),
3045            local_now(),
3046        );
3047        let (_pid, before) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
3048        assert!(before.underlay_addresses.is_empty());
3049        assert!(before.derp_region.is_none());
3050
3051        // Patch in fresh reachability (the idle-peer-reconnect case).
3052        let new_ep: std::net::SocketAddr = "203.0.113.7:41641".parse().unwrap();
3053        let patch = ts_control::PeerChange {
3054            id: 1,
3055            derp_region: Some(ts_derp::RegionId(core::num::NonZeroU32::new(5).unwrap())),
3056            cap: None,
3057            cap_map: None,
3058            underlay_addresses: Some(vec![new_ep]),
3059            node_key: None,
3060            key_signature: None,
3061            disco_key: None,
3062            node_key_expiry: None,
3063            online: None,
3064            last_seen: None,
3065        };
3066        let (upserts, deletions) =
3067            tracker.apply_peer_patches(std::slice::from_ref(&patch), local_now());
3068
3069        assert_eq!(upserts.len(), 1);
3070        assert_eq!(deletions.len(), 0);
3071        // Same peer, now carrying the patched endpoint + DERP; node key untouched.
3072        assert_eq!(tracker.peer_db.peers().len(), 1);
3073        let (_pid, after) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
3074        assert_eq!(after.underlay_addresses, vec![new_ep]);
3075        assert_eq!(
3076            after.derp_region,
3077            Some(ts_derp::RegionId(core::num::NonZeroU32::new(5).unwrap()))
3078        );
3079        assert_eq!(after.node_key, peer.node_key);
3080    }
3081
3082    /// Regression for `tsr-5u0`: when a whole-node set (`Delta`/`Full`) and a patch co-occur in one
3083    /// response, the patch is applied *on top of* the node the set just upserted — mirroring the
3084    /// handler's apply-order (peer set first, then `peer_patches`). Before the fix the patch shared
3085    /// the single `peer_update` slot and the co-occurring set silently dropped it, so a peer brought
3086    /// in by the delta kept stale (empty) reachability.
3087    #[tokio::test]
3088    async fn patch_applies_on_top_of_co_occurring_delta() {
3089        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3090
3091        // The whole-node delta upserts a brand-new peer (id == 1) with no reachability.
3092        let peer = peer_node("mover", [1u8; 32], vec![]);
3093        let (set_upserts, _) = tracker.apply_peer_update(
3094            &ts_control::PeerUpdate::Delta {
3095                upsert: vec![peer.clone()],
3096                remove: vec![],
3097            },
3098            local_now(),
3099        );
3100        assert_eq!(set_upserts.len(), 1, "delta upserts the new peer");
3101
3102        // The patch from the SAME response then sets that peer's endpoints + DERP. This is exactly
3103        // the consumer order the handler runs (apply_peer_update then apply_peer_patches).
3104        let new_ep: std::net::SocketAddr = "203.0.113.7:41641".parse().unwrap();
3105        let patch = ts_control::PeerChange {
3106            id: 1,
3107            derp_region: Some(ts_derp::RegionId(core::num::NonZeroU32::new(7).unwrap())),
3108            cap: None,
3109            cap_map: None,
3110            underlay_addresses: Some(vec![new_ep]),
3111            node_key: None,
3112            key_signature: None,
3113            disco_key: None,
3114            node_key_expiry: None,
3115            online: None,
3116            last_seen: None,
3117        };
3118        let (patch_upserts, patch_deletions) =
3119            tracker.apply_peer_patches(std::slice::from_ref(&patch), local_now());
3120
3121        assert_eq!(
3122            patch_upserts.len(),
3123            1,
3124            "patch re-upserts the just-added peer"
3125        );
3126        assert_eq!(patch_deletions.len(), 0);
3127        // The peer added by the delta now carries the patched reachability — the patch was NOT lost.
3128        let (_pid, after) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
3129        assert_eq!(after.underlay_addresses, vec![new_ep]);
3130        assert_eq!(
3131            after.derp_region,
3132            Some(ts_derp::RegionId(core::num::NonZeroU32::new(7).unwrap()))
3133        );
3134    }
3135
3136    /// The node attribute by which control switches this node off the incremental netmap path
3137    /// (Go `tailcfg/nodecap`'s `DisableDeltaUpdates`).
3138    const DISABLE_DELTA_UPDATES: &str = "disable-delta-updates";
3139
3140    /// A second peer, distinct from `peer_node`'s single node in every indexed field: control node
3141    /// id, stable id, node key and tailnet addresses. Used as the peer NO patch names, so a test can
3142    /// tell "only the patched node was installed" from "the whole netmap was installed".
3143    fn other_peer_node(stable_id: &str) -> Node {
3144        let mut node = peer_node(stable_id, [2u8; 32], vec![]);
3145        node.id = 2;
3146        node.addresses = vec![
3147            "100.64.0.2/32".parse().unwrap(),
3148            "fd7a:115c:a1e0::2/128".parse().unwrap(),
3149        ];
3150        node.tailnet_address = TailnetAddress {
3151            ipv4: "100.64.0.2/32".parse().unwrap(),
3152            ipv6: "fd7a:115c:a1e0::2/128".parse().unwrap(),
3153        };
3154        node
3155    }
3156
3157    /// A self node carrying `attrs` in its capability map — the channel control uses to set node
3158    /// attributes, and the one `Node::delta_updates_disabled` reads.
3159    fn self_node_with(attrs: &[&str]) -> Node {
3160        let mut node = peer_node("self", [9u8; 32], vec![]);
3161        for attr in attrs {
3162            node.cap_map.insert((*attr).to_string(), vec![]);
3163        }
3164        node
3165    }
3166
3167    /// A reachability patch (new UDP endpoint) for the peer with control node id `id`.
3168    fn endpoint_patch(
3169        id: ts_control::NodeId,
3170        endpoint: std::net::SocketAddr,
3171    ) -> ts_control::PeerChange {
3172        ts_control::PeerChange {
3173            id,
3174            derp_region: None,
3175            cap: None,
3176            cap_map: None,
3177            underlay_addresses: Some(vec![endpoint]),
3178            node_key: None,
3179            key_signature: None,
3180            disco_key: None,
3181            node_key_expiry: None,
3182            online: None,
3183            last_seen: None,
3184        }
3185    }
3186
3187    /// The positive assertion the escape hatch is measured against: with `disable-delta-updates`
3188    /// ABSENT the patch path is exactly what it was — the patched peer is re-installed and reported,
3189    /// and a peer no patch names is left alone. This is the default and the overwhelmingly common
3190    /// case, so it is the one that must not move.
3191    #[tokio::test]
3192    async fn a_patch_without_the_attribute_installs_only_the_patched_peer() {
3193        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3194        tracker.apply_peer_update(
3195            &ts_control::PeerUpdate::Full(vec![
3196                peer_node("a", [1u8; 32], vec![]),
3197                other_peer_node("b"),
3198            ]),
3199            local_now(),
3200        );
3201        // A self node with no attributes at all: control has said nothing about delta updates.
3202        tracker.self_node = Some(self_node_with(&[]));
3203
3204        let new_ep: std::net::SocketAddr = "203.0.113.7:41641".parse().unwrap();
3205        let patch = endpoint_patch(1, new_ep);
3206        let (upserts, deletions) =
3207            tracker.apply_peer_patch_set(std::slice::from_ref(&patch), local_now());
3208
3209        assert!(deletions.is_empty());
3210        assert_eq!(
3211            upserts.len(),
3212            1,
3213            "the incremental path installs the patch's mutation, not the whole netmap"
3214        );
3215        let (patched_id, patched) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
3216        assert_eq!(patched.underlay_addresses, vec![new_ep]);
3217        assert!(upserts.contains(&patched_id));
3218        let (unpatched_id, unpatched) = tracker.peer_db.get(&(2 as ts_control::NodeId)).unwrap();
3219        assert!(
3220            unpatched.underlay_addresses.is_empty(),
3221            "a peer no patch names keeps its own reachability"
3222        );
3223        assert!(
3224            !upserts.contains(&unpatched_id),
3225            "and is not reported as installed by the delta path"
3226        );
3227    }
3228
3229    /// Control's escape hatch: with `disable-delta-updates` set, a response carrying ONLY
3230    /// `PeersChangedPatch` is still applied — as a full netmap update. The attribute declines the
3231    /// incremental arm, exactly as Go's `tryHandleIncrementally` returning `false` does; it neither
3232    /// rejects the response nor drops the patches, so asserting the patch is *ignored* here would
3233    /// pin the opposite of upstream's behaviour.
3234    #[tokio::test]
3235    async fn disable_delta_updates_applies_a_patch_only_response_as_a_full_update() {
3236        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3237        tracker.apply_peer_update(
3238            &ts_control::PeerUpdate::Full(vec![
3239                peer_node("a", [1u8; 32], vec![]),
3240                other_peer_node("b"),
3241            ]),
3242            local_now(),
3243        );
3244        tracker.self_node = Some(self_node_with(&[DISABLE_DELTA_UPDATES]));
3245
3246        let new_ep: std::net::SocketAddr = "203.0.113.7:41641".parse().unwrap();
3247        let patch = endpoint_patch(1, new_ep);
3248        let (upserts, deletions) =
3249            tracker.apply_peer_patch_set(std::slice::from_ref(&patch), local_now());
3250
3251        assert!(deletions.is_empty(), "the fall-back never drops a peer");
3252        // Applied, not dropped: the patched field is in the netmap.
3253        let (patched_id, patched) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
3254        assert_eq!(
3255            patched.underlay_addresses,
3256            vec![new_ep],
3257            "the patch is still applied under the attribute"
3258        );
3259        // And applied as a FULL update: every retained peer is re-installed and reported, not just
3260        // the one the patch named.
3261        assert_eq!(tracker.peer_db.peers().len(), 2, "no peer is evicted");
3262        let (unpatched_id, unpatched) = tracker.peer_db.get(&(2 as ts_control::NodeId)).unwrap();
3263        assert_eq!(
3264            upserts,
3265            HashSet::from_iter([patched_id, unpatched_id]),
3266            "the full arm installs the whole netmap, not the patch's mutation"
3267        );
3268        assert!(
3269            unpatched.underlay_addresses.is_empty(),
3270            "re-installing a peer no patch named does not invent state for it"
3271        );
3272    }
3273
3274    /// Under the attribute the `Peers*`-then-patch order the module documents is unchanged: the
3275    /// whole-node set is applied first (by the caller) and the patch lands on top of the node that
3276    /// set just upserted, rather than the patch being overwritten by the netmap re-install.
3277    #[tokio::test]
3278    async fn disable_delta_updates_keeps_the_peer_set_then_patch_ordering() {
3279        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3280        tracker.self_node = Some(self_node_with(&[DISABLE_DELTA_UPDATES]));
3281
3282        // The whole-node delta from this response brings in a peer with no reachability...
3283        tracker.apply_peer_update(
3284            &ts_control::PeerUpdate::Delta {
3285                upsert: vec![peer_node("mover", [1u8; 32], vec![])],
3286                remove: vec![],
3287            },
3288            local_now(),
3289        );
3290
3291        // ...and the patch from the SAME response then sets its endpoints, second.
3292        let new_ep: std::net::SocketAddr = "203.0.113.7:41641".parse().unwrap();
3293        let patch = endpoint_patch(1, new_ep);
3294        let (upserts, _deletions) =
3295            tracker.apply_peer_patch_set(std::slice::from_ref(&patch), local_now());
3296
3297        assert_eq!(upserts.len(), 1, "one peer in the netmap, so one installed");
3298        let (_pid, after) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
3299        assert_eq!(
3300            after.underlay_addresses,
3301            vec![new_ep],
3302            "the patch is applied on top of the peer set, not lost to the re-install"
3303        );
3304    }
3305
3306    /// End-to-end through the LIVE actor, which is the only thing that proves the read is wired to
3307    /// the right node and the right response: control grants `disable-delta-updates` on the self
3308    /// node of the very response that carries the patches, and the patches must still land. A
3309    /// self-node attribute read from the wrong place (or one response late) would silently leave
3310    /// this node on the incremental path control just asked it to leave.
3311    #[tokio::test]
3312    async fn disable_delta_updates_takes_effect_on_the_response_that_grants_it() {
3313        use kameo::actor::Spawn as _;
3314
3315        let env = test_env();
3316        let (_tka_tx, tka_rx) = watch::channel(None);
3317        let tracker = PeerTracker::spawn((env.clone(), tka_rx));
3318
3319        // Await one reply first so `on_start` (which subscribes the actor to the bus) has run.
3320        assert!(
3321            tracker
3322                .ask(AllPeers)
3323                .await
3324                .expect("peer tracker started")
3325                .is_empty()
3326        );
3327
3328        env.publish(Arc::new(netmap_with_peers(vec![
3329            peer_node("a", [1u8; 32], vec![]),
3330            other_peer_node("b"),
3331        ])))
3332        .await
3333        .expect("publish netmap");
3334        await_peer_count(&tracker, 2).await;
3335
3336        // One response: the self node granting the attribute, and nothing but `PeersChangedPatch`.
3337        let new_ep: std::net::SocketAddr = "203.0.113.7:41641".parse().unwrap();
3338        env.publish(Arc::new(ts_control::StateUpdate {
3339            node: Some(self_node_with(&[DISABLE_DELTA_UPDATES])),
3340            peer_update: None,
3341            peer_patches: vec![endpoint_patch(1, new_ep)],
3342            ..netmap_with_peers(Vec::new())
3343        }))
3344        .await
3345        .expect("publish the patch-only response");
3346
3347        let settled = tokio::time::timeout(std::time::Duration::from_secs(10), async {
3348            loop {
3349                let peers = tracker.ask(AllPeers).await.expect("peer tracker is alive");
3350                if peers.iter().any(|p| p.underlay_addresses == vec![new_ep]) {
3351                    return peers;
3352                }
3353                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
3354            }
3355        })
3356        .await;
3357        let peers = settled.expect("the patch-only response is applied under the attribute");
3358        assert_eq!(peers.len(), 2, "the fall-back to full evicts nobody");
3359    }
3360
3361    /// The node attribute by which control tells this node to stop heartbeating its peers (Go
3362    /// `tailcfg/nodecap`'s `SilentDisco`).
3363    const SILENT_DISCO: &str = "silent-disco";
3364
3365    /// A stand-in for the `Arc<PeerState>` subscribers (`DirectManager` among them) that records the
3366    /// `silent_disco` flag of every snapshot the tracker publishes, so a test can read what the
3367    /// direct manager would have been handed without standing up the socket, the dataplane and the
3368    /// DERP mesh behind it.
3369    struct SilentDiscoTap {
3370        seen: Arc<std::sync::Mutex<Vec<bool>>>,
3371    }
3372    impl kameo::Actor for SilentDiscoTap {
3373        type Args = Arc<std::sync::Mutex<Vec<bool>>>;
3374        type Error = Error;
3375        async fn on_start(seen: Self::Args, _s: ActorRef<Self>) -> Result<Self, Self::Error> {
3376            Ok(Self { seen })
3377        }
3378    }
3379    impl Message<Arc<PeerState>> for SilentDiscoTap {
3380        type Reply = ();
3381        async fn handle(&mut self, m: Arc<PeerState>, _c: &mut Context<Self, Self::Reply>) {
3382            self.seen.lock().expect("tap mutex").push(m.silent_disco);
3383        }
3384    }
3385
3386    /// End to end through the live tracker and the bus: control's `silent-disco` attribute on the
3387    /// **self** node rides the published peer snapshot, which is how it reaches
3388    /// `DirectManager` and, from there, the magicsock. Granting and withdrawing both land, and the
3389    /// attribute is read off the self node of the very response that carried it — the same timing
3390    /// `disable-delta-updates` has.
3391    #[tokio::test]
3392    async fn silent_disco_rides_the_published_peer_snapshot() {
3393        use kameo::actor::Spawn as _;
3394
3395        let env = test_env();
3396        let (_tka_tx, tka_rx) = watch::channel(None);
3397        let tracker = PeerTracker::spawn((env.clone(), tka_rx));
3398        let seen: Arc<std::sync::Mutex<Vec<bool>>> = Default::default();
3399        let tap = SilentDiscoTap::spawn(seen.clone());
3400        env.subscribe::<Arc<PeerState>>(&tap)
3401            .await
3402            .expect("subscribe the tap");
3403
3404        // Await one reply so the tracker's `on_start` (which subscribes it to the bus) has run.
3405        assert!(
3406            tracker
3407                .ask(AllPeers)
3408                .await
3409                .expect("peer tracker started")
3410                .is_empty()
3411        );
3412
3413        // A netmap whose self node carries the attribute.
3414        env.publish(Arc::new(ts_control::StateUpdate {
3415            node: Some(self_node_with(&[SILENT_DISCO])),
3416            ..netmap_with_peers(vec![peer_node("a", [1u8; 32], vec![])])
3417        }))
3418        .await
3419        .expect("publish the granting netmap");
3420        await_peer_count(&tracker, 1).await;
3421
3422        let granted = await_tap(&seen, 1).await;
3423        assert_eq!(
3424            granted.last(),
3425            Some(&true),
3426            "the attribute on the self node must reach the peer snapshot the direct manager reads"
3427        );
3428
3429        // Control withdraws it on the next netmap: the flag has to come back down, because
3430        // magicsock's setter is live and would otherwise leave the node silent forever.
3431        env.publish(Arc::new(ts_control::StateUpdate {
3432            node: Some(self_node_with(&[])),
3433            ..netmap_with_peers(vec![peer_node("a", [1u8; 32], vec![])])
3434        }))
3435        .await
3436        .expect("publish the withdrawing netmap");
3437
3438        let withdrawn = await_tap(&seen, granted.len() + 1).await;
3439        assert_eq!(
3440            withdrawn.last(),
3441            Some(&false),
3442            "withdrawing the attribute must publish the node back onto the heartbeat cadence"
3443        );
3444    }
3445
3446    /// Wait for the tap to have recorded at least `want` snapshots, returning them.
3447    async fn await_tap(seen: &Arc<std::sync::Mutex<Vec<bool>>>, want: usize) -> Vec<bool> {
3448        for _ in 0..1000 {
3449            {
3450                let got = seen.lock().expect("tap mutex");
3451                if got.len() >= want {
3452                    return got.clone();
3453                }
3454            }
3455            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
3456        }
3457        panic!("the tap never saw {want} published peer snapshot(s)");
3458    }
3459
3460    /// A `Patch` whose node id is not in the current netmap is ignored (the wire contract: a patch
3461    /// never creates a node). No upsert, no deletion, peer set unchanged.
3462    #[tokio::test]
3463    async fn patch_for_unknown_node_is_ignored() {
3464        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3465        let known = peer_node("known", [1u8; 32], vec![]); // id == 1
3466        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![known]), local_now());
3467
3468        let patch = ts_control::PeerChange {
3469            id: 999, // not in the netmap
3470            derp_region: None,
3471            cap: None,
3472            cap_map: None,
3473            underlay_addresses: Some(vec!["198.51.100.9:1".parse().unwrap()]),
3474            node_key: None,
3475            key_signature: None,
3476            disco_key: None,
3477            node_key_expiry: None,
3478            online: None,
3479            last_seen: None,
3480        };
3481        let (upserts, deletions) =
3482            tracker.apply_peer_patches(std::slice::from_ref(&patch), local_now());
3483
3484        assert_eq!(upserts.len(), 0);
3485        assert_eq!(deletions.len(), 0);
3486        assert_eq!(tracker.peer_db.peers().len(), 1);
3487        assert!(tracker.peer_db.get(&(999 as ts_control::NodeId)).is_none());
3488    }
3489
3490    /// An expiry-only `Patch` updates `node_key_expiry` on the matching peer (Go
3491    /// `PeerChange.KeyExpiry`), rather than being silently dropped until the next full resync.
3492    #[tokio::test]
3493    async fn patch_updates_node_key_expiry() {
3494        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3495        let peer = peer_node("expiring", [1u8; 32], vec![]); // id == 1, node_key_expiry: None
3496        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]), local_now());
3497
3498        let expiry = "2027-01-01T00:00:00Z"
3499            .parse::<chrono::DateTime<chrono::Utc>>()
3500            .unwrap();
3501        let patch = ts_control::PeerChange {
3502            id: 1,
3503            derp_region: None,
3504            cap: None,
3505            cap_map: None,
3506            underlay_addresses: None,
3507            node_key: None,
3508            key_signature: None,
3509            disco_key: None,
3510            node_key_expiry: Some(expiry),
3511            online: None,
3512            last_seen: None,
3513        };
3514        tracker.apply_peer_patches(std::slice::from_ref(&patch), local_now());
3515
3516        let (_pid, after) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
3517        assert_eq!(after.node_key_expiry, Some(expiry));
3518    }
3519
3520    /// Channel B: a `PeerChange.online` patch flips a peer's online state without a full node.
3521    #[tokio::test]
3522    async fn patch_updates_online() {
3523        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3524        let peer = peer_node("p", [1u8; 32], vec![]); // id == 1, online: None
3525        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]), local_now());
3526        assert_eq!(
3527            tracker
3528                .peer_db
3529                .get(&(1 as ts_control::NodeId))
3530                .unwrap()
3531                .1
3532                .online,
3533            None
3534        );
3535
3536        let mut patch = ts_control::PeerChange {
3537            id: 1,
3538            derp_region: None,
3539            cap: None,
3540            cap_map: None,
3541            underlay_addresses: None,
3542            node_key: None,
3543            key_signature: None,
3544            disco_key: None,
3545            node_key_expiry: None,
3546            online: Some(true),
3547            last_seen: None,
3548        };
3549        tracker.apply_peer_patches(std::slice::from_ref(&patch), local_now());
3550        assert_eq!(
3551            tracker
3552                .peer_db
3553                .get(&(1 as ts_control::NodeId))
3554                .unwrap()
3555                .1
3556                .online,
3557            Some(true),
3558            "PeerChange.online=Some(true) marks the peer online"
3559        );
3560
3561        // A subsequent patch flips it offline.
3562        patch.online = Some(false);
3563        tracker.apply_peer_patches(std::slice::from_ref(&patch), local_now());
3564        assert_eq!(
3565            tracker
3566                .peer_db
3567                .get(&(1 as ts_control::NodeId))
3568                .unwrap()
3569                .1
3570                .online,
3571            Some(false)
3572        );
3573    }
3574
3575    /// Channel C/D (Go `map.go:updatePeersStateFromResponse`): `online_change` is the sole driver of
3576    /// `online`; `peer_seen_change` is the sole driver of `last_seen` (true ⇒ now, false ⇒ cleared)
3577    /// and must NEVER touch `online`. Both apply to a peer already in the netmap and ignore unknown
3578    /// ids. This pins the fix for the prior bug where channel D wrote `online=false` (conflating
3579    /// "not seen recently" with "offline" — distinct signals in Go).
3580    #[tokio::test]
3581    async fn liveness_change_maps_apply_online() {
3582        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3583        let peer = peer_node("p", [1u8; 32], vec![]); // id == 1
3584        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]), local_now());
3585        // A fixed timestamp (chrono is built without its `clock` feature, so no `Utc::now()`).
3586        let now = chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap();
3587
3588        // Channel C: online_change sets online=true.
3589        let mut online_change = std::collections::BTreeMap::new();
3590        online_change.insert(1 as ts_control::NodeId, true);
3591        online_change.insert(999 as ts_control::NodeId, true); // unknown id — ignored
3592        let changed = tracker.apply_liveness_changes(&online_change, &Default::default(), now);
3593        assert!(changed);
3594        assert_eq!(
3595            tracker
3596                .peer_db
3597                .get(&(1 as ts_control::NodeId))
3598                .unwrap()
3599                .1
3600                .online,
3601            Some(true)
3602        );
3603
3604        // Channel D: peer_seen_change=true sets last_seen=now and leaves online UNTOUCHED.
3605        let mut seen_true = std::collections::BTreeMap::new();
3606        seen_true.insert(1 as ts_control::NodeId, true);
3607        let changed = tracker.apply_liveness_changes(&Default::default(), &seen_true, now);
3608        assert!(changed);
3609        {
3610            let (_id, node) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
3611            assert_eq!(
3612                node.last_seen,
3613                Some(now),
3614                "peer_seen_change=true sets last_seen=now"
3615            );
3616            assert_eq!(
3617                node.online,
3618                Some(true),
3619                "channel D must NOT touch online (still true from channel C)"
3620            );
3621        }
3622
3623        // Channel D: peer_seen_change=false clears last_seen, still leaving online untouched.
3624        let mut seen_false = std::collections::BTreeMap::new();
3625        seen_false.insert(1 as ts_control::NodeId, false);
3626        let changed = tracker.apply_liveness_changes(&Default::default(), &seen_false, now);
3627        assert!(changed);
3628        {
3629            let (_id, node) = tracker.peer_db.get(&(1 as ts_control::NodeId)).unwrap();
3630            assert_eq!(
3631                node.last_seen, None,
3632                "peer_seen_change=false clears last_seen"
3633            );
3634            assert_eq!(node.online, Some(true), "channel D must NOT mark offline");
3635        }
3636        assert_eq!(
3637            tracker.peer_db.peers().len(),
3638            1,
3639            "the node is retained, not removed"
3640        );
3641
3642        // No-op when nothing matches / changes.
3643        assert!(!tracker.apply_liveness_changes(&Default::default(), &Default::default(), now));
3644    }
3645
3646    /// Security: a `Patch` that rotates the node key must re-satisfy the tailnet-lock authority,
3647    /// exactly like a `Delta` upsert. A key-rotation patch whose new signature does NOT verify
3648    /// evicts the peer (fail-closed) rather than leaving a now-unverified entry — closing what would
3649    /// otherwise be a trust-enforcement bypass via the patch path.
3650    #[tokio::test]
3651    async fn patch_key_rotation_failing_tka_evicts_peer() {
3652        let (authority, sig) = authority_and_valid_sig();
3653        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
3654
3655        // Admit a correctly-signed peer (id == 1).
3656        let good = peer_node("rotator", NODE_KEY_BYTES, sig.clone());
3657        tracker.apply_peer_update(
3658            &ts_control::PeerUpdate::Full(vec![good.clone()]),
3659            local_now(),
3660        );
3661        assert_eq!(tracker.peer_db.peers().len(), 1);
3662
3663        // Patch a new node key whose signature is garbage under the active authority.
3664        let patch = ts_control::PeerChange {
3665            id: 1,
3666            derp_region: None,
3667            cap: None,
3668            cap_map: None,
3669            underlay_addresses: None,
3670            node_key: Some([0x33u8; 32].into()),
3671            key_signature: Some(vec![0x00, 0x01, 0x02]),
3672            disco_key: None,
3673            node_key_expiry: None,
3674            online: None,
3675            last_seen: None,
3676        };
3677        let (upserts, deletions) =
3678            tracker.apply_peer_patches(std::slice::from_ref(&patch), local_now());
3679
3680        assert_eq!(upserts.len(), 0);
3681        assert_eq!(deletions.len(), 1);
3682        assert_eq!(tracker.peer_db.peers().len(), 0);
3683    }
3684
3685    /// A node's `user_id` joins against the accumulated UserProfiles table to resolve the owning
3686    /// user's profile in `WhoIs.user_profile`. With no matching profile, it is `None` (the
3687    /// pre-existing behavior); once a profile arrives, the same node resolves to it. This
3688    /// proves the accumulate-then-join path the netmap handler builds.
3689    fn profile(id: ts_control::UserId, login: &str) -> ts_control::UserProfile {
3690        ts_control::UserProfile {
3691            id,
3692            login_name: login.to_string(),
3693            display_name: None,
3694            groups: Vec::new(),
3695        }
3696    }
3697
3698    #[tokio::test]
3699    async fn whois_resolves_user_from_accumulated_profiles() {
3700        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3701
3702        // A peer owned by user id 42 at 100.64.0.1 (the peer_node fixture's address).
3703        let mut peer = peer_node("p", NODE_KEY_BYTES, Vec::new());
3704        peer.user_id = 42;
3705        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer]), local_now());
3706        let addr = "100.64.0.1:0".parse().unwrap();
3707
3708        // No profile yet: the node resolves but its owner is unknown.
3709        let who = tracker.whois_opt(addr).expect("peer is known");
3710        assert_eq!(who.user_profile, None);
3711        assert_eq!(who.user(), None);
3712
3713        // Profile for a DIFFERENT user must not match.
3714        tracker
3715            .user_profiles
3716            .insert(7, profile(7, "someone-else@example.com"));
3717        assert_eq!(tracker.whois_opt(addr).unwrap().user(), None);
3718
3719        // The owning user's profile arrives (as the netmap handler would accumulate it): now the
3720        // login resolves.
3721        tracker
3722            .user_profiles
3723            .insert(42, profile(42, "alice@example.com"));
3724        assert_eq!(
3725            tracker.whois_opt(addr).unwrap().user(),
3726            Some("alice@example.com".to_string())
3727        );
3728    }
3729
3730    /// The whole carry, end to end: a real `MapResponse` body — the JSON control writes on the map
3731    /// poll — decoded by the production wire types and the production `From` impls, accumulated by
3732    /// the production profile merge, and read back out of `whois`.
3733    ///
3734    /// `Groups` is why `WhoIs` carries the profile rather than one display label: it is the only
3735    /// attribute of an owning user that a node cannot re-derive from anything else in the netmap,
3736    /// so an embedder authorising an inbound connection on group membership has no other source
3737    /// for it. Every hop here is production code; the only thing the test assembles is the
3738    /// `StateUpdate` struct itself (`ts_control`'s frame decode is not public, and its own tests
3739    /// pin the body-to-`StateUpdate` half).
3740    fn state_update_from_body(body: &str) -> ts_control::StateUpdate {
3741        let wire: ts_control_serde::MapResponse<'_> =
3742            serde_json::from_str(body).expect("a real MapResponse body decodes");
3743        let peers = wire
3744            .peers
3745            .as_ref()
3746            .expect("the fixture carries a full peer set")
3747            .iter()
3748            .map(ts_control::Node::from)
3749            .collect();
3750        ts_control::StateUpdate {
3751            user_profiles: wire
3752                .user_profiles
3753                .iter()
3754                .map(ts_control::UserProfile::from)
3755                .collect(),
3756            ..netmap_with_peers(peers)
3757        }
3758    }
3759
3760    /// The body control sends for a tailnet with one peer owned by user 42, whose profile carries
3761    /// `Groups`. `groups` is spliced in so the present and absent cases share one fixture.
3762    fn netmap_body_with_profile_groups(groups: &str) -> String {
3763        format!(
3764            r#"{{
3765                "MapSessionHandle": "sess-1",
3766                "Seq": 9,
3767                "Peers": [{{
3768                    "ID": 2,
3769                    "StableID": "peer-2",
3770                    "Name": "peer.example.ts.net.",
3771                    "Addresses": ["100.64.0.1/32", "fd7a:115c:a1e0::1/128"],
3772                    "User": 42
3773                }}],
3774                "UserProfiles": [{{
3775                    "ID": 42,
3776                    "LoginName": "alice@example.com",
3777                    "DisplayName": "Alice Smith"{groups}
3778                }}]
3779            }}"#
3780        )
3781    }
3782
3783    #[tokio::test]
3784    async fn whois_carries_user_groups_from_a_real_map_response() {
3785        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3786        let update = state_update_from_body(&netmap_body_with_profile_groups(
3787            r#", "Groups": ["engineering@example.com", "group:eng"]"#,
3788        ));
3789
3790        tracker.accumulate_user_profiles(&update.user_profiles);
3791        tracker.apply_peer_update(
3792            update.peer_update.as_ref().expect("a full peer set"),
3793            local_now(),
3794        );
3795
3796        let who = tracker
3797            .whois_opt("100.64.0.1:0".parse().unwrap())
3798            .expect("the peer owns that address");
3799
3800        let profile = who.user_profile.as_ref().expect("user 42's profile");
3801        assert_eq!(profile.id, 42);
3802        assert_eq!(profile.login_name, "alice@example.com");
3803        assert_eq!(profile.display_name.as_deref(), Some("Alice Smith"));
3804        assert_eq!(
3805            who.user_groups(),
3806            ["engineering@example.com", "group:eng"],
3807            "the groups control reported reach the embedder in the order control sent them"
3808        );
3809        // The flattened label the pre-widening `WhoIs.user` field carried is unchanged.
3810        assert_eq!(who.user(), Some("alice@example.com".to_string()));
3811    }
3812
3813    /// The absent case, which is what every control server that does not send the field looks
3814    /// like: no `Groups` key at all. That must yield a profile with an EMPTY group list — never a
3815    /// missing profile, and never a failed decode that would drop the owner identity entirely.
3816    #[tokio::test]
3817    async fn a_map_response_without_groups_yields_an_empty_group_list() {
3818        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3819        let update = state_update_from_body(&netmap_body_with_profile_groups(""));
3820
3821        tracker.accumulate_user_profiles(&update.user_profiles);
3822        tracker.apply_peer_update(
3823            update.peer_update.as_ref().expect("a full peer set"),
3824            local_now(),
3825        );
3826
3827        let who = tracker
3828            .whois_opt("100.64.0.1:0".parse().unwrap())
3829            .expect("the peer owns that address");
3830
3831        assert!(
3832            who.user_profile.is_some(),
3833            "an omitted Groups must not cost us the profile"
3834        );
3835        assert_eq!(who.user(), Some("alice@example.com".to_string()));
3836        assert!(who.user_groups().is_empty());
3837    }
3838
3839    /// Control sends profiles incrementally, so a later response restating user 42 replaces the
3840    /// held copy wholesale — including a group list that SHRANK. A membership control has revoked
3841    /// must stop being reported, or an embedder authorising on it keeps honouring it forever.
3842    #[tokio::test]
3843    async fn a_restated_profile_replaces_the_held_group_list() {
3844        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
3845        let first = state_update_from_body(&netmap_body_with_profile_groups(
3846            r#", "Groups": ["group:eng", "group:oncall"]"#,
3847        ));
3848        tracker.accumulate_user_profiles(&first.user_profiles);
3849        tracker.apply_peer_update(
3850            first.peer_update.as_ref().expect("a full peer set"),
3851            local_now(),
3852        );
3853
3854        let second = state_update_from_body(&netmap_body_with_profile_groups(
3855            r#", "Groups": ["group:eng"]"#,
3856        ));
3857        tracker.accumulate_user_profiles(&second.user_profiles);
3858
3859        let who = tracker
3860            .whois_opt("100.64.0.1:0".parse().unwrap())
3861            .expect("the peer owns that address");
3862        assert_eq!(who.user_groups(), ["group:eng"]);
3863    }
3864
3865    /// `UserProfile::best_label` prefers the login name, falling back to display name, else `None`.
3866    #[test]
3867    fn user_profile_best_label_prefers_login() {
3868        assert_eq!(
3869            profile(1, "alice@example.com").best_label(),
3870            Some("alice@example.com".to_string())
3871        );
3872        let display_only = ts_control::UserProfile {
3873            id: 2,
3874            login_name: String::new(),
3875            display_name: Some("Bob".to_string()),
3876            groups: Vec::new(),
3877        };
3878        assert_eq!(display_only.best_label(), Some("Bob".to_string()));
3879        let empty = ts_control::UserProfile {
3880            id: 3,
3881            login_name: String::new(),
3882            display_name: None,
3883            groups: Vec::new(),
3884        };
3885        assert_eq!(empty.best_label(), None);
3886    }
3887
3888    // ----- tsr-jo1: RotationTracker (Go ipnlocal.rotationTracker.obsoleteKeys) -----
3889
3890    /// A `RotationDetails` for a `Direct`-rooted chain with the given prior keys + wrapping key.
3891    fn rot_details(
3892        prev: &[&[u8]],
3893        wrapping: &[u8],
3894        kind: ts_tka::SigKind,
3895    ) -> ts_tka::RotationDetails {
3896        ts_tka::RotationDetails {
3897            prev_node_keys: prev.iter().map(|p| p.to_vec()).collect(),
3898            initial_sig_kind: kind,
3899            initial_wrapping_pubkey: wrapping.to_vec(),
3900        }
3901    }
3902
3903    /// Rule 1: every prior node key named by any rotation chain is obsolete, regardless of the
3904    /// chain's root kind (Go's ungated `obsolete.AddSlice(d.PrevNodeKeys)`).
3905    #[test]
3906    fn rotation_tracker_prev_keys_always_obsolete() {
3907        let mut t = RotationTracker::default();
3908        // A Direct-rooted chain that rotated away OLD1, and a Credential-rooted one that rotated OLD2.
3909        t.add(
3910            b"newA".to_vec(),
3911            &rot_details(&[b"OLD1"], b"wrapA", ts_tka::SigKind::Direct),
3912        );
3913        t.add(
3914            b"newB".to_vec(),
3915            &rot_details(&[b"OLD2"], b"wrapB", ts_tka::SigKind::Credential),
3916        );
3917        let obsolete = t.obsolete_keys();
3918        assert!(
3919            obsolete.contains(b"OLD1".as_slice()),
3920            "Direct chain's prior key obsolete"
3921        );
3922        assert!(
3923            obsolete.contains(b"OLD2".as_slice()),
3924            "Credential chain's prior key obsolete too (rule 1 is ungated)"
3925        );
3926        // The current keys themselves are not obsolete (only one peer per wrapping key here).
3927        assert!(!obsolete.contains(b"newA".as_slice()));
3928        assert!(!obsolete.contains(b"newB".as_slice()));
3929    }
3930
3931    /// Rule 2: among `Direct`-rooted chains sharing a wrapping key, only the longest survives; the
3932    /// shorter (older) clone's key is obsolete.
3933    #[test]
3934    fn rotation_tracker_unequal_chain_keeps_longest() {
3935        let mut t = RotationTracker::default();
3936        // Same wrapping key; "long" has 2 prior keys, "short" has 1 ⇒ "short" is the older clone.
3937        t.add(
3938            b"long".to_vec(),
3939            &rot_details(&[b"p1", b"p2"], b"wrap", ts_tka::SigKind::Direct),
3940        );
3941        t.add(
3942            b"short".to_vec(),
3943            &rot_details(&[b"q1"], b"wrap", ts_tka::SigKind::Direct),
3944        );
3945        let obsolete = t.obsolete_keys();
3946        assert!(
3947            obsolete.contains(b"short".as_slice()),
3948            "the shorter-chain clone is obsolete"
3949        );
3950        assert!(
3951            !obsolete.contains(b"long".as_slice()),
3952            "the longest-chain peer survives"
3953        );
3954    }
3955
3956    /// Rule 2 tie: two `Direct`-rooted chains sharing a wrapping key with EQUAL chain length cannot
3957    /// be disambiguated ⇒ BOTH are dropped (Go's safety branch).
3958    #[test]
3959    fn rotation_tracker_equal_chain_drops_both() {
3960        let mut t = RotationTracker::default();
3961        t.add(
3962            b"cloneA".to_vec(),
3963            &rot_details(&[b"p1"], b"wrap", ts_tka::SigKind::Direct),
3964        );
3965        t.add(
3966            b"cloneB".to_vec(),
3967            &rot_details(&[b"p2"], b"wrap", ts_tka::SigKind::Direct),
3968        );
3969        let obsolete = t.obsolete_keys();
3970        assert!(
3971            obsolete.contains(b"cloneA".as_slice()),
3972            "tied clone A dropped"
3973        );
3974        assert!(
3975            obsolete.contains(b"cloneB".as_slice()),
3976            "tied clone B dropped"
3977        );
3978    }
3979
3980    /// `Credential`-rooted chains sharing a wrapping key are EXEMPT from rule 2 (reusable-authkey
3981    /// carve-out): both are kept even with equal chain length.
3982    #[test]
3983    fn rotation_tracker_credential_root_clones_both_kept() {
3984        let mut t = RotationTracker::default();
3985        t.add(
3986            b"credA".to_vec(),
3987            &rot_details(&[b"p1"], b"wrap", ts_tka::SigKind::Credential),
3988        );
3989        t.add(
3990            b"credB".to_vec(),
3991            &rot_details(&[b"p2"], b"wrap", ts_tka::SigKind::Credential),
3992        );
3993        let obsolete = t.obsolete_keys();
3994        assert!(
3995            !obsolete.contains(b"credA".as_slice()),
3996            "credential-rooted clone A kept"
3997        );
3998        assert!(
3999            !obsolete.contains(b"credB".as_slice()),
4000            "credential-rooted clone B kept"
4001        );
4002    }
4003
4004    /// A peer that another chain already rotated away does not also act as a surviving clone: it is
4005    /// removed from its wrapping-key group before the longest-survivor pick (Go's `DeleteFunc`).
4006    #[test]
4007    fn rotation_tracker_already_obsolete_peer_not_a_survivor() {
4008        let mut t = RotationTracker::default();
4009        // "victim" is rotated away by "rotator" (different wrapping key), AND shares wrapping key
4010        // "w" with "other". Because "victim" is already obsolete, only "other" is in play for "w" and
4011        // survives (no spurious tie-drop of "other").
4012        t.add(
4013            b"rotator".to_vec(),
4014            &rot_details(&[b"victim"], b"wRot", ts_tka::SigKind::Direct),
4015        );
4016        t.add(
4017            b"victim".to_vec(),
4018            &rot_details(&[b"x"], b"w", ts_tka::SigKind::Direct),
4019        );
4020        t.add(
4021            b"other".to_vec(),
4022            &rot_details(&[b"y"], b"w", ts_tka::SigKind::Direct),
4023        );
4024        let obsolete = t.obsolete_keys();
4025        assert!(
4026            obsolete.contains(b"victim".as_slice()),
4027            "victim rotated away by rotator"
4028        );
4029        assert!(
4030            !obsolete.contains(b"other".as_slice()),
4031            "other survives — victim was removed from the group before the tie check"
4032        );
4033    }
4034
4035    /// Empty tracker (no rotation-signed peers) ⇒ no obsolete keys (the non-rotation netmap path).
4036    #[test]
4037    fn rotation_tracker_empty_is_noop() {
4038        let t = RotationTracker::default();
4039        assert!(t.obsolete_keys().is_empty());
4040    }
4041
4042    /// End-to-end through the real `Full` path: a peer presenting a freshly-rotated key (a Rotation
4043    /// chain) is admitted, while a second peer still presenting the rotated-AWAY pivot key — even with
4044    /// that key's own still-valid Direct signature — is DROPPED by the cross-peer rotation filter.
4045    /// This is the gap closed here: Go `tkaFilterNetmapLocked` drops the stale clone; we used to admit
4046    /// it. Uses real `ts_tka` signing (`sign_direct` + `sign_rotation`) so the whole
4047    /// verify → details → filter pipeline runs.
4048    ///
4049    /// Construction: the trusted key signs an inner `Direct` over the PIVOT keypair's public key; the
4050    /// pivot key then signs an outer `Rotation` authorizing `new_key`. That chain's `prev_node_keys`
4051    /// names the pivot pubkey — so a peer presenting the pivot pubkey as its node key is the
4052    /// rotated-away key the filter must drop.
4053    #[tokio::test]
4054    async fn tka_full_drops_rotated_away_key_e2e() {
4055        use ed25519_dalek::SigningKey;
4056        use ts_tka::NodeKeySignature;
4057
4058        let trusted = SigningKey::from_bytes(&[42u8; 32]);
4059        let trusted_pub = trusted.verifying_key().to_bytes().to_vec();
4060        let authority = Authority::from_state(
4061            AumHash([0; 32]),
4062            State {
4063                keys: vec![Key {
4064                    kind: KeyKind::Ed25519,
4065                    votes: 1,
4066                    public: trusted_pub.clone(),
4067                }],
4068            },
4069        );
4070
4071        // The rotation pivot: a keypair whose public key the inner Direct authorizes and whose
4072        // private key signs the outer rotation wrap. This pivot pubkey IS the key being rotated away.
4073        let pivot = SigningKey::from_bytes(&[9u8; 32]);
4074        let pivot_pub: [u8; 32] = pivot.verifying_key().to_bytes();
4075
4076        let new_key = [4u8; 32]; // the freshly-rotated node key
4077
4078        // Fresh peer: a Rotation chain authorizing `new_key`, inner Direct over the pivot signed by
4079        // trusted, outer wrap signed by the pivot. Its prev_node_keys names `pivot_pub`.
4080        let new_sig = NodeKeySignature::sign_rotation(&new_key, &trusted, &pivot).serialize();
4081        let new_peer = peer_node("rotated", new_key, new_sig);
4082
4083        // Stale peer: still presents the pivot pubkey (the rotated-away key) with its own valid
4084        // Direct signature — valid in isolation, but obsoleted by the fresh peer's rotation chain.
4085        let stale_sig = NodeKeySignature::sign_direct(&pivot_pub, &trusted).serialize();
4086        let stale_peer = peer_node("stale", pivot_pub, stale_sig);
4087
4088        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), Some(authority));
4089        tracker.apply_peer_update(
4090            &ts_control::PeerUpdate::Full(vec![new_peer.clone(), stale_peer.clone()]),
4091            local_now(),
4092        );
4093
4094        assert!(
4095            tracker.peer_db.get(&new_peer.node_key).is_some(),
4096            "the freshly-rotated peer is admitted"
4097        );
4098        assert!(
4099            tracker.peer_db.get(&stale_peer.node_key).is_none(),
4100            "the peer presenting the rotated-away key is dropped (Go tkaFilterNetmapLocked)"
4101        );
4102    }
4103}
4104
4105#[cfg(test)]
4106mod tsmp_disco_key_tests {
4107    //! Receive side of the TSMP disco-key advertisement, at the point the key is *learned*.
4108    //!
4109    //! These exercise [`PeerTracker::learn_disco_key`] — the fork's stand-in for Go
4110    //! `magicsock.Conn.HandleDiscoKeyAdvertisement` — which is the single place an advertisement
4111    //! reaches peer state. The wire decode and the "consumed, not delivered" drop are covered in
4112    //! `ts_packet::tsmp` and `ts_dataplane` respectively.
4113
4114    use ts_keys::DiscoPublicKey;
4115
4116    use super::{
4117        tka_tests::{peer_node, test_env},
4118        *,
4119    };
4120
4121    /// The key a peer advertises, and a second one for the re-advertise case.
4122    const ADVERTISED: [u8; 32] = [0xa5u8; 32];
4123    const READVERTISED: [u8; 32] = [0x5au8; 32];
4124    /// The (staler) key control has for that same peer, and the one control eventually catches up
4125    /// to.
4126    const FROM_CONTROL: [u8; 32] = [0xc0u8; 32];
4127    const CONTROL_CAUGHT_UP: [u8; 32] = [0x0cu8; 32];
4128
4129    /// The node key of the single peer these tests use.
4130    const PEER_NODE_KEY: [u8; 32] = [1u8; 32];
4131
4132    /// A tracker holding one peer with no disco key yet, plus that peer's [`PeerId`].
4133    fn tracker_with_peer() -> (PeerTracker, PeerId) {
4134        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
4135        let node = peer_node("peer", PEER_NODE_KEY, Vec::new());
4136        let id = tracker.peer_db.upsert(&node);
4137        (tracker, id)
4138    }
4139
4140    /// The peer as CONTROL describes it: the same node, carrying whatever disco key the netmap says
4141    /// it has (`None` for a peer control has no disco key for at all).
4142    fn node_from_control(disco_key: Option<[u8; 32]>) -> Node {
4143        let mut node = peer_node("peer", PEER_NODE_KEY, Vec::new());
4144        node.disco_key = disco_key.map(DiscoPublicKey::from);
4145        node
4146    }
4147
4148    /// A netmap `Full` carrying just this peer, as control currently describes it.
4149    fn control_full(disco_key: Option<[u8; 32]>) -> ts_control::PeerUpdate {
4150        ts_control::PeerUpdate::Full(vec![node_from_control(disco_key)])
4151    }
4152
4153    /// A tracker whose single peer arrived through the netmap carrying `disco_key`, exactly as the
4154    /// actor's handler applies it. Returns the peer's [`PeerId`] too.
4155    fn tracker_with_control_peer(disco_key: Option<[u8; 32]>) -> (PeerTracker, PeerId) {
4156        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
4157        let node = node_from_control(disco_key);
4158        tracker.apply_peer_update(&control_full(disco_key), local_now());
4159        let id = tracker
4160            .peer_db
4161            .has(&node.node_key)
4162            .expect("control delivered it");
4163        (tracker, id)
4164    }
4165
4166    /// The disco key the peer db currently holds for `peer` — the effective key every direct-path
4167    /// consumer resolves against.
4168    fn effective_key(tracker: &PeerTracker, peer: PeerId) -> Option<DiscoPublicKey> {
4169        tracker
4170            .peer_db
4171            .get(&peer)
4172            .expect("peer still present")
4173            .1
4174            .disco_key
4175    }
4176
4177    /// The happy path: an advertised key is applied to the peer AND lands in the disco index, which
4178    /// is what the direct-path machinery (`direct::DiscoPeerLookup`) reads. Re-advertising the same
4179    /// key is a no-op; advertising a different one replaces it, retracting the old index entry.
4180    #[tokio::test]
4181    async fn advertisement_learns_the_peers_disco_key() {
4182        let (mut tracker, peer) = tracker_with_peer();
4183        let key = DiscoPublicKey::from(ADVERTISED);
4184
4185        assert!(
4186            tracker.learn_disco_key(peer, key),
4187            "a first advertisement changes the peer db"
4188        );
4189        assert_eq!(
4190            tracker
4191                .peer_db
4192                .get(&peer)
4193                .expect("peer still present")
4194                .1
4195                .disco_key,
4196            Some(key),
4197            "the advertised disco key is learned"
4198        );
4199        assert_eq!(
4200            tracker.peer_db.has(&key),
4201            Some(peer),
4202            "and is reachable through the disco index the direct path resolves against"
4203        );
4204
4205        assert!(
4206            !tracker.learn_disco_key(peer, key),
4207            "re-advertising the same key is a no-op (Go counts it 'unchanged' and returns)"
4208        );
4209
4210        let rotated = DiscoPublicKey::from(READVERTISED);
4211        assert!(tracker.learn_disco_key(peer, rotated));
4212        assert_eq!(
4213            tracker
4214                .peer_db
4215                .get(&peer)
4216                .expect("peer still present")
4217                .1
4218                .disco_key,
4219            Some(rotated),
4220            "a later advertisement replaces the key without a netmap update"
4221        );
4222        assert_eq!(tracker.peer_db.has(&rotated), Some(peer));
4223        assert_eq!(
4224            tracker.peer_db.has(&key),
4225            None,
4226            "the superseded key no longer resolves to the peer"
4227        );
4228    }
4229
4230    /// The refusals, each of which must leave the peer db untouched: the zero key is never learned,
4231    /// and an advertisement never creates a peer.
4232    #[tokio::test]
4233    async fn refused_advertisements_change_nothing() {
4234        let (mut tracker, peer) = tracker_with_peer();
4235
4236        assert!(
4237            !tracker.learn_disco_key(peer, DiscoPublicKey::from([0u8; 32])),
4238            "the zero key is never learned"
4239        );
4240        assert_eq!(
4241            tracker
4242                .peer_db
4243                .get(&peer)
4244                .expect("peer still present")
4245                .1
4246                .disco_key,
4247            None,
4248            "a zero-key advertisement must not bind the peer to an unusable key"
4249        );
4250
4251        // An advertisement for a peer control has never told us about. Go logs "endpoint not found
4252        // for node" and returns; it must not conjure a peer into existence.
4253        let unknown = PeerId(4242);
4254        assert_eq!(tracker.peer_db.get(&unknown), None, "precondition");
4255        assert!(
4256            !tracker.learn_disco_key(unknown, DiscoPublicKey::from(ADVERTISED)),
4257            "an advertisement for an unknown peer is ignored"
4258        );
4259        assert_eq!(
4260            tracker.peer_db.peers().len(),
4261            1,
4262            "an advertisement never creates a peer — only control does"
4263        );
4264        assert_eq!(
4265            tracker.peer_db.has(&DiscoPublicKey::from(ADVERTISED)),
4266            None,
4267            "and never indexes a key against a peer that does not exist"
4268        );
4269    }
4270
4271    /// The feature's motivating case, end to end: the peer told us a key control has not caught up
4272    /// with, and then control polls again with the SAME stale key it had before. The advertisement
4273    /// must survive.
4274    ///
4275    /// Go keeps the two keys apart on the endpoint (`endpointDisco.controlKey` /
4276    /// `tsmpKey`), and `updateFromNode` only rewrites the control side when control's key actually
4277    /// changed — so a netmap restating the old key never touches the active TSMP key. With a single
4278    /// field the next map poll silently reverted the peer to control's stale key, which is precisely
4279    /// the state the advertisement exists to escape.
4280    #[tokio::test]
4281    async fn netmap_restating_controls_stale_key_keeps_the_tsmp_key() {
4282        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4283        let advertised = DiscoPublicKey::from(ADVERTISED);
4284        assert_eq!(
4285            effective_key(&tracker, peer),
4286            Some(DiscoPublicKey::from(FROM_CONTROL)),
4287            "precondition: the peer starts on the key control gave us"
4288        );
4289
4290        assert!(tracker.learn_disco_key(peer, advertised));
4291        assert_eq!(effective_key(&tracker, peer), Some(advertised));
4292
4293        // Control polls again, still behind: a `Full` resync, then a `Delta` re-upsert, both
4294        // carrying the key control already sent.
4295        tracker.apply_peer_update(&control_full(Some(FROM_CONTROL)), local_now());
4296        assert_eq!(
4297            effective_key(&tracker, peer),
4298            Some(advertised),
4299            "a Full restating control's stale key must not undo the TSMP-learned key"
4300        );
4301        tracker.apply_peer_update(
4302            &ts_control::PeerUpdate::Delta {
4303                upsert: vec![node_from_control(Some(FROM_CONTROL))],
4304                remove: vec![],
4305            },
4306            local_now(),
4307        );
4308        assert_eq!(
4309            effective_key(&tracker, peer),
4310            Some(advertised),
4311            "and neither must a Delta re-upsert of the same node"
4312        );
4313        assert_eq!(
4314            tracker.peer_db.has(&advertised),
4315            Some(peer),
4316            "the direct path still resolves the peer by the key it advertised"
4317        );
4318        assert_eq!(
4319            tracker.peer_db.has(&DiscoPublicKey::from(FROM_CONTROL)),
4320            None,
4321            "and control's superseded key does not resolve to it"
4322        );
4323
4324        // Control finally changes its mind. The new key is recorded in control's slot, but the key
4325        // the peer itself told us stays active — upstream returns to control's key only when disco
4326        // is received under it (`endpoint.checkAndUpdateDiscoKey`).
4327        tracker.apply_peer_update(&control_full(Some(CONTROL_CAUGHT_UP)), local_now());
4328        assert_eq!(
4329            effective_key(&tracker, peer),
4330            Some(advertised),
4331            "a control-side key change must not preempt an active TSMP-learned key"
4332        );
4333        assert_eq!(
4334            tracker.control_disco_key(&PEER_NODE_KEY.into()),
4335            Some(DiscoPublicKey::from(CONTROL_CAUGHT_UP)),
4336            "but control's new key IS recorded in control's slot"
4337        );
4338    }
4339
4340    /// An advertisement that merely restates the key control already gave us is still *new*
4341    /// information — it is the peer itself confirming the key — so Go records it as the TSMP key and
4342    /// makes it active. Its "unchanged" early return compares `epDisco.keyFromTSMP()`, the
4343    /// TSMP-learned key specifically, never the effective one.
4344    ///
4345    /// The observable consequence, asserted here: once the peer has confirmed the key, control
4346    /// dropping it (a netmap node with no disco key) leaves the confirmed key in place instead of
4347    /// blinding the direct path.
4348    #[tokio::test]
4349    async fn advertisement_restating_controls_key_is_recorded_as_the_tsmp_key() {
4350        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4351        let key = DiscoPublicKey::from(FROM_CONTROL);
4352
4353        assert!(
4354            tracker.learn_disco_key(peer, key),
4355            "an advertisement of the key control already sent is recorded, not dropped"
4356        );
4357        assert_eq!(
4358            tracker
4359                .endpoint_disco
4360                .get(&PEER_NODE_KEY.into())
4361                .and_then(EndpointDisco::key_from_tsmp),
4362            Some(key),
4363            "it lands in the TSMP slot (Go epDisco.tsmpKey), not only in control's"
4364        );
4365        assert!(
4366            !tracker.learn_disco_key(peer, key),
4367            "re-advertising it now IS unchanged, and is refused"
4368        );
4369
4370        // Control drops the peer's disco key. The key the peer itself confirmed stays active.
4371        tracker.apply_peer_update(&control_full(None), local_now());
4372        assert_eq!(
4373            effective_key(&tracker, peer),
4374            Some(key),
4375            "a control key going away hands the active slot to the TSMP-learned key"
4376        );
4377        assert_eq!(tracker.peer_db.has(&key), Some(peer));
4378    }
4379
4380    /// A `PeersChangedPatch` is a control write like any other: one that says nothing about the
4381    /// disco key must leave an active TSMP key alone, and one that carries a new key is control
4382    /// catching up, so it wins.
4383    ///
4384    /// The patch path is the subtle one — it starts from the db node, which carries the *effective*
4385    /// key, so without re-deriving what control last said it would hand the TSMP key back as if
4386    /// control had sent it.
4387    #[tokio::test]
4388    async fn patch_without_a_disco_key_leaves_the_tsmp_key_active() {
4389        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4390        let advertised = DiscoPublicKey::from(ADVERTISED);
4391        assert!(tracker.learn_disco_key(peer, advertised));
4392
4393        // A reachability-only patch (the idle-peer-reconnect case) for the same node.
4394        let endpoint: std::net::SocketAddr = "203.0.113.9:41641".parse().unwrap();
4395        let mut patch = ts_control::PeerChange {
4396            id: 1,
4397            derp_region: None,
4398            cap: None,
4399            cap_map: None,
4400            underlay_addresses: Some(vec![endpoint]),
4401            node_key: None,
4402            key_signature: None,
4403            disco_key: None,
4404            node_key_expiry: None,
4405            online: None,
4406            last_seen: None,
4407        };
4408        tracker.apply_peer_patches(std::slice::from_ref(&patch), local_now());
4409        assert_eq!(
4410            effective_key(&tracker, peer),
4411            Some(advertised),
4412            "a patch that never mentions the disco key must not revert it to control's"
4413        );
4414        assert_eq!(
4415            tracker
4416                .peer_db
4417                .get(&peer)
4418                .expect("peer still present")
4419                .1
4420                .underlay_addresses,
4421            vec![endpoint],
4422            "and the patch it DID carry still applied"
4423        );
4424
4425        // Now control changes the key through the patch channel. Same rule as the netmap path: the
4426        // key lands in control's slot, and the active TSMP key is left alone.
4427        patch.disco_key = Some(DiscoPublicKey::from(CONTROL_CAUGHT_UP));
4428        tracker.apply_peer_patches(std::slice::from_ref(&patch), local_now());
4429        assert_eq!(
4430            effective_key(&tracker, peer),
4431            Some(advertised),
4432            "a patch carrying a new disco key does not preempt the active TSMP-learned key either"
4433        );
4434        assert_eq!(
4435            tracker.control_disco_key(&PEER_NODE_KEY.into()),
4436            Some(DiscoPublicKey::from(CONTROL_CAUGHT_UP)),
4437            "the patched key is still recorded as what control now says"
4438        );
4439    }
4440
4441    /// The rule this whole pair of slots exists to express: once the peer has told us its key over
4442    /// TSMP, control changing its mind is *recorded* but does not take the active slot back — Go
4443    /// `endpoint.updateDiscoKey`'s `epDisco.tsmpActive = old.tsmpActive || key.IsZero()`.
4444    ///
4445    /// Control is the slower source; a key the peer sent us itself is the better evidence. Upstream
4446    /// hands the slot back only when disco is actually *received* under control's key
4447    /// (`endpoint.checkAndUpdateDiscoKey`). Here the peer re-advertising is the path back, and it is
4448    /// asserted at the end so the sticky rule cannot be read as "the TSMP key is now permanent".
4449    #[tokio::test]
4450    async fn a_control_key_change_does_not_preempt_an_active_tsmp_key() {
4451        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4452        let advertised = DiscoPublicKey::from(ADVERTISED);
4453        let caught_up = DiscoPublicKey::from(CONTROL_CAUGHT_UP);
4454        assert!(tracker.learn_disco_key(peer, advertised));
4455
4456        tracker.apply_peer_update(&control_full(Some(CONTROL_CAUGHT_UP)), local_now());
4457        assert_eq!(
4458            effective_key(&tracker, peer),
4459            Some(advertised),
4460            "the TSMP-learned key stays active across a control-side change"
4461        );
4462        assert_eq!(
4463            tracker.peer_db.has(&advertised),
4464            Some(peer),
4465            "so the direct path still resolves the peer by the key it advertised"
4466        );
4467        assert_eq!(
4468            tracker.peer_db.has(&caught_up),
4469            None,
4470            "and control's new key is not what we send to"
4471        );
4472        assert_eq!(
4473            tracker.control_disco_key(&PEER_NODE_KEY.into()),
4474            Some(caught_up),
4475            "control's new key is recorded all the same — it is not discarded, just not active"
4476        );
4477
4478        // Control changing its mind a second time, and then dropping the key entirely, changes
4479        // nothing about which key is active.
4480        tracker.apply_peer_update(&control_full(Some(FROM_CONTROL)), local_now());
4481        tracker.apply_peer_update(&control_full(None), local_now());
4482        assert_eq!(
4483            effective_key(&tracker, peer),
4484            Some(advertised),
4485            "neither a second control change nor control dropping the key moves the active slot"
4486        );
4487
4488        // The peer itself is what moves it: it advertises the key control had been trying to give
4489        // us, and that advertisement is what we act on.
4490        assert!(tracker.learn_disco_key(peer, caught_up));
4491        assert_eq!(
4492            effective_key(&tracker, peer),
4493            Some(caught_up),
4494            "a peer re-advertising moves the active key, because the peer is the evidence"
4495        );
4496    }
4497
4498    /// The sticky flag must not strand a peer that never had a TSMP key: control sending nothing
4499    /// leaves no key material at all, and the key control sends next must become the active one.
4500    ///
4501    /// This is the case Go covers by nil-ing the endpoint's `disco` pointer when both keys are
4502    /// zero; here [`PeerTracker::upsert_from_control`] drops the entry, so the "no control key means
4503    /// the TSMP slot is active" flag cannot survive to shadow a later control key with nothing.
4504    #[tokio::test]
4505    async fn a_first_control_key_is_active_even_after_control_sent_none() {
4506        let (mut tracker, peer) = tracker_with_control_peer(None);
4507        assert_eq!(effective_key(&tracker, peer), None, "precondition");
4508        assert!(
4509            tracker.endpoint_disco.is_empty(),
4510            "a peer with no key material from either source costs no entry"
4511        );
4512
4513        tracker.apply_peer_update(&control_full(Some(FROM_CONTROL)), local_now());
4514        assert_eq!(
4515            effective_key(&tracker, peer),
4516            Some(DiscoPublicKey::from(FROM_CONTROL)),
4517            "control's first key is active — there is no TSMP key for it to defer to"
4518        );
4519        assert_eq!(
4520            tracker.peer_db.has(&DiscoPublicKey::from(FROM_CONTROL)),
4521            Some(peer)
4522        );
4523    }
4524
4525    /// The other half of `tsmpActive = old.tsmpActive || key.IsZero()`, in the one state where the
4526    /// left operand is false *and* a TSMP key exists: after disco was received under control's key,
4527    /// which is upstream's only route back to control holding the active slot
4528    /// (`endpoint.checkAndUpdateDiscoKey`).
4529    ///
4530    /// Two things follow, and neither is obvious from the sticky rule alone. Control's later changes
4531    /// **do** land, because what is sticky is the flag, not the TSMP key — so this is not "the TSMP
4532    /// key wins forever", and a peer that genuinely rotated is not stranded. And control *dropping*
4533    /// its key does not leave the peer with no disco key at all: the `key.IsZero()` operand hands the
4534    /// slot to the TSMP key still sitting in the other slot, which is why Go only nils the endpoint's
4535    /// `disco` pointer when **both** keys are zero.
4536    #[tokio::test]
4537    async fn control_regains_the_slot_by_being_received_under_and_then_keeps_it() {
4538        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4539        let from_control = DiscoPublicKey::from(FROM_CONTROL);
4540        let advertised = DiscoPublicKey::from(ADVERTISED);
4541        let caught_up = DiscoPublicKey::from(CONTROL_CAUGHT_UP);
4542
4543        // Get into the state: the peer advertises, then sends disco under control's key anyway, so
4544        // control's key is active again with the TSMP key demoted but retained.
4545        assert!(tracker.learn_disco_key(peer, advertised));
4546        assert!(tracker.observe_disco_key(peer, from_control));
4547        assert_eq!(
4548            effective_key(&tracker, peer),
4549            Some(from_control),
4550            "precondition: control holds the active slot because we received under its key"
4551        );
4552        assert_eq!(
4553            ingress_match(&tracker, advertised),
4554            Some((peer, peer_db::DiscoKeyMatch::Inactive)),
4555            "precondition: the TSMP key is demoted, not discarded"
4556        );
4557
4558        // Control changes its key. With the TSMP key demoted the sticky operand is false, so this
4559        // one does take the active slot — the flag is what is sticky, not the TSMP key.
4560        tracker.apply_peer_update(&control_full(Some(CONTROL_CAUGHT_UP)), local_now());
4561        assert_eq!(
4562            effective_key(&tracker, peer),
4563            Some(caught_up),
4564            "a demoted TSMP key does not block control's next key from becoming active"
4565        );
4566        assert_eq!(
4567            ingress_match(&tracker, advertised),
4568            Some((peer, peer_db::DiscoKeyMatch::Inactive)),
4569            "and the TSMP key is still the peer's other known key for ingress"
4570        );
4571        assert_eq!(
4572            ingress_match(&tracker, from_control),
4573            None,
4574            "control's superseded key is not a third slot"
4575        );
4576
4577        // Control drops its key entirely. `key.IsZero()` is the operand that carries the peer here:
4578        // the retained TSMP key becomes active rather than the peer losing disco altogether.
4579        tracker.apply_peer_update(&control_full(None), local_now());
4580        assert_eq!(
4581            effective_key(&tracker, peer),
4582            Some(advertised),
4583            "control dropping its key falls back to the TSMP key, not to no key"
4584        );
4585        assert_eq!(
4586            ingress_match(&tracker, advertised),
4587            Some((peer, peer_db::DiscoKeyMatch::Active))
4588        );
4589        assert_eq!(
4590            tracker.control_disco_key(&PEER_NODE_KEY.into()),
4591            None,
4592            "control's slot is cleared, so there is no second key to accept"
4593        );
4594        assert_eq!(
4595            ingress_match(&tracker, caught_up),
4596            None,
4597            "the key control withdrew stops resolving on ingress"
4598        );
4599    }
4600
4601    /// The TSMP-learned key lives exactly as long as Go's endpoint does: it is dropped when the peer
4602    /// leaves the netmap, and it is not carried across a node-key rotation (Go builds the rotated
4603    /// peer a brand-new endpoint, with a brand-new `endpointDisco`).
4604    #[tokio::test]
4605    async fn tsmp_key_does_not_outlive_the_peer_or_its_node_key() {
4606        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4607        assert!(tracker.learn_disco_key(peer, DiscoPublicKey::from(ADVERTISED)));
4608
4609        // The peer leaves the netmap, then comes back on control's key.
4610        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![]), local_now());
4611        assert!(tracker.peer_db.peers().is_empty());
4612        assert!(
4613            tracker.endpoint_disco.is_empty(),
4614            "the departed peer's disco state goes with it"
4615        );
4616        tracker.apply_peer_update(&control_full(Some(FROM_CONTROL)), local_now());
4617        let readded = node_from_control(Some(FROM_CONTROL));
4618        let peer = tracker.peer_db.has(&readded.node_key).expect("re-added");
4619        assert_eq!(
4620            effective_key(&tracker, peer),
4621            Some(DiscoPublicKey::from(FROM_CONTROL)),
4622            "a peer that left and rejoined starts from control's key again"
4623        );
4624
4625        // Learn a key again, then rotate the node key underneath it.
4626        assert!(tracker.learn_disco_key(peer, DiscoPublicKey::from(READVERTISED)));
4627        let mut rotated = node_from_control(Some(FROM_CONTROL));
4628        rotated.node_key = [2u8; 32].into();
4629        tracker.apply_peer_update(
4630            &ts_control::PeerUpdate::Full(vec![rotated.clone()]),
4631            local_now(),
4632        );
4633        let peer = tracker
4634            .peer_db
4635            .has(&rotated.node_key)
4636            .expect("rotated peer");
4637        assert_eq!(
4638            effective_key(&tracker, peer),
4639            Some(DiscoPublicKey::from(FROM_CONTROL)),
4640            "a key learned under the old node key is not carried onto the new one"
4641        );
4642        assert_eq!(
4643            tracker.endpoint_disco.len(),
4644            1,
4645            "and the old node key's state is pruned"
4646        );
4647    }
4648
4649    /// How the peer db resolves `key` for an inbound disco frame: the peer it belongs to and which
4650    /// of that peer's two slots it matched.
4651    fn ingress_match(
4652        tracker: &PeerTracker,
4653        key: DiscoPublicKey,
4654    ) -> Option<(PeerId, peer_db::DiscoKeyMatch)> {
4655        tracker
4656            .peer_db
4657            .peer_by_known_disco_key(&key)
4658            .map(|(id, _node, matched)| (id, matched))
4659    }
4660
4661    /// The bead's case, end to end: the peer advertised K2 over TSMP so we send to K2, but it is
4662    /// still sending disco under the K1 control gave us. That frame must resolve to the peer, and
4663    /// receiving under K1 must make K1 the key we send to — because it is demonstrably what the
4664    /// peer uses.
4665    ///
4666    /// Go: every inbound disco comparison goes through `endpoint.checkAndUpdateDiscoKey`, which
4667    /// accepts either slot and compare-and-swaps `tsmpActive` when the key seen is the inactive one.
4668    #[tokio::test]
4669    async fn disco_under_the_inactive_key_is_accepted_and_makes_that_key_active() {
4670        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4671        let from_control = DiscoPublicKey::from(FROM_CONTROL);
4672        let advertised = DiscoPublicKey::from(ADVERTISED);
4673
4674        assert!(tracker.learn_disco_key(peer, advertised));
4675        assert_eq!(
4676            effective_key(&tracker, peer),
4677            Some(advertised),
4678            "precondition: we are sending to the TSMP-learned key"
4679        );
4680        assert_eq!(
4681            ingress_match(&tracker, from_control),
4682            Some((peer, peer_db::DiscoKeyMatch::Inactive)),
4683            "control's key is still the peer's other known key, and still resolves on ingress"
4684        );
4685
4686        // Disco arrives under control's key: accepted, and it becomes the active one.
4687        assert!(
4688            tracker.observe_disco_key(peer, from_control),
4689            "receiving under the inactive key switches the active key"
4690        );
4691        assert_eq!(
4692            effective_key(&tracker, peer),
4693            Some(from_control),
4694            "we now send to the key the peer is demonstrably using"
4695        );
4696        assert_eq!(
4697            tracker.peer_db.has(&from_control),
4698            Some(peer),
4699            "and it is the key the send-side disco index carries"
4700        );
4701        assert_eq!(
4702            ingress_match(&tracker, from_control),
4703            Some((peer, peer_db::DiscoKeyMatch::Active))
4704        );
4705        assert_eq!(
4706            ingress_match(&tracker, advertised),
4707            Some((peer, peer_db::DiscoKeyMatch::Inactive)),
4708            "the TSMP key is retained in the other slot, so ingress under it still resolves"
4709        );
4710
4711        assert!(
4712            !tracker.observe_disco_key(peer, from_control),
4713            "a second frame under the now-active key changes nothing (and forces no republish)"
4714        );
4715
4716        // And it switches back: the peer resumes sending under the key it advertised.
4717        assert!(tracker.observe_disco_key(peer, advertised));
4718        assert_eq!(effective_key(&tracker, peer), Some(advertised));
4719        assert_eq!(
4720            ingress_match(&tracker, from_control),
4721            Some((peer, peer_db::DiscoKeyMatch::Inactive))
4722        );
4723    }
4724
4725    /// The refusal that is the whole security value of the check: a key belonging to NEITHER slot
4726    /// is rejected, leaving the peer on the key it was on. Plus the two other refusals Go has —
4727    /// an unknown peer, and a peer with no disco key material at all (`epDisco == nil`).
4728    #[tokio::test]
4729    async fn disco_under_a_key_in_neither_slot_is_refused() {
4730        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4731        let from_control = DiscoPublicKey::from(FROM_CONTROL);
4732        let advertised = DiscoPublicKey::from(ADVERTISED);
4733        let third = DiscoPublicKey::from(READVERTISED);
4734
4735        assert!(tracker.learn_disco_key(peer, advertised));
4736
4737        assert!(
4738            !tracker.observe_disco_key(peer, third),
4739            "a third key is refused: a peer must not move itself onto a key nobody told us about"
4740        );
4741        assert_eq!(
4742            effective_key(&tracker, peer),
4743            Some(advertised),
4744            "and the peer stays on the key it was on"
4745        );
4746        assert_eq!(
4747            ingress_match(&tracker, third),
4748            None,
4749            "the refused key never becomes resolvable"
4750        );
4751        assert_eq!(
4752            ingress_match(&tracker, from_control),
4753            Some((peer, peer_db::DiscoKeyMatch::Inactive)),
4754            "the two real slots are untouched"
4755        );
4756
4757        // An unknown peer: like a TSMP advertisement, this never creates one.
4758        assert!(!tracker.observe_disco_key(PeerId(4242), from_control));
4759        assert_eq!(tracker.peer_db.peers().len(), 1);
4760
4761        // A peer with no disco key from either source — Go returns false on `epDisco == nil`.
4762        let (mut bare, bare_peer) = tracker_with_control_peer(None);
4763        assert_eq!(effective_key(&bare, bare_peer), None, "precondition");
4764        assert!(
4765            !bare.observe_disco_key(bare_peer, from_control),
4766            "a peer with no known disco key has no slot for this key to match"
4767        );
4768        assert_eq!(effective_key(&bare, bare_peer), None);
4769    }
4770
4771    /// A peer that has only ever had one key registers no inactive key at all, so the second index
4772    /// stays empty and an inbound frame under any other key is refused.
4773    #[tokio::test]
4774    async fn a_single_key_peer_has_no_second_slot() {
4775        let (tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4776        let from_control = DiscoPublicKey::from(FROM_CONTROL);
4777
4778        assert_eq!(
4779            ingress_match(&tracker, from_control),
4780            Some((peer, peer_db::DiscoKeyMatch::Active))
4781        );
4782        assert_eq!(
4783            ingress_match(&tracker, DiscoPublicKey::from(ADVERTISED)),
4784            None,
4785            "no second key was ever learned, so nothing else resolves to this peer"
4786        );
4787    }
4788
4789    /// An advertisement that merely restates control's key must not leave the peer with the same
4790    /// key in both slots pretending to be two — `inactive_key` reports `None` when the inactive
4791    /// slot holds the active key, so ingress sees exactly one key.
4792    #[tokio::test]
4793    async fn the_same_key_in_both_slots_is_one_key() {
4794        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4795        let from_control = DiscoPublicKey::from(FROM_CONTROL);
4796
4797        assert!(tracker.learn_disco_key(peer, from_control));
4798        assert_eq!(
4799            tracker
4800                .endpoint_disco
4801                .get(&PEER_NODE_KEY.into())
4802                .and_then(EndpointDisco::inactive_key),
4803            None,
4804            "both slots hold the same key, so there is no second key"
4805        );
4806        assert_eq!(
4807            ingress_match(&tracker, from_control),
4808            Some((peer, peer_db::DiscoKeyMatch::Active))
4809        );
4810        assert!(
4811            !tracker.observe_disco_key(peer, from_control),
4812            "and receiving under it is a no-op, not a switch"
4813        );
4814    }
4815
4816    /// A peer that leaves the netmap takes BOTH its keys with it: the inactive-key index must not
4817    /// keep attributing frames to a peer that is gone.
4818    #[tokio::test]
4819    async fn a_departed_peer_stops_resolving_under_either_key() {
4820        let (mut tracker, peer) = tracker_with_control_peer(Some(FROM_CONTROL));
4821        let advertised = DiscoPublicKey::from(ADVERTISED);
4822        assert!(tracker.learn_disco_key(peer, advertised));
4823        assert!(ingress_match(&tracker, DiscoPublicKey::from(FROM_CONTROL)).is_some());
4824
4825        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![]), local_now());
4826        assert_eq!(ingress_match(&tracker, advertised), None);
4827        assert_eq!(
4828            ingress_match(&tracker, DiscoPublicKey::from(FROM_CONTROL)),
4829            None,
4830            "the inactive key is retracted with the peer, not left dangling"
4831        );
4832    }
4833}
4834
4835#[cfg(test)]
4836mod index_eviction_tests {
4837    //! A departing peer must not evict the index rows of the peer that took its place.
4838    //!
4839    //! Control reassigns a churning (typically ephemeral) peer's tailnet IP and MagicDNS name to a
4840    //! newer node, and the newer node's upsert can reach us before the old node's removal — either
4841    //! in an earlier `MapResponse`, or reordered inside one batch. Here it is not even a race:
4842    //! [`PeerTracker::apply_peer_update`] applies a delta's upserts first and its removals second,
4843    //! so the intra-batch ordering is the one this tree ALWAYS uses. These drive real
4844    //! [`ts_control::PeerUpdate`]s through that function and assert the lookups an embedder
4845    //! actually depends on — `peer_by_tailnet_ip` (whois, peerAPI source checks) and
4846    //! `peer_by_name` — still answer with the live peer.
4847
4848    use super::{
4849        tka_tests::{peer_node, test_env},
4850        *,
4851    };
4852
4853    /// A peer holding a specific control node id, tailnet address pair and hostname.
4854    fn peer_at(stable_id: &str, control_id: i64, key: u8, host: u8) -> Node {
4855        let mut node = peer_node(stable_id, [key; 32], Vec::new());
4856        node.id = control_id;
4857        node.hostname = stable_id.to_string();
4858        node.tailnet = Some("ts.net".to_string());
4859
4860        let ipv4: ipnet::Ipv4Net = format!("100.64.0.{host}/32").parse().unwrap();
4861        let ipv6: ipnet::Ipv6Net = format!("fd7a:115c:a1e0::{host}/128").parse().unwrap();
4862        node.addresses = vec![ipv4.into(), ipv6.into()];
4863        node.tailnet_address = ts_control::TailnetAddress { ipv4, ipv6 };
4864        node.disco_key = Some([key; 32].into());
4865        node
4866    }
4867
4868    fn tailnet_ipv4(host: u8) -> IpAddr {
4869        format!("100.64.0.{host}").parse().unwrap()
4870    }
4871
4872    /// The successor's upsert and the departing peer's removal in ONE delta — the ordering
4873    /// `apply_peer_update` always applies (upserts, then removals).
4874    #[tokio::test]
4875    async fn a_delta_that_replaces_a_peer_keeps_the_successor_addressable() {
4876        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
4877        let now = local_now();
4878
4879        let departing = peer_at("departing", 1, 1, 9);
4880        tracker.apply_peer_update(
4881            &ts_control::PeerUpdate::Delta {
4882                upsert: vec![departing.clone()],
4883                remove: Vec::new(),
4884            },
4885            now,
4886        );
4887        assert_eq!(
4888            tracker
4889                .peer_by_tailnet_ip_opt(tailnet_ipv4(9))
4890                .map(|n| &n.stable_id),
4891            Some(&departing.stable_id)
4892        );
4893
4894        // Control hands the address and the MagicDNS name to a new node and retires the old one in
4895        // the same batch.
4896        let mut successor = peer_at("successor", 2, 2, 9);
4897        successor.hostname = departing.hostname.clone();
4898        successor.disco_key = departing.disco_key;
4899
4900        tracker.apply_peer_update(
4901            &ts_control::PeerUpdate::Delta {
4902                upsert: vec![successor.clone()],
4903                remove: vec![departing.id],
4904            },
4905            now,
4906        );
4907
4908        assert_eq!(tracker.peer_db.peers().len(), 1, "the old peer is gone");
4909        assert_eq!(
4910            tracker
4911                .peer_by_tailnet_ip_opt(tailnet_ipv4(9))
4912                .map(|n| &n.stable_id),
4913            Some(&successor.stable_id),
4914            "whois and every peerAPI source check resolve through this index"
4915        );
4916        assert_eq!(
4917            tracker
4918                .peer_by_name_opt("departing.ts.net")
4919                .map(|n| &n.stable_id),
4920            Some(&successor.stable_id),
4921            "the MagicDNS name follows the address to its new owner"
4922        );
4923        assert_eq!(
4924            tracker
4925                .peer_db
4926                .get(&successor.disco_key.unwrap())
4927                .map(|(_id, n)| &n.stable_id),
4928            Some(&successor.stable_id),
4929            "and so does the disco key, which is the successor's direct path"
4930        );
4931    }
4932
4933    /// The same replacement split across TWO deltas: the successor arrives in one `MapResponse`,
4934    /// the departing peer's removal trails in a later one.
4935    #[tokio::test]
4936    async fn a_removal_trailing_a_later_upsert_keeps_the_successor_addressable() {
4937        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
4938        let now = local_now();
4939
4940        let departing = peer_at("departing", 1, 1, 9);
4941        let successor = peer_at("successor", 2, 2, 9);
4942
4943        tracker.apply_peer_update(
4944            &ts_control::PeerUpdate::Delta {
4945                upsert: vec![departing.clone()],
4946                remove: Vec::new(),
4947            },
4948            now,
4949        );
4950        tracker.apply_peer_update(
4951            &ts_control::PeerUpdate::Delta {
4952                upsert: vec![successor.clone()],
4953                remove: Vec::new(),
4954            },
4955            now,
4956        );
4957        tracker.apply_peer_update(
4958            &ts_control::PeerUpdate::Delta {
4959                upsert: Vec::new(),
4960                remove: vec![departing.id],
4961            },
4962            now,
4963        );
4964
4965        assert_eq!(tracker.peer_db.peers().len(), 1);
4966        assert_eq!(
4967            tracker
4968                .peer_by_tailnet_ip_opt(tailnet_ipv4(9))
4969                .map(|n| &n.stable_id),
4970            Some(&successor.stable_id),
4971            "a removal that arrives late must not evict the address's live owner"
4972        );
4973        assert!(
4974            tracker
4975                .whois_opt("100.64.0.9:80".parse().unwrap())
4976                .is_some(),
4977            "so whois still identifies the peer that is present and handshaking"
4978        );
4979    }
4980
4981    /// The positive case, through the same path: a peer removed while it still owns its rows is
4982    /// really gone from every index, so the guard cannot pass by never evicting anything.
4983    #[tokio::test]
4984    async fn a_removal_with_no_successor_clears_the_indexes() {
4985        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
4986        let now = local_now();
4987
4988        let peer = peer_at("solo", 1, 1, 9);
4989        tracker.apply_peer_update(
4990            &ts_control::PeerUpdate::Delta {
4991                upsert: vec![peer.clone()],
4992                remove: Vec::new(),
4993            },
4994            now,
4995        );
4996        tracker.apply_peer_update(
4997            &ts_control::PeerUpdate::Delta {
4998                upsert: Vec::new(),
4999                remove: vec![peer.id],
5000            },
5001            now,
5002        );
5003
5004        assert!(tracker.peer_db.peers().is_empty());
5005        assert!(tracker.peer_by_tailnet_ip_opt(tailnet_ipv4(9)).is_none());
5006        assert!(tracker.peer_by_name_opt("solo.ts.net").is_none());
5007        assert!(tracker.peer_db.get(&peer.node_key).is_none());
5008        assert!(tracker.peer_db.get(&peer.stable_id).is_none());
5009        assert!(
5010            tracker
5011                .whois_opt("100.64.0.9:80".parse().unwrap())
5012                .is_none(),
5013            "a departed peer must not stay attributable by its old address"
5014        );
5015    }
5016}
5017
5018#[cfg(test)]
5019mod expiry_tests {
5020    //! Node-key expiry enforcement at the peer tracker — the port of Go's `expiryManager`
5021    //! (`ipn/ipnlocal/expiry.go`) wired into this fork's netmap.
5022    //!
5023    //! [`ts_control::ExpiryManager`] carries its own unit tests for the decision itself. These
5024    //! cover the wiring: that the pass runs at the install site, that the state it leaves is
5025    //! observable through [`StatusNode`], and that the timer catches a peer that expires with **no
5026    //! netmap in between** — the case the timer exists for.
5027
5028    use chrono::TimeDelta;
5029    use kameo::actor::Spawn as _;
5030
5031    use super::{
5032        tka_tests::{await_peer_count, netmap_with_peers, peer_node, test_env},
5033        *,
5034    };
5035
5036    /// A peer with a chosen key expiry, endpoints and a DERP home — the three things the expiry
5037    /// pass strips.
5038    fn expiring_peer(
5039        stable_id: &str,
5040        key: u8,
5041        expiry: Option<chrono::DateTime<chrono::Utc>>,
5042    ) -> Node {
5043        let mut node = peer_node(stable_id, [key; 32], Vec::new());
5044        node.node_key_expiry = expiry;
5045        node.underlay_addresses = vec!["192.0.2.9:41641".parse().unwrap()];
5046        node.derp_region = Some(ts_derp::RegionId(core::num::NonZeroU32::new(3).unwrap()));
5047        node.peerapi_port = Some(8080);
5048        node
5049    }
5050
5051    /// The fail-closed direction here is to **flag, not drop**: Go deliberately keeps an expired
5052    /// peer in the netmap so callers can give a clear error, and removing it would lose that. The
5053    /// peer stays addressable by stable id while losing everything that could carry traffic.
5054    #[tokio::test]
5055    async fn an_expired_peer_is_flagged_and_kept_not_dropped() {
5056        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
5057        let now = local_now();
5058        let peer = expiring_peer("eXpIrEd", 7, Some(now - TimeDelta::hours(1)));
5059        let pristine_key = peer.node_key;
5060
5061        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer.clone()]), now);
5062
5063        let (_id, stored) = tracker
5064            .peer_db
5065            .get(&peer.stable_id)
5066            .expect("the expired peer is KEPT in the netmap, not dropped");
5067        assert!(stored.expired);
5068        assert!(
5069            stored.underlay_addresses.is_empty(),
5070            "endpoints are cleared"
5071        );
5072        assert_eq!(stored.derp_region, None, "the DERP home is cleared");
5073        assert_eq!(
5074            stored.node_key,
5075            ts_keys::node_public_with_bad_old_prefix(pristine_key),
5076            "the node key is broken, so nothing can handshake with the peer"
5077        );
5078        assert_eq!(
5079            stored.peerapi_addr(),
5080            None,
5081            "a peerAPI dial to the expired peer is refused"
5082        );
5083
5084        let status = tracker.status_peers();
5085        assert_eq!(status.len(), 1);
5086        assert!(status[0].expired, "the state is observable to a watcher");
5087    }
5088
5089    /// The negative case: a tagged node carries no key expiry at all (Go's zero `KeyExpiry`) and is
5090    /// never flagged, however far the clock is pushed.
5091    #[tokio::test]
5092    async fn a_peer_with_no_expiry_is_never_flagged() {
5093        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
5094        let now = local_now();
5095        let tagged = expiring_peer("tAgGeD", 8, None);
5096
5097        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![tagged.clone()]), now);
5098        assert!(
5099            tracker
5100                .reevaluate_expiry(now + TimeDelta::days(3650))
5101                .is_empty(),
5102            "a node with no expiry never expires, ten years on"
5103        );
5104
5105        let (_id, stored) = tracker
5106            .peer_db
5107            .get(&tagged.stable_id)
5108            .expect("still a peer");
5109        assert!(!stored.expired);
5110        assert_eq!(stored.node_key, tagged.node_key, "its key is left alone");
5111        assert_eq!(stored.underlay_addresses, tagged.underlay_addresses);
5112        assert_eq!(stored.derp_region, tagged.derp_region);
5113    }
5114
5115    /// The case the timer exists for: a peer that is perfectly live when it is installed, and whose
5116    /// key expiry then passes with **no netmap in between**. `reevaluate_expiry` is what the fired
5117    /// timer runs.
5118    #[tokio::test]
5119    async fn a_peer_that_expires_between_netmaps_is_flagged_by_the_timer_pass() {
5120        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
5121        let now = local_now();
5122        let peer = expiring_peer("lIvE", 9, Some(now + TimeDelta::hours(1)));
5123
5124        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer.clone()]), now);
5125        let (_id, stored) = tracker.peer_db.get(&peer.stable_id).expect("installed");
5126        assert!(!stored.expired, "not expired when control handed it to us");
5127
5128        // No netmap arrives. The clock crosses the peer's expiry.
5129        let upserts = tracker.reevaluate_expiry(now + TimeDelta::hours(2));
5130
5131        assert_eq!(upserts.len(), 1, "the peer is re-installed, flagged");
5132        let (_id, stored) = tracker
5133            .peer_db
5134            .get(&peer.stable_id)
5135            .expect("still kept, just flagged");
5136        assert!(stored.expired);
5137        assert!(stored.underlay_addresses.is_empty());
5138        assert_eq!(stored.derp_region, None);
5139    }
5140
5141    /// An already-expired peer must be skipped rather than re-flagged, or the log and the
5142    /// invalidation it triggers repeat on every pass — and the broken key would be re-broken.
5143    #[tokio::test]
5144    async fn an_already_flagged_peer_is_not_reflagged() {
5145        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
5146        let now = local_now();
5147        let peer = expiring_peer("lIvE", 9, Some(now + TimeDelta::hours(1)));
5148        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer.clone()]), now);
5149
5150        let later = now + TimeDelta::hours(2);
5151        assert_eq!(tracker.reevaluate_expiry(later).len(), 1);
5152        let after_first = tracker
5153            .peer_db
5154            .get(&peer.stable_id)
5155            .expect("kept")
5156            .1
5157            .clone();
5158
5159        assert!(
5160            tracker.reevaluate_expiry(later).is_empty(),
5161            "the second pass reports no transition, so nothing is re-published"
5162        );
5163        assert_eq!(
5164            tracker.peer_db.get(&peer.stable_id).expect("kept").1,
5165            &after_first,
5166            "and nothing is mutated a second time"
5167        );
5168    }
5169
5170    /// End to end through the LIVE actor, which is the only thing that proves the wiring: a peer
5171    /// that is live when the netmap installs it, and whose key then expires while the map poll sits
5172    /// idle, is flagged by the timer alone. If the timer were never armed — or its firing never
5173    /// re-ran the pass — the peer would keep its endpoints, its DERP home and a usable node key
5174    /// until control happened to send another netmap.
5175    #[tokio::test]
5176    async fn a_key_expiring_with_no_netmap_in_between_is_caught_by_the_live_timer() {
5177        let env = test_env();
5178        let (_tka_tx, tka_rx) = watch::channel(None);
5179        let live = PeerTracker::spawn((env.clone(), tka_rx));
5180        assert!(live.ask(AllPeers).await.expect("started").is_empty());
5181
5182        // Expires shortly, but strictly in the future: the install-time pass must NOT flag it. The
5183        // window has to outlast actor start + publish + one ask on a loaded box, hence seconds
5184        // rather than milliseconds; the test does not wait it out, it only waits for the wall clock
5185        // to cross it (below).
5186        let expiry = local_now() + TimeDelta::seconds(2);
5187        let peer = expiring_peer("sHoRtLiVeD", 4, Some(expiry));
5188        env.publish(Arc::new(netmap_with_peers(vec![peer.clone()])))
5189            .await
5190            .expect("publish netmap");
5191
5192        let installed = await_peer_count(&live, 1).await;
5193        assert!(
5194            local_now() < expiry,
5195            "the install has to finish inside the window, or this test is not testing the timer"
5196        );
5197        assert!(
5198            !installed[0].expired,
5199            "still live when control handed it to us"
5200        );
5201
5202        // Let the key really expire on the wall clock the pass reads...
5203        while local_now() <= expiry {
5204            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
5205        }
5206        // ...then jump the runtime's timer wheel past the armed delay (the peer's expiry plus Go's
5207        // slack) so the timer fires now instead of ten seconds from now. No netmap in between.
5208        tokio::time::pause();
5209        tokio::time::advance(std::time::Duration::from_secs(
5210            ts_control::EXPIRY_TIMER_SLACK_SECS as u64 + 5,
5211        ))
5212        .await;
5213        tokio::time::resume();
5214
5215        let flagged = tokio::time::timeout(std::time::Duration::from_secs(10), async {
5216            loop {
5217                let peers = live.ask(AllPeers).await.expect("peer tracker is alive");
5218                if peers.first().is_some_and(|p| p.expired) {
5219                    return peers;
5220                }
5221                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
5222            }
5223        })
5224        .await
5225        .expect("the expiry timer flagged the peer with no netmap in between");
5226
5227        assert_eq!(flagged.len(), 1, "flagged, not dropped");
5228        assert!(flagged[0].underlay_addresses.is_empty());
5229        assert_eq!(flagged[0].derp_region, None);
5230        assert_eq!(
5231            flagged[0].node_key,
5232            ts_keys::node_public_with_bad_old_prefix(peer.node_key)
5233        );
5234    }
5235
5236    /// The recovery path, through the channel that actually carries it: control extends an expired
5237    /// peer's key with a `PeerChange` that restates only `KeyExpiry`. The peer has to come back
5238    /// with its direct candidates and its home DERP, not merely with a usable node key — flagging
5239    /// cleared all three, the patch restates none of them, and a peer that is un-expired but has
5240    /// neither an endpoint nor a DERP home is unroutable until the next full netmap.
5241    #[tokio::test]
5242    async fn an_expiry_only_patch_restores_the_peers_routes() {
5243        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
5244        let now = local_now();
5245        let peer = expiring_peer("eXtEnDeD", 6, Some(now - TimeDelta::hours(1)));
5246
5247        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer.clone()]), now);
5248        assert!(
5249            tracker
5250                .peer_db
5251                .get(&peer.stable_id)
5252                .expect("kept")
5253                .1
5254                .expired,
5255            "flagged on the way in"
5256        );
5257
5258        // Exactly the shape of a `PeerChange` that only extends the key's life.
5259        let patch = ts_control::PeerChange {
5260            id: peer.id,
5261            derp_region: None,
5262            cap: None,
5263            cap_map: None,
5264            underlay_addresses: None,
5265            node_key: None,
5266            key_signature: None,
5267            disco_key: None,
5268            node_key_expiry: Some(now + TimeDelta::days(30)),
5269            online: None,
5270            last_seen: None,
5271        };
5272        tracker.apply_peer_patches(std::slice::from_ref(&patch), now);
5273
5274        let (_id, stored) = tracker.peer_db.get(&peer.stable_id).expect("still a peer");
5275        assert!(!stored.expired, "the extension un-expires the peer");
5276        assert_eq!(stored.node_key, peer.node_key, "its real node key is back");
5277        assert_eq!(
5278            stored.underlay_addresses, peer.underlay_addresses,
5279            "and its direct-path candidates"
5280        );
5281        assert_eq!(
5282            stored.derp_region, peer.derp_region,
5283            "and its home DERP route"
5284        );
5285        assert_eq!(
5286            stored.peerapi_addr(),
5287            peer.peerapi_addr(),
5288            "so a peerAPI dial to it is answerable again"
5289        );
5290    }
5291
5292    /// The lookup a caller holding an older [`Node`] snapshot refreshes it through, end to end
5293    /// through the live actor: `tailscale::Device::send_file` re-reads the peer by stable id so it
5294    /// refuses an expired peer with the reason instead of dialing a broken one and reporting a
5295    /// timeout. Also pins that the query answers *immediately* before the first netmap — queueing
5296    /// it (as [`PeerByName`] does) would park a send behind a netmap that may never arrive.
5297    #[tokio::test]
5298    async fn peer_by_stable_id_answers_with_the_current_flagged_record() {
5299        let env = test_env();
5300        let (_tka_tx, tka_rx) = watch::channel(None);
5301        let live = PeerTracker::spawn((env.clone(), tka_rx));
5302
5303        let peer = expiring_peer("eXpIrEd", 7, Some(local_now() - TimeDelta::hours(1)));
5304
5305        // Before any netmap: an immediate `None`, not a queued reply.
5306        let unknown = tokio::time::timeout(
5307            std::time::Duration::from_secs(5),
5308            live.ask(PeerByStableId {
5309                stable_id: peer.stable_id.clone(),
5310            }),
5311        )
5312        .await
5313        .expect("the query answers without waiting for a netmap")
5314        .expect("peer tracker is alive");
5315        assert_eq!(unknown, None);
5316
5317        env.publish(Arc::new(netmap_with_peers(vec![peer.clone()])))
5318            .await
5319            .expect("publish netmap");
5320        await_peer_count(&live, 1).await;
5321
5322        let current = live
5323            .ask(PeerByStableId {
5324                stable_id: peer.stable_id.clone(),
5325            })
5326            .await
5327            .expect("peer tracker is alive")
5328            .expect("the expired peer is kept, so it is still resolvable by stable id");
5329        assert!(
5330            current.expired,
5331            "the record carries the flag, not the stale state"
5332        );
5333        assert_eq!(
5334            current.peerapi_addr(),
5335            None,
5336            "so a peerAPI dial resolved from it is refused"
5337        );
5338    }
5339
5340    /// `MapResponse.ControlTime` is the reason the comparison is exact rather than approximate: a
5341    /// node whose own clock is hours behind control's must still see a peer as expired.
5342    #[tokio::test]
5343    async fn a_control_time_delta_decides_expiry_against_controls_clock() {
5344        let (mut tracker, _tka_tx) = PeerTracker::for_test(test_env(), None);
5345        let now = local_now();
5346        // Local time says this expires in an hour.
5347        let peer = expiring_peer("sKeWeD", 5, Some(now + TimeDelta::hours(1)));
5348
5349        // Control's clock is two hours ahead of ours, so by control's reckoning it went an hour ago.
5350        tracker
5351            .expiry
5352            .on_control_time(now + TimeDelta::hours(2), now);
5353        tracker.apply_peer_update(&ts_control::PeerUpdate::Full(vec![peer.clone()]), now);
5354
5355        let (_id, stored) = tracker.peer_db.get(&peer.stable_id).expect("kept");
5356        assert!(
5357            stored.expired,
5358            "expiry is judged against control's clock, not this host's"
5359        );
5360    }
5361}