Skip to main content

icinga2_api/
config.rs

1//! Configuration related code
2
3pub mod instance_file;
4
5use std::path::{Path, PathBuf};
6
7use serde::Deserialize;
8
9/// this represents the configuration for an Icinga instance we connect to
10#[derive(Debug, Clone, Deserialize)]
11pub struct Icinga2Instance {
12    /// the URL to connect to, without the v1 component or anything after that
13    pub url: String,
14    /// the CA certificate to use to validate the server certificate
15    pub ca_certificate: Option<PathBuf>,
16    /// username
17    pub username: String,
18    /// password
19    pub password: String,
20}
21
22impl Icinga2Instance {
23    /// create a new Icinga2 instance from a TOML config file
24    ///
25    /// # Errors
26    /// this fails if the configuration file can not be found or parsed
27    /// or the CA certificate file mentioned in the configuration file
28    /// can not be found or parsed
29    pub fn from_config_file(path: &Path) -> Result<Self, crate::error::Error> {
30        let content =
31            fs_err::read_to_string(path).map_err(crate::error::Error::CouldNotReadConfigFile)?;
32        let config: Self =
33            toml::from_str(&content).map_err(crate::error::Error::CouldNotParseConfig)?;
34        Ok(config)
35    }
36}
37
38/// how a client authenticates against the Icinga API
39///
40/// used with `from_parts` on the clients, the [`Debug`] implementation
41/// does not print the password or the private key
42#[derive(Clone)]
43pub enum Icinga2Auth {
44    /// HTTP basic auth as an Icinga `ApiUser` with a password
45    Basic {
46        /// the name of the `ApiUser`
47        username: String,
48        /// the password of the `ApiUser`
49        password: String,
50    },
51    /// TLS client certificate auth as an Icinga `ApiUser` with a `client_cn`,
52    /// e.g. with the certificate of an Icinga agent
53    ClientCertificate {
54        /// the PEM encoded certificate followed by the PEM encoded private key
55        identity_pem: Vec<u8>,
56    },
57}
58
59impl Icinga2Auth {
60    /// client certificate auth from a PEM certificate file and a PEM private
61    /// key file, e.g. `/var/lib/icinga2/certs/<fqdn>.crt` and `.key`
62    ///
63    /// # Errors
64    ///
65    /// this fails if either file can not be read
66    pub fn client_certificate_from_files(
67        certificate: &Path,
68        key: &Path,
69    ) -> Result<Self, std::io::Error> {
70        let mut identity_pem = fs_err::read(certificate)?;
71        if !identity_pem.ends_with(b"\n") {
72            identity_pem.push(b'\n');
73        }
74        identity_pem.extend(fs_err::read(key)?);
75        Ok(Self::ClientCertificate { identity_pem })
76    }
77
78    /// the username to report for this auth, empty for client certificates
79    #[must_use]
80    pub fn username(&self) -> &str {
81        match self {
82            Self::Basic { username, .. } => username,
83            Self::ClientCertificate { .. } => "",
84        }
85    }
86}
87
88impl std::fmt::Debug for Icinga2Auth {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        match self {
91            Self::Basic { username, .. } => f
92                .debug_struct("Basic")
93                .field("username", username)
94                .field("password", &"<redacted>")
95                .finish(),
96            Self::ClientCertificate { .. } => f
97                .debug_struct("ClientCertificate")
98                .field("identity_pem", &"<redacted>")
99                .finish(),
100        }
101    }
102}
103
104/// builds the settings shared by the async and blocking clients
105///
106/// # Errors
107///
108/// this fails if the CA certificate can not be read or parsed, the client
109/// identity can not be parsed or the URL can not be parsed
110#[cfg(any(feature = "async", feature = "blocking"))]
111pub(crate) fn client_parts(
112    url: &str,
113    ca_certificate: Option<&Path>,
114    auth: &Icinga2Auth,
115) -> Result<ClientParts, crate::error::Error> {
116    let mut headers = reqwest::header::HeaderMap::new();
117    headers.insert(
118        "Content-Type",
119        reqwest::header::HeaderValue::from_static("application/json"),
120    );
121    headers.insert(
122        "Accept",
123        reqwest::header::HeaderValue::from_static("application/json"),
124    );
125    let ca_certificate = if let Some(ca_certificate) = ca_certificate {
126        let ca_cert_content =
127            fs_err::read(ca_certificate).map_err(crate::error::Error::CouldNotReadCACertFile)?;
128        Some(
129            reqwest::Certificate::from_pem(&ca_cert_content)
130                .map_err(crate::error::Error::CouldNotParsePEMCACertificate)?,
131        )
132    } else {
133        None
134    };
135    let identity = match auth {
136        Icinga2Auth::Basic { .. } => None,
137        Icinga2Auth::ClientCertificate { identity_pem } => Some(
138            reqwest::Identity::from_pem(identity_pem)
139                .map_err(crate::error::Error::CouldNotBuildReqwestClientFromSuppliedInformation)?,
140        ),
141    };
142    Ok(ClientParts {
143        headers,
144        ca_certificate,
145        identity,
146        url: url::Url::parse(url).map_err(crate::error::Error::CouldNotParseUrlInConfig)?,
147    })
148}
149
150/// the settings shared by the async and blocking clients, see [`client_parts`]
151#[cfg(any(feature = "async", feature = "blocking"))]
152pub(crate) struct ClientParts {
153    /// the default headers for every request
154    pub(crate) headers: reqwest::header::HeaderMap,
155    /// the only CA certificate to trust, if one was configured
156    pub(crate) ca_certificate: Option<reqwest::Certificate>,
157    /// the TLS client identity for client certificate auth
158    pub(crate) identity: Option<reqwest::Identity>,
159    /// the base URL of the Icinga API
160    pub(crate) url: url::Url,
161}