Skip to main content

manta_shared/common/config/
types.rs

1//! Typed config-file schemas for `cli.toml` and `server.toml`.
2//!
3//! See [`CliConfiguration`] and [`ServerConfiguration`] for the
4//! top-level shapes. The loaders that materialise these from disk
5//! live in the parent module ([`super::get_cli_configuration`],
6//! [`super::get_server_configuration`]).
7
8use std::collections::HashMap;
9
10use crate::common::audit::Auditor;
11
12use manta_backend_dispatcher::types::K8sDetails;
13use serde::{Deserialize, Serialize};
14
15/// Which backend API this site speaks.
16#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
17#[serde(rename_all = "lowercase")]
18pub enum BackendTechnology {
19  /// HPE Cray System Management (CSM) backend.
20  Csm,
21  /// OpenCHAMI backend.
22  Ochami,
23}
24
25impl BackendTechnology {
26  /// Return the lowercase string expected by `StaticBackendDispatcher::new`.
27  pub fn as_str(&self) -> &'static str {
28    match self {
29      Self::Csm => "csm",
30      Self::Ochami => "ochami",
31    }
32  }
33}
34
35#[derive(Serialize, Deserialize, Debug)]
36/// Connection details for a single ALPS site (CSM or OCHAMI instance).
37///
38/// The Vault URL used by handlers requiring vault (sat-file, session,
39/// console, logs) is derived at startup from
40/// `[sites.X.k8s.authentication.vault] base_url`. The vault secret path
41/// is derived from a hard-coded prefix and the site name. Neither is
42/// configured here.
43pub struct Site {
44  /// Which backend implementation this site uses (`csm` or `ochami`).
45  pub backend: BackendTechnology,
46  /// Optional per-site SOCKS5 proxy URL used by every outbound HTTP
47  /// request to this site's backend. `None` means direct connection.
48  pub socks5_proxy: Option<String>,
49  /// Base URL of the backend API (e.g. `https://api.alps.cscs.ch`).
50  pub shasta_base_url: String,
51  /// Optional Kubernetes connection details, required by handlers
52  /// that stream CFS session logs or attach to consoles.
53  pub k8s: Option<K8sDetails>,
54  /// Path (absolute or relative to the config dir) of the backend's
55  /// root CA certificate, used to verify TLS to `shasta_base_url`.
56  pub root_ca_cert_file: String,
57}
58
59/// Top-level configuration for the `manta-cli` binary. Persisted as TOML
60/// under `~/.config/manta/cli.toml`. Carries only the fields the CLI uses
61/// — every backend connection detail (per-site URLs, TLS certs, vault,
62/// k8s, per-site SOCKS proxies) lives in `ServerConfiguration`. The CLI
63/// only knows about the *one* manta-server it talks to.
64#[derive(Serialize, Deserialize, Debug)]
65pub struct CliConfiguration {
66  /// `EnvFilter` directive string for the tracing subscriber
67  /// (e.g. `"info"`, `"manta=debug,hyper=warn"`).
68  pub log: String,
69  /// Path to the local file the CLI appends audit lines to.
70  pub audit_file: String,
71  /// Active site name, sent as the `X-Manta-Site` header on every
72  /// request to manta-server. Overridable per-invocation with `--site`.
73  /// The server validates that the name matches one of its configured
74  /// sites; the CLI does no local validation.
75  pub site: String,
76  /// Default HSM group threaded into commands that accept
77  /// `--hsm-group` when none is supplied on the command line.
78  pub parent_hsm_group: String,
79  /// URL of the manta HTTP server this CLI talks to. Required — the CLI
80  /// no longer calls CSM/OCHAMI backends directly; every operation
81  /// (including auth) is forwarded through `manta-server`.
82  pub manta_server_url: String,
83  /// Optional SOCKS5 proxy used to reach `manta_server_url`. Per-site
84  /// proxying for backend traffic is the server's concern.
85  pub socks5_proxy: Option<String>,
86  /// Optional per-request HTTP timeout, in seconds. When set, the
87  /// reqwest client used to reach `manta_server_url` is built with
88  /// `.timeout(Duration::from_secs(n))`; when `None` (the default),
89  /// reqwest applies no per-request timeout — long-running calls
90  /// (e.g. `POST /power`) hang until the server responds or the
91  /// underlying connection drops. Set this to match the server's
92  /// longest legitimate response time when running through a SOCKS5
93  /// tunnel or proxy that silently drops idle connections.
94  #[serde(default)]
95  pub request_timeout_secs: Option<u64>,
96}
97
98/// Server-only settings — TLS, listen address, console behaviour. Lives
99/// under `[server]` in `server.toml`.
100#[derive(Serialize, Deserialize, Debug)]
101pub struct ServerSettings {
102  /// TCP listen address (e.g. "0.0.0.0"). When omitted from config
103  /// **and** no `--listen-address` flag is supplied, the server falls
104  /// back to `"0.0.0.0"`.
105  #[serde(default)]
106  pub listen_address: Option<String>,
107  /// TCP port. When omitted from config **and** no `--port` flag is
108  /// supplied, the effective default depends on whether TLS is
109  /// configured: `8443` if both `cert` and `key` are present (HTTPS),
110  /// otherwise `8080` (plain HTTP). See
111  /// [`ServerSettings::default_port`].
112  #[serde(default)]
113  pub port: Option<u16>,
114  /// Path to the TLS certificate (PEM).
115  pub cert: Option<String>,
116  /// Path to the TLS private key (PEM).
117  pub key: Option<String>,
118  /// How long a node-console WebSocket stays open without activity
119  /// before the server tears it down.
120  pub console_inactivity_timeout_secs: u64,
121  /// Per-source-IP rate limit for the `/api/v1/auth/*` endpoints,
122  /// in requests per minute. `None` disables in-process rate limiting
123  /// (operators are then expected to enforce it at the reverse proxy).
124  pub auth_rate_limit_per_minute: Option<u32>,
125  /// Global request timeout applied to every HTTP route, in seconds.
126  /// When this elapses the server returns `408 REQUEST_TIMEOUT`. All
127  /// long-running work (e.g. power transitions) now runs CLI-side,
128  /// so no endpoint needs more than the default.
129  #[serde(default = "default_request_timeout_secs")]
130  pub request_timeout_secs: u64,
131}
132
133impl ServerSettings {
134  /// Effective default listen address when neither config nor CLI flag
135  /// supplies one: bind on all interfaces.
136  pub const DEFAULT_LISTEN_ADDRESS: &'static str = "0.0.0.0";
137
138  /// Effective default port when neither config nor CLI flag supplies
139  /// one. `8443` for the HTTPS path (cert + key both present), `8080`
140  /// for plain HTTP — the latter is the typical dev / sidecar setup
141  /// where TLS is terminated upstream.
142  pub fn default_port(has_tls: bool) -> u16 {
143    if has_tls { 8443 } else { 8080 }
144  }
145}
146
147/// Default global request timeout — 60s. Matches the historical
148/// hardcoded value.
149fn default_request_timeout_secs() -> u64 {
150  60
151}
152
153/// Top-level configuration for the `manta-server` binary. Persisted as
154/// TOML under `~/.config/manta/server.toml`. Has no notion of an "active"
155/// site — the server hosts every configured site simultaneously and
156/// clients select per-request via the `X-Manta-Site` header.
157#[derive(Serialize, Deserialize, Debug)]
158pub struct ServerConfiguration {
159  /// `EnvFilter` directive for the tracing subscriber.
160  pub log: String,
161  /// Path to the local file the server appends audit lines to.
162  pub audit_file: String,
163  /// Network / TLS / console / rate-limit knobs for the HTTPS server.
164  pub server: ServerSettings,
165  /// Per-site backend connection details, keyed by site name. The
166  /// `X-Manta-Site` header on each request picks which one to route to.
167  pub sites: HashMap<String, Site>,
168  /// Optional Kafka audit forwarder (typically used for `/auth/*`
169  /// attempts). When `None`, the server emits no audit messages.
170  pub auditor: Option<Auditor>,
171}
172
173#[cfg(test)]
174mod tests {
175  use super::*;
176
177  #[test]
178  fn site_deserialize_missing_backend_fails() {
179    let bad_toml = r#"
180      shasta_base_url = "https://api.example.com"
181      root_ca_cert_file = "cert.pem"
182      # missing backend
183    "#;
184    let result = toml::from_str::<Site>(bad_toml);
185    assert!(result.is_err());
186  }
187
188  #[test]
189  fn backend_technology_as_str() {
190    assert_eq!(BackendTechnology::Csm.as_str(), "csm");
191    assert_eq!(BackendTechnology::Ochami.as_str(), "ochami");
192  }
193
194  #[test]
195  fn backend_technology_roundtrip_toml() {
196    // Verify TOML serializes as lowercase "csm" / "ochami"
197    #[derive(Serialize, Deserialize)]
198    struct Wrapper {
199      backend: BackendTechnology,
200    }
201    let w = Wrapper {
202      backend: BackendTechnology::Csm,
203    };
204    let s = toml::to_string(&w).unwrap();
205    assert!(s.contains("\"csm\"") || s.contains("csm"));
206    let parsed: Wrapper = toml::from_str(&s).unwrap();
207    assert_eq!(parsed.backend, BackendTechnology::Csm);
208  }
209
210  fn make_minimal_site() -> Site {
211    Site {
212      backend: BackendTechnology::Csm,
213      socks5_proxy: None,
214      shasta_base_url: "https://api.example.com".to_string(),
215      k8s: None,
216      root_ca_cert_file: "cert.pem".to_string(),
217    }
218  }
219
220  #[test]
221  fn cli_configuration_roundtrip_toml_minimal() {
222    let cfg = CliConfiguration {
223      log: "info".to_string(),
224      audit_file: "/tmp/cli-audit.log".to_string(),
225      site: "alps".to_string(),
226      parent_hsm_group: "nodes_free".to_string(),
227      manta_server_url: "https://manta-server.cscs.ch:8443".to_string(),
228      socks5_proxy: Some("socks5h://127.0.0.1:1080".to_string()),
229      request_timeout_secs: None,
230    };
231    let toml_str = toml::to_string(&cfg).unwrap();
232    let parsed: CliConfiguration = toml::from_str(&toml_str).unwrap();
233    assert_eq!(parsed.site, "alps");
234    assert_eq!(parsed.parent_hsm_group, "nodes_free");
235    assert_eq!(parsed.manta_server_url, "https://manta-server.cscs.ch:8443");
236    assert_eq!(
237      parsed.socks5_proxy.as_deref(),
238      Some("socks5h://127.0.0.1:1080")
239    );
240  }
241
242  #[test]
243  fn cli_configuration_socks5_proxy_optional() {
244    let toml_str = r#"
245      log = "info"
246      audit_file = "/tmp/cli-audit.log"
247      site = "alps"
248      parent_hsm_group = ""
249      manta_server_url = "https://manta-server.cscs.ch:8443"
250    "#;
251    let parsed: CliConfiguration = toml::from_str(toml_str).unwrap();
252    assert!(parsed.socks5_proxy.is_none());
253  }
254
255  #[test]
256  fn cli_configuration_missing_manta_server_url_fails() {
257    let bad_toml = r#"
258      log = "info"
259      audit_file = "/tmp/cli-audit.log"
260      site = "alps"
261      parent_hsm_group = ""
262      # missing manta_server_url
263    "#;
264    let result = toml::from_str::<CliConfiguration>(bad_toml);
265    assert!(result.is_err());
266  }
267
268  #[test]
269  fn server_configuration_roundtrip_toml_minimal() {
270    let mut sites = HashMap::new();
271    sites.insert("alps".to_string(), make_minimal_site());
272    let cfg = ServerConfiguration {
273      log: "info".to_string(),
274      audit_file: "/var/log/manta/server-audit.log".to_string(),
275      server: ServerSettings {
276        listen_address: Some("0.0.0.0".to_string()),
277        port: Some(8443),
278        cert: Some("/etc/manta/tls/server.crt".to_string()),
279        key: Some("/etc/manta/tls/server.key".to_string()),
280        console_inactivity_timeout_secs: 1800,
281        auth_rate_limit_per_minute: Some(60),
282        request_timeout_secs: 60,
283      },
284      sites,
285      auditor: None,
286    };
287    let toml_str = toml::to_string(&cfg).unwrap();
288    let parsed: ServerConfiguration = toml::from_str(&toml_str).unwrap();
289    assert_eq!(parsed.server.port, Some(8443));
290    assert_eq!(parsed.server.listen_address.as_deref(), Some("0.0.0.0"));
291    assert_eq!(parsed.server.console_inactivity_timeout_secs, 1800);
292    assert_eq!(parsed.server.request_timeout_secs, 60);
293    assert_eq!(
294      parsed.server.cert.as_deref(),
295      Some("/etc/manta/tls/server.crt")
296    );
297  }
298
299  /// Default port helper: 8443 when TLS is configured, 8080
300  /// otherwise. Used by `manta-server::main` when no `port` is set
301  /// in config or on the CLI.
302  #[test]
303  fn server_settings_default_port_depends_on_tls() {
304    assert_eq!(ServerSettings::default_port(true), 8443);
305    assert_eq!(ServerSettings::default_port(false), 8080);
306  }
307
308  /// power_timeout_secs is gone — confirm the surrounding
309  /// timeout-related fields still default correctly when the only
310  /// remaining knob is absent.
311  #[test]
312  fn server_settings_request_timeout_secs_defaults_to_60() {
313    let toml_str = r#"
314      listen_address = "0.0.0.0"
315      port = 8443
316      console_inactivity_timeout_secs = 1800
317    "#;
318    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
319    assert_eq!(parsed.request_timeout_secs, 60);
320  }
321
322  /// `[server]` block with neither `listen_address` nor `port`
323  /// supplied — both fields deserialise as `None`, leaving the
324  /// effective values to be filled in at startup time. Confirms the
325  /// schema-level back-compat for the new defaults.
326  #[test]
327  fn server_settings_listen_address_and_port_default_to_none() {
328    let toml_str = r#"
329      console_inactivity_timeout_secs = 1800
330    "#;
331    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
332    assert!(parsed.listen_address.is_none());
333    assert!(parsed.port.is_none());
334  }
335
336  /// Existing server.toml files that pre-date the request_timeout
337  /// field must keep working — the field falls back to its default.
338  #[test]
339  fn server_settings_request_timeout_field_defaults_when_omitted() {
340    let toml_str = r#"
341      listen_address = "0.0.0.0"
342      port = 8443
343      console_inactivity_timeout_secs = 1800
344    "#;
345    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
346    assert_eq!(parsed.request_timeout_secs, 60);
347  }
348
349  #[test]
350  fn server_configuration_deserialize_missing_server_section_fails() {
351    let bad_toml = r#"
352      log = "info"
353      audit_file = "/tmp/server.log"
354      [sites]
355    "#;
356    let result = toml::from_str::<ServerConfiguration>(bad_toml);
357    assert!(result.is_err());
358  }
359
360  #[test]
361  fn server_settings_optional_tls_paths() {
362    // TLS cert/key are optional in the schema — flags can supply them
363    // at runtime when the config omits them.
364    let toml_str = r#"
365      listen_address = "0.0.0.0"
366      port = 8443
367      console_inactivity_timeout_secs = 1800
368    "#;
369    let parsed: ServerSettings = toml::from_str(toml_str).unwrap();
370    assert!(parsed.cert.is_none());
371    assert!(parsed.key.is_none());
372  }
373}