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        /// Whether the current map poll has received a response and is still live.
973        #[message]
974        pub fn control_connected(&self) -> bool {
975            self.client.is_connected()
976        }
977
978        /// Fetch the IPv4 address for this tailscale device.
979        #[message(ctx)]
980        pub fn ipv4(
981            &self,
982            ctx: &mut Context<Self, DelegatedReply<Option<Ipv4Addr>>>,
983        ) -> DelegatedReply<Option<Ipv4Addr>> {
984            let (deleg, replier) = ctx.reply_sender();
985
986            if let Some(replier) = replier {
987                let fut = self.with_self_node(|node| node.tailnet_address.ipv4.addr());
988
989                tokio::spawn(async move {
990                    let ip = fut.await;
991                    replier.send(ip);
992                });
993            }
994
995            deleg
996        }
997
998        /// Fetch the IPv6 address for this tailscale device.
999        #[message(ctx)]
1000        pub fn ipv6(
1001            &self,
1002            ctx: &mut Context<Self, DelegatedReply<Option<Ipv6Addr>>>,
1003        ) -> DelegatedReply<Option<Ipv6Addr>> {
1004            let (deleg, replier) = ctx.reply_sender();
1005
1006            if let Some(replier) = replier {
1007                let fut = self.with_self_node(|node| node.tailnet_address.ipv6.addr());
1008
1009                tokio::spawn(async move {
1010                    let ip = fut.await;
1011                    replier.send(ip);
1012                });
1013            }
1014
1015            deleg
1016        }
1017
1018        /// Fetch the self node for this tailscale device.
1019        #[message(ctx)]
1020        pub fn self_node(
1021            &self,
1022            ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
1023        ) -> DelegatedReply<Option<Node>> {
1024            let (deleg, replier) = ctx.reply_sender();
1025
1026            if let Some(replier) = replier {
1027                let node = self.with_self_node(|node| node.clone());
1028
1029                tokio::spawn(async move {
1030                    let node = node.await;
1031                    replier.send(node)
1032                });
1033            }
1034
1035            deleg
1036        }
1037
1038        /// Fetch the current Tailscale SSH policy, if control has pushed one.
1039        ///
1040        /// Returns `None` when control has not sent an SSH policy (the SSH server treats this as
1041        /// deny-all — fail-closed). Unlike `self_node` this does not block waiting
1042        /// for a value: an absent policy is a legitimate, immediate answer.
1043        #[message]
1044        pub fn current_ssh_policy(&self) -> Option<SshPolicy> {
1045            self.ssh_policy.borrow().clone()
1046        }
1047
1048        /// Fetch the current Tailnet Lock status, if control has pushed one.
1049        ///
1050        /// Returns `None` when control has sent no `TKAInfo` (tailnet lock not in use / no change seen).
1051        #[message]
1052        pub fn current_tka_status(&self) -> Option<TkaStatus> {
1053            self.tka.borrow().clone()
1054        }
1055
1056        /// Read up to `limit` entries of the Tailnet-Lock update-chain log, **head-first** (newest →
1057        /// oldest), from the locally-synced AUM chain (Go `NetworkLockLog`).
1058        ///
1059        /// A **pure local read** — no crypto, no mutation, no control round-trip: it walks the
1060        /// already-verified `SyncedTka` store this actor owns. Returns an empty `Vec` when no lock is
1061        /// synced (Go's `b.tka == nil`). Synchronous (no spawn), like `current_tka_status` — the
1062        /// chain is in memory.
1063        #[message]
1064        pub fn tka_log(&self, limit: usize) -> Vec<crate::tka_sync::TkaLogEntry> {
1065            let Some(synced) = self.tka_synced.as_ref() else {
1066                return Vec::new();
1067            };
1068            crate::tka_sync::tka_log_entries(&synced.store, synced.oldest, limit)
1069        }
1070
1071        /// Sign `node_key` directly with this node's network-lock key and submit the signature to
1072        /// control (Go `tka.sign` for the Direct case → `tkaSubmitSignature`).
1073        ///
1074        /// Builds a `Direct` [`NodeKeySignature`](ts_tka::NodeKeySignature) via
1075        /// [`sign_direct`](ts_tka::NodeKeySignature::sign_direct) over this node's inner ed25519
1076        /// network-lock signing key, serializes it (raw CBOR), and POSTs it to `/machine/tka/sign`.
1077        /// Mirrors `set_dns`/`get_certificate`: clones the control config + node keys into a spawned
1078        /// task (delegated reply, so the round-trip doesn't block the mailbox) over a fresh Noise
1079        /// channel.
1080        ///
1081        /// **Posture: this only *submits* a signature to control — it does NOT mutate the local
1082        /// [`Authority`](ts_tka::Authority).** The local trusted-key state advances solely through the
1083        /// existing verified-sync path (`sync_tka` → `VerifiedAumChain::verify`); a `tka_sign` success
1084        /// is acknowledged to the caller, and the resulting AUM is picked up on the next netmap-driven
1085        /// sync. Verify-and-log is unchanged.
1086        #[message(ctx)]
1087        pub fn tka_sign(
1088            &self,
1089            ctx: &mut Context<Self, DelegatedReply<Result<(), TkaSyncError>>>,
1090            node_key: [u8; 32],
1091        ) -> DelegatedReply<Result<(), TkaSyncError>> {
1092            let (deleg, replier) = ctx.reply_sender();
1093
1094            if let Some(replier) = replier {
1095                let config = self.params.config.clone();
1096                let keys = self.params.env.keys.clone();
1097                tokio::spawn(async move {
1098                    // Sign the node key with our network-lock key, then submit the raw-CBOR NKS.
1099                    let nks = ts_tka::NodeKeySignature::sign_direct(
1100                        &node_key,
1101                        &keys.network_lock_keys.private.signing_key(),
1102                    );
1103                    let req = ts_control::TkaSubmitSignatureRequest {
1104                        // node_key + version are stamped by the RPC client from `keys`.
1105                        version: Default::default(),
1106                        node_key: keys.node_keys.public,
1107                        signature: nks.serialize(),
1108                    };
1109                    let result = tka_submit_signature(
1110                        &config.server_url,
1111                        &keys,
1112                        req,
1113                        config.allow_http_key_fetch,
1114                    )
1115                    .await
1116                    .map(|_response| ());
1117                    replier.send(result);
1118                });
1119            }
1120
1121            deleg
1122        }
1123
1124        /// Disable Tailnet Lock by presenting the disablement secret to control (Go
1125        /// `tka.disable` → `/machine/tka/disable`).
1126        ///
1127        /// Targets the **current** authority head (read from the cached [`TkaStatus`]); the caller
1128        /// supplies the `disablement_secret` out of band (it is the operator-held capability that
1129        /// authorizes turning the lock off). Mirrors `tka_sign`: clones config + keys into a spawned
1130        /// task (delegated reply). Returns [`TkaSyncError::Unsupported`] when there is no known TKA
1131        /// head (lock not in use / control hasn't pushed a status), since there is nothing to disable.
1132        ///
1133        /// **Submit-only, like `tka_sign`:** this POSTs the disablement to control and does NOT mutate
1134        /// the local [`Authority`](ts_tka::Authority). Control acts on the disablement; this node
1135        /// observes the result through the existing verified-sync path. Verify-and-log unchanged.
1136        #[message(ctx)]
1137        pub fn tka_disable(
1138            &self,
1139            ctx: &mut Context<Self, DelegatedReply<Result<(), TkaSyncError>>>,
1140            disablement_secret: Vec<u8>,
1141        ) -> DelegatedReply<Result<(), TkaSyncError>> {
1142            let (deleg, replier) = ctx.reply_sender();
1143
1144            if let Some(replier) = replier {
1145                // Read the current head from the cached status BEFORE the spawn (can't borrow &self
1146                // across the await). No head ⇒ no lock to disable ⇒ Unsupported.
1147                let head = self.tka.borrow().as_ref().map(|s| s.head.clone());
1148                let config = self.params.config.clone();
1149                let keys = self.params.env.keys.clone();
1150                tokio::spawn(async move {
1151                    let result = match head {
1152                        Some(head) => {
1153                            let req = ts_control::TkaDisableRequest {
1154                                // node_key + version are stamped by the RPC client from `keys`.
1155                                version: Default::default(),
1156                                node_key: keys.node_keys.public,
1157                                head,
1158                                disablement_secret,
1159                            };
1160                            tka_disable(&config.server_url, &keys, req, config.allow_http_key_fetch)
1161                                .await
1162                                .map(|_response| ())
1163                        }
1164                        None => Err(TkaSyncError::Unsupported),
1165                    };
1166                    replier.send(result);
1167                });
1168            }
1169
1170            deleg
1171        }
1172
1173        /// Initialize Tailnet Lock with this node as the sole initial trusted key, gated by
1174        /// `disablement_secret` (Go `LocalClient.NetworkLockInit` — the "lock yourself in" case).
1175        ///
1176        /// Builds + signs a genesis Checkpoint AUM whose only trusted key is this node's network-lock
1177        /// public key (votes 1) and whose single DisablementValue is `disablement_value(secret)`, then
1178        /// drives the two-phase init: `tka/init/begin` (submit the genesis) → if control needs no
1179        /// further node signatures (`NeedSignatures` empty, the case when this node is the only key) →
1180        /// `tka/init/finish` carrying the raw `disablement_secret` as `SupportDisablement`. Mirrors
1181        /// `tka_sign`/`tka_disable`: cloned config + keys into a spawned task (delegated reply).
1182        ///
1183        /// If control returns a non-empty `NeedSignatures` (other nodes must be re-signed under the new
1184        /// lock — a multi-node tailnet), this returns [`TkaSyncError::Unsupported`]: re-signing each
1185        /// listed node (incl. the Rotation-key case) is a larger flow deferred to a fuller
1186        /// `tka_init(keys, secrets)` — the single-node lock-init is the shipped subset.
1187        ///
1188        /// **Submit-only**, like `tka_sign`/`tka_disable`: this creates the lock at control and does
1189        /// NOT seed the local [`Authority`](ts_tka::Authority) — the node picks up the new lock through
1190        /// the existing verified netmap-sync (control pushes a `TKAInfo`, `maybe_sync_tka` bootstraps
1191        /// the genesis through `VerifiedAumChain::verify`). Verify-and-log posture unchanged.
1192        #[message(ctx)]
1193        pub fn tka_init(
1194            &self,
1195            ctx: &mut Context<Self, DelegatedReply<Result<(), TkaSyncError>>>,
1196            disablement_secret: Vec<u8>,
1197        ) -> DelegatedReply<Result<(), TkaSyncError>> {
1198            let (deleg, replier) = ctx.reply_sender();
1199
1200            if let Some(replier) = replier {
1201                let config = self.params.config.clone();
1202                let keys = self.params.env.keys.clone();
1203                tokio::spawn(async move {
1204                    let result = tka_init_run(&config, &keys, disablement_secret).await;
1205                    replier.send(result);
1206                });
1207            }
1208
1209            deleg
1210        }
1211
1212        /// The cert-eligible DNS names from control's netmap DNS config (Go `nm.DNS.CertDomains`).
1213        ///
1214        /// Returns an empty `Vec` when control has sent no DNS config, or one carrying no cert
1215        /// domains (an empty list is a legitimate, immediate answer — like `current_ssh_policy`, this
1216        /// does not block waiting for a value).
1217        #[message]
1218        pub fn cert_domains(&self) -> Vec<String> {
1219            self.cert_domains.borrow().clone()
1220        }
1221
1222        /// The full DNS config from control's netmap (Go `netmap.NetworkMap.DNS`), or `None` when
1223        /// control has sent no DNS config yet. An immediate answer (does not block); the facade
1224        /// surfaces this for `Device::dns_config` (the daemon's `tnet dns status`).
1225        #[message]
1226        pub fn dns_config(&self) -> Option<ts_control::DnsConfig> {
1227            self.dns_config.borrow().clone()
1228        }
1229
1230        /// The interactive-login / consent URL control last asked this node to open
1231        /// (`MapResponse.PopBrowserURL`), or `None` when control has sent none. An immediate answer
1232        /// (does not block); the facade surfaces this for `Device::pop_browser_url`.
1233        #[message]
1234        pub fn pop_browser_url(&self) -> Option<url::Url> {
1235            self.pop_browser_url.borrow().clone()
1236        }
1237
1238        /// Subscribe to the interactive-login / consent URL cell (`MapResponse.PopBrowserURL`).
1239        ///
1240        /// Returns a [`watch::Receiver`] whose value is the latest running-node consent URL, used by
1241        /// [`Runtime::watch_ipn_bus`](crate::Runtime::watch_ipn_bus) to surface `browse_to_url`
1242        /// events mid-session. The cell is sticky (updated only on a new non-empty URL, never reset
1243        /// to `None` by an empty update — see the field docs), so a subscriber is not thrashed and a
1244        /// late subscriber sees the current URL. The initial value is `None` until control sends one.
1245        #[message(derive(Clone))]
1246        pub fn watch_browser_url(&self) -> watch::Receiver<Option<url::Url>> {
1247            self.pop_browser_url.subscribe()
1248        }
1249
1250        /// Subscribe to the self-node cell: the latest self node control sent, `None` until the
1251        /// first one arrives. [`Runtime::watch_ipn_bus`](crate::Runtime::watch_ipn_bus) watches it
1252        /// so a netmap update that moves only this node (key-expiry extension, rename, reassigned
1253        /// addresses) still reaches bus watchers as a `net_map` tick, as Go's `Notify.SelfChange`
1254        /// does.
1255        #[message(derive(Clone))]
1256        pub fn watch_self_node(&self) -> watch::Receiver<Option<Node>> {
1257            self.self_node.subscribe()
1258        }
1259
1260        /// The latest network-conditions report (preferred DERP region + per-region latencies). An
1261        /// immediate answer (does not block); empty before the first DERP-latency measurement. The
1262        /// facade surfaces this for `Device::netcheck` (the daemon's `tnet netcheck`).
1263        #[message]
1264        pub fn netcheck(&self) -> crate::status::NetcheckReport {
1265            self.netcheck.borrow().clone()
1266        }
1267
1268        /// The lowest latency seen for each DERP region across the retained measurement history —
1269        /// the Rust analog of Go `netcheck.Client.RecentRegionLatency()`, and what
1270        /// [`Runtime::suggest_exit_node`](crate::Runtime::suggest_exit_node) ranks exit-node
1271        /// candidates on.
1272        ///
1273        /// Ranking on this rather than on the newest report is the whole point: every measurement
1274        /// this fork makes is *partial* (`ts_netcheck::Config::complete_threshold` ends it once
1275        /// three regions have answered), so the newest report names a handful of regions and a
1276        /// candidate homed anywhere else would be ranked against nothing — collapsing the
1277        /// suggestion to a uniform random pick. The union over the retained window gives every
1278        /// region a recent latency to be ranked on.
1279        ///
1280        /// The window (`DERP_HISTORY_MAX_AGE`) is re-applied *here*, at read time, not just when
1281        /// a measurement lands: the history is only pruned on arrival, so a node that has gone
1282        /// quiet must not serve latencies that have since aged out. An immediate answer (does not
1283        /// block); empty before the first DERP-latency measurement.
1284        #[message]
1285        pub fn recent_region_latency(&self) -> HashMap<ts_derp::RegionId, Duration> {
1286            best_recent(
1287                &self.derp_report_history,
1288                Instant::now(),
1289                DERP_HISTORY_MAX_AGE,
1290            )
1291        }
1292
1293        /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
1294        ///
1295        /// Opens a fresh Noise channel and POSTs `/machine/id-token`; returns the signed JWT or an
1296        /// [`IdTokenError`]. Runs on a spawned task (delegated reply) so the actor mailbox isn't blocked
1297        /// for the round-trip.
1298        #[message(ctx)]
1299        pub fn fetch_id_token(
1300            &self,
1301            ctx: &mut Context<Self, DelegatedReply<Result<String, IdTokenError>>>,
1302            audience: String,
1303        ) -> DelegatedReply<Result<String, IdTokenError>> {
1304            let (deleg, replier) = ctx.reply_sender();
1305
1306            if let Some(replier) = replier {
1307                let config = self.params.config.clone();
1308                let keys = self.params.env.keys.clone();
1309                tokio::spawn(async move {
1310                    let result = ts_control::fetch_id_token(&config, &keys, &audience).await;
1311                    replier.send(result);
1312                });
1313            }
1314
1315            deleg
1316        }
1317
1318        /// Log this node out of the tailnet: deregister it by expiring its current node key.
1319        ///
1320        /// Mirrors `fetch_id_token`: clones the control config + node keys
1321        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox) and
1322        /// re-POSTs `/machine/register` with a past expiry over a fresh Noise channel. This is a
1323        /// control-plane state change only — it does NOT stop this actor or tear down the datapath
1324        /// (the caller follows up with the normal runtime shutdown), and it does not touch the
1325        /// on-disk node key, so re-registering with the same key is the re-login path.
1326        #[message(ctx)]
1327        pub fn logout(
1328            &self,
1329            ctx: &mut Context<Self, DelegatedReply<Result<(), LogoutError>>>,
1330        ) -> DelegatedReply<Result<(), LogoutError>> {
1331            let (deleg, replier) = ctx.reply_sender();
1332
1333            if let Some(replier) = replier {
1334                let config = self.params.config.clone();
1335                let keys = self.params.env.keys.clone();
1336                tokio::spawn(async move {
1337                    let result = ts_control::logout(&config, &keys).await;
1338                    replier.send(result);
1339                });
1340            }
1341
1342            deleg
1343        }
1344
1345        /// Publish a DNS record for this node via control's `/machine/set-dns` (Go
1346        /// `LocalClient.SetDNS`).
1347        ///
1348        /// Mirrors `fetch_id_token`: clones the control config + node keys
1349        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox) and
1350        /// POSTs the record over a fresh Noise channel. Go's `SetDNS` is `TXT`-only (its sole use is
1351        /// the ACME DNS-01 `_acme-challenge` record); the record type is fixed to `"TXT"` here to
1352        /// match, so the surfaced API takes only `name` + `value`.
1353        #[message(ctx)]
1354        pub fn set_dns(
1355            &self,
1356            ctx: &mut Context<Self, DelegatedReply<Result<(), SetDnsError>>>,
1357            name: String,
1358            value: String,
1359        ) -> DelegatedReply<Result<(), SetDnsError>> {
1360            let (deleg, replier) = ctx.reply_sender();
1361
1362            if let Some(replier) = replier {
1363                let config = self.params.config.clone();
1364                let keys = self.params.env.keys.clone();
1365                tokio::spawn(async move {
1366                    let result = ts_control::set_dns(&config, &keys, &name, "TXT", &value).await;
1367                    replier.send(result);
1368                });
1369            }
1370
1371            deleg
1372        }
1373    }
1374
1375    /// The reply type of the [`get_cert_pair`](ControlRunner::get_cert_pair) message: the issued
1376    /// `(cert_chain_pem, key_pem)` PEM pair (the `tnet cert` surface) or a [`ts_control::CertError`].
1377    /// Aliased so the message's `Context` type stays under clippy's `type_complexity` bar (the
1378    /// nested `Result<(String, String), _>` trips it inline).
1379    #[cfg(feature = "acme")]
1380    pub type CertPairReply = Result<(String, String), ts_control::CertError>;
1381
1382    // The `acme`-gated cert-issuance message lives in its own `#[kameo::messages]` impl block so the
1383    // proc-macro never sees it in a non-`acme` build (a `#[cfg]` *inside* a single messages-impl
1384    // block is not honored by the macro's generated dispatch — it would emit a `GetCertificate`
1385    // handler calling a `get_certificate` method that the same `#[cfg]` strips). A separate gated
1386    // block keeps the default build clean.
1387    #[cfg(feature = "acme")]
1388    #[kameo::messages]
1389    impl ControlRunner {
1390        /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` via the
1391        /// client-side ACME DNS-01 engine (`acme` feature).
1392        ///
1393        /// Mirrors `fetch_id_token`: clones the control config + node keys
1394        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox), loads
1395        /// or generates the ACME account key, and runs issuance against Let's Encrypt production,
1396        /// publishing the DNS-01 challenge TXT through the node's `POST /machine/set-dns` RPC.
1397        ///
1398        /// The account key is loaded from [`ts_keys::NodeState::acme_account_key`] (PKCS#8 DER) when
1399        /// present, so the same ACME account persists across renewals; otherwise an ephemeral key is
1400        /// generated for this call only (a fresh ACME account each issuance — acceptable for v1; LE
1401        /// allows it). Persisting a generated key back into the key file is the embedder's job (no
1402        /// write-back path here). SaaS-only: against a self-hosted control plane the set-dns
1403        /// publish 501s.
1404        #[message(ctx)]
1405        pub fn get_certificate(
1406            &self,
1407            ctx: &mut Context<
1408                Self,
1409                DelegatedReply<Result<ts_control::tls::CertifiedKey, ts_control::CertError>>,
1410            >,
1411            name: String,
1412        ) -> DelegatedReply<Result<ts_control::tls::CertifiedKey, ts_control::CertError>> {
1413            let (deleg, replier) = ctx.reply_sender();
1414
1415            if let Some(replier) = replier {
1416                let config = self.params.config.clone();
1417                let keys = self.params.env.keys.clone();
1418                tokio::spawn(async move {
1419                    let result = issue_certificate(&config, &keys, &name).await;
1420                    replier.send(result);
1421                });
1422            }
1423
1424            deleg
1425        }
1426
1427        /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` and return the
1428        /// **PEM pair** — `(cert_chain_pem, key_pem)` — for writing the on-disk `.crt` + `.key`
1429        /// (the daemon's `tnet cert`, Go's `LocalClient.CertPair`). `acme` feature.
1430        ///
1431        /// Identical issuance to [`get_certificate`](Self::get_certificate) (same client-side ACME
1432        /// DNS-01 flow, same set-dns publish, same account-key handling), only the *shape* of the
1433        /// result differs: this surfaces the raw chain + leaf-key PEMs instead of the opaque
1434        /// [`CertifiedKey`](ts_control::tls::CertifiedKey). The leaf **private key** PEM is the
1435        /// second tuple element and is NEVER logged — the spawned task sends it straight back to the
1436        /// replier. SaaS-only: against a self-hosted control plane the set-dns publish 501s.
1437        #[message(ctx)]
1438        pub fn get_cert_pair(
1439            &self,
1440            ctx: &mut Context<Self, DelegatedReply<CertPairReply>>,
1441            name: String,
1442        ) -> DelegatedReply<CertPairReply> {
1443            let (deleg, replier) = ctx.reply_sender();
1444
1445            if let Some(replier) = replier {
1446                let config = self.params.config.clone();
1447                let keys = self.params.env.keys.clone();
1448                tokio::spawn(async move {
1449                    let result = issue_cert_pair(&config, &keys, &name).await;
1450                    replier.send(result);
1451                });
1452            }
1453
1454            deleg
1455        }
1456    }
1457}
1458
1459/// The `tka_init` body (the genesis-build + two-phase init/begin→init/finish choreography),
1460/// factored out of the actor handler so it runs in the spawned task. See [`ControlRunner::tka_init`].
1461///
1462/// "Lock yourself in": the genesis trusts only this node's network-lock key (votes 1) and stores one
1463/// DisablementValue = `disablement_value(secret)`. On a non-empty `NeedSignatures` (multi-node
1464/// tailnet needing re-signs) it returns [`TkaSyncError::Unsupported`] — the single-node subset.
1465async fn tka_init_run(
1466    config: &ts_control::Config,
1467    keys: &ts_keys::NodeState,
1468    disablement_secret: Vec<u8>,
1469) -> Result<(), TkaSyncError> {
1470    // Build the genesis: this node's NL public key as the sole trusted key, one disablement value.
1471    let nl_public = keys.network_lock_keys.public.to_bytes().to_vec();
1472    let genesis_key = ts_tka::AumKey {
1473        kind: ts_tka::KeyKind::Ed25519,
1474        votes: 1,
1475        public: nl_public,
1476        meta: Vec::new(),
1477    };
1478    let dvalue = ts_tka::disablement_value(&disablement_secret).to_vec();
1479    let mut genesis = ts_tka::Aum::new_genesis_checkpoint(vec![genesis_key], vec![dvalue])
1480        // A malformed genesis is a local construction bug, not a transient RPC failure — surface it as a
1481        // coarse internal error rather than NetworkError (which would invite a pointless retry).
1482        .map_err(|_| TkaSyncError::Internal(ts_control::TkaSyncInternalErrorKind::SerDe))?;
1483    genesis.sign(&keys.network_lock_keys.private.signing_key());
1484
1485    // Phase 1: submit the genesis. node_key + version are stamped by the RPC client from `keys`.
1486    let begin_req = ts_control::TkaInitBeginRequest {
1487        version: Default::default(),
1488        node_key: keys.node_keys.public,
1489        genesis_aum: genesis.serialize(),
1490    };
1491    let begin_resp = tka_init_begin(
1492        &config.server_url,
1493        keys,
1494        begin_req,
1495        config.allow_http_key_fetch,
1496    )
1497    .await?;
1498
1499    // Single-node case only: control must need no further node signatures. A non-empty
1500    // NeedSignatures means other nodes must be re-signed under the new lock — deferred.
1501    if !begin_resp.need_signatures.is_empty() {
1502        tracing::warn!(
1503            need = begin_resp.need_signatures.len(),
1504            "tka_init: control requires re-signing other nodes; the multi-node init is not yet \
1505             implemented (single-node lock-init only)"
1506        );
1507        return Err(TkaSyncError::Unsupported);
1508    }
1509
1510    // Phase 2: finish, carrying the raw disablement secret as SupportDisablement (Go sends the raw
1511    // secret here; only the genesis stores its Argon2i hash).
1512    let finish_req = ts_control::TkaInitFinishRequest {
1513        version: Default::default(),
1514        node_key: keys.node_keys.public,
1515        signatures: std::collections::BTreeMap::new(),
1516        support_disablement: disablement_secret,
1517    };
1518    tka_init_finish(
1519        &config.server_url,
1520        keys,
1521        finish_req,
1522        config.allow_http_key_fetch,
1523    )
1524    .await
1525    .map(|_response| ())
1526}
1527
1528/// Load or generate the ACME account key, then issue a cert for `name` via set-dns DNS-01,
1529/// returning just the ready-to-serve [`CertifiedKey`](ts_control::tls::CertifiedKey) (the
1530/// `get_certificate` / `ListenTLS` path).
1531///
1532/// Thin wrapper over [`issue_cert_pair`] that drops the PEMs — one issuance, this caller just
1533/// doesn't need the on-disk pair. See [`issue_cert_pair`] for the account-key handling.
1534#[cfg(feature = "acme")]
1535async fn issue_certificate(
1536    config: &ts_control::Config,
1537    keys: &ts_keys::NodeState,
1538    name: &str,
1539) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
1540    issue_cert_pair_inner(config, keys, name)
1541        .await
1542        .map(|issued| issued.certified)
1543}
1544
1545/// Load or generate the ACME account key, then issue a cert for `name` via set-dns DNS-01,
1546/// returning the **PEM pair** `(cert_chain_pem, key_pem)` for the daemon's on-disk `.crt`/`.key`
1547/// (`tnet cert`, Go `LocalClient.CertPair`).
1548///
1549/// Same single issuance as [`issue_certificate`]; only the result shape differs. The leaf
1550/// **private key** PEM is the second element and is NEVER logged here.
1551#[cfg(feature = "acme")]
1552async fn issue_cert_pair(
1553    config: &ts_control::Config,
1554    keys: &ts_keys::NodeState,
1555    name: &str,
1556) -> Result<(String, String), ts_control::CertError> {
1557    issue_cert_pair_inner(config, keys, name)
1558        .await
1559        .map(|issued| (issued.cert_chain_pem, issued.key_pem))
1560}
1561
1562/// Shared issuance core for [`issue_certificate`] and [`issue_cert_pair`]: load (or generate) the
1563/// ACME account key, target Let's Encrypt production, and run one DNS-01 issuance, returning the
1564/// full [`IssuedCert`](ts_control::acme::IssuedCert) so each caller projects out what it needs (one
1565/// ACME order, two consumers).
1566///
1567/// Reuses the persisted [`ts_keys::NodeState::acme_account_key`] (PKCS#8 DER) when present so the
1568/// same Let's Encrypt account survives renewals; otherwise generates an ephemeral per-call key
1569/// (logged at debug — a new ACME account each issuance, with no write-back). Always targets Let's
1570/// Encrypt production ([`ts_control::acme::LETS_ENCRYPT_PRODUCTION_DIRECTORY`]). Never logs the leaf
1571/// private key.
1572#[cfg(feature = "acme")]
1573async fn issue_cert_pair_inner(
1574    config: &ts_control::Config,
1575    keys: &ts_keys::NodeState,
1576    name: &str,
1577) -> Result<ts_control::acme::IssuedCert, ts_control::CertError> {
1578    let account_key = match keys.acme_account_key.as_deref() {
1579        Some(der) => ts_control::acme::AcmeAccountKey::from_pkcs8(der)?,
1580        None => {
1581            tracing::debug!(
1582                "no persisted ACME account key in key state; generating an ephemeral per-call key \
1583                 (a new ACME account this issuance — not persisted back)"
1584            );
1585            ts_control::acme::AcmeAccountKey::generate()?.0
1586        }
1587    };
1588    let directory = ts_control::acme::LETS_ENCRYPT_PRODUCTION_DIRECTORY
1589        .parse()
1590        .map_err(|e| {
1591            ts_control::CertError::Acme(format!("parsing Let's Encrypt directory URL: {e}"))
1592        })?;
1593    ts_control::issue_cert_pair_via_setdns(config, keys, name, &account_key, &directory).await
1594}
1595
1596/// Publish the cached netmap, if this node has one, onto the netmap bus.
1597///
1598/// The cold-start half of the netmap cache (Go `nodecap.CacheNetworkMaps`). Reads
1599/// [`Config::netmap_cache_dir`](ts_control::Config::netmap_cache_dir) — `None` means the embedder
1600/// configured no storage, so there is nothing to replay — and decodes whatever is there with the
1601/// same decoder the live map poll uses.
1602///
1603/// The read is deliberately **not** gated on the node attributes. Nothing is ever written without
1604/// the grant, so the presence of a cache is itself the record that control asked for one (Go makes
1605/// the same argument: at this point in start-up the client has not spoken to control yet, so the
1606/// grant is not knowable). If the grant has since been withdrawn, the first netmap of this session
1607/// says so and the cache is discarded then.
1608///
1609/// **Peers cached under Tailnet Lock are filtered, not withheld.** Go replays its cached map through
1610/// `tkaFilterNetmapLocked`, which it can do at cold start because its TKA authority is persisted on
1611/// disk; the peers that hold a valid signature survive and are dialed. This port persists the same
1612/// authority next to the cached netmap (see [`load_cached_netmap`]) and runs the same filter over the
1613/// cached peers. With no persisted authority to run it with — a cache written before this node ever
1614/// completed a TKA sync — the peers are withheld and control's first netmap brings them back moments
1615/// later, behind a synced authority.
1616///
1617/// The bus has no replay, so this reaches only subscribers already registered. Every netmap
1618/// subscriber is spawned by `Runtime::spawn` before the control runner and registers from its own
1619/// `on_start` with no I/O in the way, while this path awaits a file read first — so in practice the
1620/// subscribers are there. A subscriber that is not simply misses the head start and is brought
1621/// current by control's first netmap, which is exactly the behaviour of a node with no cache.
1622async fn replay_cached_netmap(params: &Params) {
1623    let Some(dir) = params.config.netmap_cache_dir.as_ref() else {
1624        return;
1625    };
1626
1627    let Some(update) = load_cached_netmap(&ts_control::NetmapCache::new(dir)).await else {
1628        return;
1629    };
1630
1631    let peers = match update.peer_update.as_ref() {
1632        Some(ts_control::PeerUpdate::Full(peers)) => peers.len(),
1633        _ => 0,
1634    };
1635    tracing::info!(peers, "replaying cached netmap on cold start");
1636
1637    if let Err(e) = params.env.publish(Arc::new(update)).await {
1638        tracing::warn!(error = %e, "publishing the cached netmap");
1639    }
1640}
1641
1642/// Read the cached netmap, vouching for its peers with the Tailnet-Lock authority persisted beside
1643/// it — the whole of the cold-start decision, with no actor state in it so it can be tested directly.
1644///
1645/// A netmap cached while the lock was **off** replays whole; there is nothing to enforce (Go's
1646/// `tkaFilterNetmapLocked` returns early on `b.tka == nil`). A netmap cached while the lock was
1647/// **on** replays exactly the peers
1648/// [`PeerTracker::tka_keep_verdicts`](crate::peer_tracker::PeerTracker::tka_keep_verdicts) admits —
1649/// the same pass the live netmap path runs, so a peer that is dialed from the cache is one the
1650/// authority authorized, and an unsigned peer, a peer whose signature fails, or a peer a newer
1651/// rotation obsoletes is dropped.
1652///
1653/// Three things make the persisted authority safe to enforce with:
1654///
1655/// * it is re-verified from genesis on load ([`crate::tka_sync::authority_from_encoded_chain`]), so a
1656///   blob that is not a signed chain yields no authority;
1657/// * it is read back out of the same directory the netmap is, vetted as private to this user, so a
1658///   local attacker cannot choose which chain we start from any more than they can choose the netmap;
1659/// * its head must equal the head the **cached frame** recorded (`MapResponse.TKAInfo.Head`) — see
1660///   [`vouch_cached_peers`]. Go does not need that check because it has no second file to reconcile,
1661///   only the chonk.
1662pub(crate) async fn load_cached_netmap(cache: &ts_control::NetmapCache) -> Option<StateUpdate> {
1663    let authority = match cache.load_tka_chain().await {
1664        None => None,
1665        Some(blob) => match crate::tka_sync::authority_from_encoded_chain(&blob) {
1666            Ok(authority) => Some(authority),
1667            Err(e) => {
1668                tracing::warn!(
1669                    error = %e,
1670                    "persisted tailnet-lock chain did not verify; replaying the cached netmap \
1671                     without its peers"
1672                );
1673                None
1674            }
1675        },
1676    };
1677
1678    cache
1679        .load_state_update_vouched(|tka, peers| vouch_cached_peers(authority.as_ref(), tka, peers))
1680        .await
1681}
1682
1683/// The peers of a netmap cached under an **active** Tailnet Lock that may be replayed on this cold
1684/// start: those the persisted `authority` authorizes, by exactly the pass a live netmap's peers go
1685/// through (Go's `tkaFilterNetmapLocked`, via
1686/// [`PeerTracker::tka_keep_verdicts`](crate::peer_tracker::PeerTracker::tka_keep_verdicts) — the
1687/// per-peer signature verdict plus the cross-peer rotation filter).
1688///
1689/// Nothing is replayed unless the authority can be held to the netmap:
1690///
1691/// * **no persisted authority** (this node has never completed a TKA sync, or the chain did not
1692///   verify) ⇒ no peers. There is nothing to check a `key_signature` against, and admitting them
1693///   unchecked would dial a peer the lock may have revoked while this node was off.
1694/// * **the chain is not at the head the cached frame recorded** (`MapResponse.TKAInfo.Head`) ⇒ no
1695///   peers. The netmap and the chain are written on separate events, so they can disagree — a crash
1696///   between them, or a lock disabled and re-enabled under a fresh genesis — and a chain that
1697///   describes a different lock says nothing about these peers.
1698///
1699/// Separated from the I/O in [`load_cached_netmap`] so the decision itself is directly testable with
1700/// a real chain-derived [`Authority`](ts_tka::Authority) and real signatures.
1701pub(crate) fn vouch_cached_peers(
1702    authority: Option<&ts_tka::Authority>,
1703    tka: &TkaStatus,
1704    peers: Vec<Node>,
1705) -> Vec<Node> {
1706    let Some(authority) = authority else {
1707        tracing::info!(
1708            "no persisted tailnet-lock authority to verify the cached peers against; withholding \
1709             them until control's first netmap"
1710        );
1711        return Vec::new();
1712    };
1713
1714    if !ts_tka::AumHash::from_base32(&tka.head).is_some_and(|head| authority.head_matches(&head)) {
1715        tracing::warn!(
1716            head = %tka.head,
1717            "persisted tailnet-lock chain is not at the head the cached netmap recorded; \
1718             withholding its peers"
1719        );
1720        return Vec::new();
1721    }
1722
1723    let keep = {
1724        let refs: Vec<&Node> = peers.iter().collect();
1725        crate::peer_tracker::PeerTracker::tka_keep_verdicts(Some(authority), &refs)
1726    };
1727    peers
1728        .into_iter()
1729        .zip(keep)
1730        .filter_map(|(peer, keep)| keep.then_some(peer))
1731        .collect()
1732}
1733
1734/// The Tailnet-Lock chain persisted beside the cached netmap ([`load_cached_netmap`]), and the only
1735/// path that writes or removes it.
1736///
1737/// It is one owner because the two operations have to be ordered **against each other**. They used
1738/// not to be: the write was awaited on the actor thread while the removal was `tokio::spawn`ed, so a
1739/// removal scheduled by a lock *disable* could still be sitting in the runtime's queue when a sync
1740/// that followed it persisted a fresh chain, and then delete that fresh chain. Nothing tells the node
1741/// afterwards — the loss shows up one restart later, as a cold start that withholds peers it was
1742/// entitled to dial. Every operation here is awaited by its caller instead, and both callers
1743/// ([`ControlRunner::persist_tka_chain`] and the two lock-off paths) run on the actor thread, so the
1744/// actor's mailbox is the order.
1745///
1746/// This owns no policy about *which* chain may be replayed: the cold-start replay judges whatever it
1747/// finds on disk against the head the cached netmap frame itself recorded, so nothing here can admit
1748/// a peer, and a failed removal is a chain the replay refuses rather than one it trusts.
1749struct PersistedTkaChain {
1750    /// The cache directory the chain lives in, or `None` when the embedder configured no
1751    /// [`netmap_cache_dir`](ts_control::Config::netmap_cache_dir) — then no netmap is cached either,
1752    /// so there is nothing to vouch for and nothing to remove.
1753    cache: Option<ts_control::NetmapCache>,
1754    /// Whether a chain may be on disk right now.
1755    ///
1756    /// **Starts `true`.** A fresh process has synced nothing, but an earlier process of this node can
1757    /// have left a chain in the cache directory, and that chain is precisely what the next cold start
1758    /// would load. So "this process never synced a lock" is not evidence that there is nothing to
1759    /// remove, and the lock-off paths must not treat it as such.
1760    ///
1761    /// Its only job is to keep the repeated removal free: a tailnet with no lock reports the lock off
1762    /// on *every* netmap, and one `remove_file` per netmap tick is a syscall for nothing. It is never
1763    /// trusted in the other direction — a stale `false` cannot admit a peer, because admitting is the
1764    /// replay's decision and the replay reads the disk.
1765    maybe_on_disk: bool,
1766}
1767
1768impl PersistedTkaChain {
1769    /// The chain owner for a node configured with `dir` as its netmap cache directory.
1770    fn new(dir: Option<&std::path::PathBuf>) -> Self {
1771        Self {
1772            cache: dir.map(ts_control::NetmapCache::new),
1773            maybe_on_disk: true,
1774        }
1775    }
1776
1777    /// Persist `blob` as the chain the cached netmap's peers were admitted under. A write failure is
1778    /// logged inside the cache and swallowed; the flag stays set, so the next lock-off still tries to
1779    /// remove whatever did land.
1780    async fn store(&mut self, blob: &[u8]) {
1781        let Some(cache) = self.cache.as_ref() else {
1782            return;
1783        };
1784        cache.store_tka_chain(blob).await;
1785        self.maybe_on_disk = true;
1786    }
1787
1788    /// Remove the persisted chain. Awaited, so it has happened by the time this returns and cannot
1789    /// overtake a later [`store`](Self::store).
1790    async fn discard(&mut self) {
1791        if !self.maybe_on_disk {
1792            return;
1793        }
1794        let Some(cache) = self.cache.as_ref() else {
1795            // No directory was ever configured, so nothing can be on disk and nothing ever will be.
1796            // Settle the flag rather than re-deciding this on every netmap.
1797            self.maybe_on_disk = false;
1798            return;
1799        };
1800        cache.discard_tka_chain().await;
1801        self.maybe_on_disk = false;
1802    }
1803}
1804
1805impl Message<StreamMessage<Arc<StateUpdate>, (), ()>> for ControlRunner {
1806    type Reply = ();
1807
1808    async fn handle(
1809        &mut self,
1810        msg: StreamMessage<Arc<StateUpdate>, (), ()>,
1811        ctx: &mut Context<Self, Self::Reply>,
1812    ) {
1813        match msg {
1814            StreamMessage::Started(_) => {
1815                tracing::trace!("started listening to state updates");
1816            }
1817
1818            StreamMessage::Next(msg) => {
1819                if let Some(node) = msg.node.as_ref() {
1820                    // Reflect node-key expiry into the device state. Control delivering a self-node
1821                    // whose key is in the past means the node must re-authenticate; the arrival of a
1822                    // fresh (non-expired) self-node confirms we are Running (recovering the state if a
1823                    // prior update had flipped it to Expired/Reauthenticating). On expiry, decide
1824                    // between an automatic re-auth (Go `doLogin`: rotate key + re-register with the
1825                    // stored auth key) and the terminal Expired state via the pure `expiry_action`:
1826                    //   - auth key retained, reauth enabled, and TKA NOT enforcing → Reauthenticate.
1827                    //   - otherwise → Expired (no auth key / reauth disabled / TKA-locked).
1828                    // The TKA gate is a hard safety constraint: rotating on a locked tailnet would
1829                    // install an unsigned key and lock this node out of locked peers (the TKA re-sign
1830                    // is a separate follow-up). Recovery from Reauthenticating is automatic — the next
1831                    // good self-node flips back to Running at this same handler.
1832                    let now_unix = std::time::SystemTime::now()
1833                        .duration_since(std::time::UNIX_EPOCH)
1834                        .map(|d| d.as_secs() as i64)
1835                        .unwrap_or(0);
1836                    let action = expiry_action(
1837                        node.key_expired_at_unix(now_unix),
1838                        self.params.auth_key.is_some(),
1839                        self.params.config.reauth_on_expiry,
1840                        self.tka_authority.borrow().is_some(),
1841                    );
1842
1843                    // Bounded reauth sub-state-machine (circuit breaker), evaluated by the pure
1844                    // `reauth_circuit_step`. The `Reauthenticate` path must settle — a one-shot /
1845                    // already-consumed auth key cannot re-register, so an unbounded reauth would sit in
1846                    // `Reauthenticating` forever. The step takes the `expiry_action` verdict, whether we
1847                    // are ALREADY reauthenticating (i.e. the prior reauth has not recovered), and the
1848                    // current attempt counter, and returns the target state, the new counter, and
1849                    // whether to fire the one-shot reauth (fired ONLY on entry, so the node key rotates
1850                    // at most once per episode — a second rotation would lose the original `OldNodeKey`
1851                    // anchor). At `MAX_REAUTH_ATTEMPTS` it trips to terminal `Expired`.
1852                    //
1853                    // NOTE: we may act (count, and eventually flip to `Expired`) even when the published
1854                    // state does NOT change — a repeated `Reauthenticating` self-node is exactly the
1855                    // "prior reauth didn't recover" signal we must tally, so the counting reads the
1856                    // pre-step state directly here and `send_if_modified`'s `changed` only gates the
1857                    // log/firing below, never the counting.
1858                    let already_reauthing = matches!(
1859                        &*self.params.state_tx.borrow(),
1860                        crate::DeviceState::Reauthenticating
1861                    );
1862                    let step = reauth_circuit_step(action, already_reauthing, self.reauth_attempts);
1863                    self.reauth_attempts = step.attempts;
1864                    if step.next == ReauthState::Expired
1865                        && action == ExpiryAction::Reauthenticate
1866                        && already_reauthing
1867                    {
1868                        tracing::warn!(
1869                            attempts = step.attempts,
1870                            "automatic re-auth did not recover the node after {MAX_REAUTH_ATTEMPTS} \
1871                             attempts (auth key likely one-shot / consumed); falling back to terminal \
1872                             Expired"
1873                        );
1874                    }
1875                    let next = match step.next {
1876                        ReauthState::Running => crate::DeviceState::Running,
1877                        ReauthState::Reauthenticating => crate::DeviceState::Reauthenticating,
1878                        ReauthState::Expired => crate::DeviceState::Expired,
1879                    };
1880
1881                    // `send_if_modified` avoids waking watchers when the state is unchanged (a fresh
1882                    // self-node arrives on every netmap update). Returns whether the state changed.
1883                    let changed = self.params.state_tx.send_if_modified(|s| {
1884                        if *s != next {
1885                            *s = next.clone();
1886                            true
1887                        } else {
1888                            false
1889                        }
1890                    });
1891
1892                    if changed && step.fire_reauth {
1893                        tracing::info!(
1894                            "self node-key expired; starting automatic re-auth (rotate node key + \
1895                             re-register with stored auth key)"
1896                        );
1897                        self.client.reauth().await;
1898                    }
1899
1900                    self.self_node.send_replace(Some(node.clone()));
1901                }
1902
1903                if let Some(policy) = msg.ssh_policy.as_ref() {
1904                    self.ssh_policy.send_replace(Some(policy.clone()));
1905                }
1906
1907                if let Some(tka) = msg.tka.as_ref() {
1908                    self.tka.send_replace(Some(tka.clone()));
1909                    self.maybe_sync_tka(tka, ctx.actor_ref().clone()).await;
1910                }
1911
1912                // Track the DNS config for `Device::dns_config` (the daemon's `tnet dns status`) and
1913                // its cert-domain list for `Device::cert_domains`. See `retain_dns_config`: a delta
1914                // without a DNS config leaves both as they were.
1915                retain_dns_config(
1916                    &self.dns_config,
1917                    &self.cert_domains,
1918                    msg.dns_config.as_ref(),
1919                );
1920
1921                // Track the interactive-login URL for `Device::pop_browser_url` /
1922                // `Runtime::watch_ipn_bus`. See `sticky_update_pop_browser_url` for the Go-faithful
1923                // sticky semantics (update only on a new non-empty URL; never reset to `None`).
1924                sticky_update_pop_browser_url(&self.pop_browser_url, msg.pop_browser_url.as_ref());
1925
1926                if let Err(e) = self.params.env.publish(msg).await {
1927                    tracing::error!(error = %e, "publishing netmap update");
1928                }
1929            }
1930
1931            StreamMessage::Finished(_) => {
1932                tracing::error!("state update stream terminated")
1933            }
1934        }
1935    }
1936}
1937
1938/// The outcome of a spawned TKA bootstrap+sync task, delivered back to the actor thread so the
1939/// result can be applied to actor state (which a spawned task cannot touch directly). Sent by
1940/// [`ControlRunner::maybe_sync_tka`]; handled by applying via
1941/// [`ControlRunner::apply_tka_synced`](ControlRunner).
1942#[doc(hidden)]
1943pub struct TkaSynced {
1944    pub(crate) result:
1945        Result<Option<crate::tka_sync::SyncedTka>, crate::tka_sync::TkaSyncDriverError>,
1946    /// The [`ControlRunner::tka_generation`] captured when this sync was spawned; the handler
1947    /// discards the result if it no longer matches (the lock was disabled/re-synced mid-flight).
1948    pub(crate) generation: u64,
1949}
1950
1951impl Message<TkaSynced> for ControlRunner {
1952    type Reply = ();
1953
1954    async fn handle(&mut self, msg: TkaSynced, _ctx: &mut Context<Self, Self::Reply>) {
1955        self.apply_tka_synced(msg.result, msg.generation).await;
1956    }
1957}
1958
1959impl Message<DerpLatencyMeasurement> for ControlRunner {
1960    type Reply = ();
1961
1962    async fn handle(&mut self, msg: DerpLatencyMeasurement, _ctx: &mut Context<Self, Self::Reply>) {
1963        let measurements = msg.measurement.as_ref().clone();
1964
1965        // Publish the net-report snapshot for `Device::netcheck` (the daemon's `tnet netcheck`) from
1966        // the same measurements, before the home-region short-circuit below — an empty set still
1967        // yields a (default/empty) report rather than a stale one.
1968        self.netcheck
1969            .send_replace(crate::status::NetcheckReport::from_region_results(
1970                &measurements,
1971            ));
1972
1973        if measurements.is_empty() {
1974            tracing::debug!("derp latency measurements empty");
1975            return;
1976        };
1977
1978        // Record this cycle into the rolling history and evict reports older than the smoothing
1979        // window, then compute each region's `bestRecent` (5-min min). `Instant::now()` is the
1980        // arrival stamp; `best_recent` takes it as a param so the decision stays unit-testable.
1981        let now = Instant::now();
1982        self.derp_report_history
1983            .push((now, msg.measurement.clone()));
1984        self.derp_report_history
1985            .retain(|(stamp, _)| now.saturating_duration_since(*stamp) <= DERP_HISTORY_MAX_AGE);
1986        let best_recent = best_recent(&self.derp_report_history, now, DERP_HISTORY_MAX_AGE);
1987
1988        // Apply selection hysteresis (the pure decision lives in `select_home_region` for testability)
1989        // so jitter between near-equal regions does not flap the home relay. Go's asymmetric
1990        // smoothed-best vs raw-old comparison lives in `select_home_region`; here we just resolve the
1991        // chosen id back to its current-cycle latency for the home-region record + control update.
1992        let selected_id = select_home_region(
1993            self.home_region.map(|(id, _)| id),
1994            &measurements,
1995            &best_recent,
1996        )
1997        .expect("non-empty measurements always yield a selection");
1998        // `select_home_region` only ever returns an id drawn from `measurements`, so this lookup
1999        // always succeeds (same invariant the prior impl relied on when it returned the result by
2000        // reference). We record the current-cycle (raw) latency for the chosen region.
2001        let selected_latency = measurements
2002            .iter()
2003            .find(|m| m.id == selected_id)
2004            .expect("the selected region id is always one of the measurements")
2005            .latency;
2006
2007        let iter = measurements.iter().map(|result| {
2008            (
2009                result.latency_map_key.as_str(),
2010                result.latency.as_secs_f64(),
2011            )
2012        });
2013
2014        if self.home_region.map(|(id, _)| id) != Some(selected_id) {
2015            tracing::debug!(selected_region_id = ?selected_id, "updating home region");
2016        }
2017        self.home_region = Some((selected_id, selected_latency));
2018        // Advertise the smoothed home to control AND drive the local DERP relay to the same region
2019        // (Go `report.PreferredDERP` feeds both). `send_replace` wakes the watch on every send (it
2020        // does NOT coalesce same-value writes), so Multiderp's bridge sees a `SetHomeRegion` each
2021        // cycle; the de-dup is one layer down — `home_transition` returns `Unchanged` for a
2022        // re-selection of the current home, so the relay only churns on an actual home change.
2023        self.client.set_home_region(selected_id, iter).await;
2024        self.params.home_region.send_replace(Some(selected_id));
2025    }
2026}
2027
2028/// The cadence on which this node re-measures the derp map — the fork's analog of Go netcheck's
2029/// `fullReportInterval` (also 5 minutes). This fork has no netcheck timer of its own: a re-measure
2030/// is triggered by control pushing a derp map and by a link change
2031/// ([`MeasureNow`](crate::derp_latency::MeasureNow)), so this is the *assumed* cycle length that
2032/// [`DERP_HISTORY_MAX_AGE`] is sized from, not a period anything here sleeps on.
2033const FULL_REPORT_INTERVAL: Duration = Duration::from_secs(5 * 60);
2034
2035/// The window over which the rolling DERP-latency history is retained: it feeds both `best_recent`
2036/// (the home-region smoothing) and [`ControlRunner::recent_region_latency`] (the exit-node
2037/// suggestion's per-region ranking), exactly as Go's one `netcheck.Client.prev` history feeds both
2038/// `bestRecent` and `RecentRegionLatency`.
2039///
2040/// Sized as Go sizes it — `maxAge = fullReportInterval + ReportTimeout` — so the window covers a
2041/// whole re-measure cycle *plus* the time one measurement is allowed to take, and a report cannot
2042/// age out before its successor exists. Go's stronger guarantee ("the window always holds one
2043/// *full* report") does not carry over: `ts_netcheck`'s `complete_threshold` means **every**
2044/// measurement here is partial, so the window holds a union of partial reports rather than one
2045/// complete one — which is precisely why the union is what the suggestion ranks on.
2046const DERP_HISTORY_MAX_AGE: Duration =
2047    FULL_REPORT_INTERVAL.saturating_add(ts_netcheck::REPORT_TIMEOUT);
2048
2049/// Compute each region's `bestRecent` — its **minimum** latency over the reports within
2050/// `max_age` of `now` (Go `addReportHistoryAndSetPreferredDERP`'s `bestRecent` map). Reports older
2051/// than the window are ignored. `now` and `max_age` are parameters (not clock-read) so this is
2052/// deterministically unit-testable. A region absent from every in-window report is absent from the
2053/// result.
2054///
2055/// This is also the body of Go's `netcheck.Client.RecentRegionLatency()` — the same "lowest latency
2056/// seen per region across the retained history" map — which is why
2057/// [`ControlRunner::recent_region_latency`] serves the exit-node suggestion straight out of it
2058/// rather than keeping a second history.
2059fn best_recent(
2060    history: &[(Instant, Arc<Vec<ts_netcheck::RegionResult>>)],
2061    now: Instant,
2062    max_age: Duration,
2063) -> HashMap<ts_derp::RegionId, Duration> {
2064    let mut best: HashMap<ts_derp::RegionId, Duration> = HashMap::new();
2065    for (stamp, report) in history {
2066        // Skip reports outside the window. `saturating_duration_since` guards a `stamp` that is
2067        // somehow after `now` (clock skew): age 0, always in-window.
2068        if now.saturating_duration_since(*stamp) > max_age {
2069            continue;
2070        }
2071        for r in report.iter() {
2072            best.entry(r.id)
2073                .and_modify(|d| {
2074                    if r.latency < *d {
2075                        *d = r.latency;
2076                    }
2077                })
2078                .or_insert(r.latency);
2079        }
2080    }
2081    best
2082}
2083
2084/// Choose the DERP home region id, applying Go's selection hysteresis
2085/// (`netcheck.addReportHistoryAndSetPreferredDERP`). Pure so the decision is unit-testable.
2086///
2087/// `measurements` is the current cycle sorted by latency ascending (so `measurements[0]` is the
2088/// raw-current best). `best_recent` is each region's smoothed (5-min-min) latency. Matching Go's
2089/// **asymmetric** comparison exactly: the new best candidate is chosen by the *smoothed* `best_recent`
2090/// latency (`bestAny`), while the old/home region is compared using its *current-cycle* (raw)
2091/// latency (`oldRegionCurLatency`). Smoothing the best damps oscillation of the best region across
2092/// the switch boundary that the raw-vs-raw comparison (the prior impl) would still flap on.
2093///
2094/// Keeps the `current` home region unless the new best is *meaningfully* lower-latency — switching
2095/// only when BOTH the current region's raw latency exceeds the smoothed-best by at least
2096/// `PREFERRED_DERP_ABSOLUTE_DIFF` (10ms) AND the smoothed-best is at most two-thirds of the current
2097/// region's raw latency (a >~33% improvement). On the first selection (`current` is `None`), when the
2098/// smoothed-best already IS the current region, or when the current region dropped out of the
2099/// measurements, returns the best directly. `None` only if `measurements` is empty.
2100fn select_home_region(
2101    current: Option<ts_derp::RegionId>,
2102    measurements: &[ts_netcheck::RegionResult],
2103    best_recent: &HashMap<ts_derp::RegionId, Duration>,
2104) -> Option<ts_derp::RegionId> {
2105    /// Go `netcheck.preferredDERPAbsoluteDiff`.
2106    const PREFERRED_DERP_ABSOLUTE_DIFF: Duration = Duration::from_millis(10);
2107
2108    // The smoothed latency for a region: its `best_recent` if present, else its current sample (a
2109    // region seen only this cycle has a 1-sample history, so its min == its current latency anyway).
2110    let smoothed = |m: &ts_netcheck::RegionResult| -> Duration {
2111        best_recent.get(&m.id).copied().unwrap_or(m.latency)
2112    };
2113
2114    // Pick the best candidate by SMOOTHED latency (Go `bestAny = min over regions of bestRecent`).
2115    // `measurements` is sorted by raw latency, but smoothing can reorder, so scan for the smoothed
2116    // minimum explicitly rather than trusting `measurements[0]`.
2117    let best = measurements.iter().min_by_key(|m| smoothed(m))?;
2118    let best_any = smoothed(best);
2119
2120    let Some(old_id) = current.filter(|id| *id != best.id) else {
2121        // First selection, or the smoothed-best already is the current home region.
2122        return Some(best.id);
2123    };
2124
2125    // Compare against the old region's CURRENT (raw) latency this cycle, if it is still present —
2126    // Go's `oldRegionCurLatency`, deliberately unsmoothed (the asymmetry).
2127    match measurements.iter().find(|m| m.id == old_id) {
2128        Some(old) => {
2129            // Byte-faithful to Go: `oldRegionCurLatency - bestAny < 10ms || bestAny >
2130            // oldRegionCurLatency/3*2`. `saturating_sub` matches Go's signed subtraction for the
2131            // `< 10ms` test (when `old < best_any` Go is negative → `< 10ms` true; saturating_sub
2132            // floors to 0 → also true). The two-thirds rule uses INTEGER `Duration` division
2133            // `(old/3)*2` — NOT float `* 2.0/3.0`: Go computes the threshold in integer nanoseconds
2134            // (`oldNs/3` truncates), and float arithmetic diverges from it at the exact 2/3 boundary
2135            // with whole-millisecond inputs (e.g. old=36ms, best=24ms: Go's `24ms > 24ms` is false →
2136            // switch, but float `0.024 > 0.0239999997` is true → keep). `Duration / u32` truncates
2137            // nanos exactly like Go and `* u32` is exact, reproducing `oldRegionCurLatency/3*2`.
2138            let keep_old = old.latency.saturating_sub(best_any) < PREFERRED_DERP_ABSOLUTE_DIFF
2139                || best_any > (old.latency / 3) * 2;
2140            Some(if keep_old { old.id } else { best.id })
2141        }
2142        // The current region is no longer reachable this cycle: take the new best.
2143        None => Some(best.id),
2144    }
2145}
2146
2147impl Message<EndpointAdvertisement> for ControlRunner {
2148    type Reply = ();
2149
2150    async fn handle(&mut self, msg: EndpointAdvertisement, _ctx: &mut Context<Self, Self::Reply>) {
2151        let endpoints: Vec<Endpoint> = msg
2152            .endpoints
2153            .iter()
2154            .map(|ep| Endpoint {
2155                endpoint: ep.addr,
2156                ty: match ep.ty {
2157                    SelfEndpointType::Local => EndpointType::Local,
2158                    SelfEndpointType::Stun => EndpointType::Stun,
2159                    SelfEndpointType::Stun4LocalPort => EndpointType::Stun4LocalPort,
2160                },
2161            })
2162            .collect();
2163
2164        tracing::debug!(
2165            n_endpoints = endpoints.len(),
2166            "advertising endpoints to control"
2167        );
2168
2169        self.client.set_endpoints(endpoints).await;
2170    }
2171}
2172
2173/// Re-advertise this node's routable IP prefixes (`Hostinfo.RoutableIPs`) to control — the wire
2174/// half of a runtime [`Runtime::set_advertise_routes`](crate::Runtime::set_advertise_routes). Sent
2175/// as a direct `ask` from the runtime (not over the bus), so the route change reaches the live
2176/// map-poll client. `routes` is the final advertised set the caller wants control to grant.
2177#[derive(Debug)]
2178pub struct SetAdvertiseRoutes {
2179    /// The prefixes to advertise to control (already filtered to the final set).
2180    pub routes: Vec<ipnet::IpNet>,
2181}
2182
2183impl Message<SetAdvertiseRoutes> for ControlRunner {
2184    type Reply = ();
2185
2186    async fn handle(&mut self, msg: SetAdvertiseRoutes, _ctx: &mut Context<Self, Self::Reply>) {
2187        tracing::debug!(n_routes = msg.routes.len(), "advertising routes to control");
2188        self.client.set_routable_ips(msg.routes).await;
2189    }
2190}
2191
2192/// Update this node's `Hostinfo.Hostname` at control — the wire half of a runtime
2193/// [`Runtime::set_hostname`](crate::Runtime::set_hostname). A direct `ask` from the runtime, so the
2194/// change reaches the live map-poll client.
2195#[derive(Debug)]
2196pub struct SetHostname {
2197    /// The new hostname to report to control.
2198    pub hostname: String,
2199}
2200
2201impl Message<SetHostname> for ControlRunner {
2202    type Reply = ();
2203
2204    async fn handle(&mut self, msg: SetHostname, _ctx: &mut Context<Self, Self::Reply>) {
2205        tracing::debug!("updating hostname at control");
2206        self.client.set_hostname(msg.hostname).await;
2207    }
2208}
2209
2210#[cfg(test)]
2211mod reauth_bridge_tests {
2212    use tokio::sync::watch;
2213
2214    use super::bridge_reauth_url_to_state;
2215    use crate::DeviceState;
2216
2217    fn url(s: &str) -> url::Url {
2218        s.parse().unwrap()
2219    }
2220
2221    /// The bridge maps a surfaced re-auth URL onto `DeviceState::NeedsLogin(url)` — the fix's core:
2222    /// a mid-session `MachineNotAuthorized` (forwarded by the control client as `Some(url)`) becomes
2223    /// the "needs login" state the IPN bus turns into `browse_to_url`.
2224    #[test]
2225    fn bridge_maps_auth_url_to_needs_login() {
2226        let u = url("https://login.example/auth");
2227        let (tx, rx) = watch::channel(DeviceState::Running);
2228
2229        bridge_reauth_url_to_state(&tx, Some(&u));
2230
2231        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u));
2232    }
2233
2234    /// `None` never drives a transition — the recovery to `Running` is the netmap self-node
2235    /// handler's job, so the bridge ignores a `None` and leaves the state untouched.
2236    #[test]
2237    fn bridge_none_leaves_state_unchanged() {
2238        let (tx, rx) = watch::channel(DeviceState::Running);
2239
2240        bridge_reauth_url_to_state(&tx, None);
2241
2242        assert_eq!(*rx.borrow(), DeviceState::Running);
2243    }
2244
2245    /// Re-surfacing the same URL across retries does not re-fire the watch (`send_if_modified`
2246    /// dedupe against the cell's current value), so a stuck re-auth does not thrash subscribers.
2247    #[test]
2248    fn bridge_same_url_does_not_refire() {
2249        let u = url("https://login.example/auth");
2250        let (tx, mut rx) = watch::channel(DeviceState::Running);
2251
2252        bridge_reauth_url_to_state(&tx, Some(&u)); // first: fires
2253        assert!(rx.has_changed().unwrap(), "first NeedsLogin fires");
2254        rx.mark_unchanged();
2255        bridge_reauth_url_to_state(&tx, Some(&u)); // same URL: deduped
2256        assert!(
2257            !rx.has_changed().unwrap(),
2258            "the same re-auth URL must not re-fire the state watch"
2259        );
2260    }
2261
2262    /// A genuinely different re-auth URL after a prior one fires again (the dedupe tracks changes,
2263    /// it does not pin the first URL forever).
2264    #[test]
2265    fn bridge_new_url_after_prior_fires() {
2266        let a = url("https://login.example/a");
2267        let b = url("https://login.example/b");
2268        let (tx, rx) = watch::channel(DeviceState::Running);
2269
2270        bridge_reauth_url_to_state(&tx, Some(&a));
2271        bridge_reauth_url_to_state(&tx, Some(&b));
2272
2273        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(b));
2274    }
2275
2276    /// End-to-end of the *clear* contract: after the bridge sets `NeedsLogin`, the netmap self-node
2277    /// path (modeled here as a direct `send_replace(Running)`, the exact transition the
2278    /// `StreamMessage::Next` handler performs on the next good self-node) flips back to `Running`.
2279    /// This pins that the bridge does NOT need a `None`-clear arm — recovery is owned elsewhere.
2280    #[test]
2281    fn running_netmap_clears_needs_login() {
2282        let u = url("https://login.example/auth");
2283        let (tx, rx) = watch::channel(DeviceState::Running);
2284
2285        bridge_reauth_url_to_state(&tx, Some(&u));
2286        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u));
2287
2288        // The self-node handler's recovery transition (next good netmap self-node → Running).
2289        tx.send_replace(DeviceState::Running);
2290        assert_eq!(*rx.borrow(), DeviceState::Running);
2291    }
2292
2293    /// Fix 2 — the bridge must NOT clobber an in-flight automatic re-auth. While the cell holds
2294    /// `Reauthenticating`, an auth URL surfaced by the rotated re-register (over the same
2295    /// `auth_url_tx` cell) must leave the state UNTOUCHED: flipping to `NeedsLogin` would surface a
2296    /// misleading `browse_to_url` on a headless node and, by moving the cell off `Reauthenticating`,
2297    /// re-arm a second node-key rotation that loses the original `OldNodeKey` anchor. The auto-reauth
2298    /// path owns the cell until it recovers to `Running` or trips to `Expired`.
2299    #[test]
2300    fn bridge_does_not_clobber_reauthenticating() {
2301        let u = url("https://login.example/auth");
2302        let (tx, rx) = watch::channel(DeviceState::Reauthenticating);
2303
2304        bridge_reauth_url_to_state(&tx, Some(&u));
2305
2306        assert_eq!(
2307            *rx.borrow(),
2308            DeviceState::Reauthenticating,
2309            "a surfaced auth URL must not downgrade an in-flight auto-reauth to NeedsLogin"
2310        );
2311    }
2312
2313    /// The no-clobber guard is scoped to `Reauthenticating` only — it does not change the bridge's
2314    /// behavior in any other state. From `Running` (and likewise `Connecting`/`NeedsLogin`) a
2315    /// surfaced URL still drives `NeedsLogin` as before, so an ordinary interactive re-auth is
2316    /// unaffected.
2317    #[test]
2318    fn bridge_still_sets_needs_login_from_non_reauthenticating() {
2319        let u = url("https://login.example/auth");
2320        for start in [
2321            DeviceState::Running,
2322            DeviceState::Connecting,
2323            DeviceState::Expired,
2324        ] {
2325            let (tx, rx) = watch::channel(start);
2326            bridge_reauth_url_to_state(&tx, Some(&u));
2327            assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u.clone()));
2328        }
2329    }
2330}
2331
2332#[cfg(test)]
2333mod retain_dns_config_tests {
2334    use tokio::sync::watch;
2335
2336    use super::retain_dns_config;
2337
2338    fn cfg(cert_domains: &[&str]) -> ts_control::DnsConfig {
2339        ts_control::DnsConfig {
2340            magic_dns: true,
2341            cert_domains: cert_domains.iter().map(|d| (*d).to_owned()).collect(),
2342            ..Default::default()
2343        }
2344    }
2345
2346    /// A delta without a DNS config keeps the config and cert domains from the last response that
2347    /// carried one (Go `ms.lastDNSConfig`); a later config replaces both, even an empty one.
2348    #[test]
2349    fn delta_without_dns_config_keeps_the_last_one() {
2350        let (dns_tx, dns_rx) = watch::channel(None);
2351        let (cert_tx, cert_rx) = watch::channel(Vec::new());
2352
2353        let full = cfg(&["host.tail0123.ts.net"]);
2354        retain_dns_config(&dns_tx, &cert_tx, Some(&full));
2355        retain_dns_config(&dns_tx, &cert_tx, None);
2356        assert_eq!(*dns_rx.borrow(), Some(full));
2357        assert_eq!(*cert_rx.borrow(), vec!["host.tail0123.ts.net".to_owned()]);
2358
2359        let emptied = cfg(&[]);
2360        retain_dns_config(&dns_tx, &cert_tx, Some(&emptied));
2361        assert_eq!(*dns_rx.borrow(), Some(emptied));
2362        assert!(cert_rx.borrow().is_empty());
2363    }
2364}
2365
2366#[cfg(test)]
2367mod sticky_pop_browser_url_tests {
2368    use tokio::sync::watch;
2369
2370    use super::sticky_update_pop_browser_url;
2371
2372    fn url(s: &str) -> url::Url {
2373        s.parse().unwrap()
2374    }
2375
2376    /// A non-empty URL publishes to the cell.
2377    #[test]
2378    fn non_empty_url_publishes() {
2379        let (tx, rx) = watch::channel(None);
2380        let u = url("https://login.example/consent");
2381        sticky_update_pop_browser_url(&tx, Some(&u));
2382        assert_eq!(*rx.borrow(), Some(u));
2383    }
2384
2385    /// An absent (`None`) update — the common netmap tick — must NOT reset the cell. This is the
2386    /// regression guard for the thrash bug (a reset-every-tick would coalesce the URL away on the bus).
2387    #[test]
2388    fn absent_update_does_not_reset() {
2389        let u = url("https://login.example/consent");
2390        let (tx, rx) = watch::channel(Some(u.clone()));
2391        // Simulate many empty netmap updates.
2392        for _ in 0..5 {
2393            sticky_update_pop_browser_url(&tx, None);
2394        }
2395        assert_eq!(
2396            *rx.borrow(),
2397            Some(u),
2398            "empty updates must not clear the URL"
2399        );
2400    }
2401
2402    /// The same URL repeated does not re-fire the watch (in-place dedupe via `send_if_modified`), so
2403    /// a subscriber isn't woken spuriously. Proven by the borrow not having been marked changed.
2404    #[test]
2405    fn repeated_same_url_does_not_refire() {
2406        let u = url("https://login.example/consent");
2407        let (tx, mut rx) = watch::channel(None);
2408        sticky_update_pop_browser_url(&tx, Some(&u)); // first: fires
2409        assert!(rx.has_changed().unwrap(), "first non-empty URL fires");
2410        rx.mark_unchanged();
2411        sticky_update_pop_browser_url(&tx, Some(&u)); // same: deduped
2412        assert!(
2413            !rx.has_changed().unwrap(),
2414            "repeating the same URL must not re-fire the watch"
2415        );
2416    }
2417
2418    /// A genuinely new URL after a prior one fires again (sticky but tracks changes).
2419    #[test]
2420    fn new_url_after_prior_fires() {
2421        let a = url("https://login.example/a");
2422        let b = url("https://login.example/b");
2423        let (tx, rx) = watch::channel(None);
2424        sticky_update_pop_browser_url(&tx, Some(&a));
2425        sticky_update_pop_browser_url(&tx, Some(&b));
2426        assert_eq!(*rx.borrow(), Some(b));
2427    }
2428
2429    /// The realistic session sequence: a URL stays sticky through a run of `None` ticks, and a
2430    /// *different* URL after that gap still fires. Chains the legs the other tests cover in isolation
2431    /// (the actual control cadence is "URL, then many empty updates, then maybe a new URL").
2432    #[test]
2433    fn sticky_through_none_gap_then_new_url_fires() {
2434        let a = url("https://login.example/a");
2435        let b = url("https://login.example/b");
2436        let (tx, rx) = watch::channel(None);
2437        sticky_update_pop_browser_url(&tx, Some(&a));
2438        for _ in 0..3 {
2439            sticky_update_pop_browser_url(&tx, None);
2440        }
2441        assert_eq!(*rx.borrow(), Some(a), "stayed sticky through the None gap");
2442        sticky_update_pop_browser_url(&tx, Some(&b));
2443        assert_eq!(
2444            *rx.borrow(),
2445            Some(b),
2446            "a new URL after a None gap still fires"
2447        );
2448    }
2449
2450    /// Returning to a previously-seen URL (A → B → A) re-fires: the dedupe is against the cell's
2451    /// *current* value, not a full history, so A after B is a genuine change.
2452    #[test]
2453    fn returning_to_prior_url_refires() {
2454        let a = url("https://login.example/a");
2455        let b = url("https://login.example/b");
2456        let (tx, mut rx) = watch::channel(None);
2457        sticky_update_pop_browser_url(&tx, Some(&a));
2458        sticky_update_pop_browser_url(&tx, Some(&b));
2459        rx.mark_unchanged();
2460        sticky_update_pop_browser_url(&tx, Some(&a)); // back to A: differs from current (B) → fires
2461        assert!(
2462            rx.has_changed().unwrap(),
2463            "returning to a prior URL re-fires"
2464        );
2465        assert_eq!(*rx.borrow(), Some(a));
2466    }
2467
2468    /// End-to-end de-thrash: feed a realistic netmap cadence (empty, empty, URL, empty, empty)
2469    /// through the producer into a cell, and count the changes a `run_bus`-style subscriber would
2470    /// observe via `changed()`. The whole point of the fix is that exactly ONE change survives the
2471    /// surrounding `None` thrash — the pre-fix code (`send_replace` every tick) would have woken the
2472    /// subscriber on every empty tick and coalesced the URL away. This exercises the producer + the
2473    /// watch-subscribe path together (the two halves the unit tests cover in isolation).
2474    #[tokio::test]
2475    async fn end_to_end_one_change_survives_none_thrash() {
2476        let u = url("https://login.example/consent");
2477        let (tx, mut rx) = watch::channel(None);
2478        // The cadence control actually sends: mostly-empty MapResponses with one carrying the URL.
2479        let cadence = [None, None, Some(&u), None, None];
2480        for incoming in cadence {
2481            sticky_update_pop_browser_url(&tx, incoming);
2482        }
2483        // A subscriber sees exactly one change, and it carries the URL (not a coalesced `None`).
2484        let mut changes = 0;
2485        while rx.has_changed().unwrap() {
2486            let v = rx.borrow_and_update().clone();
2487            changes += 1;
2488            assert_eq!(v, Some(u.clone()), "the surviving change carries the URL");
2489        }
2490        assert_eq!(changes, 1, "exactly one change survives the None thrash");
2491    }
2492}
2493
2494#[cfg(test)]
2495mod home_region_hysteresis_tests {
2496    use core::time::Duration;
2497    use std::{collections::HashMap, sync::Arc, time::Instant};
2498
2499    use ts_derp::RegionId;
2500    use ts_netcheck::RegionResult;
2501
2502    use super::{DERP_HISTORY_MAX_AGE, best_recent, select_home_region};
2503
2504    fn region(id: u32, latency_ms: u64) -> RegionResult {
2505        RegionResult {
2506            latency: Duration::from_millis(latency_ms),
2507            id: RegionId(core::num::NonZeroU32::new(id).unwrap()),
2508            latency_map_key: format!("region-{id}"),
2509            connected_remote: "127.0.0.1:0".parse().unwrap(),
2510        }
2511    }
2512
2513    fn rid(id: u32) -> RegionId {
2514        RegionId(core::num::NonZeroU32::new(id).unwrap())
2515    }
2516
2517    /// Call `select_home_region` with NO smoothing history — `best_recent` empty, so each region's
2518    /// smoothed latency falls back to its current sample, reproducing the original raw-vs-raw
2519    /// hysteresis these tests pin. (The smoothing-specific tests below pass a populated map.)
2520    fn sel(current: Option<RegionId>, m: &[RegionResult]) -> Option<RegionId> {
2521        select_home_region(current, m, &HashMap::new())
2522    }
2523
2524    /// Empty measurements yield no selection.
2525    #[test]
2526    fn empty_measurements_select_none() {
2527        assert!(sel(Some(rid(1)), &[]).is_none());
2528        assert!(sel(None, &[]).is_none());
2529    }
2530
2531    /// First selection (no current home region) takes the best (lowest-latency) region directly.
2532    #[test]
2533    fn first_selection_takes_best() {
2534        let m = [region(1, 20), region(2, 50)];
2535        assert_eq!(sel(None, &m).unwrap(), rid(1));
2536    }
2537
2538    /// Jitter within the 10ms absolute-diff band keeps the current region (no flap). Current=region 2
2539    /// at 25ms; new best=region 1 at 20ms (only 5ms better) -> keep region 2.
2540    #[test]
2541    fn keeps_current_when_within_absolute_diff() {
2542        let m = [region(1, 20), region(2, 25)];
2543        assert_eq!(
2544            sel(Some(rid(2)), &m).unwrap(),
2545            rid(2),
2546            "a 5ms improvement (< 10ms) must not flap the home region"
2547        );
2548    }
2549
2550    /// A meaningful improvement (>10ms AND best <= 2/3 of current) switches. Current=region 2 at
2551    /// 100ms; new best=region 1 at 20ms -> switch to region 1.
2552    #[test]
2553    fn switches_on_meaningful_improvement() {
2554        let m = [region(1, 20), region(2, 100)];
2555        assert_eq!(
2556            sel(Some(rid(2)), &m).unwrap(),
2557            rid(1),
2558            "a large improvement must switch the home region"
2559        );
2560    }
2561
2562    /// The two-thirds rule: even past the 10ms absolute diff, an improvement that does not beat 2/3
2563    /// of the current latency keeps the current region. current=60ms, best=45ms: diff=15ms (>10ms,
2564    /// so the absolute test alone would switch), but 45 > 60*2/3=40, so keep.
2565    #[test]
2566    fn keeps_current_when_two_thirds_rule_not_met() {
2567        let m = [region(1, 45), region(2, 60)];
2568        assert_eq!(
2569            sel(Some(rid(2)), &m).unwrap(),
2570            rid(2),
2571            "best (45ms) is not <= 2/3 of current (40ms), so keep current despite >10ms diff"
2572        );
2573    }
2574
2575    /// When the current home region is no longer present in the measurements, take the new best.
2576    #[test]
2577    fn switches_when_current_region_absent() {
2578        let m = [region(1, 20), region(3, 25)];
2579        assert_eq!(
2580            sel(Some(rid(2)), &m).unwrap(),
2581            rid(1),
2582            "a current region absent from the measurements falls through to the best"
2583        );
2584    }
2585
2586    /// When the best already IS the current home region, it is kept (no spurious change).
2587    #[test]
2588    fn keeps_current_when_it_is_already_best() {
2589        let m = [region(2, 20), region(1, 50)];
2590        assert_eq!(sel(Some(rid(2)), &m).unwrap(), rid(2));
2591    }
2592
2593    /// The exit-node suggestion ranks on the *union* of the retained partial measurements, not on
2594    /// the newest one — this fork's form of upstream's `TestRecentReportsRetainFullNetcheck`.
2595    ///
2596    /// Go retains reports for `fullReportInterval + ReportTimeout` so the history is guaranteed to
2597    /// hold one *full* netcheck. This fork never produces a full one: `complete_threshold` ends
2598    /// every measurement once three regions have answered, so the window instead has to hold enough
2599    /// *partial* reports for their union to cover every region. Both halves are asserted against
2600    /// the production code — `best_recent`, which `ControlRunner::recent_region_latency` serves the
2601    /// suggestion from, and `suggest_exit_node`, the ranking itself.
2602    #[test]
2603    fn partial_reports_union_keeps_every_region_rankable() {
2604        use ts_control::StableNodeId;
2605
2606        use crate::exit_node_suggest::{ExitNodeCandidate, suggest_exit_node};
2607
2608        let now = Instant::now();
2609
2610        // Six measurement cycles, each naming only three regions — what a `complete_threshold: 3`
2611        // measurement produces against a real derp map. The nearby regions 1/2/3 answer nearly every
2612        // cycle; region 9 (far away, 300ms) got in exactly ONE cycle, four minutes ago; region 7 has
2613        // never been measured at all. The 10-minute-old cycle is outside the retention window and
2614        // its absurdly good 5ms sample for region 9 must not survive into the ranking.
2615        let history = vec![
2616            (now - Duration::from_secs(600), Arc::new(vec![region(9, 5)])),
2617            (
2618                now - Duration::from_secs(240),
2619                Arc::new(vec![region(1, 13), region(2, 20), region(9, 300)]),
2620            ),
2621            (
2622                now - Duration::from_secs(180),
2623                Arc::new(vec![region(1, 11), region(2, 21), region(3, 30)]),
2624            ),
2625            (
2626                now - Duration::from_secs(120),
2627                Arc::new(vec![region(1, 14), region(2, 19), region(3, 31)]),
2628            ),
2629            (
2630                now - Duration::from_secs(60),
2631                Arc::new(vec![region(1, 10), region(2, 23), region(3, 29)]),
2632            ),
2633            (
2634                now,
2635                Arc::new(vec![region(1, 12), region(2, 18), region(3, 28)]),
2636            ),
2637        ];
2638
2639        // Half one: every region any in-window cycle reached still has a latency to rank on, at its
2640        // lowest in-window sample. Region 9's stale 5ms is evicted; its 300ms stands.
2641        let recent = best_recent(&history, now, DERP_HISTORY_MAX_AGE);
2642        for (id, want_ms) in [(1, 10), (2, 18), (3, 28), (9, 300)] {
2643            assert_eq!(
2644                recent.get(&rid(id)).copied(),
2645                Some(Duration::from_millis(want_ms)),
2646                "region {id} must still be rankable off the retained history"
2647            );
2648        }
2649        assert!(
2650            !recent.contains_key(&rid(7)),
2651            "a region no in-window cycle ever measured has no latency"
2652        );
2653
2654        fn exit_node(id: u32, derp: u32) -> ExitNodeCandidate {
2655            ExitNodeCandidate {
2656                stable_id: StableNodeId(format!("stable{id}")),
2657                name: format!("peer{id}"),
2658                derp_region: Some(rid(derp)),
2659                online: Some(true),
2660                advertises_exit_route: true,
2661                has_suggest_cap: true,
2662            }
2663        }
2664        // One exit node in the far-but-measured region 9, one in the never-measured region 7.
2665        let candidates = [exit_node(9, 9), exit_node(7, 7)];
2666        let first_node = |nodes: &[ExitNodeCandidate], _: Option<&StableNodeId>| nodes[0].clone();
2667
2668        // Half two: ranked on the history, region 9's four-minute-old 300ms beats region 7's nothing,
2669        // and the uniform region pick is never reached.
2670        let no_random = |_: &[RegionId]| panic!("select_region must not be reached");
2671        let got = suggest_exit_node(Some(1), &recent, &candidates, None, &no_random, &first_node)
2672            .expect("ok")
2673            .expect("some");
2674        assert_eq!(
2675            got.id,
2676            StableNodeId("stable9".to_owned()),
2677            "a region measured four minutes ago must still beat an unmeasured one"
2678        );
2679
2680        // The regression this replaces: ranked on the NEWEST report alone — regions 1/2/3, the only
2681        // ones that cycle answered — neither candidate's region has a latency, so the suggestion
2682        // falls through to the uniform random pick and the unmeasured region 7 can win the coin flip.
2683        let newest: HashMap<RegionId, Duration> = history
2684            .last()
2685            .unwrap()
2686            .1
2687            .iter()
2688            .map(|r| (r.id, r.latency))
2689            .collect();
2690        let pick_seven = |regions: &[RegionId]| {
2691            assert!(regions.contains(&rid(7)) && regions.contains(&rid(9)));
2692            rid(7)
2693        };
2694        let got = suggest_exit_node(
2695            Some(1),
2696            &newest,
2697            &candidates,
2698            None,
2699            &pick_seven,
2700            &first_node,
2701        )
2702        .expect("ok")
2703        .expect("some");
2704        assert_eq!(
2705            got.id,
2706            StableNodeId("stable7".to_owned()),
2707            "ranking on one partial report leaves both candidates unmeasured and picks at random"
2708        );
2709    }
2710
2711    /// `best_recent` is each region's MINIMUM latency over the in-window reports; a report older than
2712    /// `max_age` is excluded.
2713    #[test]
2714    fn best_recent_is_min_over_window_and_evicts_aged() {
2715        let now = Instant::now();
2716        // Two in-window reports for region 1 (50ms then 20ms) → min 20ms; region 2 once at 30ms.
2717        // One aged report (region 1 at 5ms) outside the window must be ignored.
2718        let history = vec![
2719            (
2720                now - Duration::from_secs(10 * 60), // aged out (> 5min)
2721                Arc::new(vec![region(1, 5)]),
2722            ),
2723            (
2724                now - Duration::from_secs(60),
2725                Arc::new(vec![region(1, 50), region(2, 30)]),
2726            ),
2727            (now, Arc::new(vec![region(1, 20)])),
2728        ];
2729        let br = best_recent(&history, now, DERP_HISTORY_MAX_AGE);
2730        assert_eq!(
2731            br.get(&rid(1)).copied(),
2732            Some(Duration::from_millis(20)),
2733            "region 1 min over the window is 20ms (the aged 5ms is excluded)"
2734        );
2735        assert_eq!(br.get(&rid(2)).copied(), Some(Duration::from_millis(30)));
2736    }
2737
2738    /// The asymmetric comparison: the new best is chosen by its SMOOTHED (best_recent) latency while
2739    /// the old region is compared on its RAW current latency. A best region whose CURRENT sample
2740    /// looks much better but whose 5-min MIN is only marginally better must NOT flap the home region
2741    /// — exactly the oscillation the raw-vs-raw comparison would have switched on.
2742    #[test]
2743    fn smoothed_best_damps_oscillation_across_boundary() {
2744        // Current home = region 2, raw 60ms this cycle. Region 1's CURRENT sample is 20ms (a >2/3,
2745        // >10ms improvement → raw-vs-raw would SWITCH), but its 5-min MIN (best_recent) is 50ms
2746        // (it oscillates). Smoothed-best 50ms vs raw-old 60ms: diff 10ms is NOT < 10ms, but
2747        // 50 > 60*2/3=40 → keepOld. So we KEEP region 2, where the raw comparison would have flapped.
2748        let m = [region(1, 20), region(2, 60)];
2749        let mut br = HashMap::new();
2750        br.insert(rid(1), Duration::from_millis(50)); // smoothed best is worse than its raw sample
2751        br.insert(rid(2), Duration::from_millis(60));
2752        assert_eq!(
2753            select_home_region(Some(rid(2)), &m, &br).unwrap(),
2754            rid(2),
2755            "a best region whose 5-min min is only marginally better must not flap the home region"
2756        );
2757
2758        // Sanity: with NO smoothing (raw 20ms best), the same inputs WOULD switch — proving the
2759        // smoothing is what holds it.
2760        assert_eq!(
2761            select_home_region(Some(rid(2)), &m, &HashMap::new()).unwrap(),
2762            rid(1),
2763            "raw-vs-raw (no smoothing) switches on the 20ms-vs-60ms current samples"
2764        );
2765    }
2766
2767    /// Smoothing can reorder which region is "best": `measurements` is sorted by raw latency, but the
2768    /// smoothed minimum may favor a different region. `select_home_region` must pick by smoothed
2769    /// latency, not blindly trust `measurements[0]`.
2770    #[test]
2771    fn smoothed_best_may_differ_from_raw_first() {
2772        // Raw order: region 1 (10ms) is first. But region 2's 5-min min is 5ms while region 1's is
2773        // 40ms (region 1's 10ms was a lucky low sample). Smoothed-best is region 2. First selection.
2774        let m = [region(1, 10), region(2, 12)];
2775        let mut br = HashMap::new();
2776        br.insert(rid(1), Duration::from_millis(40));
2777        br.insert(rid(2), Duration::from_millis(5));
2778        assert_eq!(
2779            select_home_region(None, &m, &br).unwrap(),
2780            rid(2),
2781            "the smoothed-best region wins even when it is not the raw-latency first"
2782        );
2783    }
2784
2785    /// Byte-faithful integer two-thirds boundary (the float-vs-integer divergence): at exactly
2786    /// `best == old * 2/3` (old=36ms, best=24ms), Go's integer `bestAny > old/3*2` = `24ms > 24ms`
2787    /// is FALSE, so it does NOT keep on the 2/3 arm; and `cond_a` `36-24=12ms < 10ms` is also false,
2788    /// so Go SWITCHES. A float `0.024 > 0.036*2.0/3.0 = 0.0239999997` would wrongly KEEP. This test
2789    /// pins the integer math: it must switch to the best.
2790    #[test]
2791    fn two_thirds_boundary_is_integer_not_float() {
2792        let m = [region(1, 24), region(2, 36)];
2793        // No smoothing (raw == smoothed): isolates the 2/3 arithmetic at the exact boundary.
2794        assert_eq!(
2795            sel(Some(rid(2)), &m).unwrap(),
2796            rid(1),
2797            "at best == old*2/3 the integer rule does NOT keep (Go switches); a float rule would keep"
2798        );
2799    }
2800
2801    /// The `cond_a` (absolute-diff) arm via `saturating_sub`: when the old region's RAW current
2802    /// latency is FASTER than the smoothed-best (old=20ms raw, smoothed-best=50ms), `old - best_any`
2803    /// underflows. Go's signed subtraction is negative (`< 10ms` → keepOld); `saturating_sub` floors
2804    /// to 0 (`< 10ms` → keepOld) — same outcome. The old region is kept.
2805    #[test]
2806    fn old_faster_than_smoothed_best_keeps_via_absolute_diff() {
2807        // Current home = region 2, raw 20ms. Region 1 is the raw-best at 15ms but its smoothed min is
2808        // 50ms (it oscillates badly). smoothed-best candidate by min = region 2 (raw 20 == smoothed
2809        // 20, since br[2]=20) vs region 1 smoothed 50 → best is region 2 itself → already-best path.
2810        // To exercise the old<best_any underflow we need best != old: make region 1 the smoothed best
2811        // at 18ms but the OLD region's raw 20ms... use: old=region2 raw 20, best=region1 smoothed 18.
2812        let m = [region(1, 15), region(2, 20)];
2813        let mut br = HashMap::new();
2814        br.insert(rid(1), Duration::from_millis(18)); // smoothed-best = region 1 at 18ms
2815        br.insert(rid(2), Duration::from_millis(25)); // region 2 smoothed worse than its raw 20ms
2816        // best_any = 18ms (region 1). old (region 2) RAW = 20ms. 20 - 18 = 2ms < 10ms → keepOld.
2817        assert_eq!(
2818            select_home_region(Some(rid(2)), &m, &br).unwrap(),
2819            rid(2),
2820            "old raw (20ms) within 10ms of smoothed-best (18ms) keeps via the absolute-diff arm"
2821        );
2822    }
2823}
2824
2825#[cfg(test)]
2826mod expiry_action_tests {
2827    use super::{ExpiryAction, expiry_action};
2828
2829    /// Not expired → `Running`, regardless of the other inputs (the gate fields are only consulted
2830    /// once the key is expired).
2831    #[test]
2832    fn not_expired_is_always_running() {
2833        for has_auth_key in [false, true] {
2834            for reauth_enabled in [false, true] {
2835                for tka_active in [false, true] {
2836                    assert_eq!(
2837                        expiry_action(false, has_auth_key, reauth_enabled, tka_active),
2838                        ExpiryAction::Running,
2839                        "a non-expired key is Running for any gate combination"
2840                    );
2841                }
2842            }
2843        }
2844    }
2845
2846    /// The ONLY input combination that auto-reauths: expired AND auth key retained AND reauth enabled
2847    /// AND TKA not enforcing.
2848    #[test]
2849    fn expired_with_authkey_reauth_enabled_and_no_tka_reauthenticates() {
2850        assert_eq!(
2851            expiry_action(true, true, true, false),
2852            ExpiryAction::Reauthenticate
2853        );
2854    }
2855
2856    /// Every other expired combination falls back to the terminal `Expired` (today's behavior, no
2857    /// regression): no auth key, reauth disabled, or TKA enforcing each independently forces Expired.
2858    #[test]
2859    fn expired_falls_back_to_expired_for_every_other_combination() {
2860        // The full expired-input matrix minus the single Reauthenticate cell above.
2861        for has_auth_key in [false, true] {
2862            for reauth_enabled in [false, true] {
2863                for tka_active in [false, true] {
2864                    let action = expiry_action(true, has_auth_key, reauth_enabled, tka_active);
2865                    if has_auth_key && reauth_enabled && !tka_active {
2866                        // The one Reauthenticate cell, asserted above.
2867                        assert_eq!(action, ExpiryAction::Reauthenticate);
2868                    } else {
2869                        assert_eq!(
2870                            action,
2871                            ExpiryAction::Expired,
2872                            "expired with has_auth_key={has_auth_key}, \
2873                             reauth_enabled={reauth_enabled}, tka_active={tka_active} must be Expired"
2874                        );
2875                    }
2876                }
2877            }
2878        }
2879    }
2880
2881    /// The TKA safety gate in isolation: even with an auth key and reauth enabled, an ACTIVE lock
2882    /// forces `Expired` (never rotate an unsigned key on a locked tailnet). This is the hard
2883    /// constraint from the design — pinned as its own test so a regression that drops the `!tka_active`
2884    /// term is caught explicitly.
2885    #[test]
2886    fn tka_active_forces_expired_even_when_reauth_would_otherwise_fire() {
2887        assert_eq!(
2888            expiry_action(true, true, true, true),
2889            ExpiryAction::Expired,
2890            "an enforcing Tailnet Lock must veto auto-reauth (unsigned-key lockout safety gate)"
2891        );
2892    }
2893
2894    /// No auth key forces `Expired`: there is nothing to non-interactively re-register with, so even
2895    /// with reauth enabled and no lock the node goes terminal (unchanged from today).
2896    #[test]
2897    fn no_auth_key_forces_expired() {
2898        assert_eq!(
2899            expiry_action(true, false, true, false),
2900            ExpiryAction::Expired
2901        );
2902    }
2903
2904    /// The config opt-out: `reauth_on_expiry=false` forces `Expired` even with an auth key and no
2905    /// lock (the conservative posture / historical behavior).
2906    #[test]
2907    fn reauth_disabled_forces_expired() {
2908        assert_eq!(
2909            expiry_action(true, true, false, false),
2910            ExpiryAction::Expired
2911        );
2912    }
2913}
2914
2915#[cfg(test)]
2916mod reauth_circuit_tests {
2917    use super::{ExpiryAction, MAX_REAUTH_ATTEMPTS, ReauthState, reauth_circuit_step};
2918
2919    /// Entering reauth (a `Reauthenticate` verdict while NOT already reauthenticating) fires the
2920    /// one-shot reauth and starts the counter at 1.
2921    #[test]
2922    fn enter_reauth_fires_once_and_starts_counter() {
2923        let step = reauth_circuit_step(ExpiryAction::Reauthenticate, false, 0);
2924        assert_eq!(step.next, ReauthState::Reauthenticating);
2925        assert_eq!(
2926            step.attempts, 1,
2927            "the entering attempt starts the counter at 1"
2928        );
2929        assert!(step.fire_reauth, "entry fires the one-shot Command::Reauth");
2930    }
2931
2932    /// A subsequent expired self-node while ALREADY reauthenticating (prior reauth not recovered)
2933    /// counts up but does NOT re-fire — re-firing would rotate the node key a second time and lose the
2934    /// original `OldNodeKey` anchor.
2935    #[test]
2936    fn still_reauthing_counts_but_does_not_refire() {
2937        let step = reauth_circuit_step(ExpiryAction::Reauthenticate, true, 1);
2938        assert_eq!(step.next, ReauthState::Reauthenticating);
2939        assert_eq!(
2940            step.attempts, 2,
2941            "a non-recovering reauth increments the counter"
2942        );
2943        assert!(
2944            !step.fire_reauth,
2945            "must NOT re-fire reauth while already reauthenticating (no second rotation)"
2946        );
2947    }
2948
2949    /// At `MAX_REAUTH_ATTEMPTS` consecutive non-recovering reauths, the breaker trips to the terminal
2950    /// `Expired` and stops re-arming reauth (the one-shot auth-key case settles instead of looping).
2951    #[test]
2952    fn trips_to_expired_at_cap() {
2953        // One step below the cap still stays reauthenticating.
2954        let below =
2955            reauth_circuit_step(ExpiryAction::Reauthenticate, true, MAX_REAUTH_ATTEMPTS - 2);
2956        assert_eq!(below.next, ReauthState::Reauthenticating);
2957        assert!(!below.fire_reauth);
2958
2959        // The step that reaches the cap flips to terminal Expired and does not fire.
2960        let at_cap =
2961            reauth_circuit_step(ExpiryAction::Reauthenticate, true, MAX_REAUTH_ATTEMPTS - 1);
2962        assert_eq!(at_cap.attempts, MAX_REAUTH_ATTEMPTS);
2963        assert_eq!(
2964            at_cap.next,
2965            ReauthState::Expired,
2966            "at the cap the circuit breaker trips to terminal Expired"
2967        );
2968        assert!(
2969            !at_cap.fire_reauth,
2970            "a tripped breaker never fires another reauth"
2971        );
2972    }
2973
2974    /// A good (non-expired) self-node resets the counter to 0 (the node recovered) — so a later,
2975    /// genuine expiry cycle gets a fresh full budget of attempts, never a stale leftover count.
2976    #[test]
2977    fn running_resets_counter() {
2978        let step = reauth_circuit_step(ExpiryAction::Running, true, MAX_REAUTH_ATTEMPTS);
2979        assert_eq!(step.next, ReauthState::Running);
2980        assert_eq!(
2981            step.attempts, 0,
2982            "recovery to Running resets the attempt counter"
2983        );
2984        assert!(!step.fire_reauth);
2985    }
2986
2987    /// The non-reauth terminal path (`expiry_action` → `Expired`: no auth key / reauth disabled /
2988    /// TKA-locked) reports `Expired` and never fires reauth; the counter is irrelevant (this path
2989    /// never armed the machine), so it resets to 0.
2990    #[test]
2991    fn expired_action_is_terminal_without_firing() {
2992        let step = reauth_circuit_step(ExpiryAction::Expired, false, 0);
2993        assert_eq!(step.next, ReauthState::Expired);
2994        assert!(!step.fire_reauth);
2995        assert_eq!(step.attempts, 0);
2996    }
2997
2998    /// The full episode as the handler drives it, feeding each step's `attempts` into the next: a
2999    /// one-shot auth key that never recovers fires reauth exactly ONCE, counts each repeated expired
3000    /// self-node, and settles on terminal `Expired` at the cap — never an indefinite `Reauthenticating`
3001    /// spell and never a second rotation.
3002    #[test]
3003    fn full_episode_one_shot_key_settles_at_expired_after_one_fire() {
3004        // Step 1: first expired self-node (state was Running → not already reauthing): enter + fire.
3005        let s1 = reauth_circuit_step(ExpiryAction::Reauthenticate, false, 0);
3006        assert_eq!(s1.next, ReauthState::Reauthenticating);
3007        assert!(s1.fire_reauth);
3008        let mut attempts = s1.attempts;
3009        let mut fires = 1; // counted the one fire
3010
3011        // Steps 2..: still expired while reauthenticating — count only, never re-fire — until the cap.
3012        loop {
3013            let s = reauth_circuit_step(ExpiryAction::Reauthenticate, true, attempts);
3014            if s.fire_reauth {
3015                fires += 1;
3016            }
3017            attempts = s.attempts;
3018            if s.next == ReauthState::Expired {
3019                break;
3020            }
3021            assert_eq!(s.next, ReauthState::Reauthenticating);
3022            assert!(attempts < MAX_REAUTH_ATTEMPTS);
3023        }
3024
3025        assert_eq!(attempts, MAX_REAUTH_ATTEMPTS, "settles exactly at the cap");
3026        assert_eq!(
3027            fires, 1,
3028            "reauth (and thus a node-key rotation) fires exactly once across the whole episode"
3029        );
3030    }
3031
3032    /// Recovery then a fresh failing episode: `Reauthenticating → Running` (reset) → a later expiry
3033    /// re-enters and re-fires. Proves the reset gives the next episode a full attempt budget rather
3034    /// than carrying a stale count that would trip the breaker early.
3035    #[test]
3036    fn recovery_then_new_episode_re_fires() {
3037        // Episode 1 entry.
3038        let e1 = reauth_circuit_step(ExpiryAction::Reauthenticate, false, 0);
3039        assert!(e1.fire_reauth);
3040        // A non-recovering step, then recovery to Running resets.
3041        let mid = reauth_circuit_step(ExpiryAction::Reauthenticate, true, e1.attempts);
3042        assert_eq!(mid.attempts, 2);
3043        let recovered = reauth_circuit_step(ExpiryAction::Running, true, mid.attempts);
3044        assert_eq!(recovered.attempts, 0);
3045
3046        // Episode 2: a fresh expiry (state is Running again → not already reauthing) re-enters + fires.
3047        let e2 = reauth_circuit_step(ExpiryAction::Reauthenticate, false, recovered.attempts);
3048        assert_eq!(e2.next, ReauthState::Reauthenticating);
3049        assert_eq!(e2.attempts, 1, "the new episode starts fresh at 1");
3050        assert!(
3051            e2.fire_reauth,
3052            "a new episode after recovery fires reauth again"
3053        );
3054    }
3055}
3056
3057#[cfg(test)]
3058mod self_lockout_tests {
3059    use ts_tka::{AumHash, Authority, State};
3060
3061    use super::{SelfLockVerdict, self_lock_verdict};
3062
3063    fn node_key() -> ts_keys::NodePublicKey {
3064        ts_keys::NodePrivateKey::random().public_key()
3065    }
3066
3067    /// An empty key-signature is the "not signed yet" case: `Unsigned`, never a lockout warning —
3068    /// so a tailnet that simply has not signed this node does not spam a `warn`.
3069    #[test]
3070    fn empty_signature_is_unsigned_not_locked_out() {
3071        let authority = Authority::from_state(AumHash([0; 32]), State::default());
3072        assert_eq!(
3073            self_lock_verdict(&node_key(), &[], &authority),
3074            SelfLockVerdict::Unsigned
3075        );
3076    }
3077
3078    /// A non-empty key-signature that does not authorize self classifies as `LockedOut` — the
3079    /// operator-facing condition — and the verdict carries the verify error string for the log. Here
3080    /// the blob is non-empty (so we attempt verification rather than short-circuiting to `Unsigned`)
3081    /// but is not a valid NodeKeySignature CBOR (`0x01` decodes as a bare uint with trailing bytes),
3082    /// so `node_key_authorized` returns a `Decode` error → `LockedOut`. The cryptographic-rejection
3083    /// arms (`UntrustedKey` / `BadSignature` for a well-formed-but-untrusted NKS) are covered by
3084    /// `ts_tka`'s own `node_key_authorized` tests; this only needs to prove the runtime classifier
3085    /// routes a verify `Err` to `LockedOut`.
3086    #[test]
3087    fn unverifiable_signature_is_locked_out() {
3088        let authority = Authority::from_state(AumHash([0; 32]), State::default());
3089        let verdict = self_lock_verdict(&node_key(), &[0x01, 0x02, 0x03], &authority);
3090        assert!(
3091            matches!(verdict, SelfLockVerdict::LockedOut(_)),
3092            "a signature the lock cannot authorize must classify as LockedOut, got {verdict:?}"
3093        );
3094    }
3095}
3096
3097#[cfg(test)]
3098mod cached_replay_tests {
3099    //! The cold-start replay of a netmap cached under Tailnet Lock: which of its peers this node
3100    //! dials before control has answered.
3101    //!
3102    //! Go replays its cached map through `setNetMapLocked`, so `tkaFilterNetmapLocked`
3103    //! (`ipn/ipnlocal/tailnet-lock.go`, upstream `9ea7cba44591e0cd840c6c94d23274dd222059bf`) runs
3104    //! over it against the authority it re-opened from disk, and the peers holding a valid signature
3105    //! survive. These cover the same outcome here, over a chain persisted beside the netmap.
3106
3107    use ed25519_dalek::SigningKey;
3108    use ts_tka::{Aum, AumHash, AumKey, Authority, KeyKind, MemAumStore, NodeKeySignature};
3109
3110    use super::{TkaStatus, vouch_cached_peers};
3111    use crate::peer_tracker::tka_tests::peer_node;
3112
3113    /// The node key of the peer the lock authorizes in these tests.
3114    const SIGNED_PEER_KEY: [u8; 32] = [9u8; 32];
3115    /// The node key of the peer that presents nothing.
3116    const UNSIGNED_PEER_KEY: [u8; 32] = [10u8; 32];
3117
3118    /// A locked tailnet: a genesis checkpoint trusting `signer` (signed by it, so the chain verifies),
3119    /// plus the store and the [`Authority`] a completed sync would hold.
3120    fn locked_tailnet(signer: &SigningKey) -> (MemAumStore, AumHash, Authority) {
3121        let key = AumKey {
3122            kind: KeyKind::Ed25519,
3123            votes: 1,
3124            public: signer.verifying_key().to_bytes().to_vec(),
3125            meta: Vec::new(),
3126        };
3127        let mut genesis = Aum::new_genesis_checkpoint(vec![key], vec![vec![0x11; 32]])
3128            .expect("a well-formed genesis checkpoint");
3129        genesis.sign(signer);
3130        let oldest = genesis.hash();
3131        let store = MemAumStore::from_aums([genesis]);
3132        let authority = crate::tka_sync::authority_from_encoded_chain(
3133            &crate::tka_sync::encode_chain(&store, oldest).expect("encode"),
3134        )
3135        .expect("the chain verifies");
3136        (store, oldest, authority)
3137    }
3138
3139    /// The status control stamped on the netmap that was cached under `authority`.
3140    fn cached_lock(authority: &Authority) -> TkaStatus {
3141        TkaStatus {
3142            head: authority.head().to_base32(),
3143            disabled: false,
3144        }
3145    }
3146
3147    /// The headline: with the authority those peers were cached under, the cold start replays the
3148    /// peer that authority authorizes and drops the one it does not.
3149    ///
3150    /// Without the persisted authority this replays **nothing** — which is what made a locked
3151    /// tailnet lose the cache entirely, while Go kept dialing its authorized peers.
3152    #[test]
3153    fn a_persisted_authority_replays_the_peers_it_authorizes() {
3154        let signer = SigningKey::from_bytes(&[42u8; 32]);
3155        let (_store, _oldest, authority) = locked_tailnet(&signer);
3156
3157        let signed = peer_node(
3158            "signed-peer",
3159            SIGNED_PEER_KEY,
3160            NodeKeySignature::sign_direct(&SIGNED_PEER_KEY, &signer).serialize(),
3161        );
3162        let unsigned = peer_node("unsigned-peer", UNSIGNED_PEER_KEY, Vec::new());
3163
3164        let replayed = vouch_cached_peers(
3165            Some(&authority),
3166            &cached_lock(&authority),
3167            vec![signed, unsigned],
3168        );
3169
3170        assert_eq!(
3171            replayed
3172                .iter()
3173                .map(|p| p.stable_id.0.as_str())
3174                .collect::<Vec<_>>(),
3175            vec!["signed-peer"],
3176            "the peer the lock authorizes is dialed at cold start; the unsigned one is dropped"
3177        );
3178    }
3179
3180    /// No persisted authority (this node has never completed a sync, or the chain did not verify) ⇒
3181    /// no peers. There is nothing to check a signature against, and a peer the lock revoked while
3182    /// this node was off must not be dialed on the strength of a cache entry.
3183    #[test]
3184    fn without_an_authority_no_cached_peer_is_replayed() {
3185        let signer = SigningKey::from_bytes(&[42u8; 32]);
3186        let (_store, _oldest, authority) = locked_tailnet(&signer);
3187        let signed = peer_node(
3188            "signed-peer",
3189            SIGNED_PEER_KEY,
3190            NodeKeySignature::sign_direct(&SIGNED_PEER_KEY, &signer).serialize(),
3191        );
3192
3193        assert!(
3194            vouch_cached_peers(None, &cached_lock(&authority), vec![signed]).is_empty(),
3195            "a peer nothing can vouch for waits for control's first netmap"
3196        );
3197    }
3198
3199    /// A netmap cached on disk (raw `MapResponse` JSON, exactly what `NetmapCache` persists), in a
3200    /// directory private to this user so the cache's own vetting accepts it.
3201    #[cfg(unix)]
3202    fn cache_dir_with(label: &str, tka_info: &str, peers: &str) -> std::path::PathBuf {
3203        use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};
3204
3205        let dir = std::env::temp_dir().join(format!(
3206            "ts-rs-cached-replay-{}-{label}",
3207            std::process::id()
3208        ));
3209        std::fs::remove_dir_all(&dir).ok();
3210        std::fs::create_dir_all(&dir).expect("scratch dir");
3211        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).expect("chmod");
3212
3213        let body = format!(
3214            r#"{{
3215                {tka_info}
3216                "Node": {{
3217                    "ID": 1,
3218                    "StableID": "self-1",
3219                    "Name": "self.example.ts.net.",
3220                    "Addresses": ["100.64.0.1/32"],
3221                    "CapMap": {{"cache-network-maps": null}}
3222                }},
3223                "Peers": [{peers}],
3224                "DERPMap": {{ "Regions": {{ "3": {{
3225                    "RegionID": 3, "RegionCode": "tst", "RegionName": "Test", "Nodes": []
3226                }} }} }}
3227            }}"#
3228        );
3229        let mut file = std::fs::OpenOptions::new()
3230            .write(true)
3231            .create_new(true)
3232            .mode(0o600)
3233            .open(dir.join(ts_control::NETMAP_CACHE_FILE))
3234            .expect("cache file");
3235        std::io::Write::write_all(&mut file, body.as_bytes()).expect("write cached netmap");
3236        dir
3237    }
3238
3239    /// One cached peer, with no `KeySignature` — an unsigned peer, which a lock drops.
3240    #[cfg(unix)]
3241    const UNSIGNED_CACHED_PEER: &str = r#"{
3242        "ID": 2,
3243        "StableID": "peer-2",
3244        "Name": "peer.example.ts.net.",
3245        "Addresses": ["100.64.0.2/32"],
3246        "Endpoints": ["192.0.2.7:41641"],
3247        "HomeDERP": 3
3248    }"#;
3249
3250    /// End to end over the files a cold start actually finds: the persisted chain is read from the
3251    /// cache directory, re-verified, and used to judge the cached peers — an unsigned one is dropped
3252    /// while the rest of the netmap replays.
3253    ///
3254    /// The *admit* side is proven on [`vouch_cached_peers`] directly rather than here: a cached
3255    /// frame's `KeySignature` decodes to the raw bytes of its JSON string, so a real signature (64
3256    /// arbitrary bytes inside a CBOR structure) cannot be written into a JSON fixture at all.
3257    #[cfg(unix)]
3258    #[tokio::test]
3259    async fn a_cold_start_judges_the_cached_peers_against_the_persisted_chain() {
3260        let signer = SigningKey::from_bytes(&[42u8; 32]);
3261        let (store, oldest, authority) = locked_tailnet(&signer);
3262        let dir = cache_dir_with(
3263            "with-chain",
3264            &format!(
3265                r#""TKAInfo": {{ "Head": "{}", "Disabled": false }},"#,
3266                authority.head().to_base32()
3267            ),
3268            UNSIGNED_CACHED_PEER,
3269        );
3270        let cache = ts_control::NetmapCache::new(&dir);
3271        cache
3272            .store_tka_chain(&crate::tka_sync::encode_chain(&store, oldest).expect("encode"))
3273            .await;
3274
3275        let replayed = super::load_cached_netmap(&cache)
3276            .await
3277            .expect("the cached netmap replays");
3278
3279        assert!(
3280            replayed.peer_update.is_none(),
3281            "an unsigned peer is dropped by the same filter the live netmap runs, got {:?}",
3282            replayed.peer_update
3283        );
3284        assert!(
3285            replayed.node.is_some() && replayed.derp.is_some(),
3286            "the rest of the netmap carries no peer identity and still replays"
3287        );
3288
3289        std::fs::remove_dir_all(&dir).ok();
3290    }
3291
3292    /// A netmap cached while the lock was **off** replays whole: there is no authority to consult and
3293    /// nothing to enforce (Go's filter returns early on `b.tka == nil`).
3294    #[cfg(unix)]
3295    #[tokio::test]
3296    async fn a_cold_start_without_a_lock_replays_every_cached_peer() {
3297        let dir = cache_dir_with("no-lock", "", UNSIGNED_CACHED_PEER);
3298
3299        let replayed = super::load_cached_netmap(&ts_control::NetmapCache::new(&dir))
3300            .await
3301            .expect("the cached netmap replays");
3302
3303        assert!(
3304            matches!(replayed.peer_update, Some(ts_control::PeerUpdate::Full(ref p)) if p.len() == 1),
3305            "an unlocked tailnet replays its cached peers untouched: {:?}",
3306            replayed.peer_update
3307        );
3308
3309        std::fs::remove_dir_all(&dir).ok();
3310    }
3311
3312    /// A chain that does not verify is no authority at all, so the cached peers are withheld — the
3313    /// same outcome as never having persisted one. The netmap around them still replays.
3314    #[cfg(unix)]
3315    #[tokio::test]
3316    async fn a_cold_start_withholds_peers_when_the_persisted_chain_does_not_verify() {
3317        let signer = SigningKey::from_bytes(&[42u8; 32]);
3318        let (_store, _oldest, authority) = locked_tailnet(&signer);
3319        let tka_info = format!(
3320            r#""TKAInfo": {{ "Head": "{}", "Disabled": false }},"#,
3321            authority.head().to_base32()
3322        );
3323
3324        // No chain at all.
3325        let dir = cache_dir_with("no-chain", &tka_info, UNSIGNED_CACHED_PEER);
3326        let replayed = super::load_cached_netmap(&ts_control::NetmapCache::new(&dir))
3327            .await
3328            .expect("the cached netmap replays");
3329        assert!(replayed.peer_update.is_none());
3330        assert!(replayed.node.is_some());
3331        std::fs::remove_dir_all(&dir).ok();
3332
3333        // A chain blob that is not a verified chain.
3334        let dir = cache_dir_with("bad-chain", &tka_info, UNSIGNED_CACHED_PEER);
3335        let cache = ts_control::NetmapCache::new(&dir);
3336        cache.store_tka_chain(b"ts-tka-chain-v1\nAQID").await;
3337        let replayed = super::load_cached_netmap(&cache)
3338            .await
3339            .expect("the cached netmap replays");
3340        assert!(replayed.peer_update.is_none());
3341        assert!(replayed.node.is_some());
3342        std::fs::remove_dir_all(&dir).ok();
3343    }
3344
3345    /// A chain that is not at the head the cached frame recorded describes a different lock — a
3346    /// disable-and-re-enable under a fresh genesis, or a crash between writing the netmap and syncing
3347    /// the chain that followed it. It vouches for nothing.
3348    #[test]
3349    fn a_chain_at_another_head_vouches_for_nothing() {
3350        let signer = SigningKey::from_bytes(&[42u8; 32]);
3351        let (_store, _oldest, authority) = locked_tailnet(&signer);
3352        let signed = peer_node(
3353            "signed-peer",
3354            SIGNED_PEER_KEY,
3355            NodeKeySignature::sign_direct(&SIGNED_PEER_KEY, &signer).serialize(),
3356        );
3357
3358        // Another lock's head: valid base32, not ours.
3359        let other = TkaStatus {
3360            head: AumHash([0x5a; 32]).to_base32(),
3361            disabled: false,
3362        };
3363        assert!(vouch_cached_peers(Some(&authority), &other, vec![signed.clone()]).is_empty());
3364
3365        // A head control did not send, or one this node cannot parse, is not a match either.
3366        for head in ["", "not base32"] {
3367            let malformed = TkaStatus {
3368                head: head.to_string(),
3369                disabled: false,
3370            };
3371            assert!(
3372                vouch_cached_peers(Some(&authority), &malformed, vec![signed.clone()]).is_empty(),
3373                "a head that does not parse must not be treated as matching ({head:?})"
3374            );
3375        }
3376    }
3377}
3378
3379#[cfg(test)]
3380mod persisted_tka_chain_tests {
3381    //! The lifecycle of the Tailnet-Lock chain persisted for the cold-start replay: when it is
3382    //! removed, and that a removal can never outlive the write that follows it.
3383
3384    use super::PersistedTkaChain;
3385
3386    /// A cache directory this test owns, not yet created — [`PersistedTkaChain::store`] creates it
3387    /// private to this user, which is the same path the runtime takes.
3388    fn scratch_dir(label: &str) -> std::path::PathBuf {
3389        let dir =
3390            std::env::temp_dir().join(format!("ts-rs-tka-chain-{}-{label}", std::process::id()));
3391        std::fs::remove_dir_all(&dir).ok();
3392        dir
3393    }
3394
3395    /// An opaque chain blob. The cache stores and returns bytes; only the runtime decodes them, and
3396    /// nothing in this module does.
3397    const CHAIN: &[u8] = b"ts-tka-chain-v1\nAQID";
3398
3399    /// A process that has synced nothing still clears a chain an **earlier** process left behind.
3400    ///
3401    /// This is the state a cold start is in: `tka_synced` is `None` because this process has not
3402    /// spoken to control yet, while the chain the last run persisted is sitting in the cache
3403    /// directory — and that chain is exactly the one the *next* cold start would load. Gating the
3404    /// removal on live synced state (as the lock-off paths once did) leaves it there for good on a
3405    /// node whose lock was turned off between runs.
3406    #[tokio::test]
3407    async fn a_chain_an_earlier_process_left_is_cleared_by_one_that_synced_nothing() {
3408        let dir = scratch_dir("stale");
3409        let cache = ts_control::NetmapCache::new(&dir);
3410        cache.store_tka_chain(CHAIN).await;
3411        assert!(
3412            cache.load_tka_chain().await.is_some(),
3413            "the earlier process's chain is on disk"
3414        );
3415
3416        // Freshly constructed, exactly as `on_start` builds it: no sync has happened.
3417        let mut chain = PersistedTkaChain::new(Some(&dir));
3418        chain.discard().await;
3419
3420        assert!(
3421            cache.load_tka_chain().await.is_none(),
3422            "a lock control reports off clears the chain whether or not this process enforced it"
3423        );
3424
3425        std::fs::remove_dir_all(&dir).ok();
3426    }
3427
3428    /// A removal is complete when it returns, so a chain synced *after* it survives.
3429    ///
3430    /// The removal used to be detached (`tokio::spawn`), so a lock disable could leave one queued
3431    /// while a later sync persisted a fresh chain, and the queued removal would then delete it. The
3432    /// yields below are where such a task would get to run.
3433    #[tokio::test]
3434    async fn a_removal_never_outlives_the_chain_synced_after_it() {
3435        let dir = scratch_dir("ordering");
3436        let cache = ts_control::NetmapCache::new(&dir);
3437        let mut chain = PersistedTkaChain::new(Some(&dir));
3438
3439        chain.store(CHAIN).await;
3440        chain.discard().await;
3441        assert!(
3442            cache.load_tka_chain().await.is_none(),
3443            "the removal has happened by the time it returns; nothing is left pending"
3444        );
3445
3446        // The lock comes back on and a sync persists a new chain.
3447        let resynced = b"ts-tka-chain-v1\nBBBB".as_slice();
3448        chain.store(resynced).await;
3449        for _ in 0..8 {
3450            tokio::task::yield_now().await;
3451        }
3452
3453        assert_eq!(
3454            cache.load_tka_chain().await.as_deref(),
3455            Some(resynced),
3456            "the freshly synced chain is what the next cold start finds"
3457        );
3458
3459        std::fs::remove_dir_all(&dir).ok();
3460    }
3461
3462    /// Repeated lock-off netmaps stay cheap: the removal is idempotent and the chain stays gone.
3463    #[tokio::test]
3464    async fn repeating_the_removal_is_a_no_op() {
3465        let dir = scratch_dir("idempotent");
3466        let cache = ts_control::NetmapCache::new(&dir);
3467        let mut chain = PersistedTkaChain::new(Some(&dir));
3468
3469        chain.store(CHAIN).await;
3470        for _ in 0..3 {
3471            chain.discard().await;
3472            assert!(cache.load_tka_chain().await.is_none());
3473        }
3474
3475        std::fs::remove_dir_all(&dir).ok();
3476    }
3477
3478    /// An embedder that configured no netmap cache directory writes nothing and removes nothing —
3479    /// there is no cache, so there is never a chain to vouch with.
3480    #[tokio::test]
3481    async fn no_cache_directory_means_no_chain_at_all() {
3482        let mut chain = PersistedTkaChain::new(None);
3483        chain.store(CHAIN).await;
3484        chain.discard().await;
3485    }
3486}