Skip to main content

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//!
19//! [sites.alps]
20//! backend = "csm"
21//! shasta_base_url = "https://api.alps.cscs.ch"
22//! root_ca_cert_file = "/etc/manta/alps-ca.pem"
23//!
24//! [sites.alps.token_exchange]
25//! client_id = "cscs-token-exchanger"
26//! client_secret = "…"
27//! subject_issuer = "cscs"
28//!
29//! [sites.basodino]
30//! backend = "ochami"
31//! shasta_base_url = "https://basodino-mgmt.cscs.ch:8443"
32//! root_ca_cert_file = "/etc/manta/basodino-ca.pem"
33//!
34//! [sites.basodino.token_exchange]
35//! client_id = "…"
36//! client_secret = "…"
37//! scope = "smd.read bss.read smd.write bss.write"
38//! ```
39//!
40//! [`ServerConfiguration`] is the top-level type; [`ServerSettings`]
41//! and [`Site`] are its nested sections. There is no notion of an
42//! "active" site — the server hosts every entry in `[sites.*]`
43//! simultaneously and clients pick one per request via the
44//! `X-Manta-Site` header.
45
46use std::collections::HashMap;
47
48use crate::server::audit::Auditor;
49use manta_backend_dispatcher::{error::Error, types::K8sDetails};
50use serde::{Deserialize, Serialize};
51
52/// Which backend API this site speaks.
53#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
54#[serde(rename_all = "lowercase")]
55pub enum BackendTechnology {
56  /// HPE Cray System Management (CSM) backend.
57  Csm,
58  /// OpenCHAMI backend.
59  Ochami,
60}
61
62impl BackendTechnology {
63  /// Return the lowercase string expected by `StaticBackendDispatcher::new`.
64  pub fn as_str(&self) -> &'static str {
65    match self {
66      Self::Csm => "csm",
67      Self::Ochami => "ochami",
68    }
69  }
70}
71
72#[derive(Serialize, Deserialize, Debug)]
73/// Connection details for a single ALPS site (CSM or OCHAMI instance).
74///
75/// The Vault URL used by handlers requiring vault (sat-file, session,
76/// console, logs) is derived at startup from
77/// `[sites.X.k8s.authentication.vault] base_url`. The vault secret path
78/// is derived from a hard-coded prefix and the site name. Neither is
79/// configured here.
80pub struct Site {
81  /// Which backend implementation this site uses (`csm` or `ochami`).
82  pub backend: BackendTechnology,
83  /// Base URL of the backend API (e.g. `https://api.alps.cscs.ch`).
84  pub shasta_base_url: String,
85  /// Optional Kubernetes connection details, required by handlers
86  /// that stream CFS session logs or attach to consoles.
87  pub k8s: Option<K8sDetails>,
88  /// Path (absolute or relative to the config dir) of the backend's
89  /// root CA certificate, used to verify TLS to `shasta_base_url`.
90  pub root_ca_cert_file: String,
91  /// How to exchange the caller's CSCS Keycloak token for a token this
92  /// site accepts. Required: the server refuses to start without it.
93  pub token_exchange: Option<TokenExchangeConfig>,
94}
95
96/// `[sites.X.token_exchange]`: client credentials for exchanging the
97/// caller's CSCS Keycloak token for a token the site accepts.
98///
99/// - `csm` sites use an RFC 8693 token exchange at the site's Keycloak
100///   (`shasta` realm), at a URL derived from `shasta_base_url`
101///   (`<base without a trailing /apis>/keycloak`). They need
102///   `subject_issuer`.
103/// - `ochami` sites use an RFC 7523 JWT bearer grant at the site's
104///   Hydra, at a URL derived from `shasta_base_url`
105///   (`<base>/hydra/oauth2/token`). They need `scope`.
106///
107/// [`TokenExchangeConfig::csm`] and [`TokenExchangeConfig::ochami`]
108/// check that the backend's fields are present.
109#[derive(Serialize, Deserialize, Clone)]
110pub struct TokenExchangeConfig {
111  /// Client allowed to exchange tokens, e.g. `cscs-token-exchanger`.
112  pub client_id: String,
113  /// Secret of the confidential `client_id`.
114  pub client_secret: String,
115  /// `csm` only: alias of the CSCS identity provider in the `shasta`
116  /// realm, e.g. `cscs`.
117  #[serde(default, skip_serializing_if = "Option::is_none")]
118  pub subject_issuer: Option<String>,
119  /// `ochami` only: space-separated scopes to request.
120  #[serde(default, skip_serializing_if = "Option::is_none")]
121  pub scope: Option<String>,
122}
123
124impl std::fmt::Debug for TokenExchangeConfig {
125  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126    f.debug_struct("TokenExchangeConfig")
127      .field("client_id", &self.client_id)
128      .field("client_secret", &"<redacted>")
129      .field("subject_issuer", &self.subject_issuer)
130      .field("scope", &self.scope)
131      .finish()
132  }
133}
134
135impl TokenExchangeConfig {
136  /// The credentials as `csm-rs` takes them.
137  ///
138  /// # Errors
139  ///
140  /// [`Error::MissingField`] when `subject_issuer` is not set.
141  pub fn csm(&self) -> Result<csm_rs::backend_connector::TokenExchange, Error> {
142    Ok(csm_rs::backend_connector::TokenExchange {
143      client_id: self.client_id.clone(),
144      client_secret: self.client_secret.clone(),
145      subject_issuer: required(&self.subject_issuer, "subject_issuer", "csm")?,
146    })
147  }
148
149  /// The credentials as `ochami-rs` takes them.
150  ///
151  /// # Errors
152  ///
153  /// [`Error::MissingField`] when `scope` is not set.
154  pub fn ochami(
155    &self,
156  ) -> Result<ochami_rs::authentication::TokenExchange, Error> {
157    Ok(ochami_rs::authentication::TokenExchange {
158      client_id: self.client_id.clone(),
159      client_secret: self.client_secret.clone(),
160      scope: required(&self.scope, "scope", "ochami")?,
161    })
162  }
163}
164
165fn required(
166  value: &Option<String>,
167  field: &str,
168  backend: &str,
169) -> Result<String, Error> {
170  value.clone().ok_or_else(|| {
171    Error::MissingField(format!(
172      "token_exchange.{field} is required for backend = \"{backend}\""
173    ))
174  })
175}
176
177/// Server-only settings — TLS, listen address, console behaviour. Lives
178/// under `[server]` in `server.toml`.
179#[derive(Serialize, Deserialize, Debug)]
180pub struct ServerSettings {
181  /// TCP listen address (e.g. "0.0.0.0"). When omitted from config
182  /// **and** no `--listen-address` flag is supplied, the server falls
183  /// back to `"0.0.0.0"`.
184  #[serde(default)]
185  pub listen_address: Option<String>,
186  /// TCP port. When omitted from config **and** no `--port` flag is
187  /// supplied, the effective default depends on whether TLS is
188  /// configured: `8443` if both `cert` and `key` are present (HTTPS),
189  /// otherwise `8080` (plain HTTP). See
190  /// [`ServerSettings::default_port`].
191  #[serde(default)]
192  pub port: Option<u16>,
193  /// Path to the TLS certificate (PEM).
194  pub cert: Option<String>,
195  /// Path to the TLS private key (PEM).
196  pub key: Option<String>,
197  /// How long a node-console WebSocket stays open without activity
198  /// before the server tears it down.
199  pub console_inactivity_timeout_secs: u64,
200  /// Global request timeout applied to every HTTP route, in seconds.
201  /// When this elapses the server returns `408 REQUEST_TIMEOUT`. All
202  /// long-running work (e.g. power transitions) now runs CLI-side,
203  /// so no endpoint needs more than the default.
204  #[serde(default = "default_request_timeout_secs")]
205  pub request_timeout_secs: u64,
206  /// Grace period (seconds) `axum_server` waits for in-flight
207  /// requests to finish after SIGTERM / Ctrl+C before force-aborting.
208  /// Matches the standard k8s `terminationGracePeriodSeconds` default
209  /// (30 s); pods that hit this without finishing get SIGKILL'd by
210  /// the kubelet.
211  #[serde(default = "default_shutdown_grace_period_secs")]
212  pub shutdown_grace_period_secs: u64,
213  /// Filesystem root that confines `POST /migrate/{backup,restore}`
214  /// file access. When set, every `destination` / `bos_file` /
215  /// `cfs_file` / `hsm_file` / `ims_file` / `image_dir` path in the
216  /// request is canonicalised and rejected unless it resolves under
217  /// this directory. When unset (default), the migrate endpoints
218  /// return `BadRequest` even for admin callers — the operator must
219  /// explicitly opt in to server-side filesystem writes.
220  #[serde(default)]
221  pub migrate_backup_root: Option<String>,
222  /// Opt in to plain-HTTP listen mode. Default `false`: when neither
223  /// `cert` nor `key` is configured the server refuses to start, so
224  /// bearer tokens can't accidentally land on the wire in cleartext.
225  /// Set to `true` only when TLS terminates upstream (reverse proxy
226  /// or sidecar); otherwise leave it off and configure both `cert`
227  /// and `key`.
228  #[serde(default)]
229  pub allow_http: bool,
230}
231
232impl ServerSettings {
233  /// Effective default listen address when neither config nor CLI flag
234  /// supplies one: bind on all interfaces.
235  pub const DEFAULT_LISTEN_ADDRESS: &'static str = "0.0.0.0";
236
237  /// Effective default port when neither config nor CLI flag supplies
238  /// one. `8443` for the HTTPS path (cert + key both present), `8080`
239  /// for plain HTTP — the latter is the typical dev / sidecar setup
240  /// where TLS is terminated upstream.
241  pub fn default_port(has_tls: bool) -> u16 {
242    if has_tls { 8443 } else { 8080 }
243  }
244}
245
246/// Default global request timeout — 600s (10 min). Bumped from 300s
247/// after `GET /cache/configuration` (and other cross-resource fan-out
248/// endpoints that hit CFS + BSS + IMS concurrently) started 408'ing
249/// against busy sites where any single upstream fetch can stall on
250/// the CSM Envoy reset window. 10 min still bounds truly hung
251/// requests while letting heavy-but-healthy ones through. Override
252/// via `request_timeout_secs` in `server.toml` if your deployment
253/// needs a different ceiling.
254fn default_shutdown_grace_period_secs() -> u64 {
255  30
256}
257
258fn default_request_timeout_secs() -> u64 {
259  600
260}
261
262/// Top-level configuration for the `manta-server` binary.
263///
264/// Persisted as TOML under `~/.config/manta/server.toml` and loaded
265/// once at startup. Has no notion of an "active" site — the server
266/// hosts every entry in [`Self::sites`] simultaneously and clients
267/// select per-request via the `X-Manta-Site` header.
268///
269/// See the module-level docs for the on-disk layout.
270#[derive(Serialize, Deserialize, Debug)]
271pub struct ServerConfiguration {
272  /// `EnvFilter` directive for the tracing subscriber.
273  pub log: String,
274  /// Network / TLS / console / timeout knobs for the HTTPS server.
275  pub server: ServerSettings,
276  /// Per-site backend connection details, keyed by site name. The
277  /// `X-Manta-Site` header on each request picks which one to route to.
278  pub sites: HashMap<String, Site>,
279  /// Optional Kafka destination for the audit trail. When `None`,
280  /// audit events go to the log (`manta::audit` target) only.
281  pub auditor: Option<Auditor>,
282}
283
284#[cfg(test)]
285mod tests {
286  use super::*;
287
288  #[test]
289  fn site_deserialize_missing_backend_fails() {
290    let bad_toml = r#"
291      shasta_base_url = "https://api.example.com"
292      root_ca_cert_file = "cert.pem"
293      # missing backend
294    "#;
295    let result = toml::from_str::<Site>(bad_toml);
296    assert!(result.is_err());
297  }
298
299  #[test]
300  fn backend_technology_as_str() {
301    assert_eq!(BackendTechnology::Csm.as_str(), "csm");
302    assert_eq!(BackendTechnology::Ochami.as_str(), "ochami");
303  }
304
305  #[test]
306  fn backend_technology_roundtrip_toml() {
307    // Verify TOML serializes as lowercase "csm" / "ochami"
308    #[derive(Serialize, Deserialize)]
309    struct Wrapper {
310      backend: BackendTechnology,
311    }
312    let w = Wrapper {
313      backend: BackendTechnology::Csm,
314    };
315    let s = toml::to_string(&w).unwrap();
316    assert!(s.contains("\"csm\"") || s.contains("csm"));
317    let parsed: Wrapper = toml::from_str(&s).unwrap();
318    assert_eq!(parsed.backend, BackendTechnology::Csm);
319  }
320
321  fn make_minimal_site() -> Site {
322    Site {
323      backend: BackendTechnology::Csm,
324      shasta_base_url: "https://api.example.com".to_string(),
325      k8s: None,
326      root_ca_cert_file: "cert.pem".to_string(),
327      token_exchange: Some(TokenExchangeConfig {
328        client_id: "cscs-token-exchanger".to_string(),
329        client_secret: "s3cret".to_string(),
330        subject_issuer: Some("cscs".to_string()),
331        scope: None,
332      }),
333    }
334  }
335
336  /// `examples/server.toml`, with its commented-out sites enabled, is a
337  /// config the server starts with: every site has the token exchange
338  /// its backend needs (`run_server` refuses a site without one, and
339  /// [`TokenExchangeConfig::csm`] / [`TokenExchangeConfig::ochami`] check
340  /// the backend's fields).
341  #[test]
342  fn the_example_server_toml_is_a_valid_config() {
343    let path =
344      concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/server.toml");
345    let example = std::fs::read_to_string(path).unwrap();
346    // Each commented-out site: a `# [sites.<name>]` line and the comment
347    // lines right after it, with the `# ` taken off. (Not the commented
348    // alternatives inside an enabled site, such as `alps`' `Native`.)
349    let is_site_header = |line: &str| {
350      line
351        .strip_prefix("# [sites.")
352        .and_then(|rest| rest.strip_suffix(']'))
353        .is_some_and(|name| !name.contains('.'))
354    };
355    let mut enabled = String::new();
356    let mut in_site = false;
357    for line in example.lines() {
358      if is_site_header(line) {
359        in_site = true;
360      } else if !line.starts_with('#') {
361        in_site = false;
362      }
363      if in_site {
364        let toml_line = line.strip_prefix('#').unwrap_or(line);
365        enabled.push_str(toml_line.strip_prefix(' ').unwrap_or(toml_line));
366        enabled.push('\n');
367      }
368    }
369    let config: ServerConfiguration =
370      toml::from_str(&format!("{example}\n{enabled}")).unwrap();
371
372    assert!(
373      config.sites.contains_key("ochami-dev"),
374      "{:?}",
375      config.sites.keys()
376    );
377    for (name, site) in &config.sites {
378      let exchange = site
379        .token_exchange
380        .as_ref()
381        .unwrap_or_else(|| panic!("[sites.{name}] has no token_exchange"));
382      match site.backend {
383        BackendTechnology::Csm => assert!(exchange.csm().is_ok(), "{name}"),
384        BackendTechnology::Ochami => {
385          assert!(exchange.ochami().is_ok(), "{name}");
386        }
387      }
388    }
389  }
390
391  #[test]
392  fn token_exchange_may_be_absent_in_toml() {
393    let site: Site = toml::from_str(
394      r#"
395      backend = "ochami"
396      shasta_base_url = "https://api.example.com"
397      root_ca_cert_file = "cert.pem"
398    "#,
399    )
400    .unwrap();
401    assert!(site.token_exchange.is_none());
402  }
403
404  #[test]
405  fn token_exchange_parses_and_redacts_the_secret() {
406    let site: Site = toml::from_str(
407      r#"
408      backend = "csm"
409      shasta_base_url = "https://api.example.com"
410      root_ca_cert_file = "cert.pem"
411
412      [token_exchange]
413      client_id = "cscs-token-exchanger"
414      client_secret = "s3cret"
415      subject_issuer = "cscs"
416    "#,
417    )
418    .unwrap();
419    let te = site.token_exchange.expect("token_exchange parsed");
420    assert_eq!(te.client_id, "cscs-token-exchanger");
421    assert_eq!(te.client_secret, "s3cret");
422    assert_eq!(te.subject_issuer.as_deref(), Some("cscs"));
423    assert_eq!(te.csm().unwrap().subject_issuer, "cscs");
424    assert!(!format!("{te:?}").contains("s3cret"));
425  }
426
427  #[test]
428  fn ochami_token_exchange_parses() {
429    let site: Site = toml::from_str(
430      r#"
431      backend = "ochami"
432      shasta_base_url = "https://api.example.com"
433      root_ca_cert_file = "cert.pem"
434
435      [token_exchange]
436      client_id = "client"
437      client_secret = "s3cret"
438      scope = "smd.read bss.read"
439    "#,
440    )
441    .unwrap();
442    let te = site
443      .token_exchange
444      .expect("token_exchange parsed")
445      .ochami()
446      .unwrap();
447    assert_eq!(te.scope, "smd.read bss.read");
448  }
449
450  #[test]
451  fn each_backend_names_the_token_exchange_field_it_misses() {
452    let te = TokenExchangeConfig {
453      client_id: "client".to_string(),
454      client_secret: "s3cret".to_string(),
455      subject_issuer: None,
456      scope: None,
457    };
458    let csm_err = te.csm().unwrap_err().to_string();
459    assert!(csm_err.contains("subject_issuer"), "{csm_err}");
460    let ochami_err = te.ochami().unwrap_err().to_string();
461    assert!(ochami_err.contains("scope"), "{ochami_err}");
462  }
463
464  #[test]
465  fn server_configuration_roundtrip_toml_minimal() {
466    let mut sites = HashMap::new();
467    sites.insert("alps".to_string(), make_minimal_site());
468    let cfg = ServerConfiguration {
469      log: "info".to_string(),
470      server: ServerSettings {
471        listen_address: Some("0.0.0.0".to_string()),
472        port: Some(8443),
473        cert: Some("/etc/manta/tls/server.crt".to_string()),
474        key: Some("/etc/manta/tls/server.key".to_string()),
475        console_inactivity_timeout_secs: 1800,
476        request_timeout_secs: 300,
477        shutdown_grace_period_secs: 30,
478        migrate_backup_root: None,
479        allow_http: false,
480      },
481      sites,
482      auditor: None,
483    };
484    let toml_str = toml::to_string(&cfg).unwrap();
485    let parsed: ServerConfiguration = toml::from_str(&toml_str).unwrap();
486    assert_eq!(parsed.server.port, Some(8443));
487    assert_eq!(parsed.server.listen_address.as_deref(), Some("0.0.0.0"));
488    assert_eq!(parsed.server.console_inactivity_timeout_secs, 1800);
489    assert_eq!(parsed.server.request_timeout_secs, 300);
490    assert_eq!(
491      parsed.server.cert.as_deref(),
492      Some("/etc/manta/tls/server.crt")
493    );
494  }
495
496  /// Default port helper: 8443 when TLS is configured, 8080
497  /// otherwise. Used by `manta-server::main` when no `port` is set
498  /// in config or on the CLI.
499  #[test]
500  fn server_settings_default_port_depends_on_tls() {
501    assert_eq!(ServerSettings::default_port(true), 8443);
502    assert_eq!(ServerSettings::default_port(false), 8080);
503  }
504
505  /// power_timeout_secs is gone — confirm the surrounding
506  /// timeout-related fields still default correctly when the only
507  /// remaining knob is absent.
508  #[test]
509  fn server_settings_request_timeout_secs_defaults_to_600() {
510    let toml_str = r#"
511      listen_address = "0.0.0.0"
512      port = 8443
513      console_inactivity_timeout_secs = 1800
514    "#;
515    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
516    assert_eq!(parsed.request_timeout_secs, 600);
517  }
518
519  /// `[server]` block with neither `listen_address` nor `port`
520  /// supplied — both fields deserialise as `None`, leaving the
521  /// effective values to be filled in at startup time. Confirms the
522  /// schema-level back-compat for the new defaults.
523  #[test]
524  fn server_settings_listen_address_and_port_default_to_none() {
525    let toml_str = r#"
526      console_inactivity_timeout_secs = 1800
527    "#;
528    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
529    assert!(parsed.listen_address.is_none());
530    assert!(parsed.port.is_none());
531  }
532
533  /// Existing server.toml files that pre-date the request_timeout
534  /// field must keep working — the field falls back to its default.
535  #[test]
536  fn server_settings_request_timeout_field_defaults_when_omitted() {
537    let toml_str = r#"
538      listen_address = "0.0.0.0"
539      port = 8443
540      console_inactivity_timeout_secs = 1800
541    "#;
542    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
543    assert_eq!(parsed.request_timeout_secs, 600);
544  }
545
546  #[test]
547  fn server_configuration_deserialize_missing_server_section_fails() {
548    let bad_toml = r#"
549      log = "info"
550      [sites]
551    "#;
552    let result = toml::from_str::<ServerConfiguration>(bad_toml);
553    assert!(result.is_err());
554  }
555
556  #[test]
557  fn server_settings_optional_tls_paths() {
558    // TLS cert/key are optional in the schema — flags can supply them
559    // at runtime when the config omits them.
560    let toml_str = r#"
561      listen_address = "0.0.0.0"
562      port = 8443
563      console_inactivity_timeout_secs = 1800
564    "#;
565    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
566    assert!(parsed.cert.is_none());
567    assert!(parsed.key.is_none());
568  }
569}