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