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, Spawn},
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::{
22    derp_latency::{DerpLatencyMeasurement, DerpLatencyMeasurer},
23    direct::EndpointAdvertisement,
24};
25
26/// Actor responsible for maintaining the connection to control.
27///
28/// This actor is responsible for proxying the map response stream onto the message bus.
29pub struct ControlRunner {
30    client: AsyncControlClient,
31    params: Params,
32
33    self_node: watch::Sender<Option<Node>>,
34    /// Latest Tailscale SSH policy pushed by control, or `None` until control sends one. The SSH
35    /// server reads this to authorize incoming connections; absent policy means deny-all.
36    ssh_policy: watch::Sender<Option<SshPolicy>>,
37    /// Latest Tailnet Lock status pushed by control, or `None` until control sends one.
38    tka: watch::Sender<Option<TkaStatus>>,
39    /// The locally-synced Tailnet-Lock state (verified `Authority` + AUM store), or `None` until a
40    /// successful bootstrap+sync. Held here because `ControlRunner` owns the netmap stream that
41    /// triggers resync. Mutated only on the actor thread (the netmap handler spawns the sync RPC and
42    /// the result returns via the [`TkaSynced`] self-message).
43    tka_synced: Option<crate::tka_sync::SyncedTka>,
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 = 5 * time.Minute`), each stamped with its arrival `Instant`. Feeds the
96    /// `bestRecent` smoothing (Go `addReportHistoryAndSetPreferredDERP`): the new home candidate is
97    /// chosen by each region's **minimum** latency over this window, not its raw current sample, so a
98    /// best region whose latency oscillates across the switch boundary does not flap the home relay.
99    /// Aged entries are evicted on each measurement; the buffer is therefore bounded by the netcheck
100    /// cadence × the window.
101    derp_report_history: Vec<(Instant, Arc<Vec<ts_netcheck::RegionResult>>)>,
102    /// Consecutive automatic-reauth attempts that have NOT yet recovered the node to a good (non-
103    /// expired) self-node. The circuit breaker for [`expiry_action`]'s `Reauthenticate` path: a
104    /// one-shot / already-consumed auth key cannot re-register, so without a bound an expired node
105    /// would sit in [`DeviceState::Reauthenticating`] indefinitely (the rotated re-register keeps
106    /// failing or control keeps returning a still-expired self-node).
107    ///
108    /// Incremented once per expired self-node seen while *already* `Reauthenticating` (each such
109    /// arrival is evidence the prior reauth did not recover); reset to `0` whenever a good
110    /// (non-expired) self-node arrives (the node recovered) — see the [`StreamMessage::Next`] handler.
111    /// At [`MAX_REAUTH_ATTEMPTS`] the runner stops re-arming reauth and flips the cell to the terminal
112    /// [`DeviceState::Expired`], giving the cell a stable terminal state (a genuinely good self-node
113    /// can still recover it later). The one-shot `Command::Reauth` is fired ONLY on the transition
114    /// INTO `Reauthenticating`, never re-fired while already reauthenticating, so the node key is
115    /// rotated at most once per episode (a second rotation would lose the original `OldNodeKey`
116    /// anchor control needs to link the rotation).
117    reauth_attempts: u32,
118    /// Background task that bridges the control client's mid-session re-auth URL cell onto
119    /// [`Self::params`]'s device-state cell (sets [`DeviceState::NeedsLogin`] when control returns
120    /// `MachineNotAuthorized` on a live re-register — see [`bridge_reauth_url_to_state`]). Aborted on
121    /// [`Drop`] so it cannot outlive the actor (the [`DataplaneActor`](crate::dataplane) pattern).
122    reauth_bridge: tokio::task::JoinHandle<()>,
123}
124
125/// The number of consecutive failed automatic-reauth attempts after which the runner gives up
126/// re-arming reauth and flips the device to the terminal [`DeviceState::Expired`] (the circuit
127/// breaker from the design's deferred-question Q1). A one-shot auth key was consumed by the first
128/// registration, so an auto re-register with it cannot succeed; this bounds that case to today's
129/// terminal behavior instead of an indefinite `Reauthenticating` spell. The first arrival fires the
130/// reauth; each subsequent expired self-node while still reauthenticating counts toward this cap.
131const MAX_REAUTH_ATTEMPTS: u32 = 3;
132
133impl Drop for ControlRunner {
134    fn drop(&mut self) {
135        // Stop the re-auth bridge so it does not outlive the actor (mirrors `DataplaneActor`).
136        self.reauth_bridge.abort();
137    }
138}
139
140/// Control runner args.
141pub struct Params {
142    /// Control config.
143    pub(crate) config: ts_control::Config,
144
145    /// Auth key (if needed).
146    pub(crate) auth_key: Option<String>,
147
148    /// The [`crate::Env`] for this actor.
149    pub(crate) env: crate::Env,
150
151    /// Sender for the device connection-state cell. Created in [`Runtime::spawn`](crate::Runtime)
152    /// so it outlives the actor's `on_start` (which may publish [`DeviceState::Failed`] and then
153    /// return `Err`, before `Self` exists). The runtime keeps the matching `Receiver` for
154    /// [`watch_state`](crate::Runtime::watch_state) / [`wait_until_running`](crate::Runtime::wait_until_running).
155    pub(crate) state_tx: watch::Sender<crate::DeviceState>,
156
157    /// Sender for the TKA enforcement-authority cell the peer tracker reads (Go
158    /// `tkaFilterNetmapLocked`). Created in [`Runtime::spawn`](crate::Runtime) and threaded into BOTH
159    /// the peer tracker (the `Receiver`) and this runner (the `Sender`), so the runner is the sole
160    /// writer and the tracker reads the latest verified `Authority` on demand. `None` = no lock /
161    /// disabled (admit all).
162    pub(crate) tka_authority: watch::Sender<Option<Arc<ts_tka::Authority>>>,
163
164    /// Sender for the selected DERP home region (the **smoothed** `bestRecent` + hysteresis choice,
165    /// Go `report.PreferredDERP`). Created in [`Runtime::spawn`](crate::Runtime); the runner is the
166    /// sole writer and [`Multiderp`](crate::multiderp) holds the `Receiver`, so the local DERP relay
167    /// follows the SAME home the runner advertises to control — not the raw per-cycle latency
168    /// minimum (which would flap on jitter and disagree with the advertised home). `None` until the
169    /// first home is chosen.
170    pub(crate) home_region: watch::Sender<Option<ts_derp::RegionId>>,
171}
172
173#[doc(hidden)]
174#[derive(Debug, thiserror::Error)]
175pub enum ControlRunnerError {
176    #[error(transparent)]
177    Control(#[from] ControlError),
178
179    #[error(transparent)]
180    Crate(#[from] crate::Error),
181}
182
183impl kameo::Actor for ControlRunner {
184    type Args = Params;
185    type Error = ControlRunnerError;
186
187    async fn on_start(params: Params, slf: ActorRef<Self>) -> Result<Self, Self::Error> {
188        // The interactive AuthURL, captured on the first unauthorized reply and reused as the
189        // `followup` on every subsequent poll so control long-polls ONE stable URL (rather than
190        // minting a fresh, racing URL each retry) until the user visits it.
191        let mut login_url: Option<url::Url> = None;
192        loop {
193            match AsyncControlClient::check_auth(
194                &params.config,
195                &params.env.keys,
196                params.auth_key.as_deref(),
197                login_url.as_ref(),
198            )
199            .await
200            {
201                Ok(()) => break,
202                Err(ControlError::MachineNotAuthorized(u)) => {
203                    // Capture the FIRST url and keep showing/following-up on it, so the link the
204                    // user opened stays valid instead of being superseded by the next poll.
205                    let url = login_url.get_or_insert(u).clone();
206                    tracing::info!(auth_url = %url, "please authorize this machine or pass an auth key");
207                    // Publish `NeedsLogin(url)` only when it actually changes the cell. With `followup`
208                    // set, the SAME URL is re-affirmed on every long-poll timeout; a bare `send_replace`
209                    // re-notifies `state_rx` each cycle, so the bus re-emits `browse_to_url` for a link
210                    // the user already has — reopening it repeatedly. `send_if_modified` dedups the
211                    // no-op, mirroring `bridge_reauth_url_to_state` (the mid-session re-auth path).
212                    let next = crate::DeviceState::NeedsLogin(url);
213                    params.state_tx.send_if_modified(|current| {
214                        if *current == next {
215                            false
216                        } else {
217                            *current = next.clone();
218                            true
219                        }
220                    });
221                    // With followup set, check_auth long-polls until the URL is visited; this short
222                    // sleep only applies if control times the poll out, and we re-followup the SAME url.
223                    tokio::time::sleep(Duration::from_secs(2)).await;
224                }
225                Err(ControlError::NeedsMachineAuth) => {
226                    // The node is registered with a valid key but awaiting ADMIN APPROVAL on an
227                    // approval-gated tailnet, and control offered NO interactive URL. This is
228                    // TRANSIENT (Go's `NeedsMachineAuth`): poll registration until an admin approves,
229                    // then `check_auth` returns `Ok(())` → the loop breaks and the node comes up with
230                    // no re-registration. Publishing the (no-URL) `NeedsMachineAuth` state — NOT a
231                    // terminal `Failed` and NOT `NeedsLogin` (there is no URL to open) — lets a
232                    // watcher / `wait_until_running` see "awaiting approval" instead of an opaque
233                    // timeout. Same 5s poll cadence as the `MachineNotAuthorized(url)` arm.
234                    tracing::info!(
235                        "machine awaiting admin approval to join the tailnet; polling until approved"
236                    );
237                    params
238                        .state_tx
239                        .send_replace(crate::DeviceState::NeedsMachineAuth);
240                    tokio::time::sleep(Duration::from_secs(5)).await;
241                }
242                Err(ControlError::RateLimited(retry_after)) => {
243                    // Control asked us to slow down (HTTP 429). Wait exactly the server-requested
244                    // cooldown and retry — this is transient, NOT a terminal `Failed`, so we must
245                    // not stop the runner (mirrors Go's `authRoutine` sleeping `rle.retryAfter`).
246                    tracing::warn!(
247                        ?retry_after,
248                        "control rate-limited registration; waiting before retry"
249                    );
250                    tokio::time::sleep(retry_after).await;
251                }
252                Err(e) => {
253                    // Followup auth path gone: while long-polling a STABLE AuthURL, control returns
254                    // an HTTP registration error (410 "auth path not found") once the path is either
255                    // VISITED + approved (consumed) or expired. This is NOT terminal — drop the
256                    // followup and re-register ONCE: an approved node key comes back `MachineAuthorized`
257                    // (`Ok(())` → login completes), an expired one comes back with a fresh AuthURL.
258                    // Without this, the user's own approval (which consumes the path → 410) kills the
259                    // runner. Bounded: on re-register `login_url` is None, so a repeat HTTP error falls
260                    // through to the terminal handling below (no infinite loop).
261                    if login_url.is_some()
262                        && matches!(
263                            e,
264                            ControlError::Internal(
265                                ts_control::InternalErrorKind::Http,
266                                ts_control::Operation::Registration,
267                            )
268                        )
269                    {
270                        tracing::info!(
271                            "followup auth path gone (approved or expired); re-registering"
272                        );
273                        login_url = None;
274                        tokio::time::sleep(Duration::from_secs(1)).await;
275                        continue;
276                    }
277                    // A hard registration failure (bad/expired/unknown auth key, etc.). Log the
278                    // specific reason control gave AND publish it as a typed `Failed` state so
279                    // `Device::wait_until_running` returns the actionable reason (tsr-kqj) instead
280                    // of the opaque `Internal(Actor)` the caller would otherwise see once the
281                    // stopped actor is next asked. Publishing before `return Err` is why the state
282                    // sender lives on `Runtime`, not on `Self` (which never gets constructed here).
283                    let reason = crate::RegistrationError::from(&e);
284                    tracing::error!(error = %e, "registration failed; control runner stopping");
285                    params
286                        .state_tx
287                        .send_replace(crate::DeviceState::Failed(reason));
288                    return Err(e.into());
289                }
290            }
291        }
292        // check_auth succeeded, but the node is not "up" until the netmap stream is actually
293        // attached below. Publish `Running` only AFTER `attach_stream` so `wait_until_running` never
294        // resolves `Ok` for a device whose stream connect failed (which would leave a stopped actor
295        // behind). If the connect/subscribe steps fail, publish a transient `Failed` first so the
296        // waiter sees an actionable reason instead of the opaque post-mortem `Internal(Actor)`.
297        // The control client's live map-poll loop publishes a mid-session re-auth URL here (set when
298        // a re-register returns `MachineNotAuthorized` because the node key expired/was revoked). The
299        // runtime owns the receiver; `connect` takes the sender. Created before `connect` so the
300        // sender is in place for the very first poll, and so the receiver outlives `bring_up`.
301        let (auth_url_tx, auth_url_rx) = watch::channel::<Option<url::Url>>(None);
302
303        // `connect` issues its own `machine/register` POST (a second one after `check_auth`'s), so
304        // it too can hit a 429. Wrap it in the same honor-`Retry-After` retry as the `check_auth`
305        // loop above: a rate-limit is transient — sleeping the server-requested cooldown and
306        // retrying must NOT stop the runtime (a 429 here previously fell into the `Err(e)` arm →
307        // `Failed` → actor stop). `connect` consumes a `watch::Sender` by value (and drops it on a
308        // failed register, before it would be moved into the live-poll task), so we keep the original
309        // `auth_url_tx` alive here across all attempts and hand `connect` a CLONE each time. That
310        // keeps the runtime's `auth_url_rx` (the `reauth_bridge` receiver) paired with a live sender:
311        // recreating a fresh sender per attempt instead would orphan the bridge the moment the
312        // original dropped, silently killing mid-session re-auth-URL delivery.
313        let client = loop {
314            let bring_up = async {
315                let (client, stream) = AsyncControlClient::connect(
316                    &params.config,
317                    &params.env.keys,
318                    params.auth_key.as_deref(),
319                    auth_url_tx.clone(),
320                )
321                .await?;
322
323                DerpLatencyMeasurer::spawn_link(&slf, params.env.clone()).await;
324
325                params.env.subscribe::<DerpLatencyMeasurement>(&slf).await?;
326                params.env.subscribe::<EndpointAdvertisement>(&slf).await?;
327                slf.attach_stream(stream.boxed(), (), ());
328                Ok::<_, ControlRunnerError>(client)
329            };
330
331            match bring_up.await {
332                Ok(client) => break client,
333                Err(ControlRunnerError::Control(ControlError::RateLimited(retry_after))) => {
334                    tracing::warn!(
335                        ?retry_after,
336                        "control rate-limited the session bring-up; waiting before retry"
337                    );
338                    tokio::time::sleep(retry_after).await;
339                }
340                Err(ControlRunnerError::Control(ControlError::NeedsMachineAuth)) => {
341                    // `connect` issues its OWN `machine/register` POST (a second one after
342                    // `check_auth`'s), so it too can come back "awaiting admin approval, no URL". In
343                    // the normal flow the `check_auth` loop above already gated this (it only breaks
344                    // once registration returns `Ok`, and approval is monotonic), so this arm is the
345                    // defensive twin for a node de-authorized in the race window between the two POSTs:
346                    // treat it as TRANSIENT exactly like the `check_auth` arm — publish the (no-URL)
347                    // `NeedsMachineAuth` state, poll the same 5s, and retry the bring-up — rather than
348                    // collapsing into the terminal `Failed` arm below (which would permanently stop
349                    // the runner on a recoverable await-approval). Mirrors Go's `NeedsMachineAuth`.
350                    tracing::info!(
351                        "machine awaiting admin approval during session bring-up; polling until \
352                         approved"
353                    );
354                    params
355                        .state_tx
356                        .send_replace(crate::DeviceState::NeedsMachineAuth);
357                    tokio::time::sleep(Duration::from_secs(5)).await;
358                }
359                Err(e) => {
360                    tracing::error!(error = %e, "bringing up the control session failed");
361                    // The control session never came up; surface it as a transient registration
362                    // failure (a retry / fresh `Device::new` may succeed) rather than leaving the
363                    // state stuck at `Connecting`.
364                    params.state_tx.send_replace(crate::DeviceState::Failed(
365                        crate::RegistrationError::NetworkUnreachable,
366                    ));
367                    return Err(e);
368                }
369            }
370        };
371
372        // The netmap stream is attached: the node is up. The stream `Next` handler keeps this
373        // current (and flips to `Expired` if the self-node's key lapses).
374        params.state_tx.send_replace(crate::DeviceState::Running);
375
376        // Bridge the control client's mid-session re-auth URL cell onto the device-state cell: a
377        // `Some(url)` (control returned `MachineNotAuthorized` on a live re-register) becomes
378        // `DeviceState::NeedsLogin(url)` so the IPN bus surfaces `browse_to_url` and the embedder can
379        // prompt the user — the live-session analogue of the initial `check_auth` loop above. The
380        // recovery to `Running` is the netmap self-node handler's job (next good self-node), so this
381        // bridge only forwards `Some`. The task ends when the sender drops (the client's `run` task
382        // ended) and is aborted on actor `Drop`, so it cannot leak past the actor.
383        let reauth_bridge = {
384            let state_tx = params.state_tx.clone();
385            let mut auth_url_rx = auth_url_rx;
386            tokio::spawn(async move {
387                while auth_url_rx.changed().await.is_ok() {
388                    let url = auth_url_rx.borrow_and_update().clone();
389                    bridge_reauth_url_to_state(&state_tx, url.as_ref());
390                }
391            })
392        };
393
394        // Clone the TKA authority publisher before `params` moves into `Self` below. The matching
395        // `Receiver` lives on the peer tracker; this sender is the sole writer (enforce on sync,
396        // clear on disable).
397        let tka_authority = params.tka_authority.clone();
398
399        Ok(Self {
400            client,
401            params,
402            self_node: Default::default(),
403            ssh_policy: Default::default(),
404            tka: Default::default(),
405            tka_synced: None,
406            tka_authority,
407            tka_syncing: false,
408            tka_generation: 0,
409            cert_domains: Default::default(),
410            dns_config: Default::default(),
411            pop_browser_url: Default::default(),
412            netcheck: Default::default(),
413            home_region: None,
414            derp_report_history: Vec::new(),
415            reauth_attempts: 0,
416            reauth_bridge,
417        })
418    }
419}
420
421impl ControlRunner {
422    /// Decide whether the latest netmap's Tailnet-Lock status warrants a (re)sync and, if so, spawn
423    /// the bootstrap+sync RPC off the actor thread (so the netmap stream never blocks on a control
424    /// round-trip). The result returns via the [`TkaSynced`] self-message.
425    ///
426    /// Triggers when control reports TKA enabled (`is_enabled`) AND we are not already syncing AND
427    /// either we hold no `Authority` yet (→ bootstrap) or control's head differs from ours (→ catch
428    /// up). When TKA is disabled, clears any synced state (the lock was turned off). Mirrors Go's
429    /// `tkaSyncIfNeeded`: a no-op when our head already matches.
430    fn maybe_sync_tka(&mut self, tka: &TkaStatus, self_ref: ActorRef<Self>) {
431        if !tka.is_enabled() {
432            // Lock disabled (or never enabled): clear enforcement by writing `None` to the authority
433            // cell the peer tracker reads — synchronously, so it can never be reordered behind or
434            // dropped before a stale `Some` (the failure a best-effort broadcast had). Always bump the
435            // generation so ANY sync currently in flight is invalidated: without this, a disable that
436            // races an in-flight sync (whose `take()` already cleared `tka_synced`) would be a no-op
437            // here, and the sync's late `Ok(Some)` would silently re-enable a lock control just turned
438            // off (the in-flight window the `tka_synced.is_some()` guard alone misses). Cheap and
439            // idempotent: clearing an already-`None` cell and bumping the generation are harmless.
440            self.tka_generation = self.tka_generation.wrapping_add(1);
441            if self.tka_synced.is_some() {
442                tracing::info!("TKA lock disabled; clearing enforcement (admitting all peers)");
443                self.tka_synced = None;
444            }
445            self.tka_authority.send_replace(None);
446            return;
447        }
448        if self.tka_syncing {
449            return; // a sync is already in flight; the next netmap will re-trigger if still stale
450        }
451        // Up-to-date check: if we already have an Authority whose head matches control's, nothing to
452        // do. A malformed control head is treated as "different" (we'll attempt a sync, which
453        // fail-closes harmlessly).
454        if let Some(synced) = &self.tka_synced
455            && let Some(control_head) = ts_tka::AumHash::from_base32(&tka.head)
456            && synced.authority.head_matches(&control_head)
457        {
458            return;
459        }
460
461        // Spawn the sync. Move the current synced state out (the driver takes it by value and returns
462        // the advanced state); `tka_synced` stays `None` until the result lands, guarded by
463        // `tka_syncing` so we don't spawn a second concurrent sync. Capture the current generation so
464        // `apply_tka_synced` can discard this result if a disable bumped the generation while the sync
465        // was in flight (H1: don't re-enable a lock that was disabled mid-sync).
466        self.tka_syncing = true;
467        let generation = self.tka_generation;
468        let current = self.tka_synced.take();
469        let config = self.params.config.clone();
470        let keys = self.params.env.keys.clone();
471        tokio::spawn(async move {
472            let result = crate::tka_sync::sync_tka(&config, &keys, current).await;
473            // Hand the outcome back to the actor thread to apply (mutating actor state off-thread is
474            // not allowed). A send failure just means the actor is gone — nothing to do.
475            if let Err(e) = self_ref.tell(TkaSynced { result, generation }).await {
476                tracing::debug!(error = ?e, "TKA sync result not delivered (actor gone)");
477            }
478        });
479    }
480
481    /// Apply the outcome of a spawned [`maybe_sync_tka`] task on the actor thread: store the advanced
482    /// state + publish the `Authority` to the peer tracker's enforcement cell (or, on inert/failed
483    /// sync, leave peers unaffected). Always clears the in-flight guard.
484    ///
485    /// `generation` is the value captured when the sync was spawned. If it no longer matches
486    /// `self.tka_generation`, the lock was disabled (or re-synced) while this sync was in flight, so
487    /// the result is discarded — never re-enabling an authority control has since turned off.
488    async fn apply_tka_synced(
489        &mut self,
490        result: Result<Option<crate::tka_sync::SyncedTka>, crate::tka_sync::TkaSyncDriverError>,
491        generation: u64,
492    ) {
493        self.tka_syncing = false;
494
495        // H1 guard: a disable (or a superseding sync) bumped the generation while this sync ran. Drop
496        // the stale result — `maybe_sync_tka`'s disable branch already cleared enforcement to `None`,
497        // and re-applying this `Some` would re-enforce a lock that is no longer active.
498        if generation != self.tka_generation {
499            tracing::info!(
500                "TKA sync result superseded (lock disabled or re-synced mid-flight); discarding"
501            );
502            return;
503        }
504
505        match result {
506            Ok(Some(synced)) => {
507                tracing::info!(
508                    head = %synced.authority.head().to_base32(),
509                    "TKA sync succeeded; enforcing verified Authority (Go tkaFilterNetmapLocked)"
510                );
511                // Deliver the verified Authority to the peer tracker's enforcement cell. The tracker
512                // reads it on every peer upsert and drops unauthorized peers. `Some(..)` = enforce; a
513                // `None` is written on disable. `watch` is the sole channel (last-write-wins, never
514                // dropped, ordered by this actor) — no bus, no re-publish-for-replay needed.
515                self.tka_authority
516                    .send_replace(Some(synced.authority.clone()));
517
518                // Observability (Go `tkaFilterNetmapLocked`'s self check → `LockedOut` health
519                // warning): verify SELF's own node-key signature against the freshly-synced
520                // Authority and warn if self is NOT authorized. We never FILTER self (self never
521                // enters the peer db, so enforcement can't lock us out of our own netmap), but Go
522                // raises an operator-facing warning here because a self that the lock does not
523                // authorize means this node's key-signature is missing/invalid for the current lock
524                // — it will be unable to prove itself to locked peers. This fork has no health
525                // subsystem, so the signal is a `tracing::warn!` (its observability channel).
526                //
527                // `self_node` is a sticky cell set on every netmap carrying a self-node; if a sync
528                // somehow lands before the first self-node ever arrived it is `None`, so we skip the
529                // advisory this cycle and re-evaluate on the next sync — fine for observability-only.
530                // The `borrow()` ref is scoped to this `if let` and dropped before the `&mut self`
531                // write below.
532                if let Some(self_node) = self.self_node.borrow().as_ref() {
533                    log_self_lockout(self_node, &synced.authority);
534                }
535
536                self.tka_synced = Some(synced);
537            }
538            Ok(None) => {
539                // Control has no lock for us (no genesis / disabled). Clear any authority we were
540                // previously enforcing — symmetric with the disable path — so a transition to
541                // "no lock" stops dropping peers. Not an error.
542                if self.tka_synced.is_some() {
543                    tracing::info!("TKA sync: control reports no lock; clearing enforcement");
544                    self.tka_synced = None;
545                }
546                self.tka_authority.send_replace(None);
547            }
548            Err(e) => {
549                // Transport or verify failure: log and leave the prior authority in place (a failed
550                // sync must not drop enforcement — that would fail OPEN). NEVER errors the netmap.
551                // The next netmap update re-triggers a sync attempt.
552                tracing::warn!(error = %e, "TKA sync failed; keeping prior enforcement state");
553            }
554        }
555    }
556
557    fn with_self_node<F, R>(&self, f: F) -> impl Future<Output = Option<R>> + use<F, R>
558    where
559        F: FnOnce(&Node) -> R,
560    {
561        let mut sub = self.self_node.subscribe();
562        let mut shutdown = self.params.env.shutdown.clone();
563
564        async move {
565            tokio::select! {
566                _ = shutdown.wait_for(|x| *x) => {
567                    None
568                },
569                node = sub.wait_for(Option::is_some) => {
570                    Some(f(node.ok()?.as_ref()?))
571                },
572            }
573        }
574    }
575}
576
577/// Apply Go's sticky `PopBrowserURL` semantics to the consent-URL `watch` cell.
578///
579/// Control sends `MapResponse.PopBrowserURL` empty on nearly every netmap update, so the cell is
580/// updated ONLY when `incoming` is a non-empty URL that differs from the cell's current value —
581/// Go's `direct.go` guard `u != "" && u != sess.lastPopBrowserURL`. The cell is **never reset to
582/// `None`** by an empty/absent update — the running-node consent URL is sticky for the session.
583/// Updating unconditionally would thrash the cell to `None` on every tick and coalesce the URL away
584/// for a `watch`/bus subscriber.
585///
586/// The dedupe is in-place via [`watch::Sender::send_if_modified`] — the cell's own value is the
587/// "last URL sent" (this sticky path is its only writer), so no separate mirror field is needed and
588/// the watch is woken only on a genuine change (Go's `sess.lastPopBrowserURL` role, for free). This
589/// matches the [`send_if_modified`](watch::Sender::send_if_modified) idiom already used for the
590/// device-state cell in this handler.
591///
592/// Factored out of the netmap-update handler so the (easy-to-regress) sticky logic is unit-testable
593/// against a plain `watch` channel without standing up the actor.
594fn sticky_update_pop_browser_url(
595    cell: &watch::Sender<Option<url::Url>>,
596    incoming: Option<&url::Url>,
597) {
598    if let Some(url) = incoming {
599        cell.send_if_modified(|current| {
600            if current.as_ref() == Some(url) {
601                false
602            } else {
603                *current = Some(url.clone());
604                true
605            }
606        });
607    }
608}
609
610/// Map a mid-session re-auth URL surfaced by the control client onto the device-state cell.
611///
612/// The control client's live map-poll loop publishes an `Option<url::Url>` into a `watch` cell when
613/// a re-register hits `MachineNotAuthorized` (the node key expired/was revoked mid-session — see
614/// [`ts_control::AsyncControlClient::connect`]'s `auth_url_tx`). `ts_control` cannot name
615/// [`DeviceState`] (it must not depend on this crate), so this bridge fn does the translation:
616/// a `Some(url)` sets [`DeviceState::NeedsLogin`]`(url)` so the IPN bus derives `browse_to_url` and
617/// the embedder can prompt the user, exactly like the initial-registration `check_auth` path.
618///
619/// **Only `Some` drives a transition; `None` is ignored here.** The clear back to
620/// [`DeviceState::Running`] is owned by the netmap self-node handler (the next good self-node flips
621/// it — see the `StreamMessage::Next` arm), which is the authoritative "we are up again" signal; an
622/// independent `None`-clear in this bridge could race that and is unnecessary. The
623/// [`send_if_modified`](watch::Sender::send_if_modified) guard fires the watch only on a genuine
624/// state change (it is a no-op when the cell already holds `NeedsLogin(url)` for the same URL), so a
625/// re-auth URL re-surfaced across retries does not thrash the cell — mirroring the device-state
626/// dedupe in the netmap handler.
627///
628/// Factored out so the (regress-prone) map-and-guard is unit-testable against a plain `watch`
629/// channel without standing up the actor (mirrors [`sticky_update_pop_browser_url`]).
630/// **Auto-reauth ownership.** While an automatic re-auth is in flight (the cell holds
631/// [`DeviceState::Reauthenticating`]), this bridge must NOT downgrade it to `NeedsLogin`. An
632/// auto-reauth's rotated re-register surfaces an auth URL through the SAME `auth_url_tx` cell this
633/// bridge watches, but on a headless / auth-key node there is no human to visit it — flipping to
634/// `NeedsLogin` would surface a misleading `browse_to_url` AND, by moving the cell off
635/// `Reauthenticating`, let the next expired self-node re-fire reauth (a second node-key rotation that
636/// loses the original `OldNodeKey` anchor). The auto-reauth path owns the cell until it recovers to
637/// `Running` (the netmap self-node handler) or its circuit breaker trips it to `Expired`; this bridge
638/// stands down for the duration.
639pub(crate) fn bridge_reauth_url_to_state(
640    state_tx: &watch::Sender<crate::DeviceState>,
641    incoming: Option<&url::Url>,
642) {
643    if let Some(url) = incoming {
644        let next = crate::DeviceState::NeedsLogin(url.clone());
645        state_tx.send_if_modified(|current| {
646            // Do not clobber an in-flight automatic re-auth (see the ownership note above): leave
647            // `Reauthenticating` untouched so it can recover to `Running` or trip to `Expired` on its
648            // own terms.
649            if *current == crate::DeviceState::Reauthenticating || *current == next {
650                false
651            } else {
652                *current = next.clone();
653                true
654            }
655        });
656    }
657}
658
659/// What to do when control delivers a self-node whose node-key expiry has passed — the decision
660/// behind the [`StreamMessage::Next`] handler's expiry branch, factored into a pure function so the
661/// full input matrix is unit-testable (mirrors [`bridge_reauth_url_to_state`] being pure).
662#[derive(Debug, Clone, Copy, PartialEq, Eq)]
663pub(crate) enum ExpiryAction {
664    /// The key is not expired — the node is up. (`→ DeviceState::Running`.)
665    Running,
666    /// The key expired and auto-reauth is permitted (auth key retained, reauth enabled, TKA NOT
667    /// enforcing): rotate the node key + re-register (`→ DeviceState::Reauthenticating` +
668    /// `Command::Reauth`).
669    Reauthenticate,
670    /// The key expired and auto-reauth is NOT permitted (no auth key, reauth disabled, or TKA
671    /// enforcing): fall back to today's terminal behavior (`→ DeviceState::Expired`).
672    Expired,
673}
674
675/// Decide the action for an expired-or-not self node (pure; the live handler at
676/// [`StreamMessage::Next`] applies it). Go's `ipnlocal` runs `doLogin` (rotate the node key +
677/// re-register with the stored auth key) when an auth-key node's key expires; this fork does the
678/// same, gated by three safety conditions:
679///
680/// - `key_expired` — control reported the self-node's key expiry is in the past.
681/// - `has_auth_key` — a usable auth key is retained for a non-interactive re-register (without one
682///   there is nothing to re-register with → fall back to `Expired`, today's behavior).
683/// - `reauth_enabled` — the `reauth_on_expiry` config opt-out is on (default true).
684/// - `tka_active` — Tailnet Lock enforcement is currently active. **Hard safety gate:** a node-key
685///   rotation on a locked tailnet would install an UNSIGNED key, locking the node out of locked
686///   peers (the TKA re-sign is a separate follow-up — see `keystate.rs` `rotate_node_key`). So when
687///   the lock is enforcing, never rotate — fall back to `Expired`.
688///
689/// Truth table: not expired → `Running`; expired AND auth-key AND reauth-enabled AND NOT TKA →
690/// `Reauthenticate`; otherwise → `Expired`.
691pub(crate) fn expiry_action(
692    key_expired: bool,
693    has_auth_key: bool,
694    reauth_enabled: bool,
695    tka_active: bool,
696) -> ExpiryAction {
697    if !key_expired {
698        return ExpiryAction::Running;
699    }
700    if has_auth_key && reauth_enabled && !tka_active {
701        ExpiryAction::Reauthenticate
702    } else {
703        ExpiryAction::Expired
704    }
705}
706
707/// The outcome of one step of the bounded reauth sub-state-machine: the device state to publish, the
708/// updated consecutive-attempt counter, and whether to fire the one-shot `Command::Reauth` this step.
709#[derive(Debug, Clone, Copy, PartialEq, Eq)]
710pub(crate) struct ReauthStep {
711    /// The device state to publish for this self-node.
712    pub next: ReauthState,
713    /// The consecutive-failed-reauth counter after this step (the caller stores it back).
714    pub attempts: u32,
715    /// Whether to fire the one-shot `Command::Reauth` (rotate + re-register) this step. Set ONLY on
716    /// the transition INTO reauthenticating, so the node key rotates at most once per episode.
717    pub fire_reauth: bool,
718}
719
720/// The device state a [`ReauthStep`] resolves to — the subset of [`DeviceState`](crate::DeviceState)
721/// the circuit breaker can produce. Kept as its own enum so the breaker stays pure (no dependency on
722/// the URL-carrying `DeviceState` variants) and the truth table is exhaustively testable.
723#[derive(Debug, Clone, Copy, PartialEq, Eq)]
724pub(crate) enum ReauthState {
725    /// The node is up — `→ DeviceState::Running`.
726    Running,
727    /// An automatic re-auth is in flight — `→ DeviceState::Reauthenticating`.
728    Reauthenticating,
729    /// Terminal expiry — `→ DeviceState::Expired` (either the non-reauth path or the breaker tripped).
730    Expired,
731}
732
733/// One step of the bounded reauth sub-state-machine (pure; the [`StreamMessage::Next`] handler stores
734/// the result back into [`ControlRunner::reauth_attempts`] and publishes [`ReauthStep::next`]). This
735/// is the circuit breaker for the design's deferred-question Q1: a one-shot / already-consumed auth
736/// key cannot re-register, so the `Reauthenticate` path must settle rather than loop forever.
737///
738/// Inputs:
739/// - `action` — the [`expiry_action`] verdict for this self-node.
740/// - `already_reauthing` — whether the published state is currently
741///   [`DeviceState::Reauthenticating`](crate::DeviceState::Reauthenticating) (the prior reauth has
742///   not yet recovered the node).
743/// - `attempts` — the current consecutive-failed-reauth counter.
744///
745/// Rules:
746/// - `Running` → reset the counter to `0` (the node recovered) and report `Running`.
747/// - `Reauthenticate` while NOT already reauthing → ENTER reauthenticating: counter `= 1`, fire the
748///   one-shot reauth.
749/// - `Reauthenticate` while ALREADY reauthing → the prior reauth did not recover; COUNT it (counter
750///   `+= 1`) and do NOT re-fire (a second rotation would lose the original `OldNodeKey` anchor). At
751///   [`MAX_REAUTH_ATTEMPTS`] the breaker trips to terminal `Expired`; below the cap, stay reauthing.
752/// - `Expired` → terminal; the counter is irrelevant (this path never armed the reauth machine), so
753///   it is reset to `0`.
754pub(crate) fn reauth_circuit_step(
755    action: ExpiryAction,
756    already_reauthing: bool,
757    attempts: u32,
758) -> ReauthStep {
759    match action {
760        ExpiryAction::Running => ReauthStep {
761            next: ReauthState::Running,
762            attempts: 0,
763            fire_reauth: false,
764        },
765        ExpiryAction::Reauthenticate if !already_reauthing => ReauthStep {
766            next: ReauthState::Reauthenticating,
767            attempts: 1,
768            fire_reauth: true,
769        },
770        ExpiryAction::Reauthenticate => {
771            let attempts = attempts.saturating_add(1);
772            if attempts >= MAX_REAUTH_ATTEMPTS {
773                ReauthStep {
774                    next: ReauthState::Expired,
775                    attempts,
776                    fire_reauth: false,
777                }
778            } else {
779                ReauthStep {
780                    next: ReauthState::Reauthenticating,
781                    attempts,
782                    fire_reauth: false,
783                }
784            }
785        }
786        ExpiryAction::Expired => ReauthStep {
787            next: ReauthState::Expired,
788            attempts: 0,
789            fire_reauth: false,
790        },
791    }
792}
793
794/// The classification of SELF against the active network lock — the observability analog of Go
795/// `tkaFilterNetmapLocked`'s self check (which raises a `LockedOut` health warning).
796#[derive(Debug, Clone, PartialEq, Eq)]
797enum SelfLockVerdict {
798    /// Self carries no key-signature at all (empty). The common "not signed yet" case: the node
799    /// simply has not been signed for this lock — not locked out, just unsigned.
800    Unsigned,
801    /// Self's key-signature is authorized by the active lock; nothing to warn about.
802    Authorized,
803    /// Self has a key-signature but the lock does NOT authorize it (the message is the verify
804    /// error). The operator-facing `LockedOut` condition: locked peers will reject this node.
805    LockedOut(String),
806}
807
808/// Classify a node key + its key-signature against `authority` (pure: verify-and-classify, no
809/// logging, no I/O). Takes only the two fields it needs — not the whole `Node` — so the decision is
810/// unit-testable without constructing a full `Node` or standing up the actor.
811fn self_lock_verdict(
812    node_key: &ts_keys::NodePublicKey,
813    key_signature: &[u8],
814    authority: &ts_tka::Authority,
815) -> SelfLockVerdict {
816    // Mirror the peer path (`peer_tracker` `tka_snapshot_admits`): treat an empty signature as
817    // "unsigned" rather than the `LockedOut` bucket Go's `NodeKeyAuthorized` would put a nil sig in
818    // (it errors at decode). This is a deliberate, narrow divergence from a literal Go port: it
819    // avoids `warn`-spam on a lock that simply has not signed this node yet, and keeps self and peer
820    // classification consistent.
821    if key_signature.is_empty() {
822        return SelfLockVerdict::Unsigned;
823    }
824    match authority.node_key_authorized(&node_key.to_bytes(), key_signature) {
825        Ok(()) => SelfLockVerdict::Authorized,
826        Err(e) => SelfLockVerdict::LockedOut(e.to_string()),
827    }
828}
829
830/// Emit the self-locked-out observability signal (Go `tkaFilterNetmapLocked`'s self check → a
831/// `LockedOut` health warning): classify SELF against the freshly-synced `authority` and log.
832///
833/// This is **observability, not enforcement** — self never enters the peer db, so the lock can never
834/// filter our own node out of the netmap. But a self the lock does not authorize means this node's
835/// key-signature is absent or invalid for the active lock, so it cannot prove itself to locked peers
836/// (they will drop it); surfacing that lets an operator notice and re-sign. A never-signed node
837/// (empty signature) logs at `info`, distinct from a present-but-invalid signature (`warn`), so the
838/// common unsigned case does not spam a warning. This fork has no health subsystem, so the operator
839/// signal is a `tracing` event (its observability channel).
840fn log_self_lockout(self_node: &Node, authority: &ts_tka::Authority) {
841    match self_lock_verdict(&self_node.node_key, &self_node.key_signature, authority) {
842        SelfLockVerdict::Unsigned => tracing::info!(
843            "TKA: this node has no key-signature for the active lock; it cannot prove itself to \
844             locked peers until control signs it (not locked out, just unsigned)"
845        ),
846        SelfLockVerdict::Authorized => {
847            tracing::debug!("TKA: self node-key is authorized by the active lock")
848        }
849        SelfLockVerdict::LockedOut(error) => tracing::warn!(
850            %error,
851            "TKA self locked out: this node's key-signature is not authorized by the active \
852             network lock; locked peers will reject it until control re-signs this node \
853             (Go LockedOut)"
854        ),
855    }
856}
857
858// The `#[kameo::messages]` macro generates message structs whose fields mirror the method params;
859// those generated fields carry no doc and can't take attributes, so wrap in a module where
860// missing-docs is allowed (same pattern as PeerTracker's `msg_impl`). The generated message structs
861// are re-exported so callers keep referencing them at `control_runner::<Name>`.
862pub use msg_impl::*;
863
864#[allow(missing_docs)]
865mod msg_impl {
866    use kameo::{message::Context, reply::DelegatedReply};
867
868    use super::*;
869
870    #[kameo::messages]
871    impl ControlRunner {
872        /// Fetch the IPv4 address for this tailscale device.
873        #[message(ctx)]
874        pub fn ipv4(
875            &self,
876            ctx: &mut Context<Self, DelegatedReply<Option<Ipv4Addr>>>,
877        ) -> DelegatedReply<Option<Ipv4Addr>> {
878            let (deleg, replier) = ctx.reply_sender();
879
880            if let Some(replier) = replier {
881                let fut = self.with_self_node(|node| node.tailnet_address.ipv4.addr());
882
883                tokio::spawn(async move {
884                    let ip = fut.await;
885                    replier.send(ip);
886                });
887            }
888
889            deleg
890        }
891
892        /// Fetch the IPv6 address for this tailscale device.
893        #[message(ctx)]
894        pub fn ipv6(
895            &self,
896            ctx: &mut Context<Self, DelegatedReply<Option<Ipv6Addr>>>,
897        ) -> DelegatedReply<Option<Ipv6Addr>> {
898            let (deleg, replier) = ctx.reply_sender();
899
900            if let Some(replier) = replier {
901                let fut = self.with_self_node(|node| node.tailnet_address.ipv6.addr());
902
903                tokio::spawn(async move {
904                    let ip = fut.await;
905                    replier.send(ip);
906                });
907            }
908
909            deleg
910        }
911
912        /// Fetch the self node for this tailscale device.
913        #[message(ctx)]
914        pub fn self_node(
915            &self,
916            ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
917        ) -> DelegatedReply<Option<Node>> {
918            let (deleg, replier) = ctx.reply_sender();
919
920            if let Some(replier) = replier {
921                let node = self.with_self_node(|node| node.clone());
922
923                tokio::spawn(async move {
924                    let node = node.await;
925                    replier.send(node)
926                });
927            }
928
929            deleg
930        }
931
932        /// Fetch the current Tailscale SSH policy, if control has pushed one.
933        ///
934        /// Returns `None` when control has not sent an SSH policy (the SSH server treats this as
935        /// deny-all — fail-closed). Unlike `self_node` this does not block waiting
936        /// for a value: an absent policy is a legitimate, immediate answer.
937        #[message]
938        pub fn current_ssh_policy(&self) -> Option<SshPolicy> {
939            self.ssh_policy.borrow().clone()
940        }
941
942        /// Fetch the current Tailnet Lock status, if control has pushed one.
943        ///
944        /// Returns `None` when control has sent no `TKAInfo` (tailnet lock not in use / no change seen).
945        #[message]
946        pub fn current_tka_status(&self) -> Option<TkaStatus> {
947            self.tka.borrow().clone()
948        }
949
950        /// Read up to `limit` entries of the Tailnet-Lock update-chain log, **head-first** (newest →
951        /// oldest), from the locally-synced AUM chain (Go `NetworkLockLog`).
952        ///
953        /// A **pure local read** — no crypto, no mutation, no control round-trip: it walks the
954        /// already-verified `SyncedTka` store this actor owns. Returns an empty `Vec` when no lock is
955        /// synced (Go's `b.tka == nil`). Synchronous (no spawn), like `current_tka_status` — the
956        /// chain is in memory.
957        #[message]
958        pub fn tka_log(&self, limit: usize) -> Vec<crate::tka_sync::TkaLogEntry> {
959            let Some(synced) = self.tka_synced.as_ref() else {
960                return Vec::new();
961            };
962            crate::tka_sync::tka_log_entries(&synced.store, synced.oldest, limit)
963        }
964
965        /// Sign `node_key` directly with this node's network-lock key and submit the signature to
966        /// control (Go `tka.sign` for the Direct case → `tkaSubmitSignature`).
967        ///
968        /// Builds a `Direct` [`NodeKeySignature`](ts_tka::NodeKeySignature) via
969        /// [`sign_direct`](ts_tka::NodeKeySignature::sign_direct) over this node's inner ed25519
970        /// network-lock signing key, serializes it (raw CBOR), and POSTs it to `/machine/tka/sign`.
971        /// Mirrors `set_dns`/`get_certificate`: clones the control config + node keys into a spawned
972        /// task (delegated reply, so the round-trip doesn't block the mailbox) over a fresh Noise
973        /// channel.
974        ///
975        /// **Posture: this only *submits* a signature to control — it does NOT mutate the local
976        /// [`Authority`](ts_tka::Authority).** The local trusted-key state advances solely through the
977        /// existing verified-sync path (`sync_tka` → `VerifiedAumChain::verify`); a `tka_sign` success
978        /// is acknowledged to the caller, and the resulting AUM is picked up on the next netmap-driven
979        /// sync. Verify-and-log is unchanged.
980        #[message(ctx)]
981        pub fn tka_sign(
982            &self,
983            ctx: &mut Context<Self, DelegatedReply<Result<(), TkaSyncError>>>,
984            node_key: [u8; 32],
985        ) -> DelegatedReply<Result<(), TkaSyncError>> {
986            let (deleg, replier) = ctx.reply_sender();
987
988            if let Some(replier) = replier {
989                let config = self.params.config.clone();
990                let keys = self.params.env.keys.clone();
991                tokio::spawn(async move {
992                    // Sign the node key with our network-lock key, then submit the raw-CBOR NKS.
993                    let nks = ts_tka::NodeKeySignature::sign_direct(
994                        &node_key,
995                        &keys.network_lock_keys.private.signing_key(),
996                    );
997                    let req = ts_control::TkaSubmitSignatureRequest {
998                        // node_key + version are stamped by the RPC client from `keys`.
999                        version: Default::default(),
1000                        node_key: keys.node_keys.public,
1001                        signature: nks.serialize(),
1002                    };
1003                    let result = tka_submit_signature(
1004                        &config.server_url,
1005                        &keys,
1006                        req,
1007                        config.allow_http_key_fetch,
1008                    )
1009                    .await
1010                    .map(|_response| ());
1011                    replier.send(result);
1012                });
1013            }
1014
1015            deleg
1016        }
1017
1018        /// Disable Tailnet Lock by presenting the disablement secret to control (Go
1019        /// `tka.disable` → `/machine/tka/disable`).
1020        ///
1021        /// Targets the **current** authority head (read from the cached [`TkaStatus`]); the caller
1022        /// supplies the `disablement_secret` out of band (it is the operator-held capability that
1023        /// authorizes turning the lock off). Mirrors `tka_sign`: clones config + keys into a spawned
1024        /// task (delegated reply). Returns [`TkaSyncError::Unsupported`] when there is no known TKA
1025        /// head (lock not in use / control hasn't pushed a status), since there is nothing to disable.
1026        ///
1027        /// **Submit-only, like `tka_sign`:** this POSTs the disablement to control and does NOT mutate
1028        /// the local [`Authority`](ts_tka::Authority). Control acts on the disablement; this node
1029        /// observes the result through the existing verified-sync path. Verify-and-log unchanged.
1030        #[message(ctx)]
1031        pub fn tka_disable(
1032            &self,
1033            ctx: &mut Context<Self, DelegatedReply<Result<(), TkaSyncError>>>,
1034            disablement_secret: Vec<u8>,
1035        ) -> DelegatedReply<Result<(), TkaSyncError>> {
1036            let (deleg, replier) = ctx.reply_sender();
1037
1038            if let Some(replier) = replier {
1039                // Read the current head from the cached status BEFORE the spawn (can't borrow &self
1040                // across the await). No head ⇒ no lock to disable ⇒ Unsupported.
1041                let head = self.tka.borrow().as_ref().map(|s| s.head.clone());
1042                let config = self.params.config.clone();
1043                let keys = self.params.env.keys.clone();
1044                tokio::spawn(async move {
1045                    let result = match head {
1046                        Some(head) => {
1047                            let req = ts_control::TkaDisableRequest {
1048                                // node_key + version are stamped by the RPC client from `keys`.
1049                                version: Default::default(),
1050                                node_key: keys.node_keys.public,
1051                                head,
1052                                disablement_secret,
1053                            };
1054                            tka_disable(&config.server_url, &keys, req, config.allow_http_key_fetch)
1055                                .await
1056                                .map(|_response| ())
1057                        }
1058                        None => Err(TkaSyncError::Unsupported),
1059                    };
1060                    replier.send(result);
1061                });
1062            }
1063
1064            deleg
1065        }
1066
1067        /// Initialize Tailnet Lock with this node as the sole initial trusted key, gated by
1068        /// `disablement_secret` (Go `LocalClient.NetworkLockInit` — the "lock yourself in" case).
1069        ///
1070        /// Builds + signs a genesis Checkpoint AUM whose only trusted key is this node's network-lock
1071        /// public key (votes 1) and whose single DisablementValue is `disablement_value(secret)`, then
1072        /// drives the two-phase init: `tka/init/begin` (submit the genesis) → if control needs no
1073        /// further node signatures (`NeedSignatures` empty, the case when this node is the only key) →
1074        /// `tka/init/finish` carrying the raw `disablement_secret` as `SupportDisablement`. Mirrors
1075        /// `tka_sign`/`tka_disable`: cloned config + keys into a spawned task (delegated reply).
1076        ///
1077        /// If control returns a non-empty `NeedSignatures` (other nodes must be re-signed under the new
1078        /// lock — a multi-node tailnet), this returns [`TkaSyncError::Unsupported`]: re-signing each
1079        /// listed node (incl. the Rotation-key case) is a larger flow deferred to a fuller
1080        /// `tka_init(keys, secrets)` — the single-node lock-init is the shipped subset.
1081        ///
1082        /// **Submit-only**, like `tka_sign`/`tka_disable`: this creates the lock at control and does
1083        /// NOT seed the local [`Authority`](ts_tka::Authority) — the node picks up the new lock through
1084        /// the existing verified netmap-sync (control pushes a `TKAInfo`, `maybe_sync_tka` bootstraps
1085        /// the genesis through `VerifiedAumChain::verify`). Verify-and-log posture unchanged.
1086        #[message(ctx)]
1087        pub fn tka_init(
1088            &self,
1089            ctx: &mut Context<Self, DelegatedReply<Result<(), TkaSyncError>>>,
1090            disablement_secret: Vec<u8>,
1091        ) -> DelegatedReply<Result<(), TkaSyncError>> {
1092            let (deleg, replier) = ctx.reply_sender();
1093
1094            if let Some(replier) = replier {
1095                let config = self.params.config.clone();
1096                let keys = self.params.env.keys.clone();
1097                tokio::spawn(async move {
1098                    let result = tka_init_run(&config, &keys, disablement_secret).await;
1099                    replier.send(result);
1100                });
1101            }
1102
1103            deleg
1104        }
1105
1106        /// The cert-eligible DNS names from control's netmap DNS config (Go `nm.DNS.CertDomains`).
1107        ///
1108        /// Returns an empty `Vec` when control has sent no DNS config, or one carrying no cert
1109        /// domains (an empty list is a legitimate, immediate answer — like `current_ssh_policy`, this
1110        /// does not block waiting for a value).
1111        #[message]
1112        pub fn cert_domains(&self) -> Vec<String> {
1113            self.cert_domains.borrow().clone()
1114        }
1115
1116        /// The full DNS config from control's netmap (Go `netmap.NetworkMap.DNS`), or `None` when
1117        /// control has sent no DNS config yet. An immediate answer (does not block); the facade
1118        /// surfaces this for `Device::dns_config` (the daemon's `tnet dns status`).
1119        #[message]
1120        pub fn dns_config(&self) -> Option<ts_control::DnsConfig> {
1121            self.dns_config.borrow().clone()
1122        }
1123
1124        /// The interactive-login / consent URL control last asked this node to open
1125        /// (`MapResponse.PopBrowserURL`), or `None` when control has sent none. An immediate answer
1126        /// (does not block); the facade surfaces this for `Device::pop_browser_url`.
1127        #[message]
1128        pub fn pop_browser_url(&self) -> Option<url::Url> {
1129            self.pop_browser_url.borrow().clone()
1130        }
1131
1132        /// Subscribe to the interactive-login / consent URL cell (`MapResponse.PopBrowserURL`).
1133        ///
1134        /// Returns a [`watch::Receiver`] whose value is the latest running-node consent URL, used by
1135        /// [`Runtime::watch_ipn_bus`](crate::Runtime::watch_ipn_bus) to surface `browse_to_url`
1136        /// events mid-session. The cell is sticky (updated only on a new non-empty URL, never reset
1137        /// to `None` by an empty update — see the field docs), so a subscriber is not thrashed and a
1138        /// late subscriber sees the current URL. The initial value is `None` until control sends one.
1139        #[message(derive(Clone))]
1140        pub fn watch_browser_url(&self) -> watch::Receiver<Option<url::Url>> {
1141            self.pop_browser_url.subscribe()
1142        }
1143
1144        /// The latest network-conditions report (preferred DERP region + per-region latencies). An
1145        /// immediate answer (does not block); empty before the first DERP-latency measurement. The
1146        /// facade surfaces this for `Device::netcheck` (the daemon's `tnet netcheck`).
1147        #[message]
1148        pub fn netcheck(&self) -> crate::status::NetcheckReport {
1149            self.netcheck.borrow().clone()
1150        }
1151
1152        /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
1153        ///
1154        /// Opens a fresh Noise channel and POSTs `/machine/id-token`; returns the signed JWT or an
1155        /// [`IdTokenError`]. Runs on a spawned task (delegated reply) so the actor mailbox isn't blocked
1156        /// for the round-trip.
1157        #[message(ctx)]
1158        pub fn fetch_id_token(
1159            &self,
1160            ctx: &mut Context<Self, DelegatedReply<Result<String, IdTokenError>>>,
1161            audience: String,
1162        ) -> DelegatedReply<Result<String, IdTokenError>> {
1163            let (deleg, replier) = ctx.reply_sender();
1164
1165            if let Some(replier) = replier {
1166                let config = self.params.config.clone();
1167                let keys = self.params.env.keys.clone();
1168                tokio::spawn(async move {
1169                    let result = ts_control::fetch_id_token(&config, &keys, &audience).await;
1170                    replier.send(result);
1171                });
1172            }
1173
1174            deleg
1175        }
1176
1177        /// Log this node out of the tailnet: deregister it by expiring its current node key.
1178        ///
1179        /// Mirrors `fetch_id_token`: clones the control config + node keys
1180        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox) and
1181        /// re-POSTs `/machine/register` with a past expiry over a fresh Noise channel. This is a
1182        /// control-plane state change only — it does NOT stop this actor or tear down the datapath
1183        /// (the caller follows up with the normal runtime shutdown), and it does not touch the
1184        /// on-disk node key, so re-registering with the same key is the re-login path.
1185        #[message(ctx)]
1186        pub fn logout(
1187            &self,
1188            ctx: &mut Context<Self, DelegatedReply<Result<(), LogoutError>>>,
1189        ) -> DelegatedReply<Result<(), LogoutError>> {
1190            let (deleg, replier) = ctx.reply_sender();
1191
1192            if let Some(replier) = replier {
1193                let config = self.params.config.clone();
1194                let keys = self.params.env.keys.clone();
1195                tokio::spawn(async move {
1196                    let result = ts_control::logout(&config, &keys).await;
1197                    replier.send(result);
1198                });
1199            }
1200
1201            deleg
1202        }
1203
1204        /// Publish a DNS record for this node via control's `/machine/set-dns` (Go
1205        /// `LocalClient.SetDNS`).
1206        ///
1207        /// Mirrors `fetch_id_token`: clones the control config + node keys
1208        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox) and
1209        /// POSTs the record over a fresh Noise channel. Go's `SetDNS` is `TXT`-only (its sole use is
1210        /// the ACME DNS-01 `_acme-challenge` record); the record type is fixed to `"TXT"` here to
1211        /// match, so the surfaced API takes only `name` + `value`.
1212        #[message(ctx)]
1213        pub fn set_dns(
1214            &self,
1215            ctx: &mut Context<Self, DelegatedReply<Result<(), SetDnsError>>>,
1216            name: String,
1217            value: String,
1218        ) -> DelegatedReply<Result<(), SetDnsError>> {
1219            let (deleg, replier) = ctx.reply_sender();
1220
1221            if let Some(replier) = replier {
1222                let config = self.params.config.clone();
1223                let keys = self.params.env.keys.clone();
1224                tokio::spawn(async move {
1225                    let result = ts_control::set_dns(&config, &keys, &name, "TXT", &value).await;
1226                    replier.send(result);
1227                });
1228            }
1229
1230            deleg
1231        }
1232    }
1233
1234    /// The reply type of the [`get_cert_pair`](ControlRunner::get_cert_pair) message: the issued
1235    /// `(cert_chain_pem, key_pem)` PEM pair (the `tnet cert` surface) or a [`ts_control::CertError`].
1236    /// Aliased so the message's `Context` type stays under clippy's `type_complexity` bar (the
1237    /// nested `Result<(String, String), _>` trips it inline).
1238    #[cfg(feature = "acme")]
1239    pub type CertPairReply = Result<(String, String), ts_control::CertError>;
1240
1241    // The `acme`-gated cert-issuance message lives in its own `#[kameo::messages]` impl block so the
1242    // proc-macro never sees it in a non-`acme` build (a `#[cfg]` *inside* a single messages-impl
1243    // block is not honored by the macro's generated dispatch — it would emit a `GetCertificate`
1244    // handler calling a `get_certificate` method that the same `#[cfg]` strips). A separate gated
1245    // block keeps the default build clean.
1246    #[cfg(feature = "acme")]
1247    #[kameo::messages]
1248    impl ControlRunner {
1249        /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` via the
1250        /// client-side ACME DNS-01 engine (`acme` feature).
1251        ///
1252        /// Mirrors `fetch_id_token`: clones the control config + node keys
1253        /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox), loads
1254        /// or generates the ACME account key, and runs issuance against Let's Encrypt production,
1255        /// publishing the DNS-01 challenge TXT through the node's `POST /machine/set-dns` RPC.
1256        ///
1257        /// The account key is loaded from [`ts_keys::NodeState::acme_account_key`] (PKCS#8 DER) when
1258        /// present, so the same ACME account persists across renewals; otherwise an ephemeral key is
1259        /// generated for this call only (a fresh ACME account each issuance — acceptable for v1; LE
1260        /// allows it). Persisting a generated key back into the key file is the embedder's job (no
1261        /// write-back path here). SaaS-only: against a self-hosted control plane the set-dns
1262        /// publish 501s.
1263        #[message(ctx)]
1264        pub fn get_certificate(
1265            &self,
1266            ctx: &mut Context<
1267                Self,
1268                DelegatedReply<Result<ts_control::tls::CertifiedKey, ts_control::CertError>>,
1269            >,
1270            name: String,
1271        ) -> DelegatedReply<Result<ts_control::tls::CertifiedKey, ts_control::CertError>> {
1272            let (deleg, replier) = ctx.reply_sender();
1273
1274            if let Some(replier) = replier {
1275                let config = self.params.config.clone();
1276                let keys = self.params.env.keys.clone();
1277                tokio::spawn(async move {
1278                    let result = issue_certificate(&config, &keys, &name).await;
1279                    replier.send(result);
1280                });
1281            }
1282
1283            deleg
1284        }
1285
1286        /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` and return the
1287        /// **PEM pair** — `(cert_chain_pem, key_pem)` — for writing the on-disk `.crt` + `.key`
1288        /// (the daemon's `tnet cert`, Go's `LocalClient.CertPair`). `acme` feature.
1289        ///
1290        /// Identical issuance to [`get_certificate`](Self::get_certificate) (same client-side ACME
1291        /// DNS-01 flow, same set-dns publish, same account-key handling), only the *shape* of the
1292        /// result differs: this surfaces the raw chain + leaf-key PEMs instead of the opaque
1293        /// [`CertifiedKey`](ts_control::tls::CertifiedKey). The leaf **private key** PEM is the
1294        /// second tuple element and is NEVER logged — the spawned task sends it straight back to the
1295        /// replier. SaaS-only: against a self-hosted control plane the set-dns publish 501s.
1296        #[message(ctx)]
1297        pub fn get_cert_pair(
1298            &self,
1299            ctx: &mut Context<Self, DelegatedReply<CertPairReply>>,
1300            name: String,
1301        ) -> DelegatedReply<CertPairReply> {
1302            let (deleg, replier) = ctx.reply_sender();
1303
1304            if let Some(replier) = replier {
1305                let config = self.params.config.clone();
1306                let keys = self.params.env.keys.clone();
1307                tokio::spawn(async move {
1308                    let result = issue_cert_pair(&config, &keys, &name).await;
1309                    replier.send(result);
1310                });
1311            }
1312
1313            deleg
1314        }
1315    }
1316}
1317
1318/// The `tka_init` body (the genesis-build + two-phase init/begin→init/finish choreography),
1319/// factored out of the actor handler so it runs in the spawned task. See [`ControlRunner::tka_init`].
1320///
1321/// "Lock yourself in": the genesis trusts only this node's network-lock key (votes 1) and stores one
1322/// DisablementValue = `disablement_value(secret)`. On a non-empty `NeedSignatures` (multi-node
1323/// tailnet needing re-signs) it returns [`TkaSyncError::Unsupported`] — the single-node subset.
1324async fn tka_init_run(
1325    config: &ts_control::Config,
1326    keys: &ts_keys::NodeState,
1327    disablement_secret: Vec<u8>,
1328) -> Result<(), TkaSyncError> {
1329    // Build the genesis: this node's NL public key as the sole trusted key, one disablement value.
1330    let nl_public = keys.network_lock_keys.public.to_bytes().to_vec();
1331    let genesis_key = ts_tka::AumKey {
1332        kind: ts_tka::KeyKind::Ed25519,
1333        votes: 1,
1334        public: nl_public,
1335        meta: Vec::new(),
1336    };
1337    let dvalue = ts_tka::disablement_value(&disablement_secret).to_vec();
1338    let mut genesis = ts_tka::Aum::new_genesis_checkpoint(vec![genesis_key], vec![dvalue])
1339        // A malformed genesis is a local construction bug, not a transient RPC failure — surface it as a
1340        // coarse internal error rather than NetworkError (which would invite a pointless retry).
1341        .map_err(|_| TkaSyncError::Internal(ts_control::TkaSyncInternalErrorKind::SerDe))?;
1342    genesis.sign(&keys.network_lock_keys.private.signing_key());
1343
1344    // Phase 1: submit the genesis. node_key + version are stamped by the RPC client from `keys`.
1345    let begin_req = ts_control::TkaInitBeginRequest {
1346        version: Default::default(),
1347        node_key: keys.node_keys.public,
1348        genesis_aum: genesis.serialize(),
1349    };
1350    let begin_resp = tka_init_begin(
1351        &config.server_url,
1352        keys,
1353        begin_req,
1354        config.allow_http_key_fetch,
1355    )
1356    .await?;
1357
1358    // Single-node case only: control must need no further node signatures. A non-empty
1359    // NeedSignatures means other nodes must be re-signed under the new lock — deferred.
1360    if !begin_resp.need_signatures.is_empty() {
1361        tracing::warn!(
1362            need = begin_resp.need_signatures.len(),
1363            "tka_init: control requires re-signing other nodes; the multi-node init is not yet \
1364             implemented (single-node lock-init only)"
1365        );
1366        return Err(TkaSyncError::Unsupported);
1367    }
1368
1369    // Phase 2: finish, carrying the raw disablement secret as SupportDisablement (Go sends the raw
1370    // secret here; only the genesis stores its Argon2i hash).
1371    let finish_req = ts_control::TkaInitFinishRequest {
1372        version: Default::default(),
1373        node_key: keys.node_keys.public,
1374        signatures: std::collections::BTreeMap::new(),
1375        support_disablement: disablement_secret,
1376    };
1377    tka_init_finish(
1378        &config.server_url,
1379        keys,
1380        finish_req,
1381        config.allow_http_key_fetch,
1382    )
1383    .await
1384    .map(|_response| ())
1385}
1386
1387/// Load or generate the ACME account key, then issue a cert for `name` via set-dns DNS-01,
1388/// returning just the ready-to-serve [`CertifiedKey`](ts_control::tls::CertifiedKey) (the
1389/// `get_certificate` / `ListenTLS` path).
1390///
1391/// Thin wrapper over [`issue_cert_pair`] that drops the PEMs — one issuance, this caller just
1392/// doesn't need the on-disk pair. See [`issue_cert_pair`] for the account-key handling.
1393#[cfg(feature = "acme")]
1394async fn issue_certificate(
1395    config: &ts_control::Config,
1396    keys: &ts_keys::NodeState,
1397    name: &str,
1398) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
1399    issue_cert_pair_inner(config, keys, name)
1400        .await
1401        .map(|issued| issued.certified)
1402}
1403
1404/// Load or generate the ACME account key, then issue a cert for `name` via set-dns DNS-01,
1405/// returning the **PEM pair** `(cert_chain_pem, key_pem)` for the daemon's on-disk `.crt`/`.key`
1406/// (`tnet cert`, Go `LocalClient.CertPair`).
1407///
1408/// Same single issuance as [`issue_certificate`]; only the result shape differs. The leaf
1409/// **private key** PEM is the second element and is NEVER logged here.
1410#[cfg(feature = "acme")]
1411async fn issue_cert_pair(
1412    config: &ts_control::Config,
1413    keys: &ts_keys::NodeState,
1414    name: &str,
1415) -> Result<(String, String), ts_control::CertError> {
1416    issue_cert_pair_inner(config, keys, name)
1417        .await
1418        .map(|issued| (issued.cert_chain_pem, issued.key_pem))
1419}
1420
1421/// Shared issuance core for [`issue_certificate`] and [`issue_cert_pair`]: load (or generate) the
1422/// ACME account key, target Let's Encrypt production, and run one DNS-01 issuance, returning the
1423/// full [`IssuedCert`](ts_control::acme::IssuedCert) so each caller projects out what it needs (one
1424/// ACME order, two consumers).
1425///
1426/// Reuses the persisted [`ts_keys::NodeState::acme_account_key`] (PKCS#8 DER) when present so the
1427/// same Let's Encrypt account survives renewals; otherwise generates an ephemeral per-call key
1428/// (logged at debug — a new ACME account each issuance, with no write-back). Always targets Let's
1429/// Encrypt production ([`ts_control::acme::LETS_ENCRYPT_PRODUCTION_DIRECTORY`]). Never logs the leaf
1430/// private key.
1431#[cfg(feature = "acme")]
1432async fn issue_cert_pair_inner(
1433    config: &ts_control::Config,
1434    keys: &ts_keys::NodeState,
1435    name: &str,
1436) -> Result<ts_control::acme::IssuedCert, ts_control::CertError> {
1437    let account_key = match keys.acme_account_key.as_deref() {
1438        Some(der) => ts_control::acme::AcmeAccountKey::from_pkcs8(der)?,
1439        None => {
1440            tracing::debug!(
1441                "no persisted ACME account key in key state; generating an ephemeral per-call key \
1442                 (a new ACME account this issuance — not persisted back)"
1443            );
1444            ts_control::acme::AcmeAccountKey::generate()?.0
1445        }
1446    };
1447    let directory = ts_control::acme::LETS_ENCRYPT_PRODUCTION_DIRECTORY
1448        .parse()
1449        .map_err(|e| {
1450            ts_control::CertError::Acme(format!("parsing Let's Encrypt directory URL: {e}"))
1451        })?;
1452    ts_control::issue_cert_pair_via_setdns(config, keys, name, &account_key, &directory).await
1453}
1454
1455impl Message<StreamMessage<Arc<StateUpdate>, (), ()>> for ControlRunner {
1456    type Reply = ();
1457
1458    async fn handle(
1459        &mut self,
1460        msg: StreamMessage<Arc<StateUpdate>, (), ()>,
1461        ctx: &mut Context<Self, Self::Reply>,
1462    ) {
1463        match msg {
1464            StreamMessage::Started(_) => {
1465                tracing::trace!("started listening to state updates");
1466            }
1467
1468            StreamMessage::Next(msg) => {
1469                if let Some(node) = msg.node.as_ref() {
1470                    // Reflect node-key expiry into the device state. Control delivering a self-node
1471                    // whose key is in the past means the node must re-authenticate; the arrival of a
1472                    // fresh (non-expired) self-node confirms we are Running (recovering the state if a
1473                    // prior update had flipped it to Expired/Reauthenticating). On expiry, decide
1474                    // between an automatic re-auth (Go `doLogin`: rotate key + re-register with the
1475                    // stored auth key) and the terminal Expired state via the pure `expiry_action`:
1476                    //   - auth key retained, reauth enabled, and TKA NOT enforcing → Reauthenticate.
1477                    //   - otherwise → Expired (no auth key / reauth disabled / TKA-locked).
1478                    // The TKA gate is a hard safety constraint: rotating on a locked tailnet would
1479                    // install an unsigned key and lock this node out of locked peers (the TKA re-sign
1480                    // is a separate follow-up). Recovery from Reauthenticating is automatic — the next
1481                    // good self-node flips back to Running at this same handler.
1482                    let now_unix = std::time::SystemTime::now()
1483                        .duration_since(std::time::UNIX_EPOCH)
1484                        .map(|d| d.as_secs() as i64)
1485                        .unwrap_or(0);
1486                    let action = expiry_action(
1487                        node.key_expired_at_unix(now_unix),
1488                        self.params.auth_key.is_some(),
1489                        self.params.config.reauth_on_expiry,
1490                        self.tka_authority.borrow().is_some(),
1491                    );
1492
1493                    // Bounded reauth sub-state-machine (circuit breaker), evaluated by the pure
1494                    // `reauth_circuit_step`. The `Reauthenticate` path must settle — a one-shot /
1495                    // already-consumed auth key cannot re-register, so an unbounded reauth would sit in
1496                    // `Reauthenticating` forever. The step takes the `expiry_action` verdict, whether we
1497                    // are ALREADY reauthenticating (i.e. the prior reauth has not recovered), and the
1498                    // current attempt counter, and returns the target state, the new counter, and
1499                    // whether to fire the one-shot reauth (fired ONLY on entry, so the node key rotates
1500                    // at most once per episode — a second rotation would lose the original `OldNodeKey`
1501                    // anchor). At `MAX_REAUTH_ATTEMPTS` it trips to terminal `Expired`.
1502                    //
1503                    // NOTE: we may act (count, and eventually flip to `Expired`) even when the published
1504                    // state does NOT change — a repeated `Reauthenticating` self-node is exactly the
1505                    // "prior reauth didn't recover" signal we must tally, so the counting reads the
1506                    // pre-step state directly here and `send_if_modified`'s `changed` only gates the
1507                    // log/firing below, never the counting.
1508                    let already_reauthing = matches!(
1509                        &*self.params.state_tx.borrow(),
1510                        crate::DeviceState::Reauthenticating
1511                    );
1512                    let step = reauth_circuit_step(action, already_reauthing, self.reauth_attempts);
1513                    self.reauth_attempts = step.attempts;
1514                    if step.next == ReauthState::Expired
1515                        && action == ExpiryAction::Reauthenticate
1516                        && already_reauthing
1517                    {
1518                        tracing::warn!(
1519                            attempts = step.attempts,
1520                            "automatic re-auth did not recover the node after {MAX_REAUTH_ATTEMPTS} \
1521                             attempts (auth key likely one-shot / consumed); falling back to terminal \
1522                             Expired"
1523                        );
1524                    }
1525                    let next = match step.next {
1526                        ReauthState::Running => crate::DeviceState::Running,
1527                        ReauthState::Reauthenticating => crate::DeviceState::Reauthenticating,
1528                        ReauthState::Expired => crate::DeviceState::Expired,
1529                    };
1530
1531                    // `send_if_modified` avoids waking watchers when the state is unchanged (a fresh
1532                    // self-node arrives on every netmap update). Returns whether the state changed.
1533                    let changed = self.params.state_tx.send_if_modified(|s| {
1534                        if *s != next {
1535                            *s = next.clone();
1536                            true
1537                        } else {
1538                            false
1539                        }
1540                    });
1541
1542                    if changed && step.fire_reauth {
1543                        tracing::info!(
1544                            "self node-key expired; starting automatic re-auth (rotate node key + \
1545                             re-register with stored auth key)"
1546                        );
1547                        self.client.reauth().await;
1548                    }
1549
1550                    self.self_node.send_replace(Some(node.clone()));
1551                }
1552
1553                if let Some(policy) = msg.ssh_policy.as_ref() {
1554                    self.ssh_policy.send_replace(Some(policy.clone()));
1555                }
1556
1557                if let Some(tka) = msg.tka.as_ref() {
1558                    self.tka.send_replace(Some(tka.clone()));
1559                    self.maybe_sync_tka(tka, ctx.actor_ref().clone());
1560                }
1561
1562                // Track the cert-domain list from the netmap DNS config (Go `nm.DNS.CertDomains`).
1563                // An update with no DNS config, or one carrying no cert domains, means "none" — Go
1564                // reads an empty slice off an absent config too, so mirror that as an empty `Vec`.
1565                let cert_domains = msg
1566                    .dns_config
1567                    .as_ref()
1568                    .map(|d| d.cert_domains.clone())
1569                    .unwrap_or_default();
1570                self.cert_domains.send_replace(cert_domains);
1571
1572                // Track the full DNS config for `Device::dns_config` (the daemon's `tnet dns status`).
1573                // `None` when control sent no DNS config on this update — distinct from a present but
1574                // empty config (Go `netmap.NetworkMap.DNS`).
1575                self.dns_config.send_replace(msg.dns_config.clone());
1576
1577                // Track the interactive-login URL for `Device::pop_browser_url` /
1578                // `Runtime::watch_ipn_bus`. See `sticky_update_pop_browser_url` for the Go-faithful
1579                // sticky semantics (update only on a new non-empty URL; never reset to `None`).
1580                sticky_update_pop_browser_url(&self.pop_browser_url, msg.pop_browser_url.as_ref());
1581
1582                if let Err(e) = self.params.env.publish(msg).await {
1583                    tracing::error!(error = %e, "publishing netmap update");
1584                }
1585            }
1586
1587            StreamMessage::Finished(_) => {
1588                tracing::error!("state update stream terminated")
1589            }
1590        }
1591    }
1592}
1593
1594/// The outcome of a spawned TKA bootstrap+sync task, delivered back to the actor thread so the
1595/// result can be applied to actor state (which a spawned task cannot touch directly). Sent by
1596/// [`ControlRunner::maybe_sync_tka`]; handled by applying via
1597/// [`ControlRunner::apply_tka_synced`](ControlRunner).
1598#[doc(hidden)]
1599pub struct TkaSynced {
1600    pub(crate) result:
1601        Result<Option<crate::tka_sync::SyncedTka>, crate::tka_sync::TkaSyncDriverError>,
1602    /// The [`ControlRunner::tka_generation`] captured when this sync was spawned; the handler
1603    /// discards the result if it no longer matches (the lock was disabled/re-synced mid-flight).
1604    pub(crate) generation: u64,
1605}
1606
1607impl Message<TkaSynced> for ControlRunner {
1608    type Reply = ();
1609
1610    async fn handle(&mut self, msg: TkaSynced, _ctx: &mut Context<Self, Self::Reply>) {
1611        self.apply_tka_synced(msg.result, msg.generation).await;
1612    }
1613}
1614
1615impl Message<DerpLatencyMeasurement> for ControlRunner {
1616    type Reply = ();
1617
1618    async fn handle(&mut self, msg: DerpLatencyMeasurement, _ctx: &mut Context<Self, Self::Reply>) {
1619        let measurements = msg.measurement.as_ref().clone();
1620
1621        // Publish the net-report snapshot for `Device::netcheck` (the daemon's `tnet netcheck`) from
1622        // the same measurements, before the home-region short-circuit below — an empty set still
1623        // yields a (default/empty) report rather than a stale one.
1624        self.netcheck
1625            .send_replace(crate::status::NetcheckReport::from_region_results(
1626                &measurements,
1627            ));
1628
1629        if measurements.is_empty() {
1630            tracing::debug!("derp latency measurements empty");
1631            return;
1632        };
1633
1634        // Record this cycle into the rolling history and evict reports older than the smoothing
1635        // window, then compute each region's `bestRecent` (5-min min). `Instant::now()` is the
1636        // arrival stamp; `best_recent` takes it as a param so the decision stays unit-testable.
1637        let now = Instant::now();
1638        self.derp_report_history
1639            .push((now, msg.measurement.clone()));
1640        self.derp_report_history
1641            .retain(|(stamp, _)| now.saturating_duration_since(*stamp) <= DERP_HISTORY_MAX_AGE);
1642        let best_recent = best_recent(&self.derp_report_history, now, DERP_HISTORY_MAX_AGE);
1643
1644        // Apply selection hysteresis (the pure decision lives in `select_home_region` for testability)
1645        // so jitter between near-equal regions does not flap the home relay. Go's asymmetric
1646        // smoothed-best vs raw-old comparison lives in `select_home_region`; here we just resolve the
1647        // chosen id back to its current-cycle latency for the home-region record + control update.
1648        let selected_id = select_home_region(
1649            self.home_region.map(|(id, _)| id),
1650            &measurements,
1651            &best_recent,
1652        )
1653        .expect("non-empty measurements always yield a selection");
1654        // `select_home_region` only ever returns an id drawn from `measurements`, so this lookup
1655        // always succeeds (same invariant the prior impl relied on when it returned the result by
1656        // reference). We record the current-cycle (raw) latency for the chosen region.
1657        let selected_latency = measurements
1658            .iter()
1659            .find(|m| m.id == selected_id)
1660            .expect("the selected region id is always one of the measurements")
1661            .latency;
1662
1663        let iter = measurements.iter().map(|result| {
1664            (
1665                result.latency_map_key.as_str(),
1666                result.latency.as_secs_f64(),
1667            )
1668        });
1669
1670        if self.home_region.map(|(id, _)| id) != Some(selected_id) {
1671            tracing::debug!(selected_region_id = ?selected_id, "updating home region");
1672        }
1673        self.home_region = Some((selected_id, selected_latency));
1674        // Advertise the smoothed home to control AND drive the local DERP relay to the same region
1675        // (Go `report.PreferredDERP` feeds both). `send_replace` wakes the watch on every send (it
1676        // does NOT coalesce same-value writes), so Multiderp's bridge sees a `SetHomeRegion` each
1677        // cycle; the de-dup is one layer down — `home_transition` returns `Unchanged` for a
1678        // re-selection of the current home, so the relay only churns on an actual home change.
1679        self.client.set_home_region(selected_id, iter).await;
1680        self.params.home_region.send_replace(Some(selected_id));
1681    }
1682}
1683
1684/// The window over which `best_recent` smooths per-region DERP latency (Go `netcheck` `maxAge`).
1685const DERP_HISTORY_MAX_AGE: Duration = Duration::from_secs(5 * 60);
1686
1687/// Compute each region's `bestRecent` — its **minimum** latency over the reports within
1688/// `max_age` of `now` (Go `addReportHistoryAndSetPreferredDERP`'s `bestRecent` map). Reports older
1689/// than the window are ignored. `now` and `max_age` are parameters (not clock-read) so this is
1690/// deterministically unit-testable. A region absent from every in-window report is absent from the
1691/// result.
1692fn best_recent(
1693    history: &[(Instant, Arc<Vec<ts_netcheck::RegionResult>>)],
1694    now: Instant,
1695    max_age: Duration,
1696) -> HashMap<ts_derp::RegionId, Duration> {
1697    let mut best: HashMap<ts_derp::RegionId, Duration> = HashMap::new();
1698    for (stamp, report) in history {
1699        // Skip reports outside the window. `saturating_duration_since` guards a `stamp` that is
1700        // somehow after `now` (clock skew): age 0, always in-window.
1701        if now.saturating_duration_since(*stamp) > max_age {
1702            continue;
1703        }
1704        for r in report.iter() {
1705            best.entry(r.id)
1706                .and_modify(|d| {
1707                    if r.latency < *d {
1708                        *d = r.latency;
1709                    }
1710                })
1711                .or_insert(r.latency);
1712        }
1713    }
1714    best
1715}
1716
1717/// Choose the DERP home region id, applying Go's selection hysteresis
1718/// (`netcheck.addReportHistoryAndSetPreferredDERP`). Pure so the decision is unit-testable.
1719///
1720/// `measurements` is the current cycle sorted by latency ascending (so `measurements[0]` is the
1721/// raw-current best). `best_recent` is each region's smoothed (5-min-min) latency. Matching Go's
1722/// **asymmetric** comparison exactly: the new best candidate is chosen by the *smoothed* `best_recent`
1723/// latency (`bestAny`), while the old/home region is compared using its *current-cycle* (raw)
1724/// latency (`oldRegionCurLatency`). Smoothing the best damps oscillation of the best region across
1725/// the switch boundary that the raw-vs-raw comparison (the prior impl) would still flap on.
1726///
1727/// Keeps the `current` home region unless the new best is *meaningfully* lower-latency — switching
1728/// only when BOTH the current region's raw latency exceeds the smoothed-best by at least
1729/// `PREFERRED_DERP_ABSOLUTE_DIFF` (10ms) AND the smoothed-best is at most two-thirds of the current
1730/// region's raw latency (a >~33% improvement). On the first selection (`current` is `None`), when the
1731/// smoothed-best already IS the current region, or when the current region dropped out of the
1732/// measurements, returns the best directly. `None` only if `measurements` is empty.
1733fn select_home_region(
1734    current: Option<ts_derp::RegionId>,
1735    measurements: &[ts_netcheck::RegionResult],
1736    best_recent: &HashMap<ts_derp::RegionId, Duration>,
1737) -> Option<ts_derp::RegionId> {
1738    /// Go `netcheck.preferredDERPAbsoluteDiff`.
1739    const PREFERRED_DERP_ABSOLUTE_DIFF: Duration = Duration::from_millis(10);
1740
1741    // The smoothed latency for a region: its `best_recent` if present, else its current sample (a
1742    // region seen only this cycle has a 1-sample history, so its min == its current latency anyway).
1743    let smoothed = |m: &ts_netcheck::RegionResult| -> Duration {
1744        best_recent.get(&m.id).copied().unwrap_or(m.latency)
1745    };
1746
1747    // Pick the best candidate by SMOOTHED latency (Go `bestAny = min over regions of bestRecent`).
1748    // `measurements` is sorted by raw latency, but smoothing can reorder, so scan for the smoothed
1749    // minimum explicitly rather than trusting `measurements[0]`.
1750    let best = measurements.iter().min_by_key(|m| smoothed(m))?;
1751    let best_any = smoothed(best);
1752
1753    let Some(old_id) = current.filter(|id| *id != best.id) else {
1754        // First selection, or the smoothed-best already is the current home region.
1755        return Some(best.id);
1756    };
1757
1758    // Compare against the old region's CURRENT (raw) latency this cycle, if it is still present —
1759    // Go's `oldRegionCurLatency`, deliberately unsmoothed (the asymmetry).
1760    match measurements.iter().find(|m| m.id == old_id) {
1761        Some(old) => {
1762            // Byte-faithful to Go: `oldRegionCurLatency - bestAny < 10ms || bestAny >
1763            // oldRegionCurLatency/3*2`. `saturating_sub` matches Go's signed subtraction for the
1764            // `< 10ms` test (when `old < best_any` Go is negative → `< 10ms` true; saturating_sub
1765            // floors to 0 → also true). The two-thirds rule uses INTEGER `Duration` division
1766            // `(old/3)*2` — NOT float `* 2.0/3.0`: Go computes the threshold in integer nanoseconds
1767            // (`oldNs/3` truncates), and float arithmetic diverges from it at the exact 2/3 boundary
1768            // with whole-millisecond inputs (e.g. old=36ms, best=24ms: Go's `24ms > 24ms` is false →
1769            // switch, but float `0.024 > 0.0239999997` is true → keep). `Duration / u32` truncates
1770            // nanos exactly like Go and `* u32` is exact, reproducing `oldRegionCurLatency/3*2`.
1771            let keep_old = old.latency.saturating_sub(best_any) < PREFERRED_DERP_ABSOLUTE_DIFF
1772                || best_any > (old.latency / 3) * 2;
1773            Some(if keep_old { old.id } else { best.id })
1774        }
1775        // The current region is no longer reachable this cycle: take the new best.
1776        None => Some(best.id),
1777    }
1778}
1779
1780impl Message<EndpointAdvertisement> for ControlRunner {
1781    type Reply = ();
1782
1783    async fn handle(&mut self, msg: EndpointAdvertisement, _ctx: &mut Context<Self, Self::Reply>) {
1784        let endpoints: Vec<Endpoint> = msg
1785            .endpoints
1786            .iter()
1787            .map(|ep| Endpoint {
1788                endpoint: ep.addr,
1789                ty: match ep.ty {
1790                    SelfEndpointType::Local => EndpointType::Local,
1791                    SelfEndpointType::Stun => EndpointType::Stun,
1792                    SelfEndpointType::Stun4LocalPort => EndpointType::Stun4LocalPort,
1793                },
1794            })
1795            .collect();
1796
1797        tracing::debug!(
1798            n_endpoints = endpoints.len(),
1799            "advertising endpoints to control"
1800        );
1801
1802        self.client.set_endpoints(endpoints).await;
1803    }
1804}
1805
1806/// Re-advertise this node's routable IP prefixes (`Hostinfo.RoutableIPs`) to control — the wire
1807/// half of a runtime [`Runtime::set_advertise_routes`](crate::Runtime::set_advertise_routes). Sent
1808/// as a direct `ask` from the runtime (not over the bus), so the route change reaches the live
1809/// map-poll client. `routes` is the final advertised set the caller wants control to grant.
1810#[derive(Debug)]
1811pub struct SetAdvertiseRoutes {
1812    /// The prefixes to advertise to control (already filtered to the final set).
1813    pub routes: Vec<ipnet::IpNet>,
1814}
1815
1816impl Message<SetAdvertiseRoutes> for ControlRunner {
1817    type Reply = ();
1818
1819    async fn handle(&mut self, msg: SetAdvertiseRoutes, _ctx: &mut Context<Self, Self::Reply>) {
1820        tracing::debug!(n_routes = msg.routes.len(), "advertising routes to control");
1821        self.client.set_routable_ips(msg.routes).await;
1822    }
1823}
1824
1825/// Update this node's `Hostinfo.Hostname` at control — the wire half of a runtime
1826/// [`Runtime::set_hostname`](crate::Runtime::set_hostname). A direct `ask` from the runtime, so the
1827/// change reaches the live map-poll client.
1828#[derive(Debug)]
1829pub struct SetHostname {
1830    /// The new hostname to report to control.
1831    pub hostname: String,
1832}
1833
1834impl Message<SetHostname> for ControlRunner {
1835    type Reply = ();
1836
1837    async fn handle(&mut self, msg: SetHostname, _ctx: &mut Context<Self, Self::Reply>) {
1838        tracing::debug!("updating hostname at control");
1839        self.client.set_hostname(msg.hostname).await;
1840    }
1841}
1842
1843#[cfg(test)]
1844mod reauth_bridge_tests {
1845    use tokio::sync::watch;
1846
1847    use super::bridge_reauth_url_to_state;
1848    use crate::DeviceState;
1849
1850    fn url(s: &str) -> url::Url {
1851        s.parse().unwrap()
1852    }
1853
1854    /// The bridge maps a surfaced re-auth URL onto `DeviceState::NeedsLogin(url)` — the fix's core:
1855    /// a mid-session `MachineNotAuthorized` (forwarded by the control client as `Some(url)`) becomes
1856    /// the "needs login" state the IPN bus turns into `browse_to_url`.
1857    #[test]
1858    fn bridge_maps_auth_url_to_needs_login() {
1859        let u = url("https://login.example/auth");
1860        let (tx, rx) = watch::channel(DeviceState::Running);
1861
1862        bridge_reauth_url_to_state(&tx, Some(&u));
1863
1864        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u));
1865    }
1866
1867    /// `None` never drives a transition — the recovery to `Running` is the netmap self-node
1868    /// handler's job, so the bridge ignores a `None` and leaves the state untouched.
1869    #[test]
1870    fn bridge_none_leaves_state_unchanged() {
1871        let (tx, rx) = watch::channel(DeviceState::Running);
1872
1873        bridge_reauth_url_to_state(&tx, None);
1874
1875        assert_eq!(*rx.borrow(), DeviceState::Running);
1876    }
1877
1878    /// Re-surfacing the same URL across retries does not re-fire the watch (`send_if_modified`
1879    /// dedupe against the cell's current value), so a stuck re-auth does not thrash subscribers.
1880    #[test]
1881    fn bridge_same_url_does_not_refire() {
1882        let u = url("https://login.example/auth");
1883        let (tx, mut rx) = watch::channel(DeviceState::Running);
1884
1885        bridge_reauth_url_to_state(&tx, Some(&u)); // first: fires
1886        assert!(rx.has_changed().unwrap(), "first NeedsLogin fires");
1887        rx.mark_unchanged();
1888        bridge_reauth_url_to_state(&tx, Some(&u)); // same URL: deduped
1889        assert!(
1890            !rx.has_changed().unwrap(),
1891            "the same re-auth URL must not re-fire the state watch"
1892        );
1893    }
1894
1895    /// A genuinely different re-auth URL after a prior one fires again (the dedupe tracks changes,
1896    /// it does not pin the first URL forever).
1897    #[test]
1898    fn bridge_new_url_after_prior_fires() {
1899        let a = url("https://login.example/a");
1900        let b = url("https://login.example/b");
1901        let (tx, rx) = watch::channel(DeviceState::Running);
1902
1903        bridge_reauth_url_to_state(&tx, Some(&a));
1904        bridge_reauth_url_to_state(&tx, Some(&b));
1905
1906        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(b));
1907    }
1908
1909    /// End-to-end of the *clear* contract: after the bridge sets `NeedsLogin`, the netmap self-node
1910    /// path (modeled here as a direct `send_replace(Running)`, the exact transition the
1911    /// `StreamMessage::Next` handler performs on the next good self-node) flips back to `Running`.
1912    /// This pins that the bridge does NOT need a `None`-clear arm — recovery is owned elsewhere.
1913    #[test]
1914    fn running_netmap_clears_needs_login() {
1915        let u = url("https://login.example/auth");
1916        let (tx, rx) = watch::channel(DeviceState::Running);
1917
1918        bridge_reauth_url_to_state(&tx, Some(&u));
1919        assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u));
1920
1921        // The self-node handler's recovery transition (next good netmap self-node → Running).
1922        tx.send_replace(DeviceState::Running);
1923        assert_eq!(*rx.borrow(), DeviceState::Running);
1924    }
1925
1926    /// Fix 2 — the bridge must NOT clobber an in-flight automatic re-auth. While the cell holds
1927    /// `Reauthenticating`, an auth URL surfaced by the rotated re-register (over the same
1928    /// `auth_url_tx` cell) must leave the state UNTOUCHED: flipping to `NeedsLogin` would surface a
1929    /// misleading `browse_to_url` on a headless node and, by moving the cell off `Reauthenticating`,
1930    /// re-arm a second node-key rotation that loses the original `OldNodeKey` anchor. The auto-reauth
1931    /// path owns the cell until it recovers to `Running` or trips to `Expired`.
1932    #[test]
1933    fn bridge_does_not_clobber_reauthenticating() {
1934        let u = url("https://login.example/auth");
1935        let (tx, rx) = watch::channel(DeviceState::Reauthenticating);
1936
1937        bridge_reauth_url_to_state(&tx, Some(&u));
1938
1939        assert_eq!(
1940            *rx.borrow(),
1941            DeviceState::Reauthenticating,
1942            "a surfaced auth URL must not downgrade an in-flight auto-reauth to NeedsLogin"
1943        );
1944    }
1945
1946    /// The no-clobber guard is scoped to `Reauthenticating` only — it does not change the bridge's
1947    /// behavior in any other state. From `Running` (and likewise `Connecting`/`NeedsLogin`) a
1948    /// surfaced URL still drives `NeedsLogin` as before, so an ordinary interactive re-auth is
1949    /// unaffected.
1950    #[test]
1951    fn bridge_still_sets_needs_login_from_non_reauthenticating() {
1952        let u = url("https://login.example/auth");
1953        for start in [
1954            DeviceState::Running,
1955            DeviceState::Connecting,
1956            DeviceState::Expired,
1957        ] {
1958            let (tx, rx) = watch::channel(start);
1959            bridge_reauth_url_to_state(&tx, Some(&u));
1960            assert_eq!(*rx.borrow(), DeviceState::NeedsLogin(u.clone()));
1961        }
1962    }
1963}
1964
1965#[cfg(test)]
1966mod sticky_pop_browser_url_tests {
1967    use tokio::sync::watch;
1968
1969    use super::sticky_update_pop_browser_url;
1970
1971    fn url(s: &str) -> url::Url {
1972        s.parse().unwrap()
1973    }
1974
1975    /// A non-empty URL publishes to the cell.
1976    #[test]
1977    fn non_empty_url_publishes() {
1978        let (tx, rx) = watch::channel(None);
1979        let u = url("https://login.example/consent");
1980        sticky_update_pop_browser_url(&tx, Some(&u));
1981        assert_eq!(*rx.borrow(), Some(u));
1982    }
1983
1984    /// An absent (`None`) update — the common netmap tick — must NOT reset the cell. This is the
1985    /// regression guard for the thrash bug (a reset-every-tick would coalesce the URL away on the bus).
1986    #[test]
1987    fn absent_update_does_not_reset() {
1988        let u = url("https://login.example/consent");
1989        let (tx, rx) = watch::channel(Some(u.clone()));
1990        // Simulate many empty netmap updates.
1991        for _ in 0..5 {
1992            sticky_update_pop_browser_url(&tx, None);
1993        }
1994        assert_eq!(
1995            *rx.borrow(),
1996            Some(u),
1997            "empty updates must not clear the URL"
1998        );
1999    }
2000
2001    /// The same URL repeated does not re-fire the watch (in-place dedupe via `send_if_modified`), so
2002    /// a subscriber isn't woken spuriously. Proven by the borrow not having been marked changed.
2003    #[test]
2004    fn repeated_same_url_does_not_refire() {
2005        let u = url("https://login.example/consent");
2006        let (tx, mut rx) = watch::channel(None);
2007        sticky_update_pop_browser_url(&tx, Some(&u)); // first: fires
2008        assert!(rx.has_changed().unwrap(), "first non-empty URL fires");
2009        rx.mark_unchanged();
2010        sticky_update_pop_browser_url(&tx, Some(&u)); // same: deduped
2011        assert!(
2012            !rx.has_changed().unwrap(),
2013            "repeating the same URL must not re-fire the watch"
2014        );
2015    }
2016
2017    /// A genuinely new URL after a prior one fires again (sticky but tracks changes).
2018    #[test]
2019    fn new_url_after_prior_fires() {
2020        let a = url("https://login.example/a");
2021        let b = url("https://login.example/b");
2022        let (tx, rx) = watch::channel(None);
2023        sticky_update_pop_browser_url(&tx, Some(&a));
2024        sticky_update_pop_browser_url(&tx, Some(&b));
2025        assert_eq!(*rx.borrow(), Some(b));
2026    }
2027
2028    /// The realistic session sequence: a URL stays sticky through a run of `None` ticks, and a
2029    /// *different* URL after that gap still fires. Chains the legs the other tests cover in isolation
2030    /// (the actual control cadence is "URL, then many empty updates, then maybe a new URL").
2031    #[test]
2032    fn sticky_through_none_gap_then_new_url_fires() {
2033        let a = url("https://login.example/a");
2034        let b = url("https://login.example/b");
2035        let (tx, rx) = watch::channel(None);
2036        sticky_update_pop_browser_url(&tx, Some(&a));
2037        for _ in 0..3 {
2038            sticky_update_pop_browser_url(&tx, None);
2039        }
2040        assert_eq!(*rx.borrow(), Some(a), "stayed sticky through the None gap");
2041        sticky_update_pop_browser_url(&tx, Some(&b));
2042        assert_eq!(
2043            *rx.borrow(),
2044            Some(b),
2045            "a new URL after a None gap still fires"
2046        );
2047    }
2048
2049    /// Returning to a previously-seen URL (A → B → A) re-fires: the dedupe is against the cell's
2050    /// *current* value, not a full history, so A after B is a genuine change.
2051    #[test]
2052    fn returning_to_prior_url_refires() {
2053        let a = url("https://login.example/a");
2054        let b = url("https://login.example/b");
2055        let (tx, mut rx) = watch::channel(None);
2056        sticky_update_pop_browser_url(&tx, Some(&a));
2057        sticky_update_pop_browser_url(&tx, Some(&b));
2058        rx.mark_unchanged();
2059        sticky_update_pop_browser_url(&tx, Some(&a)); // back to A: differs from current (B) → fires
2060        assert!(
2061            rx.has_changed().unwrap(),
2062            "returning to a prior URL re-fires"
2063        );
2064        assert_eq!(*rx.borrow(), Some(a));
2065    }
2066
2067    /// End-to-end de-thrash: feed a realistic netmap cadence (empty, empty, URL, empty, empty)
2068    /// through the producer into a cell, and count the changes a `run_bus`-style subscriber would
2069    /// observe via `changed()`. The whole point of the fix is that exactly ONE change survives the
2070    /// surrounding `None` thrash — the pre-fix code (`send_replace` every tick) would have woken the
2071    /// subscriber on every empty tick and coalesced the URL away. This exercises the producer + the
2072    /// watch-subscribe path together (the two halves the unit tests cover in isolation).
2073    #[tokio::test]
2074    async fn end_to_end_one_change_survives_none_thrash() {
2075        let u = url("https://login.example/consent");
2076        let (tx, mut rx) = watch::channel(None);
2077        // The cadence control actually sends: mostly-empty MapResponses with one carrying the URL.
2078        let cadence = [None, None, Some(&u), None, None];
2079        for incoming in cadence {
2080            sticky_update_pop_browser_url(&tx, incoming);
2081        }
2082        // A subscriber sees exactly one change, and it carries the URL (not a coalesced `None`).
2083        let mut changes = 0;
2084        while rx.has_changed().unwrap() {
2085            let v = rx.borrow_and_update().clone();
2086            changes += 1;
2087            assert_eq!(v, Some(u.clone()), "the surviving change carries the URL");
2088        }
2089        assert_eq!(changes, 1, "exactly one change survives the None thrash");
2090    }
2091}
2092
2093#[cfg(test)]
2094mod home_region_hysteresis_tests {
2095    use core::time::Duration;
2096    use std::{collections::HashMap, sync::Arc, time::Instant};
2097
2098    use ts_derp::RegionId;
2099    use ts_netcheck::RegionResult;
2100
2101    use super::{DERP_HISTORY_MAX_AGE, best_recent, select_home_region};
2102
2103    fn region(id: u32, latency_ms: u64) -> RegionResult {
2104        RegionResult {
2105            latency: Duration::from_millis(latency_ms),
2106            id: RegionId(core::num::NonZeroU32::new(id).unwrap()),
2107            latency_map_key: format!("region-{id}"),
2108            connected_remote: "127.0.0.1:0".parse().unwrap(),
2109        }
2110    }
2111
2112    fn rid(id: u32) -> RegionId {
2113        RegionId(core::num::NonZeroU32::new(id).unwrap())
2114    }
2115
2116    /// Call `select_home_region` with NO smoothing history — `best_recent` empty, so each region's
2117    /// smoothed latency falls back to its current sample, reproducing the original raw-vs-raw
2118    /// hysteresis these tests pin. (The smoothing-specific tests below pass a populated map.)
2119    fn sel(current: Option<RegionId>, m: &[RegionResult]) -> Option<RegionId> {
2120        select_home_region(current, m, &HashMap::new())
2121    }
2122
2123    /// Empty measurements yield no selection.
2124    #[test]
2125    fn empty_measurements_select_none() {
2126        assert!(sel(Some(rid(1)), &[]).is_none());
2127        assert!(sel(None, &[]).is_none());
2128    }
2129
2130    /// First selection (no current home region) takes the best (lowest-latency) region directly.
2131    #[test]
2132    fn first_selection_takes_best() {
2133        let m = [region(1, 20), region(2, 50)];
2134        assert_eq!(sel(None, &m).unwrap(), rid(1));
2135    }
2136
2137    /// Jitter within the 10ms absolute-diff band keeps the current region (no flap). Current=region 2
2138    /// at 25ms; new best=region 1 at 20ms (only 5ms better) -> keep region 2.
2139    #[test]
2140    fn keeps_current_when_within_absolute_diff() {
2141        let m = [region(1, 20), region(2, 25)];
2142        assert_eq!(
2143            sel(Some(rid(2)), &m).unwrap(),
2144            rid(2),
2145            "a 5ms improvement (< 10ms) must not flap the home region"
2146        );
2147    }
2148
2149    /// A meaningful improvement (>10ms AND best <= 2/3 of current) switches. Current=region 2 at
2150    /// 100ms; new best=region 1 at 20ms -> switch to region 1.
2151    #[test]
2152    fn switches_on_meaningful_improvement() {
2153        let m = [region(1, 20), region(2, 100)];
2154        assert_eq!(
2155            sel(Some(rid(2)), &m).unwrap(),
2156            rid(1),
2157            "a large improvement must switch the home region"
2158        );
2159    }
2160
2161    /// The two-thirds rule: even past the 10ms absolute diff, an improvement that does not beat 2/3
2162    /// of the current latency keeps the current region. current=60ms, best=45ms: diff=15ms (>10ms,
2163    /// so the absolute test alone would switch), but 45 > 60*2/3=40, so keep.
2164    #[test]
2165    fn keeps_current_when_two_thirds_rule_not_met() {
2166        let m = [region(1, 45), region(2, 60)];
2167        assert_eq!(
2168            sel(Some(rid(2)), &m).unwrap(),
2169            rid(2),
2170            "best (45ms) is not <= 2/3 of current (40ms), so keep current despite >10ms diff"
2171        );
2172    }
2173
2174    /// When the current home region is no longer present in the measurements, take the new best.
2175    #[test]
2176    fn switches_when_current_region_absent() {
2177        let m = [region(1, 20), region(3, 25)];
2178        assert_eq!(
2179            sel(Some(rid(2)), &m).unwrap(),
2180            rid(1),
2181            "a current region absent from the measurements falls through to the best"
2182        );
2183    }
2184
2185    /// When the best already IS the current home region, it is kept (no spurious change).
2186    #[test]
2187    fn keeps_current_when_it_is_already_best() {
2188        let m = [region(2, 20), region(1, 50)];
2189        assert_eq!(sel(Some(rid(2)), &m).unwrap(), rid(2));
2190    }
2191
2192    /// `best_recent` is each region's MINIMUM latency over the in-window reports; a report older than
2193    /// `max_age` is excluded.
2194    #[test]
2195    fn best_recent_is_min_over_window_and_evicts_aged() {
2196        let now = Instant::now();
2197        // Two in-window reports for region 1 (50ms then 20ms) → min 20ms; region 2 once at 30ms.
2198        // One aged report (region 1 at 5ms) outside the window must be ignored.
2199        let history = vec![
2200            (
2201                now - Duration::from_secs(10 * 60), // aged out (> 5min)
2202                Arc::new(vec![region(1, 5)]),
2203            ),
2204            (
2205                now - Duration::from_secs(60),
2206                Arc::new(vec![region(1, 50), region(2, 30)]),
2207            ),
2208            (now, Arc::new(vec![region(1, 20)])),
2209        ];
2210        let br = best_recent(&history, now, DERP_HISTORY_MAX_AGE);
2211        assert_eq!(
2212            br.get(&rid(1)).copied(),
2213            Some(Duration::from_millis(20)),
2214            "region 1 min over the window is 20ms (the aged 5ms is excluded)"
2215        );
2216        assert_eq!(br.get(&rid(2)).copied(), Some(Duration::from_millis(30)));
2217    }
2218
2219    /// The asymmetric comparison: the new best is chosen by its SMOOTHED (best_recent) latency while
2220    /// the old region is compared on its RAW current latency. A best region whose CURRENT sample
2221    /// looks much better but whose 5-min MIN is only marginally better must NOT flap the home region
2222    /// — exactly the oscillation the raw-vs-raw comparison would have switched on.
2223    #[test]
2224    fn smoothed_best_damps_oscillation_across_boundary() {
2225        // Current home = region 2, raw 60ms this cycle. Region 1's CURRENT sample is 20ms (a >2/3,
2226        // >10ms improvement → raw-vs-raw would SWITCH), but its 5-min MIN (best_recent) is 50ms
2227        // (it oscillates). Smoothed-best 50ms vs raw-old 60ms: diff 10ms is NOT < 10ms, but
2228        // 50 > 60*2/3=40 → keepOld. So we KEEP region 2, where the raw comparison would have flapped.
2229        let m = [region(1, 20), region(2, 60)];
2230        let mut br = HashMap::new();
2231        br.insert(rid(1), Duration::from_millis(50)); // smoothed best is worse than its raw sample
2232        br.insert(rid(2), Duration::from_millis(60));
2233        assert_eq!(
2234            select_home_region(Some(rid(2)), &m, &br).unwrap(),
2235            rid(2),
2236            "a best region whose 5-min min is only marginally better must not flap the home region"
2237        );
2238
2239        // Sanity: with NO smoothing (raw 20ms best), the same inputs WOULD switch — proving the
2240        // smoothing is what holds it.
2241        assert_eq!(
2242            select_home_region(Some(rid(2)), &m, &HashMap::new()).unwrap(),
2243            rid(1),
2244            "raw-vs-raw (no smoothing) switches on the 20ms-vs-60ms current samples"
2245        );
2246    }
2247
2248    /// Smoothing can reorder which region is "best": `measurements` is sorted by raw latency, but the
2249    /// smoothed minimum may favor a different region. `select_home_region` must pick by smoothed
2250    /// latency, not blindly trust `measurements[0]`.
2251    #[test]
2252    fn smoothed_best_may_differ_from_raw_first() {
2253        // Raw order: region 1 (10ms) is first. But region 2's 5-min min is 5ms while region 1's is
2254        // 40ms (region 1's 10ms was a lucky low sample). Smoothed-best is region 2. First selection.
2255        let m = [region(1, 10), region(2, 12)];
2256        let mut br = HashMap::new();
2257        br.insert(rid(1), Duration::from_millis(40));
2258        br.insert(rid(2), Duration::from_millis(5));
2259        assert_eq!(
2260            select_home_region(None, &m, &br).unwrap(),
2261            rid(2),
2262            "the smoothed-best region wins even when it is not the raw-latency first"
2263        );
2264    }
2265
2266    /// Byte-faithful integer two-thirds boundary (the float-vs-integer divergence): at exactly
2267    /// `best == old * 2/3` (old=36ms, best=24ms), Go's integer `bestAny > old/3*2` = `24ms > 24ms`
2268    /// is FALSE, so it does NOT keep on the 2/3 arm; and `cond_a` `36-24=12ms < 10ms` is also false,
2269    /// so Go SWITCHES. A float `0.024 > 0.036*2.0/3.0 = 0.0239999997` would wrongly KEEP. This test
2270    /// pins the integer math: it must switch to the best.
2271    #[test]
2272    fn two_thirds_boundary_is_integer_not_float() {
2273        let m = [region(1, 24), region(2, 36)];
2274        // No smoothing (raw == smoothed): isolates the 2/3 arithmetic at the exact boundary.
2275        assert_eq!(
2276            sel(Some(rid(2)), &m).unwrap(),
2277            rid(1),
2278            "at best == old*2/3 the integer rule does NOT keep (Go switches); a float rule would keep"
2279        );
2280    }
2281
2282    /// The `cond_a` (absolute-diff) arm via `saturating_sub`: when the old region's RAW current
2283    /// latency is FASTER than the smoothed-best (old=20ms raw, smoothed-best=50ms), `old - best_any`
2284    /// underflows. Go's signed subtraction is negative (`< 10ms` → keepOld); `saturating_sub` floors
2285    /// to 0 (`< 10ms` → keepOld) — same outcome. The old region is kept.
2286    #[test]
2287    fn old_faster_than_smoothed_best_keeps_via_absolute_diff() {
2288        // Current home = region 2, raw 20ms. Region 1 is the raw-best at 15ms but its smoothed min is
2289        // 50ms (it oscillates badly). smoothed-best candidate by min = region 2 (raw 20 == smoothed
2290        // 20, since br[2]=20) vs region 1 smoothed 50 → best is region 2 itself → already-best path.
2291        // To exercise the old<best_any underflow we need best != old: make region 1 the smoothed best
2292        // at 18ms but the OLD region's raw 20ms... use: old=region2 raw 20, best=region1 smoothed 18.
2293        let m = [region(1, 15), region(2, 20)];
2294        let mut br = HashMap::new();
2295        br.insert(rid(1), Duration::from_millis(18)); // smoothed-best = region 1 at 18ms
2296        br.insert(rid(2), Duration::from_millis(25)); // region 2 smoothed worse than its raw 20ms
2297        // best_any = 18ms (region 1). old (region 2) RAW = 20ms. 20 - 18 = 2ms < 10ms → keepOld.
2298        assert_eq!(
2299            select_home_region(Some(rid(2)), &m, &br).unwrap(),
2300            rid(2),
2301            "old raw (20ms) within 10ms of smoothed-best (18ms) keeps via the absolute-diff arm"
2302        );
2303    }
2304}
2305
2306#[cfg(test)]
2307mod expiry_action_tests {
2308    use super::{ExpiryAction, expiry_action};
2309
2310    /// Not expired → `Running`, regardless of the other inputs (the gate fields are only consulted
2311    /// once the key is expired).
2312    #[test]
2313    fn not_expired_is_always_running() {
2314        for has_auth_key in [false, true] {
2315            for reauth_enabled in [false, true] {
2316                for tka_active in [false, true] {
2317                    assert_eq!(
2318                        expiry_action(false, has_auth_key, reauth_enabled, tka_active),
2319                        ExpiryAction::Running,
2320                        "a non-expired key is Running for any gate combination"
2321                    );
2322                }
2323            }
2324        }
2325    }
2326
2327    /// The ONLY input combination that auto-reauths: expired AND auth key retained AND reauth enabled
2328    /// AND TKA not enforcing.
2329    #[test]
2330    fn expired_with_authkey_reauth_enabled_and_no_tka_reauthenticates() {
2331        assert_eq!(
2332            expiry_action(true, true, true, false),
2333            ExpiryAction::Reauthenticate
2334        );
2335    }
2336
2337    /// Every other expired combination falls back to the terminal `Expired` (today's behavior, no
2338    /// regression): no auth key, reauth disabled, or TKA enforcing each independently forces Expired.
2339    #[test]
2340    fn expired_falls_back_to_expired_for_every_other_combination() {
2341        // The full expired-input matrix minus the single Reauthenticate cell above.
2342        for has_auth_key in [false, true] {
2343            for reauth_enabled in [false, true] {
2344                for tka_active in [false, true] {
2345                    let action = expiry_action(true, has_auth_key, reauth_enabled, tka_active);
2346                    if has_auth_key && reauth_enabled && !tka_active {
2347                        // The one Reauthenticate cell, asserted above.
2348                        assert_eq!(action, ExpiryAction::Reauthenticate);
2349                    } else {
2350                        assert_eq!(
2351                            action,
2352                            ExpiryAction::Expired,
2353                            "expired with has_auth_key={has_auth_key}, \
2354                             reauth_enabled={reauth_enabled}, tka_active={tka_active} must be Expired"
2355                        );
2356                    }
2357                }
2358            }
2359        }
2360    }
2361
2362    /// The TKA safety gate in isolation: even with an auth key and reauth enabled, an ACTIVE lock
2363    /// forces `Expired` (never rotate an unsigned key on a locked tailnet). This is the hard
2364    /// constraint from the design — pinned as its own test so a regression that drops the `!tka_active`
2365    /// term is caught explicitly.
2366    #[test]
2367    fn tka_active_forces_expired_even_when_reauth_would_otherwise_fire() {
2368        assert_eq!(
2369            expiry_action(true, true, true, true),
2370            ExpiryAction::Expired,
2371            "an enforcing Tailnet Lock must veto auto-reauth (unsigned-key lockout safety gate)"
2372        );
2373    }
2374
2375    /// No auth key forces `Expired`: there is nothing to non-interactively re-register with, so even
2376    /// with reauth enabled and no lock the node goes terminal (unchanged from today).
2377    #[test]
2378    fn no_auth_key_forces_expired() {
2379        assert_eq!(
2380            expiry_action(true, false, true, false),
2381            ExpiryAction::Expired
2382        );
2383    }
2384
2385    /// The config opt-out: `reauth_on_expiry=false` forces `Expired` even with an auth key and no
2386    /// lock (the conservative posture / historical behavior).
2387    #[test]
2388    fn reauth_disabled_forces_expired() {
2389        assert_eq!(
2390            expiry_action(true, true, false, false),
2391            ExpiryAction::Expired
2392        );
2393    }
2394}
2395
2396#[cfg(test)]
2397mod reauth_circuit_tests {
2398    use super::{ExpiryAction, MAX_REAUTH_ATTEMPTS, ReauthState, reauth_circuit_step};
2399
2400    /// Entering reauth (a `Reauthenticate` verdict while NOT already reauthenticating) fires the
2401    /// one-shot reauth and starts the counter at 1.
2402    #[test]
2403    fn enter_reauth_fires_once_and_starts_counter() {
2404        let step = reauth_circuit_step(ExpiryAction::Reauthenticate, false, 0);
2405        assert_eq!(step.next, ReauthState::Reauthenticating);
2406        assert_eq!(
2407            step.attempts, 1,
2408            "the entering attempt starts the counter at 1"
2409        );
2410        assert!(step.fire_reauth, "entry fires the one-shot Command::Reauth");
2411    }
2412
2413    /// A subsequent expired self-node while ALREADY reauthenticating (prior reauth not recovered)
2414    /// counts up but does NOT re-fire — re-firing would rotate the node key a second time and lose the
2415    /// original `OldNodeKey` anchor.
2416    #[test]
2417    fn still_reauthing_counts_but_does_not_refire() {
2418        let step = reauth_circuit_step(ExpiryAction::Reauthenticate, true, 1);
2419        assert_eq!(step.next, ReauthState::Reauthenticating);
2420        assert_eq!(
2421            step.attempts, 2,
2422            "a non-recovering reauth increments the counter"
2423        );
2424        assert!(
2425            !step.fire_reauth,
2426            "must NOT re-fire reauth while already reauthenticating (no second rotation)"
2427        );
2428    }
2429
2430    /// At `MAX_REAUTH_ATTEMPTS` consecutive non-recovering reauths, the breaker trips to the terminal
2431    /// `Expired` and stops re-arming reauth (the one-shot auth-key case settles instead of looping).
2432    #[test]
2433    fn trips_to_expired_at_cap() {
2434        // One step below the cap still stays reauthenticating.
2435        let below =
2436            reauth_circuit_step(ExpiryAction::Reauthenticate, true, MAX_REAUTH_ATTEMPTS - 2);
2437        assert_eq!(below.next, ReauthState::Reauthenticating);
2438        assert!(!below.fire_reauth);
2439
2440        // The step that reaches the cap flips to terminal Expired and does not fire.
2441        let at_cap =
2442            reauth_circuit_step(ExpiryAction::Reauthenticate, true, MAX_REAUTH_ATTEMPTS - 1);
2443        assert_eq!(at_cap.attempts, MAX_REAUTH_ATTEMPTS);
2444        assert_eq!(
2445            at_cap.next,
2446            ReauthState::Expired,
2447            "at the cap the circuit breaker trips to terminal Expired"
2448        );
2449        assert!(
2450            !at_cap.fire_reauth,
2451            "a tripped breaker never fires another reauth"
2452        );
2453    }
2454
2455    /// A good (non-expired) self-node resets the counter to 0 (the node recovered) — so a later,
2456    /// genuine expiry cycle gets a fresh full budget of attempts, never a stale leftover count.
2457    #[test]
2458    fn running_resets_counter() {
2459        let step = reauth_circuit_step(ExpiryAction::Running, true, MAX_REAUTH_ATTEMPTS);
2460        assert_eq!(step.next, ReauthState::Running);
2461        assert_eq!(
2462            step.attempts, 0,
2463            "recovery to Running resets the attempt counter"
2464        );
2465        assert!(!step.fire_reauth);
2466    }
2467
2468    /// The non-reauth terminal path (`expiry_action` → `Expired`: no auth key / reauth disabled /
2469    /// TKA-locked) reports `Expired` and never fires reauth; the counter is irrelevant (this path
2470    /// never armed the machine), so it resets to 0.
2471    #[test]
2472    fn expired_action_is_terminal_without_firing() {
2473        let step = reauth_circuit_step(ExpiryAction::Expired, false, 0);
2474        assert_eq!(step.next, ReauthState::Expired);
2475        assert!(!step.fire_reauth);
2476        assert_eq!(step.attempts, 0);
2477    }
2478
2479    /// The full episode as the handler drives it, feeding each step's `attempts` into the next: a
2480    /// one-shot auth key that never recovers fires reauth exactly ONCE, counts each repeated expired
2481    /// self-node, and settles on terminal `Expired` at the cap — never an indefinite `Reauthenticating`
2482    /// spell and never a second rotation.
2483    #[test]
2484    fn full_episode_one_shot_key_settles_at_expired_after_one_fire() {
2485        // Step 1: first expired self-node (state was Running → not already reauthing): enter + fire.
2486        let s1 = reauth_circuit_step(ExpiryAction::Reauthenticate, false, 0);
2487        assert_eq!(s1.next, ReauthState::Reauthenticating);
2488        assert!(s1.fire_reauth);
2489        let mut attempts = s1.attempts;
2490        let mut fires = 1; // counted the one fire
2491
2492        // Steps 2..: still expired while reauthenticating — count only, never re-fire — until the cap.
2493        loop {
2494            let s = reauth_circuit_step(ExpiryAction::Reauthenticate, true, attempts);
2495            if s.fire_reauth {
2496                fires += 1;
2497            }
2498            attempts = s.attempts;
2499            if s.next == ReauthState::Expired {
2500                break;
2501            }
2502            assert_eq!(s.next, ReauthState::Reauthenticating);
2503            assert!(attempts < MAX_REAUTH_ATTEMPTS);
2504        }
2505
2506        assert_eq!(attempts, MAX_REAUTH_ATTEMPTS, "settles exactly at the cap");
2507        assert_eq!(
2508            fires, 1,
2509            "reauth (and thus a node-key rotation) fires exactly once across the whole episode"
2510        );
2511    }
2512
2513    /// Recovery then a fresh failing episode: `Reauthenticating → Running` (reset) → a later expiry
2514    /// re-enters and re-fires. Proves the reset gives the next episode a full attempt budget rather
2515    /// than carrying a stale count that would trip the breaker early.
2516    #[test]
2517    fn recovery_then_new_episode_re_fires() {
2518        // Episode 1 entry.
2519        let e1 = reauth_circuit_step(ExpiryAction::Reauthenticate, false, 0);
2520        assert!(e1.fire_reauth);
2521        // A non-recovering step, then recovery to Running resets.
2522        let mid = reauth_circuit_step(ExpiryAction::Reauthenticate, true, e1.attempts);
2523        assert_eq!(mid.attempts, 2);
2524        let recovered = reauth_circuit_step(ExpiryAction::Running, true, mid.attempts);
2525        assert_eq!(recovered.attempts, 0);
2526
2527        // Episode 2: a fresh expiry (state is Running again → not already reauthing) re-enters + fires.
2528        let e2 = reauth_circuit_step(ExpiryAction::Reauthenticate, false, recovered.attempts);
2529        assert_eq!(e2.next, ReauthState::Reauthenticating);
2530        assert_eq!(e2.attempts, 1, "the new episode starts fresh at 1");
2531        assert!(
2532            e2.fire_reauth,
2533            "a new episode after recovery fires reauth again"
2534        );
2535    }
2536}
2537
2538#[cfg(test)]
2539mod self_lockout_tests {
2540    use ts_tka::{AumHash, Authority, State};
2541
2542    use super::{SelfLockVerdict, self_lock_verdict};
2543
2544    fn node_key() -> ts_keys::NodePublicKey {
2545        ts_keys::NodePrivateKey::random().public_key()
2546    }
2547
2548    /// An empty key-signature is the "not signed yet" case: `Unsigned`, never a lockout warning —
2549    /// so a tailnet that simply has not signed this node does not spam a `warn`.
2550    #[test]
2551    fn empty_signature_is_unsigned_not_locked_out() {
2552        let authority = Authority::from_state(AumHash([0; 32]), State::default());
2553        assert_eq!(
2554            self_lock_verdict(&node_key(), &[], &authority),
2555            SelfLockVerdict::Unsigned
2556        );
2557    }
2558
2559    /// A non-empty key-signature that does not authorize self classifies as `LockedOut` — the
2560    /// operator-facing condition — and the verdict carries the verify error string for the log. Here
2561    /// the blob is non-empty (so we attempt verification rather than short-circuiting to `Unsigned`)
2562    /// but is not a valid NodeKeySignature CBOR (`0x01` decodes as a bare uint with trailing bytes),
2563    /// so `node_key_authorized` returns a `Decode` error → `LockedOut`. The cryptographic-rejection
2564    /// arms (`UntrustedKey` / `BadSignature` for a well-formed-but-untrusted NKS) are covered by
2565    /// `ts_tka`'s own `node_key_authorized` tests; this only needs to prove the runtime classifier
2566    /// routes a verify `Err` to `LockedOut`.
2567    #[test]
2568    fn unverifiable_signature_is_locked_out() {
2569        let authority = Authority::from_state(AumHash([0; 32]), State::default());
2570        let verdict = self_lock_verdict(&node_key(), &[0x01, 0x02, 0x03], &authority);
2571        assert!(
2572            matches!(verdict, SelfLockVerdict::LockedOut(_)),
2573            "a signature the lock cannot authorize must classify as LockedOut, got {verdict:?}"
2574        );
2575    }
2576}