Adds a per-firmware default-login editor so the operator can set the discovery credentials each firmware is probed with, rather than a single global pair. - credentials.rs: a per-firmware store (firmware-credentials.txt, 0600, one "name<TAB>user<TAB>pass" line per firmware) keyed by the asic-rs firmware registry's Display name -- the same key the factory uses for with_firmware_discovery_auth. A firmware_default_creds() table seeds the editor with each firmware's shipped default (mirrors the asic-rs backends' default_auth constants; asic-rs does not expose them at the entry level). - configured_factory() precedence is now: a per-firmware override wins; else the single global scan credential (unchanged back-compat) applies to every backend; else the backend's own default_auth. Nothing saved -> plain MinerFactory::new(). - UI: the "Set scan credentials..." dialog gains a "Per-firmware defaults..." button opening an editor that lists every firmware in the compiled-in registry (read at runtime, not hard-coded) with editable user/pass fields prefilled from the saved override or the shipped default. Save persists only rows that differ from the shipped default (so defaults evolve with asic-rs and the file stays minimal); Reset to defaults clears all overrides. Verified under Xvfb: the editor lists all 16 registry firmwares with correct default logins (AntMiner root/root, WhatsMiner admin/admin, VNish blank/admin, UMC OS blank/letmein, ...). Round-trip/permissions/precedence covered by a unit test (folded into the existing HOME-scoped credentials test to avoid a parallel HOME race); self-test still passes. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
292 lines
12 KiB
Rust
292 lines
12 KiB
Rust
//! 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::collections::HashMap;
|
|
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";
|
|
/// Per-firmware default logins the operator can override (round 12 #13). One
|
|
/// `firmware-name<TAB>user<TAB>pass` line per firmware, 0600 like the others.
|
|
/// Keyed by the firmware registry's Display name (see `firmware_default_creds`).
|
|
pub const FIRMWARE_CREDENTIALS_FILE: &str = "firmware-credentials.txt";
|
|
/// SSH login for the control board (used by the PIC probe; distinct from the
|
|
/// web/API scan credentials above -- miners' SSH root login is usually not the
|
|
/// same account as the web digest-auth login).
|
|
pub const SSH_CREDENTIALS_FILE: &str = "ssh-credentials.txt";
|
|
|
|
/// Load a saved username/password pair from `file`, if present.
|
|
fn load_creds_file(file: &str) -> Option<(String, String)> {
|
|
let s = std::fs::read_to_string(config_path(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 a username/password pair to `file`, restricting it to owner read/write
|
|
/// (credentials are plaintext on disk, so the mode matters).
|
|
fn save_creds_file(file: &str, user: &str, pass: &str) -> std::io::Result<()> {
|
|
let p = config_path(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(())
|
|
}
|
|
|
|
fn clear_creds_file(file: &str) -> std::io::Result<()> {
|
|
match std::fs::remove_file(config_path(file)) {
|
|
Ok(()) => Ok(()),
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
|
Err(e) => Err(e),
|
|
}
|
|
}
|
|
|
|
/// Load the saved miner web/API username/password, if any were saved.
|
|
pub fn load_credentials() -> Option<(String, String)> {
|
|
load_creds_file(CREDENTIALS_FILE)
|
|
}
|
|
|
|
/// Save the miner web/API username/password (0600).
|
|
pub fn save_credentials(user: &str, pass: &str) -> std::io::Result<()> {
|
|
save_creds_file(CREDENTIALS_FILE, user, pass)
|
|
}
|
|
|
|
/// Load the saved SSH username/password for the PIC probe, if any.
|
|
pub fn load_ssh_credentials() -> Option<(String, String)> {
|
|
load_creds_file(SSH_CREDENTIALS_FILE)
|
|
}
|
|
|
|
/// Save the SSH username/password for the PIC probe (0600).
|
|
pub fn save_ssh_credentials(user: &str, pass: &str) -> std::io::Result<()> {
|
|
save_creds_file(SSH_CREDENTIALS_FILE, user, pass)
|
|
}
|
|
|
|
/// Remove the saved web/API credentials, if any. Not an error if none were saved.
|
|
pub fn clear_credentials() -> std::io::Result<()> {
|
|
match clear_creds_file(CREDENTIALS_FILE) {
|
|
Ok(()) => Ok(()),
|
|
Err(e) => Err(e),
|
|
}
|
|
}
|
|
|
|
/// The stock/default login each firmware ships with, keyed by the firmware
|
|
/// registry's Display name (round 12 #13). These seed the per-firmware editor and
|
|
/// let it tell an override from an unchanged default; they mirror the
|
|
/// `default_auth()` constants in the vendored asic-rs backends (a single
|
|
/// best-guess per registry entry, since a stock entry can span several backend
|
|
/// versions). asic-rs does not expose these at the entry level, so they are
|
|
/// duplicated here; a firmware absent from this table defaults to blank.
|
|
pub fn firmware_default_creds() -> &'static [(&'static str, &'static str, &'static str)] {
|
|
&[
|
|
("AntMiner Stock", "root", "root"),
|
|
("WhatsMiner Stock", "admin", "admin"),
|
|
("Braiins", "root", "root"),
|
|
("VNish", "", "admin"),
|
|
("LuxOS", "root", "root"),
|
|
("UMC OS", "", "letmein"),
|
|
("Marathon", "root", "root"),
|
|
("VolcMiner Stock", "root", "ltc@dog"),
|
|
("Elphapex Stock", "root", "root"),
|
|
("FutureBit Stock", "futurebit", "futurebit123"),
|
|
("SealMiner Stock", "seal", "seal"),
|
|
("Auradine Stock", "admin", "admin"),
|
|
("AvalonMiner Stock", "", ""),
|
|
("Nerdaxe Stock", "", ""),
|
|
("Proto Stock", "", ""),
|
|
("Bitaxe Stock", "", ""),
|
|
]
|
|
}
|
|
|
|
/// The shipped default login for a firmware, or `("","")` if unknown.
|
|
pub fn firmware_default_for(name: &str) -> (String, String) {
|
|
firmware_default_creds()
|
|
.iter()
|
|
.find(|(n, _, _)| *n == name)
|
|
.map(|(_, u, p)| (u.to_string(), p.to_string()))
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
/// Load the operator's per-firmware credential overrides, keyed by firmware
|
|
/// Display name. Malformed lines are skipped.
|
|
pub fn load_firmware_credentials() -> HashMap<String, (String, String)> {
|
|
let mut map = HashMap::new();
|
|
let Ok(s) = std::fs::read_to_string(config_path(FIRMWARE_CREDENTIALS_FILE)) else {
|
|
return map;
|
|
};
|
|
for line in s.lines() {
|
|
let mut parts = line.splitn(3, '\t');
|
|
let (Some(name), user) = (parts.next(), parts.next()) else {
|
|
continue;
|
|
};
|
|
if name.is_empty() {
|
|
continue;
|
|
}
|
|
let user = user.unwrap_or("").to_string();
|
|
let pass = parts.next().unwrap_or("").to_string();
|
|
map.insert(name.to_string(), (user, pass));
|
|
}
|
|
map
|
|
}
|
|
|
|
/// Save the per-firmware credential overrides (0600), sorted by name for a
|
|
/// stable file. An empty map clears the file.
|
|
pub fn save_firmware_credentials(map: &HashMap<String, (String, String)>) -> std::io::Result<()> {
|
|
if map.is_empty() {
|
|
return clear_firmware_credentials();
|
|
}
|
|
let p = config_path(FIRMWARE_CREDENTIALS_FILE);
|
|
if let Some(dir) = p.parent() {
|
|
std::fs::create_dir_all(dir)?;
|
|
}
|
|
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))?;
|
|
let mut names: Vec<&String> = map.keys().collect();
|
|
names.sort();
|
|
for name in names {
|
|
let (user, pass) = &map[name];
|
|
f.write_all(format!("{name}\t{user}\t{pass}\n").as_bytes())?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Remove the per-firmware overrides file, if any. Not an error if none exists.
|
|
pub fn clear_firmware_credentials() -> std::io::Result<()> {
|
|
clear_creds_file(FIRMWARE_CREDENTIALS_FILE)
|
|
}
|
|
|
|
/// Build a `MinerFactory` with saved credentials applied as discovery auth.
|
|
/// Precedence per firmware backend: a per-firmware override (round 12 #13) wins;
|
|
/// otherwise the single global scan credential (if set) applies to every backend;
|
|
/// otherwise the backend falls back to its own default auth. With nothing saved
|
|
/// this is plain `MinerFactory::new()`.
|
|
pub fn configured_factory() -> MinerFactory {
|
|
let mut factory = MinerFactory::new();
|
|
let global = load_credentials();
|
|
let per_fw = load_firmware_credentials();
|
|
if global.is_none() && per_fw.is_empty() {
|
|
return factory;
|
|
}
|
|
for fw in asic_rs::factory::default_firmware_registry() {
|
|
let cred = per_fw
|
|
.get(&fw.to_string())
|
|
.cloned()
|
|
.or_else(|| global.clone());
|
|
if let Some((user, pass)) = cred {
|
|
factory = factory.with_firmware_discovery_auth(fw.as_ref(), MinerAuth::new(user, pass));
|
|
}
|
|
}
|
|
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
|
|
|
|
// Per-firmware overrides (round 12 #13). Kept in this same test because
|
|
// HOME is process-global: a second #[test] mutating it would race under
|
|
// cargo's default parallel runner.
|
|
assert!(load_firmware_credentials().is_empty(), "no file -> empty map");
|
|
let mut fw = HashMap::new();
|
|
fw.insert("WhatsMiner Stock".to_string(), ("super".to_string(), "sup3r".to_string()));
|
|
fw.insert("VNish".to_string(), ("".to_string(), "hunter2".to_string()));
|
|
save_firmware_credentials(&fw).unwrap();
|
|
// 0600, and it round-trips (an empty username survives the tab format).
|
|
let fwpath = config_path(FIRMWARE_CREDENTIALS_FILE);
|
|
assert_eq!(
|
|
std::fs::metadata(&fwpath).unwrap().permissions().mode() & 0o777,
|
|
0o600,
|
|
"per-firmware creds file must be 0600"
|
|
);
|
|
let back = load_firmware_credentials();
|
|
assert_eq!(back.get("WhatsMiner Stock"), Some(&("super".into(), "sup3r".into())));
|
|
assert_eq!(back.get("VNish"), Some(&("".into(), "hunter2".into())));
|
|
assert_eq!(back.len(), 2);
|
|
// Shipped-default lookup: known firmware resolves, unknown blanks.
|
|
assert_eq!(firmware_default_for("AntMiner Stock"), ("root".into(), "root".into()));
|
|
assert_eq!(firmware_default_for("nonexistent"), (String::new(), String::new()));
|
|
// Overrides + no global still builds a factory.
|
|
let _ = configured_factory();
|
|
// Saving an empty map clears the file (no stale overrides linger).
|
|
save_firmware_credentials(&HashMap::new()).unwrap();
|
|
assert!(load_firmware_credentials().is_empty(), "empty save -> cleared");
|
|
clear_firmware_credentials().unwrap(); // idempotent
|
|
|
|
match prev {
|
|
Some(v) => std::env::set_var("HOME", v),
|
|
None => std::env::remove_var("HOME"),
|
|
}
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
}
|