//! Optional saved miner credentials, applied to every asic-rs discovery call. //! //! asic-rs has no single global credential field on `MinerFactory`: auth is set //! per firmware backend via `with_firmware_discovery_auth`. `configured_factory` //! is the one place that fans a saved username/password out across the whole //! firmware registry, so `scan`'s callers never have to think about it. use std::io::Write; use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; use asic_rs::MinerFactory; use asic_rs::core::traits::miner::MinerAuth; use crate::scan::config_path; pub const CREDENTIALS_FILE: &str = "scan-credentials.txt"; /// Load the saved miner username/password, if any were saved. pub fn load_credentials() -> Option<(String, String)> { let s = std::fs::read_to_string(config_path(CREDENTIALS_FILE)).ok()?; let mut lines = s.lines(); let user = lines.next()?.to_string(); let pass = lines.next().unwrap_or("").to_string(); Some((user, pass)) } /// Save the miner username/password, restricting the file to owner /// read/write (credentials are plaintext on disk, so the mode matters). pub fn save_credentials(user: &str, pass: &str) -> std::io::Result<()> { let p = config_path(CREDENTIALS_FILE); if let Some(dir) = p.parent() { std::fs::create_dir_all(dir)?; } // Open (and create) with mode 0600 up front so a freshly created file is // never world/group-readable, even for the instant before the write. For a // pre-existing file the create mode is ignored, so also tighten it to 0600 // while it is still empty (post-truncate, pre-write) -- the plaintext is // never on disk under a looser mode. let mut f = std::fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .mode(0o600) .open(&p)?; f.set_permissions(std::fs::Permissions::from_mode(0o600))?; f.write_all(format!("{user}\n{pass}\n").as_bytes())?; Ok(()) } /// Remove the saved credentials, if any. Not an error if none were saved. pub fn clear_credentials() -> std::io::Result<()> { match std::fs::remove_file(config_path(CREDENTIALS_FILE)) { Ok(()) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(e) => Err(e), } } /// Build a `MinerFactory` with the saved credentials (if any) applied as /// discovery auth for every firmware backend, so scans, refreshes, config /// actions, and firmware flashes all authenticate against a non-default /// login the same way. With no saved credentials this is plain `MinerFactory::new()` /// and every backend falls back to its own default auth. pub fn configured_factory() -> MinerFactory { let mut factory = MinerFactory::new(); if let Some((user, pass)) = load_credentials() { for fw in asic_rs::factory::default_firmware_registry() { factory = factory.with_firmware_discovery_auth(fw.as_ref(), MinerAuth::new(user.clone(), pass.clone())); } } factory } #[cfg(test)] mod tests { use super::*; #[test] fn credentials_round_trip_and_file_perms() { // config_path() reads $HOME; point it at a private temp dir. HOME is // process-global, so this stays one test and restores HOME afterward // (matching the pattern used by scan::tests::auto_secs_round_trip_and_defaults). let prev = std::env::var_os("HOME"); let dir = std::env::temp_dir().join(format!("alkane-cred-test-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); std::env::set_var("HOME", &dir); assert_eq!(load_credentials(), None, "no file -> None"); save_credentials("admin", "hunter2").unwrap(); assert_eq!(load_credentials(), Some(("admin".to_string(), "hunter2".to_string()))); let meta = std::fs::metadata(config_path(CREDENTIALS_FILE)).unwrap(); assert_eq!(meta.permissions().mode() & 0o777, 0o600, "credentials file must be 0600"); // configured_factory() must construct in both branches without panicking: // with saved credentials (fans auth across every firmware backend) ... let _ = configured_factory(); // A pre-existing, world-readable credentials file must be tightened to // 0600 by save_credentials (the create-mode is ignored for an existing // file, so the explicit set_permissions is what protects it). let path = config_path(CREDENTIALS_FILE); std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); save_credentials("admin2", "s3cr3t").unwrap(); let meta = std::fs::metadata(&path).unwrap(); assert_eq!( meta.permissions().mode() & 0o777, 0o600, "save over a pre-existing 0644 file must re-tighten to 0600" ); assert_eq!(load_credentials(), Some(("admin2".to_string(), "s3cr3t".to_string()))); clear_credentials().unwrap(); // ... and with no saved credentials (plain MinerFactory::new()). let _ = configured_factory(); assert_eq!(load_credentials(), None, "cleared -> None"); clear_credentials().unwrap(); // idempotent: clearing an already-clear store is not an error match prev { Some(v) => std::env::set_var("HOME", v), None => std::env::remove_var("HOME"), } let _ = std::fs::remove_dir_all(&dir); } }