pub mod instance_file;
use std::path::{Path, PathBuf};
use serde::Deserialize;
#[derive(Debug, Clone, Deserialize)]
pub struct Icinga2Instance {
pub url: String,
pub ca_certificate: Option<PathBuf>,
pub username: String,
pub password: String,
}
impl Icinga2Instance {
pub fn from_config_file(path: &Path) -> Result<Self, crate::error::Error> {
let content =
fs_err::read_to_string(path).map_err(crate::error::Error::CouldNotReadConfigFile)?;
let config: Self =
toml::from_str(&content).map_err(crate::error::Error::CouldNotParseConfig)?;
Ok(config)
}
}
#[derive(Clone)]
pub enum Icinga2Auth {
Basic {
username: String,
password: String,
},
ClientCertificate {
identity_pem: Vec<u8>,
},
}
impl Icinga2Auth {
pub fn client_certificate_from_files(
certificate: &Path,
key: &Path,
) -> Result<Self, std::io::Error> {
let mut identity_pem = fs_err::read(certificate)?;
if !identity_pem.ends_with(b"\n") {
identity_pem.push(b'\n');
}
identity_pem.extend(fs_err::read(key)?);
Ok(Self::ClientCertificate { identity_pem })
}
#[must_use]
pub fn username(&self) -> &str {
match self {
Self::Basic { username, .. } => username,
Self::ClientCertificate { .. } => "",
}
}
}
impl std::fmt::Debug for Icinga2Auth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Basic { username, .. } => f
.debug_struct("Basic")
.field("username", username)
.field("password", &"<redacted>")
.finish(),
Self::ClientCertificate { .. } => f
.debug_struct("ClientCertificate")
.field("identity_pem", &"<redacted>")
.finish(),
}
}
}
#[cfg(any(feature = "async", feature = "blocking"))]
pub(crate) fn client_parts(
url: &str,
ca_certificate: Option<&Path>,
auth: &Icinga2Auth,
) -> Result<ClientParts, crate::error::Error> {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
"Content-Type",
reqwest::header::HeaderValue::from_static("application/json"),
);
headers.insert(
"Accept",
reqwest::header::HeaderValue::from_static("application/json"),
);
let ca_certificate = if let Some(ca_certificate) = ca_certificate {
let ca_cert_content =
fs_err::read(ca_certificate).map_err(crate::error::Error::CouldNotReadCACertFile)?;
Some(
reqwest::Certificate::from_pem(&ca_cert_content)
.map_err(crate::error::Error::CouldNotParsePEMCACertificate)?,
)
} else {
None
};
let identity = match auth {
Icinga2Auth::Basic { .. } => None,
Icinga2Auth::ClientCertificate { identity_pem } => Some(
reqwest::Identity::from_pem(identity_pem)
.map_err(crate::error::Error::CouldNotBuildReqwestClientFromSuppliedInformation)?,
),
};
Ok(ClientParts {
headers,
ca_certificate,
identity,
url: url::Url::parse(url).map_err(crate::error::Error::CouldNotParseUrlInConfig)?,
})
}
#[cfg(any(feature = "async", feature = "blocking"))]
pub(crate) struct ClientParts {
pub(crate) headers: reqwest::header::HeaderMap,
pub(crate) ca_certificate: Option<reqwest::Certificate>,
pub(crate) identity: Option<reqwest::Identity>,
pub(crate) url: url::Url,
}