1use std::{
22 collections::BTreeMap,
23 path::{Path, PathBuf},
24};
25
26use serde::Deserialize;
27
28use crate::config::Icinga2Auth;
29
30#[derive(Debug, thiserror::Error)]
32pub enum Icinga2InstanceFileError {
33 #[error("could not read instance config directory: {0}")]
35 ReadDir(std::io::Error),
36 #[error("could not read instance config file: {0}")]
38 ReadFile(std::io::Error),
39 #[error("could not parse instance config file {path}: {source}")]
41 Parse {
42 path: PathBuf,
44 source: toml::de::Error,
46 },
47 #[error("password_command is empty")]
49 PasswordCommandEmpty,
50 #[error("could not run password command `{command}`: {source}")]
52 PasswordCommandExec {
53 command: String,
55 source: std::io::Error,
57 },
58 #[error("password command `{command}` failed with exit code {exit_code:?}")]
60 PasswordCommandFailed {
61 command: String,
63 exit_code: Option<i32>,
65 },
66 #[error("password command `{command}` timed out after {timeout:?}")]
68 PasswordCommandTimeout {
69 command: String,
71 timeout: std::time::Duration,
73 },
74 #[error("password command `{command}` printed invalid UTF-8: {source}")]
76 PasswordCommandOutput {
77 command: String,
79 source: std::string::FromUtf8Error,
81 },
82 #[error("password command `{command}` printed no password")]
84 PasswordCommandNoPassword {
85 command: String,
87 },
88 #[error("could not read client certificate or key: {0}")]
90 ReadClientCertificate(std::io::Error),
91 #[error(transparent)]
93 Client(#[from] crate::error::Error),
94}
95
96#[derive(Clone)]
98pub enum Icinga2InstanceFileAuth {
99 Password {
101 username: String,
103 password: String,
105 },
106 PasswordCommand {
108 username: String,
110 password_command: Vec<String>,
112 password_command_env: BTreeMap<String, String>,
114 },
115 ClientCertificate {
117 certificate: PathBuf,
119 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#[derive(Debug, Clone, Deserialize)]
153#[serde(try_from = "RawInstanceFile")]
154pub struct Icinga2InstanceFile {
155 pub url: String,
157 pub ca_certificate: Option<PathBuf>,
159 pub web_base_url: Option<String>,
162 pub auth: Icinga2InstanceFileAuth,
164}
165
166#[derive(Deserialize)]
168#[serde(deny_unknown_fields)]
169struct RawInstanceFile {
170 url: String,
172 ca_certificate: Option<PathBuf>,
174 web_base_url: Option<String>,
176 username: Option<String>,
178 password: Option<String>,
180 password_command: Option<Vec<String>>,
182 password_command_env: Option<BTreeMap<String, String>>,
184 client_certificate: Option<PathBuf>,
186 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
236fn 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 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 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 #[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 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 #[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 #[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 #[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 "url = \"https://x:5665\"\nusername = \"u\"\npassword = \"p\"\npassword_command = [\"true\"]\n",
534 "url = \"https://x:5665\"\npassword = \"p\"\n",
536 "url = \"https://x:5665\"\nclient_certificate = \"/c\"\n",
538 "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}