manta_server/
config.rs

1//! Typed schema for `server.toml`.
2//!
3//! The untyped `config::Config` is loaded by
4//! [`manta_shared::common::config::get_server_configuration`]; this
5//! module owns the typed deserialisation target.
6//!
7//! The shape on disk is:
8//!
9//! ```toml
10//! log = "info"
11//!
12//! [server]
13//! listen_address = "0.0.0.0"
14//! port = 8443
15//! cert = "/etc/manta/tls/server.crt"
16//! key = "/etc/manta/tls/server.key"
17//! console_inactivity_timeout_secs = 1800
18//! auth_rate_limit_per_minute = 60
19//!
20//! [sites.alps]
21//! backend = "csm"
22//! shasta_base_url = "https://api.alps.cscs.ch"
23//! root_ca_cert_file = "/etc/manta/alps-ca.pem"
24//! ```
25//!
26//! [`ServerConfiguration`] is the top-level type; [`ServerSettings`]
27//! and [`Site`] are its nested sections. There is no notion of an
28//! "active" site — the server hosts every entry in `[sites.*]`
29//! simultaneously and clients pick one per request via the
30//! `X-Manta-Site` header.
31
32use std::collections::HashMap;
33
34use crate::server::common::audit::Auditor;
35use manta_backend_dispatcher::types::K8sDetails;
36use serde::{Deserialize, Serialize};
37
38/// Which backend API this site speaks.
39#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
40#[serde(rename_all = "lowercase")]
41pub enum BackendTechnology {
42  /// HPE Cray System Management (CSM) backend.
43  Csm,
44  /// OpenCHAMI backend.
45  Ochami,
46}
47
48impl BackendTechnology {
49  /// Return the lowercase string expected by `StaticBackendDispatcher::new`.
50  pub fn as_str(&self) -> &'static str {
51    match self {
52      Self::Csm => "csm",
53      Self::Ochami => "ochami",
54    }
55  }
56}
57
58#[derive(Serialize, Deserialize, Debug)]
59/// Connection details for a single ALPS site (CSM or OCHAMI instance).
60///
61/// The Vault URL used by handlers requiring vault (sat-file, session,
62/// console, logs) is derived at startup from
63/// `[sites.X.k8s.authentication.vault] base_url`. The vault secret path
64/// is derived from a hard-coded prefix and the site name. Neither is
65/// configured here.
66pub struct Site {
67  /// Which backend implementation this site uses (`csm` or `ochami`).
68  pub backend: BackendTechnology,
69  /// Base URL of the backend API (e.g. `https://api.alps.cscs.ch`).
70  pub shasta_base_url: String,
71  /// Optional Kubernetes connection details, required by handlers
72  /// that stream CFS session logs or attach to consoles.
73  pub k8s: Option<K8sDetails>,
74  /// Path (absolute or relative to the config dir) of the backend's
75  /// root CA certificate, used to verify TLS to `shasta_base_url`.
76  pub root_ca_cert_file: String,
77}
78
79/// Server-only settings — TLS, listen address, console behaviour. Lives
80/// under `[server]` in `server.toml`.
81#[derive(Serialize, Deserialize, Debug)]
82pub struct ServerSettings {
83  /// TCP listen address (e.g. "0.0.0.0"). When omitted from config
84  /// **and** no `--listen-address` flag is supplied, the server falls
85  /// back to `"0.0.0.0"`.
86  #[serde(default)]
87  pub listen_address: Option<String>,
88  /// TCP port. When omitted from config **and** no `--port` flag is
89  /// supplied, the effective default depends on whether TLS is
90  /// configured: `8443` if both `cert` and `key` are present (HTTPS),
91  /// otherwise `8080` (plain HTTP). See
92  /// [`ServerSettings::default_port`].
93  #[serde(default)]
94  pub port: Option<u16>,
95  /// Path to the TLS certificate (PEM).
96  pub cert: Option<String>,
97  /// Path to the TLS private key (PEM).
98  pub key: Option<String>,
99  /// How long a node-console WebSocket stays open without activity
100  /// before the server tears it down.
101  pub console_inactivity_timeout_secs: u64,
102  /// Per-source-IP rate limit for the `/v2/auth/*` endpoints,
103  /// in requests per minute. `None` disables in-process rate limiting
104  /// (operators are then expected to enforce it at the reverse proxy).
105  pub auth_rate_limit_per_minute: Option<u32>,
106  /// Global request timeout applied to every HTTP route, in seconds.
107  /// When this elapses the server returns `408 REQUEST_TIMEOUT`. All
108  /// long-running work (e.g. power transitions) now runs CLI-side,
109  /// so no endpoint needs more than the default.
110  #[serde(default = "default_request_timeout_secs")]
111  pub request_timeout_secs: u64,
112  /// Grace period (seconds) `axum_server` waits for in-flight
113  /// requests to finish after SIGTERM / Ctrl+C before force-aborting.
114  /// Matches the standard k8s `terminationGracePeriodSeconds` default
115  /// (30 s); pods that hit this without finishing get SIGKILL'd by
116  /// the kubelet.
117  #[serde(default = "default_shutdown_grace_period_secs")]
118  pub shutdown_grace_period_secs: u64,
119  /// Filesystem root that confines `POST /migrate/{backup,restore}`
120  /// file access. When set, every `destination` / `bos_file` /
121  /// `cfs_file` / `hsm_file` / `ims_file` / `image_dir` path in the
122  /// request is canonicalised and rejected unless it resolves under
123  /// this directory. When unset (default), the migrate endpoints
124  /// return `BadRequest` even for admin callers — the operator must
125  /// explicitly opt in to server-side filesystem writes.
126  #[serde(default)]
127  pub migrate_backup_root: Option<String>,
128  /// Opt in to plain-HTTP listen mode. Default `false`: when neither
129  /// `cert` nor `key` is configured the server refuses to start, so
130  /// bearer tokens can't accidentally land on the wire in cleartext.
131  /// Set to `true` only when TLS terminates upstream (reverse proxy
132  /// or sidecar); otherwise leave it off and configure both `cert`
133  /// and `key`.
134  #[serde(default)]
135  pub allow_http: bool,
136}
137
138impl ServerSettings {
139  /// Effective default listen address when neither config nor CLI flag
140  /// supplies one: bind on all interfaces.
141  pub const DEFAULT_LISTEN_ADDRESS: &'static str = "0.0.0.0";
142
143  /// Effective default port when neither config nor CLI flag supplies
144  /// one. `8443` for the HTTPS path (cert + key both present), `8080`
145  /// for plain HTTP — the latter is the typical dev / sidecar setup
146  /// where TLS is terminated upstream.
147  pub fn default_port(has_tls: bool) -> u16 {
148    if has_tls { 8443 } else { 8080 }
149  }
150}
151
152/// Default global request timeout — 600s (10 min). Bumped from 300s
153/// after `GET /cache/configuration` (and other cross-resource fan-out
154/// endpoints that hit CFS + BSS + IMS concurrently) started 408'ing
155/// against busy sites where any single upstream fetch can stall on
156/// the CSM Envoy reset window. 10 min still bounds truly hung
157/// requests while letting heavy-but-healthy ones through. Override
158/// via `request_timeout_secs` in `server.toml` if your deployment
159/// needs a different ceiling.
160fn default_shutdown_grace_period_secs() -> u64 {
161  30
162}
163
164fn default_request_timeout_secs() -> u64 {
165  600
166}
167
168/// Top-level configuration for the `manta-server` binary.
169///
170/// Persisted as TOML under `~/.config/manta/server.toml` and loaded
171/// once at startup. Has no notion of an "active" site — the server
172/// hosts every entry in [`Self::sites`] simultaneously and clients
173/// select per-request via the `X-Manta-Site` header.
174///
175/// See the module-level docs for the on-disk layout.
176#[derive(Serialize, Deserialize, Debug)]
177pub struct ServerConfiguration {
178  /// `EnvFilter` directive for the tracing subscriber.
179  pub log: String,
180  /// Network / TLS / console / rate-limit knobs for the HTTPS server.
181  pub server: ServerSettings,
182  /// Per-site backend connection details, keyed by site name. The
183  /// `X-Manta-Site` header on each request picks which one to route to.
184  pub sites: HashMap<String, Site>,
185  /// Optional Kafka audit forwarder (typically used for `/auth/*`
186  /// attempts). When `None`, the server emits no audit messages.
187  pub auditor: Option<Auditor>,
188}
189
190#[cfg(test)]
191mod tests {
192  use super::*;
193
194  #[test]
195  fn site_deserialize_missing_backend_fails() {
196    let bad_toml = r#"
197      shasta_base_url = "https://api.example.com"
198      root_ca_cert_file = "cert.pem"
199      # missing backend
200    "#;
201    let result = toml::from_str::<Site>(bad_toml);
202    assert!(result.is_err());
203  }
204
205  #[test]
206  fn backend_technology_as_str() {
207    assert_eq!(BackendTechnology::Csm.as_str(), "csm");
208    assert_eq!(BackendTechnology::Ochami.as_str(), "ochami");
209  }
210
211  #[test]
212  fn backend_technology_roundtrip_toml() {
213    // Verify TOML serializes as lowercase "csm" / "ochami"
214    #[derive(Serialize, Deserialize)]
215    struct Wrapper {
216      backend: BackendTechnology,
217    }
218    let w = Wrapper {
219      backend: BackendTechnology::Csm,
220    };
221    let s = toml::to_string(&w).unwrap();
222    assert!(s.contains("\"csm\"") || s.contains("csm"));
223    let parsed: Wrapper = toml::from_str(&s).unwrap();
224    assert_eq!(parsed.backend, BackendTechnology::Csm);
225  }
226
227  fn make_minimal_site() -> Site {
228    Site {
229      backend: BackendTechnology::Csm,
230      shasta_base_url: "https://api.example.com".to_string(),
231      k8s: None,
232      root_ca_cert_file: "cert.pem".to_string(),
233    }
234  }
235
236  #[test]
237  fn server_configuration_roundtrip_toml_minimal() {
238    let mut sites = HashMap::new();
239    sites.insert("alps".to_string(), make_minimal_site());
240    let cfg = ServerConfiguration {
241      log: "info".to_string(),
242      server: ServerSettings {
243        listen_address: Some("0.0.0.0".to_string()),
244        port: Some(8443),
245        cert: Some("/etc/manta/tls/server.crt".to_string()),
246        key: Some("/etc/manta/tls/server.key".to_string()),
247        console_inactivity_timeout_secs: 1800,
248        auth_rate_limit_per_minute: Some(60),
249        request_timeout_secs: 300,
250        shutdown_grace_period_secs: 30,
251        migrate_backup_root: None,
252        allow_http: false,
253      },
254      sites,
255      auditor: None,
256    };
257    let toml_str = toml::to_string(&cfg).unwrap();
258    let parsed: ServerConfiguration = toml::from_str(&toml_str).unwrap();
259    assert_eq!(parsed.server.port, Some(8443));
260    assert_eq!(parsed.server.listen_address.as_deref(), Some("0.0.0.0"));
261    assert_eq!(parsed.server.console_inactivity_timeout_secs, 1800);
262    assert_eq!(parsed.server.request_timeout_secs, 300);
263    assert_eq!(
264      parsed.server.cert.as_deref(),
265      Some("/etc/manta/tls/server.crt")
266    );
267  }
268
269  /// Default port helper: 8443 when TLS is configured, 8080
270  /// otherwise. Used by `manta-server::main` when no `port` is set
271  /// in config or on the CLI.
272  #[test]
273  fn server_settings_default_port_depends_on_tls() {
274    assert_eq!(ServerSettings::default_port(true), 8443);
275    assert_eq!(ServerSettings::default_port(false), 8080);
276  }
277
278  /// power_timeout_secs is gone — confirm the surrounding
279  /// timeout-related fields still default correctly when the only
280  /// remaining knob is absent.
281  #[test]
282  fn server_settings_request_timeout_secs_defaults_to_600() {
283    let toml_str = r#"
284      listen_address = "0.0.0.0"
285      port = 8443
286      console_inactivity_timeout_secs = 1800
287    "#;
288    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
289    assert_eq!(parsed.request_timeout_secs, 600);
290  }
291
292  /// `[server]` block with neither `listen_address` nor `port`
293  /// supplied — both fields deserialise as `None`, leaving the
294  /// effective values to be filled in at startup time. Confirms the
295  /// schema-level back-compat for the new defaults.
296  #[test]
297  fn server_settings_listen_address_and_port_default_to_none() {
298    let toml_str = r#"
299      console_inactivity_timeout_secs = 1800
300    "#;
301    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
302    assert!(parsed.listen_address.is_none());
303    assert!(parsed.port.is_none());
304  }
305
306  /// Existing server.toml files that pre-date the request_timeout
307  /// field must keep working — the field falls back to its default.
308  #[test]
309  fn server_settings_request_timeout_field_defaults_when_omitted() {
310    let toml_str = r#"
311      listen_address = "0.0.0.0"
312      port = 8443
313      console_inactivity_timeout_secs = 1800
314    "#;
315    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
316    assert_eq!(parsed.request_timeout_secs, 600);
317  }
318
319  #[test]
320  fn server_configuration_deserialize_missing_server_section_fails() {
321    let bad_toml = r#"
322      log = "info"
323      [sites]
324    "#;
325    let result = toml::from_str::<ServerConfiguration>(bad_toml);
326    assert!(result.is_err());
327  }
328
329  #[test]
330  fn server_settings_optional_tls_paths() {
331    // TLS cert/key are optional in the schema — flags can supply them
332    // at runtime when the config omits them.
333    let toml_str = r#"
334      listen_address = "0.0.0.0"
335      port = 8443
336      console_inactivity_timeout_secs = 1800
337    "#;
338    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
339    assert!(parsed.cert.is_none());
340    assert!(parsed.key.is_none());
341  }
342}