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