Skip to main content

ts_runtime/
control_runner.rs

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