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