Skip to main content

gunnar_server/
serve.rs

1//! `gunnar serve` starts its listeners together and stops them together. They
2//! share nothing but the control plane behind them.
3//!
4//! ```text
5//!   :2222            SSH   git-upload-pack / git-receive-pack, publickey auth
6//!   :8080            HTTP  the same two verbs over smart HTTP, access-token
7//!                          auth — only with `--features http` AND `--http-bind`
8//!   127.0.0.1:50051  gRPC  the control plane; authenticated (sshsig + the
9//!                          ACL model) unless the development escape hatch is on
10//! ```
11//!
12//! **The two git listeners are two doors onto one room**, and the wiring below
13//! is what keeps that true: the same `Dispatch`, the same `WireTransport`, the
14//! same `ServerMetrics` and the one `allow_anonymous` field are handed to both.
15//! A second control plane or a second transport here is how SSH and HTTP would
16//! come to disagree about who may push.
17//!
18//! Git traffic never passes through gRPC. There is no bridge and none is
19//! wanted: it is that separation which makes the v1 authentication hole
20//! survivable, because an open gRPC port cannot push code.
21//!
22//! # What this module is responsible for saying out loud
23//!
24//! 1. **Whether the unauthenticated enrolment door is open**, at every start,
25//!    on stdout *and* in the log. `gunnar_core::AuthTable::prepare_to_serve`
26//!    returns the state as a value; [`announce_readiness`] is the caller that
27//!    has to branch on it, and `tests/bootstrap.rs` asserts every branch.
28//!
29//!    Until 2026-08-05 an empty identity table with no `--admin-key` was a
30//!    **refusal to start** (the secret-store seam). That is why gunnar had no first boot: the
31//!    box could not be reached to be given its first key, and the only way in
32//!    was `gunnar key add` with the server down, which needs a shell the
33//!    appliance does not have. It now starts and serves `Bootstrap.Enroll`
34//!    until somebody uses it — see `gunnar_grpc::service::bootstrap`.
35//! 2. **gRPC binds loopback unless told otherwise**, and says so at startup
36//!    whatever it binds.
37//!
38//! # Two listeners, and now two runtimes
39//!
40//! Separate listeners separate the *ports*. They did not separate the *schedulers*, and that
41//! turned out to be most of what the separation was for.
42//!
43//! `ControlPlane` is a synchronous trait — `gunnar-grpc`'s `seam.rs` says so,
44//! and says the backend belongs behind `spawn_blocking` "at the call site" —
45//! and no call site does it. `Admin.StorageInfo` runs an unbounded recursive
46//! `std::fs::read_dir` that `stat`s every loose object in the repository,
47//! straight from its `async fn`, on a worker thread. `Repos.Create` opens a git
48//! directory and replays an arrow log. While both listeners shared one runtime,
49//! a handful of concurrent control-plane calls occupied every worker and the SSH
50//! listener's accept, handshake and exec dispatch simply did not run. The loopback default leaves
51//! the control port unauthenticated, so that was reachable on purpose as well as
52//! by accident.
53//!
54//! **The control plane therefore gets its own runtime**, built here, with its
55//! own worker threads and its own blocking pool. Two properties follow that
56//! thirty `spawn_blocking` wrappers would not have given:
57//!
58//! * it holds for *every* control-plane call, including ones written later by
59//!   somebody who never read `seam.rs`. The fix is by construction rather than a
60//!   convention thirty call sites have to keep (one implementation);
61//! * a control plane that stalls completely degrades the control plane only. Git
62//!   keeps being served.
63//!
64//! The gRPC listener is bound **on** that runtime rather than handed to it: a
65//! tokio socket registers with the I/O driver of the runtime that created it,
66//! and one whose driver belongs to a runtime that is shutting down is a stall
67//! waiting to happen. `tests/control_plane_starvation.rs` measures the whole
68//! thing from an OS thread outside both runtimes.
69
70use std::net::SocketAddr;
71use std::sync::Arc;
72
73use anyhow::{bail, Context, Result};
74use gunnar_core::observe::{MetricsSnapshot, RequestId, ServerMetrics};
75use gunnar_core::{ensure_host_key, Readiness};
76use gunnar_grpc::{EventBus, ServerConfig, ServiceContext};
77use gunnar_ssh::{BoundServer, GunnarSsh, SshConfig};
78use tokio::sync::oneshot;
79use tokio::task::JoinHandle;
80
81use gunnar_common::bindspec::BindSpec;
82
83use crate::control_plane::CoreControlPlane;
84use crate::stores::ServerStores;
85use crate::transport::{WireConfig, WireTransport};
86
87/// What `gunnar serve` was asked for.
88#[derive(Debug, Clone)]
89pub struct ServeConfig {
90    /// Where the SSH listener binds.
91    pub ssh_bind: SocketAddr,
92    /// Where the gRPC control plane binds. Loopback by default.
93    ///
94    /// A [`BindSpec`] rather than a `SocketAddr` because an appliance's private
95    /// address is DHCP-learned: the declaration names `eth1:50051` and
96    /// [`run`] resolves it, ONCE, after `GUNNAR_NET` has brought the link up
97    /// and before anything binds. Downstream — the readiness line, the
98    /// dashboard row, `Admin.Health` — then reports the address the listener
99    /// actually took, not the spelling it was asked for.
100    pub grpc_bind: BindSpec,
101    /// The DEVICE the control plane listens on, when `grpc_bind` was spelled as
102    /// an interface (`eth1:50051`) — set by [`run`]/[`start`] from that spelling
103    /// and honoured as `SO_BINDTODEVICE` on the listener socket, so the
104    /// interface name means the interface and not merely the address it held
105    /// at boot. MEASURED 2026-09-05 (the KVM bench rig, two slirp NICs on the
106    /// same 10.0.2.0/24): an address-only bind of eth1's 10.0.2.15 answered
107    /// through eth0, because both NICs held that address and the route decided.
108    /// On a cloud whose utility NIC is `eth1` on its own subnet the two agree;
109    /// the device bind makes them agree everywhere. `None` for an address spec.
110    pub grpc_bind_device: Option<String>,
111    /// An OpenSSH public key line to install as the bootstrap admin when the
112    /// identity table is empty (the secret-store seam).
113    pub admin_key: Option<String>,
114    /// **The keys `Bootstrap.Restore` is taken from** (`--restore-pubkey`, h-v1-6a): OpenSSH
115    /// public key lines or `@<path>`, resolved and checked at start. An installer-fed box adds
116    /// the fed admin keys itself; a box with neither refuses every restore by name.
117    pub restore_pubkeys: Vec<String>,
118    /// Start the SSH listener only.
119    pub no_grpc: bool,
120    /// **`--wg-only`: every box-to-box connection runs over the estate's
121    /// WireGuard overlay** (owner, 2026-10-04). The address the control plane
122    /// is bound on (`eth1:50051`, the utility network) serves NOTHING: the
123    /// control plane and the replication listener answer only on the tunnel's
124    /// address ([`crate::tunnel_addr`]), and SSH — bound for the public's git
125    /// clients — drops a connection that arrives at the utility address before
126    /// a byte is spoken. A plain-IP connection between two boxes is refused.
127    pub wg_only: bool,
128    /// `--role twin`: no forge listener from the first boot (loopback only),
129    /// whether or not `Bootstrap.BecomeTwin` has run yet.
130    pub twin_role: bool,
131    /// Whether a caller with **no key** may clone a repository marked
132    /// [`Visibility::Public`](gunnar_core::Visibility::Public). `true` by
133    /// default; nothing is anonymously readable until a repository is
134    /// deliberately made public, because `Private` is the default for a new
135    /// one.
136    ///
137    /// Reaches [`SshConfig::allow_anonymous`](gunnar_ssh::SshConfig::allow_anonymous)
138    /// **and `HttpConfig::allow_anonymous`**, from this one field. Two fields
139    /// is how one of them ends up stubbed: an operator who passed
140    /// `--no-anonymous` and got it honoured on one transport has a server that
141    /// serves strangers and reports that it does not. The gRPC control plane
142    /// has no anonymous mode to switch, at any setting.
143    pub allow_anonymous: bool,
144    /// **`--anonymous allow|refuse`** (the browse replica): whether an
145    /// anonymous read is SERVED here or sent to the browse replica the
146    /// refusal names. Orthogonal to `allow_anonymous`, which is whether a
147    /// stranger authenticates at all; this is what the dispatcher tells one
148    /// who did. Both front doors read it through the one `Control`.
149    pub anonymous: gunnar_ssh::AnonymousPolicy,
150    /// Where the smart-HTTP listener binds. `None` does not start
151    /// it, which is the default.
152    ///
153    /// Off unless asked for, because a second listening port is a decision an
154    /// operator makes and not one a default makes for them. The feature it
155    /// needs is off by default too, so an appliance image compiles no HTTP at
156    /// all.
157    #[cfg(feature = "http")]
158    pub http_bind: Option<SocketAddr>,
159    /// Whether the HTTP listener will read a credential off a plain connection
160    /// Default: only when a proxy attests TLS.
161    #[cfg(feature = "http")]
162    pub http_cleartext: gunnar_http::Cleartext,
163    /// Terminate TLS on the smart-HTTP listener itself. `None` — the default —
164    /// is the proxy-terminated shape; `SelfMinted` is the single-executable
165    /// shape (leaf minted from this server's own issuer at start, chain
166    /// closed for clients that pin the issuer); `Identity` is
167    /// bring-your-own-PEM.
168    #[cfg(feature = "http")]
169    pub http_tls: Option<HttpTls>,
170    // (HttpTls is defined right below ServeConfig.)
171    /// **Build every push**, in this process, hermetically (roadmap phase 3).
172    ///
173    /// `None` — the default — is a server that stores and serves and does not
174    /// build. `Some` starts the runner on the same event bus every push
175    /// publishes on, which is what makes the golden path's fourth step
176    /// *nothing at all*.
177    ///
178    /// It is in the serving process on purpose: a second process cannot
179    /// subscribe to an in-process bus, and a runner that polled the attestation
180    /// log instead would build a push some time *after* it landed rather than
181    /// *because* it landed.
182    pub runner: Option<crate::runner::WatchConfig>,
183    /// Require a **client certificate** on the gRPC control plane, minted by
184    /// this server's own issuer (the mTLS plan).
185    ///
186    /// `None` — the default — is the loopback shape the unauthenticated v1 assumes: the listener
187    /// binds `127.0.0.1` and a credential in metadata is the identity.
188    /// `Some(GrpcTls::SelfMinted)` is the shape a control plane reachable off
189    /// the box needs, and it changes two things at once: the transport refuses
190    /// a peer whose certificate this issuer did not sign, and the gate maps the
191    /// certificate that got through to an ACL principal.
192    ///
193    /// Deliberately **not** on by default. Turning it on rewrites how every
194    /// existing client must connect, and a security default that silently
195    /// breaks the working configuration gets switched back off in a hurry —
196    /// which leaves it off everywhere. It is a flag an operator turns on when
197    /// the listener leaves loopback, and `--grpc-bind` off loopback without it
198    /// is what the startup warning names.
199    pub grpc_tls: Option<GrpcTls>,
200    /// `--web-relying-party`, unparsed: the WebAuthn relying parties the gRPC
201    /// plane answers for (`gunnar_grpc::webauthn::RelyingParty`).
202    pub web_relying_parties: Vec<String>,
203    /// **The mutual replication listener** (`--grpc-replication-bind`, lane T9):
204    /// the door a twin follows this box through. Served only with a client
205    /// certificate this box's issuer signed, TLS 1.3 only, its leaf minted from
206    /// the issuer at every start under the fixed name
207    /// `gunnar_grpc::client_signer::REPLICATION_SERVER_NAME`.
208    ///
209    /// `None` DERIVES it, and the derivation is what lets the ONE medium carry
210    /// no flag: a control plane bound off loopback (the appliance,
211    /// `0.0.0.0:50051`) gets this listener on the same address, port + 1
212    /// (`50052`); a loopback one (a laptop, a test) gets none. Its main
213    /// listener stays exactly what it was, because turning `--grpc-tls-self` on
214    /// for the whole plane would lock out every client that has no certificate
215    /// — and the bootstrap door with them.
216    pub grpc_replication_bind: Option<SocketAddr>,
217    // (HttpTls is defined right below ServeConfig.)
218    /// How many git transfers may be in flight across the whole server.
219    /// `None` takes
220    /// [`DEFAULT_MAX_CONCURRENT_TRANSFERS`](gunnar_ssh::config::DEFAULT_MAX_CONCURRENT_TRANSFERS).
221    ///
222    /// The fix note on the admission gate says every one of these numbers needs to be
223    /// settable, because the right one is deployment-specific; until now
224    /// neither was reachable from `gunnar serve` and the two defaults were the
225    /// only values any deployment could have. That is also why the pressure
226    /// harness could not reach contention without 320 client processes.
227    pub max_concurrent_transfers: Option<usize>,
228    /// The **memory budget** the admission ledger may give out to git
229    /// operations in flight, in bytes (gate 2). `None` takes
230    /// [`crate::budget::budgets`]'s derived figure — `MemAvailable` x
231    /// [`crate::budget::TRANSFER_MEMORY_PERCENT`] — rather than
232    /// `gunnar-ssh`'s compiled-in 8 GiB, which was a number about the cgroup
233    /// one bakeoff ran in and not about this box.
234    pub memory_budget_bytes: Option<u64>,
235    /// How long a transfer may **wait** for a slot before it is refused.
236    /// `None` takes [`gunnar_ssh::governor::DEFAULT_ADMISSION_WAIT`];
237    /// `Some(Duration::ZERO)` restores the instant refusal.
238    pub admission_wait: Option<std::time::Duration>,
239    /// A principal's guaranteed floor and its share of a contended server.
240    /// `None` takes
241    /// [`DEFAULT_MAX_TRANSFERS_PER_PRINCIPAL`](gunnar_ssh::config::DEFAULT_MAX_TRANSFERS_PER_PRINCIPAL).
242    pub max_transfers_per_principal: Option<usize>,
243    /// How many git reads may be served **without a key** at once.
244    /// `None` takes
245    /// [`DEFAULT_MAX_ANONYMOUS_TRANSFERS`](gunnar_ssh::admission::DEFAULT_MAX_ANONYMOUS_TRANSFERS).
246    ///
247    /// Note the asymmetry with the field above, which is deliberate: that one
248    /// is a floor a principal is guaranteed and may exceed on a quiet box, this
249    /// one is a wall that binds however empty the server is. See
250    /// [`gunnar_ssh::admission`] for why work-conserving is the right instinct
251    /// for a tenant and the wrong one for a stranger.
252    pub max_anonymous_transfers: Option<usize>,
253    /// **The usage share** (`admit-share`): `--admit-limit` and
254    /// `--admit-window-days`, parsed. See [`gunnar_ssh::SshConfig::admit`].
255    #[cfg(feature = "admit-share")]
256    pub admit: gunnar_ssh::edda_admit::Settings,
257    /// Make the per-principal number an unconditional wall again rather than a
258    /// max-min share. See
259    /// [`SshConfig::per_principal_limit_is_hard`](gunnar_ssh::SshConfig::per_principal_limit_is_hard).
260    pub per_principal_limit_is_hard: bool,
261    /// How many worker threads the control plane's **own** runtime gets.
262    /// `None` derives it from [`control_plane_workers`].
263    ///
264    /// A knob rather than a constant, because the right number is a deployment
265    /// question: a box whose operators live in the UI wants more, an appliance
266    /// serving one CI fleet wants fewer. A test also has to be able to make the
267    /// pool small enough to saturate it deliberately.
268    pub control_plane_workers: Option<usize>,
269    /// The largest object `Refs.ReadObject` will inflate. `None`
270    /// takes
271    /// [`CoreControlPlane`](crate::CoreControlPlane)'s default of 64
272    /// MiB; `Some(0)` means no ceiling.
273    ///
274    /// A knob for the same reason `control_plane_workers` is one: the number is
275    /// `memory budget / concurrent inflates`, and the budget is a deployment
276    /// question. It is also the only one of these that turns a request which
277    /// works today into a refusal, which is exactly why it must be reachable
278    /// rather than compiled in.
279    pub max_object_bytes: Option<u64>,
280    /// How often the counter heartbeat is written. `None` turns it
281    /// off.
282    ///
283    /// The heartbeat answers *"what is this server doing right now"* from a log
284    /// the operator already has open, with nothing to scrape. It stays quiet
285    /// while nothing changes, so an idle appliance does not fill its journal.
286    pub metrics_interval: Option<std::time::Duration>,
287    /// Where the **scrape endpoint** binds. `None` does not start it,
288    /// which is the default.
289    ///
290    /// The heartbeat above and this are the same nineteen numbers reached two
291    /// ways, and both are wanted: the heartbeat needs nothing set up and is
292    /// already in the journal when an incident is reconstructed afterwards; the
293    /// endpoint can be *asked*, at whatever rate the person asking chooses,
294    /// which is the only way `transfers_in_flight` distinguishes a slow
295    /// transfer from a stuck one while it is still happening.
296    ///
297    /// Off unless asked for, for the same reason [`ServeConfig::http_bind`] is:
298    /// a second listening port is an operator's decision. See
299    /// [`crate::scrape`] for why it carries no authentication and what
300    /// that does and does not expose.
301    pub metrics_bind: Option<SocketAddr>,
302    /// Replication to a second gunnar (replication). `None` reads
303    /// `<data-root>/replication.json`, which is what an operator configures and
304    /// what a restart picks up; `Some` overrides it in-process and is how a
305    /// test points a primary at a standby it just started on an ephemeral port.
306    ///
307    /// A configuration with no targets starts nothing at all: no task, no
308    /// subscriber. A server that replicates nowhere pays nothing for the
309    /// feature existing.
310    #[cfg(feature = "replication")]
311    pub replication: Option<crate::mirror::ReplicationConfig>,
312    /// **I11's passive heartbeat**: probe this primary and take over if it stops
313    /// answering. `None` — the default — starts no task at all.
314    ///
315    /// Off unless asked for, and that is the design rather than caution:
316    /// `control_plane.rs::replication_abdicate` states the rule, *"naming a new
317    /// primary is the operator's decision, never a default this box picks"*, and
318    /// a box that promoted itself because nobody configured it not to would
319    /// make that decision for every deployment that never heard of the feature.
320    ///
321    /// It does nothing on a box whose role is `Primary`: the task re-reads the
322    /// role every tick and leaves when it is not a standby, so setting it on
323    /// both boxes of a pair is harmless and is what a symmetric unit file wants.
324    /// See [`crate::standby_watch`] for what the probe does and does not prove.
325    #[cfg(feature = "replication")]
326    pub standby_watch: Option<crate::standby_watch::StandbyWatch>,
327    /// **The estate repairs itself** (5.4): the boot check after the control plane
328    /// listens (it RECHARGES only with `auto`, the estate's opt-in, off by default)
329    /// and the pull channel to monetize. `None` (the default): neither runs.
330    /// See [`crate::repair`].
331    #[cfg(feature = "replication")]
332    pub repair: Option<crate::repair::RepairConfig>,
333    /// **Where replication's counters are published to**, for the console band, the
334    /// staleness alarm and `Admin.Stats`.
335    ///
336    /// It is on the config rather than returned from [`Server::start`] because
337    /// the console band starts BEFORE the server does — [`run`] hands the same
338    /// view to both, and `start` drops the replicator into it once there is
339    /// one. Left at its default it reports "nothing configured", which is what
340    /// a server with no standby is.
341    pub replication_view: crate::replication_view::ReplicationView,
342    /// **Where the band's `tenants` row is read from**, the same shape and
343    /// for the same reason as `replication_view`: a metered `Server::start`
344    /// fills it from its entitlement slot; a community build never does, and
345    /// the band draws no row.
346    pub tenants_view: crate::dashboard::TenantView,
347    /// **Where the band's `flow` row is read from.** Filled on every build —
348    /// counting what moved is not the metered appliance's capability. See
349    /// [`crate::dashboard::FlowView`].
350    pub flow_view: crate::dashboard::FlowView,
351    /// What the two git state machines serve under (`gunnar-wire`'s own
352    /// `Config` types, held once — see [`WireConfig`]).
353    ///
354    /// Defaults to `gunnar-wire`'s defaults, which is what every deployment
355    /// silently ran on while `with_config` had no callers. The knobs it carries
356    /// were fully implemented in both protocol versions and reachable from
357    /// nowhere; `--no-filter` in particular is the difference between an
358    /// appliance that declines partial clone and one that only says it might.
359    pub wire: WireConfig,
360    /// **The metered appliance's key and pay page** (`metered` only): what
361    /// `--monetize-pubkey` and `--billing-url` resolve to. `None` on a metered
362    /// build starts it with every namespace Free and `Entitlement.Set` refusing
363    /// by name — never with a key it did not have.
364    #[cfg(feature = "metered")]
365    pub metered: Option<crate::entitlement::MeteredConfig>,
366    /// **The disk-headroom floor** (`--disk-floor`): the community plan gate,
367    /// first link of every front door's chain and the guard on `Repos.Create`.
368    /// See `gunnar_ssh::headroom`. Always present — the default is 5 % or
369    /// 2 GiB, whichever is larger — because a box with no floor is a box that
370    /// finds out it is full from a torn pack.
371    pub disk_floor: gunnar_ssh::DiskFloor,
372    /// **What measures the data set** for the floor and the space ledger.
373    /// `None` — every deployment — is one `statvfs` on the data root. A test
374    /// that must fill a data set of a stated size without a filesystem of that
375    /// size hands its own probe here (`tests/push_space_admission.rs`'s
376    /// virtual disk); nothing else about the server changes.
377    pub space_probe: Option<Arc<dyn gunnar_ssh::SpaceProbe>>,
378}
379
380/// The `--anonymous` policy type, re-exported so a caller that builds a
381/// [`ServeConfig`] (the test harness, `gunnar-cli`) names it from here.
382pub use gunnar_ssh::AnonymousPolicy;
383
384impl Default for ServeConfig {
385    fn default() -> Self {
386        ServeConfig {
387            ssh_bind: SocketAddr::from(([0, 0, 0, 0], gunnar_ssh::config::DEFAULT_PORT)),
388            grpc_bind: BindSpec::Addr(gunnar_grpc::DEFAULT_BIND),
389            grpc_bind_device: None,
390            admin_key: None,
391            restore_pubkeys: Vec::new(),
392            no_grpc: false,
393            wg_only: false,
394            twin_role: false,
395            allow_anonymous: true,
396            anonymous: gunnar_ssh::AnonymousPolicy::Allow,
397            #[cfg(feature = "http")]
398            http_bind: None,
399            #[cfg(feature = "http")]
400            http_cleartext: gunnar_http::Cleartext::default(),
401            #[cfg(feature = "http")]
402            http_tls: None,
403            grpc_tls: None,
404            web_relying_parties: Vec::new(),
405            grpc_replication_bind: None,
406            runner: None,
407            max_concurrent_transfers: None,
408            memory_budget_bytes: None,
409            admission_wait: None,
410            max_transfers_per_principal: None,
411            max_anonymous_transfers: None,
412            #[cfg(feature = "admit-share")]
413            admit: gunnar_ssh::edda_admit::Settings::default(),
414            per_principal_limit_is_hard: false,
415            control_plane_workers: None,
416            max_object_bytes: None,
417            metrics_interval: Some(METRICS_INTERVAL),
418            metrics_bind: None,
419            #[cfg(feature = "replication")]
420            replication: None,
421            #[cfg(feature = "replication")]
422            standby_watch: None,
423            #[cfg(feature = "replication")]
424            repair: None,
425            replication_view: crate::replication_view::ReplicationView::new(),
426            tenants_view: crate::dashboard::TenantView::new(),
427            flow_view: crate::dashboard::FlowView::new(),
428            wire: WireConfig::default(),
429            #[cfg(feature = "metered")]
430            metered: None,
431            disk_floor: gunnar_ssh::DiskFloor::default(),
432            space_probe: None,
433        }
434    }
435}
436
437impl ServeConfig {
438    /// A configuration whose listeners take kernel-assigned loopback ports.
439    /// A constructor for tests, not a mode: nothing about what is authenticated
440    /// or dispatched changes.
441    pub fn ephemeral() -> Self {
442        ServeConfig {
443            ssh_bind: SocketAddr::from(([127, 0, 0, 1], 0)),
444            grpc_bind: BindSpec::Addr(SocketAddr::from(([127, 0, 0, 1], 0))),
445            grpc_bind_device: None,
446            ..ServeConfig::default()
447        }
448    }
449}
450
451/// How long [`Server::shutdown`] lets the gRPC listener finish gracefully
452/// before it is aborted.
453///
454/// Long enough for an in-flight unary call to complete on a loaded box, short
455/// enough that a Ctrl-C is answered while the operator is still watching. See
456/// [`Server::shutdown`] for why any bound is needed at all.
457pub const GRPC_SHUTDOWN_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
458
459/// How often `gunnar serve` writes its counters to the log.
460///
461/// Sixty seconds: often enough that an operator watching an incident sees the
462/// numbers move while they are still watching, rare enough that a year of
463/// journal on an idle appliance is not made of heartbeats. The line is skipped
464/// when nothing has changed since the last one, so "quiet" and "not running"
465/// stay distinguishable. A *busy* server is never quiet.
466pub const METRICS_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
467
468/// The size of the blocking pool that carries git transfers.
469///
470/// **A decision, not a default.** Every in-flight transfer occupies one blocking
471/// thread for its whole duration (`WireTransport::serve` bridges the async
472/// duplex into `gunnar-wire`'s blocking `BufRead`/`Write` through
473/// `SyncIoBridge`), so this number *was* the server's real concurrency ceiling,
474/// and it was 512 because that is what `tokio` picks when nobody says. Past it,
475/// transfers queued with no log, no counter and no error.
476///
477/// The ceiling that matters is now
478/// [`SshConfig::max_concurrent_transfers`](gunnar_ssh::SshConfig::max_concurrent_transfers),
479/// which refuses visibly. This pool has to stay comfortably **above** it: it
480/// also carries every other blocking thing the server does — pack indexing, ref
481/// transactions, the arrow log — and a pool sized exactly to the transfer limit
482/// would deadlock the moment a transfer needed a second blocking task.
483/// `the_blocking_pool_is_larger_than_the_transfer_limit` asserts the ordering
484/// rather than leaving it to this paragraph.
485pub const GIT_BLOCKING_THREADS: usize = 512;
486
487/// Worker threads that RUN the control plane's calls, derived from the
488/// machine.
489///
490/// A quarter of the cores, at least four and at most eight. The control plane is
491/// an administrative surface — a handful of operators and a UI — not the
492/// serving path, and the whole point of giving it a separate pool is that stalls
493/// stay inside a bounded number of threads. Giving it one core's worth would
494/// make a single slow `StorageInfo` serialise the UI; giving it the machine
495/// would recreate the problem with extra steps. The floor was two until
496/// R5.1-G (2026-10-07): two slow synchronous calls held both, and every other
497/// call — the console's pages, monetize's `Entitlement.Set` — queued behind
498/// them.
499///
500/// These are the HANDLER workers ([`ServiceContext::with_handler_runtime`]).
501/// The HTTP/2 connections run on [`CONTROL_CONNECTION_WORKERS`] workers of
502/// their own, which no handler can hold, so a client's keepalive PING is
503/// answered however long the calls take.
504pub fn control_plane_workers() -> usize {
505    let cores = std::thread::available_parallelism()
506        .map(|n| n.get())
507        .unwrap_or(4);
508    (cores / 4).clamp(4, 8)
509}
510
511/// Worker threads that drive the control plane's HTTP/2 connections (R5.1-G).
512///
513/// They accept, read and write frames — and answer a client's keepalive PING —
514/// and nothing else: every call runs on the handler runtime
515/// ([`control_plane_workers`] workers). They used to be one runtime, and when
516/// the slow synchronous calls held all of its workers nothing answered the
517/// PING; the console and monetize then killed the connection (their keepalive:
518/// a PING every 10 s, dead 5 s later) and every call in flight on it failed.
519pub const CONTROL_CONNECTION_WORKERS: usize = 2;
520
521/// How many CPUs this process may **run on**, from its affinity mask.
522///
523/// `/proc/self/status`'s `Cpus_allowed_list`, because that is the kernel's own
524/// answer and not a request anybody made. `Some(n)` or `None` when the file is
525/// not there to be read; a missing answer is never guessed at, because the whole
526/// point of [`report_cpu_budget`] is a comparison and half a comparison is
527/// worse than none.
528fn cpus_allowed() -> Option<usize> {
529    let status = std::fs::read_to_string("/proc/self/status").ok()?;
530    let list = status
531        .lines()
532        .find_map(|line| line.strip_prefix("Cpus_allowed_list:"))?;
533    count_cpu_list(list)
534}
535
536/// How many CPUs a kernel CPU list names: `0-31`, `3`, `0-3,8,10-11`.
537///
538/// Split out of [`cpus_allowed`] so it can be exercised on lists this host does
539/// not have. It matters: the reference desktop reports a plain `0-31`, so a version of this that
540/// counted ranges and dropped the singletons passed every test on this box
541/// while answering **0 allowed CPUs on a server pinned to one core** — the
542/// condition the caller exists to detect, read exactly backwards.
543fn count_cpu_list(list: &str) -> Option<usize> {
544    let mut total = 0usize;
545    for range in list.trim().split(',') {
546        let range = range.trim();
547        if range.is_empty() {
548            continue;
549        }
550        total += match range.split_once('-') {
551            Some((lo, hi)) => {
552                let (lo, hi) = (
553                    lo.trim().parse::<usize>().ok()?,
554                    hi.trim().parse::<usize>().ok()?,
555                );
556                hi.checked_sub(lo)?.checked_add(1)?
557            }
558            None => {
559                range.parse::<usize>().ok()?;
560                1
561            }
562        };
563    }
564    (total > 0).then_some(total)
565}
566
567/// Whether the affinity is wide enough against the quota to be worth a line,
568/// and the two numbers to say it with.
569///
570/// Pure, and given both readings rather than taking them, so the condition can
571/// be seen in both states from a test on any machine. Either reading missing is
572/// `None`: half a comparison is worse than none.
573///
574/// **Twice, not any excess.** The two numbers are rarely exactly equal and a
575/// line that fires on nine-versus-eight is a line operators learn to skip.
576/// Twice is where the measurement above already showed a real cost.
577fn spread_budget(allowed: Option<usize>, quota: Option<f64>) -> Option<(usize, usize)> {
578    let (allowed, quota) = (allowed?, quota?);
579    let budget = quota.ceil().max(1.0) as usize;
580    (allowed >= budget.saturating_mul(2)).then_some((allowed, budget))
581}
582
583/// How many CPUs' worth of time this process may **use**, from cgroup v2
584/// `cpu.max`. `None` when there is no quota, which is the ordinary case.
585fn cpu_quota() -> Option<f64> {
586    let own = std::fs::read_to_string("/proc/self/cgroup").ok()?;
587    let rel = own
588        .lines()
589        .find_map(|line| line.strip_prefix("0::"))?
590        .trim()
591        .trim_start_matches('/');
592    let path = std::path::Path::new("/sys/fs/cgroup")
593        .join(rel)
594        .join("cpu.max");
595    let raw = std::fs::read_to_string(path).ok()?;
596    let mut parts = raw.split_whitespace();
597    let quota = parts.next()?;
598    if quota == "max" {
599        return None;
600    }
601    let quota: f64 = quota.parse().ok()?;
602    let period: f64 = parts.next()?.parse().ok()?;
603    (period > 0.0).then(|| quota / period)
604}
605
606/// **Say when the box will let this server run far wider than it will let it
607/// work**, because that costs more than anything in the request path.
608///
609/// A container started with `--cpus 8` on a 32-core host gets eight CPUs of
610/// *quota* spread over thirty-two CPUs of *affinity*. gunnar serves one transfer
611/// on three threads that hand work to each other — a hyper task on a runtime
612/// worker, the `spawn_blocking` thread that runs the git state machine, and the
613/// pack-entry worker `iter_from_counts` spawns — so at N concurrent transfers
614/// the scheduler has ~3N runnable threads and thirty-two places to put them,
615/// while only eight of them may run at a time. Every hand-off then crosses a
616/// core, and a hand-off that crosses a core is a futex.
617///
618/// Measured on the reference desktop, 2026-08-04, one binary, one 8-CPU budget, the `year`
619/// corpus (28 893 objects) over smart HTTP, ramp 1→32 clients:
620///
621/// | budget applied as | CPU-seconds per request, 1 client → 32 |
622/// |---|---|
623/// | `cpu.max` quota only, 32 CPUs allowed | 0.42 → 0.94 |
624/// | the same quota, affinity pinned to 8  | 0.34 → 0.35 |
625///
626/// The quota-only arm spent **40% of the server's CPU** in the kernel's futex
627/// hash-bucket spinlock (`native_queued_spin_lock_slowpath`, `perf record` on
628/// the serving process). The pinned arm is flat: gunnar's per-request cost does
629/// not in fact grow with concurrency, and the ramp that said it did was
630/// measuring where the threads were allowed to run.
631///
632/// So this is a line in the log and not a change of behaviour: gunnar must not
633/// pin itself. It does not know which CPUs are *its* to take, and choosing wrong
634/// would be worse than the condition being reported. The operator does know, and
635/// `--cpuset-cpus` is the whole fix.
636///
637/// The decision is [`spread_budget`], separately, because a condition read off
638/// the host it is running on can only ever be seen in the state that host
639/// happens to be in — and this one has to be seen in both.
640fn report_cpu_budget() {
641    let Some((allowed, budget)) = spread_budget(cpus_allowed(), cpu_quota()) else {
642        return;
643    };
644    tracing::warn!(
645        cpus_allowed = allowed,
646        cpu_quota = budget,
647        "this server may run on {allowed} CPUs but may only use {budget} CPUs' worth of \
648         them. Every hand-off between the three threads that serve one transfer then \
649         crosses a core, and in a 2026-08-04 measurement that cost 2.7x the CPU per \
650         request at 32 concurrent clients against the identical budget applied as a \
651         cpuset. Start the \
652         container with `--cpuset-cpus` (or the unit with `AllowedCPUs=`) naming {budget} \
653         CPUs, not only `--cpus`/`CPUQuota=`."
654    );
655}
656
657/// The runtime `gunnar serve` runs the **git** listener on.
658///
659/// Built here rather than with `#[tokio::main]` so a client-only build links no
660/// async runtime at all, and built with an explicit
661/// [`GIT_BLOCKING_THREADS`] so the number that used to be the server's
662/// accidental concurrency ceiling is now written down somewhere.
663pub fn runtime() -> Result<tokio::runtime::Runtime> {
664    tokio::runtime::Builder::new_multi_thread()
665        .max_blocking_threads(GIT_BLOCKING_THREADS)
666        .thread_name("gunnar-git")
667        .enable_all()
668        .build()
669        .context("building the git runtime")
670}
671
672/// Both listeners, bound and running.
673/// How the smart-HTTP listener gets its TLS identity (see
674/// [`ServeConfig::http_tls`]).
675#[cfg(feature = "http")]
676#[derive(Debug, Clone)]
677pub enum HttpTls {
678    /// Mint a leaf from this server's own issuer at start — the
679    /// single-executable deployment. Refuses to start if it cannot mint;
680    /// silent cleartext fallback is the defect this enum exists to prevent.
681    SelfMinted,
682    /// Operator-supplied chain and key.
683    Identity(gunnar_http::TlsIdentity),
684}
685
686/// How the gRPC control plane gets its **mutual** TLS material.
687///
688/// The mirror of [`HttpTls`], with one difference that is the whole point: the
689/// smart-HTTP listener terminates TLS to encrypt, and this one terminates TLS
690/// to *identify*. So there is no bring-your-own-CA arm here yet. A certificate
691/// the gate can turn into a principal has to have been registered in the ACL
692/// table, and the only thing that mints and registers in one act is this
693/// server's own issuer (`Bootstrap.Enroll`, `gunnar control bootstrap`).
694/// Trusting a foreign CA would mean a certificate that passes the handshake and
695/// can never pass the gate, which is a confusing way to be refused.
696#[derive(Debug, Clone, Copy, PartialEq, Eq)]
697pub enum GrpcTls {
698    /// Mint the listener's own leaf from this server's issuer at start, and
699    /// pin that issuer as the CA every client certificate must come from.
700    ///
701    /// Refuses to start if it cannot mint. A control plane that asked for
702    /// client certificates and came up without them would be the same silent
703    /// downgrade [`HttpTls`] refuses.
704    SelfMinted,
705}
706
707/// **A tokio `Runtime` that is always torn down with `shutdown_background`,
708/// never by a blocking `Drop`.**
709///
710/// Dropping a `Runtime` blocks the current thread on its worker and blocking
711/// pools' shutdown, and tokio **panics** when that blocking drop happens inside
712/// another runtime's context: *"Cannot drop a runtime in a context where
713/// blocking is not allowed."*
714///
715/// [`Server::start`] is an `async fn` that builds the control plane's own
716/// runtime and then runs several more fallible steps before it moves that
717/// runtime into [`Server`]. A `?` anywhere in that window used to drop a bare
718/// `Runtime` on the async stack — and on the appliance gunnar is **PID 1**, so
719/// that panic is the kernel's `Attempted to kill init`. Measured 2026-08-31:
720/// a power cut left a 0-byte `replication.json`, its parse in `start`
721/// failed, the `?` unwound past the live runtime, and the box wedged on every
722/// reboot. Wrapping the runtime in this guard makes the early return safe **by
723/// construction** — one drop path, and it never blocks — instead of by
724/// remembering to hand-`take()` it at each of the several exits.
725///
726/// Since R5.1-G it holds the control plane's TWO runtimes — the connections'
727/// and the calls' — under the one guard, in that order.
728#[derive(Default)]
729struct ControlRuntime(Vec<tokio::runtime::Runtime>);
730
731impl ControlRuntime {
732    /// Hold a runtime whose drop must be non-blocking.
733    fn new(runtime: tokio::runtime::Runtime) -> Self {
734        ControlRuntime(vec![runtime])
735    }
736
737    /// Take over every runtime `other` holds, so one guard drops them all.
738    fn hold(&mut self, other: &mut ControlRuntime) {
739        self.0.append(&mut other.0);
740    }
741
742    /// A handle on the first runtime held, if any.
743    fn handle(&self) -> Option<tokio::runtime::Handle> {
744        self.0.first().map(|runtime| runtime.handle().clone())
745    }
746
747    /// Tear the runtimes down now, without blocking, if any are still held.
748    /// Idempotent, so an explicit call and the `Drop` cannot double-free.
749    fn shutdown(&mut self) {
750        for runtime in self.0.drain(..) {
751            runtime.shutdown_background();
752        }
753    }
754}
755
756impl Drop for ControlRuntime {
757    fn drop(&mut self) {
758        self.shutdown();
759    }
760}
761
762pub struct Server {
763    /// An `Option` only because [`Server`] now has a [`Drop`] impl, which makes
764    /// moving a field out of `self` in [`Server::shutdown`] illegal.
765    ssh: Option<BoundServer>,
766    grpc: Option<JoinHandle<Result<()>>>,
767    grpc_shutdown: Option<oneshot::Sender<()>>,
768    /// The bound gRPC address and whether that listener authenticates, as
769    /// ONE field. They are printed together and must not be able to disagree.
770    grpc_endpoint: Option<(SocketAddr, bool)>,
771    /// The control plane's **own** runtime, kept alive here because
772    /// dropping it would stop the listener it carries.
773    ///
774    /// A [`ControlRuntime`] guard, not a bare `Runtime`: dropping a `Runtime`
775    /// blocks, and doing so from inside another runtime's context panics
776    /// ("Cannot drop a runtime in a context where blocking is not allowed"),
777    /// and both [`Server::start`] and [`Server::shutdown`] run in async
778    /// context. The guard routes *every* drop through `shutdown_background`, so
779    /// no `?`, panic or forgotten `take()` can turn a teardown into an abort —
780    /// which as PID 1 is a kernel panic.
781    control_runtime: ControlRuntime,
782    stores: Arc<ServerStores>,
783    /// Whether the unauthenticated `Bootstrap.Enroll` window was open when this
784    /// server started, so the banner on stdout says the same thing the log does.
785    ///
786    /// A field rather than a re-read: the banner and the warning must not be
787    /// able to disagree about the single most important fact a fresh server has
788    /// (one implementation).
789    bootstrap_window_open: bool,
790    /// **The SSH host key this server is serving, `SHA256:…`.**
791    ///
792    /// Kept so the startup banner can print it. It is logged at start through
793    /// `tracing`, which on the appliance means stderr, which means
794    /// `/dev/console`, which is the LAST `console=` on the command line, which
795    /// is the serial line — and the UpCloud shape has no serial line. So the
796    /// one emission this box makes of the one fact a client has to pin
797    /// reached nobody in production, and `known_hosts` got filled by scanning
798    /// instead. A field, not a re-read, for the same reason
799    /// `bootstrap_window_open` is one: the banner and the log must not be able
800    /// to disagree about it.
801    host_key_fingerprint: String,
802    /// The counters both listeners write to.
803    metrics: Arc<ServerMetrics>,
804    /// The heartbeat task, aborted at shutdown so a stopped server stops
805    /// narrating.
806    heartbeat: Option<JoinHandle<()>>,
807    /// I11's standby watch, held so it is aborted with the server. A watchdog
808    /// that outlived the box it watches over could promote a server that is
809    /// shutting down.
810    #[cfg(feature = "replication")]
811    standby_watch: Option<JoinHandle<()>>,
812    /// The boot check and the pull channel ([`crate::repair`]), aborted with the
813    /// server (a recharge it was running fails its restore stream, never ends it).
814    #[cfg(feature = "replication")]
815    repair: Option<JoinHandle<()>>,
816    /// The event bus both the transport and the control plane publish to.
817    bus: Arc<EventBus>,
818    /// The smart-HTTP listener's task and the address it bound (smart HTTP).
819    /// Dropped with the `Server`, and therefore aborted.
820    #[cfg(feature = "http")]
821    http: Option<(JoinHandle<std::io::Result<()>>, SocketAddr, bool)>,
822    /// The scrape listener's task and the address it bound. Dropped
823    /// with the `Server`, and therefore aborted: a stopped server must stop
824    /// answering, or a scraper keeps drawing the last numbers it saw.
825    scrape: Option<(JoinHandle<std::io::Result<()>>, SocketAddr)>,
826    /// The replicator, when any standby is configured.
827    /// the replicator and its workers, in the LIVE SLOT the control plane
828    /// reconfigures through.
829    ///
830    /// It was an `Option<Arc<Replicator>>` plus an `Option<ReplicationTasks>`
831    /// until 2026-08-30 — decided once at startup, from a file. That is
832    /// unusable on the shape this ships to: an OS-less appliance with no shell,
833    /// where the only way to name a standby is over the control plane. See
834    /// [`ReplicationSlot`](crate::mirror::ReplicationSlot).
835    ///
836    /// Dropped with the `Server`, and therefore aborted, so a stopped server
837    /// stops replicating.
838    #[cfg(feature = "replication")]
839    replication: Arc<crate::mirror::ReplicationSlot>,
840    /// The outbound webhook delivery slot, reconfigured through the control plane.
841    /// Dropped with the `Server`, and therefore aborted, so a stopped server
842    /// stops delivering.
843    #[cfg(feature = "webhooks")]
844    webhook: Arc<crate::webhook::WebhookSlot>,
845}
846
847/// One line every `interval` naming what the server has done, but only when
848/// something moved.
849///
850/// **Not a scrape endpoint.** The load target is a forge, and the first
851/// question at an incident gets answered from the log the operator already has
852/// open. A Prometheus surface is a separate decision with its own cost: another
853/// listener, and another thing to authenticate. This makes the counters
854/// readable today, in four lines.
855async fn heartbeat(metrics: Arc<ServerMetrics>, interval: std::time::Duration) {
856    let mut ticker = tokio::time::interval(interval);
857    // The first tick fires immediately; skip it so start-up does not emit a row
858    // of zeroes that reads like traffic.
859    ticker.tick().await;
860    let mut previous = metrics.snapshot();
861    loop {
862        ticker.tick().await;
863        let now = metrics.snapshot();
864        // An idle server says nothing. A server that has served ANYTHING since
865        // the last beat says what, including one whose only change is that a
866        // transfer finished; that is how `transfers_in_flight` coming back to
867        // zero becomes visible.
868        if now == previous {
869            continue;
870        }
871        emit_metrics(&now);
872        previous = now;
873    }
874}
875
876/// The gRPC control plane's request ids, minted from the **same** counter the
877/// SSH listener and the smart-HTTP listener mint theirs from.
878///
879/// This one line is why `gunnar_grpc::router` takes a source instead of owning
880/// one: `gunnar-grpc` has no `gunnar-core` edge and must not grow one (it would
881/// put `aws-lc-rs`, C and a build script into the `--features client,control`
882/// graph), and a private counter over there would mean a control-plane call and
883/// a git transfer could print the same `req=` value in one log.
884///
885/// `gunnar_grpc::trace`'s rendering is asserted equal to
886/// [`RequestId`]'s by `the_grpc_request_id_renders_exactly_as_gunnar_core_
887/// renders_one` in `tests/observability.rs`, because a shared counter rendered
888/// two ways is still two identifiers.
889fn grpc_request_id() -> u64 {
890    RequestId::next().get()
891}
892
893/// The heartbeat line.
894///
895/// **This function used to BE the line**, and it listed eighteen of the
896/// nineteen counters. `connections_anonymous` — written by both transports
897/// (`gunnar-ssh/src/server.rs`, `gunnar-http/src/service.rs`), and the answer to
898/// *how much of my traffic is strangers*, which the field's own documentation
899/// calls the first question an operator asks after making anything public —
900/// appeared in no line gunnar had ever printed. Nothing was wrong with the
901/// counter; the hand-written list next to it had simply never been updated when
902/// the field was added.
903///
904/// So it is not a hand-written list any more. The line expands from the same
905/// macro arm that declares the fields, in `gunnar-core`, beside the scrape
906/// endpoint's renderer, and neither can fall behind the struct (one implementation). This
907/// wrapper stays only so the heartbeat task and a test call the same one thing.
908fn emit_metrics(now: &MetricsSnapshot) {
909    now.emit_heartbeat();
910}
911
912impl Server {
913    /// Bind everything and start accepting.
914    ///
915    /// Returns once both sockets are bound, so a caller knows the real
916    /// addresses before the first client connects, which is what makes port 0
917    /// usable in a test.
918    pub async fn start(stores: Arc<ServerStores>, config: ServeConfig) -> Result<Server> {
919        report_cpu_budget();
920        // The bind spelling becomes an address HERE, before anything else in
921        // this function can report one. `run` has already resolved it and
922        // replaced the spec with the answer, so on the appliance path this is
923        // the identity case; a caller that reaches `start` directly (every
924        // test, and `gunnar serve` under an init system) gets the resolution
925        // it would otherwise have had to do itself.
926        let mut config = config;
927        // The interface spelling names a DEVICE as well as an address; keep the
928        // device before the spec becomes an address, so the listener can bind it.
929        if let BindSpec::Interface { interface, .. } = &config.grpc_bind {
930            config.grpc_bind_device = Some(interface.clone());
931        }
932        // **An interface whose lease PID 1 still asks for** (its boot DHCP failed —
933        // estate-box3 D4, a box rebooted while its network was down) is WAITED for: the
934        // control plane binds once the address arrives instead of never.
935        if let BindSpec::Interface { interface, .. } = &config.grpc_bind {
936            let has_address = |i: &str| matches!(appliance_pid1::net::interface_ipv4(i), Ok(Some(_)));
937            if !has_address(interface) && appliance_pid1::net::dhcp_pending(interface) {
938                tracing::info!(interface = %interface, "the control plane waits for {interface}'s address (PID 1 asks DHCP again in the background)");
939                while !has_address(interface) && appliance_pid1::net::dhcp_pending(interface) {
940                    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
941                }
942            }
943        }
944        // ★ **An estate box is WireGuard-only** (owner 2026-10-04: every
945        //   box-to-box connection over the tunnel), whatever its medium says: a
946        //   pairing seed with a WireGuard tunnel IS an estate (the front, the
947        //   relay, the overlay). A standalone appliance — no seed — is not.
948        #[cfg(feature = "wg-client")]
949        if !config.wg_only {
950            if let Ok(Some(seed)) = crate::pairing::seed(stores.root()) {
951                if crate::tunnel_addr::estate_is_wg_only(Some(seed.tunnel == nordisk_pairing::seed::TunnelKind::Wireguard)) {
952                    config.wg_only = true;
953                    tracing::warn!("serve: this box belongs to an estate (a WireGuard pairing seed) — WireGuard-only: its utility address serves nothing, boxes speak over the tunnel");
954                }
955            }
956        }
957        // The posture the pairing reads (which address of the primary a twin joins).
958        crate::tunnel_addr::set_wg_only(config.wg_only);
959        let resolved_grpc_bind = match resolve_grpc_bind(&config.grpc_bind)? {
960            Some(addr) => addr,
961            None => {
962                // The interface is there and holds no address. There is nothing
963                // to bind, so there is no control plane — the same shape
964                // `--no-grpc` produces, reached for the same honest reason and
965                // reported through the same field, so the dashboard row, the
966                // readiness line and `Admin.Health` all agree.
967                config.no_grpc = true;
968                gunnar_grpc::DEFAULT_BIND
969            }
970        };
971        // ── the bootstrap: refuse to serve rather than start unreachable ───
972        let admin_key = match &config.admin_key {
973            Some(spec) => Some(read_key_argument(spec)?),
974            None => None,
975        };
976        // The keys a restore is taken from, resolved and CHECKED now: a line that does not
977        // parse would otherwise be a key that silently lets nobody in, found out on the day
978        // of the restore.
979        let restore_keys = config
980            .restore_pubkeys
981            .iter()
982            .map(|spec| {
983                let line = read_key_argument(spec)?;
984                gunnar_core::auth::parse_public_key(line.trim())
985                    .map_err(|err| anyhow::anyhow!("--restore-pubkey {spec:?} is not an OpenSSH public key line: {err:#}"))?;
986                Ok(line.trim().to_owned())
987            })
988            .collect::<Result<Vec<String>>>()?;
989        let readiness = stores
990            .auth()
991            .prepare_to_serve(admin_key.as_deref())
992            .with_context(|| {
993                format!(
994                    "reading the identity table at {}. This is NOT the same as finding it \
995                     empty: a data path that cannot be read must never be served as a server \
996                     nobody has enrolled yet, because that would reopen the bootstrap window on \
997                     a disk fault.",
998                    stores.root().display()
999                )
1000            })?;
1001        announce_readiness(&readiness, stores.root(), resolved_grpc_bind, config.no_grpc);
1002        let bootstrap_window_open = readiness.bootstrap_window_open();
1003
1004        // ── the SSH host key, minted in-process and persisted ──────────────
1005        // A twin frames nothing: its host key is read (the primary's, replayed)
1006        // or minted through the UNLOGGED store, and its follower starts here.
1007        let host_key_store = if stores.is_twin() { stores.secrets_unframed()? } else { stores.secrets()? };
1008        let host_key =
1009            ensure_host_key(&host_key_store).context("loading or minting the SSH host key")?;
1010        if stores.is_twin() {
1011            crate::twin::start_follower(Arc::clone(&stores));
1012        }
1013        // The pairing loop, once the control plane serves: join the front,
1014        // take the role, become the twin if elected (pairing.rs).
1015        #[cfg(feature = "wg-client")]
1016        match crate::pairing::seed(stores.root()) {
1017            Ok(Some(seed)) => crate::pairing::start(Arc::clone(&stores), seed),
1018            Ok(None) => {}
1019            Err(e) => tracing::error!(error = %format!("{e:#}"), "pairing: the seed is present and unusable — this box will not pair"),
1020        }
1021        let host_key_fingerprint = host_key.fingerprint().to_string();
1022        tracing::info!(
1023            fingerprint = %host_key_fingerprint,
1024            "ssh host key ready (persisted; it survives a restart)"
1025        );
1026        // The fingerprint crosses the ssh-key version split as BYTES: gunnar-core
1027        // links ssh-key 0.6 and russh pins 0.7.0-rc.10, so no key type can be
1028        // handed from one to the other.
1029        let russh_key = russh_private_key(host_key.private_openssh())
1030            .context("handing the host key to russh")?;
1031
1032        // ── the certificate issuer, minted at first start ──────────────────
1033        //
1034        // The same discipline as the host key above: a fresh appliance mints
1035        // its own, and a restart finds the one it minted. `Pki::create`'s
1036        // refusal lives under the document's compare-and-swap, so two racing
1037        // starts cannot mint two issuers. Failure is a warning, not a refusal
1038        // to serve: SSH-key auth carries the server whether or not certificates
1039        // exist, and an operator who imports a CA later gets exactly the
1040        // `issuer import` refusal they should.
1041        match stores.pki() {
1042            Ok(pki) => match pki.issuer() {
1043                Ok(Some(live)) => tracing::info!(
1044                    subject = %live.subject,
1045                    fingerprint = %live.fingerprint,
1046                    "issuer ready (persisted; it survives a restart)"
1047                ),
1048                Ok(None) => match pki.create("gunnar issuer", gunnar_core::DEFAULT_ISSUER_DAYS) {
1049                    Ok(created) => tracing::warn!(
1050                        subject = %created.subject,
1051                        fingerprint = %created.fingerprint,
1052                        "FIRST START: this server minted its own certificate issuer. Its \
1053                         private key is sealed in the secret store. `gunnar issuer show --pem` \
1054                         prints the certificate clients pin."
1055                    ),
1056                    Err(err) => tracing::warn!(
1057                        %err,
1058                        "the issuer could not be minted at first start; certificate issuance \
1059                         is unavailable until `gunnar issuer create` or `issuer import` succeeds"
1060                    ),
1061                },
1062                Err(err) => tracing::warn!(%err, "the PKI document could not be read"),
1063            },
1064            Err(err) => tracing::warn!(
1065                %err,
1066                "no secret store, so no issuer: certificate issuance is unavailable"
1067            ),
1068        }
1069
1070        // ── can this server be moved onto mutual TLS? ──────────────────────
1071        //
1072        // Asked HERE, and the position is two decisions rather than one.
1073        //
1074        // **After the issuer block above**, because that block MINTS one on a
1075        // first start: asking before it would refuse a server whose issuer is
1076        // four lines from existing, and the refusal would name the one thing
1077        // the operator did not have to do.
1078        //
1079        // **Before anything binds, and before the control plane's runtime is
1080        // built.** Two reasons:
1081        //
1082        // 1. `--grpc-tls-self` is a one-way door for everybody who cannot
1083        //    complete the handshake afterwards, and exactly one state makes
1084        //    it a door with nobody on either side. A server asked for client
1085        //    certificates that cannot honour the ask must be a startup error
1086        //    naming the cause, never a listener that came up — the same
1087        //    discipline `--http-tls-*` already follows.
1088        // 2. **A `?` past the control runtime is an appliance that will not
1089        //    boot.** `ControlRuntime`'s own docs record the measurement: that
1090        //    `Runtime` is built bare inside this function and dropping one on
1091        //    an async stack panics, and on the appliance gunnar is PID 1, so
1092        //    the panic is `Attempted to kill init`. The first draft of this
1093        //    check sat beside the trust root, inside that window, and
1094        //    `tests/tls_transition.rs` failed with exactly that panic instead
1095        //    of the refusal it was asserting. That test is the guard that it
1096        //    does not move back.
1097        //
1098        // `crate::tls_preflight` holds the argument and the verdicts;
1099        // `gunnar issuer readiness` is this same function asked in advance,
1100        // so the answer an operator plans against is the answer acted on here
1101        // (one implementation).
1102        if !config.no_grpc && config.grpc_tls.is_some() {
1103            let preflight = crate::tls_preflight::preflight(&stores)
1104                .context("checking whether this server can move to mutual TLS")?;
1105            if let Some(refusal) = preflight.refusal() {
1106                anyhow::bail!("{refusal}");
1107            }
1108            preflight.warn();
1109        }
1110
1111        // ── the SSH listener ───────────────────────────────────────────────
1112        //
1113        // ONE set of counters, minted here and shared by the listener
1114        // and the transport. Two `ServerMetrics` would produce two partial
1115        // truths, the listener's refusals in one and the transport's pushes in
1116        // the other, and neither answers "what is this server doing".
1117        let metrics = Arc::new(ServerMetrics::new());
1118        let bus = Arc::new(EventBus::new(gunnar_grpc::DEFAULT_EVENT_BUFFER));
1119        let transport = Arc::new(
1120            WireTransport::new(Arc::clone(&stores))
1121                .with_bus(Arc::clone(&bus))
1122                .with_metrics(Arc::clone(&metrics))
1123                .with_wire_config(config.wire.clone()),
1124        );
1125        let defaults = SshConfig::default();
1126        // The DECLARED budget (`crate::budget`): cores x TRANSFERS_PER_CORE,
1127        // capped by the descriptors the handle cache has not already spoken
1128        // for, with `MemAvailable` sizing the ledger. An operator's
1129        // `--max-concurrent-transfers` still wins — `.or()` below — and so does
1130        // `GUNNAR_MAX_TRANSFERS`, which is how the appliance's kernel command
1131        // line reaches it. Before this the ceiling was the shipped 256, which
1132        // the governor then walked down to 19 under load while the
1133        // ledger's flat 320 MiB-per-push refused everything past 25.
1134        let mut budgets = crate::budget::budgets();
1135        // **Recorded, so the box can say later whether its socket is where a
1136        // twin's belongs** (2026-09-21, lane T4). A box told it is a twin AFTER
1137        // this line keeps whatever was bound here until it restarts;
1138        // `twin::git_listener_needs_restart` is how that is reported instead of
1139        // being left to `ss`.
1140        let twin_shaped = stores.is_twin() || config.twin_role;
1141        crate::twin::note_git_bind_is_twin_shaped(twin_shaped);
1142        let ssh_config = SshConfig {
1143            bind: if twin_shaped {
1144                // **No forge listener on a twin.** It serves no git to anyone: a
1145                // read would grow the caches the twin must not hold. The listener
1146                // the rest of `start` is wired around stays, on loopback, port 0.
1147                tracing::warn!(target: gunnar_core::observe::TARGET_TWIN, asked = %config.ssh_bind, "this box is a TWIN: the git listener is bound to loopback only");
1148                SocketAddr::from(([127, 0, 0, 1], 0))
1149            } else {
1150                config.ssh_bind
1151            },
1152            allow_anonymous: config.allow_anonymous,
1153            // The banner names the BUILD, not just the crate version. On the
1154            // OS-less appliance this listener is the only thing that can be
1155            // asked what is running — there is no shell to run `gunnar
1156            // --version` in. See `gunnar_common::ssh_server_id`.
1157            server_id: gunnar_common::ssh_server_id(),
1158            // `or` rather than `unwrap_or`: `None` here means "the operator did
1159            // not say", which takes the default. Turning a limit *off* is
1160            // `Some(0)`-free and stays a code path, not a flag, because an
1161            // appliance with no transfer ceiling is the unbounded listener
1162            // exactly as it was.
1163            max_concurrent_transfers: config.max_concurrent_transfers.or(Some(budgets.transfers)),
1164            memory_budget_bytes: config.memory_budget_bytes.or(Some(budgets.memory_bytes)),
1165            admission_wait: config.admission_wait.or(defaults.admission_wait),
1166            max_transfers_per_principal: config
1167                .max_transfers_per_principal
1168                .or(defaults.max_transfers_per_principal),
1169            // `or` for the same reason as the two above: `None` means the
1170            // operator did not say, which takes `SshConfig::default`'s
1171            // ceiling. Switching it OFF is deliberately not reachable from a
1172            // flag — `Some(0)` refuses everything anonymous, and letting
1173            // anonymous inherit a keyed identity's share is the hole anonymous read opened
1174            // and this closed, not a configuration.
1175            max_anonymous_transfers: config
1176                .max_anonymous_transfers
1177                .or(defaults.max_anonymous_transfers),
1178            per_principal_limit_is_hard: config.per_principal_limit_is_hard,
1179            #[cfg(feature = "admit-share")]
1180            admit: config.admit,
1181            ..defaults
1182        };
1183        // The row says what is IN FORCE, after the operator's flags: a line
1184        // that printed the derivation while the server ran on something else
1185        // would be worse than no line, because the first thing anybody does
1186        // with it is compare it to the refusals underneath it.
1187        if let Some(n) = config.max_concurrent_transfers {
1188            budgets.transfers = n;
1189            budgets.transfers_from = crate::budget::Source::Operator;
1190        }
1191        if let Some(bytes) = config.memory_budget_bytes {
1192            budgets.memory_bytes = bytes;
1193        }
1194        if let Some(wait) = config.admission_wait {
1195            budgets.wait_ms = wait.as_millis() as u64;
1196        }
1197        crate::budget::announce(&budgets);
1198
1199        #[cfg(feature = "http")]
1200        let http_transport: Arc<dyn gunnar_ssh::seam::GitTransport> = Arc::clone(&transport) as _;
1201        // The SAME `WireTransport`, reached through a second trait rather than
1202        // a second object: `open_lfs` hands out the store under the repository's
1203        // own git dir and the `WireConfig::lfs` limits the SSH session is built
1204        // with, so an operator's `--max-lfs-object-bytes` binds on both
1205        // transports or on neither.
1206        // ── the metered appliance's entitlement slot, before any front door ─
1207        //
1208        // Opened here so BOTH front doors and the control plane share ONE
1209        // slot (one implementation): the same arc-swap the SSH dispatch reads is the one
1210        // `Entitlement.Set` swaps. Loading it re-verifies every stored fact
1211        // (see `crate::entitlement`), and a key that does not parse is a
1212        // startup error — a metered box that silently ran Free would be the
1213        // provider's revenue leaking with no line to say so.
1214        #[cfg(feature = "metered")]
1215        let entitlement = match &config.metered {
1216            Some(metered) => Some(
1217                crate::entitlement::EntitlementSlot::open(Arc::clone(&stores), metered)
1218                    .context("opening the entitlement slot")?,
1219            ),
1220            None => {
1221                tracing::warn!(
1222                    "metered build started without --monetize-pubkey: every namespace is Free \
1223                     and Entitlement.Set refuses every fact"
1224                );
1225                None
1226            }
1227        };
1228        // The band's tenants row reads the SAME slot `Admin.Stats` counts from
1229        // (one implementation). Filled here, before any door and outside the gRPC branch, so
1230        // a `--no-grpc` metered box still shows its tenants.
1231        // **This estate SELLS room** (the feed's `sells_room`, LIVE; gunnar-grpc `selling`):
1232        // ONE flag, read by the entitlement slot's push gate and the gRPC context alike.
1233        #[cfg(feature = "metered")]
1234        let sells_room = entitlement.as_ref().map(|slot| slot.sells_room_flag()).unwrap_or_else(|| Arc::new(std::sync::atomic::AtomicBool::new(false)));
1235        #[cfg(not(feature = "metered"))]
1236        let sells_room = Arc::new(std::sync::atomic::AtomicBool::new(false));
1237        {
1238            let flag = Arc::clone(&sells_room);
1239            nordisk_pairing::feedbus::on_published("shop room: a person's account with no fact", move |feed| {
1240                let sells_room = crate::feed::Fed::from_feed(feed).sells_room;
1241                if flag.swap(sells_room, std::sync::atomic::Ordering::Relaxed) != sells_room {
1242                    tracing::info!(target: "gunnar::audit", event = "shop_room", sells_room, "{}", if sells_room { "this estate's room comes from the shop: a person's own account with no fact holds no room until its fact lands" } else { "this estate's room does not come from a shop: an account with no fact is uncapped" });
1243                }
1244            });
1245        }
1246        #[cfg(feature = "metered")]
1247        if let Some(slot) = &entitlement {
1248            // A key the installer feeds later is applied to THIS slot in place
1249            // (owner 2026-09-25: avoid restarts; `feed::monetize_arrived`).
1250            let taker = Arc::clone(slot);
1251            crate::feed::on_monetize_key("entitlement slot", Box::new(move |k| taker.set_key(k).map(|_| ())));
1252            // ★ UW-6: the SITE's pay page, fed per estate (`refusal_link`), replaces the
1253            // constant medium's — now and on every feed after (LIVE).
1254            let pay = Arc::clone(slot);
1255            nordisk_pairing::feedbus::on_published("entitlement: the site's pay page", move |feed| {
1256                if let Some(url) = crate::feed::Fed::from_feed(feed).billing_url.as_deref() {
1257                    if let Err(why) = pay.set_billing_url(url) {
1258                        tracing::warn!(target: "gunnar::audit", event = "entitlement.billing_url_refused", reason = %why, "the fed pay page was refused; the one in force stays");
1259                    }
1260                }
1261            });
1262            let slot = Arc::clone(slot);
1263            config.tenants_view.fill(move || slot.counts());
1264        }
1265        // ── spools a crash left behind (cov-13) ──
1266        //
1267        // A pushed pack of 64 MiB or more is spooled to `incoming-*.pack` while
1268        // it arrives and removed by `Drop` when it lands or fails. A process
1269        // that died mid-receive ran no `Drop`, so the file is still here, full
1270        // size, under a name nothing reads — room the next push is refused for.
1271        // No door is open yet, so no live push owns one.
1272        let (mut swept, mut swept_bytes) = crate::push_space::sweep_spool_leftovers(stores.repos_root());
1273        // …and an LFS upload's `<txlog>/spool/*.part`, the same shape one door over.
1274        let (lfs, lfs_bytes) = crate::push_space::sweep_lfs_spool(&stores.txlog().dir().join(gunnar_core::txlog::SPOOL_DIR));
1275        swept += lfs;
1276        swept_bytes += lfs_bytes;
1277        if swept > 0 {
1278            tracing::warn!(
1279                files = swept,
1280                bytes = swept_bytes,
1281                "deleted {swept} pushed-pack spool file(s) a crash left behind ({})",
1282                gunnar_ssh::headroom::human(swept_bytes)
1283            );
1284        }
1285        // ── the disk-headroom gate: the community plan gate, every build ──
1286        //
1287        // Measured once here so the boot log states the floor IN FORCE beside
1288        // what is free right now; refused per request in the chain below and
1289        // in `Repos.Create`. A root that cannot be measured is logged as the
1290        // refusal it will be, not hidden until the first push finds it.
1291        //
1292        // ★ The filesystem's preallocation, measured once here (round 5.2): what a growing
1293        // spool-sized file occupies beyond its bytes on THIS data set (XFS doubles it; tmpfs and
1294        // ext4 add nothing), so every push reserves what it will really hold while it lands.
1295        let (fs_slack, unmeasured) = gunnar_ssh::space::FsSlack::of(stores.root());
1296        match &unmeasured {
1297            None => tracing::info!(root = %stores.root().display(), measured_permille = ?fs_slack.measured_permille, slack_permille = fs_slack.slack_permille, "{}", fs_slack.words(stores.root(), None)),
1298            Some(why) => tracing::warn!(root = %stores.root().display(), slack_permille = fs_slack.slack_permille, "{}", fs_slack.words(stores.root(), Some(why))),
1299        }
1300        let ledger = match &config.space_probe {
1301            None => gunnar_ssh::SpaceLedger::new(stores.root(), config.disk_floor),
1302            Some(probe) => gunnar_ssh::SpaceLedger::with_probe(stores.root(), config.disk_floor, Arc::clone(probe)),
1303        };
1304        let disk_gate = Arc::new(gunnar_ssh::DiskHeadroomGate::over(Arc::new(ledger.with_fs_slack(fs_slack))));
1305        match disk_gate.headroom() {
1306            Ok(room) => tracing::info!(
1307                root = %stores.root().display(),
1308                free = %gunnar_ssh::headroom::human(room.free),
1309                floor = %gunnar_ssh::headroom::human(room.floor),
1310                disk_floor = %config.disk_floor,
1311                has_room = room.has_room(),
1312                "disk headroom: pushes and Repos.Create are refused under the floor"
1313            ),
1314            Err(err) => tracing::error!(
1315                root = %stores.root().display(),
1316                %err,
1317                "disk headroom could not be measured; every push and Repos.Create will be \
1318                 refused until it can be"
1319            ),
1320        }
1321        // The front doors' control: the gate CHAIN, disk first, then the plan.
1322        let front_control = || {
1323            front_control(
1324                &stores,
1325                config.anonymous.clone(),
1326                Arc::clone(&disk_gate),
1327                #[cfg(feature = "metered")]
1328                entitlement.as_ref(),
1329            )
1330        };
1331        #[cfg(feature = "http")]
1332        let http_lfs: Arc<dyn gunnar_ssh::seam::LfsTransport> = Arc::clone(&transport) as _;
1333        // **Repository settings over the forge's door** (owner, 2026-10-14):
1334        // `gunnar-repo …` on this listener, answered by the control plane's own
1335        // `Repos` handlers once the control plane exists (set further down);
1336        // until then — or on `--no-grpc` — the verb says it is not answered here.
1337        let repo_door_ctx: Arc<std::sync::OnceLock<gunnar_grpc::service::ServiceContext>> =
1338            Arc::new(std::sync::OnceLock::new());
1339        let ssh = GunnarSsh::new(ssh_config, front_control(), transport)
1340            // The boot window (`crate::readiness`): while the start-up disk
1341            // test is saturating /data, a git transfer is refused with
1342            // `starting` and EX_TEMPFAIL rather than served an open that
1343            // fails and reads as a missing repository.
1344            .with_readiness(crate::readiness::flag())
1345            // The admission gate is the ONE door all three git fronts ask, so
1346            // it is where a refusal is charged to the tenant that met it. See
1347            // `GunnarSsh::with_flow`.
1348            .with_flow(Arc::clone(stores.flow()))
1349            .with_metrics(Arc::clone(&metrics));
1350        // **The sealed box's tunnel-address door** (T17): `gunnar-tunnel-address`
1351        // over this listener, server-wide Admin, answered by the SAME function
1352        // `Bootstrap.AssignTunnelAddress` and `Admin.SetTunnelAddress` call. The
1353        // listener already held the caller to server Admin, so `may_write`.
1354        #[cfg(feature = "wg-client")]
1355        let ssh = {
1356            let root = stores.root().to_path_buf();
1357            ssh.with_tunnel_address_door(Arc::new(move |address: &str| {
1358                crate::appliance::tunnel_address_answer(&root, address, true)
1359                    .map(|answer| crate::appliance::render_tunnel_answer(&answer))
1360                    .map_err(|err| format!("{err}"))
1361            }))
1362        };
1363        let ssh = {
1364            let cell = Arc::clone(&repo_door_ctx);
1365            ssh.with_repo_door(Arc::new(move |ask: gunnar_ssh::RepoAsk| {
1366                let cell = Arc::clone(&cell);
1367                Box::pin(async move {
1368                    let Some(ctx) = cell.get() else {
1369                        return Err("this server answers repository settings only on its control plane".to_owned());
1370                    };
1371                    let setting = match ask.action {
1372                        gunnar_ssh::RepoAction::Show => gunnar_grpc::repo_door::RepoSetting::Show,
1373                        gunnar_ssh::RepoAction::Visibility(public) => gunnar_grpc::repo_door::RepoSetting::Visibility(public),
1374                        gunnar_ssh::RepoAction::DefaultBranch(b) => gunnar_grpc::repo_door::RepoSetting::DefaultBranch(b),
1375                        gunnar_ssh::RepoAction::Create { sha256 } => gunnar_grpc::repo_door::RepoSetting::Create(sha256),
1376                    };
1377                    gunnar_grpc::repo_door::ask(ctx, &ask.principal, &ask.fingerprint, ask.repo.namespace(), ask.repo.name(), setting)
1378                        .await
1379                        .map(|repo| gunnar_grpc::repo_door::render(&repo))
1380                        .map_err(|status| status.message().to_owned())
1381                })
1382            }))
1383        };
1384        // **--wg-only** (owner 2026-10-04): a connection at the utility address
1385        // — where the control plane is bound — is refused before a byte; the
1386        // public's git clients and the tunnel are served as ever.
1387        let ssh = if config.wg_only && !config.no_grpc {
1388            let utility = resolved_grpc_bind.ip();
1389            tracing::warn!(%utility, "ssh: --wg-only — a connection at the utility address is refused; boxes speak over the tunnel");
1390            ssh.with_refused_local(Arc::new(move |local: std::net::IpAddr| local == utility))
1391        } else {
1392            ssh
1393        };
1394        let ssh = ssh
1395            .bind(russh_key)
1396            .await
1397            .with_context(|| format!("binding the SSH listener on {}", config.ssh_bind))?;
1398        // The anonymous setting is on the *bind* line rather than in a separate
1399        // one, so an operator reading a boot log sees what this listener will
1400        // serve strangers in the same place they see where it is listening.
1401        tracing::info!(
1402            addr = %ssh.local_addr(),
1403            anonymous_read = config.allow_anonymous,
1404            "gunnar ssh listener: git-upload-pack, git-receive-pack; publickey, plus \
1405             anonymous read of public repositories when enabled"
1406        );
1407
1408        // ── the smart-HTTP listener ────────────────────────────────────────
1409        //
1410        // The SAME `Dispatch` the SSH listener authorises with, the SAME
1411        // `WireTransport`, the SAME counters. That is the whole point of the
1412        // crate: a second transport, not a second server. If this ever needed
1413        // its own control plane or its own transport, HTTP and SSH would be
1414        // able to disagree about who may push.
1415        #[cfg(feature = "http")]
1416        let http = match config.http_bind {
1417            None => None,
1418            Some(bind) => {
1419                // The TLS identity, resolved BEFORE binding: a `--http-tls-*`
1420                // that cannot produce one must be "the server refused to
1421                // start", never a listener that quietly came up cleartext —
1422                // that silent fallback would be the whole defect the flag
1423                // exists to prevent.
1424                let tls = match &config.http_tls {
1425                    None => None,
1426                    Some(HttpTls::Identity(identity)) => Some(identity.clone()),
1427                    Some(HttpTls::SelfMinted) => {
1428                        let pki = stores.pki().context(
1429                            "--http-tls-self needs the secret store; no PKI is available",
1430                        )?;
1431                        let issuer = pki
1432                            .issuer()
1433                            .context("reading the issuer for --http-tls-self")?
1434                            .context(
1435                                "--http-tls-self needs an issuer and none exists; the first-start \
1436                                 mint above must have failed — its warning says why",
1437                            )?;
1438                        // The names a client may dial this listener by. rcgen
1439                        // types each SAN as IP or DNS on its own. Loopback is
1440                        // always present so `git clone https://127.0.0.1/…`
1441                        // works out of the box; a concrete bind address joins
1442                        // it. An operator with real DNS names brings their own
1443                        // certificate — that is what `--http-tls-cert` is for.
1444                        let mut hosts = vec!["localhost".to_owned(), "127.0.0.1".to_owned()];
1445                        let ip = bind.ip();
1446                        if !ip.is_unspecified() && !ip.is_loopback() {
1447                            hosts.push(ip.to_string());
1448                        }
1449                        let issued = pki
1450                            .issue_server_identity(&hosts, gunnar_core::DEFAULT_LEAF_DAYS)
1451                            .context("minting the smart-HTTP server certificate")?;
1452                        let key_pem = issued.key_pem.clone().context(
1453                            "the issuer minted a server certificate but returned no key",
1454                        )?;
1455                        tracing::info!(
1456                            fingerprint = %issued.fingerprint,
1457                            sans = ?hosts,
1458                            "smart-HTTP TLS: server certificate minted from this server's own \
1459                             issuer; clients pin the issuer (`gunnar issuer show --pem`)"
1460                        );
1461                        Some(gunnar_http::TlsIdentity {
1462                            // Leaf first, issuer after, so a pinning client can
1463                            // build the chain from the handshake alone.
1464                            cert_chain_pem: format!("{}{}", issued.cert_pem, issuer.cert_pem),
1465                            key_pem,
1466                        })
1467                    }
1468                };
1469                let http_config = gunnar_http::HttpConfig {
1470                    listen: bind,
1471                    // One field, both listeners. See `ServeConfig::allow_anonymous`.
1472                    allow_anonymous: config.allow_anonymous,
1473                    cleartext: config.http_cleartext,
1474                    tls,
1475                    ..gunnar_http::HttpConfig::default()
1476                };
1477                let bound = gunnar_http::GunnarHttp::new(
1478                    http_config,
1479                    gunnar_ssh::server::Dispatch::new(front_control()),
1480                    Arc::clone(&http_transport),
1481                )
1482                .with_metrics(Arc::clone(&metrics))
1483                // ── ONE admission gate for BOTH front doors ─────────────────
1484                //
1485                // The SSH listener's own gate, handed in rather than rebuilt,
1486                // so a git transfer over smart HTTP counts against the same
1487                // server-wide limit, the same per-principal share and the same
1488                // memory budget as one over SSH. Before this the HTTP front had
1489                // no gate at all (measured: 64 clients, 64 slots, nothing
1490                // refused); two independent gates would have been the next
1491                // worst thing, doubling the appliance's real ceiling in
1492                // silence. This is the same-writer fix the crate's own comment
1493                // above demands: "a second transport, not a second server."
1494                .with_admission(ssh.admission_gate())
1495                .with_lfs(Arc::clone(&http_lfs))
1496                // The registry rides the same listener as git, on the same
1497                // credentials: one port, one identity table, one place an
1498                // operator opens in a firewall.
1499                .with_registry(Arc::new(crate::registry::StoreRegistry::new(Arc::clone(
1500                    &stores,
1501                ))))
1502                .bind()
1503                .await
1504                .with_context(|| format!("binding the HTTP listener on {bind}"))?;
1505                let addr = bound.local_addr();
1506                let tls_on = bound.tls();
1507                tracing::info!(
1508                    %addr,
1509                    anonymous_read = config.allow_anonymous,
1510                    cleartext_credentials = ?config.http_cleartext,
1511                    tls = tls_on,
1512                    "gunnar smart-http listener: info/refs, git-upload-pack, git-receive-pack, \
1513                     info/lfs/objects (batch, get, put, verify)"
1514                );
1515                Some((tokio::spawn(bound.serve()), addr, tls_on))
1516            }
1517        };
1518
1519        // ── the scrape endpoint ────────────────────────────────────────────
1520        //
1521        // The SAME `Arc<ServerMetrics>` the heartbeat reads and both transports
1522        // write. Two readings of one set of counters, never two sets: a scrape
1523        // that disagreed with the heartbeat would leave an operator with no way
1524        // to decide which one to believe during the one hour they need either.
1525        //
1526        // On the GIT runtime and not the control plane's: the whole point of
1527        // this endpoint is that it still answers when the control plane is what
1528        // is wedged, and putting it on the pool that starves would have made it
1529        // useless in exactly that case.
1530        let scrape = match config.metrics_bind {
1531            None => None,
1532            Some(bind) => {
1533                let bound = crate::scrape::bind(bind, Arc::clone(&metrics))
1534                    .await
1535                    .with_context(|| format!("binding the metrics listener on {bind}"))?;
1536                let addr = bound.local_addr();
1537                Some((tokio::spawn(bound.serve()), addr))
1538            }
1539        };
1540
1541        // ── the gRPC control plane, on a runtime of its own ────────────────
1542        // ── replication slot: built EMPTY, and built EARLY ─────────────────
1543        //
1544        // Before the control plane, because the control plane takes a clone of
1545        // it: `Mirror.SetReplication` has to work on a box that has never had a
1546        // target and holds no repositories yet, which is every box on its first
1547        // boot. And it captures THIS runtime — the git one — because a blocking
1548        // send-pack belongs here and not on the control plane an operator is
1549        // using while the box is in trouble.
1550        #[cfg(feature = "replication")]
1551        let replication = crate::mirror::ReplicationSlot::new(
1552            Arc::clone(&stores),
1553            Arc::clone(&bus),
1554            tokio::runtime::Handle::current(),
1555        );
1556
1557        // ── the outbound webhook slot: same shape, same reason ─────────────
1558        //
1559        // Built empty and early, for the same reason the replication slot is:
1560        // the control plane takes a clone of it so `Webhooks.AddWebhook` works
1561        // on a box that has never had an endpoint. Its workers do async POSTs,
1562        // not blocking send-packs, but sharing the git runtime keeps them off
1563        // the control plane an operator uses while the box is in trouble.
1564        #[cfg(feature = "webhooks")]
1565        let webhook = crate::webhook::WebhookSlot::new(
1566            Arc::clone(&stores),
1567            Arc::clone(&bus),
1568            tokio::runtime::Handle::current(),
1569        );
1570
1571        // The control plane's copy of the replication view, taken while the
1572        // plane is built and filled below once the replicator exists.
1573        let mut control_view: Option<crate::replication_view::ReplicationView> = None;
1574        #[cfg(feature = "replication")]
1575        let mut control_for_repair: Option<Arc<dyn gunnar_grpc::ControlPlane>> = None;
1576        // The SAME grow machine `Admin.GrowStart` drives: a pulled `grow_go_ahead` (G16-d).
1577        #[cfg(feature = "replication")]
1578        let mut grow_for_repair: Option<Arc<crate::grow::GrowMachine>> = None;
1579        let (grpc, grpc_shutdown, grpc_endpoint, control_runtime) = if config.no_grpc {
1580            tracing::warn!(
1581                "the gRPC control plane is disabled; repositories, keys and grants can only be \
1582                 administered from this host's command line"
1583            );
1584            (None, None, None, ControlRuntime::default())
1585        } else {
1586            let workers = config
1587                .control_plane_workers
1588                .unwrap_or_else(control_plane_workers);
1589            // **The calls on one runtime, the connections on another**
1590            // (R5.1-G). The handler runtime is held by a guard from the moment
1591            // it exists, so the `?` below cannot drop a bare runtime here (see
1592            // `ControlRuntime`).
1593            let mut handler_runtime = ControlRuntime::new(
1594                tokio::runtime::Builder::new_multi_thread()
1595                    .worker_threads(workers)
1596                    .thread_name("gunnar-control-call")
1597                    .enable_all()
1598                    .build()
1599                    .context("building the control plane's handler runtime")?,
1600            );
1601            let handlers = handler_runtime
1602                .handle()
1603                .context("the control plane's handler runtime was gone as soon as it was built")?;
1604            let control_runtime = tokio::runtime::Builder::new_multi_thread()
1605                .worker_threads(CONTROL_CONNECTION_WORKERS)
1606                .thread_name("gunnar-control")
1607                .enable_all()
1608                .build()
1609                .context("building the control plane's runtime")?;
1610
1611            let grpc_bind = resolved_grpc_bind;
1612            let grpc_bind_device = config.grpc_bind_device.clone();
1613            let web_relying_parties = config
1614                .web_relying_parties
1615                .iter()
1616                .map(|party| party.parse::<gunnar_grpc::webauthn::RelyingParty>().map_err(|why| anyhow::anyhow!("--web-relying-party: {why}")))
1617                .collect::<Result<Vec<_>>>()?;
1618            let ssh_hint = ssh.local_addr().to_string();
1619            // **ONE twin heartbeat registry, shared by the gRPC plane that
1620            // RECORDS a twin's poll and the drain that READS what it applied.**
1621            //
1622            // It used to be created inside `ServiceContext` and owned only
1623            // there, so the grow world could not see it — and the drain proved
1624            // itself instead by pushing to the replication roster, which for a
1625            // twin can never succeed (a twin serves no git). Built here so both
1626            // halves hold the same `Arc`; two registries would be two answers
1627            // to "what has the twin applied", and the one in front of the
1628            // unmount would be the empty one.
1629            let heartbeats = Arc::new(gunnar_grpc::heartbeat::Registry::default());
1630            // ── the runtime data-set growth (`crate::grow`) ────────────────
1631            //
1632            // Over the ONE admission gate the fronts share (the drain pauses
1633            // it) and these stores (the identity handle, the close/reopen).
1634            // With `grow-runtime` the world is the box; without it the machine
1635            // still answers `GrowStatus` honestly and refuses `GrowStart` by
1636            // name.
1637            #[cfg(feature = "grow-runtime")]
1638            let grow_world: Arc<dyn crate::grow::World> = Arc::new(
1639                crate::grow::world::BoxWorld::new(ssh.admission_gate(), Arc::clone(&stores))
1640                    // So the drain can prove the standbys are caught up once
1641                    // the gate is shut and nothing is in flight — the only
1642                    // moment at which "everything is drained to the twin" is
1643                    // a true sentence. Without this the world falls back to
1644                    // `NoStandby` and a growth would proceed having proved
1645                    // nothing about a twin that exists.
1646                    .with_replication(Arc::clone(&replication))
1647                    // The twin's OWN reported position — the only thing on
1648                    // this box that says whether it holds the set.
1649                    .with_heartbeats(Arc::clone(&heartbeats)),
1650            );
1651            #[cfg(not(feature = "grow-runtime"))]
1652            let grow_world: Arc<dyn crate::grow::World> = Arc::new(crate::grow::world::NoEngine);
1653            // **The go-ahead policy is the metered half's, and only the metered
1654            // half's.** AUDITED 2026-09-18: this line read
1655            // `GrowMachine::new(grow_world)` on every build, which installs
1656            // `OperatorPolicy` — and that policy refuses every signer but
1657            // `operator` by name. monetize signs its go-ahead `signer:
1658            // "monetize"`, so its orchestrator reached `phase::STARTING`,
1659            // called `Admin.GrowStart` and was refused AFTER it had reserved
1660            // the spend: front-driven growth was dead at step 3 and had never
1661            // worked. `MonetizePolicy` verifies that signature under the key
1662            // the box already holds from `--monetize-pubkey` (the same one
1663            // `EntitlementSlot::open` above was given), and it takes an
1664            // `operator` go-ahead exactly as before. `cfg`, not a runtime
1665            // branch: a community binary has no monetize verifier in it at all.
1666            #[cfg(feature = "metered")]
1667            let grow = match &config.metered {
1668                Some(metered) => {
1669                    // Keyless when the key is fed and has not arrived: it is then
1670                    // applied here in place too (`feed::on_monetize_key`).
1671                    let policy = Arc::new(match &metered.monetize_pubkey {
1672                        Some(key) => crate::grow::MonetizePolicy::new(key).map_err(|e| anyhow::anyhow!("the growth go-ahead policy: {e}"))?,
1673                        None => crate::grow::MonetizePolicy::awaiting(),
1674                    });
1675                    let taker = Arc::clone(&policy);
1676                    crate::feed::on_monetize_key("growth go-ahead policy", Box::new(move |k| taker.set_key(k)));
1677                    crate::grow::GrowMachine::with_policy(grow_world, policy)
1678                }
1679                // A metered binary started without `--monetize-pubkey` serves
1680                // Free (the warning three hundred lines up); it has no key to
1681                // verify a `monetize` go-ahead with either, so it keeps the
1682                // operator door and refuses monetize by name rather than
1683                // pretending to a check it cannot make.
1684                None => crate::grow::GrowMachine::new(grow_world),
1685            };
1686            #[cfg(not(feature = "metered"))]
1687            let grow = crate::grow::GrowMachine::new(grow_world);
1688            #[cfg(feature = "replication")]
1689            {
1690                grow_for_repair = Some(Arc::clone(&grow));
1691            }
1692            let mut plane = CoreControlPlane::new(Arc::clone(&stores))
1693                // `Bootstrap.Restore`'s keys from the medium; the fed ones are read per ask.
1694                .with_restore_keys(restore_keys.clone())
1695                // `Repos.Create` asks the SAME gate the front doors ask (one implementation):
1696                // a disk that refuses a push refuses a new repository with the
1697                // same line.
1698                .with_headroom(Arc::clone(&disk_gate))
1699                .with_grow(grow)
1700                // The in-flight count `Mirror.FlushReplication` reports (T11).
1701                .with_admission(ssh.admission_gate())
1702                // The SAME bus the SSH front door publishes a push onto, so a
1703                // `MirrorSynced` and a `RefUpdated` reach one `Events.Watch`
1704                // stream. The plane publishes it from the mirror queue's worker
1705                // when a sync completes — `Mirror.Sync` itself only enqueues,
1706                // and an event announcing a fetch that has not happened would
1707                // be worse than no event.
1708                .with_bus(Arc::clone(&bus))
1709                // `Bootstrap.Status` names the role before the join (a twin has no banner).
1710                .with_twin_role(config.twin_role)
1711                // **`serving_git` is a reading of THIS socket.** Both addresses,
1712                // so the status door can say what was asked for and what was
1713                // taken: on a twin those differ, because the branch above binds
1714                // loopback:0 whatever `--ssh-bind` named, and a box that reports
1715                // `git serving` while its :2222 sends an RST is a health line
1716                // that cannot fail.
1717                .with_git_listener(crate::readiness::GitListener {
1718                    asked: config.ssh_bind,
1719                    bound: ssh.local_addr(),
1720                });
1721            // The plane publishes into the SAME view the band reads, so
1722            // `Admin.Stats` and the console can never disagree about whether a
1723            // standby is taking bytes (one implementation).
1724            // The WRITE side. `replication_view` just below is the READ side
1725            // one slot, two halves, and neither is the other's twin —
1726            // a `SetReplication` changes what is running, a `Stats` reads what
1727            // it did.
1728            #[cfg(feature = "replication")]
1729            {
1730                plane = plane.with_replication(Arc::clone(&replication));
1731            }
1732            #[cfg(feature = "webhooks")]
1733            {
1734                plane = plane.with_webhooks(Arc::clone(&webhook));
1735            }
1736            #[cfg(feature = "metered")]
1737            if let Some(slot) = &entitlement {
1738                plane = plane.with_entitlement(Arc::clone(slot));
1739            }
1740            let plane_view = plane.replication_view();
1741            if let Some(bytes) = config.max_object_bytes {
1742                plane = plane.with_max_object_bytes(bytes);
1743            }
1744            // The trust root, resolved BEFORE the listener is spawned, for the
1745            // reason `--http-tls-*` is resolved before its bind: a control
1746            // plane that was asked for client certificates and could not mint
1747            // its own identity must be a startup error naming the cause, never
1748            // a listener that came up accepting anyone.
1749            let grpc_trust = match config.grpc_tls {
1750                None => None,
1751                Some(GrpcTls::SelfMinted) => {
1752                    let pki = stores
1753                        .pki()
1754                        .context("--grpc-tls-self needs the secret store; no PKI is available")?;
1755                    let issuer = pki
1756                        .issuer()
1757                        .context("reading the issuer for --grpc-tls-self")?
1758                        .context(
1759                            "--grpc-tls-self needs an issuer and none exists; the first-start \
1760                             mint above must have failed — its warning says why",
1761                        )?;
1762                    // The same SAN reasoning as the HTTP listener's: loopback
1763                    // always, plus a concrete bind address when there is one.
1764                    let mut hosts = vec!["localhost".to_owned(), "127.0.0.1".to_owned()];
1765                    let ip = grpc_bind.ip();
1766                    if !ip.is_unspecified() && !ip.is_loopback() {
1767                        hosts.push(ip.to_string());
1768                    }
1769                    let issued = pki
1770                        .issue_server_identity(&hosts, gunnar_core::DEFAULT_LEAF_DAYS)
1771                        .context("minting the gRPC server certificate")?;
1772                    let key_pem = issued
1773                        .key_pem
1774                        .clone()
1775                        .context("the issuer minted a server certificate but returned no key")?;
1776                    tracing::info!(
1777                        fingerprint = %issued.fingerprint,
1778                        sans = ?hosts,
1779                        "gRPC control plane: mutual TLS on. Clients must present a certificate \
1780                         this server's issuer signed AND registered (`gunnar control bootstrap`, \
1781                         `gunnar key add`)"
1782                    );
1783                    Some(gunnar_grpc::Trust {
1784                        // The issuer is both halves here: the CA every client
1785                        // certificate must chain to, and the second link of
1786                        // the chain this listener presents. Beside it, the
1787                        // CENTRAL monetize's attach CA when this estate
1788                        // attached from another cloud (f-grpc-tls): the
1789                        // central dials in with a client identity under it.
1790                        #[cfg(feature = "wg-client")]
1791                        client_ca: crate::fed_principals::grpc_client_cas(&issuer.cert_pem, stores.root()).into_bytes(),
1792                        // No fed attach CA without the installer's feed (wg-client).
1793                        #[cfg(not(feature = "wg-client"))]
1794                        client_ca: issuer.cert_pem.clone().into_bytes(),
1795                        cert: format!("{}{}", issued.cert_pem, issuer.cert_pem).into_bytes(),
1796                        key: key_pem.into_bytes(),
1797                    })
1798                }
1799            };
1800            // Taken from the trust root itself rather than from
1801            // `config.grpc_tls`, so the field `Admin.Health` reports is the
1802            // one the listener is actually built with.
1803            let grpc_mutual_tls = grpc_trust.is_some();
1804
1805            // ── the MUTUAL REPLICATION LISTENER (lane T9) ──────────────────────
1806            //
1807            // The door a twin follows this box through. Resolved HERE, before
1808            // anything is spawned, for the reason the main trust root is: a box
1809            // that should serve its twin and cannot mint the identity to do it
1810            // must fail to start NAMING the cause, not come up with a twin that
1811            // retries into nothing for ever. `grpc_replication_bind` unset derives
1812            // it from the main bind (off loopback ⇒ port + 1), which is what lets
1813            // the one medium carry no flag.
1814            let replication_root = stores.root().to_path_buf();
1815            let replication = {
1816                // The ONE derivation (`client_signer::replication_address`), so the
1817                // operator side that dials it cannot drift from what is bound here.
1818                let derived = (!grpc_bind.ip().is_loopback() && grpc_bind.port() != 0)
1819                    .then(|| gunnar_grpc::client_signer::replication_address(&grpc_bind.to_string()).ok())
1820                    .flatten()
1821                    .and_then(|at| at.parse::<SocketAddr>().ok());
1822                // **Where it binds** (owner 2026-09-22, amended 2026-09-24): on the
1823                // derived (eth1) address for the process lifetime, and ALSO on
1824                // `wg0`'s address while the tunnel is up (`replication_door`); an
1825                // explicit `--grpc-replication-bind` is never widened.
1826                let explicit = config.grpc_replication_bind.is_some();
1827                match config.grpc_replication_bind.or(derived) {
1828                    None => None,
1829                    Some(base) => {
1830                        let bind = base;
1831                        let pki = stores.pki().with_context(|| {
1832                            format!("the mutual replication listener on {bind} needs the secret store; no PKI is available")
1833                        })?;
1834                        let issuer = pki.issuer().context("reading the issuer for the replication listener")?.with_context(|| {
1835                            format!(
1836                                "the mutual replication listener on {bind} needs this box's issuer and there is \
1837                                 none — the first-start mint above must have failed, and its warning says why. \
1838                                 Without it no twin of this box can ever follow it."
1839                            )
1840                        })?;
1841                        let mut hosts = vec![
1842                            gunnar_grpc::client_signer::REPLICATION_SERVER_NAME.to_owned(),
1843                            "localhost".to_owned(),
1844                            "127.0.0.1".to_owned(),
1845                        ];
1846                        for ip in [bind.ip(), base.ip()] {
1847                            if !ip.is_unspecified() && !ip.is_loopback() && !hosts.contains(&ip.to_string()) {
1848                                hosts.push(ip.to_string());
1849                            }
1850                        }
1851                        // Minted at EVERY start, so a restart is a renewal and a
1852                        // lapse needs a year of uninterrupted uptime.
1853                        let issued = pki
1854                            .issue_server_identity(&hosts, gunnar_core::DEFAULT_LEAF_DAYS)
1855                            .context("minting the replication listener's certificate")?;
1856                        let key_pem = issued
1857                            .key_pem
1858                            .clone()
1859                            .context("the issuer minted the replication certificate but returned no key")?;
1860                        Some((
1861                            base,
1862                            explicit,
1863                            bind,
1864                            gunnar_grpc::Trust {
1865                                client_ca: issuer.cert_pem.clone().into_bytes(),
1866                                cert: format!("{}{}", issued.cert_pem, issuer.cert_pem).into_bytes(),
1867                                key: key_pem.into_bytes(),
1868                            },
1869                        ))
1870                    }
1871                }
1872            };
1873
1874            let control = Arc::new(plane);
1875            control_view = Some(plane_view);
1876            #[cfg(feature = "replication")]
1877            {
1878                control_for_repair = Some(control.clone());
1879            }
1880            let bus_for_grpc = Arc::clone(&bus);
1881            // ── ONE admission gate on ALL THREE front doors ────────────────
1882            //
1883            // `Repos.ArchiveOut` streams a whole repository's stored bytes down
1884            // the control-plane channel — a transfer in everything but name — so
1885            // it takes a permit from the SAME `Arc<Admission>` the SSH and HTTP
1886            // git fronts hold (`ssh.admission_gate()`), not a second gate (one
1887            // implementation). The *cheap* control RPCs get no gate on purpose: the control
1888            // plane runs on its own runtime, so their walks starve
1889            // nothing but themselves. Captured here and moved into the control
1890            // runtime's spawn below.
1891            let grpc_transfer_gate =
1892                crate::grpc_gate::control_transfer_gate(ssh.admission_gate());
1893            let browse_flag = stores.browse();
1894            // ── the durable audit trail (GUN-044) ──────────────────────────
1895            //
1896            // Opened HERE, on the startup path, because `AuditChain::open`
1897            // verifies the existing chain and an operator has to be told about
1898            // a broken one at the moment the server starts — not the first time
1899            // somebody runs a verification months later.
1900            //
1901            // A chain that will not open does NOT stop the server. The control
1902            // plane still authenticates, still authorises and still writes the
1903            // `tracing` record it always did; what it loses is the durable
1904            // copy, and it says so at `error!` with the reason. Refusing to
1905            // serve would turn a full disk — or a chain somebody has already
1906            // tampered with — into an outage, which hands whoever tampered
1907            // with it exactly what they wanted.
1908            let audit_ledger = {
1909                // **Off the stripe.** The trail records who changed what on
1910                // this box, which is exactly the question asked the morning
1911                // after the four striped data disks have gone — so a copy that
1912                // dies with them answers nobody. `ServerStores::audit_path`
1913                // adopts an existing chain from the control directory once and
1914                // falls back to it unchanged if the slow disk will not take it.
1915                let path = stores.audit_path();
1916                // ── and it must SURVIVE A RESTORE (lane T11, 2026-09-21) ───
1917                //
1918                // D6: `log/` was a per-box path, so the twin never held the
1919                // trail and `twin replay` brought a box back with no audit
1920                // history at all — silently, reporting success. A system whose
1921                // audit trail is destroyed by its own recovery procedure
1922                // cannot answer the only question that will be asked.
1923                //
1924                // So the primary's chain is opened FRAMED: every entry is an
1925                // `Append` transaction, the twin holds it, and a restored box
1926                // continues the dead primary's chain from its own tip.
1927                //
1928                // A twin — and a box mid-restore — originates nothing, so it
1929                // gets an ordinary chain at its OWN per-box path
1930                // (`audit_path` decides the name), and this branch does not
1931                // even try to frame it.
1932                let originates = !stores.is_twin() && !crate::twin::is_restoring(stores.root());
1933                let opened = if originates {
1934                    match gunnar_core::AuditChain::open_framed(&path) {
1935                        Ok(chain) => Ok(chain),
1936                        // **Never silent.** An unframable chain is the D6 bug
1937                        // coming back, so it is said in the words an operator
1938                        // needs, and the server still writes a local trail.
1939                        Err(err @ gunnar_core::AuditError::Unframed { .. }) => {
1940                            tracing::error!(
1941                                target: gunnar_grpc::AUDIT_TARGET,
1942                                path = %path.display(),
1943                                error = %err,
1944                                "this box's audit trail is NOT replicated: it will be written \
1945                                 here and it will NOT survive a restore from the twin. Every \
1946                                 other class of state comes back; this one will not."
1947                            );
1948                            gunnar_core::AuditChain::open(&path)
1949                        }
1950                        Err(err) => Err(err),
1951                    }
1952                } else {
1953                    gunnar_core::AuditChain::open(&path)
1954                };
1955                match opened {
1956                    Ok(chain) => Some(crate::grpc_gate::control_audit_ledger(Arc::new(chain))),
1957                    Err(err) => {
1958                        tracing::error!(
1959                            target: gunnar_grpc::AUDIT_TARGET,
1960                            path = %path.display(),
1961                            error = %err,
1962                            "the control-plane audit chain could not be opened; this server \
1963                             will log its decisions and will NOT write them to a trail. If the \
1964                             chain is reported BROKEN, the file has been edited or truncated \
1965                             since gunnar wrote it."
1966                        );
1967                        None
1968                    }
1969                }
1970            };
1971            let (tx, rx) = oneshot::channel();
1972            // The listener is bound INSIDE the control runtime. A tokio socket
1973            // registers with the I/O driver of the runtime that created it, so
1974            // one bound out here would keep the git runtime's driver in the
1975            // control plane's critical path, which is the exact coupling this
1976            // change exists to remove.
1977            let (bound_tx, bound_rx) = oneshot::channel::<Result<(SocketAddr, bool)>>();
1978            let sweep_stores = Arc::clone(&stores);
1979            let activity_stores = Arc::clone(&stores);
1980            let wg_only = config.wg_only;
1981            let join = control_runtime.spawn(async move {
1982                // Bound WITH PATIENCE: a control plane on a tailnet or VPN
1983                // address is asked for before that interface exists on a cold
1984                // boot (builder, every boot until 2026-09-10: six `EADDRNOTAVAIL`
1985                // exits and six blind systemd restarts before the seventh try
1986                // found the address). The wait is bounded and only for that
1987                // one errno; everything else still fails at once.
1988                let listener = match bind_when_the_address_arrives(
1989                    || bind_grpc_listener(grpc_bind, grpc_bind_device.as_deref()),
1990                    GRPC_BIND_PATIENCE,
1991                    GRPC_BIND_RETRY_EVERY,
1992                )
1993                .await
1994                .0
1995                .with_context(|| match &grpc_bind_device {
1996                    Some(dev) => format!("binding the gRPC listener on {grpc_bind} (device {dev})"),
1997                    None => format!("binding the gRPC listener on {grpc_bind}"),
1998                }) {
1999                    Ok(listener) => listener,
2000                    Err(err) => {
2001                        // Report the bind failure to `start`, which is the only
2002                        // place that can turn it into a startup error. Swallowing
2003                        // it here would leave `gunnar serve` announcing a control
2004                        // plane that never bound.
2005                        let _ = bound_tx.send(Err(err));
2006                        return Ok(());
2007                    }
2008                };
2009                let addr = match listener
2010                    .local_addr()
2011                    .context("reading the gRPC local address")
2012                {
2013                    Ok(addr) => addr,
2014                    Err(err) => {
2015                        let _ = bound_tx.send(Err(err));
2016                        return Ok(());
2017                    }
2018                };
2019                let server_config = ServerConfig::default()
2020                    .with_bind(addr)
2021                    .with_ssh_bind_hint(ssh_hint)
2022                    .with_web_relying_parties(web_relying_parties)
2023                    // Reported from the SAME value that decides whether the
2024                    // listener is built with a trust root, three lines below
2025                    // (`router_with_trust(…, grpc_trust.as_ref())`). Derived
2026                    // from anything else it would be a second opinion about
2027                    // whether the door is locked, and `Admin.Health`'s job
2028                    // here is to be the answer rather than to remember one.
2029                    .with_mutual_tls(grpc_mutual_tls);
2030                // Every start, on purpose: a hole nobody is reminded of is a hole
2031                // nobody fixes.
2032                gunnar_grpc::warn_authentication_disabled(&server_config);
2033                // Reported out rather than re-derived by the caller. `serve`
2034                // prints this on stdout, and a second reader of "is auth on"
2035                // is a second thing that can be wrong: the line it replaced
2036                // said `UNAUTHENTICATED in v1` unconditionally, and had
2037                // gone stale against a control plane that authenticates.
2038                let authenticated = server_config.authentication_enabled();
2039                let ctx = ServiceContext::new(control, bus_for_grpc, server_config)
2040                    // The one "this estate sells room" flag the push gate reads too.
2041                    .with_sells_room(Arc::clone(&sells_room))
2042                    // Every call on the handler runtime, the connections on
2043                    // this one (R5.1-G): no slow call can hold the worker that
2044                    // answers a client's keepalive PING.
2045                    .with_handler_runtime(handlers)
2046                    // The transfer-shaped RPC's permit, from the git
2047                    // fronts' own gate.
2048                    .with_transfer_gate(grpc_transfer_gate)
2049                    // The browse replica: the browse flag the mutator refusal reads —
2050                    // the same `Arc` the replication slot flips.
2051                    .with_browse_flag(browse_flag)
2052                    // The SAME registry the drain reads (see where it is built).
2053                    .with_heartbeats(Arc::clone(&heartbeats));
2054                // The hash-chained trail, when there is one; `tracing` alone
2055                // when there is not. Either way the gate's decisions also
2056                // stamp who last changed something (2026-10-21, the admin's
2057                // user list): `grpc_gate::activity_ledger`.
2058                let ctx = ctx.with_audit_ledger(crate::grpc_gate::activity_ledger(
2059                    audit_ledger,
2060                    Arc::clone(activity_stores.activity()),
2061                ));
2062                // The forge door's `gunnar-repo` verb answers from here on.
2063                let _ = repo_door_ctx.set(ctx.clone());
2064                // **Company SSO's network**: the one way gunnar reaches an
2065                // account's identity provider. `GUNNAR_SSO_ALLOW_LOOPBACK_HTTP=1`
2066                // is the operator's test door (an IdP on this box's loopback,
2067                // over http) and nothing else.
2068                let sso_loopback = std::env::var("GUNNAR_SSO_ALLOW_LOOPBACK_HTTP").is_ok_and(|v| v.trim() == "1");
2069                if sso_loopback {
2070                    tracing::warn!("GUNNAR_SSO_ALLOW_LOOPBACK_HTTP=1: an identity provider on this box's loopback is reachable over http (a test door)");
2071                }
2072                ctx.sso.set_allow_loopback_http(sso_loopback);
2073                ctx.sso.set_egress(std::sync::Arc::new(crate::sso_egress::UreqEgress::with_nets(
2074                    sso_loopback,
2075                    crate::sso_egress::system_lookup(),
2076                    ctx.sso.private_nets_handle(),
2077                )));
2078                // **The operator's internal networks a company IdP may live
2079                // on** (owner 2026-10-06): the installer's feed, applied now and
2080                // on every feed after (LIVE); a list gunnar refuses is said and
2081                // applied as none — today's guard.
2082                {
2083                    let sso = std::sync::Arc::clone(&ctx.sso);
2084                    nordisk_pairing::feedbus::on_published(
2085                        "sso: the operator's identity-provider networks",
2086                        move |feed| {
2087                            let nets = match crate::feed::sso_private_nets(Some(&crate::feed::Fed::from_feed(feed))) {
2088                                Ok(nets) => nets,
2089                                Err(why) => {
2090                                    tracing::warn!(target: "gunnar::audit", event = "sso.private_nets_refused", reason = %why, "the fed identity-provider networks were refused; none are admitted");
2091                                    gunnar_grpc::sso::PrivateNets::default()
2092                                }
2093                            };
2094                            if nets != sso.private_nets() {
2095                                tracing::info!(target: "gunnar::audit", event = "sso.private_nets", nets = %nets, "identity providers on the operator's internal networks: {}", if nets.is_empty() { "none (public addresses only)".to_owned() } else { nets.to_string() });
2096                                sso.set_private_nets(nets);
2097                            }
2098                        },
2099                    );
2100                }
2101                // **The transaction log's default retention** (h-txlog-2x): a PRIMARY
2102                // retains its log behind its slowest REPORTING twin, minus a window, every
2103                // ten minutes — never with no twin, never past a silent or unheard one, and
2104                // never on a twin (its log is its only copy; the pass says so and does
2105                // nothing). `GUNNAR_TXLOG_RETAIN=off` turns it off.
2106                tokio::spawn(gunnar_grpc::retention::run(ctx.clone()));
2107                // **The account audit logs' retention** (2026-10-05): a year by
2108                // default, swept every six hours on a primary.
2109                tokio::spawn(crate::account_audit_sweep::run(sweep_stores));
2110                // The replication listener: bound BEFORE the address is reported,
2111                // so a port that will not bind is a startup error and not a twin
2112                // that retries into a closed door. The same context — the same
2113                // gate, grants and audit trail — on a door that demands a
2114                // certificate at the handshake.
2115                // One stop for the replication door, whichever address it is on
2116                // (it may rebind when the tunnel comes up at runtime).
2117                let (replication_stop_tx, replication_stop_rx) = tokio::sync::watch::channel(false);
2118                match replication {
2119                    Some((base, explicit, bind, trust)) => {
2120                        let listener = match tokio::net::TcpListener::bind(bind).await {
2121                            Ok(listener) => listener,
2122                            Err(err) => {
2123                                let _ = bound_tx.send(Err(anyhow::Error::new(err).context(format!(
2124                                    "binding the mutual replication listener on {bind} (the door this box's twin follows it through)"
2125                                ))));
2126                                return Ok(());
2127                            }
2128                        };
2129                        let bound = listener.local_addr().unwrap_or(base);
2130                        let recorded = if wg_only { record_replication_door_wg_only(&replication_root, bound.port(), None) } else { record_replication_door(&replication_root, bound, None) };
2131                        if let Err(err) = recorded {
2132                            let _ = bound_tx.send(Err(err));
2133                            return Ok(());
2134                        }
2135                        // Built once up front so a broken trust is a STARTUP error;
2136                        // every rebind builds its own from the same trust.
2137                        if let Err(err) = gunnar_grpc::router_with_trust(ctx.clone(), grpc_request_id, Some(&trust)) {
2138                            let _ = bound_tx.send(Err(err.context("configuring the mutual replication listener")));
2139                            return Ok(());
2140                        }
2141                        tracing::info!(
2142                            %bind, suite = gunnar_grpc::preferred_bulk_suite(),
2143                            "mutual replication listener up: TLS 1.3, a client certificate from this box's issuer required"
2144                        );
2145                        tokio::spawn(replication_door(
2146                            listener,
2147                            base,
2148                            explicit,
2149                            wg_only,
2150                            ctx.clone(),
2151                            grpc_request_id,
2152                            trust,
2153                            replication_root.clone(),
2154                            replication_stop_rx,
2155                        ));
2156                    }
2157                    None => {
2158                        if let Err(err) = crate::twin_tls::record_replication_port(&replication_root, None) {
2159                            let _ = bound_tx.send(Err(err));
2160                            return Ok(());
2161                        }
2162                    }
2163                }
2164                if bound_tx.send(Ok((addr, authenticated))).is_err() {
2165                    // `start` gave up on us; do not leave a listener running.
2166                    return Ok(());
2167                }
2168                if wg_only {
2169                    // **--wg-only** (owner 2026-10-04): the bound — utility —
2170                    // listener serves nothing; the control plane answers on the
2171                    // tunnel's address only, following it (`control_doors`).
2172                    gunnar_grpc::router_with_trust(ctx.clone(), grpc_request_id, grpc_trust.as_ref())
2173                        .context("configuring mutual TLS on the gRPC control plane")?;
2174                    let (control_stop_tx, control_stop_rx) = tokio::sync::watch::channel(false);
2175                    let serve_control = move |l: tokio::net::TcpListener, mut stop: tokio::sync::watch::Receiver<bool>| {
2176                        let router = gunnar_grpc::router_with_trust(ctx.clone(), grpc_request_id, grpc_trust.as_ref());
2177                        async move {
2178                            let router = match router {
2179                                Ok(r) => r,
2180                                Err(err) => {
2181                                    tracing::error!(%err, "the control plane's tunnel door could not be configured");
2182                                    return;
2183                                }
2184                            };
2185                            let at = l.local_addr().map(|a| a.to_string()).unwrap_or_default();
2186                            if let Err(err) = router
2187                                .serve_with_incoming_shutdown(tokio_stream::wrappers::TcpListenerStream::new(l), async move {
2188                                    let _ = stop.wait_for(|s| *s).await;
2189                                })
2190                                .await
2191                            {
2192                                tracing::error!(%err, %at, "a control plane door stopped");
2193                            }
2194                        }
2195                    };
2196                    let doors = tokio::spawn(control_doors(listener, addr, true, crate::tunnel_addr::subscribe(), control_stop_rx, serve_control));
2197                    let _ = rx.await;
2198                    // One stop for every door.
2199                    let _ = replication_stop_tx.send(true);
2200                    let _ = control_stop_tx.send(true);
2201                    let _ = doors.await;
2202                    Ok(())
2203                } else {
2204                    gunnar_grpc::router_with_trust(ctx, grpc_request_id, grpc_trust.as_ref())
2205                        .context("configuring mutual TLS on the gRPC control plane")?
2206                        .serve_with_incoming_shutdown(
2207                            tokio_stream::wrappers::TcpListenerStream::new(listener),
2208                            async {
2209                                let _ = rx.await;
2210                                // One stop for both doors.
2211                                let _ = replication_stop_tx.send(true);
2212                            },
2213                        )
2214                        .await
2215                        .context("the gRPC control plane stopped")
2216                }
2217            });
2218
2219            let (addr, grpc_authenticated) = match bound_rx.await {
2220                Ok(Ok(pair)) => pair,
2221                Ok(Err(err)) => {
2222                    control_runtime.shutdown_background();
2223                    return Err(err);
2224                }
2225                Err(_) => {
2226                    control_runtime.shutdown_background();
2227                    bail!(
2228                        "the gRPC control plane task ended before it reported an address; the \
2229                         listener on {grpc_bind} never came up"
2230                    );
2231                }
2232            };
2233            tracing::info!(
2234                %addr,
2235                control_plane_workers = workers,
2236                control_connection_workers = CONTROL_CONNECTION_WORKERS,
2237                "gunnar grpc control plane listening on its own runtime (a control-plane \
2238                 stall cannot reach the git listener, and its calls run on a handler runtime \
2239                 that cannot hold the connections)"
2240            );
2241            let mut held = ControlRuntime::new(control_runtime);
2242            held.hold(&mut handler_runtime);
2243            (
2244                Some(join),
2245                Some(tx),
2246                Some((addr, grpc_authenticated)),
2247                held,
2248            )
2249        };
2250
2251        // ── the log level, changeable from here on ─────────────────────────
2252        //
2253        // Started here rather than in `main` because it needs a runtime, and
2254        // deliberately NOT held on `Server`: the task owns two signal streams
2255        // and nothing else, and a level-control task that stopped with the
2256        // server would be one more thing to get wrong at shutdown.
2257        //
2258        // It also has to exist for a NEGATIVE reason. The default disposition
2259        // of both `SIGUSR1` and `SIGUSR2` is to TERMINATE the process, so
2260        // before this an operator who reached for the usual signal killed the
2261        // server they were debugging.
2262        gunnar_common::logging::spawn_signal_control();
2263
2264        // ── the counter heartbeat ──────────────────────────────────────────
2265        let heartbeat = config.metrics_interval.map(|interval| {
2266            let metrics = Arc::clone(&metrics);
2267            tokio::spawn(async move { heartbeat(metrics, interval).await })
2268        });
2269
2270        // ── the runner, on the same bus every push publishes on ────────────
2271        //
2272        // Subscribed **before** the listeners bind, so a push that lands in the
2273        // first millisecond is seen. Subscribing after would lose it silently,
2274        // which is the shape of bug that shows up once a month and is blamed on
2275        // the network.
2276        //
2277        // Its own OS thread rather than a tokio task: a build is a blocking
2278        // child process that can run for minutes, and putting it on a runtime
2279        // worker would starve whatever else that runtime is for.
2280        let runner = match config.runner.clone() {
2281            None => None,
2282            Some(runner_config) => {
2283                if let Err(err) = crate::sandbox::available() {
2284                    if !runner_config.allow_network {
2285                        bail!(
2286                            "the runner was asked for hermetic builds and this kernel cannot \
2287                             give it a sandbox: {}\n\n\
2288                             Refusing to start rather than building with the network up and \
2289                             signing records that say otherwise. Pass --runner-allow-network to \
2290                             build anyway; every record will say the network was up.",
2291                            err.explain()
2292                        );
2293                    }
2294                }
2295                let stores = Arc::clone(&stores);
2296                let bus = Arc::clone(&bus);
2297                tracing::info!(
2298                    workspace = %runner_config.workspace.display(),
2299                    builder = %runner_config.builder,
2300                    hermetic = !runner_config.allow_network,
2301                    "the build runner is watching this server's pushes"
2302                );
2303                Some(std::thread::spawn(move || {
2304                    let _ = crate::runner::watch(&stores, &bus, &runner_config, |outcome| {
2305                        match outcome {
2306                            crate::runner::Watched::Built(built) => tracing::info!(
2307                                target: "gunnar::runner",
2308                                event = "runner.built",
2309                                repo = %built.record.source_repo,
2310                                commit = %built.record.source_commit,
2311                                recipe = %built.record.recipe,
2312                                artifacts = built.record.subjects.len(),
2313                                "a push was built and attested"
2314                            ),
2315                            crate::runner::Watched::Failed { repo, commit, why } => {
2316                                // At `error`, and the watch continues: one
2317                                // repository's broken recipe must not stop
2318                                // every other repository's builds.
2319                                tracing::error!(
2320                                    target: "gunnar::runner",
2321                                    event = "runner.failed",
2322                                    %repo, %commit, %why,
2323                                    "a push could not be built; the runner is still watching"
2324                                )
2325                            }
2326                            crate::runner::Watched::Skipped { repo, r#ref, why } => {
2327                                tracing::debug!(
2328                                    target: "gunnar::runner",
2329                                    event = "runner.skipped",
2330                                    %repo, r#ref = %r#ref, %why,
2331                                    "a ref moved and was not built"
2332                                )
2333                            }
2334                        }
2335                    });
2336                }))
2337            }
2338        };
2339        // Held so the thread is not detached from the server's lifetime; the
2340        // watch ends when the bus's last sender goes.
2341        let _runner = runner;
2342
2343        // ── replication, a SUBSCRIBER and nothing else ─────────────────────
2344        //
2345        // Started last, and started on the git runtime deliberately: the work
2346        // it does is a git push over SSH, and the blocking part of it goes to
2347        // the blocking pool. Nothing above this line knows it exists, which is
2348        // the property that makes "replication can never fail a push" true by
2349        // construction rather than by care.
2350        #[cfg(feature = "replication")]
2351        {
2352            use crate::mirror::ReplicationConfig;
2353            let replication_config = match config.replication.clone() {
2354                Some(explicit) => explicit,
2355                None => ReplicationConfig::load(stores.root())
2356                    .context("reading the replication configuration")?,
2357            };
2358            // An empty target list leaves the slot empty, which is still replication's
2359            // "a server that replicates nowhere pays nothing": no replicator, no
2360            // subscriber, no task. What it no longer means is that the operator
2361            // has no way to add one.
2362            replication
2363                .apply(replication_config)
2364                .context("starting replication")?;
2365        }
2366
2367        // ── I11's passive heartbeat, if this box was asked for one ─────────
2368        //
2369        // Started AFTER the slot has its configuration, because the task's
2370        // first act is to read the role out of it: a watch spawned before
2371        // `apply` would read the pre-boot file and could leave immediately on a
2372        // box that is about to become a standby.
2373        //
2374        // On the GIT runtime, with the replicator, and for the same reason: the
2375        // probe is a blocking-shaped network wait, and the control plane is the
2376        // surface an operator uses while a box is in trouble.
2377        #[cfg(feature = "replication")]
2378        let standby_watch = config.standby_watch.map(|watch| {
2379            tracing::info!(
2380                target: "gunnar::replication",
2381                primary = %watch.primary,
2382                probe_interval_ms = watch.probe_interval.as_millis() as u64,
2383                promote_after = watch.promote_after,
2384                earliest_takeover_ms = watch.earliest_takeover().as_millis() as u64,
2385                "watching the primary; this box takes over by itself if it stops answering"
2386            );
2387            let slot = Arc::clone(&replication);
2388            tokio::spawn(async move { crate::standby_watch::watch(slot, watch).await })
2389        });
2390
2391        // ── 5.4: the boot check, then the pull channel ─────────────────────
2392        //
2393        // After the control plane listens: the boot check reads this box's own
2394        // `Bootstrap.Status`, and a recharge into this box goes through it.
2395        #[cfg(feature = "replication")]
2396        let repair = match (config.repair, grpc_endpoint) {
2397            (Some(cfg), Some((bound, _))) => {
2398                let own = crate::repair::own_addr(bound);
2399                let mut entitlements = crate::repair::Entitlements::of(Arc::clone(&stores));
2400                if let Some(control) = control_for_repair.clone() {
2401                    entitlements = entitlements.with_control(control);
2402                }
2403                #[cfg(feature = "metered")]
2404                let mut entitlements = entitlements.with_slot(entitlement.clone());
2405                if let Some(grow) = grow_for_repair.clone() {
2406                    entitlements = entitlements.with_grow(crate::paid_growth::PaidGrowth::new(grow));
2407                }
2408                // The environment's relay; else (a SOLD estate's main, P1) the one the shop FED it,
2409                // read at each mail — not ready until the feed names it, so a resend is refused
2410                // by name before anything is minted.
2411                let postman: Option<Arc<dyn crate::postman::Postman>> = match crate::postman::Smtp::from_env() {
2412                    Ok(Some(smtp)) => Some(Arc::new(smtp)),
2413                    Ok(None) => Some(Arc::new(crate::postman::FedRelay { fed: crate::feed::Fed::current })),
2414                    Err(why) => {
2415                        tracing::warn!(target: crate::repair::TARGET, "no mail relay: a sign_in_again order is refused by name ({why})");
2416                        None
2417                    }
2418                };
2419                let entitlements = entitlements.with_twin(cfg.twin.clone()).with_postman(postman);
2420                let stores = Arc::clone(&stores);
2421                crate::repair::arm(cfg.clone(), own.clone(), tokio::runtime::Handle::current());
2422                Some(tokio::spawn(async move {
2423                    crate::repair::boot(Arc::clone(&stores), cfg.clone(), own.clone()).await;
2424                    if let Some(fleet) = crate::repair::fleet_when_fed(cfg.fleet.clone(), crate::repair::FED_EVERY).await {
2425                        let estate = crate::repair::ServerEstate::new(stores.root(), &cfg, own.clone())
2426                            .map_err(|why| tracing::warn!(target: crate::repair::TARGET, "the pull channel runs without a repair key: every order is refused by name ({why})"))
2427                            .ok();
2428                        let (_keep, stop) = tokio::sync::watch::channel(false);
2429                        crate::repair::pull_loop(stores, fleet, estate, entitlements, own, stop).await;
2430                    }
2431                }))
2432            }
2433            (Some(_), None) => {
2434                tracing::warn!(target: "gunnar::repair", "the boot check and the pull channel need the control plane, which is off");
2435                None
2436            }
2437            (None, _) => None,
2438        };
2439
2440        // Outbound webhooks: load webhooks.json and start delivering. An empty file
2441        // (or none) leaves the slot empty — no subscriber, no task — the "a
2442        // server with no webhooks pays nothing" property; a malformed file is a
2443        // hard error here, so a typo is caught at boot and not per delivery.
2444        #[cfg(feature = "webhooks")]
2445        {
2446            let webhook_config = crate::webhook::WebhookConfig::load(stores.root())
2447                .context("reading the webhook configuration")?;
2448            webhook
2449                .apply(webhook_config)
2450                .context("starting outbound webhook delivery")?;
2451        }
2452
2453        // ── publish the counters, so something finally READS them ──────────
2454        //
2455        // One closure, two readers: `config.replication_view` is the console
2456        // band's and `control_view` is `Admin.Stats`'s. Before this the
2457        // counters existed and nothing looked at them, which is how every
2458        // configured standby receiving NOTHING went unnoticed for weeks.
2459        //
2460        // The closure reads the slot on EVERY call rather than closing over one
2461        // `Arc<Replicator>`. That is what keeps the band and `Admin.Stats`
2462        // honest after a live `SetReplication`: a captured replicator would go
2463        // on reporting the standby that was just removed, and report nothing at
2464        // all about the one that was just added. With no target configured the
2465        // slot is empty and the answer is `ReplicationReport::default()` —
2466        // `configured: false`, which is a fact rather than an absence.
2467        #[cfg(feature = "replication")]
2468        for view in [Some(config.replication_view.clone()), control_view.clone()]
2469            .into_iter()
2470            .flatten()
2471        {
2472            let slot = Arc::clone(&replication);
2473            view.fill(move || {
2474                slot.replicator()
2475                    .as_deref()
2476                    .map(|replicator| {
2477                        // The cheap report, plus the ref number PEEKED from the
2478                        // last on-demand walk — never a walk of its own. This
2479                        // closure runs on every `Admin.Stats` and every band
2480                        // frame, so a reader that walked would be the cold-status
2481                        // "re-open every store every 60 s from a polling
2482                        // caller". `ref_coverage_cached` opens nothing; the
2483                        // number is whatever the most recent `--refs` warmed,
2484                        // and zeros until the first one.
2485                        let mut report = crate::replication_view::report(replicator);
2486                        report.refs = replicator.ref_coverage_cached();
2487                        report
2488                    })
2489                    .unwrap_or_default()
2490            });
2491        }
2492        let _ = &control_view;
2493
2494        Ok(Server {
2495            ssh: Some(ssh),
2496            grpc,
2497            grpc_shutdown,
2498            grpc_endpoint,
2499            control_runtime,
2500            stores,
2501            bootstrap_window_open,
2502            host_key_fingerprint,
2503            metrics,
2504            heartbeat,
2505            #[cfg(feature = "replication")]
2506            standby_watch,
2507            #[cfg(feature = "replication")]
2508            repair,
2509            bus,
2510            #[cfg(feature = "http")]
2511            http,
2512            scrape,
2513            #[cfg(feature = "replication")]
2514            replication,
2515            #[cfg(feature = "webhooks")]
2516            webhook,
2517        })
2518    }
2519
2520    /// The event bus.
2521    ///
2522    /// The same object `Events.Watch` streams from, exposed here so an
2523    /// in-process caller (the replicator, and the tests that assert what it
2524    /// publishes) can subscribe without a gRPC listener and a credential in
2525    /// between.
2526    pub fn bus(&self) -> &Arc<EventBus> {
2527        &self.bus
2528    }
2529
2530    /// The replicator, when this server has any standby configured.
2531    ///
2532    /// Exposed so an operator surface, and `tests/replication.rs`, can read the
2533    /// counters and the per-standby status without reaching into the tasks.
2534    #[cfg(feature = "replication")]
2535    pub fn replication(&self) -> Option<Arc<crate::mirror::Replicator>> {
2536        self.replication.replicator()
2537    }
2538
2539    /// The live slot, for a caller that RECONFIGURES rather than only observes:
2540    /// `Mirror.SetReplication`'s in-process half and `tests/replication.rs`.
2541    #[cfg(feature = "replication")]
2542    pub fn replication_slot(&self) -> &Arc<crate::mirror::ReplicationSlot> {
2543        &self.replication
2544    }
2545
2546    /// The live webhook slot, for a caller that reconfigures outbound delivery:
2547    /// `Webhooks.AddWebhook`'s in-process half and `tests/webhooks.rs`.
2548    #[cfg(feature = "webhooks")]
2549    pub fn webhook_slot(&self) -> &Arc<crate::webhook::WebhookSlot> {
2550        &self.webhook
2551    }
2552
2553    /// **The SSH host key this server serves**, `SHA256:…` — the fingerprint a
2554    /// client pins, read off the key that is actually loaded rather than off a
2555    /// file somebody remembers.
2556    pub fn host_key_fingerprint(&self) -> &str {
2557        &self.host_key_fingerprint
2558    }
2559
2560    /// The address the SSH listener actually bound.
2561    pub fn ssh_addr(&self) -> SocketAddr {
2562        self.ssh().local_addr()
2563    }
2564
2565    /// The address the scrape endpoint bound, if it was started.
2566    ///
2567    /// `None` is the ordinary answer: nothing binds unless `--metrics-bind`
2568    /// asked for it. A test that asked for port 0 learns its port here.
2569    pub fn metrics_addr(&self) -> Option<SocketAddr> {
2570        self.scrape.as_ref().map(|(_, addr)| *addr)
2571    }
2572
2573    /// The address the smart-HTTP listener bound, if it was started.
2574    #[cfg(feature = "http")]
2575    pub fn http_addr(&self) -> Option<SocketAddr> {
2576        self.http.as_ref().map(|(_, addr, _)| *addr)
2577    }
2578
2579    /// Whether the smart-HTTP listener terminates TLS itself.
2580    #[cfg(feature = "http")]
2581    pub fn http_tls(&self) -> bool {
2582        self.http.as_ref().is_some_and(|(_, _, tls)| *tls)
2583    }
2584
2585    /// The SSH listener. Present for the whole life of a `Server`; the `Option`
2586    /// exists only so [`Server::shutdown`] can move it out past the [`Drop`]
2587    /// impl.
2588    fn ssh(&self) -> &BoundServer {
2589        self.ssh
2590            .as_ref()
2591            .expect("the SSH listener is taken only by shutdown, which consumes the Server")
2592    }
2593
2594    /// The address the gRPC listener actually bound, if it was started.
2595    pub fn grpc_addr(&self) -> Option<SocketAddr> {
2596        self.grpc_endpoint.map(|(addr, _)| addr)
2597    }
2598
2599    /// The bound gRPC address together with whether that listener
2600    /// authenticates, which is what `serve` prints.
2601    ///
2602    /// One accessor rather than two, because the banner used to carry a
2603    /// hardcoded `UNAUTHENTICATED in v1` beside a control plane that
2604    /// authenticates. A caller that cannot get the address without the verdict
2605    /// cannot print a stale one.
2606    pub fn grpc_endpoint(&self) -> Option<(SocketAddr, bool)> {
2607        self.grpc_endpoint
2608    }
2609
2610    /// Was the unauthenticated enrolment window open when this server started?
2611    ///
2612    /// What `serve` prints beside the gRPC address. `false` is the ordinary
2613    /// answer, which is why the banner says nothing at all in that case.
2614    pub fn bootstrap_window_open(&self) -> bool {
2615        self.bootstrap_window_open
2616    }
2617
2618    /// The stores behind both listeners.
2619    pub fn stores(&self) -> &Arc<ServerStores> {
2620        &self.stores
2621    }
2622
2623    /// Serve until a stop is requested: a signal, or on the appliance the ACPI
2624    /// power button ([`appliance_pid1::runtime::stop_request`]).
2625    ///
2626    /// **Not `ctrl_c()`.** That is `SIGINT` alone, and nothing in an appliance's
2627    /// life sends `SIGINT`: `podman stop` sends `SIGTERM` and every service
2628    /// manager sends `SIGTERM`. A cloud's soft stop (UpCloud `stop`, QEMU
2629    /// `system_powerdown`) is not a signal at all: it is an ACPI power-button
2630    /// press the kernel reports on the `acpi_event` generic-netlink group
2631    /// (corrected 2026-09-28; this said it became `SIGTERM`, and a soft stop
2632    /// then waited out the cloud's timeout and was hard-stopped). PID 1 also
2633    /// gets **no default disposition** for a signal it has not handled — the
2634    /// kernel discards it. See edda's `appliance_pid1::net`.
2635    pub async fn wait(self) -> Result<()> {
2636        let signal = appliance_pid1::runtime::stop_request().await;
2637        tracing::info!(signal, "shutting both listeners down");
2638        self.shutdown().await
2639    }
2640
2641    /// Ask both listeners to stop, and wait for them.
2642    ///
2643    /// # Why the gRPC wait is bounded (measured 2026-08-03)
2644    ///
2645    /// `serve_with_incoming_shutdown` is *graceful*: it stops accepting and
2646    /// then waits for every in-flight request to finish. `Events.Watch` (the event stream)
2647    /// is server-streaming and by design **never finishes**; it ends when the
2648    /// subscriber goes away. So one connected UI made this wait forever, and
2649    /// `gunnar serve` could not be stopped with Ctrl-C at all. Measured: a test
2650    /// binary wedged for eleven minutes with the watch connection still
2651    /// `ESTAB`, no CPU, no progress.
2652    ///
2653    /// Graceful is still tried first — an in-flight `Repos.Create` should be
2654    /// allowed to land — but after [`GRPC_SHUTDOWN_GRACE`] the task is aborted
2655    /// and the process is free to exit. A watcher losing its stream at shutdown
2656    /// is what a watcher is built to handle. A server that cannot be stopped
2657    /// is not.
2658    pub async fn shutdown(mut self) -> Result<()> {
2659        // One last line before the listeners go, so the final numbers are in
2660        // the log rather than only in a process that is about to exit.
2661        if let Some(beat) = self.heartbeat.take() {
2662            beat.abort();
2663        }
2664        // I11's watchdog goes with the listeners. A watch that outlived the
2665        // server it belongs to could promote a box that is shutting down —
2666        // writing `role: primary` to disk as its last act, so the NEXT boot
2667        // comes up writable. Aborting it here is what keeps a shutdown a
2668        // shutdown.
2669        #[cfg(feature = "replication")]
2670        if let Some(watch) = self.standby_watch.take() {
2671            watch.abort();
2672        }
2673        #[cfg(feature = "replication")]
2674        if let Some(repair) = self.repair.take() {
2675            repair.abort();
2676        }
2677        // Replication stops with the server. An in-flight attempt is abandoned
2678        // rather than waited for: the job it was draining is still in the
2679        // queue's shape ("converge this repository") and the next start
2680        // re-derives it from the repository itself.
2681        #[cfg(feature = "replication")]
2682        self.replication.stop();
2683        #[cfg(feature = "webhooks")]
2684        self.webhook.stop();
2685        self.log_metrics();
2686        if let Some(tx) = self.grpc_shutdown.take() {
2687            let _ = tx.send(());
2688        }
2689        if let Some(join) = self.grpc.take() {
2690            let abort = join.abort_handle();
2691            match tokio::time::timeout(GRPC_SHUTDOWN_GRACE, join).await {
2692                Ok(Ok(result)) => result?,
2693                Ok(Err(err)) if err.is_cancelled() => {}
2694                Ok(Err(err)) => return Err(anyhow::anyhow!("the gRPC task panicked: {err}")),
2695                Err(_elapsed) => {
2696                    tracing::warn!(
2697                        grace = ?GRPC_SHUTDOWN_GRACE,
2698                        "the gRPC control plane did not stop gracefully; almost certainly an \
2699                         open Events.Watch stream, which by design never ends. Aborting it so \
2700                         the process can exit."
2701                    );
2702                    abort.abort();
2703                }
2704            }
2705        }
2706        // `shutdown_background`, not a drop: `shutdown` is an `async fn` and may
2707        // well be running on a runtime thread, where dropping a `Runtime`
2708        // panics. The listener is already stopped or aborted above, so there is
2709        // nothing left worth blocking for. The `ControlRuntime` guard's own
2710        // `Drop` would do this too; doing it explicitly here just tears the
2711        // control plane down before the SSH listener rather than after.
2712        self.control_runtime.shutdown();
2713        if let Some(ssh) = self.ssh.take() {
2714            ssh.shutdown("gunnar is shutting down")
2715                .await
2716                .context("stopping the SSH listener")?;
2717        }
2718        Ok(())
2719    }
2720
2721    /// What the SSH admission gate has done since start-up.
2722    ///
2723    /// Here so an operator surface (and `tests/`) can read the saturation
2724    /// counters without reaching into `gunnar-ssh`.
2725    pub fn admission(&self) -> gunnar_ssh::AdmissionStats {
2726        self.ssh().admission()
2727    }
2728
2729    /// Every counter this server keeps, read now.
2730    ///
2731    /// One reading of one set: the SSH listener and the git transport write to
2732    /// the same block, so `connections_refused` and `pushes_rejected` are facts
2733    /// about the same server rather than two crates' private tallies.
2734    pub fn metrics(&self) -> MetricsSnapshot {
2735        self.metrics.snapshot()
2736    }
2737
2738    /// The counter block itself, for a caller that wants to keep a handle to it.
2739    pub fn metrics_handle(&self) -> &Arc<ServerMetrics> {
2740        &self.metrics
2741    }
2742
2743    /// Write the counter line now, without waiting for the next heartbeat.
2744    pub fn log_metrics(&self) {
2745        emit_metrics(&self.metrics.snapshot());
2746    }
2747}
2748
2749impl Drop for Server {
2750    fn drop(&mut self) {
2751        if let Some(beat) = self.heartbeat.take() {
2752            beat.abort();
2753        }
2754        // Same reason as in `shutdown`: a watchdog that survives its server
2755        // could promote a box on its way out.
2756        #[cfg(feature = "replication")]
2757        if let Some(watch) = self.standby_watch.take() {
2758            watch.abort();
2759        }
2760        #[cfg(feature = "replication")]
2761        if let Some(repair) = self.repair.take() {
2762            repair.abort();
2763        }
2764        #[cfg(feature = "replication")]
2765        self.replication.stop();
2766        #[cfg(feature = "webhooks")]
2767        self.webhook.stop();
2768        // A `Server` dropped without `shutdown` (a test that panicked, say)
2769        // would otherwise take its control runtime down by a blocking `Drop`,
2770        // which panics on a runtime thread and would bury the real failure. The
2771        // `ControlRuntime` field's own `Drop` already routes through
2772        // `shutdown_background`; this is that same call, made explicit.
2773        self.control_runtime.shutdown();
2774    }
2775}
2776
2777/// **Say, at every start, whether the unauthenticated enrolment door is open.**
2778///
2779/// Silence here is the disease this repository keeps finding. A server standing
2780/// with an open door is a server anybody who can reach the control port can
2781/// take; an operator must never have to guess which state their box is in, and
2782/// on an unenrolled server there is by definition no credential with which to
2783/// ask `Admin.Health`.
2784///
2785/// Split out of [`Server::start`] and given both readings rather than taking
2786/// them, so every branch can be driven from a test on any box. A warning that
2787/// reads its own host can only ever be seen in the state that host happens to
2788/// be in.
2789///
2790/// Returns the line it emitted, so a test asserts on the **text an operator
2791/// sees** rather than on a boolean that proves nothing about the log.
2792pub fn announce_readiness(
2793    readiness: &Readiness,
2794    data_root: &std::path::Path,
2795    grpc_bind: SocketAddr,
2796    no_grpc: bool,
2797) -> String {
2798    match readiness {
2799        Readiness::Ready => {
2800            let line = format!("identity table ready at {}", data_root.display());
2801            tracing::info!(data_root = %data_root.display(), "{line}");
2802            line
2803        }
2804        Readiness::AwaitingBootstrap if no_grpc => {
2805            let line = format!(
2806                "NO IDENTITY HAS EVER BEEN ENROLLED at {}, and the gRPC control plane is \
2807                 DISABLED, so there is no way to enrol one. Nobody can reach this server. Start \
2808                 without --no-grpc and call Bootstrap.Enroll, or pass --admin-key.",
2809                data_root.display()
2810            );
2811            tracing::error!(data_root = %data_root.display(), "{line}");
2812            line
2813        }
2814        Readiness::AwaitingBootstrap => {
2815            let line = format!(
2816                "NO IDENTITY HAS EVER BEEN ENROLLED at {}. Bootstrap.Enroll on {grpc_bind} is \
2817                 open to ANY caller that can reach it, with NO credential, and it creates a \
2818                 gunnar-admin. It closes permanently on the first success and deleting \
2819                 identities does not reopen it. Enrol now, or bind the control plane where \
2820                 nobody else can reach it.",
2821                data_root.display()
2822            );
2823            tracing::warn!(
2824                data_root = %data_root.display(),
2825                %grpc_bind,
2826                bootstrap_window = "OPEN",
2827                "{line}"
2828            );
2829            line
2830        }
2831        Readiness::SealedAndEmpty { record } => {
2832            let who = match record {
2833                Some(record) => format!(
2834                    "was bootstrapped by \"{}\" at {}",
2835                    record.principal_id, record.at
2836                ),
2837                None => "holds principals but no keys and carries no bootstrap record, so it \
2838                         was written before that record existed, and"
2839                    .to_owned(),
2840            };
2841            let line = format!(
2842                "this server {who} its identity table at {} now holds no keys. NOBODY CAN \
2843                 AUTHENTICATE against it, and the enrolment window stays shut — deleting \
2844                 identities does not reopen it. Add a key with `gunnar key add` while the \
2845                 server is down.",
2846                data_root.display()
2847            );
2848            tracing::error!(
2849                data_root = %data_root.display(),
2850                bootstrap_window = "SHUT",
2851                "{line}"
2852            );
2853            line
2854        }
2855    }
2856}
2857
2858/// **Turn `--grpc-bind` into the address the listener binds.**
2859///
2860/// The one caller of [`BindSpec::resolve_with`] in the server, and the one
2861/// place `appliance_pid1::net::interface_ipv4` is wired to it. An address resolves to itself
2862/// and never touches netlink; an interface is asked, once, and a refusal stops
2863/// the start rather than widening the bind — the whole point of the spelling.
2864/// Returns the address to bind, or `None` when the named interface exists and
2865/// holds no IPv4 — see [`BindSpec::resolve_with`] for why that is `Ok` and not
2866/// an error, and what the caller owes it.
2867/// **Bind the control plane's listener — on a DEVICE when the spelling named
2868/// one.** `eth1:50051` resolves to the address eth1 holds, and an address alone
2869/// is not the interface: MEASURED 2026-09-05 on the KVM bench rig (two slirp
2870/// NICs, both 10.0.2.15), the listener bound to eth1's address answered on
2871/// eth0's forward and refused eth1's, because the kernel routes by address and
2872/// both interfaces held it. `SO_BINDTODEVICE` makes the socket the interface's
2873/// — the same call the DHCP client makes for its broadcast socket — so the
2874/// declaration `--grpc-bind eth1:50051` means eth1 on every machine, not just on
2875/// one whose subnets happen to differ. An address spelling (`None`) binds as
2876/// before. The socket is made non-blocking and handed to the control runtime's
2877/// I/O driver by `from_std`, on the runtime that calls this.
2878fn bind_grpc_listener(addr: SocketAddr, device: Option<&str>) -> Result<tokio::net::TcpListener> {
2879    use socket2::{Domain, Protocol, Socket, Type};
2880    let domain = if addr.is_ipv6() { Domain::IPV6 } else { Domain::IPV4 };
2881    let sock = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))
2882        .context("opening the gRPC listener socket")?;
2883    sock.set_reuse_address(true).context("SO_REUSEADDR on the gRPC listener")?;
2884    if let Some(dev) = device {
2885        sock.bind_device(Some(dev.as_bytes()))
2886            .with_context(|| format!("SO_BINDTODEVICE {dev} on the gRPC listener"))?;
2887    }
2888    sock.bind(&addr.into()).with_context(|| format!("bind {addr}"))?;
2889    sock.listen(1024).context("listen on the gRPC listener")?;
2890    sock.set_nonblocking(true).context("non-blocking gRPC listener")?;
2891    tokio::net::TcpListener::from_std(sock.into()).context("registering the gRPC listener with the runtime")
2892}
2893
2894/// How long `serve` waits for the gRPC bind address to turn up on an interface
2895/// before it gives up. Thirty seconds covers a tailnet or WireGuard interface
2896/// that comes up after this service on a cold boot; anything slower is a box
2897/// with a real problem, and the bounded exit hands it to the supervisor.
2898pub const GRPC_BIND_PATIENCE: std::time::Duration = std::time::Duration::from_secs(30);
2899
2900/// The pause between two bind attempts while waiting for the address.
2901pub const GRPC_BIND_RETRY_EVERY: std::time::Duration = std::time::Duration::from_millis(500);
2902
2903/// `EADDRNOTAVAIL` and nothing else. That errno means "no interface on this
2904/// box has that address", which on a cold boot means *yet*. `EADDRINUSE`, a
2905/// bad device, a permission refusal: none of those get better by waiting.
2906fn bind_failed_because_the_address_is_not_here_yet(err: &anyhow::Error) -> bool {
2907    err.chain()
2908        .filter_map(|cause| cause.downcast_ref::<std::io::Error>())
2909        .any(|io| io.kind() == std::io::ErrorKind::AddrNotAvailable)
2910}
2911
2912/// Run `attempt` until it binds, retrying only while the failure is the
2913/// address-not-here-yet errno, every `every`, for at most `patience`.
2914///
2915/// Returns the final result AND the number of retries taken, so a caller (and
2916/// the test) can tell a first-try bind from a waited-for one.
2917async fn bind_when_the_address_arrives<T, F>(
2918    mut attempt: F,
2919    patience: std::time::Duration,
2920    every: std::time::Duration,
2921) -> (Result<T>, u32)
2922where
2923    F: FnMut() -> Result<T>,
2924{
2925    let started = std::time::Instant::now();
2926    let mut retries = 0u32;
2927    loop {
2928        match attempt() {
2929            Ok(bound) => {
2930                if retries > 0 {
2931                    tracing::info!(
2932                        retries,
2933                        waited_ms = started.elapsed().as_millis() as u64,
2934                        "the gRPC bind address arrived; the control plane is bound"
2935                    );
2936                }
2937                return (Ok(bound), retries);
2938            }
2939            Err(err) if bind_failed_because_the_address_is_not_here_yet(&err) => {
2940                if started.elapsed() >= patience {
2941                    return (
2942                        Err(err.context(format!(
2943                            "the address was on no interface for {} s ({retries} retries)",
2944                            patience.as_secs()
2945                        ))),
2946                        retries,
2947                    );
2948                }
2949                if retries == 0 {
2950                    tracing::warn!(
2951                        patience_s = patience.as_secs(),
2952                        "the gRPC bind address is on no interface yet (EADDRNOTAVAIL); waiting for \
2953                         it. A tailnet or VPN interface that comes up after this service is the \
2954                         usual cause"
2955                    );
2956                }
2957                retries += 1;
2958                tokio::time::sleep(every).await;
2959            }
2960            Err(err) => return (Err(err), retries),
2961        }
2962    }
2963}
2964
2965#[cfg(test)]
2966mod grpc_bind_patience_tests {
2967    use super::*;
2968    use std::time::Duration;
2969
2970    fn not_here_yet() -> anyhow::Error {
2971        anyhow::Error::from(std::io::Error::from(std::io::ErrorKind::AddrNotAvailable))
2972            .context("bind 100.64.0.1:50061")
2973    }
2974
2975    /// The address arrives on the third try: bound, and the retry count says
2976    /// the wait was real (a wrapper that never retried would return 0 here).
2977    #[test]
2978    fn an_address_that_arrives_later_is_bound_and_the_retries_are_counted() {
2979        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2980        let mut left = 2;
2981        let (bound, retries) = rt.block_on(bind_when_the_address_arrives(
2982            || {
2983                if left > 0 {
2984                    left -= 1;
2985                    Err(not_here_yet())
2986                } else {
2987                    Ok(7u8)
2988                }
2989            },
2990            Duration::from_secs(5),
2991            Duration::from_millis(1),
2992        ));
2993        assert_eq!(bound.unwrap(), 7);
2994        assert_eq!(retries, 2);
2995    }
2996
2997    /// Any other errno fails on the first try, with zero retries: waiting on
2998    /// `EADDRINUSE` would hide a second server on the port for thirty seconds.
2999    #[test]
3000    fn an_address_in_use_is_not_waited_for() {
3001        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
3002        let mut calls = 0;
3003        let (bound, retries) = rt.block_on(bind_when_the_address_arrives(
3004            || -> Result<u8> {
3005                calls += 1;
3006                Err(anyhow::Error::from(std::io::Error::from(std::io::ErrorKind::AddrInUse)))
3007            },
3008            Duration::from_secs(5),
3009            Duration::from_millis(1),
3010        ));
3011        assert!(bound.is_err());
3012        assert_eq!(retries, 0);
3013        assert_eq!(calls, 1);
3014    }
3015
3016    /// The patience is a bound: an address that never comes gives up with the
3017    /// wait named in the error, not a hang.
3018    #[test]
3019    fn an_address_that_never_comes_gives_up_after_the_patience() {
3020        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
3021        let (bound, retries) = rt.block_on(bind_when_the_address_arrives(
3022            || -> Result<u8> { Err(not_here_yet()) },
3023            Duration::from_millis(30),
3024            Duration::from_millis(5),
3025        ));
3026        let msg = format!("{:#}", bound.unwrap_err());
3027        assert!(msg.contains("on no interface for 0 s"), "{msg}");
3028        assert!(retries >= 3, "retries={retries}");
3029    }
3030
3031    /// The real socket path: TEST-NET-1 is on no interface anywhere, and the
3032    /// kernel's answer is the errno the wait is keyed on. This is the red that
3033    /// proves the classifier reads the errno that `bind_grpc_listener` actually
3034    /// produces, not one the test invented.
3035    #[test]
3036    fn the_real_bind_error_for_an_absent_address_is_classified_as_not_here_yet() {
3037        let rt = tokio::runtime::Builder::new_current_thread().enable_io().build().unwrap();
3038        let _guard = rt.enter();
3039        let err = bind_grpc_listener("192.0.2.1:0".parse().unwrap(), None)
3040            .expect_err("TEST-NET-1 is on no interface");
3041        assert!(bind_failed_because_the_address_is_not_here_yet(&err), "{err:#}");
3042        let in_use = anyhow::Error::from(std::io::Error::from(std::io::ErrorKind::AddrInUse));
3043        assert!(!bind_failed_because_the_address_is_not_here_yet(&in_use));
3044    }
3045}
3046
3047#[cfg(test)]
3048mod grpc_bind_device_tests {
3049    use super::*;
3050
3051    /// A device that does not exist is refused BY NAME before anything binds —
3052    /// the red that proves the device half is wired at all.
3053    #[test]
3054    fn a_device_the_machine_does_not_have_is_refused_by_name() {
3055        let rt = tokio::runtime::Builder::new_current_thread().enable_io().build().unwrap();
3056        let _guard = rt.enter();
3057        let err = bind_grpc_listener("127.0.0.1:0".parse().unwrap(), Some("nosuchdev0"))
3058            .expect_err("a nonexistent device cannot be bound");
3059        let msg = format!("{err:#}");
3060        assert!(msg.contains("SO_BINDTODEVICE nosuchdev0"), "{msg}");
3061    }
3062
3063    /// The address-only spelling binds exactly as before, and on the loopback
3064    /// device by name too (the one device every box has).
3065    #[test]
3066    fn an_address_binds_and_so_does_the_loopback_device() {
3067        let rt = tokio::runtime::Builder::new_current_thread().enable_io().build().unwrap();
3068        let _guard = rt.enter();
3069        let plain = bind_grpc_listener("127.0.0.1:0".parse().unwrap(), None).unwrap();
3070        assert!(plain.local_addr().unwrap().port() != 0);
3071        match bind_grpc_listener("127.0.0.1:0".parse().unwrap(), Some("lo")) {
3072            Ok(l) => assert!(l.local_addr().unwrap().port() != 0),
3073            // Kernels before 5.7 gate SO_BINDTODEVICE behind CAP_NET_RAW; a
3074            // permission refusal is that gate, not a wiring defect.
3075            Err(e) => assert!(format!("{e:#}").contains("SO_BINDTODEVICE lo"), "{e:#}"),
3076        }
3077    }
3078}
3079
3080fn resolve_grpc_bind(spec: &BindSpec) -> Result<Option<SocketAddr>> {
3081    match spec
3082        .resolve_with(|name| appliance_pid1::net::interface_ipv4(name).map_err(|e| format!("{e:#}")))
3083        .map_err(|why| anyhow::anyhow!("{why}"))?
3084    {
3085        gunnar_common::bindspec::Resolved::Bound(addr) => Ok(Some(addr)),
3086        gunnar_common::bindspec::Resolved::NoAddress { interface, why } => {
3087            // ERROR and not WARN: an operator who asked for a control plane
3088            // has not got one, and nothing else on the box will say so.
3089            tracing::error!(
3090                interface = %interface,
3091                "{why} The gRPC control plane will NOT start. The git listener is unaffected \
3092                 and this server still serves and authenticates pushes and fetches over SSH."
3093            );
3094            Ok(None)
3095        }
3096    }
3097}
3098
3099/// `--admin-key` is either the key line itself or `@<path>`.
3100fn read_key_argument(spec: &str) -> Result<String> {
3101    match spec.strip_prefix('@') {
3102        Some(path) => std::fs::read_to_string(path)
3103            .with_context(|| format!("reading the public key from {path}"))
3104            .map(|text| text.trim().to_owned()),
3105        None => Ok(spec.trim().to_owned()),
3106    }
3107}
3108
3109/// **The startup banner's host-key line.**
3110///
3111/// The fingerprint IN FULL, never shortened: the dashboard's `short_fp` is for
3112/// recognising a key you already know, and this line exists to be the first
3113/// place anybody learns it. It is read off a VNC screenshot by a human and
3114/// typed into a `known_hosts` line, and twelve characters cannot be typed into
3115/// anything.
3116///
3117/// The word `sshkey` leads it so a screenshot can be searched for one token.
3118///
3119/// Why this is worth a line of banner at all: `known_hosts` records no
3120/// provenance. Once written, a key taken off the wire by `ssh-keyscan` and a
3121/// key read off a console are the same bytes, for ever after, and nothing in
3122/// the file can tell the two apart. The only thing that makes a forge push
3123/// mean anything is WHERE the fingerprint came from — a record written by the
3124/// install (`deploy/upcloud`'s receipt) or a reading off the box's own console.
3125/// Never from whatever answered on `:2222`.
3126pub(crate) fn host_key_banner_line(fingerprint: &str) -> String {
3127    format!("sshkey {fingerprint}   (pin THIS; a key scanned off the port proves nothing)")
3128}
3129
3130/// The host key, as russh's `ssh-key` sees it.
3131fn russh_private_key(openssh: &[u8]) -> Result<gunnar_ssh::russh::keys::PrivateKey> {
3132    gunnar_ssh::russh::keys::PrivateKey::from_openssh(openssh)
3133        .map_err(|err| anyhow::anyhow!("the stored host key did not parse: {err}"))
3134}
3135
3136/// Run `gunnar serve` to completion.
3137pub async fn run(stores: Arc<ServerStores>, config: ServeConfig, check_only: bool) -> Result<()> {
3138    // The descriptor limit, raised once. `ServerStores::open` already did this
3139    // (its handle cache is sized from the answer); calling it here is the
3140    // guarantee that the `limits.nofile` line — a WARN row on the dashboard
3141    // when the limit is low — exists before a listener binds, whichever path
3142    // built `stores`.
3143    let _ = crate::limits::nofile();
3144    // ── THE NARRATOR, BEFORE ANYTHING ELSE ──────────────────────────────────
3145    //
3146    // MEASURED 2026-09-23: `boot::ship_boot_narration` ends at `end of
3147    // hand-off` — the moment the DHCP lease makes the wire usable — and the
3148    // estate's twin died in the silence after it, having read its config,
3149    // bound its listeners, taken its role, held its certificate and started
3150    // following. None of that was said. From here on every boundary is.
3151    //
3152    // The sink is `korp.log_udp=` off the kernel command line and nothing
3153    // else. Absent ⇒ nothing is armed, no thread is started, no datagram is
3154    // sent, and the two file readers (the ESP's BOOTLOG.TXT and /data) carry
3155    // the story as they always did. That is the off switch.
3156    use crate::narrate::Stage;
3157    crate::narrate::install();
3158    crate::narrate::data_home(stores.root());
3159    crate::narrate::at(
3160        Stage::Config,
3161        &format!(
3162            "data root {}, engine {:?}, ssh {}, grpc {:?}, twin_role={}, is_twin={}",
3163            stores.root().display(),
3164            stores.engine(),
3165            config.ssh_bind,
3166            config.grpc_bind,
3167            config.twin_role,
3168            stores.is_twin(),
3169        ),
3170    );
3171    // ── PID 1's own duties, before anything binds ───────────────────────────
3172    //
3173    // The network first and by hand, because the interface has to exist before
3174    // a listener can be reached over it and on this appliance nothing else
3175    // brings it up: measured on the reference desktop 2026-08-03, the kernel is built with
3176    // `CONFIG_IP_PNP` off, so `ip=` on the command line configures nothing.
3177    // A refused static plan or malformed GUNNAR_NET is fatal on purpose: the
3178    // alternative is a server that starts, logs "ssh 0.0.0.0:2222" and can
3179    // never be reached, which is the same failure `Readiness::RefuseToServe`
3180    // exists to prevent. A DHCP timeout is NOT fatal — bring_up_network warns
3181    // and serves unreachable, the missing-GUNNAR_NET posture — because there
3182    // the world declined to answer; the declaration did not lie.
3183    crate::narrate::at(Stage::Network, "bringing the declared interfaces up over netlink");
3184    let dhcp_session = crate::boot::bring_up_network()?;
3185    // The lease. The UDP narration wire is retired (2026-09-24): the installer
3186    // collects this box's whole boot log over its own mutual TLS.
3187    crate::narrate::at(Stage::Lease, &format!("{} DHCP lease(s) held", dhcp_session.len()));
3188    crate::narrate::at(Stage::Sink, "the boot log is kept for the installer (its bootstrap listener serves it)");
3189    // **The clock, and here rather than anywhere later.** It is after the
3190    // network because it is fetched over the network, and before every listener
3191    // because `gunnar_grpc::auth::MAX_CLOCK_SKEW_MS` is ±5 minutes: an appliance
3192    // that serves a single request on a clock two hours out refuses a genuine
3193    // credential and a genuine Stripe webhook signature, which is precisely what
3194    // gunnar.rs measured on 2026-09-14. Never fatal, never a `?`: see
3195    // `crate::clock`'s note on why a failed clock fetch must not cost a forge.
3196    crate::clock::synchronise_at_boot().await;
3197    // And again when a credential is refused for skew, and every six hours: a
3198    // boot-time step fixes the clock the box boots with, never the drift of the
3199    // months until the next re-image. Background threads; see `crate::clock`.
3200    crate::clock::arm_triggers();
3201    // **The bind spelling becomes an address here, and not one line earlier.**
3202    // `--grpc-bind eth1:50051` names an interface whose address arrives with
3203    // the DHCP lease above; asking before `bring_up_network` would find an
3204    // interface with no address every time. Asking AFTER is also what makes
3205    // the refusal actionable: if it fires, the lease genuinely did not land,
3206    // and the warning `bring_up_network` already logged says why.
3207    let mut config = config;
3208    // **An interface whose lease PID 1 still asks for** (its boot DHCP failed — estate-box3
3209    // D4, a box rebooted while its network was down) is WAITED for, here on the appliance's
3210    // path as in `Server::start`: the control plane binds once the address arrives.
3211    if let BindSpec::Interface { interface, .. } = &config.grpc_bind {
3212        let has_address = |i: &str| matches!(appliance_pid1::net::interface_ipv4(i), Ok(Some(_)));
3213        if !has_address(interface) && appliance_pid1::net::dhcp_pending(interface) {
3214            tracing::info!(interface = %interface, "the control plane waits for {interface}'s address (PID 1 asks DHCP again in the background)");
3215            while !has_address(interface) && appliance_pid1::net::dhcp_pending(interface) {
3216                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
3217            }
3218        }
3219    }
3220    let resolved = resolve_grpc_bind(&config.grpc_bind).with_context(|| {
3221        "resolving --grpc-bind after the network came up. A medium that names a NIC this \
3222         machine does not have is a declaration that lies, and gunnar stops rather than \
3223         falling back to a wildcard bind: an unauthenticated control plane on every \
3224         interface is the defect the interface spelling exists to close."
3225    })?;
3226    let resolved_grpc_bind = match resolved {
3227        Some(addr) => addr,
3228        None => {
3229            config.no_grpc = true;
3230            gunnar_grpc::DEFAULT_BIND
3231        }
3232    };
3233    // Pin the answer into the config so `Server::start`, the dashboard and the
3234    // readiness line all report the address the listener took rather than the
3235    // spelling it was asked for — and so the netlink question is asked once.
3236    if let BindSpec::Interface { interface, .. } = &config.grpc_bind {
3237        config.grpc_bind_device = Some(interface.clone());
3238    }
3239    config.grpc_bind = BindSpec::Addr(resolved_grpc_bind);
3240    if !config.no_grpc && !resolved_grpc_bind.ip().is_loopback() {
3241        tracing::info!(
3242            grpc_bind = %resolved_grpc_bind,
3243            "gRPC control plane will bind a NON-loopback address"
3244        );
3245    }
3246    // Whether /data survived the last install (the ESP record korp-installer
3247    // left) — one event, one dashboard row, before the band starts.
3248    crate::boot::announce_install_mode(stores.root());
3249    // The start-up disk test, appliance only (same gate as the dashboard, or
3250    // `GUNNAR_DISKTEST=1`): one thread, one `disktest` row, never waited for.
3251    crate::disktest::spawn(stores.root().to_path_buf());
3252    if appliance_pid1::net::is_init() {
3253        tracing::info!(
3254            "running as pid 1: no init system underneath, so this process handles SIGTERM and \
3255             reaps re-parented orphans itself"
3256        );
3257    }
3258    // Installed unconditionally. A reaper that only exists at pid 1 is a reaper
3259    // no test on a developer machine ever runs.
3260    let reaper = tokio::spawn(appliance_pid1::runtime::reaper());
3261    // **The soft-delete sweep**: the half of `repo delete` that gives the bytes
3262    // back. Hourly, and once now. Without it a retention window would be a
3263    // promise to keep repositories forever, and `/data` would fill with
3264    // repositories nobody can list.
3265    let tombstone_sweep = crate::stores::spawn_tombstone_sweep(Arc::clone(&stores));
3266    // **The flow flush**: the half of the activity ledger that survives a
3267    // restart. The counters a transfer bumps live in atomics in this process;
3268    // this copies them into the control store every minute, and rolls the UTC
3269    // day on a box that is idle at midnight. See `stores::spawn_flow_flush`.
3270    // The band's fold, refreshed by the flush task once a minute. `None` until
3271    // the first flush: a row of zeroes before anything has been folded would
3272    // claim the box served nobody today.
3273    let flow_band: Arc<std::sync::Mutex<Option<gunnar_core::Fleet>>> =
3274        Arc::new(std::sync::Mutex::new(None));
3275    let flow_flush = crate::stores::spawn_flow_flush(Arc::clone(&stores), Arc::clone(&flow_band));
3276    config.flow_view.fill(move || *flow_band.lock().expect("the flow band"));
3277    // Kept out of the move into `Server::start` below, for the shutdown flush.
3278    let flow_at_exit = Arc::clone(stores.flow());
3279    // The VGA status screen, appliance only (PID 1 booted by korp-start) or
3280    // `GUNNAR_DASHBOARD=<device>`. One thread, fed by the log tap; the lease
3281    // line above is already in the tap's buffer and is its first row. Never
3282    // fatal, never waited for — see `crate::dashboard`.
3283    // The band starts before the server does, so it is handed a VIEW and the
3284    // replicator is dropped into it below, once `Server::start` has one. A box
3285    // with no standby leaves it unfilled and the band draws no `standby` row.
3286    let replication_view = config.replication_view.clone();
3287    crate::dashboard::spawn(crate::dashboard::Facts {
3288        ssh_bind: config.ssh_bind,
3289        grpc_bind: (!config.no_grpc).then_some(resolved_grpc_bind),
3290        data_root: stores.root().to_path_buf(),
3291        build: gunnar_common::BUILD_REF.to_owned(),
3292        engine: Some(stores.engine()),
3293        replication: replication_view.clone(),
3294        tenants: config.tenants_view.clone(),
3295        flow: config.flow_view.clone(),
3296    });
3297    // Exactly when the address is DHCP-learned, a task keeps the lease alive
3298    // (RFC 2131 §4.4.5 — appliance_pid1::runtime::dhcp_renewal). Static and unconfigured paths
3299    // return an EMPTY list above and gain no task: renewal exists only where a
3300    // lease does — and a two-NIC appliance holds TWO leases, each with its own
3301    // T1, so there is one task per lease rather than one task guessing which
3302    // interface it is keeping alive.
3303    #[cfg(feature = "dhcp-client")]
3304    let renewals: Vec<tokio::task::JoinHandle<()>> = dhcp_session
3305        .into_iter()
3306        .map(|session| tokio::spawn(crate::boot::dhcp_renewal(session)))
3307        .collect();
3308    // Built without `dhcp-client`: `DhcpSession` is UNINHABITED, so this is the
3309    // compiler proving there is no lease rather than a runtime check claiming
3310    // it. The `Some` arm is `match session {}` — unreachable by construction —
3311    // and the abort sites below need no cfg of their own.
3312    #[cfg(not(feature = "dhcp-client"))]
3313    let renewals: Vec<tokio::task::JoinHandle<()>> = dhcp_session
3314        .into_iter()
3315        .map(|session| match session {})
3316        .collect();
3317
3318    // ── the tunnel, AFTER the outer address ─────────────────────────────────
3319    //
3320    // Order is load-bearing and not alphabetical: a WireGuard peer is reached
3321    // over the outer address, so a handshake attempted before DHCP has
3322    // finished has no source address to leave from. It is strictly additive —
3323    // no `wg0.conf` in the data root means one INFO line and nothing else
3324    // changes — and it is deliberately NOT fatal when the kernel refuses,
3325    // because an appliance that will not serve git because a tunnel failed is
3326    // worse than one that serves on its outer address and says so loudly.
3327    //
3328    // Nothing below has to be told about it: both listeners bind `0.0.0.0`
3329    // (`ServeConfig::default`, ssh 0.0.0.0:2222), so `wg0` is served the
3330    // moment it has an address.
3331    // **This binding is the tunnel's lifetime.** The data plane is a thread in
3332    // THIS process now, not a device the kernel owns: `Tunnel` holds the pump
3333    // and the tun fd, and dropping the last handle stops the pump and deletes
3334    // `wg0`. The clone below goes to a watcher task that RETURNS after the
3335    // first handshake, so if this binding were consumed instead of kept the
3336    // tunnel would come up, announce itself and vanish a few seconds later.
3337    // It stays in scope for the whole of `run`, which is the process.
3338    // A pairing box's `wg0.conf` is written by the pairing loop once the
3339    // installer's door has assigned the address (pairing.rs); on a reboot it
3340    // is already here and this lane raises it like any other.
3341    #[cfg(feature = "wg-client")]
3342    let tunnel = crate::wg::bring_up(stores.root())?;
3343    #[cfg(feature = "wg-client")]
3344    let handshake = tunnel.clone().map(|t| {
3345        tokio::spawn(crate::wg::handshake_watch(
3346            t,
3347            20,
3348            std::time::Duration::from_secs(3),
3349        ))
3350    });
3351    // Built without `wg-client`: there is no tunnel type, no boringtun and no
3352    // `wg_appliance_core` in this binary at all, so there is nothing to bring
3353    // up, nothing to watch and no banner line to write. No `tunnel` binding
3354    // exists in this build — only the watcher handle the two abort paths below
3355    // reach for, and it is permanently `None`.
3356    #[cfg(not(feature = "wg-client"))]
3357    let handshake: Option<tokio::task::JoinHandle<()>> = None;
3358
3359    // Read off both BEFORE the move below, so the role line can be narrated
3360    // after the listeners are up: `Server::start` consumes `stores` and
3361    // `config`, and the role is a property of the boot rather than of the
3362    // server object.
3363    let config_twin_role = config.twin_role;
3364    let stores_is_twin = stores.is_twin();
3365    // `Server::start` fills `config.replication_view` — the same object the
3366    // band above was handed — once the replicator exists.
3367    let server = Server::start(stores, config).await?;
3368    // The staleness alarm: one WARN into the log and one event-stream event the first
3369    // time a standby stops taking bytes — with "last successful replication:
3370    // NEVER" as its own message. Harmless when nothing is configured: the view
3371    // reports no standbys and the task never fires.
3372    let staleness_watch = crate::replication_view::spawn_staleness_watch(
3373        replication_view.clone(),
3374        Arc::clone(server.bus()),
3375    );
3376    // The banner is BUILT once and written twice (one implementation, one writer): to stdout,
3377    // which on the appliance is `/dev/console` = the serial line that
3378    // `installtest/src/iso.rs` reads its boot proof off, and — appliance only —
3379    // mirrored to `/dev/tty0` so a KVM GRAPHICS console ends on gunnar's own
3380    // status instead of the kernel's last printk. Measured 2026-08-12: with the
3381    // banner on serial alone, a VGA console showed a healthy boot log that never
3382    // once said "gunnar".
3383    let mut banner = String::new();
3384    {
3385        use std::fmt::Write as _;
3386        writeln!(banner, "ssh   {}", server.ssh_addr()).ok();
3387        // **THE HOST KEY, ON A CHANNEL PRODUCTION HAS.** Directly under the
3388        // address it belongs to, because the two together are the whole of
3389        // what a client needs to trust this box.
3390        //
3391        // MEASURED 2026-09-23. The fingerprint was logged and nowhere else:
3392        // `tracing` → stderr → `/dev/console` → the LAST `console=` on the
3393        // command line → the serial line, and the UpCloud shape has no serial
3394        // line (a panic there prints PID 1's first `print!` to nothing; the
3395        // ISO's own gate VMs are the only boxes that ever had it, in their
3396        // `serial.log`). So in production the one fact a client must pin
3397        // reached NOBODY, and this laptop's `known_hosts` has eight
3398        // `ssh-keyscan`-shaped lines for `[git.gunnar.rs]:2222` to prove what
3399        // fills the gap.
3400        //
3401        // This banner is the channel that answers: it is printed on stdout AND
3402        // mirrored to `/dev/tty0` (`appliance_pid1::console::mirror_to_gfx_console`, a few
3403        // lines below), which is the VNC screen of an UpCloud VM. The
3404        // WireGuard public key is already here for exactly this argument — on
3405        // a shell-less appliance the banner is the only channel that can
3406        // answer "is the key on this box the one I enrolled?".
3407        //
3408        // The narration wire (`korp.log_udp=`) was considered FIRST and is
3409        // not usable: it is armed and flushed long before this point, but the
3410        // one door onto it (`appliance_pid1::narration::narration_door`) classifies any
3411        // line carrying `sha256:` as `pubkey` and replaces it with a withheld
3412        // notice, the collector refuses it identically
3413        // (`<ops>/xtask/src/bootnarr.rs::secret_class`), and the 40-character
3414        // opaque-run rule catches the fingerprint's body with the label
3415        // stripped off — so no spelling escapes. That door is an OWNER RULE
3416        // ("a PUBLIC verifying key … is withheld anyway, because it is not
3417        // progress"), spelled in three repositories. Putting the fingerprint
3418        // on that wire needs the rule reversed and all three vocabularies
3419        // changed together; it is not something this line may do quietly.
3420        writeln!(banner, "{}", host_key_banner_line(server.host_key_fingerprint())).ok();
3421        match server.grpc_endpoint() {
3422            // The open enrolment window comes FIRST on this line, before the
3423            // reassuring "authenticated": a server that has never been enrolled is
3424            // one anybody who can reach the port can take, and an operator reading
3425            // three lines of banner must not have to know that "authenticated"
3426            // does not cover `Bootstrap.Enroll`.
3427            Some((addr, _)) if server.bootstrap_window_open() => writeln!(
3428                banner,
3429                "grpc  {addr}  (NOT ENROLLED — Bootstrap.Enroll is open to anyone who can reach \
3430                 this port. `gunnar control bootstrap <name>` claims it, once.)"
3431            )
3432            .ok(),
3433            Some((addr, true)) => {
3434                writeln!(banner, "grpc  {addr}  (authenticated: sshsig + the ACL model)").ok()
3435            }
3436            Some((addr, false)) => writeln!(
3437                banner,
3438                "grpc  {addr}  (UNAUTHENTICATED — the escape hatch is on)"
3439            )
3440            .ok(),
3441            None => writeln!(banner, "grpc  disabled").ok(),
3442        };
3443        // Only when it is on, like metrics below. Without this line a server asked
3444        // to bind HTTP on port 0 has bound a listener nobody can find: ssh, grpc,
3445        // metrics and the log level were all announced, and the one listener a
3446        // stock `git` client talks to was not.
3447        #[cfg(feature = "http")]
3448        if let Some(addr) = server.http_addr() {
3449            if server.http_tls() {
3450                writeln!(
3451                    banner,
3452                    "https {addr}  (TLS terminated here; clients pin the issuer)"
3453                )
3454                .ok();
3455            } else {
3456                writeln!(banner, "http  {addr}").ok();
3457            }
3458        }
3459        // Only when it is on: a line reading "metrics disabled" on every
3460        // server that never asked for the feature is banner an operator learns to
3461        // skip, and the banner's whole value is that it is short enough to read.
3462        if let Some(addr) = server.metrics_addr() {
3463            writeln!(
3464                banner,
3465                "metrics http://{addr}{}   (no authentication{})",
3466                crate::scrape::SCRAPE_PATH,
3467                if addr.ip().is_loopback() {
3468                    ""
3469                } else {
3470                    "; NOT on loopback"
3471                }
3472            )
3473            .ok();
3474        }
3475        // The tunnel, and ONLY when there is one — same rule as metrics above.
3476        //
3477        // It carries the appliance's WireGuard PUBLIC KEY, which is not
3478        // decoration: peering is mutual allowlisting by public key, and a key
3479        // the hub does not have in its `[Peer]` stanza gets **silence** rather
3480        // than a rejection. So "is the key on this box the one I enrolled?" is
3481        // the first question of every failed tunnel, and on a shell-less
3482        // appliance the banner — serial AND the mirrored graphics console — is
3483        // the only channel that can answer it.
3484        #[cfg(feature = "wg-client")]
3485        if let Some(tunnel) = &tunnel {
3486            writeln!(banner, "{}", tunnel.banner_line()).ok();
3487        }
3488        // On stdout beside the addresses rather than in the log: this is
3489        // the one fact an operator needs BEFORE the incident, and by the time they
3490        // want it the log is the thing they cannot read enough of. It also warns
3491        // them off the trap — both signals default to terminating a process, and
3492        // that is what they did to this one until today.
3493        writeln!(
3494            banner,
3495            "log   {}   (SIGUSR1 → one rung more verbose, SIGUSR2 → back; pid {})",
3496            gunnar_common::logging::current().unwrap_or_else(|| "?".to_owned()),
3497            std::process::id()
3498        )
3499        .ok();
3500    }
3501    print!("{banner}");
3502    appliance_pid1::console::mirror_to_gfx_console(&banner);
3503    // **ONE LINE PER LISTENER, WITH THE ADDRESS IT TOOK.** Not the spelling it
3504    // was asked for: `--grpc-bind eth1:50051` and `10.13.9.24:50051` are two
3505    // different facts and only the second one can be dialled. A listener the
3506    // build does not carry says nothing rather than saying `disabled`, so a
3507    // reader counting listeners counts the ones that exist.
3508    crate::narrate::at(Stage::Listener, &format!("ssh BOUND {}", server.ssh_addr()));
3509    match server.grpc_endpoint() {
3510        Some((addr, _)) => crate::narrate::at(
3511            Stage::Listener,
3512            &format!(
3513                "grpc BOUND {addr}{}",
3514                if server.bootstrap_window_open() { " (NOT ENROLLED — Bootstrap.Enroll is open)" } else { "" }
3515            ),
3516        ),
3517        None => crate::narrate::at(Stage::Listener, "grpc NOT bound — the control plane is off"),
3518    }
3519    #[cfg(feature = "http")]
3520    if let Some(addr) = server.http_addr() {
3521        crate::narrate::at(
3522            Stage::Listener,
3523            &format!("{} BOUND {addr}", if server.http_tls() { "https" } else { "http" }),
3524        );
3525    }
3526    if let Some(addr) = server.metrics_addr() {
3527        crate::narrate::at(Stage::Listener, &format!("metrics BOUND {addr}"));
3528    }
3529    // **THE ROLE**, from the two places that decide it: what the medium
3530    // declared and what the data home already is. They are narrated together
3531    // because a disagreement between them is the interesting case — a box
3532    // installed from main's medium onto a disk that already holds a twin's
3533    // certificate is exactly the shape the estate re-images into.
3534    crate::narrate::at(
3535        Stage::Role,
3536        &format!(
3537            "{} (declared twin_role={}, data home says is_twin={})",
3538            if stores_is_twin || config_twin_role { "TWIN" } else { "PRIMARY" },
3539            config_twin_role,
3540            stores_is_twin,
3541        ),
3542    );
3543    if check_only {
3544        reaper.abort();
3545        tombstone_sweep.abort();
3546        flow_flush.abort();
3547        staleness_watch.abort();
3548        for renewal in &renewals {
3549            renewal.abort();
3550        }
3551        if let Some(handshake) = &handshake {
3552            handshake.abort();
3553        }
3554        server.shutdown().await?;
3555        return Ok(());
3556    }
3557    // **SERVING.** The end of the boot story and the beginning of the ticks:
3558    // from here the only thing the box is expected to say is one short line a
3559    // minute, and the ear's threshold is measured against that. A box that
3560    // reached here and then went quiet is a DEATH AT A NAMED PLACE — which is
3561    // the reading the estate did not have on 2026-09-23.
3562    crate::narrate::at(
3563        Stage::Serving,
3564        &format!(
3565            "up at {} s",
3566            crate::narrate::uptime_s(),
3567        ),
3568    );
3569    let result = server.wait().await;
3570    reaper.abort();
3571    tombstone_sweep.abort();
3572    // One last flush before the process goes. The flush COPIES rather than
3573    // adds, so doing it here as well as on the tick cannot double a count, and
3574    // it is what stops an orderly shutdown losing the last minute of today.
3575    if let Err(err) = flow_at_exit.flush(gunnar_core::now_ms()) {
3576        tracing::warn!(
3577            target: "gunnar::store",
3578            event = "flow.flush_failed",
3579            %err,
3580            "the flow ledger could not be written on shutdown; up to one flush interval of \
3581             today's activity counters is lost"
3582        );
3583    }
3584    flow_flush.abort();
3585    staleness_watch.abort();
3586    for renewal in &renewals {
3587        renewal.abort();
3588    }
3589    if let Some(handshake) = &handshake {
3590        handshake.abort();
3591    }
3592    result
3593}
3594
3595/// The public key argument reader, exposed for the wiring tests.
3596#[cfg(test)]
3597mod tests {
3598    use super::read_key_argument;
3599    use super::*;
3600
3601    /// **The banner line an operator reads off the VNC screen.**
3602    ///
3603    /// The fingerprint must be there IN FULL and unmangled: this line is the
3604    /// only production channel that carries it (the log goes to a serial
3605    /// console the UpCloud shape does not have, and the narration wire's one
3606    /// door withholds anything containing `sha256:`), and a fingerprint that
3607    /// has been shortened for display cannot be pinned by anybody.
3608    ///
3609    /// Red-first: shortening the fingerprint the way the dashboard's
3610    /// `short_fp` does, or dropping it from the line, fails here.
3611    #[test]
3612    fn the_banner_names_the_host_key_in_full() {
3613        const FP: &str = "SHA256:z/fSv0Z0RZS+Lccbc6ZoOWwt/fbj1VFJGSBKQbo4icE";
3614        let line = host_key_banner_line(FP);
3615        assert!(line.contains(FP), "{line}");
3616        assert!(line.starts_with("sshkey "), "one searchable token: {line}");
3617        assert!(!line.contains('\n'), "one line, or the banner is not a banner: {line}");
3618        // And it warns off the thing that fills known_hosts when this line is
3619        // missing, because a fingerprint with no provenance is not evidence.
3620        assert!(line.contains("scanned off the port proves nothing"), "{line}");
3621    }
3622
3623    /// The visible limit has to sit **inside** the pool that carries
3624    /// it, or the invisible ceiling is back, at whichever of the two numbers is
3625    /// smaller, which is the one nobody is looking at.
3626    #[test]
3627    fn the_blocking_pool_is_larger_than_the_transfer_limit() {
3628        let transfers = gunnar_ssh::SshConfig::default()
3629            .max_concurrent_transfers
3630            .expect("the appliance default must have a transfer limit");
3631        assert!(
3632            transfers < GIT_BLOCKING_THREADS,
3633            "max_concurrent_transfers ({transfers}) is not below GIT_BLOCKING_THREADS \
3634             ({GIT_BLOCKING_THREADS}), so the blocking pool becomes the real ceiling again and \
3635             the admission counters would show a server that is never full while every transfer \
3636             queues"
3637        );
3638        assert!(
3639            GIT_BLOCKING_THREADS >= transfers * 2,
3640            "the blocking pool ({GIT_BLOCKING_THREADS}) leaves no headroom over \
3641             {transfers} concurrent transfers for the other blocking work a transfer needs: \
3642             pack indexing, ref transactions, the arrow log"
3643        );
3644    }
3645
3646    /// The control plane must get a pool that is bounded on both sides — and
3647    /// at least FOUR workers (R5.1-G): two slow synchronous calls (a snapshot,
3648    /// a disk walk) held both workers of the old floor, and every other call —
3649    /// the console's page loads, monetize's `Entitlement.Set` — waited behind
3650    /// them.
3651    #[test]
3652    fn the_control_plane_gets_its_own_bounded_pool() {
3653        let workers = control_plane_workers();
3654        assert!(
3655            (4..=8).contains(&workers),
3656            "control_plane_workers() returned {workers}; below four, two slow synchronous calls \
3657             hold every worker and the whole administrative surface queues behind them, and an \
3658             unbounded pool recreates the starved listener with extra steps"
3659        );
3660    }
3661
3662    #[test]
3663    fn a_literal_key_and_an_at_path_read_the_same() {
3664        let dir = tempfile::tempdir().expect("a temp dir");
3665        let path = dir.path().join("id.pub");
3666        std::fs::write(&path, "ssh-ed25519 AAAAC3Nz literal\n").expect("write");
3667        assert_eq!(
3668            read_key_argument("ssh-ed25519 AAAAC3Nz literal").expect("literal"),
3669            read_key_argument(&format!("@{}", path.display())).expect("from file"),
3670            "`--admin-key @file` and `--admin-key '<line>'` must produce the same key, or a \
3671             bootstrap that works one way fails the other"
3672        );
3673    }
3674
3675    /// The 32-CPUs-of-affinity-on-8-CPUs-of-quota condition, seen **both** ways.
3676    ///
3677    /// A warning that reads its own host can only ever be observed in the state
3678    /// that host is in, and a build box that happens to be unconstrained would
3679    /// have exercised the silent branch for ever while the loud one rotted.
3680    #[test]
3681    fn a_quota_far_narrower_than_the_affinity_is_reported_and_a_matching_one_is_not() {
3682        // The measured bad case: `podman run --cpus 8` on a 32-core host.
3683        assert_eq!(
3684            spread_budget(Some(32), Some(8.0)),
3685            Some((32, 8)),
3686            "eight CPUs of quota spread over thirty-two is the condition that cost 2.7x the \
3687             CPU per request at 32 clients; it must be said out loud"
3688        );
3689        // The same budget as a cpuset: nothing to report.
3690        assert_eq!(spread_budget(Some(8), Some(8.0)), None);
3691        // Exactly at the line, and one either side of it, because `>=` and `>`
3692        // are one character apart and both compile.
3693        assert_eq!(spread_budget(Some(16), Some(8.0)), Some((16, 8)));
3694        assert_eq!(spread_budget(Some(15), Some(8.0)), None);
3695        // A fractional quota rounds UP to the CPUs an operator would name.
3696        assert_eq!(spread_budget(Some(32), Some(1.5)), Some((32, 2)));
3697        // No quota at all is the ordinary case and is not a finding. Neither is
3698        // an unreadable affinity: half a comparison would be a number invented
3699        // to fill the other half.
3700        assert_eq!(spread_budget(Some(32), None), None);
3701        assert_eq!(spread_budget(None, Some(8.0)), None);
3702    }
3703
3704    /// `Cpus_allowed_list` is ranges *and* singletons, and the two mixed.
3705    ///
3706    /// Against literals rather than against this host: the reference desktop reports a plain
3707    /// `0-31`, and a parser that counted ranges and silently dropped singletons
3708    /// passed on this box while answering 0 for a server pinned to one CPU.
3709    #[test]
3710    fn a_cpu_list_is_counted_whether_it_is_ranges_singletons_or_both() {
3711        assert_eq!(count_cpu_list("0-31"), Some(32));
3712        assert_eq!(count_cpu_list("0-7"), Some(8));
3713        assert_eq!(
3714            count_cpu_list("3"),
3715            Some(1),
3716            "one pinned CPU is one CPU, not none"
3717        );
3718        assert_eq!(count_cpu_list("0,2,4,6"), Some(4));
3719        assert_eq!(count_cpu_list("0-3,8,10-11"), Some(7));
3720        assert_eq!(
3721            count_cpu_list("  0-3 , 8 \n"),
3722            Some(5),
3723            "the kernel line is padded"
3724        );
3725        // Unreadable is None, never a number: a guessed count is the one thing
3726        // that turns this whole check into a lie.
3727        assert_eq!(count_cpu_list(""), None);
3728        assert_eq!(count_cpu_list("banana"), None);
3729        assert_eq!(
3730            count_cpu_list("7-3"),
3731            None,
3732            "a reversed range is not 5 CPUs"
3733        );
3734    }
3735
3736    #[test]
3737    fn the_affinity_of_this_process_is_read_as_a_count_of_cpus() {
3738        let n = cpus_allowed().expect("Linux always publishes Cpus_allowed_list");
3739        assert!(
3740            (1..=1 << 20).contains(&n),
3741            "this process reports {n} allowed CPUs, which is not a count of CPUs"
3742        );
3743        // The whole comparison rests on this being the *affinity* and not the
3744        // machine, so it must never exceed what the machine has.
3745        let online = std::thread::available_parallelism()
3746            .map(|n| n.get())
3747            .unwrap_or(1);
3748        assert!(
3749            n >= online,
3750            "the affinity ({n}) is narrower than what std reports as available ({online}), \
3751             which would make every comparison against it too quiet"
3752        );
3753    }
3754
3755    #[test]
3756    fn a_missing_key_file_is_an_error_not_an_empty_key() {
3757        let err = read_key_argument("@/nonexistent/gunnar/key.pub")
3758            .expect_err("a missing key file must fail");
3759        // An empty string here would reach `bootstrap_admin` and fail there
3760        // with a parse error, but it would also be indistinguishable from "no
3761        // key was asked for" in any caller that checked for emptiness.
3762        assert!(format!("{err:#}").contains("reading the public key"));
3763    }
3764}
3765
3766/// **The front doors' gate chain, in the one order it is ever built** (one implementation):
3767/// the disk-headroom gate first — every build — then, on a `metered` build
3768/// with a monetize key, the entitlement gate. SSH and smart-HTTP take the same
3769/// `Control`, so a push is refused for the same reason on both; and
3770/// `tests/entitlement.rs` builds the chain through this function rather than
3771/// by hand, so what it asserts is the wiring `serve` runs, not a copy of it.
3772pub fn front_control(
3773    stores: &crate::stores::ServerStores,
3774    anonymous: gunnar_ssh::AnonymousPolicy,
3775    disk: Arc<gunnar_ssh::DiskHeadroomGate>,
3776    #[cfg(feature = "metered")] entitlement: Option<&Arc<crate::entitlement::EntitlementSlot>>,
3777) -> gunnar_ssh::Control {
3778    #[allow(unused_mut)]
3779    // **The data set's space ledger** (cov-13): the disk gate's own, so the door
3780    // before the first byte and every receive loop after it count one set of
3781    // promises against one floor. Installed here because this is the one place
3782    // the chain is built.
3783    stores.install_space_ledger(Arc::clone(disk.ledger()));
3784    let control = stores
3785        .ssh_control()
3786        .with_anonymous_policy(anonymous)
3787        .with_plan_gate(disk as Arc<dyn gunnar_ssh::PlanGate>);
3788    #[cfg(feature = "metered")]
3789    let control = match entitlement {
3790        Some(slot) => control.with_plan_gate(Arc::clone(slot) as Arc<dyn gunnar_ssh::PlanGate>),
3791        None => control,
3792    };
3793    // **And the same chain for a mirror's worker** (2026-10-02): a mirror sync
3794    // grows a namespace exactly as a push does, so it is held to the same
3795    // room by the same gates — `mirror_fetch::room_for` reads what is
3796    // installed here. One chain, built in this one place.
3797    stores.install_plan_gates(control.plan_gates().to_vec());
3798    control
3799}
3800
3801/// **The replication door's address, written where `twin certify` reads it**:
3802/// the bound port always; the HOSTS only while a second door is open on the
3803/// tunnel — then `<tunnel>,<utility>`, the twin's order of preference (it
3804/// dials the first that answers and falls back to the next). With no tunnel
3805/// door nothing is recorded and the twin dials the host it was joined to.
3806pub fn record_replication_door(root: &std::path::Path, utility: SocketAddr, tunnel: Option<SocketAddr>) -> Result<()> {
3807    crate::twin_tls::record_replication_port(root, Some(utility.port()))?;
3808    let hosts: Vec<std::net::IpAddr> = match tunnel {
3809        Some(t) => [t.ip(), utility.ip()].into_iter().filter(|ip| !ip.is_unspecified()).collect(),
3810        None => vec![],
3811    };
3812    crate::twin_tls::record_replication_host(root, &hosts)
3813}
3814
3815/// **The mutual replication listener** (owner 2026-09-22, amended 2026-09-24):
3816/// serves on `listener` — the UTILITY address — until the box stops, and opens
3817/// a SECOND door on the tunnel address while there is one
3818/// ([`crate::tunnel_addr::replication_extra`]), closing it when the tunnel
3819/// goes away or moves. The utility door is never taken away: raising wg0
3820/// happens before any handshake, and a tunnel that never answers must not
3821/// cost the twin the path that works.
3822#[allow(clippy::too_many_arguments)]
3823pub async fn replication_door(
3824    listener: tokio::net::TcpListener,
3825    base: SocketAddr,
3826    explicit: bool,
3827    wg_only: bool,
3828    ctx: gunnar_grpc::ServiceContext,
3829    request_ids: gunnar_grpc::RequestIdSource,
3830    trust: gunnar_grpc::Trust,
3831    root: std::path::PathBuf,
3832    stop: tokio::sync::watch::Receiver<bool>,
3833) {
3834    // The door's certificate is the twin's PAIRING: one a principal no longer
3835    // holds (a nuked twin's, superseded when its replacement was certified —
3836    // twin reborn 2026-09-30) is refused here even when a header rides along.
3837    let mut ctx = ctx;
3838    ctx.config = ctx.config.clone().with_registered_client_certificate_required(true);
3839    let serve = move |listener: tokio::net::TcpListener, mut stop: tokio::sync::watch::Receiver<bool>| {
3840        let router = gunnar_grpc::router_with_trust(ctx.clone(), request_ids, Some(&trust));
3841        async move {
3842            let router = match router {
3843                Ok(r) => r,
3844                Err(err) => {
3845                    tracing::error!(%err, "the mutual replication listener could not be configured; no twin can follow this box");
3846                    return;
3847                }
3848            };
3849            let at = listener.local_addr().map(|a| a.to_string()).unwrap_or_default();
3850            let served = router
3851                .serve_with_incoming_shutdown(tokio_stream::wrappers::TcpListenerStream::new(listener), async move {
3852                    let _ = stop.wait_for(|s| *s).await;
3853                })
3854                .await;
3855            if let Err(err) = served {
3856                tracing::error!(%err, %at, "a mutual replication door stopped");
3857            }
3858        }
3859    };
3860    replication_doors_wg(listener, base, explicit, wg_only, root, crate::tunnel_addr::subscribe(), stop, serve).await
3861}
3862
3863/// [`replication_door`]'s rule with the serving and the tunnel watch handed in
3864/// — the tests drive it with a plain accept loop and their own tunnel channel.
3865pub async fn replication_doors<S, F>(
3866    listener: tokio::net::TcpListener,
3867    base: SocketAddr,
3868    explicit: bool,
3869    root: std::path::PathBuf,
3870    tunnel: tokio::sync::watch::Receiver<Option<std::net::Ipv4Addr>>,
3871    stop: tokio::sync::watch::Receiver<bool>,
3872    serve: S,
3873) where
3874    S: Fn(tokio::net::TcpListener, tokio::sync::watch::Receiver<bool>) -> F,
3875    F: std::future::Future<Output = ()> + Send + 'static,
3876{
3877    replication_doors_wg(listener, base, explicit, false, root, tunnel, stop, serve).await
3878}
3879
3880/// [`replication_doors`] under a posture: `wg_only` closes the utility door
3881/// and serves the tunnel's alone ([`doors`]); the twin is told the tunnel host
3882/// only.
3883#[allow(clippy::too_many_arguments)]
3884pub async fn replication_doors_wg<S, F>(
3885    listener: tokio::net::TcpListener,
3886    base: SocketAddr,
3887    explicit: bool,
3888    wg_only: bool,
3889    root: std::path::PathBuf,
3890    tunnel: tokio::sync::watch::Receiver<Option<std::net::Ipv4Addr>>,
3891    stop: tokio::sync::watch::Receiver<bool>,
3892    serve: S,
3893) where
3894    S: Fn(tokio::net::TcpListener, tokio::sync::watch::Receiver<bool>) -> F,
3895    F: std::future::Future<Output = ()> + Send + 'static,
3896{
3897    let record = move |utility: SocketAddr, door: Option<SocketAddr>| {
3898        let at = if wg_only { record_replication_door_wg_only(&root, utility.port(), door) } else { record_replication_door(&root, utility, door) };
3899        if let Err(err) = at {
3900            tracing::error!(%err, "the replication doors changed but their addresses could not be recorded");
3901        }
3902    };
3903    doors(listener, base, wg_only, tunnel, stop, serve, move |b, t| crate::tunnel_addr::replication_extra(b, explicit, t), record, "mutual replication listener").await
3904}
3905
3906/// **The replication door under `--wg-only`, recorded**: the port, and the
3907/// tunnel's address as the ONE host (none while there is no tunnel: the twin
3908/// dials the host it was joined to, the primary's overlay address).
3909pub fn record_replication_door_wg_only(root: &std::path::Path, port: u16, tunnel: Option<SocketAddr>) -> Result<()> {
3910    crate::twin_tls::record_replication_port(root, Some(port))?;
3911    let hosts: Vec<std::net::IpAddr> = tunnel.map(|t| t.ip()).into_iter().collect();
3912    crate::twin_tls::record_replication_host(root, &hosts)
3913}
3914
3915/// **The control plane's doors** (`:50051`). Not `wg_only`: the listener as
3916/// bound serves for the process lifetime, as it always has. `wg_only` (owner,
3917/// 2026-10-04): the bound — utility — listener is CLOSED, so a plain-IP
3918/// connection is refused by the kernel, and a door on the tunnel's address,
3919/// same port, serves while there is a tunnel ([`doors`]).
3920pub async fn control_doors<S, F>(
3921    listener: tokio::net::TcpListener,
3922    base: SocketAddr,
3923    wg_only: bool,
3924    tunnel: tokio::sync::watch::Receiver<Option<std::net::Ipv4Addr>>,
3925    stop: tokio::sync::watch::Receiver<bool>,
3926    serve: S,
3927) where
3928    S: Fn(tokio::net::TcpListener, tokio::sync::watch::Receiver<bool>) -> F,
3929    F: std::future::Future<Output = ()> + Send + 'static,
3930{
3931    doors(listener, base, wg_only, tunnel, stop, serve, |_, _| None, |_, _| {}, "control plane").await
3932}
3933
3934/// **One rule for a listener and the tunnel**, shared by the replication
3935/// listener and the control plane.
3936///
3937/// * not `wg_only`: `listener` (the utility address) serves until `stop`;
3938///   `extra` names a SECOND door on the tunnel while there is one (the
3939///   replication rule, [`crate::tunnel_addr::replication_extra`]) or none;
3940/// * `wg_only`: `listener` is CLOSED at once — nothing serves on the utility
3941///   address, and the kernel refuses a plain-IP connection — and a door on the
3942///   tunnel's address, same port, serves while there is a tunnel, moving with
3943///   it.
3944///
3945/// `record` hears every change: `(the utility address, the tunnel door)`.
3946#[allow(clippy::too_many_arguments)]
3947pub async fn doors<S, F, X, R>(
3948    listener: tokio::net::TcpListener,
3949    base: SocketAddr,
3950    wg_only: bool,
3951    mut tunnel: tokio::sync::watch::Receiver<Option<std::net::Ipv4Addr>>,
3952    mut stop: tokio::sync::watch::Receiver<bool>,
3953    serve: S,
3954    extra: X,
3955    mut record: R,
3956    what: &'static str,
3957) where
3958    S: Fn(tokio::net::TcpListener, tokio::sync::watch::Receiver<bool>) -> F,
3959    F: std::future::Future<Output = ()> + Send + 'static,
3960    X: Fn(SocketAddr, Option<std::net::Ipv4Addr>) -> Option<SocketAddr>,
3961    R: FnMut(SocketAddr, Option<SocketAddr>),
3962{
3963    // The port actually bound (a `:0` bind in a test picks one).
3964    let port = listener.local_addr().map(|a| a.port()).unwrap_or(base.port());
3965    let base = SocketAddr::new(base.ip(), port);
3966    let utility = if wg_only {
3967        drop(listener);
3968        tracing::warn!(%base, "{what}: --wg-only — the utility door is CLOSED; it answers only on the WireGuard tunnel's address");
3969        None
3970    } else {
3971        Some(tokio::spawn(serve(listener, stop.clone())))
3972    };
3973    // The open tunnel door: its address and the switch that closes it.
3974    let mut door: Option<(SocketAddr, tokio::sync::watch::Sender<bool>)> = None;
3975    let mut first = true;
3976    loop {
3977        let t = *tunnel.borrow_and_update();
3978        let want = if wg_only { t.map(|t| SocketAddr::new(std::net::IpAddr::V4(t), port)) } else { extra(base, t) };
3979        if first || door.as_ref().map(|(a, _)| *a) != want {
3980            first = false;
3981            if let Some((at, close)) = door.take() {
3982                let _ = close.send(true);
3983                if wg_only {
3984                    tracing::warn!(%at, "{what}: the tunnel went away or moved: its door is closed, and with --wg-only nothing serves until it is back");
3985                } else {
3986                    tracing::warn!(%at, "{what}: the tunnel went away or moved: the door on it is closed; the utility door {base} keeps serving");
3987                }
3988            }
3989            if let Some(at) = want {
3990                match tokio::net::TcpListener::bind(at).await {
3991                    Ok(l) => {
3992                        let (close, closed) = tokio::sync::watch::channel(false);
3993                        tokio::spawn(serve(l, closed));
3994                        if wg_only {
3995                            tracing::info!(%at, "{what}: up on the WireGuard tunnel's address, and only there (--wg-only)");
3996                        } else {
3997                            tracing::warn!(%at, %base, "{what} ALSO on the tunnel's address (no restart); the utility door stays");
3998                        }
3999                        door = Some((at, close));
4000                    }
4001                    Err(err) => tracing::error!(%err, %at, "{what}: the tunnel's door could not bind"),
4002                }
4003            }
4004            record(base, door.as_ref().map(|(a, _)| *a));
4005        }
4006        tokio::select! {
4007            _ = async { let _ = stop.wait_for(|s| *s).await; } => break,
4008            changed = tunnel.changed() => {
4009                if changed.is_err() {
4010                    let _ = stop.wait_for(|s| *s).await;
4011                    break;
4012                }
4013            }
4014        }
4015    }
4016    if let Some((_, close)) = door.take() {
4017        let _ = close.send(true);
4018    }
4019    if let Some(u) = utility {
4020        let _ = u.await;
4021    }
4022}
4023
4024#[cfg(test)]
4025mod replication_door_tests {
4026    use super::*;
4027    use std::net::Ipv4Addr;
4028    use tokio::io::AsyncWriteExt as _;
4029
4030    /// A door that answers every connection with one byte, until closed.
4031    async fn answering(listener: tokio::net::TcpListener, mut stop: tokio::sync::watch::Receiver<bool>) {
4032        loop {
4033            tokio::select! {
4034                _ = async { let _ = stop.wait_for(|s| *s).await; } => return,
4035                got = listener.accept() => if let Ok((mut c, _)) = got { let _ = c.write_all(b"R").await; },
4036            }
4037        }
4038    }
4039
4040    /// Does a door answer at `at`? A closed one refuses at once; the 10 s bounds are hang guards
4041    /// for a door that accepted and never wrote, long enough that a loaded box's slow answer is
4042    /// still an answer (2 s was not, at load 16 under `nice`).
4043    async fn answers(at: SocketAddr) -> bool {
4044        use tokio::io::AsyncReadExt as _;
4045        let Ok(Ok(mut c)) = tokio::time::timeout(std::time::Duration::from_secs(10), tokio::net::TcpStream::connect(at)).await else { return false };
4046        let mut b = [0u8; 1];
4047        matches!(tokio::time::timeout(std::time::Duration::from_secs(10), c.read_exact(&mut b)).await, Ok(Ok(_)))
4048    }
4049
4050    async fn settle() {
4051        tokio::time::sleep(std::time::Duration::from_millis(150)).await;
4052    }
4053
4054    /// **Wait for the doors to act**, not for a fixed time (R5.1, 2026-10-07). The doors act on a
4055    /// change when their task next runs, and on a loaded box (load 32 on dwarf) that was not
4056    /// within the 150 ms `settle` these asserts used to trust: "the tunnel door answers" failed
4057    /// with the door about to open. `cond` is asked every 20 ms until it holds; the two minutes
4058    /// are a hang guard (a test that takes under a second alone took 30 s and more at load 16
4059    /// under `nice`), so only a door that never acts fails.
4060    async fn eventually<F, Fut>(mut cond: F) -> bool
4061    where
4062        F: FnMut() -> Fut,
4063        Fut: std::future::Future<Output = bool>,
4064    {
4065        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
4066        loop {
4067            if cond().await {
4068                return true;
4069            }
4070            if std::time::Instant::now() >= deadline {
4071                return false;
4072            }
4073            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4074        }
4075    }
4076
4077    /// **WireGuard-only (owner 2026-10-04)**: the utility door is CLOSED — a
4078    /// plain-IP connection to the utility address is refused — and only the
4079    /// tunnel door answers, recorded as the one host the twin is told.
4080    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4081    async fn under_wg_only_the_utility_door_is_closed_and_only_the_tunnel_door_answers() {
4082        let dir = tempfile::tempdir().unwrap();
4083        let root = dir.path().to_path_buf();
4084        let utility = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4085        let base = utility.local_addr().unwrap();
4086        let (tunnel_tx, tunnel_rx) = tokio::sync::watch::channel(None::<Ipv4Addr>);
4087        let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
4088        let doors = tokio::spawn(replication_doors_wg(utility, base, false, true, root.clone(), tunnel_rx, stop_rx, answering));
4089        let refused = |at: SocketAddr| async move { matches!(tokio::net::TcpStream::connect(at).await, Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused) };
4090
4091        assert!(eventually(|| refused(base)).await, "no tunnel: the utility door is closed, not served");
4092        assert_eq!(crate::twin_tls::replication_host(&root), None);
4093
4094        let t = Ipv4Addr::new(127, 0, 0, 2);
4095        tunnel_tx.send_replace(Some(t));
4096        let on_tunnel = SocketAddr::new(t.into(), base.port());
4097        assert!(eventually(|| answers(on_tunnel)).await, "the tunnel door answers");
4098        assert!(eventually(|| refused(base)).await, "and a plain-IP connection is refused");
4099        assert!(
4100            eventually(|| std::future::ready(crate::twin_tls::replication_host(&root).as_deref() == Some("127.0.0.2"))).await,
4101            "the twin is told the tunnel alone: {:?}",
4102            crate::twin_tls::replication_host(&root)
4103        );
4104
4105        // The CONTROL PLANE follows the same rule on its own port.
4106        let control = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4107        let cbase = control.local_addr().unwrap();
4108        let (_ctx, crx) = tokio::sync::watch::channel(Some(t));
4109        let (cstop_tx, cstop_rx) = tokio::sync::watch::channel(false);
4110        let cdoors = tokio::spawn(control_doors(control, cbase, true, crx, cstop_rx, answering));
4111        assert!(eventually(|| answers(SocketAddr::new(t.into(), cbase.port()))).await, "the control plane answers on the tunnel");
4112        assert!(eventually(|| refused(cbase)).await, "and refuses the plain IP");
4113
4114        stop_tx.send_replace(true);
4115        cstop_tx.send_replace(true);
4116        tokio::time::timeout(std::time::Duration::from_secs(5), doors).await.expect("the doors stop").unwrap();
4117        tokio::time::timeout(std::time::Duration::from_secs(5), cdoors).await.expect("the control doors stop").unwrap();
4118    }
4119
4120    /// Fix 2026-09-24: raising the tunnel no longer MOVES the replication
4121    /// listener off the utility address. With the tunnel down, not bindable, up,
4122    /// and gone again, the utility door answers throughout; the tunnel door is
4123    /// an addition, recorded `<tunnel>,<utility>` only while it is open.
4124    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4125    async fn the_utility_door_answers_whatever_the_tunnel_does() {
4126        let dir = tempfile::tempdir().unwrap();
4127        let root = dir.path().to_path_buf();
4128        let utility = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4129        let base = utility.local_addr().unwrap();
4130        let (tunnel_tx, tunnel_rx) = tokio::sync::watch::channel(None::<Ipv4Addr>);
4131        let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
4132        let doors = tokio::spawn(replication_doors(utility, base, false, root.clone(), tunnel_rx, stop_rx, answering));
4133
4134        // Tunnel down: the utility door answers, no host recorded.
4135        assert!(eventually(|| answers(base)).await);
4136        assert!(
4137            eventually(|| std::future::ready(crate::twin_tls::replication_port(&root) == Some(base.port()))).await,
4138            "the twin is told the utility port: {:?}",
4139            crate::twin_tls::replication_port(&root)
4140        );
4141        assert_eq!(crate::twin_tls::replication_host(&root), None);
4142
4143        // A tunnel address this box cannot bind (raised elsewhere / not yet on
4144        // the interface): the utility door still answers.
4145        tunnel_tx.send_replace(Some(Ipv4Addr::new(10, 254, 254, 254)));
4146        settle().await;
4147        assert!(eventually(|| answers(base)).await, "a tunnel door that cannot bind must not cost the utility door");
4148        assert_eq!(crate::twin_tls::replication_host(&root), None);
4149
4150        // Tunnel up: BOTH answer; the twin is told tunnel first, utility next.
4151        let t = Ipv4Addr::new(127, 0, 0, 2);
4152        tunnel_tx.send_replace(Some(t));
4153        let on_tunnel = SocketAddr::new(t.into(), base.port());
4154        assert!(eventually(|| answers(on_tunnel)).await, "the tunnel door answers");
4155        assert!(answers(base).await, "and the utility door still does");
4156        assert!(
4157            eventually(|| std::future::ready(crate::twin_tls::replication_host(&root).as_deref() == Some("127.0.0.2,127.0.0.1"))).await,
4158            "the twin is told tunnel first, utility next: {:?}",
4159            crate::twin_tls::replication_host(&root)
4160        );
4161
4162        // Tunnel gone: its door closes, the utility door stays.
4163        tunnel_tx.send_replace(None);
4164        assert!(eventually(|| async move { !answers(on_tunnel).await }).await, "the tunnel door is closed");
4165        assert!(answers(base).await);
4166        assert!(
4167            eventually(|| std::future::ready(crate::twin_tls::replication_host(&root).is_none())).await,
4168            "no host once the tunnel is gone: {:?}",
4169            crate::twin_tls::replication_host(&root)
4170        );
4171
4172        stop_tx.send_replace(true);
4173        tokio::time::timeout(std::time::Duration::from_secs(5), doors).await.expect("the doors stop").unwrap();
4174    }
4175}