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}
110
111#[derive(Deserialize, Debug, Clone)]
112pub struct DbSection {
113 pub sqlite_path: String,
114}
115
116// ─── Loader ──────────────────────────────────────────────────────────
117
118fn load_typed<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T> {
119 let mut engine = teravars::Engine::new();
120 let ctx = teravars::system_context();
121 let paths: Vec<PathBuf> = vec![path.to_path_buf()];
122 let merged = teravars::load_merged(&paths, &mut engine, &ctx)
123 .with_context(|| format!("teravars load_merged: {path:?}"))?;
124 let cfg: T = toml::Value::Table(merged.config)
125 .try_into()
126 .with_context(|| format!("decode config from {path:?}"))?;
127 Ok(cfg)
128}
129
130pub fn load_agent_config(path: &Path) -> Result<AgentConfig> {
131 load_typed(path)
132}
133
134pub fn load_backend_config(path: &Path) -> Result<BackendConfig> {
135 load_typed(path)
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 /// Smoke test the dev-fleet flow against `agent.dev.toml`:
143 /// 1. When `KANADE_DEV_AGENT_ID` is set, the teravars template
144 /// resolves `vars.pc_id` to that value and propagates it
145 /// into `agent.id` + `log.path`. Also exercises a `[vars]`
146 /// self-reference (`pc_id` falls back to `vars.hostname`),
147 /// which `load_merged` resolves via its internal
148 /// fixed-point pass.
149 /// 2. Without the env, the template falls back to `system.host`
150 /// so vanilla `cargo make agent-dev` still works.
151 ///
152 /// Both halves live in a single `#[test]` so they execute
153 /// sequentially within the cargo test runtime — splitting them
154 /// across two tests races on `KANADE_DEV_AGENT_ID` (macOS CI
155 /// turned the race up enough to fail consistently).
156 #[test]
157 fn agent_dev_toml_renders_pc_id_from_env_or_system_host() {
158 // The dev config lives at the workspace root; CARGO_MANIFEST_DIR
159 // resolves to crates/kanade-shared/, so hop up two.
160 let cfg_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
161 .join("..")
162 .join("..")
163 .join("configs")
164 .join("agent.dev.toml");
165
166 // (1) env set → pc_id == env value
167 // SAFETY: env mutation is process-global; this single test
168 // body owns set + remove so no sibling test can race us.
169 unsafe {
170 std::env::set_var("KANADE_DEV_AGENT_ID", "dev-pc-render-test");
171 }
172 let cfg = load_agent_config(&cfg_path).expect("load agent.dev.toml (env set)");
173 assert_eq!(cfg.agent.id, "dev-pc-render-test");
174 assert!(
175 cfg.log.path.contains("dev-pc-render-test"),
176 "log path should embed pc_id, got {}",
177 cfg.log.path,
178 );
179
180 // (2) env removed → pc_id falls back to vars.hostname
181 // = system.host. The host string varies by box; just assert
182 // it's non-empty and not the literal template that would mean
183 // teravars failed to render.
184 unsafe {
185 std::env::remove_var("KANADE_DEV_AGENT_ID");
186 }
187 let cfg = load_agent_config(&cfg_path).expect("load agent.dev.toml (env unset)");
188 assert!(
189 !cfg.agent.id.is_empty(),
190 "pc_id should fall back to system.host"
191 );
192 assert_ne!(
193 cfg.agent.id, "{{ system.host }}",
194 "template should render, not leak"
195 );
196 }
197}