From 467042b83c2894dbea0530b383fa9ee63a69aa53 Mon Sep 17 00:00:00 2001 From: noah Date: Fri, 18 Sep 2026 10:32:44 -0600 Subject: [PATCH] GUI: real access/lock-state detection via credentialed digest probe asic-rs has no lock-state signal (a wrong-password miner just silently returns fewer fields, because the collector drops the 401). This builds the real check ON TOP of asic-rs: - access_probe.rs: a NON-mutating, digest-authenticated GET to a privileged endpoint (Antminer get_miner_conf.cgi, read-only). The HTTP status is decisive -- 200 = credentials authenticate (writable -> unlocked), 401/403 = rejected (view-only -> locked); anything else -> indeterminate. Pure classifier + unit tests; shells out to curl --digest (no HTTP crate) so the offline build is unaffected. - Right-click "Check access (auth)" on the selected miners runs start_access_probe on a background thread using the saved scan (web) credentials (default root/root), updating write_locked in the rows as results arrive. Fake-scan mode returns deterministic demo results. Guarded against a flash / concurrent probe. Replaces the previous capability-based inference for the miners the user explicitly checks. cargo check --release --tests clean. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh --- crates/alkane-gui/src/access_probe.rs | 115 ++++++++++++++++++++++++++ crates/alkane-gui/src/main.rs | 1 + crates/alkane-gui/src/scan.rs | 78 +++++++++++++++++ crates/alkane-gui/src/ui.rs | 89 +++++++++++++++++++- 4 files changed, 281 insertions(+), 2 deletions(-) create mode 100644 crates/alkane-gui/src/access_probe.rs diff --git a/crates/alkane-gui/src/access_probe.rs b/crates/alkane-gui/src/access_probe.rs new file mode 100644 index 00000000..9001069b --- /dev/null +++ b/crates/alkane-gui/src/access_probe.rs @@ -0,0 +1,115 @@ +//! Real access / lock-state detection: whether this miner accepts privileged +//! (credentialed) command writes, or is view-only. +//! +//! asic-rs has no lock-state signal (a wrong-password miner just silently +//! returns fewer fields, because the collector drops the 401). We build the real +//! check ON TOP of asic-rs: a NON-mutating, digest-authenticated GET to a +//! privileged endpoint. On Antminer every `/cgi-bin/*.cgi` requires digest auth, +//! so the HTTP status is decisive -- 200 means our credentials authenticate +//! (we can write -> unlocked), 401/403 means they are rejected (view-only -> +//! locked). We probe `get_miner_conf.cgi`, which is read-only (never the +//! mutating `set_miner_conf.cgi`). +//! +//! We shell out to `curl --digest` (already present, supports digest auth) +//! rather than add an HTTP+digest crate, so the offline/vendored build is +//! unaffected. `Some(true)` = locked, `Some(false)` = unlocked, `None` = +//! indeterminate (unreachable, or an endpoint/vendor this probe doesn't cover). + +use std::process::Command; +use std::time::Duration; + +/// Classify a miner's access state from an HTTP status code string (curl's +/// `%{http_code}` output). Conservative: anything other than a clear +/// authenticated/unauthorized answer is `None`. +pub fn classify_http_code(code: &str) -> Option { + match code.trim() { + "200" | "204" => Some(false), // authenticated -> unlocked/writable + "401" | "403" => Some(true), // rejected -> locked/view-only + _ => None, // 000 (no connect), 404, 5xx, ... -> unknown + } +} + +/// The privileged, read-only endpoint we probe per firmware family. Antminer +/// stock/aftermarket all gate `get_miner_conf.cgi` behind digest auth. +fn endpoint(_firmware: &str) -> &'static str { + "/cgi-bin/get_miner_conf.cgi" +} + +/// Probe one miner's access state over its web API with the given credentials. +/// Returns `Ok(Some(true/false))` on a decisive lock/unlock answer, `Ok(None)` +/// if reachable-but-indeterminate or a vendor this probe doesn't cover, or +/// `Err` only on a failure to run curl at all. +pub fn probe_access(ip: &str, firmware: &str, user: &str, pass: &str) -> Result, String> { + let url = format!("http://{ip}{}", endpoint(firmware)); + let userpass = format!("{user}:{pass}"); + let mut cmd = Command::new("curl"); + cmd.args([ + "-s", + "-o", + "/dev/null", + "-w", + "%{http_code}", + "--digest", + "-u", + &userpass, + "--connect-timeout", + "5", + "--max-time", + "9", + &url, + ]); + let out = wait_with_timeout(cmd, Duration::from_secs(12))?; + // curl prints the status code to stdout regardless of exit status (000 on a + // connection failure), so classify the code rather than the exit status. + let code = String::from_utf8_lossy(&out.stdout); + Ok(classify_http_code(&code)) +} + +/// Run a command with a wall-clock timeout (curl can hang past --max-time on a +/// black-holed host). +fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result { + use std::io::Read; + cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); + let mut child = cmd.spawn().map_err(|e| format!("spawn curl: {e}"))?; + let start = std::time::Instant::now(); + loop { + match child.try_wait().map_err(|e| e.to_string())? { + Some(status) => { + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + if let Some(mut o) = child.stdout.take() { + let _ = o.read_to_end(&mut stdout); + } + if let Some(mut e) = child.stderr.take() { + let _ = e.read_to_end(&mut stderr); + } + return Ok(std::process::Output { status, stdout, stderr }); + } + None => { + if start.elapsed() >= timeout { + let _ = child.kill(); + return Err("curl timed out".into()); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classify_codes() { + assert_eq!(classify_http_code("200"), Some(false), "authenticated -> unlocked"); + assert_eq!(classify_http_code("204"), Some(false)); + assert_eq!(classify_http_code("401"), Some(true), "unauthorized -> locked"); + assert_eq!(classify_http_code("403"), Some(true)); + assert_eq!(classify_http_code("000"), None, "no connection -> unknown"); + assert_eq!(classify_http_code("404"), None, "endpoint absent -> unknown"); + assert_eq!(classify_http_code("500"), None); + assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated"); + assert_eq!(classify_http_code(""), None); + } +} diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index bdc4402d..097d9cb4 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -1,6 +1,7 @@ //! alkane-toolkit — primary view (docs/UI-SPEC.md). //! Pure-Rust wxWidgets app on the vendored, patched wx-rs. +mod access_probe; mod credentials; mod fixtures; mod model; diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index 7aa0df92..1a68ce58 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -988,6 +988,84 @@ pub fn start_pic_probe( PicProbeHandle { rx, cancel } } +/// Progress/results from a background access (lock-state) probe. +pub enum AccessProbeMsg { + Started { total: usize }, + /// `locked` = Some(true) locked/view-only, Some(false) unlocked/writable, + /// None indeterminate; `error` set only when the probe couldn't run. + Result { ip: String, locked: Option, error: Option }, + Done { total: usize }, +} + +/// A running access probe; `stop` cancels the remaining miners. +pub struct AccessProbeHandle { + pub rx: Receiver, + cancel: Arc, +} + +impl AccessProbeHandle { + pub fn stop(&self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +/// Probe the access/lock state of `targets` (ip + firmware string) over the web +/// API with `creds` (user, pass), on a background thread. A digest-auth GET is +/// fast, but we still run one miner at a time with cancel-between. Fake-scan mode +/// returns deterministic demo results. +pub fn start_access_probe( + targets: Vec<(String, String)>, + creds: (String, String), +) -> AccessProbeHandle { + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let total = targets.len(); + let _ = tx.send(AccessProbeMsg::Started { total }); + let (user, pass) = creds; + + if fake_scan_enabled() { + let err_tx = tx.clone(); + let thread_cancel = cancel.clone(); + let res = std::thread::Builder::new().name("fake-access-probe".into()).spawn(move || { + for (ip, _fw) in targets { + if thread_cancel.load(Ordering::Relaxed) { + break; + } + // Demo: the WardenOS-dev unit (.115) is locked, others unlocked. + let locked = Some(ip.ends_with(".115")); + let _ = tx.send(AccessProbeMsg::Result { ip, locked, error: None }); + } + let _ = tx.send(AccessProbeMsg::Done { total }); + }); + if res.is_err() { + let _ = err_tx.send(AccessProbeMsg::Done { total }); + } + return AccessProbeHandle { rx, cancel }; + } + + let thread_cancel = cancel.clone(); + let err_tx = tx.clone(); + let res = std::thread::Builder::new().name("access-probe".into()).spawn(move || { + for (ip, fw) in targets { + if thread_cancel.load(Ordering::Relaxed) { + break; + } + let (locked, error) = match crate::access_probe::probe_access(&ip, &fw, &user, &pass) { + Ok(v) => (v, None), + Err(e) => (None, Some(e)), + }; + if tx.send(AccessProbeMsg::Result { ip, locked, error }).is_err() { + return; // UI gone + } + } + let _ = tx.send(AccessProbeMsg::Done { total }); + }); + if res.is_err() { + let _ = err_tx.send(AccessProbeMsg::Done { total }); + } + AccessProbeHandle { rx, cancel } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 0cf94848..40a3a58b 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -53,6 +53,7 @@ const ID_CTX_TUNING: i32 = 727; const ID_CTX_POWER: i32 = 728; const ID_CTX_RESTART: i32 = 729; const ID_CTX_PIC_PROBE: i32 = 730; +const ID_CTX_ACCESS_PROBE: i32 = 731; // SSH PIC-probe credentials dialog. const ID_PICSSH_OK: i32 = 780; const ID_PICSSH_CANCEL: i32 = 781; @@ -348,6 +349,8 @@ pub struct App { creds_dialog: Widget, creds_user_input: Widget, creds_pass_input: Widget, + // Background access (lock-state) probe. + access_probe: Option, // Background SSH PIC probe + its credentials dialog. pic_probe: Option, pending_pic_targets: Vec<(String, String)>, @@ -546,6 +549,7 @@ pub fn build(frame: Widget) -> App { creds_dialog: frame, creds_user_input: frame, creds_pass_input: frame, + access_probe: None, pic_probe: None, pending_pic_targets: Vec::new(), picssh_dialog: frame, @@ -833,6 +837,9 @@ impl App { // Real PIC-vs-noPIC detection via an on-board SSH i2c probe (asic-rs // cannot report it over the network); offered for any selection. menu.menu_append(ID_CTX_PIC_PROBE, "Detect PIC (SSH)..."); + // Real access/lock-state check (credentialed digest GET; uses the saved + // scan credentials). + menu.menu_append(ID_CTX_ACCESS_PROBE, "Check access (auth)"); // Config actions common to the whole selection (capability // intersection): an action is offered only if every selected miner // supports it. @@ -1018,6 +1025,82 @@ impl App { wx_rs::set_status_text(&format!("probing PIC on {n} miner(s) via SSH...")); } + /// Start the access (lock-state) probe on the selected miners, using the + /// saved scan (web) credentials (defaulting to root/root if none are set). + fn start_access_probe(&mut self) { + if self.flashing { + wx_rs::set_status_text("firmware flash in progress -- wait for it to finish"); + return; + } + if self.access_probe.is_some() { + wx_rs::set_status_text("an access check is already running"); + return; + } + let targets: Vec<(String, String)> = self + .selected_rows() + .iter() + .map(|r| (r.ip.clone(), r.firmware.clone())) + .collect(); + if targets.is_empty() { + return; + } + let creds = credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into())); + let n = targets.len(); + self.access_probe = Some(scan::start_access_probe(targets, creds)); + wx_rs::set_status_text(&format!("checking access on {n} miner(s)...")); + } + + /// Drain the running access probe: update each miner's write_locked as its + /// result arrives, and refresh the table + status when done. + fn drain_access_probe(&mut self) { + let Some(h) = &self.access_probe else { return }; + let mut status: Option = None; + let mut done = false; + let mut changed = false; + loop { + match h.rx.try_recv() { + Ok(scan::AccessProbeMsg::Started { total }) => { + status = Some(format!("access check: 0/{total}...")); + } + Ok(scan::AccessProbeMsg::Result { ip, locked, error }) => { + if let Some(r) = self.rows.iter_mut().find(|r| r.ip == ip) { + if error.is_none() { + r.write_locked = locked; + changed = true; + } + } + status = Some(match (&locked, &error) { + (_, Some(e)) => format!("access {ip}: {e}"), + (Some(true), _) => format!("access {ip}: locked"), + (Some(false), _) => format!("access {ip}: unlocked"), + (None, _) => format!("access {ip}: indeterminate"), + }); + } + Ok(scan::AccessProbeMsg::Done { total }) => { + status = Some(format!("access check done ({total} miner(s))")); + done = true; + break; + } + Err(std::sync::mpsc::TryRecvError::Empty) => break, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + done = true; + break; + } + } + } + if changed { + self.fill_rows(); + } + if done { + self.access_probe = None; + self.action_result = status.clone(); + self.action_result_ticks = ACTION_RESULT_TICKS; + } + if let Some(s) = status { + wx_rs::set_status_text(&s); + } + } + /// Drain the running PIC probe: update each miner's pic_present as its result /// arrives, and refresh the table + status when done. fn drain_pic_probe(&mut self) { @@ -1083,6 +1166,7 @@ impl App { } ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()), ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(), + ID_CTX_ACCESS_PROBE => self.start_access_probe(), ID_CTX_FLASH => { // A flash needs exclusive hardware access; don't even prompt if // any scan / refresh / action is running (re-checked at confirm). @@ -1563,11 +1647,12 @@ impl App { self.drain_action(); self.drain_refresh(); self.drain_pic_probe(); + self.drain_access_probe(); if self.scanning { return; // status already shows scan progress } - if self.pic_probe.is_some() { - return; // a PIC probe is in flight; keep its status + if self.pic_probe.is_some() || self.access_probe.is_some() { + return; // a probe is in flight; keep its status } if self.action.is_some() { return; // a config action is in flight; keep its status