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