Skip to main content

icinga2_api/config/
instance_file.rs

1//! Icinga instance config files, one TOML file per Icinga master
2//!
3//! A directory of these files can be shared by several tools that talk to the
4//! same Icinga masters. The file stem is the instance name. A file looks like
5//! this:
6//!
7//! ```toml
8//! url = "https://icinga.example.com:5665"
9//! ca_certificate = "/path/to/ca.pem"
10//! web_base_url = "https://icinga.example.com/monitoring/"
11//! username = "api-user"
12//! password_command = ["pass", "show", "icinga/api-user"]
13//! password_command_env = { PASSWORD_STORE_DIR = "/path/to/store" }
14//! ```
15//!
16//! Instead of `password_command` a literal `password` can be used, and
17//! instead of `username` and a password a TLS client certificate can be used
18//! with `client_certificate` and `client_key` (PEM files), e.g. the
19//! certificate of an Icinga agent for an `ApiUser` with a `client_cn`.
20
21use std::{
22    collections::BTreeMap,
23    path::{Path, PathBuf},
24};
25
26use serde::Deserialize;
27
28use crate::config::Icinga2Auth;
29
30/// errors when loading instance config files or resolving their auth
31#[derive(Debug, thiserror::Error)]
32pub enum Icinga2InstanceFileError {
33    /// could not read the instance config directory
34    #[error("could not read instance config directory: {0}")]
35    ReadDir(std::io::Error),
36    /// could not read an instance config file
37    #[error("could not read instance config file: {0}")]
38    ReadFile(std::io::Error),
39    /// could not parse an instance config file
40    #[error("could not parse instance config file {path}: {source}")]
41    Parse {
42        /// the file that could not be parsed
43        path: PathBuf,
44        /// the parse error
45        source: toml::de::Error,
46    },
47    /// the password command is empty
48    #[error("password_command is empty")]
49    PasswordCommandEmpty,
50    /// the password command could not be started
51    #[error("could not run password command `{command}`: {source}")]
52    PasswordCommandExec {
53        /// the command line
54        command: String,
55        /// the error starting it
56        source: std::io::Error,
57    },
58    /// the password command failed
59    #[error("password command `{command}` failed with exit code {exit_code:?}")]
60    PasswordCommandFailed {
61        /// the command line
62        command: String,
63        /// its exit code, `None` if it was killed by a signal
64        exit_code: Option<i32>,
65    },
66    /// the password command did not finish in time
67    #[error("password command `{command}` timed out after {timeout:?}")]
68    PasswordCommandTimeout {
69        /// the command line
70        command: String,
71        /// the timeout that expired
72        timeout: std::time::Duration,
73    },
74    /// the password command output was not UTF-8
75    #[error("password command `{command}` printed invalid UTF-8: {source}")]
76    PasswordCommandOutput {
77        /// the command line
78        command: String,
79        /// the decoding error
80        source: std::string::FromUtf8Error,
81    },
82    /// the password command printed nothing
83    #[error("password command `{command}` printed no password")]
84    PasswordCommandNoPassword {
85        /// the command line
86        command: String,
87    },
88    /// could not read the client certificate or key
89    #[error("could not read client certificate or key: {0}")]
90    ReadClientCertificate(std::io::Error),
91    /// could not build the client
92    #[error(transparent)]
93    Client(#[from] crate::error::Error),
94}
95
96/// how an instance config file authenticates
97#[derive(Clone)]
98pub enum Icinga2InstanceFileAuth {
99    /// basic auth with a literal password from the file
100    Password {
101        /// the name of the `ApiUser`
102        username: String,
103        /// the password
104        password: String,
105    },
106    /// basic auth with a password printed by a command
107    PasswordCommand {
108        /// the name of the `ApiUser`
109        username: String,
110        /// program and arguments, the first line of its output is the password
111        password_command: Vec<String>,
112        /// extra environment variables for the command, e.g. `PASSWORD_STORE_DIR`
113        password_command_env: BTreeMap<String, String>,
114    },
115    /// TLS client certificate auth
116    ClientCertificate {
117        /// the PEM certificate file
118        certificate: PathBuf,
119        /// the PEM private key file
120        key: PathBuf,
121    },
122}
123
124impl std::fmt::Debug for Icinga2InstanceFileAuth {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        match self {
127            Self::Password { username, .. } => f
128                .debug_struct("Password")
129                .field("username", username)
130                .field("password", &"<redacted>")
131                .finish(),
132            Self::PasswordCommand {
133                username,
134                password_command,
135                password_command_env,
136            } => f
137                .debug_struct("PasswordCommand")
138                .field("username", username)
139                .field("password_command", password_command)
140                .field("password_command_env", password_command_env)
141                .finish(),
142            Self::ClientCertificate { certificate, key } => f
143                .debug_struct("ClientCertificate")
144                .field("certificate", certificate)
145                .field("key", key)
146                .finish(),
147        }
148    }
149}
150
151/// one Icinga instance config file
152#[derive(Debug, Clone, Deserialize)]
153#[serde(try_from = "RawInstanceFile")]
154pub struct Icinga2InstanceFile {
155    /// the API URL, without the v1 component, e.g. `https://icinga.example.com:5665`
156    pub url: String,
157    /// the CA certificate to validate the server certificate with
158    pub ca_certificate: Option<PathBuf>,
159    /// the Icinga Web base URL, e.g. `https://icinga.example.com/monitoring/`,
160    /// not used by this crate, for tools that link to the web interface
161    pub web_base_url: Option<String>,
162    /// how to authenticate
163    pub auth: Icinga2InstanceFileAuth,
164}
165
166/// the instance config file as written, before checking which auth it uses
167#[derive(Deserialize)]
168#[serde(deny_unknown_fields)]
169struct RawInstanceFile {
170    /// see [`Icinga2InstanceFile::url`]
171    url: String,
172    /// see [`Icinga2InstanceFile::ca_certificate`]
173    ca_certificate: Option<PathBuf>,
174    /// see [`Icinga2InstanceFile::web_base_url`]
175    web_base_url: Option<String>,
176    /// basic auth username
177    username: Option<String>,
178    /// literal basic auth password
179    password: Option<String>,
180    /// command printing the basic auth password
181    password_command: Option<Vec<String>>,
182    /// environment for the password command
183    password_command_env: Option<BTreeMap<String, String>>,
184    /// client certificate file
185    client_certificate: Option<PathBuf>,
186    /// client key file
187    client_key: Option<PathBuf>,
188}
189
190impl TryFrom<RawInstanceFile> for Icinga2InstanceFile {
191    type Error = String;
192
193    fn try_from(raw: RawInstanceFile) -> Result<Self, Self::Error> {
194        let auth = match (
195            raw.username,
196            raw.password,
197            raw.password_command,
198            raw.client_certificate,
199            raw.client_key,
200        ) {
201            (Some(username), Some(password), None, None, None) => {
202                if raw.password_command_env.is_some() {
203                    return Err("password_command_env requires password_command".to_owned());
204                }
205                Icinga2InstanceFileAuth::Password { username, password }
206            }
207            (Some(username), None, Some(password_command), None, None) => {
208                Icinga2InstanceFileAuth::PasswordCommand {
209                    username,
210                    password_command,
211                    password_command_env: raw.password_command_env.unwrap_or_default(),
212                }
213            }
214            (None, None, None, Some(certificate), Some(key)) => {
215                if raw.password_command_env.is_some() {
216                    return Err("password_command_env requires password_command".to_owned());
217                }
218                Icinga2InstanceFileAuth::ClientCertificate { certificate, key }
219            }
220            _ => {
221                return Err("expected exactly one of: username with password, \
222                     username with password_command, \
223                     or client_certificate with client_key"
224                    .to_owned());
225            }
226        };
227        Ok(Self {
228            url: raw.url,
229            ca_certificate: raw.ca_certificate,
230            web_base_url: raw.web_base_url,
231            auth,
232        })
233    }
234}
235
236/// the first line of the password command output, trimmed
237///
238/// # Errors
239///
240/// fails if the command failed, its output is not UTF-8 or it is empty
241fn password_from_output(
242    command: &str,
243    output: std::process::Output,
244) -> Result<String, Icinga2InstanceFileError> {
245    if !output.status.success() {
246        return Err(Icinga2InstanceFileError::PasswordCommandFailed {
247            command: command.to_owned(),
248            exit_code: output.status.code(),
249        });
250    }
251    let stdout = String::from_utf8(output.stdout).map_err(|source| {
252        Icinga2InstanceFileError::PasswordCommandOutput {
253            command: command.to_owned(),
254            source,
255        }
256    })?;
257    let password = stdout.lines().next().unwrap_or_default().trim();
258    if password.is_empty() {
259        return Err(Icinga2InstanceFileError::PasswordCommandNoPassword {
260            command: command.to_owned(),
261        });
262    }
263    Ok(password.to_owned())
264}
265
266impl Icinga2InstanceFile {
267    /// read one instance config file
268    ///
269    /// # Errors
270    ///
271    /// fails if the file can not be read or parsed
272    pub fn from_file(path: &Path) -> Result<Self, Icinga2InstanceFileError> {
273        let content = fs_err::read_to_string(path).map_err(Icinga2InstanceFileError::ReadFile)?;
274        toml::from_str(&content).map_err(|source| Icinga2InstanceFileError::Parse {
275            path: path.to_path_buf(),
276            source,
277        })
278    }
279
280    /// read all `*.toml` files in a directory, sorted by name
281    ///
282    /// the name of each instance is its file stem
283    ///
284    /// # Errors
285    ///
286    /// fails if the directory or any of the files can not be read or parsed
287    pub fn load_dir(dir: &Path) -> Result<Vec<(String, Self)>, Icinga2InstanceFileError> {
288        let mut result = Vec::new();
289        for entry in fs_err::read_dir(dir).map_err(Icinga2InstanceFileError::ReadDir)? {
290            let path = entry.map_err(Icinga2InstanceFileError::ReadDir)?.path();
291            if path.extension().and_then(|s| s.to_str()) != Some("toml") {
292                continue;
293            }
294            let Some(name) = path.file_stem().map(|s| s.to_string_lossy().into_owned()) else {
295                continue;
296            };
297            result.push((name, Self::from_file(&path)?));
298        }
299        result.sort_by(|(a, _), (b, _)| a.cmp(b));
300        Ok(result)
301    }
302
303    /// the basic auth username, `None` for client certificate auth
304    #[must_use]
305    pub fn username(&self) -> Option<&str> {
306        match &self.auth {
307            Icinga2InstanceFileAuth::Password { username, .. }
308            | Icinga2InstanceFileAuth::PasswordCommand { username, .. } => Some(username),
309            Icinga2InstanceFileAuth::ClientCertificate { .. } => None,
310        }
311    }
312
313    /// resolve the auth, running the password command or reading the client
314    /// certificate if necessary
315    ///
316    /// the password command gets no stdin and inherits stderr
317    ///
318    /// # Errors
319    ///
320    /// fails if the password command fails or prints no password, or if the
321    /// client certificate or key can not be read
322    pub fn resolve_auth(&self) -> Result<Icinga2Auth, Icinga2InstanceFileError> {
323        match &self.auth {
324            Icinga2InstanceFileAuth::Password { username, password } => Ok(Icinga2Auth::Basic {
325                username: username.to_owned(),
326                password: password.to_owned(),
327            }),
328            Icinga2InstanceFileAuth::PasswordCommand {
329                username,
330                password_command,
331                password_command_env,
332            } => {
333                let (program, args) = password_command
334                    .split_first()
335                    .ok_or(Icinga2InstanceFileError::PasswordCommandEmpty)?;
336                let command = password_command.join(" ");
337                let output = std::process::Command::new(program)
338                    .args(args)
339                    .envs(password_command_env)
340                    .stdin(std::process::Stdio::null())
341                    .stderr(std::process::Stdio::inherit())
342                    .output()
343                    .map_err(|source| Icinga2InstanceFileError::PasswordCommandExec {
344                        command: command.clone(),
345                        source,
346                    })?;
347                Ok(Icinga2Auth::Basic {
348                    username: username.to_owned(),
349                    password: password_from_output(&command, output)?,
350                })
351            }
352            Icinga2InstanceFileAuth::ClientCertificate { certificate, key } => {
353                Icinga2Auth::client_certificate_from_files(certificate, key)
354                    .map_err(Icinga2InstanceFileError::ReadClientCertificate)
355            }
356        }
357    }
358
359    /// like [`Self::resolve_auth`] but runs the password command
360    /// asynchronously, killing it if it does not finish within `timeout`
361    /// (e.g. while a password store waits for a locked key)
362    ///
363    /// # Errors
364    ///
365    /// fails like [`Self::resolve_auth`] or if the timeout expires
366    #[cfg(feature = "async")]
367    pub async fn resolve_auth_async(
368        &self,
369        timeout: Option<std::time::Duration>,
370    ) -> Result<Icinga2Auth, Icinga2InstanceFileError> {
371        let Icinga2InstanceFileAuth::PasswordCommand {
372            username,
373            password_command,
374            password_command_env,
375        } = &self.auth
376        else {
377            return self.resolve_auth();
378        };
379        let (program, args) = password_command
380            .split_first()
381            .ok_or(Icinga2InstanceFileError::PasswordCommandEmpty)?;
382        let command = password_command.join(" ");
383        let output_future = tokio::process::Command::new(program)
384            .args(args)
385            .envs(password_command_env)
386            .stdin(std::process::Stdio::null())
387            .stderr(std::process::Stdio::inherit())
388            .kill_on_drop(true)
389            .output();
390        let output = if let Some(timeout) = timeout {
391            tokio::time::timeout(timeout, output_future)
392                .await
393                .map_err(
394                    |_elapsed| Icinga2InstanceFileError::PasswordCommandTimeout {
395                        command: command.clone(),
396                        timeout,
397                    },
398                )?
399        } else {
400            output_future.await
401        }
402        .map_err(|source| Icinga2InstanceFileError::PasswordCommandExec {
403            command: command.clone(),
404            source,
405        })?;
406        Ok(Icinga2Auth::Basic {
407            username: username.to_owned(),
408            password: password_from_output(&command, output)?,
409        })
410    }
411
412    /// resolve the auth and build a blocking client
413    ///
414    /// # Errors
415    ///
416    /// fails if the auth can not be resolved or the client can not be built
417    #[cfg(feature = "blocking")]
418    pub fn connect_blocking(
419        &self,
420    ) -> Result<crate::api::blocking::Icinga2, Icinga2InstanceFileError> {
421        Ok(crate::api::blocking::Icinga2::from_parts(
422            &self.url,
423            self.ca_certificate.as_deref(),
424            self.resolve_auth()?,
425        )?)
426    }
427
428    /// resolve the auth asynchronously (see [`Self::resolve_auth_async`]) and
429    /// build an async client
430    ///
431    /// # Errors
432    ///
433    /// fails if the auth can not be resolved or the client can not be built
434    #[cfg(feature = "async")]
435    pub async fn connect_async(
436        &self,
437        timeout: Option<std::time::Duration>,
438    ) -> Result<crate::api::async_client::Icinga2Async, Icinga2InstanceFileError> {
439        Ok(crate::api::async_client::Icinga2Async::from_parts(
440            &self.url,
441            self.ca_certificate.as_deref(),
442            self.resolve_auth_async(timeout).await?,
443        )?)
444    }
445}
446
447#[cfg(test)]
448mod test {
449    use super::*;
450    use pretty_assertions::assert_eq;
451
452    #[test]
453    fn test_parse_password_command() -> Result<(), Box<dyn std::error::Error>> {
454        let file: Icinga2InstanceFile = toml::from_str(
455            r#"
456url = "https://icinga.example.com:5665"
457ca_certificate = "/path/to/ca.pem"
458username = "api-user"
459password_command = [
460  "pass",
461  "show",
462  "icinga/api-user",
463]
464password_command_env = { PASSWORD_STORE_DIR = "/path/to/store" }
465"#,
466        )?;
467        assert_eq!(file.url, "https://icinga.example.com:5665");
468        assert_eq!(file.ca_certificate, Some(PathBuf::from("/path/to/ca.pem")));
469        assert_eq!(file.web_base_url, None);
470        assert_eq!(file.username(), Some("api-user"));
471        let Icinga2InstanceFileAuth::PasswordCommand {
472            password_command,
473            password_command_env,
474            ..
475        } = file.auth
476        else {
477            return Err("expected password command auth".into());
478        };
479        assert_eq!(password_command, vec!["pass", "show", "icinga/api-user"]);
480        assert_eq!(
481            password_command_env
482                .get("PASSWORD_STORE_DIR")
483                .map(String::as_str),
484            Some("/path/to/store")
485        );
486        Ok(())
487    }
488
489    #[test]
490    fn test_parse_password_and_web_base_url() -> Result<(), Box<dyn std::error::Error>> {
491        let file: Icinga2InstanceFile = toml::from_str(
492            r#"
493url = "https://icinga.example.com:5665"
494web_base_url = "https://icinga.example.com/monitoring/"
495username = "api-user"
496password = "secret"
497"#,
498        )?;
499        assert_eq!(
500            file.web_base_url.as_deref(),
501            Some("https://icinga.example.com/monitoring/")
502        );
503        let Icinga2Auth::Basic { username, password } = file.resolve_auth()? else {
504            return Err("expected basic auth".into());
505        };
506        assert_eq!(username, "api-user");
507        assert_eq!(password, "secret");
508        Ok(())
509    }
510
511    #[test]
512    fn test_parse_client_certificate() -> Result<(), Box<dyn std::error::Error>> {
513        let file: Icinga2InstanceFile = toml::from_str(
514            r#"
515url = "https://icinga.example.com:5665"
516ca_certificate = "/var/lib/icinga2/certs/ca.crt"
517client_certificate = "/var/lib/icinga2/certs/host.example.com.crt"
518client_key = "/var/lib/icinga2/certs/host.example.com.key"
519"#,
520        )?;
521        assert_eq!(file.username(), None);
522        assert!(
523            matches!(file.auth, Icinga2InstanceFileAuth::ClientCertificate { .. }),
524            "expected client certificate auth"
525        );
526        Ok(())
527    }
528
529    #[test]
530    fn test_reject_ambiguous_or_unknown() {
531        for content in [
532            // password and password command
533            "url = \"https://x:5665\"\nusername = \"u\"\npassword = \"p\"\npassword_command = [\"true\"]\n",
534            // no username
535            "url = \"https://x:5665\"\npassword = \"p\"\n",
536            // certificate without key
537            "url = \"https://x:5665\"\nclient_certificate = \"/c\"\n",
538            // unknown field
539            "url = \"https://x:5665\"\nusername = \"u\"\npassword = \"p\"\npasword_command = []\n",
540        ] {
541            assert!(
542                toml::from_str::<Icinga2InstanceFile>(content).is_err(),
543                "should be rejected: {content}"
544            );
545        }
546    }
547
548    #[test]
549    fn test_resolve_password_command() -> Result<(), Box<dyn std::error::Error>> {
550        let file: Icinga2InstanceFile = toml::from_str(
551            r#"
552url = "https://icinga.example.com:5665"
553username = "api-user"
554password_command = ["sh", "-c", "printf '%s\nsecond line\n' \"$SECRET\""]
555password_command_env = { SECRET = " from-env " }
556"#,
557        )?;
558        let Icinga2Auth::Basic { password, .. } = file.resolve_auth()? else {
559            return Err("expected basic auth".into());
560        };
561        assert_eq!(password, "from-env");
562        Ok(())
563    }
564
565    #[test]
566    fn test_resolve_failing_password_command() -> Result<(), Box<dyn std::error::Error>> {
567        let file: Icinga2InstanceFile = toml::from_str(
568            r#"
569url = "https://icinga.example.com:5665"
570username = "api-user"
571password_command = ["false"]
572"#,
573        )?;
574        assert!(
575            matches!(
576                file.resolve_auth(),
577                Err(Icinga2InstanceFileError::PasswordCommandFailed { .. })
578            ),
579            "expected a failed password command"
580        );
581        Ok(())
582    }
583
584    #[cfg(feature = "async")]
585    #[tokio::test]
586    async fn test_resolve_password_command_timeout() -> Result<(), Box<dyn std::error::Error>> {
587        let file: Icinga2InstanceFile = toml::from_str(
588            r#"
589url = "https://icinga.example.com:5665"
590username = "api-user"
591password_command = ["sleep", "10"]
592"#,
593        )?;
594        assert!(
595            matches!(
596                file.resolve_auth_async(Some(std::time::Duration::from_millis(100)))
597                    .await,
598                Err(Icinga2InstanceFileError::PasswordCommandTimeout { .. })
599            ),
600            "expected a timeout"
601        );
602        Ok(())
603    }
604
605    #[test]
606    fn test_debug_redacts_password() -> Result<(), Box<dyn std::error::Error>> {
607        let file: Icinga2InstanceFile =
608            toml::from_str("url = \"https://x:5665\"\nusername = \"u\"\npassword = \"hunter2\"\n")?;
609        assert!(
610            !format!("{file:?}").contains("hunter2"),
611            "password in debug output"
612        );
613        assert!(
614            !format!("{:?}", file.resolve_auth()?).contains("hunter2"),
615            "password in debug output"
616        );
617        Ok(())
618    }
619}