Skip to main content

sapphire_framework_server/
config.rs

1//! The server's own settings: `http.*` and `update.check` in `<config dir>/config.toml`.
2//!
3//! What a server offers beyond its IPC endpoint is the host's choice, so it lives in the
4//! application's config directory beside `workspace.toml`, with the application's own
5//! device settings (#314). Every setting is off or empty by default, and a missing file is
6//! all defaults. The server reads them when it starts, through [`Settings`]; the file used
7//! to be `server.toml`, which the server moves over once.
8//!
9//! ```toml
10//! [http]
11//! # Where the HTTP listener binds. Overrides the application's default address.
12//! listen = "127.0.0.1:3173"
13//! # The Host names clients use beyond loopback (a LAN name, a Tailscale name).
14//! allowed_hosts = ["box.tailnet.ts.net"]
15//!
16//! [http.mcp]
17//! # Serve the application's MCP tools at /mcp, behind an API key's token.
18//! enabled = true
19//!
20//! [http.metrics]
21//! # Serve Prometheus metrics at /metrics, without a token (counts and states only).
22//! enabled = true
23//!
24//! [update]
25//! # Do not ask GitHub for newer releases of this application. On by default, for an
26//! # application that names where its releases are.
27//! check = false
28//! ```
29
30use std::collections::BTreeSet;
31use std::net::SocketAddr;
32
33use sapphire_framework_settings::Value;
34use serde::{Deserialize, Serialize};
35
36use crate::error::{Error, Result};
37use crate::settings::{HTTP_NAMES, Settings};
38
39/// The device settings file's name inside the application's config directory.
40pub const SERVER_CONFIG_FILE: &str = "config.toml";
41
42/// Where the old `[mcp] http` went: `deny_unknown_fields` alone would only say that `mcp`
43/// is unknown.
44pub(crate) const MCP_MOVED: &str = "[mcp] http moved to [http.mcp] enabled";
45
46/// The server's settings, as `config.toml` holds them.
47#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(deny_unknown_fields)]
49pub struct ServerConfig {
50    /// The HTTP listener.
51    #[serde(default)]
52    pub http: HttpConfig,
53    /// Looking for newer releases.
54    #[serde(default)]
55    pub update: UpdateConfig,
56}
57
58/// The `[http]` table: the listener every HTTP route shares.
59///
60/// The listener binds only when something is served over it. Every route on it but
61/// `/metrics` is behind an API key's bearer token (`sapphire-framework-keys`).
62#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct HttpConfig {
65    /// Where to bind. `None` is the application's default address, if it has one.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub listen: Option<SocketAddr>,
68    /// The `Host` names clients reach the server by, beyond loopback.
69    #[serde(default, skip_serializing_if = "Vec::is_empty")]
70    pub allowed_hosts: Vec<String>,
71    /// MCP over HTTP.
72    #[serde(default, skip_serializing_if = "is_default")]
73    pub mcp: HttpMcpConfig,
74    /// Prometheus metrics over HTTP.
75    #[serde(default, skip_serializing_if = "is_default")]
76    pub metrics: HttpMetricsConfig,
77    /// The application's HTTP endpoints turned on (`http.<name>.enabled`), by name. Read
78    /// from the settings, which know the endpoints the application declares.
79    #[serde(skip)]
80    pub endpoints: BTreeSet<String>,
81}
82
83/// The `[http.mcp]` table.
84#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(deny_unknown_fields)]
86pub struct HttpMcpConfig {
87    /// Serve the application's MCP tools at `/mcp` on the HTTP listener. Off by default.
88    #[serde(default)]
89    pub enabled: bool,
90}
91
92/// The `[http.metrics]` table.
93#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(deny_unknown_fields)]
95pub struct HttpMetricsConfig {
96    /// Serve Prometheus metrics at `/metrics` on the HTTP listener. Off by default.
97    #[serde(default)]
98    pub enabled: bool,
99}
100
101/// Serde's `skip_serializing_if` wants a function, and a table that is all defaults is
102/// not worth writing out.
103fn is_default<T: Default + PartialEq>(value: &T) -> bool {
104    *value == T::default()
105}
106
107/// The `[update]` table.
108#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(deny_unknown_fields)]
110pub struct UpdateConfig {
111    /// Ask the application's release page for newer releases, once at start and once a
112    /// day. On by default; it does nothing for an application that names no release page.
113    #[serde(default = "UpdateConfig::default_check")]
114    pub check: bool,
115}
116
117impl UpdateConfig {
118    fn default_check() -> bool {
119        true
120    }
121}
122
123impl Default for UpdateConfig {
124    fn default() -> Self {
125        UpdateConfig { check: true }
126    }
127}
128
129impl ServerConfig {
130    /// The framework's settings out of `settings`, as they were when it was read.
131    pub fn from_settings(settings: &Settings) -> Result<ServerConfig> {
132        let flag = |key: &str, default: bool| match settings.get(key) {
133            None => Ok(default),
134            Some(Value::Bool(b)) => Ok(b),
135            Some(_) => Err(invalid(key)),
136        };
137        let listen = match settings.get("http.listen") {
138            None => None,
139            Some(Value::String(s)) => Some(s.parse().map_err(|_| invalid("http.listen"))?),
140            Some(_) => return Err(invalid("http.listen")),
141        };
142        let allowed_hosts = match settings.get("http.allowed_hosts") {
143            None => Vec::new(),
144            Some(_) => settings
145                .get_as::<Vec<String>>("http.allowed_hosts")
146                .ok_or_else(|| invalid("http.allowed_hosts"))?,
147        };
148        let mut endpoints = BTreeSet::new();
149        for def in settings.registry().schema() {
150            let Some(name) = def
151                .key
152                .strip_prefix("http.")
153                .and_then(|rest| rest.strip_suffix(".enabled"))
154                .filter(|name| !name.contains('.') && !HTTP_NAMES.contains(name))
155            else {
156                continue;
157            };
158            if flag(&def.key, false)? {
159                endpoints.insert(name.to_owned());
160            }
161        }
162        Ok(ServerConfig {
163            http: HttpConfig {
164                listen,
165                allowed_hosts,
166                endpoints,
167                mcp: HttpMcpConfig {
168                    enabled: flag("http.mcp.enabled", false)?,
169                },
170                metrics: HttpMetricsConfig {
171                    enabled: flag("http.metrics.enabled", false)?,
172                },
173            },
174            update: UpdateConfig {
175                check: flag("update.check", true)?,
176            },
177        })
178    }
179}
180
181/// A framework setting whose value is not one it takes; the value itself is not repeated.
182fn invalid(key: &str) -> Error {
183    Error::Config(format!(
184        "`{key}` in {SERVER_CONFIG_FILE} does not hold a valid value"
185    ))
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use std::sync::Arc;
192
193    /// The server config a `config.toml` of `text` (none for `None`) reads as.
194    fn from_text(text: Option<&str>) -> Result<ServerConfig> {
195        let tmp = tempfile::TempDir::new().unwrap();
196        let ctx = sapphire_workspace::AppContext::new("configtest");
197        ctx.set_config_dir(tmp.path().to_path_buf());
198        if let Some(text) = text {
199            std::fs::write(tmp.path().join(SERVER_CONFIG_FILE), text).unwrap();
200        }
201        ServerConfig::from_settings(&Settings::load(&ctx, Arc::new(()))?)
202    }
203
204    #[test]
205    fn a_missing_file_is_all_defaults_and_mcp_is_off() {
206        let config = from_text(None).unwrap();
207        assert_eq!(config, ServerConfig::default());
208        assert!(!config.http.mcp.enabled);
209        assert!(!config.http.metrics.enabled);
210        assert_eq!(config.http.listen, None);
211        assert!(config.update.check);
212    }
213
214    #[test]
215    fn the_file_turns_the_update_check_off() {
216        assert!(
217            !from_text(Some("[update]\ncheck = false\n"))
218                .unwrap()
219                .update
220                .check
221        );
222        assert!(from_text(Some("[update]\n")).unwrap().update.check);
223    }
224
225    #[test]
226    fn the_file_turns_mcp_on_and_names_the_listener() {
227        let config = from_text(Some(
228            "[http]\nlisten = \"127.0.0.1:3173\"\nallowed_hosts = [\"box.example\"]\n\n[http.mcp]\nenabled = true\n",
229        ))
230        .unwrap();
231        assert!(config.http.mcp.enabled);
232        assert_eq!(config.http.listen, Some("127.0.0.1:3173".parse().unwrap()));
233        assert_eq!(config.http.allowed_hosts, vec!["box.example".to_owned()]);
234    }
235
236    #[test]
237    fn a_misspelt_setting_is_an_error_not_a_default() {
238        assert!(from_text(Some("[http.mcp]\nenabeld = true\n")).is_err());
239        // A table of another name may be the application's own: the file is shared.
240        assert!(from_text(Some("[htp]\nlisten = \"127.0.0.1:1\"\n")).is_ok());
241    }
242
243    #[test]
244    fn the_file_turns_metrics_on_under_http() {
245        let config = from_text(Some(
246            "[http]\nlisten = \"127.0.0.1:3173\"\n\n[http.metrics]\nenabled = true\n",
247        ))
248        .unwrap();
249        assert!(config.http.metrics.enabled);
250        assert!(!config.http.mcp.enabled);
251    }
252
253    #[test]
254    fn the_application_keeps_its_own_table() {
255        let config = from_text(Some("[configtest]\nanything = 1\n")).unwrap();
256        assert_eq!(config, ServerConfig::default());
257    }
258}