Skip to main content

gunnar_server/
feed.rs

1//! **The estate values the installer's door FEEDS**, taken instead of the
2//! medium's — so one medium serves any estate.
3//!
4//! The join reply the pairing loop receives carries a `feed` table
5//! (`nordisk_pairing::join::JoinReply::feed`); the loop persists the whole
6//! reply to `<data>/pairing/joined.toml` ([`crate::pairing::JOINED_REL`]).
7//! Three of its keys configure this box:
8//!
9//! | key               | what it replaces on the medium                       | applied            |
10//! |-------------------|------------------------------------------------------|--------------------|
11//! | `monetize_pubkey` | `GUNNAR_MONETIZE_PUBKEY` / `--monetize-pubkey`        | at start, or LIVE when it arrives |
12//! | `clock_key`       | `ESTATE_CLOCK_KEY` / `GUNNAR_CLOCK_KEY` (`korp.env.` / `clock_key=` param) | on every clock sync|
13//! | `clock_peer`      | `ESTATE_CLOCK` / `GUNNAR_CLOCK` (`korp.env.` / `clock=` param)         | on every clock sync|
14//!
15//! (`admin_pubkey` is the fourth feed key; the pairing loop installs it itself.)
16//!
17//! # Precedence: there is none — a disagreement is REFUSED by name
18//!
19//! Medium alone → the medium's. Door alone → the door's. Both and EQUAL →
20//! that value. Both and DIFFERENT → [`FEED_MISMATCH`], never a silent pick:
21//! the medium and the installer disagree about which estate this box is in,
22//! and choosing either one is choosing whose money or whose time to trust
23//! without saying so (the reasoning of ops' `monetize-pubkey-mismatch`
24//! preflight, which refuses a bring-up over the same disagreement).
25//!
26//! * The monetize key at start: a refusal to start ([`resolve_monetize`]).
27//! * The monetize key arriving while running (first boot): the key in force
28//!   stays, the `Admin.Health` alarm [`FEED_MISMATCH`] is raised.
29//! * The clock: every sync reads the effective configuration
30//!   ([`clock_config`]), and a disagreement is the sync's `misconfigured`
31//!   report naming [`FEED_MISMATCH`] — the clock is left alone.
32//!
33//! # The monetize key applies LIVE (owner 2026-09-25: avoid restarts)
34//!
35//! A metered box on a `fed` medium starts KEYLESS: its entitlement slot and
36//! its growth go-ahead policy are built with no key (every namespace Free,
37//! `Entitlement.Set` refused, a `monetize` go-ahead refused) and registered
38//! as takers ([`on_monetize_key`]). When the installer feeds the key (or vm1
39//! offers it), [`monetize_arrived`] hands it to each taker, which swaps it in
40//! place — the slot re-verifies every stored fact under it — and the key is
41//! persisted in `joined.toml` for the next start as before. Until 2026-09-25
42//! this was a restart of the machine. The clock (`clock_key`, `clock_peer`)
43//! and the fed principals were already live: the clock reads the feed on
44//! every sync, and the primary installs principals on every feed.
45//!
46//! # The bus is the shared one (L10, 2026-10-20)
47//!
48//! Every feed this process takes is published on nordisk-pairing's process-wide
49//! feed bus ([`feedbus::publish`], Skidbladnir 0.5.15, A7 row 8): a part that
50//! applies a fed value LIVE subscribes with [`feedbus::on_published`] and reads
51//! the typed [`Fed::from_feed`]; [`Fed::current`] is the typed view of the
52//! value in force. Gunnar's own bus (this module's `publish`, `on_published`,
53//! `current`) is gone; this module is the typed view over the shared one.
54
55use std::path::Path;
56use std::sync::{Mutex, OnceLock, RwLock};
57
58use nordisk_pairing::feedbus::{self, Feed};
59
60/// The relay a sold estate's main mails through, as the shop feeds it (monetize-server
61/// `estate_order::FEED_SMTP_*`, P1).
62pub const FEED_SMTP_URL: &str = "secret.smtp_url";
63pub const FEED_SMTP_FROM: &str = "secret.smtp_from";
64
65/// The feed keys this module reads (the contract's names; never renamed).
66pub const FEED_MONETIZE: &str = "monetize_pubkey";
67pub const FEED_CLOCK_KEY: &str = "clock_key";
68pub const FEED_CLOCK_PEER: &str = "clock_peer";
69/// **The operator's internal networks a company IdP may live on** (owner
70/// 2026-10-06, a private gunnar): a list of CIDRs, estate config the
71/// installer feeds; never an account admin's. Empty or absent: today's guard
72/// (`gunnar_grpc::sso::PrivateNets`). Applied LIVE on every feed.
73pub const FEED_SSO_PRIVATE_IDP_CIDRS: &str = "sso_private_idp_cidrs";
74/// **This estate SELLS room** (2026-10-08): `true` on a selling shop's boxes (gunnar.rs,
75/// test2), absent everywhere else — a SOLD estate and the open build keep "no fact is
76/// uncapped". Applied LIVE ([`Fed::sells_room`], gunnar-grpc `selling`).
77pub const FEED_SELLS_ROOM: &str = "sells_room";
78/// **The ONE monetize's `Fleet` door** (5.4, ONE monetize, M-D35): what `--fleet` names on
79/// the medium. shop-pairing feeds it to the front, the front offers it to every box; the
80/// box's pull channel reports there ([`crate::repair::resolve_fleet`]).
81pub const FEED_FLEET: &str = "fleet";
82/// **The estate this box reports for** (`--fleet-instance`), fed beside [`FEED_FLEET`].
83pub const FEED_FLEET_INSTANCE: &str = "fleet_instance";
84/// **Where the pull channel connects** (`host:port`), fed beside [`FEED_FLEET`] when the
85/// door's name is not what this box should dial (a test bench whose guests resolve no
86/// names). TLS still verifies the certificate under [`FEED_FLEET`]'s host. Absent: the
87/// URL's own host, resolved. A BENCH address only (ST-19, [`crate::repair::seam_refusal`]).
88pub const FEED_FLEET_AT: &str = "fleet_at";
89/// **The PEM the pull channel's door is checked against**, fed beside [`FEED_FLEET`] when
90/// its certificate is not under the public roots. Absent: the public roots. Only beside a
91/// bench [`FEED_FLEET_AT`] (ST-19).
92pub const FEED_FLEET_CA: &str = "fleet_ca";
93
94/// **The SITE's pay page** (UW-6, feed key `refusal_link`: the open build names no money): a `{tenant}` template, `https://<site>/billing/{tenant}`
95/// — a page the site's own console serves. The medium is one for every estate, so the
96/// page it bakes (`--billing-url`) is a placeholder this replaces, LIVE
97/// ([`crate::entitlement::EntitlementSlot::set_billing_url`]).
98pub const FEED_BILLING_URL: &str = "refusal_link";
99/// **Auto-fix, fed** (main rebuild, 2026-10-12): exactly `true` turns the box's auto-fix on,
100/// as `--repair-auto` does. The estate's opt-in, carried by its installer; nothing else
101/// changes what the guard allows (`gunnar_repair::rebuild`).
102pub const FEED_REPAIR_AUTO: &str = "repair_auto";
103/// **The repair key, fed** (main rebuild, 2026-10-12): an OpenSSH private key this box signs
104/// its repair calls with when no `--repair-key` is given — a re-laid main holds no twin key,
105/// and without one every pulled order and the auto recharge were refused. The installer
106/// feeds its public half as a principal, so the twin reads its log to it and a fresh main
107/// takes its `Bootstrap.Restore`.
108pub const FEED_REPAIR_KEY: &str = "secret.repair_key";
109
110/// The alarm/refusal word for a medium value and a DIFFERENT fed value.
111pub const FEED_MISMATCH: &str = "pairing.feed_mismatch";
112/// The alarm for a fed monetize key this running process could not apply
113/// (no entitlement slot to apply it to, or a taker refused it). It used to be
114/// `pairing.feed_restart` and a reboot; the key is applied live now.
115pub const FEED_NOT_APPLIED: &str = "pairing.feed_not_applied";
116
117/// **`vm`'s offer of `key`** (`offer.<vm>.<key>`), trimmed; blank is absent.
118pub fn offered_by<'a>(feed: &'a std::collections::BTreeMap<String, String>, vm: &str, key: &str) -> Option<&'a str> {
119    feed.get(&format!("offer.{vm}.{key}")).map(|v| v.trim()).filter(|v| !v.is_empty())
120}
121
122/// What the door fed, as far as this box's configuration goes.
123#[derive(Debug, Clone, Default, PartialEq, Eq)]
124pub struct Fed {
125    pub monetize_pubkey: Option<String>,
126    pub clock_key: Option<String>,
127    pub clock_peer: Option<String>,
128    /// [`FEED_SSO_PRIVATE_IDP_CIDRS`], as fed.
129    pub sso_private_idp_cidrs: Option<String>,
130    /// [`FEED_SELLS_ROOM`]: exactly `true`, as fed; anything else is false.
131    pub sells_room: bool,
132    /// [`FEED_FLEET`], as fed.
133    pub fleet: Option<String>,
134    /// [`FEED_FLEET_INSTANCE`], as fed.
135    pub fleet_instance: Option<String>,
136    /// [`FEED_FLEET_AT`], as fed.
137    pub fleet_at: Option<String>,
138    /// [`FEED_FLEET_CA`], as fed.
139    pub fleet_ca: Option<String>,
140    /// [`FEED_SMTP_URL`], as fed: the relay a SOLD estate's main mails through (P1). Its
141    /// `Debug` withholds it (it carries the submission token).
142    pub smtp_url: Option<Withheld>,
143    /// [`FEED_SMTP_FROM`], as fed.
144    pub smtp_from: Option<String>,
145    /// [`FEED_BILLING_URL`], as fed.
146    pub billing_url: Option<String>,
147    /// [`FEED_REPAIR_AUTO`]: exactly `true`, as fed; anything else is false.
148    pub repair_auto: bool,
149    /// [`FEED_REPAIR_KEY`], as fed (withheld from `Debug`).
150    pub repair_key: Option<Withheld>,
151}
152
153/// A fed value that is a credential: kept, compared, never shown.
154#[derive(Clone, Default, PartialEq, Eq)]
155pub struct Withheld(pub String);
156
157impl std::fmt::Debug for Withheld {
158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159        f.write_str("<withheld>")
160    }
161}
162
163impl Fed {
164    /// From the reply's `feed` table. Blank values are absent. A value the
165    /// installer does not feed itself may reach this box as a VM's OFFER,
166    /// fed onward as `offer.<vm>.<key>` (edda nordisk-pairing 0.3.1; since
167    /// 0.4 the front's keys — monetize's verifying key, the clock key — come
168    /// that way): the plain key wins, then the first offer by VM name.
169    pub fn from_feed(feed: &std::collections::BTreeMap<String, String>) -> Fed {
170        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));
171        Fed {
172            monetize_pubkey: get(FEED_MONETIZE),
173            clock_key: get(FEED_CLOCK_KEY),
174            clock_peer: get(FEED_CLOCK_PEER),
175            sso_private_idp_cidrs: get(FEED_SSO_PRIVATE_IDP_CIDRS),
176            sells_room: get(FEED_SELLS_ROOM).as_deref() == Some("true"),
177            fleet: get(FEED_FLEET),
178            fleet_instance: get(FEED_FLEET_INSTANCE),
179            fleet_at: get(FEED_FLEET_AT),
180            fleet_ca: get(FEED_FLEET_CA),
181            smtp_url: get(FEED_SMTP_URL).map(Withheld),
182            smtp_from: get(FEED_SMTP_FROM),
183            billing_url: get(FEED_BILLING_URL),
184            repair_auto: get(FEED_REPAIR_AUTO).as_deref() == Some("true"),
185            repair_key: get(FEED_REPAIR_KEY).map(Withheld),
186        }
187    }
188
189    pub fn is_empty(&self) -> bool {
190        self == &Fed::default()
191    }
192
193    /// `<data>/pairing/joined.toml`, if the loop has persisted one. Absent is
194    /// `None`; present and unreadable is an error — a persisted answer that
195    /// lies must not be quietly ignored.
196    pub fn read(root: &Path) -> anyhow::Result<Option<Fed>> {
197        Ok(kept_feed(root)?.as_ref().map(Fed::from_feed))
198    }
199
200    /// **The typed view of the feed in force** on the shared bus
201    /// (nordisk-pairing [`feedbus::current`]); `None` before anything was published.
202    pub fn current() -> Option<Fed> {
203        feedbus::current().map(|feed| Fed::from_feed(&feed))
204    }
205}
206
207/// The feed of `<data>/pairing/joined.toml`, as the door fed it ([`Fed::read`]).
208#[cfg(feature = "wg-client")]
209pub fn kept_feed(root: &Path) -> anyhow::Result<Option<Feed>> {
210    let p = root.join(crate::pairing::JOINED_REL);
211    let Some(text) = crate::fed_at_rest::read_checked(root, crate::pairing::JOINED_REL)? else { return Ok(None) };
212    let reply = nordisk_pairing::join::JoinReply::parse(&text).map_err(|e| anyhow::anyhow!("{}: {e}", p.display()))?;
213    Ok(Some(reply.feed))
214}
215
216/// A build without the pairing loop has no door to be fed by.
217#[cfg(not(feature = "wg-client"))]
218pub fn kept_feed(_root: &Path) -> anyhow::Result<Option<Feed>> {
219    Ok(None)
220}
221
222/// **The operator's internal networks a company IdP may live on**, as `fed`
223/// names them: none when nothing is fed. A list gunnar refuses (a public or
224/// loopback range) is an error, said by the caller and applied as none.
225pub fn sso_private_nets(fed: Option<&Fed>) -> Result<gunnar_grpc::sso::PrivateNets, String> {
226    match fed.and_then(|f| f.sso_private_idp_cidrs.as_deref()) {
227        Some(text) => gunnar_grpc::sso::PrivateNets::parse(text).map_err(|why| format!("`{FEED_SSO_PRIVATE_IDP_CIDRS}`: {why}")),
228        None => Ok(gunnar_grpc::sso::PrivateNets::default()),
229    }
230}
231
232/// Read `joined.toml` under `root` and publish its feed on the shared bus
233/// ([`feedbus::publish`]). Called once at start; an unreadable file is logged
234/// and treated as no feed (the loop re-joins and rewrites it).
235pub fn load_at_start(root: &Path) -> Option<Fed> {
236    match kept_feed(root) {
237        Ok(Some(feed)) => {
238            let fed = Fed::from_feed(&feed);
239            if !fed.is_empty() {
240                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");
241            }
242            feedbus::publish(feed);
243            Some(fed)
244        }
245        Ok(None) => None,
246        Err(e) => {
247            tracing::error!(error = %format!("{e:#}"), "feed: the persisted join reply is unreadable — this start uses the medium's values only");
248            None
249        }
250    }
251}
252
253// ── the monetize key ────────────────────────────────────────────────────────
254
255/// The key the running server enforces with: recorded at start (outer `None`
256/// = nothing recorded, e.g. a test), and moved ONCE more when an awaited key
257/// arrives and is applied live ([`monetize_arrived`]).
258fn in_force_slot() -> &'static RwLock<Option<Option<[u8; 32]>>> {
259    static IN_FORCE: OnceLock<RwLock<Option<Option<[u8; 32]>>>> = OnceLock::new();
260    IN_FORCE.get_or_init(|| RwLock::new(None))
261}
262
263pub fn record_monetize_in_force(key: Option<[u8; 32]>) {
264    if let Ok(mut s) = in_force_slot().write() {
265        *s = Some(key);
266    }
267}
268
269pub fn monetize_in_force() -> Option<[u8; 32]> {
270    in_force_slot().read().ok().and_then(|s| s.flatten())
271}
272
273/// Something that takes the monetize key LIVE: the entitlement slot (both
274/// front doors' plan gate and `Entitlement.Set` read it) and the growth
275/// go-ahead policy. Registered by `serve` once each is built.
276pub type MonetizeTaker = Box<dyn Fn(&[u8; 32]) -> Result<(), String> + Send + Sync>;
277
278fn takers() -> &'static Mutex<Vec<(&'static str, MonetizeTaker)>> {
279    static TAKERS: OnceLock<Mutex<Vec<(&'static str, MonetizeTaker)>>> = OnceLock::new();
280    TAKERS.get_or_init(|| Mutex::new(Vec::new()))
281}
282
283/// **Register a taker of the monetize key** (owner 2026-09-25: avoid
284/// restarts) — called by `serve` for the entitlement slot and the go-ahead
285/// policy it built keyless, so a key the installer feeds later is applied in
286/// place by [`monetize_arrived`].
287pub fn on_monetize_key(name: &'static str, take: MonetizeTaker) {
288    if let Ok(mut t) = takers().lock() {
289        t.push((name, take));
290    }
291}
292
293fn hex(k: &[u8; 32]) -> String {
294    k.iter().map(|b| format!("{b:02x}")).collect()
295}
296
297/// **The monetize key at start.** `medium` is the resolved key off
298/// `--monetize-pubkey`/`GUNNAR_MONETIZE_PUBKEY`; `fed` is the door's spelling
299/// (64 hex). A fed value that is not a key, or that differs from the
300/// medium's, is refused by name.
301pub fn resolve_monetize(medium: Option<[u8; 32]>, fed: Option<&str>) -> Result<Option<[u8; 32]>, String> {
302    let fed = match fed {
303        None => return Ok(medium),
304        Some(text) => gunnar_common::monetize_key::parse_hex32(text.trim()).map_err(|why| {
305            format!("REFUSED [pairing-feed-monetize-malformed] the installer fed `{FEED_MONETIZE}` = `{text}`, which is not a monetize key: {why}")
306        })?,
307    };
308    match medium {
309        None => Ok(Some(fed)),
310        Some(m) if m == fed => Ok(Some(m)),
311        Some(m) => Err(format!(
312            "REFUSED [{FEED_MISMATCH}] the medium trusts monetize key {} and the installer's door fed {} — \
313             this box will not pick one silently. Compose the medium without `monetize_pubkey` (the door \
314             feeds it), or with the front's live key",
315            hex(&m),
316            hex(&fed)
317        )),
318    }
319}
320
321/// Why a fed monetize key found no taker, in the words THIS build can say.
322///
323/// The metered build names the flag that opens the slot. The open build has no
324/// such flag (`--billing-url` is declared in `entitlement.rs`, which is
325/// `metered`-only) and must not compile the word into anything an operator can
326/// read — `tests/open_build_speaks_no_money.rs::the_open_sources_say_no_money`,
327/// the owner's ruling of 2026-09-15. Before this split the open build carried
328/// the metered sentence verbatim and the guard was red on it (feed.rs:243).
329#[cfg(feature = "metered")]
330const NO_TAKER_WHY: &str = "the metered start opened no entitlement slot (no --billing-url on a `fed` medium)";
331#[cfg(not(feature = "metered"))]
332const NO_TAKER_WHY: &str = "this build carries no entitlement module, so no start opens a slot to take it";
333
334/// **The fed monetize key arriving while running** (the pairing loop's
335/// answer, or vm1's offer carried by the installer): APPLIED IN PLACE by every
336/// registered taker ([`on_monetize_key`]), with no restart (owner 2026-09-25).
337/// `None` = nothing to do (no key fed, the same key already in force, or a
338/// process that recorded none — a community build or a test).
339pub fn monetize_arrived(fed: Option<&str>) -> Option<MonetizeArrival> {
340    let in_force = in_force_slot().read().ok().and_then(|s| *s)?;
341    let fed = fed?;
342    match resolve_monetize(in_force, Some(fed)) {
343        Ok(Some(k)) if Some(k) == in_force => None,
344        Ok(Some(k)) => {
345            let takers = takers().lock().ok()?;
346            if takers.is_empty() {
347                let detail = format!(
348                    "the installer fed monetize key {} and nothing on this box can enforce it: {NO_TAKER_WHY}",
349                    hex(&k)
350                );
351                raise(FEED_NOT_APPLIED, &detail);
352                return Some(MonetizeArrival::NotApplied(detail));
353            }
354            let failed: Vec<String> = takers.iter().filter_map(|(name, take)| take(&k).err().map(|e| format!("{name}: {e}"))).collect();
355            if !failed.is_empty() {
356                let detail = format!("the installer fed monetize key {}, and it could not be applied: {}", hex(&k), failed.join("; "));
357                raise(FEED_NOT_APPLIED, &detail);
358                return Some(MonetizeArrival::NotApplied(detail));
359            }
360            record_monetize_in_force(Some(k));
361            let detail = format!("the installer fed monetize key {}; it is IN FORCE now (applied in place, no restart)", hex(&k));
362            tracing::info!(event = "pairing.feed_applied", "feed: {detail}");
363            Some(MonetizeArrival::Applied(detail))
364        }
365        Ok(None) => None,
366        Err(why) => {
367            raise(FEED_MISMATCH, &why);
368            Some(MonetizeArrival::Mismatch(why))
369        }
370    }
371}
372
373#[derive(Debug, Clone, PartialEq, Eq)]
374pub enum MonetizeArrival {
375    /// The server started with no key; the fed one is enforced from now on.
376    Applied(String),
377    /// The server started with no key and cannot take the fed one: alarmed.
378    NotApplied(String),
379    /// The medium's key is in force and the door fed another: refused, alarmed.
380    Mismatch(String),
381}
382
383// ── the clock ───────────────────────────────────────────────────────────────
384
385/// **The clock's two values**, medium against door — edda estate-clock's
386/// (`offer::resolve_clock`, moved there from here AS IS; the refusal names
387/// [`FEED_MISMATCH`], the same word). `Ok((clock, key))` is what
388/// [`estate_clock::config::Config::parse`] is handed.
389pub use estate_clock::offer::resolve_clock;
390
391/// **The clock configuration in force now**: the process environment (the
392/// medium's `korp.env.ESTATE_CLOCK*`, or Gunnar's `korp.env.GUNNAR_CLOCK*`
393/// read as its alias, `estate_clock::config::var`) merged with the current
394/// feed. Read on EVERY sync, so a feed that arrives while running applies to
395/// the next one.
396pub fn clock_config() -> Result<estate_clock::config::Config, String> {
397    use estate_clock::config::{var, Config, Role, CLOCK_ENV, CLOCK_KEY_ENV};
398    let env_clock = var(CLOCK_ENV);
399    let env_key = var(CLOCK_KEY_ENV);
400    let fed = Fed::current().unwrap_or_default();
401    let (clock, key) = resolve_clock(env_clock.as_deref(), env_key.as_deref(), fed.clock_peer.as_deref(), fed.clock_key.as_deref())?;
402    Config::parse(clock.as_deref(), key.as_deref(), Role::Appliance)
403}
404
405/// Whether the door fed a clock source.
406pub fn clock_fed() -> bool {
407    Fed::current().is_some_and(|f| f.clock_peer.is_some())
408}
409
410// ── alarms ──────────────────────────────────────────────────────────────────
411
412fn alarm_slot() -> &'static Mutex<Vec<gunnar_proto::HealthAlarm>> {
413    static ALARMS: OnceLock<Mutex<Vec<gunnar_proto::HealthAlarm>>> = OnceLock::new();
414    ALARMS.get_or_init(|| Mutex::new(Vec::new()))
415}
416
417/// Raise (or re-raise, counting) a feed alarm; said on the log too.
418pub fn raise(event: &str, detail: &str) {
419    tracing::error!(event, "feed: {detail}");
420    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0);
421    if let Ok(mut alarms) = alarm_slot().lock() {
422        match alarms.iter_mut().find(|a| a.event == event) {
423            Some(a) => {
424                a.count += 1;
425                a.detail = detail.to_string();
426            }
427            None => alarms.push(gunnar_proto::HealthAlarm { event: event.into(), count: 1, since_unix_ms: now, detail: detail.to_string() }),
428        }
429    }
430}
431
432/// The feed alarms, for `Admin.Health`.
433pub fn alarms() -> Vec<gunnar_proto::HealthAlarm> {
434    alarm_slot().lock().map(|a| a.clone()).unwrap_or_default()
435}
436
437/// **The mock's seam, honoured only as the mock feeds it** (ST-19): a fed `fleet_at` is a
438/// bench forward — an address literal `ip:port` on a private, loopback, link-local or
439/// shared (100.64/10) network — and a fed `fleet_ca` comes only beside one. Anything else
440/// (a public address, a name, a CA with no bench address) is refused by name: a release
441/// box never dials elsewhere, nor re-roots its trust, on a feed's word.
442pub fn seam_refusal(at: Option<&str>, ca: bool) -> Option<String> {
443    const WORD: &str = "fleet-seam-bench-only";
444    match at {
445        None if ca => Some(format!(
446            "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",
447            crate::feed::FEED_FLEET_CA,
448            crate::feed::FEED_FLEET_AT
449        )),
450        None => None,
451        Some(at) => match at.trim().parse::<std::net::SocketAddr>() {
452            Ok(a) if bench_address(a.ip()) => None,
453            _ => Some(format!(
454                "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`)",
455                crate::feed::FEED_FLEET_AT
456            )),
457        },
458    }
459}
460
461/// A bench guest's network: private, loopback, link-local, or shared address space.
462fn bench_address(ip: std::net::IpAddr) -> bool {
463    match ip {
464        std::net::IpAddr::V4(v) => v.is_private() || v.is_loopback() || v.is_link_local() || (v.octets()[0] == 100 && (v.octets()[1] & 0xc0) == 64),
465        std::net::IpAddr::V6(v) => v.is_loopback() || (v.segments()[0] & 0xfe00) == 0xfc00 || (v.segments()[0] & 0xffc0) == 0xfe80,
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472
473    /// ★ **P1: the relay a sold estate's main mails through comes in the feed** — read from
474    /// `secret.smtp_url` / `secret.smtp_from`; the URL (it carries the token) never shows.
475    #[test]
476    fn the_fed_relay_is_read_and_its_url_withheld() {
477        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();
478        let f = Fed::from_feed(&feed);
479        assert_eq!(f.smtp_url, Some(Withheld("smtp://u:TOKENvalue@smtp.example:587".into())));
480        assert_eq!(f.smtp_from.as_deref(), Some("u@smtp.example"));
481        assert!(!format!("{f:?}").contains("TOKENvalue"), "{f:?}");
482        assert!(Fed::from_feed(&Default::default()).smtp_url.is_none());
483    }
484
485    const A: &str = "43cb00000000000000000000000000000000000000000000000000000000842a";
486    const B: &str = "43cb00000000000000000000000000000000000000000000000000000000842b";
487
488    fn k(s: &str) -> [u8; 32] {
489        gunnar_common::monetize_key::parse_hex32(s).unwrap()
490    }
491
492    /// Since 0.4 the front's keys reach the boxes as vm1's offer; the plain
493    /// key, when the installer feeds one, still wins.
494    #[test]
495    fn a_value_offered_by_a_vm_is_taken_when_the_installer_feeds_none_itself() {
496        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
497        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)]));
498        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() });
499        assert_eq!(Fed::from_feed(&feed(&[(FEED_MONETIZE, B), ("offer.front.monetize_pubkey", A)])).monetize_pubkey.as_deref(), Some(B), "the plain key wins");
500        assert_eq!(nordisk_pairing::feedbus::offered(&feed(&[("offer..monetize_pubkey", A), ("offer.a.b.monetize_pubkey", A)]), FEED_MONETIZE), None, "not a VM name");
501    }
502
503    /// ONE monetize (M-D35): shop-pairing feeds the front `fleet` and `fleet_instance`; the
504    /// front offers them, and every box takes them — the plain key first, then the offer.
505    #[test]
506    fn the_fleet_door_and_the_estate_are_taken_from_the_feed_or_the_fronts_offer() {
507        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
508        let f = Fed::from_feed(&feed(&[("offer.front.fleet", "https://monetize.ignalina.dk:8443"), ("offer.front.fleet_instance", "acme"), ("offer.front.monetize_pubkey", A)]));
509        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)));
510        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")]));
511        assert_eq!((f.fleet.as_deref(), f.fleet_instance.as_deref()), (Some("https://one:8443"), Some("acme")), "the plain key wins; blank is absent");
512        assert!(Fed::from_feed(&feed(&[])).fleet.is_none());
513    }
514
515    /// ★ **`sells_room` is the installer's word, exactly `true`** (2026-10-08): fed on a
516    /// selling shop's boxes, absent on a sold estate; anything else is false.
517    #[test]
518    fn sells_room_is_fed_as_exactly_true() {
519        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
520        assert!(Fed::from_feed(&feed(&[(FEED_SELLS_ROOM, "true")])).sells_room);
521        assert!(Fed::from_feed(&feed(&[(FEED_SELLS_ROOM, " true\n")])).sells_room, "trimmed, as fed");
522        assert!(!Fed::from_feed(&feed(&[(FEED_SELLS_ROOM, "yes")])).sells_room);
523        assert!(!Fed::from_feed(&feed(&[])).sells_room, "a sold estate is fed nothing");
524    }
525
526    /// ★ UW-6: **the site's pay page is the installer's word** (`refusal_link`), trimmed;
527    /// blank or absent is none (the medium's page stays).
528    #[test]
529    fn the_sites_pay_page_is_read_from_the_feed() {
530        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
531        assert_eq!(FEED_BILLING_URL, "refusal_link");
532        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}"));
533        assert_eq!(Fed::from_feed(&feed(&[(FEED_BILLING_URL, " ")])).billing_url, None);
534        assert_eq!(Fed::from_feed(&feed(&[])).billing_url, None);
535    }
536
537    /// ★ **The operator's internal IdP networks are the installer's feed**
538    /// (owner 2026-10-06): read from the feed, applied to every taker on
539    /// every publish (live), parsed by gunnar's own rule — a public or
540    /// loopback range is refused, nothing fed is none.
541    #[test]
542    fn the_operators_idp_networks_are_fed_and_applied_live() {
543        let feed = |pairs: &[(&str, &str)]| pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect::<std::collections::BTreeMap<_, _>>();
544        let fed = Fed::from_feed(&feed(&[(FEED_SSO_PRIVATE_IDP_CIDRS, " 10.0.2.100/32 ")]));
545        assert_eq!(fed.sso_private_idp_cidrs.as_deref(), Some("10.0.2.100/32"));
546        assert_eq!(sso_private_nets(Some(&fed)).expect("a private network").to_string(), "10.0.2.100/32");
547        assert!(sso_private_nets(None).expect("nothing fed").is_empty());
548        let public = Fed::from_feed(&feed(&[(FEED_SSO_PRIVATE_IDP_CIDRS, "8.8.8.0/24")]));
549        assert!(sso_private_nets(Some(&public)).is_err(), "a public range is refused");
550        let seen = std::sync::Arc::new(Mutex::new(Vec::<String>::new()));
551        let into = std::sync::Arc::clone(&seen);
552        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()));
553        feedbus::publish(feed(&[(FEED_SSO_PRIVATE_IDP_CIDRS, " 10.0.2.100/32 ")]));
554        feedbus::publish(feed(&[]));
555        let got = seen.lock().unwrap().clone();
556        let at = got.iter().position(|v| v == "10.0.2.100/32").expect("the list reached the taker");
557        assert!(got[at + 1..].iter().any(String::is_empty), "every publish reaches the taker: {got:?}");
558    }
559
560    /// **A role-bound offer is read from the VM that holds the role**: with the
561    /// twin sorting first, "the first by name" is the twin's stale key.
562    #[test]
563    fn an_offer_is_read_from_the_named_vm_not_the_first_by_name() {
564        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();
565        assert_eq!(nordisk_pairing::feedbus::offered(&feed, "ticket_pubkey").as_deref(), Some(A), "the first by name");
566        assert_eq!(offered_by(&feed, "vm3", "ticket_pubkey"), Some(B), "the primary's own");
567        assert_eq!(offered_by(&feed, "vm4", "ticket_pubkey"), None, "blank is absent");
568        assert_eq!(offered_by(&feed, "vm9", "ticket_pubkey"), None);
569    }
570
571    #[test]
572    fn monetize_door_alone_medium_alone_and_equal_are_taken() {
573        assert_eq!(resolve_monetize(None, Some(A)), Ok(Some(k(A))), "one medium, any estate: the door's key");
574        assert_eq!(resolve_monetize(Some(k(A)), None), Ok(Some(k(A))), "no feed: today's behaviour");
575        assert_eq!(resolve_monetize(Some(k(A)), Some(A)), Ok(Some(k(A))));
576        assert_eq!(resolve_monetize(None, None), Ok(None), "a metered build with no key from either source: today's behaviour");
577    }
578
579    #[test]
580    fn monetize_medium_and_a_different_door_key_is_refused_by_name() {
581        let why = resolve_monetize(Some(k(A)), Some(B)).unwrap_err();
582        assert!(why.contains(&format!("[{FEED_MISMATCH}]")) && why.contains(A) && why.contains(B), "{why}");
583        let why = resolve_monetize(None, Some("not-a-key")).unwrap_err();
584        assert!(why.contains("[pairing-feed-monetize-malformed]"), "{why}");
585    }
586
587    #[test]
588    fn the_feed_table_reads_the_contract_keys_and_blank_is_absent() {
589        let mut feed = std::collections::BTreeMap::new();
590        feed.insert(FEED_MONETIZE.to_string(), A.to_string());
591        feed.insert(FEED_CLOCK_PEER.to_string(), "peer://10.13.8.179:50123".to_string());
592        feed.insert(FEED_CLOCK_KEY.to_string(), "  ".to_string());
593        feed.insert("admin_pubkey".to_string(), "ssh-ed25519 AAAAconsole".to_string());
594        let fed = Fed::from_feed(&feed);
595        assert_eq!(fed, Fed { monetize_pubkey: Some(A.into()), clock_key: None, clock_peer: Some("peer://10.13.8.179:50123".into()), ..Fed::default() });
596    }
597
598    #[cfg(feature = "wg-client")]
599    #[test]
600    fn a_persisted_join_reply_is_read_back_and_absent_is_none() {
601        let dir = std::env::temp_dir().join(format!("gunnar-feed-{}", std::process::id()));
602        let _ = std::fs::create_dir_all(dir.join("pairing"));
603        assert_eq!(Fed::read(&dir.join("nowhere")).unwrap(), None);
604        let mut feed = std::collections::BTreeMap::new();
605        feed.insert(FEED_MONETIZE.to_string(), A.to_string());
606        feed.insert(FEED_CLOCK_KEY.to_string(), "ssh-ed25519 AAAAk".to_string());
607        let reply = nordisk_pairing::join::JoinReply {
608            estate: "gunnar.rs".into(),
609            me: nordisk_pairing::join::Assigned { name: "main".into(), overlay: nordisk_pairing::OVERLAY_BOX_A },
610            cert_pem: None,
611            role: None,
612            primary_overlay: None,
613            primary_utility: None,
614            peers: vec![],
615            feed,
616        };
617        std::fs::write(dir.join(crate::pairing::JOINED_REL), reply.render().unwrap()).unwrap();
618        let fed = Fed::read(&dir).unwrap().unwrap();
619        assert_eq!(fed.monetize_pubkey.as_deref(), Some(A));
620        assert_eq!(fed.clock_key.as_deref(), Some("ssh-ed25519 AAAAk"));
621        let _ = std::fs::remove_dir_all(&dir);
622    }
623}