Skip to main content

ts_runtime/
control_runner.rs

1use core::{
2    net::{Ipv4Addr, Ipv6Addr},
3    time::Duration,
4};
5use std::{collections::HashMap, sync::Arc, time::Instant};
6
7use futures::StreamExt;
8use kameo::{
9    actor::{ActorRef, Spawn},
10    message::{Context, StreamMessage},
11    prelude::Message,
12};
13use tokio::sync::watch;
14use ts_control::{
15    AsyncControlClient, Endpoint, EndpointType, Error as ControlError, IdTokenError, LogoutError,
16    Node, SetDnsError, SshPolicy, StateUpdate, TkaStatus, TkaSyncError, tka_disable,
17    tka_init_begin, tka_init_finish, tka_submit_signature,
18};
19use ts_magicsock::SelfEndpointType;
20
21use crate::{
22    derp_latency::{DerpLatencyMeasurement, DerpLatencyMeasurer},
23    direct::EndpointAdvertisement,
24};
25
26/// Actor responsible for maintaining the connection to control.
27///
28/// This actor is responsible for proxying the map response stream onto the message bus.
29pub struct ControlRunner {
30    client: AsyncControlClient,
31    params: Params,
32
33    self_node: watch::Sender<Option<Node>>,
34    /// Latest Tailscale SSH policy pushed by control, or `None` until control sends one. The SSH
35    /// server reads this to authorize incoming connections; absent policy means deny-all.
36    ssh_policy: watch::Sender<Option<SshPolicy>>,
37    /// Latest Tailnet Lock status pushed by control, or `None` until control sends one.
38    tka: watch::Sender<Option<TkaStatus>>,
39    /// The locally-synced Tailnet-Lock state (verified `Authority` + AUM store), or `None` until a
40    /// successful bootstrap+sync. Held here because `ControlRunner` owns the netmap stream that
41    /// triggers resync. Mutated only on the actor thread (the netmap handler spawns the sync RPC and
42    /// the result returns via the [`TkaSynced`] self-message).
43    tka_synced: Option<crate::tka_sync::SyncedTka>,
44    /// The verified TKA [`Authority`](ts_tka::Authority) the peer tracker **enforces** (Go
45    /// `tkaFilterNetmapLocked`). `None` until the first successful sync, and reset to `None` when the
46    /// lock is disabled. This is the SOLE delivery channel to the peer tracker (which holds the
47    /// matching `Receiver` and reads it on every peer upsert): a `watch` cell, not a bus message, so
48    /// the latest value is always readable, never dropped under load, and writes are strictly ordered
49    /// by this actor — a disable (`None`) can never be reordered behind or dropped before a stale
50    /// `Some`. Written only from [`apply_tka_synced`] (enable) and [`maybe_sync_tka`] (disable), both
51    /// on the actor thread. The published `Authority` has always passed `VerifiedAumChain::verify`.
52    tka_authority: watch::Sender<Option<Arc<ts_tka::Authority>>>,
53    /// In-flight guard: `true` while a sync RPC task is running, so a burst of netmap updates does
54    /// not spawn overlapping syncs (Go serializes sync under `b.mu`).
55    tka_syncing: bool,
56    /// Monotonic generation stamped when a disable (or a fresh sync) supersedes any in-flight sync.
57    /// `maybe_sync_tka` bumps this on a disable transition and captures it into each spawned sync;
58    /// [`apply_tka_synced`] discards a sync result whose captured generation is stale, so a lock
59    /// disabled *while a sync was in flight* is never re-enabled by that sync's late `Ok(Some)`
60    /// (the in-flight window the `tka_synced.is_some()` disable guard alone does not cover).
61    tka_generation: u64,
62    /// Latest cert-domain list from control's netmap DNS config (Go `nm.DNS.CertDomains`), or empty
63    /// until control sends a DNS config carrying one. The facade reads this for `Device::cert_domains`.
64    cert_domains: watch::Sender<Vec<String>>,
65    /// Latest full DNS config from control's netmap (Go `netmap.NetworkMap.DNS`), or `None` until
66    /// control sends one. The facade reads this for `Device::dns_config` (the daemon's
67    /// `tnet dns status`). A superset of [`cert_domains`](Self::cert_domains), which is kept as its
68    /// own cell for the narrower TLS-cert use.
69    dns_config: watch::Sender<Option<ts_control::DnsConfig>>,
70    /// Latest interactive-login / consent URL control asked this node to open
71    /// (`MapResponse.PopBrowserURL`), or `None` until control sends one. The facade reads this for
72    /// `Device::pop_browser_url` (a daemon driving a non-authkey login surfaces it to the user), and
73    /// [`Runtime::watch_ipn_bus`](crate::Runtime::watch_ipn_bus) subscribes to it for the bus's
74    /// `browse_to_url` running-node events.
75    ///
76    /// **Sticky, not per-update** (Go `controlclient` `sess.lastPopBrowserURL`): control sends
77    /// `MapResponse.PopBrowserURL` empty on nearly every netmap tick, so this cell is updated ONLY on
78    /// a non-empty URL that differs from its current value (`sticky_update_pop_browser_url`, via
79    /// `send_if_modified` — the cell's own value is the "last URL seen", so no separate mirror is
80    /// needed). It is never reset to `None` by an empty update — matching Go's `direct.go` guard
81    /// `u != "" && u != sess.lastPopBrowserURL`. Updating on every tick would thrash the cell to
82    /// `None` and coalesce the URL away for a `watch` subscriber.
83    pop_browser_url: watch::Sender<Option<url::Url>>,
84    /// Latest network-conditions report (preferred DERP region + per-region latencies), updated each
85    /// time the DERP-latency measurer reports in. The facade reads this for `Device::netcheck` (the
86    /// daemon's `tnet netcheck`). Empty until the first measurement.
87    netcheck: watch::Sender<crate::status::NetcheckReport>,
88    /// The DERP home region currently selected, with the latency measured for it at selection time.
89    /// `None` until the first home region is chosen. Used to apply selection **hysteresis** (Go
90    /// `netcheck.addReportHistoryAndSetPreferredDERP`): the home region is only switched when a new
91    /// region is *meaningfully* lower-latency than the current one, so jitter between near-equal
92    /// regions does not flap the home relay (which would cause repeated reconnects + brief loss).
93    home_region: Option<(ts_derp::RegionId, core::time::Duration)>,
94    /// Rolling history of per-cycle DERP-latency reports within the last [`DERP_HISTORY_MAX_AGE`]
95    /// (Go `netcheck` `maxAge = 5 * time.Minute`), each stamped with its arrival `Instant`. Feeds the
96    /// `bestRecent` smoothing (Go `addReportHistoryAndSetPreferredDERP`): the new home candidate is
97    /// chosen by each region's **minimum** latency over this window, not its raw current sample, so a
98    /// best region whose latency oscillates across the switch boundary does not flap the home relay.
99    /// Aged entries are evicted on each measurement; the buffer is therefore bounded by the netcheck
100    /// cadence × the window.
101    derp_report_history: Vec<(Instant, Arc<Vec<ts_netcheck::RegionResult>>)>,
102    /// Consecutive automatic-reauth attempts that have NOT yet recovered the node to a good (non-
103    /// expired) self-node. The circuit breaker for [`expiry_action`]'s `Reauthenticate` path: a
104    /// one-shot / already-consumed auth key cannot re-register, so without a bound an expired node
105    /// would sit in [`DeviceState::Reauthenticating`] indefinitely (the rotated re-register keeps
106    /// failing or control keeps returning a still-expired self-node).
107    ///
108    /// Incremented once per expired self-node seen while *already* `Reauthenticating` (each such
109    /// arrival is evidence the prior reauth did not recover); reset to `0` whenever a good
110    /// (non-expired) self-node arrives (the node recovered) — see the [`StreamMessage::Next`] handler.
111    /// At [`MAX_REAUTH_ATTEMPTS`] the runner stops re-arming reauth and flips the cell to the terminal
112    /// [`DeviceState::Expired`], giving the cell a stable terminal state (a genuinely good self-node
113    /// can still recover it later). The one-shot `Command::Reauth` is fired ONLY on the transition
114    /// INTO `Reauthenticating`, never re-fired while already reauthenticating, so the node key is
115    /// rotated at most once per episode (a second rotation would lose the original `OldNodeKey`
116    /// anchor control needs to link the rotation).
117    reauth_attempts: u32,
118    /// Background task that bridges the control client's mid-session re-auth URL cell onto
119    /// [`Self::params`]'s device-state cell (sets [`DeviceState::NeedsLogin`] when control returns
120    /// `MachineNotAuthorized` on a live re-register — see [`bridge_reauth_url_to_state`]). Aborted on
121    /// [`Drop`] so it cannot outlive the actor (the [`DataplaneActor`](crate::dataplane) pattern).
122    reauth_bridge: tokio::task::JoinHandle<()>,
123}
124
125/// The number of consecutive failed automatic-reauth attempts after which the runner gives up
126/// re-arming reauth and flips the device to the terminal [`DeviceState::Expired`] (the circuit
127/// breaker from the design's deferred-question Q1). A one-shot auth key was consumed by the first
128/// registration, so an auto re-register with it cannot succeed; this bounds that case to today's
129/// terminal behavior instead of an indefinite `Reauthenticating` spell. The first arrival fires the
130/// reauth; each subsequent expired self-node while still reauthenticating counts toward this cap.
131const MAX_REAUTH_ATTEMPTS: u32 = 3;
132
133impl Drop for ControlRunner {
134    fn drop(&mut self) {
135        // Stop the re-auth bridge so it does not outlive the actor (mirrors `DataplaneActor`).
136        self.reauth_bridge.abort();
137    }
138}
139
140/// Control runner args.
141pub struct Params {
142    /// Control config.
143    pub(crate) config: ts_control::Config,
144
145    /// Auth key (if needed).
146    pub(crate) auth_key: Option<String>,
147
148    /// The [`crate::Env`] for this actor.
149    pub(crate) env: crate::Env,
150
151    /// Sender for the device connection-state cell. Created in [`Runtime::spawn`](crate::Runtime)
152    /// so it outlives the actor's `on_start` (which may publish [`DeviceState::Failed`] and then
153    /// return `Err`, before `Self` exists). The runtime keeps the matching `Receiver` for
154    /// [`watch_state`](crate::Runtime::watch_state) / [`wait_until_running`](crate::Runtime::wait_until_running).
155    pub(crate) state_tx: watch::Sender<crate::DeviceState>,
156
157    /// Sender for the TKA enforcement-authority cell the peer tracker reads (Go
158    /// `tkaFilterNetmapLocked`). Created in [`Runtime::spawn`](crate::Runtime) and threaded into BOTH
159    /// the peer tracker (the `Receiver`) and this runner (the `Sender`), so the runner is the sole
160    /// writer and the tracker reads the latest verified `Authority` on demand. `None` = no lock /
161    /// disabled (admit all).
162    pub(crate) tka_authority: watch::Sender<Option<Arc<ts_tka::Authority>>>,
163
164    /// Sender for the selected DERP home region (the **smoothed** `bestRecent` + hysteresis choice,
165    /// Go `report.PreferredDERP`). Created in [`Runtime::spawn`](crate::Runtime); the runner is the
166    /// sole writer and [`Multiderp`](crate::multiderp) holds the `Receiver`, so the local DERP relay
167    /// follows the SAME home the runner advertises to control — not the raw per-cycle latency
168    /// minimum (which would flap on jitter and disagree with the advertised home). `None` until the
169    /// first home is chosen.
170    pub(crate) home_region: watch::Sender<Option<ts_derp::RegionId>>,
171}
172
173#[doc(hidden)]
174#[derive(Debug, thiserror::Error)]
175pub enum ControlRunnerError {
176    #[error(transparent)]
177    Control(#[from] ControlError),
178
179    #[error(transparent)]
180    Crate(#[from] crate::Error),
181}
182
183impl kameo::Actor for ControlRunner {
184    type Args = Params;
185    type Error = ControlRunnerError;
186
187    async fn on_start(params: Params, slf: ActorRef<Self>) -> Result<Self, Self::Error> {
188        // Cold start: replay the netmap this node cached the last time control granted it
189        // `cache-network-maps` (Go `nodecap.CacheNetworkMaps`, capability version 135 — upstream
190        // does the same from `ipnlocal.Start`, feeding the cached map through
191        // `setControlClientStatusLocked` before it builds its control client). Publishing it here,
192        // ahead of registration, is the whole point: the peer tracker, dataplane and packet filter
193        // get the last-known peers, DERP map and rules while this node is still doing its
194        // register/poll round trips, so peer connectivity can start coming up before control has
195        // said a word. Control's own first netmap lands on the same bus moments later and replaces
196        // it, and a netmap that no longer carries the attribute deletes the cache (see
197        // `NetmapCache::observe`).
198        //
199        // Nothing here can fail the start-up: no cache configured, nothing cached, or an
200        // undecodable cache all mean "carry on without one".
201        replay_cached_netmap(&params).await;
202
203        // The interactive AuthURL, captured on the first unauthorized reply and reused as the
204        // `followup` on every subsequent poll so control long-polls ONE stable URL (rather than
205        // minting a fresh, racing URL each retry) until the user visits it.
206        let mut login_url: Option<url::Url> = None;
207        loop {
208            match AsyncControlClient::check_auth(
209                &params.config,
210                &params.env.keys,
211                params.auth_key.as_deref(),
212                login_url.as_ref(),
213            )
214            .await
215            {
216                Ok(()) => break,
217                Err(ControlError::MachineNotAuthorized(u)) => {
218                    // Capture the FIRST url and keep showing/following-up on it, so the link the
219                    // user opened stays valid instead of being superseded by the next poll.
220                    let url = login_url.get_or_insert(u).clone();
221                    tracing::info!(auth_url = %url, "please authorize this machine or pass an auth key");
222                    // Publish `NeedsLogin(url)` only when it actually changes the cell. With `followup`
223                    // set, the SAME URL is re-affirmed on every long-poll timeout; a bare `send_replace`
224                    // re-notifies `state_rx` each cycle, so the bus re-emits `browse_to_url` for a link
225                    // the user already has — reopening it repeatedly. `send_if_modified` dedups the
226                    // no-op, mirroring `bridge_reauth_url_to_state` (the mid-session re-auth path).
227                    let next = crate::DeviceState::NeedsLogin(url);
228                    params.state_tx.send_if_modified(|current| {
229                        if *current == next {
230                            false
231                        } else {
232                            *current = next.clone();
233                            true
234                        }
235                    });
236                    // With followup set, check_auth long-polls until the URL is visited; this short
237                    // sleep only applies if control times the poll out, and we re-followup the SAME url.
238                    tokio::time::sleep(Duration::from_secs(2)).await;
239                }
240                Err(ControlError::NeedsMachineAuth) => {
241                    // The node is registered with a valid key but awaiting ADMIN APPROVAL on an
242                    // approval-gated tailnet, and control offered NO interactive URL. This is
243                    // TRANSIENT (Go's `NeedsMachineAuth`): poll registration until an admin approves,
244                    // then `check_auth` returns `Ok(())` → the loop breaks and the node comes up with
245                    // no re-registration. Publishing the (no-URL) `NeedsMachineAuth` state — NOT a
246                    // terminal `Failed` and NOT `NeedsLogin` (there is no URL to open) — lets a
247                    // watcher / `wait_until_running` see "awaiting approval" instead of an opaque
248                    // timeout. Same 5s poll cadence as the `MachineNotAuthorized(url)` arm.
249                    tracing::info!(
250                        "machine awaiting admin approval to join the tailnet; polling until approved"
251                    );
252                    params
253                        .state_tx
254                        .send_replace(crate::DeviceState::NeedsMachineAuth);
255                    tokio::time::sleep(Duration::from_secs(5)).await;
256                }
257                Err(ControlError::RateLimited(retry_after)) => {
258                    // Control asked us to slow down (HTTP 429). Wait exactly the server-requested
259                    // cooldown and retry — this is transient, NOT a terminal `Failed`, so we must
260                    // not stop the runner (mirrors Go's `authRoutine` sleeping `rle.retryAfter`).
261                    tracing::warn!(
262                        ?retry_after,
263                        "control rate-limited registration; waiting before retry"
264                    );
265                    tokio::time::sleep(retry_after).await;
266                }
267                Err(e) => {
268                    // Followup auth path gone: while long-polling a STABLE AuthURL, control returns
269                    // an HTTP registration error (410 "auth path not found") once the path is either
270                    // VISITED + approved (consumed) or expired. This is NOT terminal — drop the
271                    // followup and re-register ONCE: an approved node key comes back `MachineAuthorized`
272                    // (`Ok(())` → login completes), an expired one comes back with a fresh AuthURL.
273                    // Without this, the user's own approval (which consumes the path → 410) kills the
274                    // runner. Bounded: on re-register `login_url` is None, so a repeat HTTP error falls
275                    // through to the terminal handling below (no infinite loop).
276                    if login_url.is_some()
277                        && matches!(
278                            e,
279                            ControlError::Internal(
280                                ts_control::InternalErrorKind::Http,
281                                ts_control::Operation::Registration,
282                            )
283                        )
284                    {
285                        tracing::info!(
286                            "followup auth path gone (approved or expired); re-registering"
287                        );
288                        login_url = None;
289                        tokio::time::sleep(Duration::from_secs(1)).await;
290                        continue;
291                    }
292                    // A hard registration failure (bad/expired/unknown auth key, etc.). Log the
293                    // specific reason control gave AND publish it as a typed `Failed` state so
294                    // `Device::wait_until_running` returns the actionable reason (tsr-kqj) instead
295                    // of the opaque `Internal(Actor)` the caller would otherwise see once the
296                    // stopped actor is next asked. Publishing before `return Err` is why the state
297                    // sender lives on `Runtime`, not on `Self` (which never gets constructed here).
298                    let reason = crate::RegistrationError::from(&e);
299                    tracing::error!(error = %e, "registration failed; control runner stopping");
300                    params
301                        .state_tx
302                        .send_replace(crate::DeviceState::Failed(reason));
303                    return Err(e.into());
304                }
305            }
306        }
307        // check_auth succeeded, but the node is not "up" until the netmap stream is actually
308        // attached below. Publish `Running` only AFTER `attach_stream` so `wait_until_running` never
309        // resolves `Ok` for a device whose stream connect failed (which would leave a stopped actor
310        // behind). If the connect/subscribe steps fail, publish a transient `Failed` first so the
311        // waiter sees an actionable reason instead of the opaque post-mortem `Internal(Actor)`.
312        // The control client's live map-poll loop publishes a mid-session re-auth URL here (set when
313        // a re-register returns `MachineNotAuthorized` because the node key expired/was revoked). The
314        // runtime owns the receiver; `connect` takes the sender. Created before `connect` so the
315        // sender is in place for the very first poll, and so the receiver outlives `bring_up`.
316        let (auth_url_tx, auth_url_rx) = watch::channel::<Option<url::Url>>(None);
317
318        // `connect` issues its own `machine/register` POST (a second one after `check_auth`'s), so
319        // it too can hit a 429. Wrap it in the same honor-`Retry-After` retry as the `check_auth`
320        // loop above: a rate-limit is transient — sleeping the server-requested cooldown and
321        // retrying must NOT stop the runtime (a 429 here previously fell into the `Err(e)` arm →
322        // `Failed` → actor stop). `connect` consumes a `watch::Sender` by value (and drops it on a
323        // failed register, before it would be moved into the live-poll task), so we keep the original
324        // `auth_url_tx` alive here across all attempts and hand `connect` a CLONE each time. That
325        // keeps the runtime's `auth_url_rx` (the `reauth_bridge` receiver) paired with a live sender:
326        // recreating a fresh sender per attempt instead would orphan the bridge the moment the
327        // original dropped, silently killing mid-session re-auth-URL delivery.
328        let client = loop {
329            let bring_up = async {
330                let (client, stream) = AsyncControlClient::connect(
331                    &params.config,
332                    &params.env.keys,
333                    params.auth_key.as_deref(),
334                    auth_url_tx.clone(),
335                )
336                .await?;
337
338                DerpLatencyMeasurer::spawn_link(&slf, params.env.clone()).await;
339
340                params.env.subscribe::<DerpLatencyMeasurement>(&slf).await?;
341                params.env.subscribe::<EndpointAdvertisement>(&slf).await?;
342                slf.attach_stream(stream.boxed(), (), ());
343                Ok::<_, ControlRunnerError>(client)
344            };
345
346            match bring_up.await {
347                Ok(client) => break client,
348                Err(ControlRunnerError::Control(ControlError::RateLimited(retry_after))) => {
349                    tracing::warn!(
350                        ?retry_after,
351                        "control rate-limited the session bring-up; waiting before retry"
352                    );
353                    tokio::time::sleep(retry_after).await;
354                }
355                Err(ControlRunnerError::Control(ControlError::NeedsMachineAuth)) => {
356                    // `connect` issues its OWN `machine/register` POST (a second one after
357                    // `check_auth`'s), so it too can come back "awaiting admin approval, no URL". In
358                    // the normal flow the `check_auth` loop above already gated this (it only breaks
359                    // once registration returns `Ok`, and approval is monotonic), so this arm is the
360                    // defensive twin for a node de-authorized in the race window between the two POSTs:
361                    // treat it as TRANSIENT exactly like the `check_auth` arm — publish the (no-URL)
362                    // `NeedsMachineAuth` state, poll the same 5s, and retry the bring-up — rather than
363                    // collapsing into the terminal `Failed` arm below (which would permanently stop
364                    // the runner on a recoverable await-approval). Mirrors Go's `NeedsMachineAuth`.
365                    tracing::info!(
366                        "machine awaiting admin approval during session bring-up; polling until \
367                         approved"
368                    );
369                    params
370                        .state_tx
371                        .send_replace(crate::DeviceState::NeedsMachineAuth);
372                    tokio::time::sleep(Duration::from_secs(5)).await;
373                }
374                Err(e) => {
375                    tracing::error!(error = %e, "bringing up the control session failed");
376                    // The control session never came up; surface it as a transient registration
377                    // failure (a retry / fresh `Device::new` may succeed) rather than leaving the
378                    // state stuck at `Connecting`.
379                    params.state_tx.send_replace(crate::DeviceState::Failed(
380                        crate::RegistrationError::NetworkUnreachable,
381                    ));
382                    return Err(e);
383                }
384            }
385        };
386
387        // The netmap stream is attached: the node is up. The stream `Next` handler keeps this
388        // current (and flips to `Expired` if the self-node's key lapses).
389        params.state_tx.send_replace(crate::DeviceState::Running);
390
391        // Bridge the control client's mid-session re-auth URL cell onto the device-state cell: a
392        // `Some(url)` (control returned `MachineNotAuthorized` on a live re-register) becomes
393        // `DeviceState::NeedsLogin(url)` so the IPN bus surfaces `browse_to_url` and the embedder can
394        // prompt the user — the live-session analogue of the initial `check_auth` loop above. The
395        // recovery to `Running` is the netmap self-node handler's job (next good self-node), so this
396        // bridge only forwards `Some`. The task ends when the sender drops (the client's `run` task
397        // ended) and is aborted on actor `Drop`, so it cannot leak past the actor.
398        let reauth_bridge = {
399            let state_tx = params.state_tx.clone();
400            let mut auth_url_rx = auth_url_rx;
401            tokio::spawn(async move {
402                while auth_url_rx.changed().await.is_ok() {
403                    let url = auth_url_rx.borrow_and_update().clone();
404                    bridge_reauth_url_to_state(&state_tx, url.as_ref());
405                }
406            })
407        };
408
409        // Clone the TKA authority publisher before `params` moves into `Self` below. The matching
410        // `Receiver` lives on the peer tracker; this sender is the sole writer (enforce on sync,
411        // clear on disable).
412        let tka_authority = params.tka_authority.clone();
413
414        Ok(Self {
415            client,
416            params,
417            self_node: Default::default(),
418            ssh_policy: Default::default(),
419            tka: Default::default(),
420            tka_synced: None,
421            tka_authority,
422            tka_syncing: false,
423            tka_generation: 0,
424            cert_domains: Default::default(),
425            dns_config: Default::default(),
426            pop_browser_url: Default::default(),
427            netcheck: Default::default(),
428            home_region: None,
429            derp_report_history: Vec::new(),
430            reauth_attempts: 0,
431            reauth_bridge,
432        })
433    }
434}
435
436impl ControlRunner {
437    /// Decide whether the latest netmap's Tailnet-Lock status warrants a (re)sync and, if so, spawn
438    /// the bootstrap+sync RPC off the actor thread (so the netmap stream never blocks on a control
439    /// round-trip). The result returns via the [`TkaSynced`] self-message.
440    ///
441    /// Triggers when control reports TKA enabled (`is_enabled`) AND we are not already syncing AND
442    /// either we hold no `Authority` yet (→ bootstrap) or control's head differs from ours (→ catch
443    /// up). When TKA is disabled, clears any synced state (the lock was turned off). Mirrors Go's
444    /// `tkaSyncIfNeeded`: a no-op when our head already matches.
445    fn maybe_sync_tka(&mut self, tka: &TkaStatus, self_ref: ActorRef<Self>) {
446        if !tka.is_enabled() {
447            // Lock disabled (or never enabled): clear enforcement by writing `None` to the authority
448            // cell the peer tracker reads — synchronously, so it can never be reordered behind or
449            // dropped before a stale `Some` (the failure a best-effort broadcast had). Always bump the
450            // generation so ANY sync currently in flight is invalidated: without this, a disable that
451            // races an in-flight sync (whose `take()` already cleared `tka_synced`) would be a no-op
452            // here, and the sync's late `Ok(Some)` would silently re-enable a lock control just turned
453            // off (the in-flight window the `tka_synced.is_some()` guard alone misses). Cheap and
454            // idempotent: clearing an already-`None` cell and bumping the generation are harmless.
455            self.tka_generation = self.tka_generation.wrapping_add(1);
456            if self.tka_synced.is_some() {
457                tracing::info!("TKA lock disabled; clearing enforcement (admitting all peers)");
458                self.tka_synced = None;
459                // The chain we persisted for the cold-start replay described a lock that is now off.
460                // Dropping it is not what keeps the next cold start honest (the replay only vouches
461                // when the cached frame itself says the lock was on, and only with a chain at that
462                // frame's head) — it is so a disabled lock leaves nothing of itself on disk.
463                self.discard_persisted_tka_chain();
464            }
465            self.tka_authority.send_replace(None);
466            return;
467        }
468        if self.tka_syncing {
469            return; // a sync is already in flight; the next netmap will re-trigger if still stale
470        }
471        // Up-to-date check: if we already have an Authority whose head matches control's, nothing to
472        // do. A malformed control head is treated as "different" (we'll attempt a sync, which
473        // fail-closes harmlessly).
474        if let Some(synced) = &self.tka_synced
475            && let Some(control_head) = ts_tka::AumHash::from_base32(&tka.head)
476            && synced.authority.head_matches(&control_head)
477        {
478            return;
479        }
480
481        // Spawn the sync. Move the current synced state out (the driver takes it by value and returns
482        // the advanced state); `tka_synced` stays `None` until the result lands, guarded by
483        // `tka_syncing` so we don't spawn a second concurrent sync. Capture the current generation so
484        // `apply_tka_synced` can discard this result if a disable bumped the generation while the sync
485        // was in flight (H1: don't re-enable a lock that was disabled mid-sync).
486        self.tka_syncing = true;
487        let generation = self.tka_generation;
488        let current = self.tka_synced.take();
489        let config = self.params.config.clone();
490        let keys = self.params.env.keys.clone();
491        tokio::spawn(async move {
492            let result = crate::tka_sync::sync_tka(&config, &keys, current).await;
493            // Hand the outcome back to the actor thread to apply (mutating actor state off-thread is
494            // not allowed). A send failure just means the actor is gone — nothing to do.
495            if let Err(e) = self_ref.tell(TkaSynced { result, generation }).await {
496                tracing::debug!(error = ?e, "TKA sync result not delivered (actor gone)");
497            }
498        });
499    }
500
501    /// Apply the outcome of a spawned [`maybe_sync_tka`] task on the actor thread: store the advanced
502    /// state + publish the `Authority` to the peer tracker's enforcement cell (or, on inert/failed
503    /// sync, leave peers unaffected). Always clears the in-flight guard.
504    ///
505    /// `generation` is the value captured when the sync was spawned. If it no longer matches
506    /// `self.tka_generation`, the lock was disabled (or re-synced) while this sync was in flight, so
507    /// the result is discarded — never re-enabling an authority control has since turned off.
508    async fn apply_tka_synced(
509        &mut self,
510        result: Result<Option<crate::tka_sync::SyncedTka>, crate::tka_sync::TkaSyncDriverError>,
511        generation: u64,
512    ) {
513        self.tka_syncing = false;
514
515        // H1 guard: a disable (or a superseding sync) bumped the generation while this sync ran. Drop
516        // the stale result — `maybe_sync_tka`'s disable branch already cleared enforcement to `None`,
517        // and re-applying this `Some` would re-enforce a lock that is no longer active.
518        if generation != self.tka_generation {
519            tracing::info!(
520                "TKA sync result superseded (lock disabled or re-synced mid-flight); discarding"
521            );
522            return;
523        }
524
525        match result {
526            Ok(Some(synced)) => {
527                tracing::info!(
528                    head = %synced.authority.head().to_base32(),
529                    "TKA sync succeeded; enforcing verified Authority (Go tkaFilterNetmapLocked)"
530                );
531                // Deliver the verified Authority to the peer tracker's enforcement cell. The tracker
532                // reads it on every peer upsert and drops unauthorized peers. `Some(..)` = enforce; a
533                // `None` is written on disable. `watch` is the sole channel (last-write-wins, never
534                // dropped, ordered by this actor) — no bus, no re-publish-for-replay needed.
535                self.tka_authority
536                    .send_replace(Some(synced.authority.clone()));
537
538                // Observability (Go `tkaFilterNetmapLocked`'s self check → `LockedOut` health
539                // warning): verify SELF's own node-key signature against the freshly-synced
540                // Authority and warn if self is NOT authorized. We never FILTER self (self never
541                // enters the peer db, so enforcement can't lock us out of our own netmap), but Go
542                // raises an operator-facing warning here because a self that the lock does not
543                // authorize means this node's key-signature is missing/invalid for the current lock
544                // — it will be unable to prove itself to locked peers. This fork has no health
545                // subsystem, so the signal is a `tracing::warn!` (its observability channel).
546                //
547                // `self_node` is a sticky cell set on every netmap carrying a self-node; if a sync
548                // somehow lands before the first self-node ever arrived it is `None`, so we skip the
549                // advisory this cycle and re-evaluate on the next sync — fine for observability-only.
550                // The `borrow()` ref is scoped to this `if let` and dropped before the `&mut self`
551                // write below.
552                if let Some(self_node) = self.self_node.borrow().as_ref() {
553                    log_self_lockout(self_node, &synced.authority);
554                }
555
556                // Persist the verified chain beside the cached netmap so the *next* cold start can
557                // run this same filter over the cached peers before control answers — Go's cold
558                // start filters its cached map against the authority it re-opens from disk, and this
559                // is the disk it re-opens (see `replay_cached_netmap`).
560                self.persist_tka_chain(&synced).await;
561
562                self.tka_synced = Some(synced);
563            }
564            Ok(None) => {
565                // Control has no lock for us (no genesis / disabled). Clear any authority we were
566                // previously enforcing — symmetric with the disable path — so a transition to
567                // "no lock" stops dropping peers. Not an error.
568                if self.tka_synced.is_some() {
569                    tracing::info!("TKA sync: control reports no lock; clearing enforcement");
570                    self.tka_synced = None;
571                    self.discard_persisted_tka_chain();
572                }
573                self.tka_authority.send_replace(None);
574            }
575            Err(e) => {
576                // Transport or verify failure: log and leave the prior authority in place (a failed
577                // sync must not drop enforcement — that would fail OPEN). NEVER errors the netmap.
578                // The next netmap update re-triggers a sync attempt.
579                tracing::warn!(error = %e, "TKA sync failed; keeping prior enforcement state");
580            }
581        }
582    }
583
584    /// Persist the freshly-synced AUM chain next to the cached netmap, so a cold start can vouch for
585    /// the peers in that netmap ([`load_cached_netmap`]).
586    ///
587    /// Written only where the netmap itself is written: with no
588    /// [`netmap_cache_dir`](ts_control::Config::netmap_cache_dir) there is nothing to vouch for, and
589    /// with the `cache-network-maps` grant absent or overridden nothing is cached either, so the
590    /// chain is removed instead of written — the same withdrawal rule `NetmapCache::observe` applies
591    /// to the netmap. The grant is read from the last self node control sent, which is the same
592    /// source `observe` reads it from: nothing is ever cached before one arrives, so "no self node
593    /// yet" is also "nothing to vouch for". A write failure is logged inside the cache and changes
594    /// nothing: the next cold start simply withholds the cached peers.
595    async fn persist_tka_chain(&self, synced: &crate::tka_sync::SyncedTka) {
596        let Some(cache) = self.netmap_cache() else {
597            return;
598        };
599
600        // Scoped so the `watch` borrow is dropped before the awaits below (it is not `Send`).
601        let caching_granted = {
602            let self_node = self.self_node.borrow();
603            self_node
604                .as_ref()
605                .is_some_and(|node| ts_control::netmap_caching_enabled(&node.cap_map))
606        };
607        if !caching_granted {
608            cache.discard_tka_chain().await;
609            return;
610        }
611
612        match crate::tka_sync::encode_chain(&synced.store, synced.oldest) {
613            Some(blob) => cache.store_tka_chain(&blob).await,
614            None => {
615                // The store cannot be walked genesis→head, so there is no chain to persist. Drop any
616                // older one rather than leaving a chain that no longer matches what we enforce.
617                tracing::warn!("TKA: synced chain is not walkable; not persisting it");
618                cache.discard_tka_chain().await;
619            }
620        }
621    }
622
623    /// Remove the persisted AUM chain (the lock was disabled, or control reports no lock). Spawned
624    /// because the call sites are synchronous actor paths and this is best-effort cleanup: the file
625    /// is never *trusted* out of existence — the replay checks the chain against the cached frame's
626    /// own recorded head.
627    fn discard_persisted_tka_chain(&self) {
628        let Some(cache) = self.netmap_cache() else {
629            return;
630        };
631        tokio::spawn(async move { cache.discard_tka_chain().await });
632    }
633
634    /// The netmap cache this node was configured with, or `None` when the embedder configured no
635    /// directory (nothing is cached, so there is nothing to vouch for).
636    fn netmap_cache(&self) -> Option<ts_control::NetmapCache> {
637        self.params
638            .config
639            .netmap_cache_dir
640            .as_ref()
641            .map(ts_control::NetmapCache::new)
642    }
643
644    fn with_self_node<F, R>(&self, f: F) -> impl Future<Output = Option<R>> + use<F, R>
645    where
646        F: FnOnce(&Node) -> R,
647    {
648        let mut sub = self.self_node.subscribe();
649        let mut shutdown = self.params.env.shutdown.clone();
650
651        async move {
652            tokio::select! {
653                _ = shutdown.wait_for(|x| *x) => {
654                    None
655                },
656                node = sub.wait_for(Option::is_some) => {
657                    Some(f(node.ok()?.as_ref()?))
658                },
659            }
660        }
661    }
662}
663
664/// Apply Go's sticky `PopBrowserURL` semantics to the consent-URL `watch` cell.
665///
666/// Control sends `MapResponse.PopBrowserURL` empty on nearly every netmap update, so the cell is
667/// updated ONLY when `incoming` is a non-empty URL that differs from the cell's current value —
668/// Go's `direct.go` guard `u != "" && u != sess.lastPopBrowserURL`. The cell is **never reset to
669/// `None`** by an empty/absent update — the running-node consent URL is sticky for the session.
670/// Updating unconditionally would thrash the cell to `None` on every tick and coalesce the URL away
671/// for a `watch`/bus subscriber.
672///
673/// The dedupe is in-place via [`watch::Sender::send_if_modified`] — the cell's own value is the
674/// "last URL sent" (this sticky path is its only writer), so no separate mirror field is needed and
675/// the watch is woken only on a genuine change (Go's `sess.lastPopBrowserURL` role, for free). This
676/// matches the [`send_if_modified`](watch::Sender::send_if_modified) idiom already used for the
677/// device-state cell in this handler.
678///
679/// Factored out of the netmap-update handler so the (easy-to-regress) sticky logic is unit-testable
680/// against a plain `watch` channel without standing up the actor.
681fn sticky_update_pop_browser_url(
682    cell: &watch::Sender<Option<url::Url>>,
683    incoming: Option<&url::Url>,
684) {
685    if let Some(url) = incoming {
686        cell.send_if_modified(|current| {
687            if current.as_ref() == Some(url) {
688                false
689            } else {
690                *current = Some(url.clone());
691                true
692            }
693        });
694    }
695}
696
697/// Map a mid-session re-auth URL surfaced by the control client onto the device-state cell.
698///
699/// The control client's live map-poll loop publishes an `Option<url::Url>` into a `watch` cell when
700/// a re-register hits `MachineNotAuthorized` (the node key expired/was revoked mid-session — see
701/// [`ts_control::AsyncControlClient::connect`]'s `auth_url_tx`). `ts_control` cannot name
702/// [`DeviceState`] (it must not depend on this crate), so this bridge fn does the translation:
703/// a `Some(url)` sets [`DeviceState::NeedsLogin`]`(url)` so the IPN bus derives `browse_to_url` and
704/// the embedder can prompt the user, exactly like the initial-registration `check_auth` path.
705///
706/// **Only `Some` drives a transition; `None` is ignored here.** The clear back to
707/// [`DeviceState::Running`] is owned by the netmap self-node handler (the next good self-node flips
708/// it — see the `StreamMessage::Next` arm), which is the authoritative "we are up again" signal; an
709/// independent `None`-clear in this bridge could race that and is unnecessary. The
710/// [`send_if_modified`](watch::Sender::send_if_modified) guard fires the watch only on a genuine
711/// state change (it is a no-op when the cell already holds `NeedsLogin(url)` for the same URL), so a
712/// re-auth URL re-surfaced across retries does not thrash the cell — mirroring the device-state
713/// dedupe in the netmap handler.
714///
715/// Factored out so the (regress-prone) map-and-guard is unit-testable against a plain `watch`
716/// channel without standing up the actor (mirrors [`sticky_update_pop_browser_url`]).
717/// **Auto-reauth ownership.** While an automatic re-auth is in flight (the cell holds
718/// [`DeviceState::Reauthenticating`]), this bridge must NOT downgrade it to `NeedsLogin`. An
719/// auto-reauth's rotated re-register surfaces an auth URL through the SAME `auth_url_tx` cell this
720/// bridge watches, but on a headless / auth-key node there is no human to visit it — flipping to
721/// `NeedsLogin` would surface a misleading `browse_to_url` AND, by moving the cell off
722/// `Reauthenticating`, let the next expired self-node re-fire reauth (a second node-key rotation that
723/// loses the original `OldNodeKey` anchor). The auto-reauth path owns the cell until it recovers to
724/// `Running` (the netmap self-node handler) or its circuit breaker trips it to `Expired`; this bridge
725/// stands down for the duration.
726pub(crate) fn bridge_reauth_url_to_state(
727    state_tx: &watch::Sender<crate::DeviceState>,
728    incoming: Option<&url::Url>,
729) {
730    if let Some(url) = incoming {
731        let next = crate::DeviceState::NeedsLogin(url.clone());
732        state_tx.send_if_modified(|current| {
733            // Do not clobber an in-flight automatic re-auth (see the ownership note above): leave
734            // `Reauthenticating` untouched so it can recover to `Running` or trip to `Expired` on its
735            // own terms.
736            if *current == crate::DeviceState::Reauthenticating || *current == next {
737                false
738            } else {
739                *current = next.clone();
740                true
741            }
742        });
743    }
744}
745
746/// What to do when control delivers a self-node whose node-key expiry has passed — the decision
747/// behind the [`StreamMessage::Next`] handler's expiry branch, factored into a pure function so the
748/// full input matrix is unit-testable (mirrors [`bridge_reauth_url_to_state`] being pure).
749#[derive(Debug, Clone, Copy, PartialEq, Eq)]
750pub(crate) enum ExpiryAction {
751    /// The key is not expired — the node is up. (`→ DeviceState::Running`.)
752    Running,
753    /// The key expired and auto-reauth is permitted (auth key retained, reauth enabled, TKA NOT
754    /// enforcing): rotate the node key + re-register (`→ DeviceState::Reauthenticating` +
755    /// `Command::Reauth`).
756    Reauthenticate,
757    /// The key expired and auto-reauth is NOT permitted (no auth key, reauth disabled, or TKA
758    /// enforcing): fall back to today's terminal behavior (`→ DeviceState::Expired`).
759    Expired,
760}
761
762/// Decide the action for an expired-or-not self node (pure; the live handler at
763/// [`StreamMessage::Next`] applies it). Go's `ipnlocal` runs `doLogin` (rotate the node key +
764/// re-register with the stored auth key) when an auth-key node's key expires; this fork does the
765/// same, gated by three safety conditions:
766///
767/// - `key_expired` — control reported the self-node's key expiry is in the past.
768/// - `has_auth_key` — a usable auth key is retained for a non-interactive re-register (without one
769///   there is nothing to re-register with → fall back to `Expired`, today's behavior).
770/// - `reauth_enabled` — the `reauth_on_expiry` config opt-out is on (default true).
771/// - `tka_active` — Tailnet Lock enforcement is currently active. **Hard safety gate:** a node-key
772///   rotation on a locked tailnet would install an UNSIGNED key, locking the node out of locked
773///   peers (the TKA re-sign is a separate follow-up — see `keystate.rs` `rotate_node_key`). So when
774///   the lock is enforcing, never rotate — fall back to `Expired`.
775///
776/// Truth table: not expired → `Running`; expired AND auth-key AND reauth-enabled AND NOT TKA →
777/// `Reauthenticate`; otherwise → `Expired`.
778pub(crate) fn expiry_action(
779    key_expired: bool,
780    has_auth_key: bool,
781    reauth_enabled: bool,
782    tka_active: bool,
783) -> ExpiryAction {
784    if !key_expired {
785        return ExpiryAction::Running;
786    }
787    if has_auth_key && reauth_enabled && !tka_active {
788        ExpiryAction::Reauthenticate
789    } else {
790        ExpiryAction::Expired
791    }
792}
793
794/// The outcome of one step of the bounded reauth sub-state-machine: the device state to publish, the
795/// updated consecutive-attempt counter, and whether to fire the one-shot `Command::Reauth` this step.
796#[derive(Debug, Clone, Copy, PartialEq, Eq)]
797pub(crate) struct ReauthStep {
798    /// The device state to publish for this self-node.
799    pub next: ReauthState,
800    /// The consecutive-failed-reauth counter after this step (the caller stores it back).
801    pub attempts: u32,
802    /// Whether to fire the one-shot `Command::Reauth` (rotate + re-register) this step. Set ONLY on
803    /// the transition INTO reauthenticating, so the node key rotates at most once per episode.
804    pub fire_reauth: bool,
805}
806
807/// The device state a [`ReauthStep`] resolves to — the subset of [`DeviceState`](crate::DeviceState)
808/// the circuit breaker can produce. Kept as its own enum so the breaker stays pure (no dependency on
809/// the URL-carrying `DeviceState` variants) and the truth table is exhaustively testable.
810#[derive(Debug, Clone, Copy, PartialEq, Eq)]
811pub(crate) enum ReauthState {
812    /// The node is up — `→ DeviceState::Running`.
813    Running,
814    /// An automatic re-auth is in flight — `→ DeviceState::Reauthenticating`.
815    Reauthenticating,
816    /// Terminal expiry — `→ DeviceState::Expired` (either the non-reauth path or the breaker tripped).
817    Expired,
818}
819
820/// One step of the bounded reauth sub-state-machine (pure; the [`StreamMessage::Next`] handler stores
821/// the result back into [`ControlRunner::reauth_attempts`] and publishes [`ReauthStep::next`]). This
822/// is the circuit breaker for the design's deferred-question Q1: a one-shot / already-consumed auth
823/// key cannot re-register, so the `Reauthenticate` path must settle rather than loop forever.
824///
825/// Inputs:
826/// - `action` — the [`expiry_action`] verdict for this self-node.
827/// - `already_reauthing` — whether the published state is currently
828///   [`DeviceState::Reauthenticating`](crate::DeviceState::Reauthenticating) (the prior reauth has
829///   not yet recovered the node).
830/// - `attempts` — the current consecutive-failed-reauth counter.
831///
832/// Rules:
833/// - `Running` → reset the counter to `0` (the node recovered) and report `Running`.
834/// - `Reauthenticate` while NOT already reauthing → ENTER reauthenticating: counter `= 1`, fire the
835///   one-shot reauth.
836/// - `Reauthenticate` while ALREADY reauthing → the prior reauth did not recover; COUNT it (counter
837///   `+= 1`) and do NOT re-fire (a second rotation would lose the original `OldNodeKey` anchor). At
838///   [`MAX_REAUTH_ATTEMPTS`] the breaker trips to terminal `Expired`; below the cap, stay reauthing.
839/// - `Expired` → terminal; the counter is irrelevant (this path never armed the reauth machine), so
840///   it is reset to `0`.
841pub(crate) fn reauth_circuit_step(
842    action: ExpiryAction,
843    already_reauthing: bool,
844    attempts: u32,
845) -> ReauthStep {
846    match action {
847        ExpiryAction::Running => ReauthStep {
848            next: ReauthState::Running,
849            attempts: 0,
850            fire_reauth: false,
851        },
852        ExpiryAction::Reauthenticate if !already_reauthing => ReauthStep {
853            next: ReauthState::Reauthenticating,
854            attempts: 1,
855            fire_reauth: true,
856        },
857        ExpiryAction::Reauthenticate => {
858            let attempts = attempts.saturating_add(1);
859            if attempts >= MAX_REAUTH_ATTEMPTS {
860                ReauthStep {
861                    next: ReauthState::Expired,
862                    attempts,
863                    fire_reauth: false,
864                }
865            } else {
866                ReauthStep {
867                    next: ReauthState::Reauthenticating,
868                    attempts,
869                    fire_reauth: false,
870                }
871            }
872        }
873        ExpiryAction::Expired => ReauthStep {
874            next: ReauthState::Expired,
875            attempts: 0,
876            fire_reauth: false,
877        },
878    }
879}
880
881/// The classification of SELF against the active network lock — the observability analog of Go
882/// `tkaFilterNetmapLocked`'s self check (which raises a `LockedOut` health warning).
883#[derive(Debug, Clone, PartialEq, Eq)]
884enum SelfLockVerdict {
885    /// Self carries no key-signature at all (empty). The common "not signed yet" case: the node
886    /// simply has not been signed for this lock — not locked out, just unsigned.
887    Unsigned,
888    /// Self's key-signature is authorized by the active lock; nothing to warn about.
889    Authorized,
890    /// Self has a key-signature but the lock does NOT authorize it (the message is the verify
891    /// error). The operator-facing `LockedOut` condition: locked peers will reject this node.
892    LockedOut(String),
893}
894
895/// Classify a node key + its key-signature against `authority` (pure: verify-and-classify, no
896/// logging, no I/O). Takes only the two fields it needs — not the whole `Node` — so the decision is
897/// unit-testable without constructing a full `Node` or standing up the actor.
898fn self_lock_verdict(
899    node_key: &ts_keys::NodePublicKey,
900    key_signature: &[u8],
901    authority: &ts_tka::Authority,
902) -> SelfLockVerdict {
903    // Mirror the peer path (`peer_tracker` `tka_snapshot_admits`): treat an empty signature as
904    // "unsigned" rather than the `LockedOut` bucket Go's `NodeKeyAuthorized` would put a nil sig in
905    // (it errors at decode). This is a deliberate, narrow divergence from a literal Go port: it
906    // avoids `warn`-spam on a lock that simply has not signed this node yet, and keeps self and peer
907    // classification consistent.
908    if key_signature.is_empty() {
909        return SelfLockVerdict::Unsigned;
910    }
911    match authority.node_key_authorized(&node_key.to_bytes(), key_signature) {
912        Ok(()) => SelfLockVerdict::Authorized,
913        Err(e) => SelfLockVerdict::LockedOut(e.to_string()),
914    }
915}
916
917/// Emit the self-locked-out observability signal (Go `tkaFilterNetmapLocked`'s self check → a
918/// `LockedOut` health warning): classify SELF against the freshly-synced `authority` and log.
919///
920/// This is **observability, not enforcement** — self never enters the peer db, so the lock can never
921/// filter our own node out of the netmap. But a self the lock does not authorize means this node's
922/// key-signature is absent or invalid for the active lock, so it cannot prove itself to locked peers
923/// (they will drop it); surfacing that lets an operator notice and re-sign. A never-signed node
924/// (empty signature) logs at `info`, distinct from a present-but-invalid signature (`warn`), so the
925/// common unsigned case does not spam a warning. This fork has no health subsystem, so the operator
926/// signal is a `tracing` event (its observability channel).
927fn log_self_lockout(self_node: &Node, authority: &ts_tka::Authority) {
928    match self_lock_verdict(&self_node.node_key, &self_node.key_signature, authority) {
929        SelfLockVerdict::Unsigned => tracing::info!(
930            "TKA: this node has no key-signature for the active lock; it cannot prove itself to \
931             locked peers until control signs it (not locked out, just unsigned)"
932        ),
933        SelfLockVerdict::Authorized => {
934            tracing::debug!("TKA: self node-key is authorized by the active lock")
935        }
936        SelfLockVerdict::LockedOut(error) => tracing::warn!(
937            %error,
938            "TKA self locked out: this node's key-signature is not authorized by the active \
939             network lock; locked peers will reject it until control re-signs this node \
940             (Go LockedOut)"
941        ),
942    }
943}
944
945// The `#[kameo::messages]` macro generates message structs whose fields mirror the method params;
946// those generated fields carry no doc and can't take attributes, so wrap in a module where
947// missing-docs is allowed (same pattern as PeerTracker's `msg_impl`). The generated message structs
948// are re-exported so callers keep referencing them at `control_runner::<Name>`.
949pub use msg_impl::*;
950
951#[allow(missing_docs)]
952mod msg_impl {
953    use kameo::{message::Context, reply::DelegatedReply};
954
955    use super::*;
956
957    #[kameo::messages]
958    impl ControlRunner {
959        /// Fetch the IPv4 address for this tailscale device.
960        #[message(ctx)]
961        pub fn ipv4(
962            &self,
963            ctx: &mut Context<Self, DelegatedReply<Option<Ipv4Addr>>>,
964        ) -> DelegatedReply<Option<Ipv4Addr>> {
965            let (deleg, replier) = ctx.reply_sender();
966
967            if let Some(replier) = replier {
968                let fut = self.with_self_node(|node| node.tailnet_address.ipv4.addr());
969
970                tokio::spawn(async move {
971                    let ip = fut.await;
972                    replier.send(ip);
973                });
974            }
975
976            deleg
977        }
978
979        /// Fetch the IPv6 address for this tailscale device.
980        #[message(ctx)]
981        pub fn ipv6(
982            &self,
983            ctx: &mut Context<Self, DelegatedReply<Option<Ipv6Addr>>>,
984        ) -> DelegatedReply<Option<Ipv6Addr>> {
985            let (deleg, replier) = ctx.reply_sender();
986
987            if let Some(replier) = replier {
988                let fut = self.with_self_node(|node| node.tailnet_address.ipv6.addr());
989
990                tokio::spawn(async move {
991                    let ip = fut.await;
992                    replier.send(ip);
993                });
994            }
995
996            deleg
997        }
998
999        /// Fetch the self node for this tailscale device.
1000        #[message(ctx)]
1001        pub fn self_node(
1002            &self,
1003            ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
1004        ) -> DelegatedReply<Option<Node>> {
1005            let (deleg, replier) = ctx.reply_sender();
1006
1007            if let Some(replier) = replier {
1008                let node = self.with_self_node(|node| node.clone());
1009
1010                tokio::spawn(async move {
1011                    let node = node.await;
1012                    replier.send(node)
1013                });
1014            }
1015
1016            deleg
1017        }
1018
1019        /// Fetch the current Tailscale SSH policy, if control has pushed one.
1020        ///
1021        /// Returns `None` when control has not sent an SSH policy (the SSH server treats this as
1022        /// deny-all — fail-closed). Unlike `self_node` this does not block waiting
1023        /// for a value: an absent policy is a legitimate, immediate answer.
1024        #[message]
1025        pub fn current_ssh_policy(&self) -> Option<SshPolicy> {
1026            self.ssh_policy.borrow().clone()
1027        }
1028
1029        /// Fetch the current Tailnet Lock status, if control has pushed one.
1030        ///
1031        /// Returns `None` when control has sent no `TKAInfo` (tailnet lock not in use / no change seen).
1032        #[message]
1033        pub fn current_tka_status(&self) -> Option<TkaStatus> {
1034            self.tka.borrow().clone()
1035        }
1036
1037        /// Read up to `limit` entries of the Tailnet-Lock update-chain log, **head-first** (newest →
1038        /// oldest), from the locally-synced AUM chain (Go `NetworkLockLog`).
1039        ///
1040        /// A **pure local read** — no crypto, no mutation, no control round-trip: it walks the
1041        /// already-verified `SyncedTka` store this actor owns. Returns an empty `Vec` when no lock is
1042        /// synced (Go's `b.tka == nil`). Synchronous (no spawn), like `current_tka_status` — the
1043        /// chain is in memory.
1044        #[message]
1045        pub fn tka_log(&self, limit: usize) -> Vec<crate::tka_sync::TkaLogEntry> {
1046            let Some(synced) = self.tka_synced.as_ref() else {
1047                return Vec::new();
1048            };
1049            crate::tka_sync::tka_log_entries(&synced.store, synced.oldest, limit)
1050        }
1051
1052        /// Sign `node_key` directly with this node's network-lock key and submit the signature to
1053        /// control (Go `tka.sign` for the Direct case → `tkaSubmitSignature`).
1054        ///
1055        /// Builds a `Direct` [`NodeKeySignature`](ts_tka::NodeKeySignature) via
1056        /// [`sign_direct`](ts_tka::NodeKeySignature::sign_direct) over this node's inner ed25519
1057        /// network-lock signing key, serializes it (raw CBOR), and POSTs it to `/machine/tka/sign`.
1058        /// Mirrors `set_dns`/`get_certificate`: clones the control config + node keys into a spawned
1059        /// task (delegated reply, so the round-trip doesn't block the mailbox) over a fresh Noise
1060        /// channel.
1061        ///
1062        /// **Posture: this only *submits* a signature to control — it does NOT mutate the local
1063        /// [`Authority`](ts_tka::Authority).** The local trusted-key state advances solely through the
1064        /// existing verified-sync path (`sync_tka` → `VerifiedAumChain::verify`); a `tka_sign` success
1065        /// is acknowledged to the caller, and the resulting AUM is picked up on the next netmap-driven
1066        /// sync. Verify-and-log is unchanged.
1067        #[message(ctx)]
1068        pub fn tka_sign(
1069            &self,
1070            ctx: &mut Context<Self, DelegatedReply<Result<(), TkaSyncError>>>,
1071            node_key: [u8; 32],
1072        ) -> DelegatedReply<Result<(), TkaSyncError>> {
1073            let (deleg, replier) = ctx.reply_sender();
1074
1075            if let Some(replier) = replier {
1076                let config = self.params.config.clone();
1077                let keys = self.params.env.keys.clone();
1078                tokio::spawn(async move {
1079                    // Sign the node key with our network-lock key, then submit the raw-CBOR NKS.
1080                    let nks = ts_tka::NodeKeySignature::sign_direct(
1081                        &node_key,
1082                        &keys.network_lock_keys.private.signing_key(),
1083                    );
1084                    let req = ts_control::TkaSubmitSignatureRequest {
1085                        // node_key + version are stamped by the RPC client from `keys`.
1086                        version: Default::default(),
1087                        node_key: keys.node_keys.public,
1088                        signature: nks.serialize(),
1089                    };
1090                    let result = tka_submit_signature(
1091                        &config.server_url,
1092                        &keys,
1093                        req,
1094                        config.allow_http_key_fetch,
1095                    )
1096                    .await
1097                    .map(|_response| ());
1098                    replier.send(result);
1099                });
1100            }
1101
1102            deleg
1103        }
1104
1105        /// Disable Tailnet Lock by presenting the disablement secret to control (Go
1106        /// `tka.disable` → `/machine/tka/disable`).
1107        ///
1108        /// Targets the **current** authority head (read from the cached [`TkaStatus`]); the caller
1109        /// supplies the `disablement_secret` out of band (it is the operator-held capability that
1110        /// authorizes turning the lock off). Mirrors `tka_sign`: clones config + keys into a spawned
1111        /// task (delegated reply). Returns [`TkaSyncError::Unsupported`] when there is no known TKA
1112        /// head (lock not in use / control hasn't pushed a status), since there is nothing to disable.
1113        ///
1114        /// **Submit-only, like `tka_sign`:** this POSTs the disablement to control and does NOT mutate
1115        /// the local [`Authority`](ts_tka::Authority). Control acts on the disablement; this node
1116        /// observes the result through the existing verified-sync path. Verify-and-log unchanged.
1117        #[message(ctx)]
1118        pub fn tka_disable(
1119            &self,
1120            ctx: &mut Context<Self, DelegatedReply<Result<(), TkaSyncError>>>,
1121            disablement_secret: Vec<u8>,
1122        ) -> DelegatedReply<Result<(), TkaSyncError>> {
1123            let (deleg, replier) = ctx.reply_sender();
1124
1125            if let Some(replier) = replier {
1126                // Read the current head from the cached status BEFORE the spawn (can't borrow &self
1127                // across the await). No head ⇒ no lock to disable ⇒ Unsupported.
1128                let head = self.tka.borrow().as_ref().map(|s| s.head.clone());
1129                let config = self.params.config.clone();
1130                let keys = self.params.env.keys.clone();
1131                tokio::spawn(async move {
1132                    let result = match head {
1133                        Some(head) => {
1134                            let req = ts_control::TkaDisableRequest {
1135                                // node_key + version are stamped by the RPC client from `keys`.
1136                                version: Default::default(),
1137                                node_key: keys.node_keys.public,
1138                                head,
1139                                disablement_secret,
1140                            };
1141                            tka_disable(&config.server_url, &keys, req, config.allow_http_key_fetch)
1142                                .await
1143                                .map(|_response| ())
1144                        }
1145                        None => Err(TkaSyncError::Unsupported),
1146                    };
1147                    replier.send(result);
1148                });
1149            }
1150
1151            deleg
1152        }
1153
1154        /// Initialize Tailnet Lock with this node as the sole initial trusted key, gated by
1155        /// `disablement_secret` (Go `LocalClient.NetworkLockInit` — the "lock yourself in" case).
1156        ///
1157        /// Builds + signs a genesis Checkpoint AUM whose only trusted key is this node's network-lock
1158        /// public key (votes 1) and whose single DisablementValue is `disablement_value(secret)`, then
1159        /// drives the two-phase init: `tka/init/begin` (submit the genesis) → if control needs no
1160        /// further node signatures (`NeedSignatures` empty, the case when this node is the only key) →
1161        /// `tka/init/finish` carrying the raw `disablement_secret` as `SupportDisablement`. Mirrors
1162        /// `tka_sign`/`tka_disable`: cloned config + keys into a spawned task (delegated reply).
1163        ///
1164        /// If control returns a non-empty `NeedSignatures` (other nodes must be re-signed under the new
1165        /// lock — a multi-node tailnet), this returns [`TkaSyncError::Unsupported`]: re-signing each
1166        /// listed node (incl. the Rotation-key case) is a larger flow deferred to a fuller
1167        /// `tka_init(keys, secrets)` — the single-node lock-init is the shipped subset.
1168        ///
1169        /// **Submit-only**, like `tka_sign`/`tka_disable`: this creates the lock at control and does
1170        /// NOT seed the local [`Authority`](ts_tka::Authority) — the node picks up the new lock through
1171        /// the existing verified netmap-sync (control pushes a `TKAInfo`, `maybe_sync_tka` bootstraps
1172        /// the genesis through `VerifiedAumChain::verify`). Verify-and-log posture unchanged.
1173        #[message(ctx)]
1174        pub fn tka_init(
1175            &self,
1176            ctx: &mut Context<Self, DelegatedReply<Result<(), TkaSyncError>>>,
1177            disablement_secret: Vec<u8>,
1178        ) -> DelegatedReply<Result<(), TkaSyncError>> {
1179            let (deleg, replier) = ctx.reply_sender();
1180
1181            if let Some(replier) = replier {
1182                let config = self.params.config.clone();
1183                let keys = self.params.env.keys.clone();
1184                tokio::spawn(async move {
1185                    let result = tka_init_run(&config, &keys, disablement_secret).await;
1186                    replier.send(result);
1187                });
1188            }
1189
1190            deleg
1191        }
1192
1193        /// The cert-eligible DNS names from control's netmap DNS config (Go `nm.DNS.CertDomains`).
1194        ///
1195        /// Returns an empty `Vec` when control has sent no DNS config, or one carrying no cert
1196        /// domains (an empty list is a legitimate, immediate answer — like `current_ssh_policy`, this
1197        /// does not block waiting for a value).
1198        #[message]
1199        pub fn cert_domains(&self) -> Vec<String> {
1200            self.cert_domains.borrow().clone()
1201        }
1202
1203        /// The full DNS config from control's netmap (Go `netmap.NetworkMap.DNS`), or `None` when
1204        /// control has sent no DNS config yet. An immediate answer (does not block); the facade
1205        /// surfaces this for `Device::dns_config` (the daemon's `tnet dns status`).
1206        #[message]
1207        pub fn dns_config(&self) -> Option<ts_control::DnsConfig> {
1208            self.dns_config.borrow().clone()
1209        }
1210
1211        /// The interactive-login / consent URL control last asked this node to open
1212        /// (`MapResponse.PopBrowserURL`), or `None` when control has sent none. An immediate answer
1213        /// (does not block); the facade surfaces this for `Device::pop_browser_url`.
1214        #[message]
1215        pub fn pop_browser_url(&self) -> Option<url::Url> {
1216            self.pop_browser_url.borrow().clone()
1217        }
1218
1219        /// Subscribe to the interactive-login / consent URL cell (`MapResponse.PopBrowserURL`).
1220        ///
1221        /// Returns a [`watch::Receiver`] whose value is the latest running-node consent URL, used by
1222        /// [`Runtime::watch_ipn_bus`](crate::Runtime::watch_ipn_bus) to surface `browse_to_url`
1223        /// events mid-session. The cell is sticky (updated only on a new non-empty URL, never reset
1224        /// to `None` by an empty update — see the field docs), so a subscriber is not thrashed and a
1225        /// late subscriber sees the current URL. The initial value is `None` until control sends one.
1226        #[message(derive(Clone))]
1227        pub fn watch_browser_url(&self) -> watch::Receiver<Option<url::Url>> {
1228            self.pop_browser_url.subscribe()
1229        }
1230
1231        /// The latest network-conditions report (preferred DERP region + per-region latencies). An
1232        /// immediate answer (does not block); empty before the first DERP-latency measurement. The
1233        /// facade surfaces this for `Device::netcheck` (the daemon's `tnet netcheck`).
1234        #[message]
1235        pub fn netcheck(&self) -> crate::status::NetcheckReport {
1236            self.netcheck.borrow().clone()
1237        }
1238
1239        /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
1240        ///
1241        /// Opens a fresh Noise channel and POSTs `/machine/id-token`; returns the signed JWT or an
1242        /// [`IdTokenError`]. Runs on a spawned task (delegated reply) so the actor mailbox isn't blocked
1243        /// for the round-trip.
1244        #[message(ctx)]
1245        pub fn fetch_id_token(
1246            &self,
1247            ctx: &mut Context<Self, DelegatedReply<Result<String, IdTokenError>>>,
1248            audience: String,
1249        ) -> DelegatedReply<Result<String, IdTokenError>> {
1250            let (deleg, replier) = ctx.reply_sender();
1251
1252            if let Some(replier) = replier {
1253                let config = self.params.config.clone();
1254                let keys = self.params.env.keys.clone();
1255                tokio::spawn(async move {
1256                    let result = ts_control::fetch_id_token(&config, &keys, &audience).await;
1257                    replier.send(result);
1258                });
1259            }
1260
1261            deleg
1262        }
1263
1264        /// Log this node out of the tailnet: deregister it by expiring its current node key.
1265        ///
1266        /// Mirrors `fetch_id_token`: clones the control config + node keys
1267        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox) and
1268        /// re-POSTs `/machine/register` with a past expiry over a fresh Noise channel. This is a
1269        /// control-plane state change only — it does NOT stop this actor or tear down the datapath
1270        /// (the caller follows up with the normal runtime shutdown), and it does not touch the
1271        /// on-disk node key, so re-registering with the same key is the re-login path.
1272        #[message(ctx)]
1273        pub fn logout(
1274            &self,
1275            ctx: &mut Context<Self, DelegatedReply<Result<(), LogoutError>>>,
1276        ) -> DelegatedReply<Result<(), LogoutError>> {
1277            let (deleg, replier) = ctx.reply_sender();
1278
1279            if let Some(replier) = replier {
1280                let config = self.params.config.clone();
1281                let keys = self.params.env.keys.clone();
1282                tokio::spawn(async move {
1283                    let result = ts_control::logout(&config, &keys).await;
1284                    replier.send(result);
1285                });
1286            }
1287
1288            deleg
1289        }
1290
1291        /// Publish a DNS record for this node via control's `/machine/set-dns` (Go
1292        /// `LocalClient.SetDNS`).
1293        ///
1294        /// Mirrors `fetch_id_token`: clones the control config + node keys
1295        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox) and
1296        /// POSTs the record over a fresh Noise channel. Go's `SetDNS` is `TXT`-only (its sole use is
1297        /// the ACME DNS-01 `_acme-challenge` record); the record type is fixed to `"TXT"` here to
1298        /// match, so the surfaced API takes only `name` + `value`.
1299        #[message(ctx)]
1300        pub fn set_dns(
1301            &self,
1302            ctx: &mut Context<Self, DelegatedReply<Result<(), SetDnsError>>>,
1303            name: String,
1304            value: String,
1305        ) -> DelegatedReply<Result<(), SetDnsError>> {
1306            let (deleg, replier) = ctx.reply_sender();
1307
1308            if let Some(replier) = replier {
1309                let config = self.params.config.clone();
1310                let keys = self.params.env.keys.clone();
1311                tokio::spawn(async move {
1312                    let result = ts_control::set_dns(&config, &keys, &name, "TXT", &value).await;
1313                    replier.send(result);
1314                });
1315            }
1316
1317            deleg
1318        }
1319    }
1320
1321    /// The reply type of the [`get_cert_pair`](ControlRunner::get_cert_pair) message: the issued
1322    /// `(cert_chain_pem, key_pem)` PEM pair (the `tnet cert` surface) or a [`ts_control::CertError`].
1323    /// Aliased so the message's `Context` type stays under clippy's `type_complexity` bar (the
1324    /// nested `Result<(String, String), _>` trips it inline).
1325    #[cfg(feature = "acme")]
1326    pub type CertPairReply = Result<(String, String), ts_control::CertError>;
1327
1328    // The `acme`-gated cert-issuance message lives in its own `#[kameo::messages]` impl block so the
1329    // proc-macro never sees it in a non-`acme` build (a `#[cfg]` *inside* a single messages-impl
1330    // block is not honored by the macro's generated dispatch — it would emit a `GetCertificate`
1331    // handler calling a `get_certificate` method that the same `#[cfg]` strips). A separate gated
1332    // block keeps the default build clean.
1333    #[cfg(feature = "acme")]
1334    #[kameo::messages]
1335    impl ControlRunner {
1336        /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` via the
1337        /// client-side ACME DNS-01 engine (`acme` feature).
1338        ///
1339        /// Mirrors `fetch_id_token`: clones the control config + node keys
1340        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox), loads
1341        /// or generates the ACME account key, and runs issuance against Let's Encrypt production,
1342        /// publishing the DNS-01 challenge TXT through the node's `POST /machine/set-dns` RPC.
1343        ///
1344        /// The account key is loaded from [`ts_keys::NodeState::acme_account_key`] (PKCS#8 DER) when
1345        /// present, so the same ACME account persists across renewals; otherwise an ephemeral key is
1346        /// generated for this call only (a fresh ACME account each issuance — acceptable for v1; LE
1347        /// allows it). Persisting a generated key back into the key file is the embedder's job (no
1348        /// write-back path here). SaaS-only: against a self-hosted control plane the set-dns
1349        /// publish 501s.
1350        #[message(ctx)]
1351        pub fn get_certificate(
1352            &self,
1353            ctx: &mut Context<
1354                Self,
1355                DelegatedReply<Result<ts_control::tls::CertifiedKey, ts_control::CertError>>,
1356            >,
1357            name: String,
1358        ) -> DelegatedReply<Result<ts_control::tls::CertifiedKey, ts_control::CertError>> {
1359            let (deleg, replier) = ctx.reply_sender();
1360
1361            if let Some(replier) = replier {
1362                let config = self.params.config.clone();
1363                let keys = self.params.env.keys.clone();
1364                tokio::spawn(async move {
1365                    let result = issue_certificate(&config, &keys, &name).await;
1366                    replier.send(result);
1367                });
1368            }
1369
1370            deleg
1371        }
1372
1373        /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` and return the
1374        /// **PEM pair** — `(cert_chain_pem, key_pem)` — for writing the on-disk `.crt` + `.key`
1375        /// (the daemon's `tnet cert`, Go's `LocalClient.CertPair`). `acme` feature.
1376        ///
1377        /// Identical issuance to [`get_certificate`](Self::get_certificate) (same client-side ACME
1378        /// DNS-01 flow, same set-dns publish, same account-key handling), only the *shape* of the
1379        /// result differs: this surfaces the raw chain + leaf-key PEMs instead of the opaque
1380        /// [`CertifiedKey`](ts_control::tls::CertifiedKey). The leaf **private key** PEM is the
1381        /// second tuple element and is NEVER logged — the spawned task sends it straight back to the
1382        /// replier. SaaS-only: against a self-hosted control plane the set-dns publish 501s.
1383        #[message(ctx)]
1384        pub fn get_cert_pair(
1385            &self,
1386            ctx: &mut Context<Self, DelegatedReply<CertPairReply>>,
1387            name: String,
1388        ) -> DelegatedReply<CertPairReply> {
1389            let (deleg, replier) = ctx.reply_sender();
1390
1391            if let Some(replier) = replier {
1392                let config = self.params.config.clone();
1393                let keys = self.params.env.keys.clone();
1394                tokio::spawn(async move {
1395                    let result = issue_cert_pair(&config, &keys, &name).await;
1396                    replier.send(result);
1397                });
1398            }
1399
1400            deleg
1401        }
1402    }
1403}
1404
1405/// The `tka_init` body (the genesis-build + two-phase init/begin→init/finish choreography),
1406/// factored out of the actor handler so it runs in the spawned task. See [`ControlRunner::tka_init`].
1407///
1408/// "Lock yourself in": the genesis trusts only this node's network-lock key (votes 1) and stores one
1409/// DisablementValue = `disablement_value(secret)`. On a non-empty `NeedSignatures` (multi-node
1410/// tailnet needing re-signs) it returns [`TkaSyncError::Unsupported`] — the single-node subset.
1411async fn tka_init_run(
1412    config: &ts_control::Config,
1413    keys: &ts_keys::NodeState,
1414    disablement_secret: Vec<u8>,
1415) -> Result<(), TkaSyncError> {
1416    // Build the genesis: this node's NL public key as the sole trusted key, one disablement value.
1417    let nl_public = keys.network_lock_keys.public.to_bytes().to_vec();
1418    let genesis_key = ts_tka::AumKey {
1419        kind: ts_tka::KeyKind::Ed25519,
1420        votes: 1,
1421        public: nl_public,
1422        meta: Vec::new(),
1423    };
1424    let dvalue = ts_tka::disablement_value(&disablement_secret).to_vec();
1425    let mut genesis = ts_tka::Aum::new_genesis_checkpoint(vec![genesis_key], vec![dvalue])
1426        // A malformed genesis is a local construction bug, not a transient RPC failure — surface it as a
1427        // coarse internal error rather than NetworkError (which would invite a pointless retry).
1428        .map_err(|_| TkaSyncError::Internal(ts_control::TkaSyncInternalErrorKind::SerDe))?;
1429    genesis.sign(&keys.network_lock_keys.private.signing_key());
1430
1431    // Phase 1: submit the genesis. node_key + version are stamped by the RPC client from `keys`.
1432    let begin_req = ts_control::TkaInitBeginRequest {
1433        version: Default::default(),
1434        node_key: keys.node_keys.public,
1435        genesis_aum: genesis.serialize(),
1436    };
1437    let begin_resp = tka_init_begin(
1438        &config.server_url,
1439        keys,
1440        begin_req,
1441        config.allow_http_key_fetch,
1442    )
1443    .await?;
1444
1445    // Single-node case only: control must need no further node signatures. A non-empty
1446    // NeedSignatures means other nodes must be re-signed under the new lock — deferred.
1447    if !begin_resp.need_signatures.is_empty() {
1448        tracing::warn!(
1449            need = begin_resp.need_signatures.len(),
1450            "tka_init: control requires re-signing other nodes; the multi-node init is not yet \
1451             implemented (single-node lock-init only)"
1452        );
1453        return Err(TkaSyncError::Unsupported);
1454    }
1455
1456    // Phase 2: finish, carrying the raw disablement secret as SupportDisablement (Go sends the raw
1457    // secret here; only the genesis stores its Argon2i hash).
1458    let finish_req = ts_control::TkaInitFinishRequest {
1459        version: Default::default(),
1460        node_key: keys.node_keys.public,
1461        signatures: std::collections::BTreeMap::new(),
1462        support_disablement: disablement_secret,
1463    };
1464    tka_init_finish(
1465        &config.server_url,
1466        keys,
1467        finish_req,
1468        config.allow_http_key_fetch,
1469    )
1470    .await
1471    .map(|_response| ())
1472}
1473
1474/// Load or generate the ACME account key, then issue a cert for `name` via set-dns DNS-01,
1475/// returning just the ready-to-serve [`CertifiedKey`](ts_control::tls::CertifiedKey) (the
1476/// `get_certificate` / `ListenTLS` path).
1477///
1478/// Thin wrapper over [`issue_cert_pair`] that drops the PEMs — one issuance, this caller just
1479/// doesn't need the on-disk pair. See [`issue_cert_pair`] for the account-key handling.
1480#[cfg(feature = "acme")]
1481async fn issue_certificate(
1482    config: &ts_control::Config,
1483    keys: &ts_keys::NodeState,
1484    name: &str,
1485) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
1486    issue_cert_pair_inner(config, keys, name)
1487        .await
1488        .map(|issued| issued.certified)
1489}
1490
1491/// Load or generate the ACME account key, then issue a cert for `name` via set-dns DNS-01,
1492/// returning the **PEM pair** `(cert_chain_pem, key_pem)` for the daemon's on-disk `.crt`/`.key`
1493/// (`tnet cert`, Go `LocalClient.CertPair`).
1494///
1495/// Same single issuance as [`issue_certificate`]; only the result shape differs. The leaf
1496/// **private key** PEM is the second element and is NEVER logged here.
1497#[cfg(feature = "acme")]
1498async fn issue_cert_pair(
1499    config: &ts_control::Config,
1500    keys: &ts_keys::NodeState,
1501    name: &str,
1502) -> Result<(String, String), ts_control::CertError> {
1503    issue_cert_pair_inner(config, keys, name)
1504        .await
1505        .map(|issued| (issued.cert_chain_pem, issued.key_pem))
1506}
1507
1508/// Shared issuance core for [`issue_certificate`] and [`issue_cert_pair`]: load (or generate) the
1509/// ACME account key, target Let's Encrypt production, and run one DNS-01 issuance, returning the
1510/// full [`IssuedCert`](ts_control::acme::IssuedCert) so each caller projects out what it needs (one
1511/// ACME order, two consumers).
1512///
1513/// Reuses the persisted [`ts_keys::NodeState::acme_account_key`] (PKCS#8 DER) when present so the
1514/// same Let's Encrypt account survives renewals; otherwise generates an ephemeral per-call key
1515/// (logged at debug — a new ACME account each issuance, with no write-back). Always targets Let's
1516/// Encrypt production ([`ts_control::acme::LETS_ENCRYPT_PRODUCTION_DIRECTORY`]). Never logs the leaf
1517/// private key.
1518#[cfg(feature = "acme")]
1519async fn issue_cert_pair_inner(
1520    config: &ts_control::Config,
1521    keys: &ts_keys::NodeState,
1522    name: &str,
1523) -> Result<ts_control::acme::IssuedCert, ts_control::CertError> {
1524    let account_key = match keys.acme_account_key.as_deref() {
1525        Some(der) => ts_control::acme::AcmeAccountKey::from_pkcs8(der)?,
1526        None => {
1527            tracing::debug!(
1528                "no persisted ACME account key in key state; generating an ephemeral per-call key \
1529                 (a new ACME account this issuance — not persisted back)"
1530            );
1531            ts_control::acme::AcmeAccountKey::generate()?.0
1532        }
1533    };
1534    let directory = ts_control::acme::LETS_ENCRYPT_PRODUCTION_DIRECTORY
1535        .parse()
1536        .map_err(|e| {
1537            ts_control::CertError::Acme(format!("parsing Let's Encrypt directory URL: {e}"))
1538        })?;
1539    ts_control::issue_cert_pair_via_setdns(config, keys, name, &account_key, &directory).await
1540}
1541
1542/// Publish the cached netmap, if this node has one, onto the netmap bus.
1543///
1544/// The cold-start half of the netmap cache (Go `nodecap.CacheNetworkMaps`). Reads
1545/// [`Config::netmap_cache_dir`](ts_control::Config::netmap_cache_dir) — `None` means the embedder
1546/// configured no storage, so there is nothing to replay — and decodes whatever is there with the
1547/// same decoder the live map poll uses.
1548///
1549/// The read is deliberately **not** gated on the node attributes. Nothing is ever written without
1550/// the grant, so the presence of a cache is itself the record that control asked for one (Go makes
1551/// the same argument: at this point in start-up the client has not spoken to control yet, so the
1552/// grant is not knowable). If the grant has since been withdrawn, the first netmap of this session
1553/// says so and the cache is discarded then.
1554///
1555/// **Peers cached under Tailnet Lock are filtered, not withheld.** Go replays its cached map through
1556/// `tkaFilterNetmapLocked`, which it can do at cold start because its TKA authority is persisted on
1557/// disk; the peers that hold a valid signature survive and are dialed. This port persists the same
1558/// authority next to the cached netmap (see [`load_cached_netmap`]) and runs the same filter over the
1559/// cached peers. With no persisted authority to run it with — a cache written before this node ever
1560/// completed a TKA sync — the peers are withheld and control's first netmap brings them back moments
1561/// later, behind a synced authority.
1562///
1563/// The bus has no replay, so this reaches only subscribers already registered. Every netmap
1564/// subscriber is spawned by `Runtime::spawn` before the control runner and registers from its own
1565/// `on_start` with no I/O in the way, while this path awaits a file read first — so in practice the
1566/// subscribers are there. A subscriber that is not simply misses the head start and is brought
1567/// current by control's first netmap, which is exactly the behaviour of a node with no cache.
1568async fn replay_cached_netmap(params: &Params) {
1569    let Some(dir) = params.config.netmap_cache_dir.as_ref() else {
1570        return;
1571    };
1572
1573    let Some(update) = load_cached_netmap(&ts_control::NetmapCache::new(dir)).await else {
1574        return;
1575    };
1576
1577    let peers = match update.peer_update.as_ref() {
1578        Some(ts_control::PeerUpdate::Full(peers)) => peers.len(),
1579        _ => 0,
1580    };
1581    tracing::info!(peers, "replaying cached netmap on cold start");
1582
1583    if let Err(e) = params.env.publish(Arc::new(update)).await {
1584        tracing::warn!(error = %e, "publishing the cached netmap");
1585    }
1586}
1587
1588/// Read the cached netmap, vouching for its peers with the Tailnet-Lock authority persisted beside
1589/// it — the whole of the cold-start decision, with no actor state in it so it can be tested directly.
1590///
1591/// A netmap cached while the lock was **off** replays whole; there is nothing to enforce (Go's
1592/// `tkaFilterNetmapLocked` returns early on `b.tka == nil`). A netmap cached while the lock was
1593/// **on** replays exactly the peers
1594/// [`PeerTracker::tka_keep_verdicts`](crate::peer_tracker::PeerTracker::tka_keep_verdicts) admits —
1595/// the same pass the live netmap path runs, so a peer that is dialed from the cache is one the
1596/// authority authorized, and an unsigned peer, a peer whose signature fails, or a peer a newer
1597/// rotation obsoletes is dropped.
1598///
1599/// Three things make the persisted authority safe to enforce with:
1600///
1601/// * it is re-verified from genesis on load ([`crate::tka_sync::authority_from_encoded_chain`]), so a
1602///   blob that is not a signed chain yields no authority;
1603/// * it is read back out of the same directory the netmap is, vetted as private to this user, so a
1604///   local attacker cannot choose which chain we start from any more than they can choose the netmap;
1605/// * its head must equal the head the **cached frame** recorded (`MapResponse.TKAInfo.Head`) — see
1606///   [`vouch_cached_peers`]. Go does not need that check because it has no second file to reconcile,
1607///   only the chonk.
1608pub(crate) async fn load_cached_netmap(cache: &ts_control::NetmapCache) -> Option<StateUpdate> {
1609    let authority = match cache.load_tka_chain().await {
1610        None => None,
1611        Some(blob) => match crate::tka_sync::authority_from_encoded_chain(&blob) {
1612            Ok(authority) => Some(authority),
1613            Err(e) => {
1614                tracing::warn!(
1615                    error = %e,
1616                    "persisted tailnet-lock chain did not verify; replaying the cached netmap \
1617                     without its peers"
1618                );
1619                None
1620            }
1621        },
1622    };
1623
1624    cache
1625        .load_state_update_vouched(|tka, peers| vouch_cached_peers(authority.as_ref(), tka, peers))
1626        .await
1627}
1628
1629/// The peers of a netmap cached under an **active** Tailnet Lock that may be replayed on this cold
1630/// start: those the persisted `authority` authorizes, by exactly the pass a live netmap's peers go
1631/// through (Go's `tkaFilterNetmapLocked`, via
1632/// [`PeerTracker::tka_keep_verdicts`](crate::peer_tracker::PeerTracker::tka_keep_verdicts) — the
1633/// per-peer signature verdict plus the cross-peer rotation filter).
1634///
1635/// Nothing is replayed unless the authority can be held to the netmap:
1636///
1637/// * **no persisted authority** (this node has never completed a TKA sync, or the chain did not
1638///   verify) ⇒ no peers. There is nothing to check a `key_signature` against, and admitting them
1639///   unchecked would dial a peer the lock may have revoked while this node was off.
1640/// * **the chain is not at the head the cached frame recorded** (`MapResponse.TKAInfo.Head`) ⇒ no
1641///   peers. The netmap and the chain are written on separate events, so they can disagree — a crash
1642///   between them, or a lock disabled and re-enabled under a fresh genesis — and a chain that
1643///   describes a different lock says nothing about these peers.
1644///
1645/// Separated from the I/O in [`load_cached_netmap`] so the decision itself is directly testable with
1646/// a real chain-derived [`Authority`](ts_tka::Authority) and real signatures.
1647pub(crate) fn vouch_cached_peers(
1648    authority: Option<&ts_tka::Authority>,
1649    tka: &TkaStatus,
1650    peers: Vec<Node>,
1651) -> Vec<Node> {
1652    let Some(authority) = authority else {
1653        tracing::info!(
1654            "no persisted tailnet-lock authority to verify the cached peers against; withholding \
1655             them until control's first netmap"
1656        );
1657        return Vec::new();
1658    };
1659
1660    if !ts_tka::AumHash::from_base32(&tka.head).is_some_and(|head| authority.head_matches(&head)) {
1661        tracing::warn!(
1662            head = %tka.head,
1663            "persisted tailnet-lock chain is not at the head the cached netmap recorded; \
1664             withholding its peers"
1665        );
1666        return Vec::new();
1667    }
1668
1669    let keep = {
1670        let refs: Vec<&Node> = peers.iter().collect();
1671        crate::peer_tracker::PeerTracker::tka_keep_verdicts(Some(authority), &refs)
1672    };
1673    peers
1674        .into_iter()
1675        .zip(keep)
1676        .filter_map(|(peer, keep)| keep.then_some(peer))
1677        .collect()
1678}
1679
1680impl Message<StreamMessage<Arc<StateUpdate>, (), ()>> for ControlRunner {
1681    type Reply = ();
1682
1683    async fn handle(
1684        &mut self,
1685        msg: StreamMessage<Arc<StateUpdate>, (), ()>,
1686        ctx: &mut Context<Self, Self::Reply>,
1687    ) {
1688        match msg {
1689            StreamMessage::Started(_) => {
1690                tracing::trace!("started listening to state updates");
1691            }
1692
1693            StreamMessage::Next(msg) => {
1694                if let Some(node) = msg.node.as_ref() {
1695                    // Reflect node-key expiry into the device state. Control delivering a self-node
1696                    // whose key is in the past means the node must re-authenticate; the arrival of a
1697                    // fresh (non-expired) self-node confirms we are Running (recovering the state if a
1698                    // prior update had flipped it to Expired/Reauthenticating). On expiry, decide
1699                    // between an automatic re-auth (Go `doLogin`: rotate key + re-register with the
1700                    // stored auth key) and the terminal Expired state via the pure `expiry_action`:
1701                    //   - auth key retained, reauth enabled, and TKA NOT enforcing → Reauthenticate.
1702                    //   - otherwise → Expired (no auth key / reauth disabled / TKA-locked).
1703                    // The TKA gate is a hard safety constraint: rotating on a locked tailnet would
1704                    // install an unsigned key and lock this node out of locked peers (the TKA re-sign
1705                    // is a separate follow-up). Recovery from Reauthenticating is automatic — the next
1706                    // good self-node flips back to Running at this same handler.
1707                    let now_unix = std::time::SystemTime::now()
1708                        .duration_since(std::time::UNIX_EPOCH)
1709                        .map(|d| d.as_secs() as i64)
1710                        .unwrap_or(0);
1711                    let action = expiry_action(
1712                        node.key_expired_at_unix(now_unix),
1713                        self.params.auth_key.is_some(),
1714                        self.params.config.reauth_on_expiry,
1715                        self.tka_authority.borrow().is_some(),
1716                    );
1717
1718                    // Bounded reauth sub-state-machine (circuit breaker), evaluated by the pure
1719                    // `reauth_circuit_step`. The `Reauthenticate` path must settle — a one-shot /
1720                    // already-consumed auth key cannot re-register, so an unbounded reauth would sit in
1721                    // `Reauthenticating` forever. The step takes the `expiry_action` verdict, whether we
1722                    // are ALREADY reauthenticating (i.e. the prior reauth has not recovered), and the
1723                    // current attempt counter, and returns the target state, the new counter, and
1724                    // whether to fire the one-shot reauth (fired ONLY on entry, so the node key rotates
1725                    // at most once per episode — a second rotation would lose the original `OldNodeKey`
1726                    // anchor). At `MAX_REAUTH_ATTEMPTS` it trips to terminal `Expired`.
1727                    //
1728                    // NOTE: we may act (count, and eventually flip to `Expired`) even when the published
1729                    // state does NOT change — a repeated `Reauthenticating` self-node is exactly the
1730                    // "prior reauth didn't recover" signal we must tally, so the counting reads the
1731                    // pre-step state directly here and `send_if_modified`'s `changed` only gates the
1732                    // log/firing below, never the counting.
1733                    let already_reauthing = matches!(
1734                        &*self.params.state_tx.borrow(),
1735                        crate::DeviceState::Reauthenticating
1736                    );
1737                    let step = reauth_circuit_step(action, already_reauthing, self.reauth_attempts);
1738                    self.reauth_attempts = step.attempts;
1739                    if step.next == ReauthState::Expired
1740                        && action == ExpiryAction::Reauthenticate
1741                        && already_reauthing
1742                    {
1743                        tracing::warn!(
1744                            attempts = step.attempts,
1745                            "automatic re-auth did not recover the node after {MAX_REAUTH_ATTEMPTS} \
1746                             attempts (auth key likely one-shot / consumed); falling back to terminal \
1747                             Expired"
1748                        );
1749                    }
1750                    let next = match step.next {
1751                        ReauthState::Running => crate::DeviceState::Running,
1752                        ReauthState::Reauthenticating => crate::DeviceState::Reauthenticating,
1753                        ReauthState::Expired => crate::DeviceState::Expired,
1754                    };
1755
1756                    // `send_if_modified` avoids waking watchers when the state is unchanged (a fresh
1757                    // self-node arrives on every netmap update). Returns whether the state changed.
1758                    let changed = self.params.state_tx.send_if_modified(|s| {
1759                        if *s != next {
1760                            *s = next.clone();
1761                            true
1762                        } else {
1763                            false
1764                        }
1765                    });
1766
1767                    if changed && step.fire_reauth {
1768                        tracing::info!(
1769                            "self node-key expired; starting automatic re-auth (rotate node key + \
1770                             re-register with stored auth key)"
1771                        );
1772                        self.client.reauth().await;
1773                    }
1774
1775                    self.self_node.send_replace(Some(node.clone()));
1776                }
1777
1778                if let Some(policy) = msg.ssh_policy.as_ref() {
1779                    self.ssh_policy.send_replace(Some(policy.clone()));
1780                }
1781
1782                if let Some(tka) = msg.tka.as_ref() {
1783                    self.tka.send_replace(Some(tka.clone()));
1784                    self.maybe_sync_tka(tka, ctx.actor_ref().clone());
1785                }
1786
1787                // Track the cert-domain list from the netmap DNS config (Go `nm.DNS.CertDomains`).
1788                // An update with no DNS config, or one carrying no cert domains, means "none" — Go
1789                // reads an empty slice off an absent config too, so mirror that as an empty `Vec`.
1790                let cert_domains = msg
1791                    .dns_config
1792                    .as_ref()
1793                    .map(|d| d.cert_domains.clone())
1794                    .unwrap_or_default();
1795                self.cert_domains.send_replace(cert_domains);
1796
1797                // Track the full DNS config for `Device::dns_config` (the daemon's `tnet dns status`).
1798                // `None` when control sent no DNS config on this update — distinct from a present but
1799                // empty config (Go `netmap.NetworkMap.DNS`).
1800                self.dns_config.send_replace(msg.dns_config.clone());
1801
1802                // Track the interactive-login URL for `Device::pop_browser_url` /
1803                // `Runtime::watch_ipn_bus`. See `sticky_update_pop_browser_url` for the Go-faithful
1804                // sticky semantics (update only on a new non-empty URL; never reset to `None`).
1805                sticky_update_pop_browser_url(&self.pop_browser_url, msg.pop_browser_url.as_ref());
1806
1807                if let Err(e) = self.params.env.publish(msg).await {
1808                    tracing::error!(error = %e, "publishing netmap update");
1809                }
1810            }
1811
1812            StreamMessage::Finished(_) => {
1813                tracing::error!("state update stream terminated")
1814            }
1815        }
1816    }
1817}
1818
1819/// The outcome of a spawned TKA bootstrap+sync task, delivered back to the actor thread so the
1820/// result can be applied to actor state (which a spawned task cannot touch directly). Sent by
1821/// [`ControlRunner::maybe_sync_tka`]; handled by applying via
1822/// [`ControlRunner::apply_tka_synced`](ControlRunner).
1823#[doc(hidden)]
1824pub struct TkaSynced {
1825    pub(crate) result:
1826        Result<Option<crate::tka_sync::SyncedTka>, crate::tka_sync::TkaSyncDriverError>,
1827    /// The [`ControlRunner::tka_generation`] captured when this sync was spawned; the handler
1828    /// discards the result if it no longer matches (the lock was disabled/re-synced mid-flight).
1829    pub(crate) generation: u64,
1830}
1831
1832impl Message<TkaSynced> for ControlRunner {
1833    type Reply = ();
1834
1835    async fn handle(&mut self, msg: TkaSynced, _ctx: &mut Context<Self, Self::Reply>) {
1836        self.apply_tka_synced(msg.result, msg.generation).await;
1837    }
1838}
1839
1840impl Message<DerpLatencyMeasurement> for ControlRunner {
1841    type Reply = ();
1842
1843    async fn handle(&mut self, msg: DerpLatencyMeasurement, _ctx: &mut Context<Self, Self::Reply>) {
1844        let measurements = msg.measurement.as_ref().clone();
1845
1846        // Publish the net-report snapshot for `Device::netcheck` (the daemon's `tnet netcheck`) from
1847        // the same measurements, before the home-region short-circuit below — an empty set still
1848        // yields a (default/empty) report rather than a stale one.
1849        self.netcheck
1850            .send_replace(crate::status::NetcheckReport::from_region_results(
1851                &measurements,
1852            ));
1853
1854        if measurements.is_empty() {
1855            tracing::debug!("derp latency measurements empty");
1856            return;
1857        };
1858
1859        // Record this cycle into the rolling history and evict reports older than the smoothing
1860        // window, then compute each region's `bestRecent` (5-min min). `Instant::now()` is the
1861        // arrival stamp; `best_recent` takes it as a param so the decision stays unit-testable.
1862        let now = Instant::now();
1863        self.derp_report_history
1864            .push((now, msg.measurement.clone()));
1865        self.derp_report_history
1866            .retain(|(stamp, _)| now.saturating_duration_since(*stamp) <= DERP_HISTORY_MAX_AGE);
1867        let best_recent = best_recent(&self.derp_report_history, now, DERP_HISTORY_MAX_AGE);
1868
1869        // Apply selection hysteresis (the pure decision lives in `select_home_region` for testability)
1870        // so jitter between near-equal regions does not flap the home relay. Go's asymmetric
1871        // smoothed-best vs raw-old comparison lives in `select_home_region`; here we just resolve the
1872        // chosen id back to its current-cycle latency for the home-region record + control update.
1873        let selected_id = select_home_region(
1874            self.home_region.map(|(id, _)| id),
1875            &measurements,
1876            &best_recent,
1877        )
1878        .expect("non-empty measurements always yield a selection");
1879        // `select_home_region` only ever returns an id drawn from `measurements`, so this lookup
1880        // always succeeds (same invariant the prior impl relied on when it returned the result by
1881        // reference). We record the current-cycle (raw) latency for the chosen region.
1882        let selected_latency = measurements
1883            .iter()
1884            .find(|m| m.id == selected_id)
1885            .expect("the selected region id is always one of the measurements")
1886            .latency;
1887
1888        let iter = measurements.iter().map(|result| {
1889            (
1890                result.latency_map_key.as_str(),
1891                result.latency.as_secs_f64(),
1892            )
1893        });
1894
1895        if self.home_region.map(|(id, _)| id) != Some(selected_id) {
1896            tracing::debug!(selected_region_id = ?selected_id, "updating home region");
1897        }
1898        self.home_region = Some((selected_id, selected_latency));
1899        // Advertise the smoothed home to control AND drive the local DERP relay to the same region
1900        // (Go `report.PreferredDERP` feeds both). `send_replace` wakes the watch on every send (it
1901        // does NOT coalesce same-value writes), so Multiderp's bridge sees a `SetHomeRegion` each
1902        // cycle; the de-dup is one layer down — `home_transition` returns `Unchanged` for a
1903        // re-selection of the current home, so the relay only churns on an actual home change.
1904        self.client.set_home_region(selected_id, iter).await;
1905        self.params.home_region.send_replace(Some(selected_id));
1906    }
1907}
1908
1909/// The window over which `best_recent` smooths per-region DERP latency (Go `netcheck` `maxAge`).
1910const DERP_HISTORY_MAX_AGE: Duration = Duration::from_secs(5 * 60);
1911
1912/// Compute each region's `bestRecent` — its **minimum** latency over the reports within
1913/// `max_age` of `now` (Go `addReportHistoryAndSetPreferredDERP`'s `bestRecent` map). Reports older
1914/// than the window are ignored. `now` and `max_age` are parameters (not clock-read) so this is
1915/// deterministically unit-testable. A region absent from every in-window report is absent from the
1916/// result.
1917fn best_recent(
1918    history: &[(Instant, Arc<Vec<ts_netcheck::RegionResult>>)],
1919    now: Instant,
1920    max_age: Duration,
1921) -> HashMap<ts_derp::RegionId, Duration> {
1922    let mut best: HashMap<ts_derp::RegionId, Duration> = HashMap::new();
1923    for (stamp, report) in history {
1924        // Skip reports outside the window. `saturating_duration_since` guards a `stamp` that is
1925        // somehow after `now` (clock skew): age 0, always in-window.
1926        if now.saturating_duration_since(*stamp) > max_age {
1927            continue;
1928        }
1929        for r in report.iter() {
1930            best.entry(r.id)
1931                .and_modify(|d| {
1932                    if r.latency < *d {
1933                        *d = r.latency;
1934                    }
1935                })
1936                .or_insert(r.latency);
1937        }
1938    }
1939    best
1940}
1941
1942/// Choose the DERP home region id, applying Go's selection hysteresis
1943/// (`netcheck.addReportHistoryAndSetPreferredDERP`). Pure so the decision is unit-testable.
1944///
1945/// `measurements` is the current cycle sorted by latency ascending (so `measurements[0]` is the
1946/// raw-current best). `best_recent` is each region's smoothed (5-min-min) latency. Matching Go's
1947/// **asymmetric** comparison exactly: the new best candidate is chosen by the *smoothed* `best_recent`
1948/// latency (`bestAny`), while the old/home region is compared using its *current-cycle* (raw)
1949/// latency (`oldRegionCurLatency`). Smoothing the best damps oscillation of the best region across
1950/// the switch boundary that the raw-vs-raw comparison (the prior impl) would still flap on.
1951///
1952/// Keeps the `current` home region unless the new best is *meaningfully* lower-latency — switching
1953/// only when BOTH the current region's raw latency exceeds the smoothed-best by at least
1954/// `PREFERRED_DERP_ABSOLUTE_DIFF` (10ms) AND the smoothed-best is at most two-thirds of the current
1955/// region's raw latency (a >~33% improvement). On the first selection (`current` is `None`), when the
1956/// smoothed-best already IS the current region, or when the current region dropped out of the
1957/// measurements, returns the best directly. `None` only if `measurements` is empty.
1958fn select_home_region(
1959    current: Option<ts_derp::RegionId>,
1960    measurements: &[ts_netcheck::RegionResult],
1961    best_recent: &HashMap<ts_derp::RegionId, Duration>,
1962) -> Option<ts_derp::RegionId> {
1963    /// Go `netcheck.preferredDERPAbsoluteDiff`.
1964    const PREFERRED_DERP_ABSOLUTE_DIFF: Duration = Duration::from_millis(10);
1965
1966    // The smoothed latency for a region: its `best_recent` if present, else its current sample (a
1967    // region seen only this cycle has a 1-sample history, so its min == its current latency anyway).
1968    let smoothed = |m: &ts_netcheck::RegionResult| -> Duration {
1969        best_recent.get(&m.id).copied().unwrap_or(m.latency)
1970    };
1971
1972    // Pick the best candidate by SMOOTHED latency (Go `bestAny = min over regions of bestRecent`).
1973    // `measurements` is sorted by raw latency, but smoothing can reorder, so scan for the smoothed
1974    // minimum explicitly rather than trusting `measurements[0]`.
1975    let best = measurements.iter().min_by_key(|m| smoothed(m))?;
1976    let best_any = smoothed(best);
1977
1978    let Some(old_id) = current.filter(|id| *id != best.id) else {
1979        // First selection, or the smoothed-best already is the current home region.
1980        return Some(best.id);
1981    };
1982
1983    // Compare against the old region's CURRENT (raw) latency this cycle, if it is still present —
1984    // Go's `oldRegionCurLatency`, deliberately unsmoothed (the asymmetry).
1985    match measurements.iter().find(|m| m.id == old_id) {
1986        Some(old) => {
1987            // Byte-faithful to Go: `oldRegionCurLatency - bestAny < 10ms || bestAny >
1988            // oldRegionCurLatency/3*2`. `saturating_sub` matches Go's signed subtraction for the
1989            // `< 10ms` test (when `old < best_any` Go is negative → `< 10ms` true; saturating_sub
1990            // floors to 0 → also true). The two-thirds rule uses INTEGER `Duration` division
1991            // `(old/3)*2` — NOT float `* 2.0/3.0`: Go computes the threshold in integer nanoseconds
1992            // (`oldNs/3` truncates), and float arithmetic diverges from it at the exact 2/3 boundary
1993            // with whole-millisecond inputs (e.g. old=36ms, best=24ms: Go's `24ms > 24ms` is false →
1994            // switch, but float `0.024 > 0.0239999997` is true → keep). `Duration / u32` truncates
1995            // nanos exactly like Go and `* u32` is exact, reproducing `oldRegionCurLatency/3*2`.
1996            let keep_old = old.latency.saturating_sub(best_any) < PREFERRED_DERP_ABSOLUTE_DIFF
1997                || best_any > (old.latency / 3) * 2;
1998            Some(if keep_old { old.id } else { best.id })
1999        }
2000        // The current region is no longer reachable this cycle: take the new best.
2001        None => Some(best.id),
2002    }
2003}
2004
2005impl Message<EndpointAdvertisement> for ControlRunner {
2006    type Reply = ();
2007
2008    async fn handle(&mut self, msg: EndpointAdvertisement, _ctx: &mut Context<Self, Self::Reply>) {
2009        let endpoints: Vec<Endpoint> = msg
2010            .endpoints
2011            .iter()
2012            .map(|ep| Endpoint {
2013                endpoint: ep.addr,
2014                ty: match ep.ty {
2015                    SelfEndpointType::Local => EndpointType::Local,
2016                    SelfEndpointType::Stun => EndpointType::Stun,
2017                    SelfEndpointType::Stun4LocalPort => EndpointType::Stun4LocalPort,
2018                },
2019            })
2020            .collect();
2021
2022        tracing::debug!(
2023            n_endpoints = endpoints.len(),
2024            "advertising endpoints to control"
2025        );
2026
2027        self.client.set_endpoints(endpoints).await;
2028    }
2029}
2030
2031/// Re-advertise this node's routable IP prefixes (`Hostinfo.RoutableIPs`) to control — the wire
2032/// half of a runtime [`Runtime::set_advertise_routes`](crate::Runtime::set_advertise_routes). Sent
2033/// as a direct `ask` from the runtime (not over the bus), so the route change reaches the live
2034/// map-poll client. `routes` is the final advertised set the caller wants control to grant.
2035#[derive(Debug)]
2036pub struct SetAdvertiseRoutes {
2037    /// The prefixes to advertise to control (already filtered to the final set).
2038    pub routes: Vec<ipnet::IpNet>,
2039}
2040
2041impl Message<SetAdvertiseRoutes> for ControlRunner {
2042    type Reply = ();
2043
2044    async fn handle(&mut self, msg: SetAdvertiseRoutes, _ctx: &mut Context<Self, Self::Reply>) {
2045        tracing::debug!(n_routes = msg.routes.len(), "advertising routes to control");
2046        self.client.set_routable_ips(msg.routes).await;
2047    }
2048}
2049
2050/// Update this node's `Hostinfo.Hostname` at control — the wire half of a runtime
2051/// [`Runtime::set_hostname`](crate::Runtime::set_hostname). A direct `ask` from the runtime, so the
2052/// change reaches the live map-poll client.
2053#[derive(Debug)]
2054pub struct SetHostname {
2055    /// The new hostname to report to control.
2056    pub hostname: String,
2057}
2058
2059impl Message<SetHostname> for ControlRunner {
2060    type Reply = ();
2061
2062    async fn handle(&mut self, msg: SetHostname, _ctx: &mut Context<Self, Self::Reply>) {
2063        tracing::debug!("updating hostname at control");
2064        self.client.set_hostname(msg.hostname).await;
2065    }
2066}
2067
2068#[cfg(test)]
2069mod reauth_bridge_tests {
2070    use tokio::sync::watch;
2071
2072    use super::bridge_reauth_url_to_state;
2073    use crate::DeviceState;
2074
2075    fn url(s: &str) -> url::Url {
2076        s.parse().unwrap()
2077    }
2078
2079    /// The bridge maps a surfaced re-auth URL onto `DeviceState::NeedsLogin(url)` — the fix's core:
2080    /// a mid-session `MachineNotAuthorized` (forwarded by the control client as `Some(url)`) becomes
2081    /// the "needs login" state the IPN bus turns into `browse_to_url`.
2082    #[test]
2083    fn bridge_maps_auth_url_to_needs_login() {
2084        let u = url("https://login.example/auth");
2085        let (tx, rx) = watch::channel(DeviceState::Running);
2086
2087        bridge_reauth_url_to_state(&tx, Some(&u));
2088
2089        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u));
2090    }
2091
2092    /// `None` never drives a transition — the recovery to `Running` is the netmap self-node
2093    /// handler's job, so the bridge ignores a `None` and leaves the state untouched.
2094    #[test]
2095    fn bridge_none_leaves_state_unchanged() {
2096        let (tx, rx) = watch::channel(DeviceState::Running);
2097
2098        bridge_reauth_url_to_state(&tx, None);
2099
2100        assert_eq!(*rx.borrow(), DeviceState::Running);
2101    }
2102
2103    /// Re-surfacing the same URL across retries does not re-fire the watch (`send_if_modified`
2104    /// dedupe against the cell's current value), so a stuck re-auth does not thrash subscribers.
2105    #[test]
2106    fn bridge_same_url_does_not_refire() {
2107        let u = url("https://login.example/auth");
2108        let (tx, mut rx) = watch::channel(DeviceState::Running);
2109
2110        bridge_reauth_url_to_state(&tx, Some(&u)); // first: fires
2111        assert!(rx.has_changed().unwrap(), "first NeedsLogin fires");
2112        rx.mark_unchanged();
2113        bridge_reauth_url_to_state(&tx, Some(&u)); // same URL: deduped
2114        assert!(
2115            !rx.has_changed().unwrap(),
2116            "the same re-auth URL must not re-fire the state watch"
2117        );
2118    }
2119
2120    /// A genuinely different re-auth URL after a prior one fires again (the dedupe tracks changes,
2121    /// it does not pin the first URL forever).
2122    #[test]
2123    fn bridge_new_url_after_prior_fires() {
2124        let a = url("https://login.example/a");
2125        let b = url("https://login.example/b");
2126        let (tx, rx) = watch::channel(DeviceState::Running);
2127
2128        bridge_reauth_url_to_state(&tx, Some(&a));
2129        bridge_reauth_url_to_state(&tx, Some(&b));
2130
2131        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(b));
2132    }
2133
2134    /// End-to-end of the *clear* contract: after the bridge sets `NeedsLogin`, the netmap self-node
2135    /// path (modeled here as a direct `send_replace(Running)`, the exact transition the
2136    /// `StreamMessage::Next` handler performs on the next good self-node) flips back to `Running`.
2137    /// This pins that the bridge does NOT need a `None`-clear arm — recovery is owned elsewhere.
2138    #[test]
2139    fn running_netmap_clears_needs_login() {
2140        let u = url("https://login.example/auth");
2141        let (tx, rx) = watch::channel(DeviceState::Running);
2142
2143        bridge_reauth_url_to_state(&tx, Some(&u));
2144        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u));
2145
2146        // The self-node handler's recovery transition (next good netmap self-node → Running).
2147        tx.send_replace(DeviceState::Running);
2148        assert_eq!(*rx.borrow(), DeviceState::Running);
2149    }
2150
2151    /// Fix 2 — the bridge must NOT clobber an in-flight automatic re-auth. While the cell holds
2152    /// `Reauthenticating`, an auth URL surfaced by the rotated re-register (over the same
2153    /// `auth_url_tx` cell) must leave the state UNTOUCHED: flipping to `NeedsLogin` would surface a
2154    /// misleading `browse_to_url` on a headless node and, by moving the cell off `Reauthenticating`,
2155    /// re-arm a second node-key rotation that loses the original `OldNodeKey` anchor. The auto-reauth
2156    /// path owns the cell until it recovers to `Running` or trips to `Expired`.
2157    #[test]
2158    fn bridge_does_not_clobber_reauthenticating() {
2159        let u = url("https://login.example/auth");
2160        let (tx, rx) = watch::channel(DeviceState::Reauthenticating);
2161
2162        bridge_reauth_url_to_state(&tx, Some(&u));
2163
2164        assert_eq!(
2165            *rx.borrow(),
2166            DeviceState::Reauthenticating,
2167            "a surfaced auth URL must not downgrade an in-flight auto-reauth to NeedsLogin"
2168        );
2169    }
2170
2171    /// The no-clobber guard is scoped to `Reauthenticating` only — it does not change the bridge's
2172    /// behavior in any other state. From `Running` (and likewise `Connecting`/`NeedsLogin`) a
2173    /// surfaced URL still drives `NeedsLogin` as before, so an ordinary interactive re-auth is
2174    /// unaffected.
2175    #[test]
2176    fn bridge_still_sets_needs_login_from_non_reauthenticating() {
2177        let u = url("https://login.example/auth");
2178        for start in [
2179            DeviceState::Running,
2180            DeviceState::Connecting,
2181            DeviceState::Expired,
2182        ] {
2183            let (tx, rx) = watch::channel(start);
2184            bridge_reauth_url_to_state(&tx, Some(&u));
2185            assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u.clone()));
2186        }
2187    }
2188}
2189
2190#[cfg(test)]
2191mod sticky_pop_browser_url_tests {
2192    use tokio::sync::watch;
2193
2194    use super::sticky_update_pop_browser_url;
2195
2196    fn url(s: &str) -> url::Url {
2197        s.parse().unwrap()
2198    }
2199
2200    /// A non-empty URL publishes to the cell.
2201    #[test]
2202    fn non_empty_url_publishes() {
2203        let (tx, rx) = watch::channel(None);
2204        let u = url("https://login.example/consent");
2205        sticky_update_pop_browser_url(&tx, Some(&u));
2206        assert_eq!(*rx.borrow(), Some(u));
2207    }
2208
2209    /// An absent (`None`) update — the common netmap tick — must NOT reset the cell. This is the
2210    /// regression guard for the thrash bug (a reset-every-tick would coalesce the URL away on the bus).
2211    #[test]
2212    fn absent_update_does_not_reset() {
2213        let u = url("https://login.example/consent");
2214        let (tx, rx) = watch::channel(Some(u.clone()));
2215        // Simulate many empty netmap updates.
2216        for _ in 0..5 {
2217            sticky_update_pop_browser_url(&tx, None);
2218        }
2219        assert_eq!(
2220            *rx.borrow(),
2221            Some(u),
2222            "empty updates must not clear the URL"
2223        );
2224    }
2225
2226    /// The same URL repeated does not re-fire the watch (in-place dedupe via `send_if_modified`), so
2227    /// a subscriber isn't woken spuriously. Proven by the borrow not having been marked changed.
2228    #[test]
2229    fn repeated_same_url_does_not_refire() {
2230        let u = url("https://login.example/consent");
2231        let (tx, mut rx) = watch::channel(None);
2232        sticky_update_pop_browser_url(&tx, Some(&u)); // first: fires
2233        assert!(rx.has_changed().unwrap(), "first non-empty URL fires");
2234        rx.mark_unchanged();
2235        sticky_update_pop_browser_url(&tx, Some(&u)); // same: deduped
2236        assert!(
2237            !rx.has_changed().unwrap(),
2238            "repeating the same URL must not re-fire the watch"
2239        );
2240    }
2241
2242    /// A genuinely new URL after a prior one fires again (sticky but tracks changes).
2243    #[test]
2244    fn new_url_after_prior_fires() {
2245        let a = url("https://login.example/a");
2246        let b = url("https://login.example/b");
2247        let (tx, rx) = watch::channel(None);
2248        sticky_update_pop_browser_url(&tx, Some(&a));
2249        sticky_update_pop_browser_url(&tx, Some(&b));
2250        assert_eq!(*rx.borrow(), Some(b));
2251    }
2252
2253    /// The realistic session sequence: a URL stays sticky through a run of `None` ticks, and a
2254    /// *different* URL after that gap still fires. Chains the legs the other tests cover in isolation
2255    /// (the actual control cadence is "URL, then many empty updates, then maybe a new URL").
2256    #[test]
2257    fn sticky_through_none_gap_then_new_url_fires() {
2258        let a = url("https://login.example/a");
2259        let b = url("https://login.example/b");
2260        let (tx, rx) = watch::channel(None);
2261        sticky_update_pop_browser_url(&tx, Some(&a));
2262        for _ in 0..3 {
2263            sticky_update_pop_browser_url(&tx, None);
2264        }
2265        assert_eq!(*rx.borrow(), Some(a), "stayed sticky through the None gap");
2266        sticky_update_pop_browser_url(&tx, Some(&b));
2267        assert_eq!(
2268            *rx.borrow(),
2269            Some(b),
2270            "a new URL after a None gap still fires"
2271        );
2272    }
2273
2274    /// Returning to a previously-seen URL (A → B → A) re-fires: the dedupe is against the cell's
2275    /// *current* value, not a full history, so A after B is a genuine change.
2276    #[test]
2277    fn returning_to_prior_url_refires() {
2278        let a = url("https://login.example/a");
2279        let b = url("https://login.example/b");
2280        let (tx, mut rx) = watch::channel(None);
2281        sticky_update_pop_browser_url(&tx, Some(&a));
2282        sticky_update_pop_browser_url(&tx, Some(&b));
2283        rx.mark_unchanged();
2284        sticky_update_pop_browser_url(&tx, Some(&a)); // back to A: differs from current (B) → fires
2285        assert!(
2286            rx.has_changed().unwrap(),
2287            "returning to a prior URL re-fires"
2288        );
2289        assert_eq!(*rx.borrow(), Some(a));
2290    }
2291
2292    /// End-to-end de-thrash: feed a realistic netmap cadence (empty, empty, URL, empty, empty)
2293    /// through the producer into a cell, and count the changes a `run_bus`-style subscriber would
2294    /// observe via `changed()`. The whole point of the fix is that exactly ONE change survives the
2295    /// surrounding `None` thrash — the pre-fix code (`send_replace` every tick) would have woken the
2296    /// subscriber on every empty tick and coalesced the URL away. This exercises the producer + the
2297    /// watch-subscribe path together (the two halves the unit tests cover in isolation).
2298    #[tokio::test]
2299    async fn end_to_end_one_change_survives_none_thrash() {
2300        let u = url("https://login.example/consent");
2301        let (tx, mut rx) = watch::channel(None);
2302        // The cadence control actually sends: mostly-empty MapResponses with one carrying the URL.
2303        let cadence = [None, None, Some(&u), None, None];
2304        for incoming in cadence {
2305            sticky_update_pop_browser_url(&tx, incoming);
2306        }
2307        // A subscriber sees exactly one change, and it carries the URL (not a coalesced `None`).
2308        let mut changes = 0;
2309        while rx.has_changed().unwrap() {
2310            let v = rx.borrow_and_update().clone();
2311            changes += 1;
2312            assert_eq!(v, Some(u.clone()), "the surviving change carries the URL");
2313        }
2314        assert_eq!(changes, 1, "exactly one change survives the None thrash");
2315    }
2316}
2317
2318#[cfg(test)]
2319mod home_region_hysteresis_tests {
2320    use core::time::Duration;
2321    use std::{collections::HashMap, sync::Arc, time::Instant};
2322
2323    use ts_derp::RegionId;
2324    use ts_netcheck::RegionResult;
2325
2326    use super::{DERP_HISTORY_MAX_AGE, best_recent, select_home_region};
2327
2328    fn region(id: u32, latency_ms: u64) -> RegionResult {
2329        RegionResult {
2330            latency: Duration::from_millis(latency_ms),
2331            id: RegionId(core::num::NonZeroU32::new(id).unwrap()),
2332            latency_map_key: format!("region-{id}"),
2333            connected_remote: "127.0.0.1:0".parse().unwrap(),
2334        }
2335    }
2336
2337    fn rid(id: u32) -> RegionId {
2338        RegionId(core::num::NonZeroU32::new(id).unwrap())
2339    }
2340
2341    /// Call `select_home_region` with NO smoothing history — `best_recent` empty, so each region's
2342    /// smoothed latency falls back to its current sample, reproducing the original raw-vs-raw
2343    /// hysteresis these tests pin. (The smoothing-specific tests below pass a populated map.)
2344    fn sel(current: Option<RegionId>, m: &[RegionResult]) -> Option<RegionId> {
2345        select_home_region(current, m, &HashMap::new())
2346    }
2347
2348    /// Empty measurements yield no selection.
2349    #[test]
2350    fn empty_measurements_select_none() {
2351        assert!(sel(Some(rid(1)), &[]).is_none());
2352        assert!(sel(None, &[]).is_none());
2353    }
2354
2355    /// First selection (no current home region) takes the best (lowest-latency) region directly.
2356    #[test]
2357    fn first_selection_takes_best() {
2358        let m = [region(1, 20), region(2, 50)];
2359        assert_eq!(sel(None, &m).unwrap(), rid(1));
2360    }
2361
2362    /// Jitter within the 10ms absolute-diff band keeps the current region (no flap). Current=region 2
2363    /// at 25ms; new best=region 1 at 20ms (only 5ms better) -> keep region 2.
2364    #[test]
2365    fn keeps_current_when_within_absolute_diff() {
2366        let m = [region(1, 20), region(2, 25)];
2367        assert_eq!(
2368            sel(Some(rid(2)), &m).unwrap(),
2369            rid(2),
2370            "a 5ms improvement (< 10ms) must not flap the home region"
2371        );
2372    }
2373
2374    /// A meaningful improvement (>10ms AND best <= 2/3 of current) switches. Current=region 2 at
2375    /// 100ms; new best=region 1 at 20ms -> switch to region 1.
2376    #[test]
2377    fn switches_on_meaningful_improvement() {
2378        let m = [region(1, 20), region(2, 100)];
2379        assert_eq!(
2380            sel(Some(rid(2)), &m).unwrap(),
2381            rid(1),
2382            "a large improvement must switch the home region"
2383        );
2384    }
2385
2386    /// The two-thirds rule: even past the 10ms absolute diff, an improvement that does not beat 2/3
2387    /// of the current latency keeps the current region. current=60ms, best=45ms: diff=15ms (>10ms,
2388    /// so the absolute test alone would switch), but 45 > 60*2/3=40, so keep.
2389    #[test]
2390    fn keeps_current_when_two_thirds_rule_not_met() {
2391        let m = [region(1, 45), region(2, 60)];
2392        assert_eq!(
2393            sel(Some(rid(2)), &m).unwrap(),
2394            rid(2),
2395            "best (45ms) is not <= 2/3 of current (40ms), so keep current despite >10ms diff"
2396        );
2397    }
2398
2399    /// When the current home region is no longer present in the measurements, take the new best.
2400    #[test]
2401    fn switches_when_current_region_absent() {
2402        let m = [region(1, 20), region(3, 25)];
2403        assert_eq!(
2404            sel(Some(rid(2)), &m).unwrap(),
2405            rid(1),
2406            "a current region absent from the measurements falls through to the best"
2407        );
2408    }
2409
2410    /// When the best already IS the current home region, it is kept (no spurious change).
2411    #[test]
2412    fn keeps_current_when_it_is_already_best() {
2413        let m = [region(2, 20), region(1, 50)];
2414        assert_eq!(sel(Some(rid(2)), &m).unwrap(), rid(2));
2415    }
2416
2417    /// `best_recent` is each region's MINIMUM latency over the in-window reports; a report older than
2418    /// `max_age` is excluded.
2419    #[test]
2420    fn best_recent_is_min_over_window_and_evicts_aged() {
2421        let now = Instant::now();
2422        // Two in-window reports for region 1 (50ms then 20ms) → min 20ms; region 2 once at 30ms.
2423        // One aged report (region 1 at 5ms) outside the window must be ignored.
2424        let history = vec![
2425            (
2426                now - Duration::from_secs(10 * 60), // aged out (> 5min)
2427                Arc::new(vec![region(1, 5)]),
2428            ),
2429            (
2430                now - Duration::from_secs(60),
2431                Arc::new(vec![region(1, 50), region(2, 30)]),
2432            ),
2433            (now, Arc::new(vec![region(1, 20)])),
2434        ];
2435        let br = best_recent(&history, now, DERP_HISTORY_MAX_AGE);
2436        assert_eq!(
2437            br.get(&rid(1)).copied(),
2438            Some(Duration::from_millis(20)),
2439            "region 1 min over the window is 20ms (the aged 5ms is excluded)"
2440        );
2441        assert_eq!(br.get(&rid(2)).copied(), Some(Duration::from_millis(30)));
2442    }
2443
2444    /// The asymmetric comparison: the new best is chosen by its SMOOTHED (best_recent) latency while
2445    /// the old region is compared on its RAW current latency. A best region whose CURRENT sample
2446    /// looks much better but whose 5-min MIN is only marginally better must NOT flap the home region
2447    /// — exactly the oscillation the raw-vs-raw comparison would have switched on.
2448    #[test]
2449    fn smoothed_best_damps_oscillation_across_boundary() {
2450        // Current home = region 2, raw 60ms this cycle. Region 1's CURRENT sample is 20ms (a >2/3,
2451        // >10ms improvement → raw-vs-raw would SWITCH), but its 5-min MIN (best_recent) is 50ms
2452        // (it oscillates). Smoothed-best 50ms vs raw-old 60ms: diff 10ms is NOT < 10ms, but
2453        // 50 > 60*2/3=40 → keepOld. So we KEEP region 2, where the raw comparison would have flapped.
2454        let m = [region(1, 20), region(2, 60)];
2455        let mut br = HashMap::new();
2456        br.insert(rid(1), Duration::from_millis(50)); // smoothed best is worse than its raw sample
2457        br.insert(rid(2), Duration::from_millis(60));
2458        assert_eq!(
2459            select_home_region(Some(rid(2)), &m, &br).unwrap(),
2460            rid(2),
2461            "a best region whose 5-min min is only marginally better must not flap the home region"
2462        );
2463
2464        // Sanity: with NO smoothing (raw 20ms best), the same inputs WOULD switch — proving the
2465        // smoothing is what holds it.
2466        assert_eq!(
2467            select_home_region(Some(rid(2)), &m, &HashMap::new()).unwrap(),
2468            rid(1),
2469            "raw-vs-raw (no smoothing) switches on the 20ms-vs-60ms current samples"
2470        );
2471    }
2472
2473    /// Smoothing can reorder which region is "best": `measurements` is sorted by raw latency, but the
2474    /// smoothed minimum may favor a different region. `select_home_region` must pick by smoothed
2475    /// latency, not blindly trust `measurements[0]`.
2476    #[test]
2477    fn smoothed_best_may_differ_from_raw_first() {
2478        // Raw order: region 1 (10ms) is first. But region 2's 5-min min is 5ms while region 1's is
2479        // 40ms (region 1's 10ms was a lucky low sample). Smoothed-best is region 2. First selection.
2480        let m = [region(1, 10), region(2, 12)];
2481        let mut br = HashMap::new();
2482        br.insert(rid(1), Duration::from_millis(40));
2483        br.insert(rid(2), Duration::from_millis(5));
2484        assert_eq!(
2485            select_home_region(None, &m, &br).unwrap(),
2486            rid(2),
2487            "the smoothed-best region wins even when it is not the raw-latency first"
2488        );
2489    }
2490
2491    /// Byte-faithful integer two-thirds boundary (the float-vs-integer divergence): at exactly
2492    /// `best == old * 2/3` (old=36ms, best=24ms), Go's integer `bestAny > old/3*2` = `24ms > 24ms`
2493    /// is FALSE, so it does NOT keep on the 2/3 arm; and `cond_a` `36-24=12ms < 10ms` is also false,
2494    /// so Go SWITCHES. A float `0.024 > 0.036*2.0/3.0 = 0.0239999997` would wrongly KEEP. This test
2495    /// pins the integer math: it must switch to the best.
2496    #[test]
2497    fn two_thirds_boundary_is_integer_not_float() {
2498        let m = [region(1, 24), region(2, 36)];
2499        // No smoothing (raw == smoothed): isolates the 2/3 arithmetic at the exact boundary.
2500        assert_eq!(
2501            sel(Some(rid(2)), &m).unwrap(),
2502            rid(1),
2503            "at best == old*2/3 the integer rule does NOT keep (Go switches); a float rule would keep"
2504        );
2505    }
2506
2507    /// The `cond_a` (absolute-diff) arm via `saturating_sub`: when the old region's RAW current
2508    /// latency is FASTER than the smoothed-best (old=20ms raw, smoothed-best=50ms), `old - best_any`
2509    /// underflows. Go's signed subtraction is negative (`< 10ms` → keepOld); `saturating_sub` floors
2510    /// to 0 (`< 10ms` → keepOld) — same outcome. The old region is kept.
2511    #[test]
2512    fn old_faster_than_smoothed_best_keeps_via_absolute_diff() {
2513        // Current home = region 2, raw 20ms. Region 1 is the raw-best at 15ms but its smoothed min is
2514        // 50ms (it oscillates badly). smoothed-best candidate by min = region 2 (raw 20 == smoothed
2515        // 20, since br[2]=20) vs region 1 smoothed 50 → best is region 2 itself → already-best path.
2516        // To exercise the old<best_any underflow we need best != old: make region 1 the smoothed best
2517        // at 18ms but the OLD region's raw 20ms... use: old=region2 raw 20, best=region1 smoothed 18.
2518        let m = [region(1, 15), region(2, 20)];
2519        let mut br = HashMap::new();
2520        br.insert(rid(1), Duration::from_millis(18)); // smoothed-best = region 1 at 18ms
2521        br.insert(rid(2), Duration::from_millis(25)); // region 2 smoothed worse than its raw 20ms
2522        // best_any = 18ms (region 1). old (region 2) RAW = 20ms. 20 - 18 = 2ms < 10ms → keepOld.
2523        assert_eq!(
2524            select_home_region(Some(rid(2)), &m, &br).unwrap(),
2525            rid(2),
2526            "old raw (20ms) within 10ms of smoothed-best (18ms) keeps via the absolute-diff arm"
2527        );
2528    }
2529}
2530
2531#[cfg(test)]
2532mod expiry_action_tests {
2533    use super::{ExpiryAction, expiry_action};
2534
2535    /// Not expired → `Running`, regardless of the other inputs (the gate fields are only consulted
2536    /// once the key is expired).
2537    #[test]
2538    fn not_expired_is_always_running() {
2539        for has_auth_key in [false, true] {
2540            for reauth_enabled in [false, true] {
2541                for tka_active in [false, true] {
2542                    assert_eq!(
2543                        expiry_action(false, has_auth_key, reauth_enabled, tka_active),
2544                        ExpiryAction::Running,
2545                        "a non-expired key is Running for any gate combination"
2546                    );
2547                }
2548            }
2549        }
2550    }
2551
2552    /// The ONLY input combination that auto-reauths: expired AND auth key retained AND reauth enabled
2553    /// AND TKA not enforcing.
2554    #[test]
2555    fn expired_with_authkey_reauth_enabled_and_no_tka_reauthenticates() {
2556        assert_eq!(
2557            expiry_action(true, true, true, false),
2558            ExpiryAction::Reauthenticate
2559        );
2560    }
2561
2562    /// Every other expired combination falls back to the terminal `Expired` (today's behavior, no
2563    /// regression): no auth key, reauth disabled, or TKA enforcing each independently forces Expired.
2564    #[test]
2565    fn expired_falls_back_to_expired_for_every_other_combination() {
2566        // The full expired-input matrix minus the single Reauthenticate cell above.
2567        for has_auth_key in [false, true] {
2568            for reauth_enabled in [false, true] {
2569                for tka_active in [false, true] {
2570                    let action = expiry_action(true, has_auth_key, reauth_enabled, tka_active);
2571                    if has_auth_key && reauth_enabled && !tka_active {
2572                        // The one Reauthenticate cell, asserted above.
2573                        assert_eq!(action, ExpiryAction::Reauthenticate);
2574                    } else {
2575                        assert_eq!(
2576                            action,
2577                            ExpiryAction::Expired,
2578                            "expired with has_auth_key={has_auth_key}, \
2579                             reauth_enabled={reauth_enabled}, tka_active={tka_active} must be Expired"
2580                        );
2581                    }
2582                }
2583            }
2584        }
2585    }
2586
2587    /// The TKA safety gate in isolation: even with an auth key and reauth enabled, an ACTIVE lock
2588    /// forces `Expired` (never rotate an unsigned key on a locked tailnet). This is the hard
2589    /// constraint from the design — pinned as its own test so a regression that drops the `!tka_active`
2590    /// term is caught explicitly.
2591    #[test]
2592    fn tka_active_forces_expired_even_when_reauth_would_otherwise_fire() {
2593        assert_eq!(
2594            expiry_action(true, true, true, true),
2595            ExpiryAction::Expired,
2596            "an enforcing Tailnet Lock must veto auto-reauth (unsigned-key lockout safety gate)"
2597        );
2598    }
2599
2600    /// No auth key forces `Expired`: there is nothing to non-interactively re-register with, so even
2601    /// with reauth enabled and no lock the node goes terminal (unchanged from today).
2602    #[test]
2603    fn no_auth_key_forces_expired() {
2604        assert_eq!(
2605            expiry_action(true, false, true, false),
2606            ExpiryAction::Expired
2607        );
2608    }
2609
2610    /// The config opt-out: `reauth_on_expiry=false` forces `Expired` even with an auth key and no
2611    /// lock (the conservative posture / historical behavior).
2612    #[test]
2613    fn reauth_disabled_forces_expired() {
2614        assert_eq!(
2615            expiry_action(true, true, false, false),
2616            ExpiryAction::Expired
2617        );
2618    }
2619}
2620
2621#[cfg(test)]
2622mod reauth_circuit_tests {
2623    use super::{ExpiryAction, MAX_REAUTH_ATTEMPTS, ReauthState, reauth_circuit_step};
2624
2625    /// Entering reauth (a `Reauthenticate` verdict while NOT already reauthenticating) fires the
2626    /// one-shot reauth and starts the counter at 1.
2627    #[test]
2628    fn enter_reauth_fires_once_and_starts_counter() {
2629        let step = reauth_circuit_step(ExpiryAction::Reauthenticate, false, 0);
2630        assert_eq!(step.next, ReauthState::Reauthenticating);
2631        assert_eq!(
2632            step.attempts, 1,
2633            "the entering attempt starts the counter at 1"
2634        );
2635        assert!(step.fire_reauth, "entry fires the one-shot Command::Reauth");
2636    }
2637
2638    /// A subsequent expired self-node while ALREADY reauthenticating (prior reauth not recovered)
2639    /// counts up but does NOT re-fire — re-firing would rotate the node key a second time and lose the
2640    /// original `OldNodeKey` anchor.
2641    #[test]
2642    fn still_reauthing_counts_but_does_not_refire() {
2643        let step = reauth_circuit_step(ExpiryAction::Reauthenticate, true, 1);
2644        assert_eq!(step.next, ReauthState::Reauthenticating);
2645        assert_eq!(
2646            step.attempts, 2,
2647            "a non-recovering reauth increments the counter"
2648        );
2649        assert!(
2650            !step.fire_reauth,
2651            "must NOT re-fire reauth while already reauthenticating (no second rotation)"
2652        );
2653    }
2654
2655    /// At `MAX_REAUTH_ATTEMPTS` consecutive non-recovering reauths, the breaker trips to the terminal
2656    /// `Expired` and stops re-arming reauth (the one-shot auth-key case settles instead of looping).
2657    #[test]
2658    fn trips_to_expired_at_cap() {
2659        // One step below the cap still stays reauthenticating.
2660        let below =
2661            reauth_circuit_step(ExpiryAction::Reauthenticate, true, MAX_REAUTH_ATTEMPTS - 2);
2662        assert_eq!(below.next, ReauthState::Reauthenticating);
2663        assert!(!below.fire_reauth);
2664
2665        // The step that reaches the cap flips to terminal Expired and does not fire.
2666        let at_cap =
2667            reauth_circuit_step(ExpiryAction::Reauthenticate, true, MAX_REAUTH_ATTEMPTS - 1);
2668        assert_eq!(at_cap.attempts, MAX_REAUTH_ATTEMPTS);
2669        assert_eq!(
2670            at_cap.next,
2671            ReauthState::Expired,
2672            "at the cap the circuit breaker trips to terminal Expired"
2673        );
2674        assert!(
2675            !at_cap.fire_reauth,
2676            "a tripped breaker never fires another reauth"
2677        );
2678    }
2679
2680    /// A good (non-expired) self-node resets the counter to 0 (the node recovered) — so a later,
2681    /// genuine expiry cycle gets a fresh full budget of attempts, never a stale leftover count.
2682    #[test]
2683    fn running_resets_counter() {
2684        let step = reauth_circuit_step(ExpiryAction::Running, true, MAX_REAUTH_ATTEMPTS);
2685        assert_eq!(step.next, ReauthState::Running);
2686        assert_eq!(
2687            step.attempts, 0,
2688            "recovery to Running resets the attempt counter"
2689        );
2690        assert!(!step.fire_reauth);
2691    }
2692
2693    /// The non-reauth terminal path (`expiry_action` → `Expired`: no auth key / reauth disabled /
2694    /// TKA-locked) reports `Expired` and never fires reauth; the counter is irrelevant (this path
2695    /// never armed the machine), so it resets to 0.
2696    #[test]
2697    fn expired_action_is_terminal_without_firing() {
2698        let step = reauth_circuit_step(ExpiryAction::Expired, false, 0);
2699        assert_eq!(step.next, ReauthState::Expired);
2700        assert!(!step.fire_reauth);
2701        assert_eq!(step.attempts, 0);
2702    }
2703
2704    /// The full episode as the handler drives it, feeding each step's `attempts` into the next: a
2705    /// one-shot auth key that never recovers fires reauth exactly ONCE, counts each repeated expired
2706    /// self-node, and settles on terminal `Expired` at the cap — never an indefinite `Reauthenticating`
2707    /// spell and never a second rotation.
2708    #[test]
2709    fn full_episode_one_shot_key_settles_at_expired_after_one_fire() {
2710        // Step 1: first expired self-node (state was Running → not already reauthing): enter + fire.
2711        let s1 = reauth_circuit_step(ExpiryAction::Reauthenticate, false, 0);
2712        assert_eq!(s1.next, ReauthState::Reauthenticating);
2713        assert!(s1.fire_reauth);
2714        let mut attempts = s1.attempts;
2715        let mut fires = 1; // counted the one fire
2716
2717        // Steps 2..: still expired while reauthenticating — count only, never re-fire — until the cap.
2718        loop {
2719            let s = reauth_circuit_step(ExpiryAction::Reauthenticate, true, attempts);
2720            if s.fire_reauth {
2721                fires += 1;
2722            }
2723            attempts = s.attempts;
2724            if s.next == ReauthState::Expired {
2725                break;
2726            }
2727            assert_eq!(s.next, ReauthState::Reauthenticating);
2728            assert!(attempts < MAX_REAUTH_ATTEMPTS);
2729        }
2730
2731        assert_eq!(attempts, MAX_REAUTH_ATTEMPTS, "settles exactly at the cap");
2732        assert_eq!(
2733            fires, 1,
2734            "reauth (and thus a node-key rotation) fires exactly once across the whole episode"
2735        );
2736    }
2737
2738    /// Recovery then a fresh failing episode: `Reauthenticating → Running` (reset) → a later expiry
2739    /// re-enters and re-fires. Proves the reset gives the next episode a full attempt budget rather
2740    /// than carrying a stale count that would trip the breaker early.
2741    #[test]
2742    fn recovery_then_new_episode_re_fires() {
2743        // Episode 1 entry.
2744        let e1 = reauth_circuit_step(ExpiryAction::Reauthenticate, false, 0);
2745        assert!(e1.fire_reauth);
2746        // A non-recovering step, then recovery to Running resets.
2747        let mid = reauth_circuit_step(ExpiryAction::Reauthenticate, true, e1.attempts);
2748        assert_eq!(mid.attempts, 2);
2749        let recovered = reauth_circuit_step(ExpiryAction::Running, true, mid.attempts);
2750        assert_eq!(recovered.attempts, 0);
2751
2752        // Episode 2: a fresh expiry (state is Running again → not already reauthing) re-enters + fires.
2753        let e2 = reauth_circuit_step(ExpiryAction::Reauthenticate, false, recovered.attempts);
2754        assert_eq!(e2.next, ReauthState::Reauthenticating);
2755        assert_eq!(e2.attempts, 1, "the new episode starts fresh at 1");
2756        assert!(
2757            e2.fire_reauth,
2758            "a new episode after recovery fires reauth again"
2759        );
2760    }
2761}
2762
2763#[cfg(test)]
2764mod self_lockout_tests {
2765    use ts_tka::{AumHash, Authority, State};
2766
2767    use super::{SelfLockVerdict, self_lock_verdict};
2768
2769    fn node_key() -> ts_keys::NodePublicKey {
2770        ts_keys::NodePrivateKey::random().public_key()
2771    }
2772
2773    /// An empty key-signature is the "not signed yet" case: `Unsigned`, never a lockout warning —
2774    /// so a tailnet that simply has not signed this node does not spam a `warn`.
2775    #[test]
2776    fn empty_signature_is_unsigned_not_locked_out() {
2777        let authority = Authority::from_state(AumHash([0; 32]), State::default());
2778        assert_eq!(
2779            self_lock_verdict(&node_key(), &[], &authority),
2780            SelfLockVerdict::Unsigned
2781        );
2782    }
2783
2784    /// A non-empty key-signature that does not authorize self classifies as `LockedOut` — the
2785    /// operator-facing condition — and the verdict carries the verify error string for the log. Here
2786    /// the blob is non-empty (so we attempt verification rather than short-circuiting to `Unsigned`)
2787    /// but is not a valid NodeKeySignature CBOR (`0x01` decodes as a bare uint with trailing bytes),
2788    /// so `node_key_authorized` returns a `Decode` error → `LockedOut`. The cryptographic-rejection
2789    /// arms (`UntrustedKey` / `BadSignature` for a well-formed-but-untrusted NKS) are covered by
2790    /// `ts_tka`'s own `node_key_authorized` tests; this only needs to prove the runtime classifier
2791    /// routes a verify `Err` to `LockedOut`.
2792    #[test]
2793    fn unverifiable_signature_is_locked_out() {
2794        let authority = Authority::from_state(AumHash([0; 32]), State::default());
2795        let verdict = self_lock_verdict(&node_key(), &[0x01, 0x02, 0x03], &authority);
2796        assert!(
2797            matches!(verdict, SelfLockVerdict::LockedOut(_)),
2798            "a signature the lock cannot authorize must classify as LockedOut, got {verdict:?}"
2799        );
2800    }
2801}
2802
2803#[cfg(test)]
2804mod cached_replay_tests {
2805    //! The cold-start replay of a netmap cached under Tailnet Lock: which of its peers this node
2806    //! dials before control has answered.
2807    //!
2808    //! Go replays its cached map through `setNetMapLocked`, so `tkaFilterNetmapLocked`
2809    //! (`ipn/ipnlocal/tailnet-lock.go`, upstream `9ea7cba44591e0cd840c6c94d23274dd222059bf`) runs
2810    //! over it against the authority it re-opened from disk, and the peers holding a valid signature
2811    //! survive. These cover the same outcome here, over a chain persisted beside the netmap.
2812
2813    use ed25519_dalek::SigningKey;
2814    use ts_tka::{Aum, AumHash, AumKey, Authority, KeyKind, MemAumStore, NodeKeySignature};
2815
2816    use super::{TkaStatus, vouch_cached_peers};
2817    use crate::peer_tracker::tka_tests::peer_node;
2818
2819    /// The node key of the peer the lock authorizes in these tests.
2820    const SIGNED_PEER_KEY: [u8; 32] = [9u8; 32];
2821    /// The node key of the peer that presents nothing.
2822    const UNSIGNED_PEER_KEY: [u8; 32] = [10u8; 32];
2823
2824    /// A locked tailnet: a genesis checkpoint trusting `signer` (signed by it, so the chain verifies),
2825    /// plus the store and the [`Authority`] a completed sync would hold.
2826    fn locked_tailnet(signer: &SigningKey) -> (MemAumStore, AumHash, Authority) {
2827        let key = AumKey {
2828            kind: KeyKind::Ed25519,
2829            votes: 1,
2830            public: signer.verifying_key().to_bytes().to_vec(),
2831            meta: Vec::new(),
2832        };
2833        let mut genesis = Aum::new_genesis_checkpoint(vec![key], vec![vec![0x11; 32]])
2834            .expect("a well-formed genesis checkpoint");
2835        genesis.sign(signer);
2836        let oldest = genesis.hash();
2837        let store = MemAumStore::from_aums([genesis]);
2838        let authority = crate::tka_sync::authority_from_encoded_chain(
2839            &crate::tka_sync::encode_chain(&store, oldest).expect("encode"),
2840        )
2841        .expect("the chain verifies");
2842        (store, oldest, authority)
2843    }
2844
2845    /// The status control stamped on the netmap that was cached under `authority`.
2846    fn cached_lock(authority: &Authority) -> TkaStatus {
2847        TkaStatus {
2848            head: authority.head().to_base32(),
2849            disabled: false,
2850        }
2851    }
2852
2853    /// The headline: with the authority those peers were cached under, the cold start replays the
2854    /// peer that authority authorizes and drops the one it does not.
2855    ///
2856    /// Without the persisted authority this replays **nothing** — which is what made a locked
2857    /// tailnet lose the cache entirely, while Go kept dialing its authorized peers.
2858    #[test]
2859    fn a_persisted_authority_replays_the_peers_it_authorizes() {
2860        let signer = SigningKey::from_bytes(&[42u8; 32]);
2861        let (_store, _oldest, authority) = locked_tailnet(&signer);
2862
2863        let signed = peer_node(
2864            "signed-peer",
2865            SIGNED_PEER_KEY,
2866            NodeKeySignature::sign_direct(&SIGNED_PEER_KEY, &signer).serialize(),
2867        );
2868        let unsigned = peer_node("unsigned-peer", UNSIGNED_PEER_KEY, Vec::new());
2869
2870        let replayed = vouch_cached_peers(
2871            Some(&authority),
2872            &cached_lock(&authority),
2873            vec![signed, unsigned],
2874        );
2875
2876        assert_eq!(
2877            replayed
2878                .iter()
2879                .map(|p| p.stable_id.0.as_str())
2880                .collect::<Vec<_>>(),
2881            vec!["signed-peer"],
2882            "the peer the lock authorizes is dialed at cold start; the unsigned one is dropped"
2883        );
2884    }
2885
2886    /// No persisted authority (this node has never completed a sync, or the chain did not verify) ⇒
2887    /// no peers. There is nothing to check a signature against, and a peer the lock revoked while
2888    /// this node was off must not be dialed on the strength of a cache entry.
2889    #[test]
2890    fn without_an_authority_no_cached_peer_is_replayed() {
2891        let signer = SigningKey::from_bytes(&[42u8; 32]);
2892        let (_store, _oldest, authority) = locked_tailnet(&signer);
2893        let signed = peer_node(
2894            "signed-peer",
2895            SIGNED_PEER_KEY,
2896            NodeKeySignature::sign_direct(&SIGNED_PEER_KEY, &signer).serialize(),
2897        );
2898
2899        assert!(
2900            vouch_cached_peers(None, &cached_lock(&authority), vec![signed]).is_empty(),
2901            "a peer nothing can vouch for waits for control's first netmap"
2902        );
2903    }
2904
2905    /// A netmap cached on disk (raw `MapResponse` JSON, exactly what `NetmapCache` persists), in a
2906    /// directory private to this user so the cache's own vetting accepts it.
2907    #[cfg(unix)]
2908    fn cache_dir_with(label: &str, tka_info: &str, peers: &str) -> std::path::PathBuf {
2909        use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};
2910
2911        let dir = std::env::temp_dir().join(format!(
2912            "ts-rs-cached-replay-{}-{label}",
2913            std::process::id()
2914        ));
2915        std::fs::remove_dir_all(&dir).ok();
2916        std::fs::create_dir_all(&dir).expect("scratch dir");
2917        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).expect("chmod");
2918
2919        let body = format!(
2920            r#"{{
2921                {tka_info}
2922                "Node": {{
2923                    "ID": 1,
2924                    "StableID": "self-1",
2925                    "Name": "self.example.ts.net.",
2926                    "Addresses": ["100.64.0.1/32"],
2927                    "CapMap": {{"cache-network-maps": null}}
2928                }},
2929                "Peers": [{peers}],
2930                "DERPMap": {{ "Regions": {{ "3": {{
2931                    "RegionID": 3, "RegionCode": "tst", "RegionName": "Test", "Nodes": []
2932                }} }} }}
2933            }}"#
2934        );
2935        let mut file = std::fs::OpenOptions::new()
2936            .write(true)
2937            .create_new(true)
2938            .mode(0o600)
2939            .open(dir.join(ts_control::NETMAP_CACHE_FILE))
2940            .expect("cache file");
2941        std::io::Write::write_all(&mut file, body.as_bytes()).expect("write cached netmap");
2942        dir
2943    }
2944
2945    /// One cached peer, with no `KeySignature` — an unsigned peer, which a lock drops.
2946    #[cfg(unix)]
2947    const UNSIGNED_CACHED_PEER: &str = r#"{
2948        "ID": 2,
2949        "StableID": "peer-2",
2950        "Name": "peer.example.ts.net.",
2951        "Addresses": ["100.64.0.2/32"],
2952        "Endpoints": ["192.0.2.7:41641"],
2953        "HomeDERP": 3
2954    }"#;
2955
2956    /// End to end over the files a cold start actually finds: the persisted chain is read from the
2957    /// cache directory, re-verified, and used to judge the cached peers — an unsigned one is dropped
2958    /// while the rest of the netmap replays.
2959    ///
2960    /// The *admit* side is proven on [`vouch_cached_peers`] directly rather than here: a cached
2961    /// frame's `KeySignature` decodes to the raw bytes of its JSON string, so a real signature (64
2962    /// arbitrary bytes inside a CBOR structure) cannot be written into a JSON fixture at all.
2963    #[cfg(unix)]
2964    #[tokio::test]
2965    async fn a_cold_start_judges_the_cached_peers_against_the_persisted_chain() {
2966        let signer = SigningKey::from_bytes(&[42u8; 32]);
2967        let (store, oldest, authority) = locked_tailnet(&signer);
2968        let dir = cache_dir_with(
2969            "with-chain",
2970            &format!(
2971                r#""TKAInfo": {{ "Head": "{}", "Disabled": false }},"#,
2972                authority.head().to_base32()
2973            ),
2974            UNSIGNED_CACHED_PEER,
2975        );
2976        let cache = ts_control::NetmapCache::new(&dir);
2977        cache
2978            .store_tka_chain(&crate::tka_sync::encode_chain(&store, oldest).expect("encode"))
2979            .await;
2980
2981        let replayed = super::load_cached_netmap(&cache)
2982            .await
2983            .expect("the cached netmap replays");
2984
2985        assert!(
2986            replayed.peer_update.is_none(),
2987            "an unsigned peer is dropped by the same filter the live netmap runs, got {:?}",
2988            replayed.peer_update
2989        );
2990        assert!(
2991            replayed.node.is_some() && replayed.derp.is_some(),
2992            "the rest of the netmap carries no peer identity and still replays"
2993        );
2994
2995        std::fs::remove_dir_all(&dir).ok();
2996    }
2997
2998    /// A netmap cached while the lock was **off** replays whole: there is no authority to consult and
2999    /// nothing to enforce (Go's filter returns early on `b.tka == nil`).
3000    #[cfg(unix)]
3001    #[tokio::test]
3002    async fn a_cold_start_without_a_lock_replays_every_cached_peer() {
3003        let dir = cache_dir_with("no-lock", "", UNSIGNED_CACHED_PEER);
3004
3005        let replayed = super::load_cached_netmap(&ts_control::NetmapCache::new(&dir))
3006            .await
3007            .expect("the cached netmap replays");
3008
3009        assert!(
3010            matches!(replayed.peer_update, Some(ts_control::PeerUpdate::Full(ref p)) if p.len() == 1),
3011            "an unlocked tailnet replays its cached peers untouched: {:?}",
3012            replayed.peer_update
3013        );
3014
3015        std::fs::remove_dir_all(&dir).ok();
3016    }
3017
3018    /// A chain that does not verify is no authority at all, so the cached peers are withheld — the
3019    /// same outcome as never having persisted one. The netmap around them still replays.
3020    #[cfg(unix)]
3021    #[tokio::test]
3022    async fn a_cold_start_withholds_peers_when_the_persisted_chain_does_not_verify() {
3023        let signer = SigningKey::from_bytes(&[42u8; 32]);
3024        let (_store, _oldest, authority) = locked_tailnet(&signer);
3025        let tka_info = format!(
3026            r#""TKAInfo": {{ "Head": "{}", "Disabled": false }},"#,
3027            authority.head().to_base32()
3028        );
3029
3030        // No chain at all.
3031        let dir = cache_dir_with("no-chain", &tka_info, UNSIGNED_CACHED_PEER);
3032        let replayed = super::load_cached_netmap(&ts_control::NetmapCache::new(&dir))
3033            .await
3034            .expect("the cached netmap replays");
3035        assert!(replayed.peer_update.is_none());
3036        assert!(replayed.node.is_some());
3037        std::fs::remove_dir_all(&dir).ok();
3038
3039        // A chain blob that is not a verified chain.
3040        let dir = cache_dir_with("bad-chain", &tka_info, UNSIGNED_CACHED_PEER);
3041        let cache = ts_control::NetmapCache::new(&dir);
3042        cache.store_tka_chain(b"ts-tka-chain-v1\nAQID").await;
3043        let replayed = super::load_cached_netmap(&cache)
3044            .await
3045            .expect("the cached netmap replays");
3046        assert!(replayed.peer_update.is_none());
3047        assert!(replayed.node.is_some());
3048        std::fs::remove_dir_all(&dir).ok();
3049    }
3050
3051    /// A chain that is not at the head the cached frame recorded describes a different lock — a
3052    /// disable-and-re-enable under a fresh genesis, or a crash between writing the netmap and syncing
3053    /// the chain that followed it. It vouches for nothing.
3054    #[test]
3055    fn a_chain_at_another_head_vouches_for_nothing() {
3056        let signer = SigningKey::from_bytes(&[42u8; 32]);
3057        let (_store, _oldest, authority) = locked_tailnet(&signer);
3058        let signed = peer_node(
3059            "signed-peer",
3060            SIGNED_PEER_KEY,
3061            NodeKeySignature::sign_direct(&SIGNED_PEER_KEY, &signer).serialize(),
3062        );
3063
3064        // Another lock's head: valid base32, not ours.
3065        let other = TkaStatus {
3066            head: AumHash([0x5a; 32]).to_base32(),
3067            disabled: false,
3068        };
3069        assert!(vouch_cached_peers(Some(&authority), &other, vec![signed.clone()]).is_empty());
3070
3071        // A head control did not send, or one this node cannot parse, is not a match either.
3072        for head in ["", "not base32"] {
3073            let malformed = TkaStatus {
3074                head: head.to_string(),
3075                disabled: false,
3076            };
3077            assert!(
3078                vouch_cached_peers(Some(&authority), &malformed, vec![signed.clone()]).is_empty(),
3079                "a head that does not parse must not be treated as matching ({head:?})"
3080            );
3081        }
3082    }
3083}