Skip to main content

mcpmesh_node/
config.rs

1//! The `config.toml` model. Every table and key here is real, implemented surface —
2//! docs/config.md is the operator-facing reference for all of it.
3use figment::{
4    Figment,
5    providers::{Format, Toml},
6};
7use serde::Deserialize;
8use std::collections::BTreeMap;
9use std::path::PathBuf;
10
11#[derive(Debug, Default, Deserialize)]
12#[serde(default)]
13pub struct Config {
14    pub identity: IdentityCfg,
15    pub network: NetworkCfg,
16    pub limits: LimitsCfg,
17    /// Roster-mode `[roster]` tunables: the degraded-expiry grace window, the roster URL +
18    /// poll interval, and the freshness bound — one `RosterState` machine consumes them all.
19    pub roster: RosterCfg,
20    /// `[services.<name>]` registry — each entry is a served MCP server plus its allow
21    /// list. Peers do NOT live in config; they live in the daemon's state store, so
22    /// there is no `[peers]` table here.
23    pub services: std::collections::BTreeMap<String, ServiceCfg>,
24}
25
26/// A `[services.<name>]` entry: exactly one backend kind (`run` xor `socket`) plus the
27/// nicknames/groups admitted to it. The xor is validated at access time via
28/// [`ServiceCfg::backend_result`] rather than at parse time, so a malformed entry is a
29/// per-service error, not a whole-config load failure.
30#[derive(Debug, Default, Deserialize)]
31#[serde(default)]
32pub struct ServiceCfg {
33    /// `run`: spawn this command per session (a stdio MCP server).
34    pub run: Option<Vec<String>>,
35    /// `socket`: dial this local UDS (an already-running MCP server).
36    pub socket: Option<String>,
37    /// STABLE principals admitted to this service (b64u:/eid:/roster names, #38 — never display nicknames).
38    pub allow: Vec<String>,
39    /// Per-service env vars for a `run` backend (#51). The `MCPMESH_PEER_*` identity vars win
40    /// over these. Ignored for a `socket` backend. Default empty.
41    pub env: BTreeMap<String, String>,
42    /// Working directory for a `run` backend (#51). Default: inherit the daemon's cwd.
43    pub cwd: Option<String>,
44    /// Per-service proxied-request rate (#63), falling back to `[limits].rate_limit_per_min`.
45    ///
46    /// Before #63 every service a peer could reach drew from ONE shared bucket, so an agent
47    /// hammering a browser or filesystem service starved the embedder's own low-rate control
48    /// traffic to a different service on the same node. Buckets are now per `(service, endpoint)`.
49    ///
50    /// **This can only LOWER the rate.** `[limits].rate_limit_per_min` is a hard ceiling; a larger
51    /// value here is clamped, not honoured. That is what keeps the limit from being raised by a
52    /// config edit or a `register_service` call.
53    pub rate_limit_per_min: Option<u32>,
54}
55
56/// The resolved backend kind of a [`ServiceCfg`], borrowing the config as slices (no
57/// clone). `&[String]`/`&str` rather than `&Vec`/`&String` — idiomatic and gives the
58/// daemon's backend builders the most flexible borrow.
59#[derive(Debug)]
60pub enum Backend<'a> {
61    Run(&'a [String]),
62    Socket(&'a str),
63}
64
65impl ServiceCfg {
66    /// Resolve the backend, enforcing exactly-one-of `run`/`socket`. Both or neither is an
67    /// error — surfaced to the operator, never a silent default.
68    #[allow(dead_code)] // consumed by the daemon service wiring
69    pub fn backend_result(&self) -> Result<Backend<'_>, String> {
70        match (&self.run, &self.socket) {
71            (Some(cmd), None) => Ok(Backend::Run(cmd.as_slice())),
72            (None, Some(p)) => Ok(Backend::Socket(p.as_str())),
73            (Some(_), Some(_)) => Err("service has both run and socket".into()),
74            (None, None) => Err("service has neither run nor socket".into()),
75        }
76    }
77}
78
79#[derive(Debug, Default, Deserialize)]
80#[serde(default)]
81pub struct IdentityCfg {
82    pub device_key: Option<PathBuf>, // None → paths::default_device_key_path()
83    /// This device's suggested name for itself, carried in a minted pairing invite.
84    /// `None` → the daemon defaults to a short fingerprint of the endpoint id.
85    /// Additive (`#[serde(default)]` at the struct level).
86    pub nickname: Option<String>,
87    /// Roster mode: the org id this node joined (pinned at install/join).
88    pub org_id: Option<String>,
89    /// Roster mode: the pinned org-root public key, `b64u:`. The single trust anchor
90    /// roster signatures verify against. Pinned on first roster install / `join`.
91    pub org_root_pk: Option<String>,
92    /// Roster mode: this node's stable user_id in the org. Pinned at `join` (proposed)
93    /// and reconciled to the roster's authoritative value once installed.
94    pub user_id: Option<String>,
95    /// Roster mode: path to this person's user key. Minted by `join`; binds this
96    /// person's devices. `None` → paths::default_user_key_path() when needed.
97    pub user_key: Option<PathBuf>,
98}
99
100/// `[network]`. The knobs are exactly what `daemon::net_plan` implements —
101/// no aspirational surface:
102/// - `relay_mode = "default" | "custom" | "disabled"`. `"custom"` requires `relay_urls`
103///   (self-hosted iroh relays); `"disabled"` is the HERMETIC mode — no relay AND no
104///   discovery (localhost/tests).
105/// - `discovery_mode = "default" | "custom"`. `"custom"` requires `discovery_urls` —
106///   self-hosted pkarr relay URLs (e.g. an iroh-dns-server), used for BOTH publishing and
107///   resolving peer addresses in place of n0's DNS/pkarr. Ignored (off) when
108///   `relay_mode = "disabled"`.
109///
110/// Unknown modes or a `custom` without URLs are startup ERRORS (`net_plan`), never a silent
111/// fallback — a metadata-privacy knob must not quietly revert to public infrastructure.
112#[derive(Debug, Clone, Deserialize)]
113#[serde(default)]
114pub struct NetworkCfg {
115    pub relay_mode: String,
116    /// Self-hosted relay URLs, required when `relay_mode = "custom"`.
117    pub relay_urls: Vec<String>,
118    pub discovery_mode: String,
119    /// Self-hosted pkarr relay URLs, required when `discovery_mode = "custom"`.
120    pub discovery_urls: Vec<String>,
121    /// TESTING ONLY (#116): force application data over the RELAY even when a direct path exists.
122    ///
123    /// Requires the `unstable-relay-only` cargo feature. Without it this field still PARSES — a
124    /// config must stay portable between a test build and a production one — but is ignored with a
125    /// `warn!`. It is never a startup error: a testing switch must not brick a node, and it must
126    /// never be ignored SILENTLY, because believing you tested the relay when you did not is the
127    /// exact failure #116 reports.
128    ///
129    /// Selects the relay path; it does NOT prevent hole-punching (that is socket-level behaviour a
130    /// `PathSelector` cannot reach). A direct path may still form — it simply never carries data,
131    /// and `status` reports `relay` because #64 derives the path from `is_selected()`.
132    pub relay_only: bool,
133    /// `[network].presence_mode` (#89) — who gets a reachability pong on `mcpmesh/ping/1`.
134    ///
135    /// - `"paired"` (default): any paired peer, today's behaviour.
136    /// - `"granted"`: only a caller currently holding at least one service grant. This is what
137    ///   makes an embedder's per-peer sharing switch control presence too — revoking the last
138    ///   service takes presence with it, live, with no restart and no new verb.
139    /// - `"off"`: never pong.
140    ///
141    /// The arm is gated by PAIRING alone otherwise, so `service_allow_revoke` has no effect on it:
142    /// a peer whose every service was revoked still learns you are online right now, your RTT, your
143    /// `stack_version` and your app metadata, on demand and forever. The only lever was a full
144    /// unpair — a relationship-destroying action to express a privacy preference (#89).
145    ///
146    /// A refusal under `"off"`/`"granted"` matches the trust gate's, so this arm does not
147    /// distinguish "not paired" from "hidden" from "no grants".
148    ///
149    /// **This is NOT "appear offline".** It withholds the pong payload (`stack_version`, app
150    /// metadata, the caller's services) and makes our own probe report you unreachable. It does not
151    /// hide that the node is running: a QUIC application close implies a completed handshake,
152    /// `mcpmesh/pair/1` answers any stranger by design, and a paired peer still gets a served
153    /// `mcpmesh/mcp/1` session. Do not describe it to users as invisibility (#89 gate).
154    ///
155    /// Read at BOOT — changing the mode needs a restart. The per-peer effect under `"granted"` is
156    /// live, because grants are.
157    pub presence_mode: String,
158    /// QUIC idle timeout in seconds (#56) — how long a connection survives with NO traffic and no
159    /// keepalive before the transport closes it. `None` = iroh's default, **30s** on iroh 1.0.3.
160    ///
161    /// This is not "how long an idle session lives". iroh keepalives every 5s by default, so a held
162    /// session survives indefinitely while the process runs; this is what detects a peer that
163    /// VANISHED.
164    ///
165    /// **It is NEGOTIATED, not imposed.** QUIC takes the MINIMUM of the two peers' advertised
166    /// values (RFC 9000 §10.1), so raising this on one node achieves nothing against a peer still
167    /// on the default — the connection still times out at 30s. Raising it is only meaningful when
168    /// every node is configured together; lowering it works one-sidedly.
169    ///
170    /// `0` means "no timeout" from THIS side, which likewise yields the peer's value; against a
171    /// default peer that is still 30s. Only if both sides say `0` does a vanished peer go
172    /// undetected at the transport layer.
173    #[serde(default)]
174    pub idle_timeout_secs: Option<u64>,
175    /// QUIC keepalive interval in seconds (#56) — how often the transport PINGs an otherwise idle
176    /// connection. `None` = iroh's default, **5s** on iroh 1.0.3.
177    ///
178    /// Sets BOTH the connection-level and the per-path keepalive — setting only the former would
179    /// leave every path pinging at iroh's 5s regardless.
180    ///
181    /// A transport keepalive carries no method-bearing frame, so it does NOT consume a
182    /// `[limits].rate_limit_per_min` token — unlike an application-level heartbeat, which does.
183    ///
184    /// Must be less than the EFFECTIVE idle timeout — `idle_timeout_secs` if set, otherwise iroh's
185    /// 30s — or boot fails. Note that effective timeout is the negotiated minimum, so a value that
186    /// passes this check locally can still be too slow for a peer with a shorter one.
187    ///
188    /// **This can only LOWER the ping rate.** iroh caps the per-path keepalive at 5s and silently
189    /// discards anything larger, so a value above 5 would leave every path pinging at 5s anyway —
190    /// boot refuses it rather than pretend it took effect. There is no supported way to reduce
191    /// keepalive traffic on a metered link with iroh 1.0.3.
192    #[serde(default)]
193    pub keep_alive_secs: Option<u64>,
194}
195impl Default for NetworkCfg {
196    fn default() -> Self {
197        Self {
198            relay_mode: "default".into(),
199            relay_urls: Vec::new(),
200            discovery_mode: "default".into(),
201            discovery_urls: Vec::new(),
202            relay_only: false,
203            presence_mode: "paired".into(),
204            idle_timeout_secs: None,
205            keep_alive_secs: None,
206        }
207    }
208}
209
210/// `[limits]`. NOTE — the frame cap is deliberately NOT here: the 16 MiB `max_frame`
211/// default is a fixed CONSTANT at each wire (`mcpmesh_net::endpoint` for the mesh,
212/// `ipc::MAX_FRAME_BYTES` for the control socket, `backends::MAX_FRAME_BYTES` for local MCP
213/// servers), not a config tunable. A `max_frame` config field existed historically but was never
214/// threaded into any `FrameReader` (dead surface); threading it into the mesh path would widen
215/// `mcpmesh-net`'s public API for no demonstrated need, so the field was removed instead (serde
216/// ignores an unknown `max_frame` key in existing configs).
217#[derive(Debug, Deserialize)]
218#[serde(default)]
219pub struct LimitsCfg {
220    pub rate_limit_per_min: u32,
221    pub max_inflight: u32,
222    pub max_sessions: u32,
223    /// Per-authenticated-endpoint app-blob BYTE budget, bytes per minute (#84a).
224    ///
225    /// **0 = unlimited, and that is the default**, so an existing deployment is unchanged on
226    /// upgrade. The pre-existing blob limiter counts CONNECTIONS, which cannot see one granted
227    /// peer re-pulling a 4 GB blob on each of 60 connections a minute; this bounds the bytes.
228    ///
229    /// A peer that exceeds it gets its transfer ABORTED (retryable), not paced — pacing holds the
230    /// request open and turns a bandwidth problem into an unbounded-concurrency one.
231    ///
232    /// **Use 0 or at least 32768** (two chunks); a value in `1..32768` is FLOORED to 32768.
233    ///
234    /// Admission reserves one chunk before any bytes and the transfer then meters its own chunks,
235    /// so a sub-floor budget does not fail closed — it silently caps every servable blob at
236    /// roughly `budget - 16384` bytes and truncates anything larger. Measured: 20480 serves a
237    /// 4 KiB blob and nothing bigger. Two earlier drafts of this comment got that wrong, first
238    /// recommending the bricking value and then claiming it failed closed.
239    ///
240    /// Requires a restart: the limiter and the provider's event mask are both built once at boot.
241    pub blob_bytes_per_min: u64,
242    /// Audit-log retention window in calendar months (#88). **0 = keep forever, and that is the
243    /// default** — flipping today's keep-everything behavior to auto-deletion is a product call,
244    /// deliberately not made here. When N > 0, boot deletes monthly audit files older than the
245    /// last N months (the current month counts as month 1). Boot-time only: a long-running
246    /// daemon prunes on its next start; the `audit_prune` verb covers live needs.
247    pub audit_retain_months: u32,
248}
249impl Default for LimitsCfg {
250    fn default() -> Self {
251        Self {
252            rate_limit_per_min: 120,
253            max_inflight: 16,
254            max_sessions: 4,
255            blob_bytes_per_min: 0, // unlimited: opt-in, no behaviour change on upgrade
256            audit_retain_months: 0, // keep forever: opt-in, no behaviour change on upgrade
257        }
258    }
259}
260
261/// The default degraded-expiry grace window (`[roster].grace_period` default "72h").
262/// A stale roster keeps serving for this window past `expires_at` (with a warning) before it
263/// stops granting roster identity. Kept here so [`RosterCfg::default`] and the parse fallback
264/// share one source; the gate mirrors it as `roster::gate::DEFAULT_GRACE_SECS`.
265const DEFAULT_GRACE_SECS: i64 = 72 * 3600;
266
267/// The default freshness bound (`[roster].max_staleness`, default "24h" = 86400s). A roster
268/// this node has not re-confirmed current within this window degrades on the SAME `RosterState`
269/// machine as expiry (warnings within `grace`, then serving stops) — bounding adversarial staleness at
270/// `max_staleness + grace` independent of `expires_at`. Shared by [`RosterCfg::default`] + the parse
271/// fallback.
272const DEFAULT_MAX_STALENESS_SECS: i64 = 24 * 3600;
273
274/// The `[roster]` config table. `grace_period` is the degraded-expiry grace window — how
275/// long a roster past `expires_at` keeps serving (degraded, warning) before it stops. Additive
276/// (`#[serde(default)]`): a config with no `[roster]` table gets the 72h default.
277#[derive(Debug, Deserialize)]
278#[serde(default)]
279pub struct RosterCfg {
280    /// Degraded-expiry grace window: `"72h"` / `"24h"` / plain seconds (default "72h").
281    pub grace_period: String,
282    /// The pinned roster URL for the HTTPS poll. Operator-managed static hosting; also how a
283    /// joiner bootstraps its FIRST roster. `None` → no URL poll (manual installs only).
284    /// Additive (`#[serde(default)]`): a config with no `url` key gets `None`.
285    pub url: Option<String>,
286    /// How often to poll `url` (default "1h"). Total-parse like `grace_period` — an
287    /// unparseable value falls back to the hourly default rather than disabling the poll.
288    pub poll_interval: String,
289    /// The freshness bound (default "24h"): how long this node may go without re-confirming
290    /// the installed roster current (via a TLS URL poll ≥ installed, a gossip install, or a
291    /// manual install) before it degrades on the SAME `RosterState` machine as expiry. Total-parse
292    /// like `grace_period` (an unparseable value falls back to the 24h default — a typo never disables
293    /// the bound). Additive (`#[serde(default)]`): a config with no `max_staleness` key gets 24h.
294    pub max_staleness: String,
295}
296impl Default for RosterCfg {
297    fn default() -> Self {
298        Self {
299            grace_period: "72h".into(),
300            url: None,
301            poll_interval: "1h".into(),
302            max_staleness: "24h".into(),
303        }
304    }
305}
306
307impl RosterCfg {
308    /// The grace window in SECONDS. An absent or unparseable `grace_period` falls back to the 72h
309    /// default rather than erroring — an operator typo must never disable degraded serving, and a
310    /// grace window is advisory, not a security bound (revocation is enforced regardless of
311    /// degraded state).
312    ///
313    /// Two paths degrade on the ONE `RosterState` machine (`RosterView::state`, Approved →
314    /// DegradedGrace → DegradedStopped): expiry (`expires_at` + THIS grace window) and freshness
315    /// (`last_confirmed` + `max_staleness`). Once DegradedStopped, the gate stops granting roster
316    /// identity (fail-closed — revocation is still enforced); within grace, serving continues
317    /// with a warning (`daemon::warn_if_degraded_grace`).
318    pub fn grace_seconds(&self) -> i64 {
319        parse_duration(&self.grace_period).unwrap_or(DEFAULT_GRACE_SECS)
320    }
321
322    /// The URL poll interval in SECONDS (default 3600). Like [`grace_seconds`](Self::grace_seconds)
323    /// it is TOTAL — an absent/unparseable value falls back to the hourly default rather than
324    /// erroring, so an operator typo slows the poll to hourly instead of disabling freshness.
325    pub fn poll_interval_seconds(&self) -> i64 {
326        parse_duration(&self.poll_interval).unwrap_or(3600)
327    }
328
329    /// The freshness bound in SECONDS (default 86400 = 24h). Like [`grace_seconds`](Self::grace_seconds)
330    /// it is TOTAL — an absent/unparseable value falls back to the 24h default rather than erroring, so
331    /// an operator typo tightens/loosens to 24h instead of disabling the freshness bound.
332    pub fn max_staleness_seconds(&self) -> i64 {
333        parse_duration(&self.max_staleness).unwrap_or(DEFAULT_MAX_STALENESS_SECS)
334    }
335}
336
337/// Parse a duration string to SECONDS: a `d`/`h`/`m`/`s` suffix (days/hours/minutes/seconds) or a
338/// bare number (seconds). Trim + suffix-strip + checked multiply; rejects a
339/// negative/overflowing/garbage value as `Err` (the caller supplies the
340/// default). `u64` parse then a checked `i64` conversion: a negative grace is meaningless, so `-1`
341/// fails the `u64` parse and falls back to the default rather than becoming a negative window.
342// Reached only by the accessors above and the `org create --expires` porcelain
343// (`enrollcmd`, the operator-managed validity window — now across the crate seam, hence
344// `pub`; still `#[doc(hidden)]` at the module level). Pure parser — no state.
345pub fn parse_duration(s: &str) -> Result<i64, String> {
346    let s = s.trim();
347    let (num, mult) = if let Some(n) = s.strip_suffix('d') {
348        (n, 24 * 3600)
349    } else if let Some(n) = s.strip_suffix('h') {
350        (n, 3600)
351    } else if let Some(n) = s.strip_suffix('m') {
352        (n, 60)
353    } else if let Some(n) = s.strip_suffix('s') {
354        (n, 1)
355    } else {
356        (s, 1)
357    };
358    num.trim()
359        .parse::<u64>()
360        .ok()
361        .and_then(|v| v.checked_mul(mult))
362        .and_then(|v| i64::try_from(v).ok())
363        .ok_or_else(|| format!("unparseable duration: {s}"))
364}
365
366// figment::Error is ~208 bytes; boxing it would churn the API for a cold path.
367#[allow(clippy::result_large_err)]
368impl Config {
369    #[allow(dead_code)] // exercised by unit tests; config-string entry point for later tooling
370    pub fn from_toml_str(s: &str) -> Result<Self, figment::Error> {
371        Figment::new().merge(Toml::string(s)).extract()
372    }
373
374    /// Missing file → defaults (first run); malformed file → Err.
375    /// Callers must surface the Err — swallowing it silently reverts user choices.
376    pub fn load(path: &std::path::Path) -> Result<Self, figment::Error> {
377        Figment::new().merge(Toml::file(path)).extract()
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    #[test]
386    fn empty_file_yields_spec_defaults() {
387        let c = Config::from_toml_str("").unwrap();
388        assert_eq!(c.network.relay_mode, "default");
389        assert_eq!(c.network.discovery_mode, "default");
390        assert_eq!(c.limits.rate_limit_per_min, 120);
391        assert_eq!(c.limits.max_inflight, 16);
392        assert_eq!(c.limits.max_sessions, 4);
393    }
394
395    #[test]
396    fn values_override_defaults() {
397        let c = Config::from_toml_str(
398            "[network]\nrelay_mode = \"disabled\"\n[limits]\nrate_limit_per_min = 60\n",
399        )
400        .unwrap();
401        assert_eq!(c.network.relay_mode, "disabled");
402        assert_eq!(c.limits.rate_limit_per_min, 60);
403        assert_eq!(c.limits.max_inflight, 16);
404    }
405
406    /// A legacy config carrying the removed `max_frame` key still loads (serde ignores unknown
407    /// fields) — the frame cap is a fixed constant now, not a tunable (see the `LimitsCfg` doc).
408    #[test]
409    fn legacy_max_frame_key_is_ignored_not_an_error() {
410        let c =
411            Config::from_toml_str("[limits]\nmax_frame = \"1MiB\"\nmax_sessions = 2\n").unwrap();
412        assert_eq!(c.limits.max_sessions, 2);
413    }
414
415    /// The self-hosting knobs parse: `custom` modes with their URL lists. (Validation —
416    /// custom-without-urls, unknown modes — lives in `daemon::net_plan`, tested there.)
417    #[test]
418    fn network_relay_and_discovery_urls_parse() {
419        let c = Config::from_toml_str(
420            "[network]\nrelay_mode = \"custom\"\nrelay_urls = [\"https://relay.acme.com\"]\n\
421             discovery_mode = \"custom\"\ndiscovery_urls = [\"https://dns.acme.com/pkarr\"]\n",
422        )
423        .unwrap();
424        assert_eq!(c.network.relay_mode, "custom");
425        assert_eq!(
426            c.network.relay_urls,
427            vec!["https://relay.acme.com".to_string()]
428        );
429        assert_eq!(c.network.discovery_mode, "custom");
430        assert_eq!(
431            c.network.discovery_urls,
432            vec!["https://dns.acme.com/pkarr".to_string()]
433        );
434        // Absent → empty lists (the defaults need no URLs).
435        let c = Config::from_toml_str("").unwrap();
436        assert!(c.network.relay_urls.is_empty() && c.network.discovery_urls.is_empty());
437    }
438
439    #[test]
440    fn missing_file_loads_defaults() {
441        let dir = tempfile::tempdir().unwrap();
442        let c = Config::load(&dir.path().join("nope.toml")).unwrap();
443        assert_eq!(c.network.relay_mode, "default");
444    }
445
446    #[test]
447    fn roster_url_and_poll_interval_parse_with_defaults() {
448        // No [roster] table → url None, poll 1h default.
449        let c = Config::from_toml_str("").unwrap();
450        assert!(c.roster.url.is_none());
451        assert_eq!(c.roster.poll_interval_seconds(), 3600);
452        // A configured url + poll interval.
453        let c = Config::from_toml_str(
454            "[roster]\nurl = \"https://intranet.acme.com/roster.json\"\npoll_interval = \"30m\"\n",
455        )
456        .unwrap();
457        assert_eq!(
458            c.roster.url.as_deref(),
459            Some("https://intranet.acme.com/roster.json")
460        );
461        assert_eq!(c.roster.poll_interval_seconds(), 30 * 60);
462        // An unparseable poll_interval falls back to the hourly default (never disables the poll).
463        let c = Config::from_toml_str("[roster]\npoll_interval = \"never\"\n").unwrap();
464        assert_eq!(c.roster.poll_interval_seconds(), 3600);
465        // The url is additive: setting only grace_period keeps url None + the default poll.
466        let c = Config::from_toml_str("[roster]\ngrace_period = \"24h\"\n").unwrap();
467        assert!(c.roster.url.is_none());
468        assert_eq!(c.roster.poll_interval_seconds(), 3600);
469    }
470
471    #[test]
472    fn roster_max_staleness_defaults_to_24h_and_parses() {
473        // No [roster] table → the 24h freshness bound (the default).
474        let c = Config::from_toml_str("").unwrap();
475        assert_eq!(c.roster.max_staleness_seconds(), 24 * 3600);
476        // A configured value parses (units, like grace_period).
477        let c = Config::from_toml_str("[roster]\nmax_staleness = \"6h\"\n").unwrap();
478        assert_eq!(c.roster.max_staleness_seconds(), 6 * 3600);
479        // An unparseable value falls back to the 24h default (never disables the freshness bound).
480        let c = Config::from_toml_str("[roster]\nmax_staleness = \"forever\"\n").unwrap();
481        assert_eq!(c.roster.max_staleness_seconds(), 24 * 3600);
482        // Additive: setting only grace_period keeps the 24h max_staleness default.
483        let c = Config::from_toml_str("[roster]\ngrace_period = \"48h\"\n").unwrap();
484        assert_eq!(c.roster.max_staleness_seconds(), 24 * 3600);
485    }
486
487    #[test]
488    fn roster_grace_defaults_to_72h_and_parses_units() {
489        // Absent `[roster]` → the 72h default.
490        let c = Config::from_toml_str("").unwrap();
491        assert_eq!(c.roster.grace_seconds(), 72 * 3600);
492        // Hours / days / minutes / seconds / bare-seconds all resolve to seconds.
493        for (body, want) in [
494            ("[roster]\ngrace_period = \"24h\"\n", 24 * 3600),
495            ("[roster]\ngrace_period = \"72h\"\n", 72 * 3600),
496            ("[roster]\ngrace_period = \"1d\"\n", 24 * 3600),
497            ("[roster]\ngrace_period = \"30m\"\n", 30 * 60),
498            ("[roster]\ngrace_period = \"90s\"\n", 90),
499            ("[roster]\ngrace_period = \"3600\"\n", 3600), // bare seconds
500        ] {
501            assert_eq!(
502                Config::from_toml_str(body).unwrap().roster.grace_seconds(),
503                want,
504                "{body}"
505            );
506        }
507    }
508
509    #[test]
510    fn roster_grace_unparseable_or_negative_falls_back_to_default() {
511        // A garbage / negative / overflowing grace never disables degraded serving — it defaults.
512        for body in [
513            "[roster]\ngrace_period = \"seventy-two hours\"\n",
514            "[roster]\ngrace_period = \"-5h\"\n",
515            "[roster]\ngrace_period = \"18446744073709551615d\"\n", // overflows the checked_mul
516            "[roster]\ngrace_period = \"\"\n",
517        ] {
518            assert_eq!(
519                Config::from_toml_str(body).unwrap().roster.grace_seconds(),
520                72 * 3600,
521                "{body}"
522            );
523        }
524    }
525
526    #[test]
527    fn services_parse_run_and_socket() {
528        let c = Config::from_toml_str(concat!(
529            "[services.notes]\nrun = [\"npx\", \"server\"]\nallow = [\"bob\"]\n",
530            "[services.kb]\nsocket = \"/run/kb.sock\"\nallow = [\"team-eng\"]\n",
531        ))
532        .unwrap();
533        let notes = c.services.get("notes").unwrap();
534        assert!(
535            matches!(notes.backend_result(), Ok(Backend::Run(cmd)) if cmd == &["npx".to_string(), "server".to_string()][..])
536        );
537        assert_eq!(notes.allow, vec!["bob".to_string()]);
538        assert!(
539            matches!(c.services.get("kb").unwrap().backend_result(), Ok(Backend::Socket(p)) if p == "/run/kb.sock")
540        );
541    }
542
543    #[test]
544    fn service_with_both_run_and_socket_is_an_error() {
545        let e = Config::from_toml_str("[services.x]\nrun=[\"a\"]\nsocket=\"/s\"\nallow=[]\n");
546        // exactly one backend kind is required — validate at access time.
547        assert!(
548            e.unwrap()
549                .services
550                .get("x")
551                .unwrap()
552                .backend_result()
553                .is_err()
554        );
555    }
556
557    #[test]
558    fn identity_reads_user_id_and_user_key() {
559        let toml = "[identity]\n\
560            org_id = \"acme\"\n\
561            org_root_pk = \"b64u:AAAA\"\n\
562            user_id = \"alice\"\n\
563            user_key = \"/home/alice/.config/mcpmesh/user.key\"\n";
564        let cfg: Config = toml::from_str(toml).unwrap();
565        assert_eq!(cfg.identity.user_id.as_deref(), Some("alice"));
566        assert_eq!(
567            cfg.identity.user_key.as_deref(),
568            Some(std::path::Path::new("/home/alice/.config/mcpmesh/user.key"))
569        );
570        // Absent → None (pure-pairing / operator-only node).
571        let bare: Config = toml::from_str("[identity]\n").unwrap();
572        assert!(bare.identity.user_id.is_none() && bare.identity.user_key.is_none());
573    }
574}