gunnar-server 2.0.0

The gunnar git server: SSH and smart-HTTP git transports and the gRPC control plane. The appliance half, extracted from gunnar-cli so the server code lives in its own crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! **The estate values the installer's door FEEDS**, taken instead of the
//! medium's — so one medium serves any estate.
//!
//! The join reply the pairing loop receives carries a `feed` table
//! (`nordisk_pairing::join::JoinReply::feed`); the loop persists the whole
//! reply to `<data>/pairing/joined.toml` ([`crate::pairing::JOINED_REL`]).
//! Three of its keys configure this box:
//!
//! | key               | what it replaces on the medium                       | applied            |
//! |-------------------|------------------------------------------------------|--------------------|
//! | `monetize_pubkey` | `GUNNAR_MONETIZE_PUBKEY` / `--monetize-pubkey`        | at start, or LIVE when it arrives |
//! | `clock_key`       | `ESTATE_CLOCK_KEY` / `GUNNAR_CLOCK_KEY` (`korp.env.` / `clock_key=` param) | on every clock sync|
//! | `clock_peer`      | `ESTATE_CLOCK` / `GUNNAR_CLOCK` (`korp.env.` / `clock=` param)         | on every clock sync|
//!
//! (`admin_pubkey` is the fourth feed key; the pairing loop installs it itself.)
//!
//! # Precedence: there is none — a disagreement is REFUSED by name
//!
//! Medium alone → the medium's. Door alone → the door's. Both and EQUAL →
//! that value. Both and DIFFERENT → [`FEED_MISMATCH`], never a silent pick:
//! the medium and the installer disagree about which estate this box is in,
//! and choosing either one is choosing whose money or whose time to trust
//! without saying so (the reasoning of ops' `monetize-pubkey-mismatch`
//! preflight, which refuses a bring-up over the same disagreement).
//!
//! * The monetize key at start: a refusal to start ([`resolve_monetize`]).
//! * The monetize key arriving while running (first boot): the key in force
//!   stays, the `Admin.Health` alarm [`FEED_MISMATCH`] is raised.
//! * The clock: every sync reads the effective configuration
//!   ([`clock_config`]), and a disagreement is the sync's `misconfigured`
//!   report naming [`FEED_MISMATCH`] — the clock is left alone.
//!
//! # The monetize key applies LIVE (owner 2026-09-25: avoid restarts)
//!
//! A metered box on a `fed` medium starts KEYLESS: its entitlement slot and
//! its growth go-ahead policy are built with no key (every namespace Free,
//! `Entitlement.Set` refused, a `monetize` go-ahead refused) and registered
//! as takers ([`on_monetize_key`]). When the installer feeds the key (or vm1
//! offers it), [`monetize_arrived`] hands it to each taker, which swaps it in
//! place — the slot re-verifies every stored fact under it — and the key is
//! persisted in `joined.toml` for the next start as before. Until 2026-09-25
//! this was a restart of the machine. The clock (`clock_key`, `clock_peer`)
//! and the fed principals were already live: the clock reads the feed on
//! every sync, and the primary installs principals on every feed.
//!
//! # The bus is the shared one (L10, 2026-10-20)
//!
//! Every feed this process takes is published on nordisk-pairing's process-wide
//! feed bus ([`feedbus::publish`], Skidbladnir 0.5.15, A7 row 8): a part that
//! applies a fed value LIVE subscribes with [`feedbus::on_published`] and reads
//! the typed [`Fed::from_feed`]; [`Fed::current`] is the typed view of the
//! value in force. Gunnar's own bus (this module's `publish`, `on_published`,
//! `current`) is gone; this module is the typed view over the shared one.

use std::path::Path;
use std::sync::{Mutex, OnceLock, RwLock};

use nordisk_pairing::feedbus::{self, Feed};

/// The relay a sold estate's main mails through, as the shop feeds it (monetize-server
/// `estate_order::FEED_SMTP_*`, P1).
pub const FEED_SMTP_URL: &str = "secret.smtp_url";
/// **The front's egress door** (Skidbladnir nordisk-pairing `egress::FEED_EGRESS`, the lean
/// estate, A19): fed by the shop to a box laid with no public IPv4. The box's clients that
/// reach the internet (the identity provider's, the webhooks', the mirrors', the mail relay's)
/// leave through it ([`take_egress`], `nordisk_pairing::egress::proxy`).
pub const FEED_EGRESS: &str = nordisk_pairing::egress::FEED_EGRESS;
pub const FEED_SMTP_FROM: &str = "secret.smtp_from";

/// The feed keys this module reads (the contract's names; never renamed).
pub const FEED_MONETIZE: &str = "monetize_pubkey";
pub const FEED_CLOCK_KEY: &str = "clock_key";
pub const FEED_CLOCK_PEER: &str = "clock_peer";
/// **The operator's internal networks a company IdP may live on** (owner
/// 2026-10-06, a private gunnar): a list of CIDRs, estate config the
/// installer feeds; never an account admin's. Empty or absent: today's guard
/// (`gunnar_grpc::sso::PrivateNets`). Applied LIVE on every feed.
pub const FEED_SSO_PRIVATE_IDP_CIDRS: &str = "sso_private_idp_cidrs";
/// **This estate SELLS room** (2026-10-08): `true` on a selling shop's boxes (gunnar.rs,
/// test2), absent everywhere else — a SOLD estate and the open build keep "no fact is
/// uncapped". Applied LIVE ([`Fed::sells_room`], gunnar-grpc `selling`).
pub const FEED_SELLS_ROOM: &str = "sells_room";
/// **The ONE monetize's `Fleet` door** (5.4, ONE monetize, M-D35): what `--fleet` names on
/// the medium. shop-pairing feeds it to the front, the front offers it to every box; the
/// box's pull channel reports there ([`crate::repair::resolve_fleet`]).
pub const FEED_FLEET: &str = "fleet";
/// **The estate this box reports for** (`--fleet-instance`), fed beside [`FEED_FLEET`].
pub const FEED_FLEET_INSTANCE: &str = "fleet_instance";
/// **Where the pull channel connects** (`host:port`), fed beside [`FEED_FLEET`] when the
/// door's name is not what this box should dial (a test bench whose guests resolve no
/// names). TLS still verifies the certificate under [`FEED_FLEET`]'s host. Absent: the
/// URL's own host, resolved. A BENCH address only (ST-19, [`crate::repair::seam_refusal`]).
pub const FEED_FLEET_AT: &str = "fleet_at";
/// **The PEM the pull channel's door is checked against**, fed beside [`FEED_FLEET`] when
/// its certificate is not under the public roots. Absent: the public roots. Only beside a
/// bench [`FEED_FLEET_AT`] (ST-19).
pub const FEED_FLEET_CA: &str = "fleet_ca";

/// **The SITE's pay page** (UW-6, feed key `refusal_link`: the open build names no money): a `{tenant}` template, `https://<site>/billing/{tenant}`
/// — a page the site's own console serves. The medium is one for every estate, so the
/// page it bakes (`--billing-url`) is a placeholder this replaces, LIVE
/// ([`crate::entitlement::EntitlementSlot::set_billing_url`]).
pub const FEED_BILLING_URL: &str = "refusal_link";
/// **Auto-fix, fed** (main rebuild, 2026-10-12): exactly `true` turns the box's auto-fix on,
/// as `--repair-auto` does. The estate's opt-in, carried by its installer; nothing else
/// changes what the guard allows (`gunnar_repair::rebuild`).
pub const FEED_REPAIR_AUTO: &str = "repair_auto";
/// **The repair key, fed** (main rebuild, 2026-10-12): an OpenSSH private key this box signs
/// its repair calls with when no `--repair-key` is given — a re-laid main holds no twin key,
/// and without one every pulled order and the auto recharge were refused. The installer
/// feeds its public half as a principal, so the twin reads its log to it and a fresh main
/// takes its `Bootstrap.Restore`.
pub const FEED_REPAIR_KEY: &str = "secret.repair_key";

/// The alarm/refusal word for a medium value and a DIFFERENT fed value.
pub const FEED_MISMATCH: &str = "pairing.feed_mismatch";
/// The alarm for a fed monetize key this running process could not apply
/// (no entitlement slot to apply it to, or a taker refused it). It used to be
/// `pairing.feed_restart` and a reboot; the key is applied live now.
pub const FEED_NOT_APPLIED: &str = "pairing.feed_not_applied";

/// **`vm`'s offer of `key`** (`offer.<vm>.<key>`), trimmed; blank is absent.
pub fn offered_by<'a>(feed: &'a std::collections::BTreeMap<String, String>, vm: &str, key: &str) -> Option<&'a str> {
    feed.get(&format!("offer.{vm}.{key}")).map(|v| v.trim()).filter(|v| !v.is_empty())
}

/// What the door fed, as far as this box's configuration goes.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Fed {
    pub monetize_pubkey: Option<String>,
    pub clock_key: Option<String>,
    pub clock_peer: Option<String>,
    /// [`FEED_SSO_PRIVATE_IDP_CIDRS`], as fed.
    pub sso_private_idp_cidrs: Option<String>,
    /// [`FEED_SELLS_ROOM`]: exactly `true`, as fed; anything else is false.
    pub sells_room: bool,
    /// [`FEED_FLEET`], as fed.
    pub fleet: Option<String>,
    /// [`FEED_FLEET_INSTANCE`], as fed.
    pub fleet_instance: Option<String>,
    /// [`FEED_FLEET_AT`], as fed.
    pub fleet_at: Option<String>,
    /// [`FEED_FLEET_CA`], as fed.
    pub fleet_ca: Option<String>,
    /// [`FEED_SMTP_URL`], as fed: the relay a SOLD estate's main mails through (P1). Its
    /// `Debug` withholds it (it carries the submission token).
    pub smtp_url: Option<Withheld>,
    /// [`FEED_SMTP_FROM`], as fed.
    pub smtp_from: Option<String>,
    /// [`FEED_BILLING_URL`], as fed.
    pub billing_url: Option<String>,
    /// [`FEED_REPAIR_AUTO`]: exactly `true`, as fed; anything else is false.
    pub repair_auto: bool,
    /// [`FEED_REPAIR_KEY`], as fed (withheld from `Debug`).
    pub repair_key: Option<Withheld>,
    /// [`FEED_EGRESS`], as fed: an `http://` door only.
    pub egress: Option<String>,
}

/// A fed value that is a credential: kept, compared, never shown.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Withheld(pub String);

impl std::fmt::Debug for Withheld {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("<withheld>")
    }
}

impl Fed {
    /// From the reply's `feed` table. Blank values are absent. A value the
    /// installer does not feed itself may reach this box as a VM's OFFER,
    /// fed onward as `offer.<vm>.<key>` (edda nordisk-pairing 0.3.1; since
    /// 0.4 the front's keys — monetize's verifying key, the clock key — come
    /// that way): the plain key wins, then the first offer by VM name.
    pub fn from_feed(feed: &std::collections::BTreeMap<String, String>) -> Fed {
        let get = |k: &str| feed.get(k).map(|v| v.trim().to_string()).filter(|v| !v.is_empty()).or_else(|| nordisk_pairing::feedbus::offered(feed, k));
        Fed {
            monetize_pubkey: get(FEED_MONETIZE),
            clock_key: get(FEED_CLOCK_KEY),
            clock_peer: get(FEED_CLOCK_PEER),
            sso_private_idp_cidrs: get(FEED_SSO_PRIVATE_IDP_CIDRS),
            sells_room: get(FEED_SELLS_ROOM).as_deref() == Some("true"),
            fleet: get(FEED_FLEET),
            fleet_instance: get(FEED_FLEET_INSTANCE),
            fleet_at: get(FEED_FLEET_AT),
            fleet_ca: get(FEED_FLEET_CA),
            smtp_url: get(FEED_SMTP_URL).map(Withheld),
            smtp_from: get(FEED_SMTP_FROM),
            billing_url: get(FEED_BILLING_URL),
            repair_auto: get(FEED_REPAIR_AUTO).as_deref() == Some("true"),
            repair_key: get(FEED_REPAIR_KEY).map(Withheld),
            egress: get(FEED_EGRESS).filter(|d| d.starts_with("http://")),
        }
    }

    pub fn is_empty(&self) -> bool {
        self == &Fed::default()
    }

    /// `<data>/pairing/joined.toml`, if the loop has persisted one. Absent is
    /// `None`; present and unreadable is an error — a persisted answer that
    /// lies must not be quietly ignored.
    pub fn read(root: &Path) -> anyhow::Result<Option<Fed>> {
        Ok(kept_feed(root)?.as_ref().map(Fed::from_feed))
    }

    /// **The typed view of the feed in force** on the shared bus
    /// (nordisk-pairing [`feedbus::current`]); `None` before anything was published.
    pub fn current() -> Option<Fed> {
        feedbus::current().map(|feed| Fed::from_feed(&feed))
    }
}

/// **This box leaves through the door it was fed** ([`FEED_EGRESS`]): kept process-wide
/// (`nordisk_pairing::egress::set_proxy`, the first wins: the door is the front's overlay
/// address, the same for the life of the estate) for every client that reaches the internet.
/// Called with each feed published (`serve`); a feed with no door changes nothing.
pub fn take_egress(feed: &std::collections::BTreeMap<String, String>) {
    if let Some(door) = Fed::from_feed(feed).egress {
        if nordisk_pairing::egress::proxy().is_none() {
            tracing::info!(target: "gunnar::audit", event = "egress_door", door = %door, "this box leaves through its front's egress door (no public IPv4 of its own)");
        }
        nordisk_pairing::egress::set_proxy(&door);
    }
}

/// The proxy a ureq client of this box is built with: the fed door ([`take_egress`]), or none.
#[cfg(any(feature = "mirror-http", feature = "sso-egress"))]
pub fn ureq_proxy() -> Option<ureq::Proxy> {
    nordisk_pairing::egress::proxy().and_then(|d| ureq::Proxy::new(d).ok())
}

/// The feed of `<data>/pairing/joined.toml`, as the door fed it ([`Fed::read`]).
#[cfg(feature = "wg-client")]
pub fn kept_feed(root: &Path) -> anyhow::Result<Option<Feed>> {
    let p = root.join(crate::pairing::JOINED_REL);
    let Some(text) = crate::fed_at_rest::read_checked(root, crate::pairing::JOINED_REL)? else { return Ok(None) };
    let reply = nordisk_pairing::join::JoinReply::parse(&text).map_err(|e| anyhow::anyhow!("{}: {e}", p.display()))?;
    Ok(Some(reply.feed))
}

/// A build without the pairing loop has no door to be fed by.
#[cfg(not(feature = "wg-client"))]
pub fn kept_feed(_root: &Path) -> anyhow::Result<Option<Feed>> {
    Ok(None)
}

/// **The operator's internal networks a company IdP may live on**, as `fed`
/// names them: none when nothing is fed. A list gunnar refuses (a public or
/// loopback range) is an error, said by the caller and applied as none.
pub fn sso_private_nets(fed: Option<&Fed>) -> Result<gunnar_grpc::sso::PrivateNets, String> {
    match fed.and_then(|f| f.sso_private_idp_cidrs.as_deref()) {
        Some(text) => gunnar_grpc::sso::PrivateNets::parse(text).map_err(|why| format!("`{FEED_SSO_PRIVATE_IDP_CIDRS}`: {why}")),
        None => Ok(gunnar_grpc::sso::PrivateNets::default()),
    }
}

/// Read `joined.toml` under `root` and publish its feed on the shared bus
/// ([`feedbus::publish`]). Called once at start; an unreadable file is logged
/// and treated as no feed (the loop re-joins and rewrites it).
pub fn load_at_start(root: &Path) -> Option<Fed> {
    match kept_feed(root) {
        Ok(Some(feed)) => {
            let fed = Fed::from_feed(&feed);
            if !fed.is_empty() {
                tracing::info!(monetize = fed.monetize_pubkey.is_some(), clock_peer = ?fed.clock_peer, clock_key = fed.clock_key.is_some(), "feed: the installer's values from {}", "<data>/pairing/joined.toml");
            }
            feedbus::publish(feed);
            Some(fed)
        }
        Ok(None) => None,
        Err(e) => {
            tracing::error!(error = %format!("{e:#}"), "feed: the persisted join reply is unreadable — this start uses the medium's values only");
            None
        }
    }
}

// ── the monetize key ────────────────────────────────────────────────────────

/// The key the running server enforces with: recorded at start (outer `None`
/// = nothing recorded, e.g. a test), and moved ONCE more when an awaited key
/// arrives and is applied live ([`monetize_arrived`]).
fn in_force_slot() -> &'static RwLock<Option<Option<[u8; 32]>>> {
    static IN_FORCE: OnceLock<RwLock<Option<Option<[u8; 32]>>>> = OnceLock::new();
    IN_FORCE.get_or_init(|| RwLock::new(None))
}

pub fn record_monetize_in_force(key: Option<[u8; 32]>) {
    if let Ok(mut s) = in_force_slot().write() {
        *s = Some(key);
    }
}

pub fn monetize_in_force() -> Option<[u8; 32]> {
    in_force_slot().read().ok().and_then(|s| s.flatten())
}

/// Something that takes the monetize key LIVE: the entitlement slot (both
/// front doors' plan gate and `Entitlement.Set` read it) and the growth
/// go-ahead policy. Registered by `serve` once each is built.
pub type MonetizeTaker = Box<dyn Fn(&[u8; 32]) -> Result<(), String> + Send + Sync>;

fn takers() -> &'static Mutex<Vec<(&'static str, MonetizeTaker)>> {
    static TAKERS: OnceLock<Mutex<Vec<(&'static str, MonetizeTaker)>>> = OnceLock::new();
    TAKERS.get_or_init(|| Mutex::new(Vec::new()))
}

/// **Register a taker of the monetize key** (owner 2026-09-25: avoid
/// restarts) — called by `serve` for the entitlement slot and the go-ahead
/// policy it built keyless, so a key the installer feeds later is applied in
/// place by [`monetize_arrived`].
pub fn on_monetize_key(name: &'static str, take: MonetizeTaker) {
    if let Ok(mut t) = takers().lock() {
        t.push((name, take));
    }
}

fn hex(k: &[u8; 32]) -> String {
    k.iter().map(|b| format!("{b:02x}")).collect()
}

/// **The monetize key at start.** `medium` is the resolved key off
/// `--monetize-pubkey`/`GUNNAR_MONETIZE_PUBKEY`; `fed` is the door's spelling
/// (64 hex). A fed value that is not a key, or that differs from the
/// medium's, is refused by name.
pub fn resolve_monetize(medium: Option<[u8; 32]>, fed: Option<&str>) -> Result<Option<[u8; 32]>, String> {
    let fed = match fed {
        None => return Ok(medium),
        Some(text) => gunnar_common::monetize_key::parse_hex32(text.trim()).map_err(|why| {
            format!("REFUSED [pairing-feed-monetize-malformed] the installer fed `{FEED_MONETIZE}` = `{text}`, which is not a monetize key: {why}")
        })?,
    };
    match medium {
        None => Ok(Some(fed)),
        Some(m) if m == fed => Ok(Some(m)),
        Some(m) => Err(format!(
            "REFUSED [{FEED_MISMATCH}] the medium trusts monetize key {} and the installer's door fed {} — \
             this box will not pick one silently. Compose the medium without `monetize_pubkey` (the door \
             feeds it), or with the front's live key",
            hex(&m),
            hex(&fed)
        )),
    }
}

/// Why a fed monetize key found no taker, in the words THIS build can say.
///
/// The metered build names the flag that opens the slot. The open build has no
/// such flag (`--billing-url` is declared in `entitlement.rs`, which is
/// `metered`-only) and must not compile the word into anything an operator can
/// read — `tests/open_build_speaks_no_money.rs::the_open_sources_say_no_money`,
/// the owner's ruling of 2026-09-15. Before this split the open build carried
/// the metered sentence verbatim and the guard was red on it (feed.rs:243).
#[cfg(feature = "metered")]
const NO_TAKER_WHY: &str = "the metered start opened no entitlement slot (no --billing-url on a `fed` medium)";
#[cfg(not(feature = "metered"))]
const NO_TAKER_WHY: &str = "this build carries no entitlement module, so no start opens a slot to take it";

/// **The fed monetize key arriving while running** (the pairing loop's
/// answer, or vm1's offer carried by the installer): APPLIED IN PLACE by every
/// registered taker ([`on_monetize_key`]), with no restart (owner 2026-09-25).
/// `None` = nothing to do (no key fed, the same key already in force, or a
/// process that recorded none — a community build or a test).
pub fn monetize_arrived(fed: Option<&str>) -> Option<MonetizeArrival> {
    let in_force = in_force_slot().read().ok().and_then(|s| *s)?;
    let fed = fed?;
    match resolve_monetize(in_force, Some(fed)) {
        Ok(Some(k)) if Some(k) == in_force => None,
        Ok(Some(k)) => {
            let takers = takers().lock().ok()?;
            if takers.is_empty() {
                let detail = format!(
                    "the installer fed monetize key {} and nothing on this box can enforce it: {NO_TAKER_WHY}",
                    hex(&k)
                );
                raise(FEED_NOT_APPLIED, &detail);
                return Some(MonetizeArrival::NotApplied(detail));
            }
            let failed: Vec<String> = takers.iter().filter_map(|(name, take)| take(&k).err().map(|e| format!("{name}: {e}"))).collect();
            if !failed.is_empty() {
                let detail = format!("the installer fed monetize key {}, and it could not be applied: {}", hex(&k), failed.join("; "));
                raise(FEED_NOT_APPLIED, &detail);
                return Some(MonetizeArrival::NotApplied(detail));
            }
            record_monetize_in_force(Some(k));
            let detail = format!("the installer fed monetize key {}; it is IN FORCE now (applied in place, no restart)", hex(&k));
            tracing::info!(event = "pairing.feed_applied", "feed: {detail}");
            Some(MonetizeArrival::Applied(detail))
        }
        Ok(None) => None,
        Err(why) => {
            raise(FEED_MISMATCH, &why);
            Some(MonetizeArrival::Mismatch(why))
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MonetizeArrival {
    /// The server started with no key; the fed one is enforced from now on.
    Applied(String),
    /// The server started with no key and cannot take the fed one: alarmed.
    NotApplied(String),
    /// The medium's key is in force and the door fed another: refused, alarmed.
    Mismatch(String),
}

// ── the clock ───────────────────────────────────────────────────────────────

/// **The clock's two values**, medium against door — edda estate-clock's
/// (`offer::resolve_clock`, moved there from here AS IS; the refusal names
/// [`FEED_MISMATCH`], the same word). `Ok((clock, key))` is what
/// [`estate_clock::config::Config::parse`] is handed.
pub use estate_clock::offer::resolve_clock;

/// **The clock configuration in force now**: the process environment (the
/// medium's `korp.env.ESTATE_CLOCK*`, or Gunnar's `korp.env.GUNNAR_CLOCK*`
/// read as its alias, `estate_clock::config::var`) merged with the current
/// feed. Read on EVERY sync, so a feed that arrives while running applies to
/// the next one.
pub fn clock_config() -> Result<estate_clock::config::Config, String> {
    use estate_clock::config::{var, Config, Role, CLOCK_ENV, CLOCK_KEY_ENV};
    let env_clock = var(CLOCK_ENV);
    let env_key = var(CLOCK_KEY_ENV);
    let fed = Fed::current().unwrap_or_default();
    let (clock, key) = resolve_clock(env_clock.as_deref(), env_key.as_deref(), fed.clock_peer.as_deref(), fed.clock_key.as_deref())?;
    Config::parse(clock.as_deref(), key.as_deref(), Role::Appliance)
}

/// Whether the door fed a clock source.
pub fn clock_fed() -> bool {
    Fed::current().is_some_and(|f| f.clock_peer.is_some())
}

// ── alarms ──────────────────────────────────────────────────────────────────

fn alarm_slot() -> &'static Mutex<Vec<gunnar_proto::HealthAlarm>> {
    static ALARMS: OnceLock<Mutex<Vec<gunnar_proto::HealthAlarm>>> = OnceLock::new();
    ALARMS.get_or_init(|| Mutex::new(Vec::new()))
}

/// Raise (or re-raise, counting) a feed alarm; said on the log too.
pub fn raise(event: &str, detail: &str) {
    tracing::error!(event, "feed: {detail}");
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0);
    if let Ok(mut alarms) = alarm_slot().lock() {
        match alarms.iter_mut().find(|a| a.event == event) {
            Some(a) => {
                a.count += 1;
                a.detail = detail.to_string();
            }
            None => alarms.push(gunnar_proto::HealthAlarm { event: event.into(), count: 1, since_unix_ms: now, detail: detail.to_string() }),
        }
    }
}

/// The feed alarms, for `Admin.Health`.
pub fn alarms() -> Vec<gunnar_proto::HealthAlarm> {
    alarm_slot().lock().map(|a| a.clone()).unwrap_or_default()
}

/// **The mock's seam, honoured only as the mock feeds it** (ST-19): a fed `fleet_at` is a
/// bench forward — an address literal `ip:port` on a private, loopback, link-local or
/// shared (100.64/10) network — and a fed `fleet_ca` comes only beside one. Anything else
/// (a public address, a name, a CA with no bench address) is refused by name: a release
/// box never dials elsewhere, nor re-roots its trust, on a feed's word.
pub fn seam_refusal(at: Option<&str>, ca: bool) -> Option<String> {
    const WORD: &str = "fleet-seam-bench-only";
    match at {
        None if ca => Some(format!(
            "REFUSED [{WORD}] the installer fed `{}` with no `{}`: a door's own CA is a bench's, beside a bench address only — a public door is checked under the public roots",
            crate::feed::FEED_FLEET_CA,
            crate::feed::FEED_FLEET_AT
        )),
        None => None,
        Some(at) => match at.trim().parse::<std::net::SocketAddr>() {
            Ok(a) if bench_address(a.ip()) => None,
            _ => Some(format!(
                "REFUSED [{WORD}] the installer fed `{}` = {at}: the pull channel is dialled elsewhere than its door's name only on a bench (a private, loopback or link-local `ip:port`)",
                crate::feed::FEED_FLEET_AT
            )),
        },
    }
}

/// A bench guest's network: private, loopback, link-local, or shared address space.
fn bench_address(ip: std::net::IpAddr) -> bool {
    match ip {
        std::net::IpAddr::V4(v) => v.is_private() || v.is_loopback() || v.is_link_local() || (v.octets()[0] == 100 && (v.octets()[1] & 0xc0) == 64),
        std::net::IpAddr::V6(v) => v.is_loopback() || (v.segments()[0] & 0xfe00) == 0xfc00 || (v.segments()[0] & 0xffc0) == 0xfe80,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// ★ **P1: the relay a sold estate's main mails through comes in the feed** — read from
    /// `secret.smtp_url` / `secret.smtp_from`; the URL (it carries the token) never shows.
    #[test]
    fn the_fed_relay_is_read_and_its_url_withheld() {
        let feed: std::collections::BTreeMap<String, String> = [(FEED_SMTP_URL, "smtp://u:TOKENvalue@smtp.example:587"), (FEED_SMTP_FROM, "u@smtp.example")].iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
        let f = Fed::from_feed(&feed);
        assert_eq!(f.smtp_url, Some(Withheld("smtp://u:TOKENvalue@smtp.example:587".into())));
        assert_eq!(f.smtp_from.as_deref(), Some("u@smtp.example"));
        assert!(!format!("{f:?}").contains("TOKENvalue"), "{f:?}");
        assert!(Fed::from_feed(&Default::default()).smtp_url.is_none());
    }

    /// ★ **The front's egress door a box is fed** (the lean estate, A19 rows 10-14): read from
    /// `egress` (Skidbladnir nordisk-pairing's key), an `http://` door only.
    #[test]
    fn the_fed_egress_door_is_read_and_only_an_http_one() {
        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
        assert_eq!(FEED_EGRESS, nordisk_pairing::egress::FEED_EGRESS);
        assert_eq!(Fed::from_feed(&feed(&[(FEED_EGRESS, " http://10.44.0.1:3128 ")])).egress.as_deref(), Some("http://10.44.0.1:3128"));
        assert_eq!(Fed::from_feed(&feed(&[(FEED_EGRESS, "socks5://10.44.0.1:1080")])).egress, None, "only an http:// door is one");
        assert_eq!(Fed::from_feed(&feed(&[])).egress, None, "a box with its own way out is fed none");
    }

    const A: &str = "43cb00000000000000000000000000000000000000000000000000000000842a";
    const B: &str = "43cb00000000000000000000000000000000000000000000000000000000842b";

    fn k(s: &str) -> [u8; 32] {
        gunnar_common::monetize_key::parse_hex32(s).unwrap()
    }

    /// Since 0.4 the front's keys reach the boxes as vm1's offer; the plain
    /// key, when the installer feeds one, still wins.
    #[test]
    fn a_value_offered_by_a_vm_is_taken_when_the_installer_feeds_none_itself() {
        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
        let f = Fed::from_feed(&feed(&[("offer.front.monetize_pubkey", A), ("offer.front.clock_key", "ssh-ed25519 AAAAk"), ("clock_peer", "peer://10.13.8.1:50123"), ("offer.front.xmonetize_pubkey", B)]));
        assert_eq!(f, Fed { monetize_pubkey: Some(A.into()), clock_key: Some("ssh-ed25519 AAAAk".into()), clock_peer: Some("peer://10.13.8.1:50123".into()), ..Fed::default() });
        assert_eq!(Fed::from_feed(&feed(&[(FEED_MONETIZE, B), ("offer.front.monetize_pubkey", A)])).monetize_pubkey.as_deref(), Some(B), "the plain key wins");
        assert_eq!(nordisk_pairing::feedbus::offered(&feed(&[("offer..monetize_pubkey", A), ("offer.a.b.monetize_pubkey", A)]), FEED_MONETIZE), None, "not a VM name");
    }

    /// ONE monetize (M-D35): shop-pairing feeds the front `fleet` and `fleet_instance`; the
    /// front offers them, and every box takes them — the plain key first, then the offer.
    #[test]
    fn the_fleet_door_and_the_estate_are_taken_from_the_feed_or_the_fronts_offer() {
        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
        let f = Fed::from_feed(&feed(&[("offer.front.fleet", "https://monetize.ignalina.dk:8443"), ("offer.front.fleet_instance", "acme"), ("offer.front.monetize_pubkey", A)]));
        assert_eq!((f.fleet.as_deref(), f.fleet_instance.as_deref(), f.monetize_pubkey.as_deref()), (Some("https://monetize.ignalina.dk:8443"), Some("acme"), Some(A)));
        let f = Fed::from_feed(&feed(&[(FEED_FLEET, "https://one:8443"), ("offer.front.fleet", "https://other:8443"), (FEED_FLEET_INSTANCE, " "), ("offer.front.fleet_instance", "acme")]));
        assert_eq!((f.fleet.as_deref(), f.fleet_instance.as_deref()), (Some("https://one:8443"), Some("acme")), "the plain key wins; blank is absent");
        assert!(Fed::from_feed(&feed(&[])).fleet.is_none());
    }

    /// ★ **`sells_room` is the installer's word, exactly `true`** (2026-10-08): fed on a
    /// selling shop's boxes, absent on a sold estate; anything else is false.
    #[test]
    fn sells_room_is_fed_as_exactly_true() {
        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
        assert!(Fed::from_feed(&feed(&[(FEED_SELLS_ROOM, "true")])).sells_room);
        assert!(Fed::from_feed(&feed(&[(FEED_SELLS_ROOM, " true\n")])).sells_room, "trimmed, as fed");
        assert!(!Fed::from_feed(&feed(&[(FEED_SELLS_ROOM, "yes")])).sells_room);
        assert!(!Fed::from_feed(&feed(&[])).sells_room, "a sold estate is fed nothing");
    }

    /// ★ UW-6: **the site's pay page is the installer's word** (`refusal_link`), trimmed;
    /// blank or absent is none (the medium's page stays).
    #[test]
    fn the_sites_pay_page_is_read_from_the_feed() {
        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
        assert_eq!(FEED_BILLING_URL, "refusal_link");
        assert_eq!(Fed::from_feed(&feed(&[(FEED_BILLING_URL, " https://test2.gunnar.rs/billing/{tenant}\n")])).billing_url.as_deref(), Some("https://test2.gunnar.rs/billing/{tenant}"));
        assert_eq!(Fed::from_feed(&feed(&[(FEED_BILLING_URL, " ")])).billing_url, None);
        assert_eq!(Fed::from_feed(&feed(&[])).billing_url, None);
    }

    /// ★ **The operator's internal IdP networks are the installer's feed**
    /// (owner 2026-10-06): read from the feed, applied to every taker on
    /// every publish (live), parsed by gunnar's own rule — a public or
    /// loopback range is refused, nothing fed is none.
    #[test]
    fn the_operators_idp_networks_are_fed_and_applied_live() {
        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
        let fed = Fed::from_feed(&feed(&[(FEED_SSO_PRIVATE_IDP_CIDRS, " 10.0.2.100/32 ")]));
        assert_eq!(fed.sso_private_idp_cidrs.as_deref(), Some("10.0.2.100/32"));
        assert_eq!(sso_private_nets(Some(&fed)).expect("a private network").to_string(), "10.0.2.100/32");
        assert!(sso_private_nets(None).expect("nothing fed").is_empty());
        let public = Fed::from_feed(&feed(&[(FEED_SSO_PRIVATE_IDP_CIDRS, "8.8.8.0/24")]));
        assert!(sso_private_nets(Some(&public)).is_err(), "a public range is refused");
        let seen = std::sync::Arc::new(Mutex::new(Vec::<String>::new()));
        let into = std::sync::Arc::clone(&seen);
        feedbus::on_published("test: the idp networks", move |f: &Feed| into.lock().unwrap().push(Fed::from_feed(f).sso_private_idp_cidrs.clone().unwrap_or_default()));
        feedbus::publish(feed(&[(FEED_SSO_PRIVATE_IDP_CIDRS, " 10.0.2.100/32 ")]));
        feedbus::publish(feed(&[]));
        let got = seen.lock().unwrap().clone();
        let at = got.iter().position(|v| v == "10.0.2.100/32").expect("the list reached the taker");
        assert!(got[at + 1..].iter().any(String::is_empty), "every publish reaches the taker: {got:?}");
    }

    /// **A role-bound offer is read from the VM that holds the role**: with the
    /// twin sorting first, "the first by name" is the twin's stale key.
    #[test]
    fn an_offer_is_read_from_the_named_vm_not_the_first_by_name() {
        let feed: std::collections::BTreeMap<String, String> = [("offer.vm2.ticket_pubkey", A), ("offer.vm3.ticket_pubkey", B), ("offer.vm4.ticket_pubkey", " ")].iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
        assert_eq!(nordisk_pairing::feedbus::offered(&feed, "ticket_pubkey").as_deref(), Some(A), "the first by name");
        assert_eq!(offered_by(&feed, "vm3", "ticket_pubkey"), Some(B), "the primary's own");
        assert_eq!(offered_by(&feed, "vm4", "ticket_pubkey"), None, "blank is absent");
        assert_eq!(offered_by(&feed, "vm9", "ticket_pubkey"), None);
    }

    #[test]
    fn monetize_door_alone_medium_alone_and_equal_are_taken() {
        assert_eq!(resolve_monetize(None, Some(A)), Ok(Some(k(A))), "one medium, any estate: the door's key");
        assert_eq!(resolve_monetize(Some(k(A)), None), Ok(Some(k(A))), "no feed: today's behaviour");
        assert_eq!(resolve_monetize(Some(k(A)), Some(A)), Ok(Some(k(A))));
        assert_eq!(resolve_monetize(None, None), Ok(None), "a metered build with no key from either source: today's behaviour");
    }

    #[test]
    fn monetize_medium_and_a_different_door_key_is_refused_by_name() {
        let why = resolve_monetize(Some(k(A)), Some(B)).unwrap_err();
        assert!(why.contains(&format!("[{FEED_MISMATCH}]")) && why.contains(A) && why.contains(B), "{why}");
        let why = resolve_monetize(None, Some("not-a-key")).unwrap_err();
        assert!(why.contains("[pairing-feed-monetize-malformed]"), "{why}");
    }

    #[test]
    fn the_feed_table_reads_the_contract_keys_and_blank_is_absent() {
        let mut feed = std::collections::BTreeMap::new();
        feed.insert(FEED_MONETIZE.to_string(), A.to_string());
        feed.insert(FEED_CLOCK_PEER.to_string(), "peer://10.13.8.179:50123".to_string());
        feed.insert(FEED_CLOCK_KEY.to_string(), "  ".to_string());
        feed.insert("admin_pubkey".to_string(), "ssh-ed25519 AAAAconsole".to_string());
        let fed = Fed::from_feed(&feed);
        assert_eq!(fed, Fed { monetize_pubkey: Some(A.into()), clock_key: None, clock_peer: Some("peer://10.13.8.179:50123".into()), ..Fed::default() });
    }

    #[cfg(feature = "wg-client")]
    #[test]
    fn a_persisted_join_reply_is_read_back_and_absent_is_none() {
        let dir = std::env::temp_dir().join(format!("gunnar-feed-{}", std::process::id()));
        let _ = std::fs::create_dir_all(dir.join("pairing"));
        assert_eq!(Fed::read(&dir.join("nowhere")).unwrap(), None);
        let mut feed = std::collections::BTreeMap::new();
        feed.insert(FEED_MONETIZE.to_string(), A.to_string());
        feed.insert(FEED_CLOCK_KEY.to_string(), "ssh-ed25519 AAAAk".to_string());
        let reply = nordisk_pairing::join::JoinReply {
            estate: "gunnar.rs".into(),
            me: nordisk_pairing::join::Assigned { name: "main".into(), overlay: nordisk_pairing::OVERLAY_BOX_A },
            cert_pem: None,
            role: None,
            primary_overlay: None,
            primary_utility: None,
            peers: vec![],
            feed,
        };
        std::fs::write(dir.join(crate::pairing::JOINED_REL), reply.render().unwrap()).unwrap();
        let fed = Fed::read(&dir).unwrap().unwrap();
        assert_eq!(fed.monetize_pubkey.as_deref(), Some(A));
        assert_eq!(fed.clock_key.as_deref(), Some("ssh-ed25519 AAAAk"));
        let _ = std::fs::remove_dir_all(&dir);
    }
}