Skip to main content

ts_runtime/
control_runner.rs

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