Skip to main content

kanade_shared/
config.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::{Context, Result};
4use serde::{Deserialize, Serialize};
5
6// ─── Agent config ────────────────────────────────────────────────────
7
8#[derive(Deserialize, Debug, Clone)]
9pub struct AgentConfig {
10    pub agent: AgentSection,
11    pub log: LogSection,
12}
13
14#[derive(Deserialize, Debug, Clone)]
15pub struct AgentSection {
16    pub id: String,
17    pub nats_url: String,
18    /// DEPRECATED in Sprint 5: group membership is now server-managed
19    /// via the `agent_groups` KV bucket. Use
20    /// `kanade agent groups set <pc_id> <group> [<group> ...]` to
21    /// declare membership. Still parsed for back-compat; the value
22    /// is logged-and-ignored at startup. Field removal is scheduled
23    /// for v0.4.0.
24    #[serde(default)]
25    pub groups: Vec<String>,
26}
27
28#[derive(Deserialize, Debug, Clone)]
29pub struct LogSection {
30    pub path: String,
31    pub level: String,
32    /// Number of rotated daily files (incl. today's) to retain.
33    /// Defaults to 14 — covers two weeks of incidents without
34    /// blowing up disk. Set to 0 to disable on-disk logging
35    /// (stdout only).
36    #[serde(default = "default_keep_days")]
37    pub keep_days: usize,
38}
39
40fn default_keep_days() -> usize {
41    14
42}
43
44// ─── Backend config ──────────────────────────────────────────────────
45
46#[derive(Deserialize, Debug, Clone)]
47pub struct BackendConfig {
48    pub server: ServerSection,
49    pub nats: NatsSection,
50    pub db: DbSection,
51    pub log: LogSection,
52}
53
54/// Non-secret SMTP connection settings. Lives here (rather than in `wire`)
55/// because it's the shape `mail::Mailer::from_config` builds from, but it's
56/// carried operator-editably in the `server_settings` KV bucket
57/// (`wire::ServerSettings::mail` / SPA), **not** in `backend.toml` (#884).
58/// `Serialize` is derived for the KV / API path; the SMTP password is never
59/// a field here — it comes from the `MailPassword` registry secret (or
60/// `$KANADE_MAIL_PASSWORD`), keeping secrets out of the KV.
61#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
62pub struct MailSection {
63    /// SMTP relay host (e.g. an internal mail relay).
64    pub host: String,
65    /// SMTP port — 587 (STARTTLS), 465 (implicit TLS), or 25 (plain).
66    pub port: u16,
67    #[serde(default)]
68    pub encryption: MailEncryption,
69    /// Envelope/`From` address every kanade email is sent as.
70    pub from: String,
71    /// SMTP AUTH username. Omit for an unauthenticated internal relay;
72    /// when set, pair it with the `MailPassword` secret.
73    #[serde(default)]
74    pub username: Option<String>,
75}
76
77/// Transport security for the SMTP connection.
78#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)]
79#[serde(rename_all = "lowercase")]
80pub enum MailEncryption {
81    /// Upgrade a plaintext connection via STARTTLS (port 587). Default.
82    #[default]
83    Starttls,
84    /// Implicit TLS from the first byte (port 465).
85    Tls,
86    /// No transport security (port 25 on a trusted internal segment).
87    None,
88}
89
90#[derive(Deserialize, Debug, Clone)]
91pub struct ServerSection {
92    pub bind: String,
93    /// Externally-reachable base URL of the SPA (e.g.
94    /// `https://kanade.example.com`), used to build absolute links in
95    /// emails (password setup / reset). Optional: when unset the backend
96    /// derives the base from each request's `Host` header (+
97    /// `X-Forwarded-Proto`), which is correct for a direct LAN deploy.
98    /// Set this when behind a reverse proxy / TLS terminator, or to harden
99    /// the public forgot-password path against `Host`-header poisoning
100    /// (`bind` can't be used — it's a wildcard like `0.0.0.0:8080` and
101    /// carries no scheme/hostname).
102    #[serde(default)]
103    pub public_url: Option<String>,
104}
105
106#[derive(Deserialize, Debug, Clone)]
107pub struct NatsSection {
108    pub url: String,
109    /// #1270: base URL of the broker's HTTP monitoring endpoint (the
110    /// `http_port` in `nats-server.conf`, 8222 by default). The backend
111    /// polls `/connz` there to learn which NATS user each agent's live
112    /// connection authenticated as.
113    ///
114    /// Optional: when unset it is derived from [`Self::url`] by swapping
115    /// the scheme for `http` and the port for 8222, which is right for the
116    /// standard single-broker deploy. Set it when monitoring listens
117    /// elsewhere. Unreachable / disabled monitoring is not fatal — the
118    /// projection simply stays unpopulated.
119    #[serde(default)]
120    pub monitor_url: Option<String>,
121}
122
123/// Port `nats-server` serves its monitoring endpoints on by default, and
124/// the `http_port` shipped in `configs/nats-server.conf`.
125const DEFAULT_MONITOR_PORT: u16 = 8222;
126
127impl NatsSection {
128    /// The monitoring base URL to poll — configured, or derived from
129    /// [`Self::url`].
130    ///
131    /// Derivation deliberately keeps only the **host**: the client URL's
132    /// port is the client port (4222), its scheme may be `nats`/`tls`/`ws`
133    /// (none of which the monitoring endpoint speaks), and it may carry
134    /// inline credentials that must not be re-sent over plain HTTP.
135    pub fn resolved_monitor_url(&self) -> String {
136        if let Some(u) = self.monitor_url.as_deref().map(str::trim)
137            && !u.is_empty()
138        {
139            let u = u.trim_end_matches('/');
140            // A scheme-less value (`10.0.0.9:8222`) would otherwise be
141            // parsed as a URI whose *scheme* is the hostname, failing every
142            // poll behind a "monitoring endpoint unreadable" line that names
143            // the symptom rather than the typo.
144            return if u.contains("://") {
145                u.to_string()
146            } else {
147                format!("http://{u}")
148            };
149        }
150        let host = monitor_host_from_client_url(&self.url);
151        format!("http://{host}:{DEFAULT_MONITOR_PORT}")
152    }
153}
154
155/// Extract the host from a NATS client URL, dropping scheme, credentials,
156/// port and path. Returns the input unchanged when it is already a bare
157/// host, and falls back to loopback for input with no host at all — a
158/// wrong-but-harmless target beats a panic in a background poller.
159fn monitor_host_from_client_url(url: &str) -> String {
160    let after_scheme = url.split_once("://").map_or(url, |(_scheme, rest)| rest);
161    // `user:pass@host:port` — credentials are before the LAST '@' so a
162    // password containing '@' does not truncate the host.
163    let authority = match after_scheme.rsplit_once('@') {
164        Some((_creds, host)) => host,
165        None => after_scheme,
166    };
167    // Strip any path / query the URL carried.
168    let authority = authority
169        .split(['/', '?', '#'])
170        .next()
171        .unwrap_or(authority)
172        .trim();
173    // IPv6 literals are bracketed (`[::1]:4222`) and their colons are not
174    // port separators — keep the brackets, which is also the form an HTTP
175    // URL needs.
176    let host = if let Some(end) = authority.find(']') {
177        &authority[..=end]
178    } else {
179        authority.split(':').next().unwrap_or(authority)
180    };
181    if host.is_empty() {
182        "127.0.0.1".to_string()
183    } else {
184        host.to_string()
185    }
186}
187
188#[derive(Deserialize, Debug, Clone)]
189pub struct DbSection {
190    pub sqlite_path: String,
191}
192
193// ─── Loader ──────────────────────────────────────────────────────────
194
195fn load_typed<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T> {
196    let mut engine = teravars::Engine::new();
197    let ctx = teravars::system_context();
198    let paths: Vec<PathBuf> = vec![path.to_path_buf()];
199    let merged = teravars::load_merged(&paths, &mut engine, &ctx)
200        .with_context(|| format!("teravars load_merged: {path:?}"))?;
201    let cfg: T = toml::Value::Table(merged.config)
202        .try_into()
203        .with_context(|| format!("decode config from {path:?}"))?;
204    Ok(cfg)
205}
206
207pub fn load_agent_config(path: &Path) -> Result<AgentConfig> {
208    load_typed(path)
209}
210
211pub fn load_backend_config(path: &Path) -> Result<BackendConfig> {
212    load_typed(path)
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    fn nats(url: &str, monitor: Option<&str>) -> NatsSection {
220        NatsSection {
221            url: url.to_string(),
222            monitor_url: monitor.map(str::to_string),
223        }
224    }
225
226    /// #1270: the derived monitoring URL must keep the host and drop
227    /// everything else. The client port is not the monitoring port, and an
228    /// inline credential must not be replayed over plain HTTP.
229    #[test]
230    fn the_monitor_url_derives_from_the_client_url_host_only() {
231        for (client, want) in [
232            ("nats://127.0.0.1:4222", "http://127.0.0.1:8222"),
233            (
234                "nats://nats.example.com:4222",
235                "http://nats.example.com:8222",
236            ),
237            // No scheme, no port — a bare host is still a host.
238            ("broker-01", "http://broker-01:8222"),
239            // Inline credentials: the host is after the last '@'.
240            ("nats://user:p@ss@10.0.0.5:4222", "http://10.0.0.5:8222"),
241            // wss deploys terminate elsewhere, but the host still answers.
242            (
243                "wss://kanade.example.com:443/nats",
244                "http://kanade.example.com:8222",
245            ),
246            // IPv6 literals keep their brackets in both URL forms.
247            ("nats://[::1]:4222", "http://[::1]:8222"),
248        ] {
249            assert_eq!(
250                nats(client, None).resolved_monitor_url(),
251                want,
252                "deriving from {client}",
253            );
254        }
255    }
256
257    #[test]
258    fn an_explicit_monitor_url_wins_and_is_taken_verbatim() {
259        assert_eq!(
260            nats("nats://127.0.0.1:4222", Some("http://10.0.0.9:9999")).resolved_monitor_url(),
261            "http://10.0.0.9:9999",
262        );
263        // A trailing slash would produce `//connz` when joined.
264        assert_eq!(
265            nats("nats://127.0.0.1:4222", Some("http://10.0.0.9:9999/")).resolved_monitor_url(),
266            "http://10.0.0.9:9999",
267        );
268        // Blank / whitespace-only is not a configured value — fall back to
269        // derivation rather than polling the empty string.
270        assert_eq!(
271            nats("nats://127.0.0.1:4222", Some("   ")).resolved_monitor_url(),
272            "http://127.0.0.1:8222",
273        );
274        // A scheme-less value is the likely typo, and it parses as a URI
275        // whose scheme is the hostname — which fails on every poll behind an
276        // error that names the symptom, not the cause.
277        assert_eq!(
278            nats("nats://127.0.0.1:4222", Some("10.0.0.9:8222")).resolved_monitor_url(),
279            "http://10.0.0.9:8222",
280        );
281        // ...but an explicit scheme is never rewritten, including https.
282        assert_eq!(
283            nats("nats://127.0.0.1:4222", Some("https://mon.example.com")).resolved_monitor_url(),
284            "https://mon.example.com",
285        );
286    }
287
288    /// Smoke test the dev-fleet flow against `agent.dev.toml`:
289    ///   1. When `KANADE_DEV_AGENT_ID` is set, the teravars template
290    ///      resolves `vars.pc_id` to that value and propagates it
291    ///      into `agent.id` + `log.path`. Also exercises a `[vars]`
292    ///      self-reference (`pc_id` falls back to `vars.hostname`),
293    ///      which `load_merged` resolves via its internal
294    ///      fixed-point pass.
295    ///   2. Without the env, the template falls back to `system.host`
296    ///      so vanilla `cargo make agent-dev` still works.
297    ///
298    /// Both halves live in a single `#[test]` so they execute
299    /// sequentially within the cargo test runtime — splitting them
300    /// across two tests races on `KANADE_DEV_AGENT_ID` (macOS CI
301    /// turned the race up enough to fail consistently).
302    #[test]
303    fn agent_dev_toml_renders_pc_id_from_env_or_system_host() {
304        // The dev config lives at the workspace root; CARGO_MANIFEST_DIR
305        // resolves to crates/kanade-shared/, so hop up two.
306        let cfg_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
307            .join("..")
308            .join("..")
309            .join("configs")
310            .join("agent.dev.toml");
311
312        // (1) env set → pc_id == env value
313        // SAFETY: env mutation is process-global; this single test
314        // body owns set + remove so no sibling test can race us.
315        unsafe {
316            std::env::set_var("KANADE_DEV_AGENT_ID", "dev-pc-render-test");
317        }
318        let cfg = load_agent_config(&cfg_path).expect("load agent.dev.toml (env set)");
319        assert_eq!(cfg.agent.id, "dev-pc-render-test");
320        assert!(
321            cfg.log.path.contains("dev-pc-render-test"),
322            "log path should embed pc_id, got {}",
323            cfg.log.path,
324        );
325
326        // (2) env removed → pc_id falls back to vars.hostname
327        // = system.host. The host string varies by box; just assert
328        // it's non-empty and not the literal template that would mean
329        // teravars failed to render.
330        unsafe {
331            std::env::remove_var("KANADE_DEV_AGENT_ID");
332        }
333        let cfg = load_agent_config(&cfg_path).expect("load agent.dev.toml (env unset)");
334        assert!(
335            !cfg.agent.id.is_empty(),
336            "pc_id should fall back to system.host"
337        );
338        assert_ne!(
339            cfg.agent.id, "{{ system.host }}",
340            "template should render, not leak"
341        );
342    }
343}