From 571c2305aafbaae81d123895b95d0c69050a75cb Mon Sep 17 00:00:00 2001 From: noah Date: Tue, 22 Sep 2026 19:30:29 -0600 Subject: [PATCH] review wave 4: remaining round-2 findings (filters, creds, restore, panics) Clears the rest of the second review round's confirmed findings: - HIGH the Boards numeric filter compared the composite sort score (online*100+ total) instead of the board count, so a filter like "Boards <= 3" matched nothing on healthy 3-board miners. num_value now returns the detected count; regression-tested with per-board health present (the path the old test missed). - HIGH the WhatsMiner access probe ignored the operator's saved scan password (tried only admin/super), mis-reporting writable miners as locked. It now tries the caller's password first. - HIGH firmware flash and config actions were not blocked during a restore-to- stock; start_action and both flash guards now refuse while a restore runs. - MED log tail() could panic slicing at a non-UTF8 char boundary -> nudge to a boundary first (regression-tested). - MED board_index_from_text grabbed an unrelated number far past the keyword (e.g. a temperature) -> only accept a number immediately after the keyword. - MED a restore worker-thread spawn failure wedged the restore subsystem forever -> emit Done on spawn failure and treat a disconnected channel as done. - MED LuxOS restore reported failure when the miner rebooted mid-reply -> an empty reply or dropped connection after a successful logon is the expected reboot. - MED two tests raced on the process-global $HOME -> a shared serialization lock. - LOW CSV export now neutralizes spreadsheet formula-injection prefixes on miner-supplied fields. - Made miner_probe's global-only credential resolution explicit (it can't share the GUI's per-firmware configured_factory across the bin boundary). 99 tests (+3 regression tests) + clippy-clean + selftest green. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Djv3oncM4LxTS5tb61Ako6 --- crates/alkane-gui/src/access_probe.rs | 15 ++++++++++- crates/alkane-gui/src/bin/miner_probe.rs | 7 +++++- crates/alkane-gui/src/credentials.rs | 5 ++-- crates/alkane-gui/src/export.rs | 18 +++++++++---- crates/alkane-gui/src/log_scan.rs | 20 +++++++++++++-- crates/alkane-gui/src/model.rs | 28 +++++++++++++++++++++ crates/alkane-gui/src/restore.rs | 27 +++++++++++++++++++- crates/alkane-gui/src/scan.rs | 26 ++++++++++++++----- crates/alkane-gui/src/ui.rs | 32 ++++++++++++++++++------ 9 files changed, 152 insertions(+), 26 deletions(-) diff --git a/crates/alkane-gui/src/access_probe.rs b/crates/alkane-gui/src/access_probe.rs index f4986d1e..c8caa6d5 100644 --- a/crates/alkane-gui/src/access_probe.rs +++ b/crates/alkane-gui/src/access_probe.rs @@ -61,7 +61,20 @@ fn endpoint(_firmware: &str) -> &'static str { /// could not run at all. pub fn probe_access(ip: &str, make: &str, user: &str, pass: &str) -> Result, String> { if make.eq_ignore_ascii_case("whatsminer") { - return Ok(probe_whatsminer_access(ip, &whatsminer_password_candidates())); + // Try the caller's saved scan password first (round 18 #12: it was being + // ignored for WhatsMiner, so a miner opened with the operator's real + // password was mis-reported as locked), then the per-firmware override and + // factory defaults. All attempts are non-mutating. + let mut candidates = Vec::new(); + if !pass.is_empty() { + candidates.push(pass.to_string()); + } + for c in whatsminer_password_candidates() { + if !candidates.contains(&c) { + candidates.push(c); + } + } + return Ok(probe_whatsminer_access(ip, &candidates)); } let url = format!("http://{ip}{}", endpoint(make)); let mut cmd = Command::new("curl"); diff --git a/crates/alkane-gui/src/bin/miner_probe.rs b/crates/alkane-gui/src/bin/miner_probe.rs index bc1dbdcc..a7fc8156 100644 --- a/crates/alkane-gui/src/bin/miner_probe.rs +++ b/crates/alkane-gui/src/bin/miner_probe.rs @@ -39,12 +39,17 @@ fn load_creds() -> Option<(String, String)> { } fn factory() -> MinerFactory { + // This diagnostic CLI is a separate binary from the GUI, so it cannot share + // the GUI's credentials::configured_factory. It applies only the global scan + // credentials to every firmware; the GUI's per-firmware credential overrides + // are NOT read here (round 18 #12), which the message below makes explicit so a + // probe result is never mistaken for what the GUI (with overrides) would see. let mut f = MinerFactory::new(); if let Some((u, pw)) = load_creds() { for fw in asic_rs::factory::default_firmware_registry() { f = f.with_firmware_discovery_auth(fw.as_ref(), MinerAuth::new(u.clone(), pw.clone())); } - eprintln!("(using saved scan credentials for discovery auth)"); + eprintln!("(using the global scan credentials; per-firmware overrides are not applied)"); } else { eprintln!("(no saved credentials -- backends use their default auth)"); } diff --git a/crates/alkane-gui/src/credentials.rs b/crates/alkane-gui/src/credentials.rs index ffcbf064..c61104e7 100644 --- a/crates/alkane-gui/src/credentials.rs +++ b/crates/alkane-gui/src/credentials.rs @@ -216,8 +216,9 @@ mod tests { #[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). + // process-global, so serialise against other HOME-mutating tests via the + // shared lock and restore HOME afterward (round 18 #12). + let _home = crate::model::HOME_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); 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); diff --git a/crates/alkane-gui/src/export.rs b/crates/alkane-gui/src/export.rs index 634eaad0..49052cac 100644 --- a/crates/alkane-gui/src/export.rs +++ b/crates/alkane-gui/src/export.rs @@ -9,13 +9,21 @@ use crate::model::{BoardHealth, MinerRow}; -/// Escape one CSV field: quote it when it contains a comma, quote, CR or LF, and -/// double any embedded quotes. +/// Escape one CSV field: neutralise spreadsheet formula injection, then quote it +/// when it contains a comma, quote, CR or LF (doubling any embedded quotes). +/// +/// Miner-supplied fields (hostname, worker, serial, ...) can start with a formula +/// trigger; prefixing a single quote makes Excel/Sheets treat the cell as text so +/// opening the export can't execute an injected formula (round 18 #12). fn esc(s: &str) -> String { - if s.contains([',', '"', '\n', '\r']) { - format!("\"{}\"", s.replace('"', "\"\"")) + let mut val = s.to_string(); + if val.starts_with(['=', '+', '-', '@', '\t', '\r']) { + val.insert(0, '\''); + } + if val.contains([',', '"', '\n', '\r']) { + format!("\"{}\"", val.replace('"', "\"\"")) } else { - s.to_string() + val } } diff --git a/crates/alkane-gui/src/log_scan.rs b/crates/alkane-gui/src/log_scan.rs index ce2520bd..59cca4b3 100644 --- a/crates/alkane-gui/src/log_scan.rs +++ b/crates/alkane-gui/src/log_scan.rs @@ -61,8 +61,14 @@ fn tail(s: &str, max: usize) -> String { if s.len() <= max { return s.to_string(); } - let start = s.len() - max; - // advance to the next line boundary so we don't cut a line in half + // Nudge the cut forward to a UTF-8 char boundary first: a raw byte offset can + // land inside a multi-byte character and slicing there would panic (round 18 + // #12; miner logs are not guaranteed pure ASCII). + let mut start = s.len() - max; + while start < s.len() && !s.is_char_boundary(start) { + start += 1; + } + // then advance to the next line boundary so we don't cut a line in half let start = s[start..] .find('\n') .map(|i| start + i + 1) @@ -256,6 +262,16 @@ fn curl_config_quote(s: &str) -> String { mod tests { use super::*; + #[test] + fn tail_does_not_panic_mid_multibyte_char() { + // A byte-offset cut can land inside a multi-byte character; tail must nudge + // to a char boundary rather than panic (round 18 #12). + let s = "\u{00e9}".repeat(200); // 400 bytes of 2-byte chars, no newlines + let out = tail(&s, 101); // cut at an odd offset -> inside a char + assert!(out.starts_with("[... earlier log trimmed ...]")); + assert!(out.len() < s.len()); + } + #[test] fn summarize_finds_pic_chains_and_errors() { let log = "\ diff --git a/crates/alkane-gui/src/model.rs b/crates/alkane-gui/src/model.rs index d55fb362..2b2dae5c 100644 --- a/crates/alkane-gui/src/model.rs +++ b/crates/alkane-gui/src/model.rs @@ -2,6 +2,13 @@ use std::collections::{HashMap, HashSet}; +/// Serialises tests that mutate the process-global `$HOME` (config paths read it), +/// so they never race each other under the parallel test harness (round 18 #12). +/// Lock it with `.lock().unwrap_or_else(|e| e.into_inner())` to shrug off a poison +/// from a panicking sibling test. +#[cfg(test)] +pub(crate) static HOME_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// A miner counts as "slow" when it is mining but running below this fraction /// of its model's expected hashrate (UI-SPEC "Slow" band). A missing expected /// hashrate (0.0) means the band is unknown, so the miner is never "slow". @@ -1238,6 +1245,12 @@ impl Column { if !self.is_numeric() || self.cell(r).is_empty() { return None; } + // The Boards column's sort_key is a composite (online*100 + total) tuned + // for sorting; a numeric filter must compare the actual detected board + // count the cell shows, not that score (round 18 #12). + if let Column::Hashboards = self { + return r.hashboards.map(|v| v as f64); + } match self.sort_key(r) { SortKey::Num(v) if v.is_finite() => Some(v), _ => None, @@ -2642,6 +2655,21 @@ mod tests { assert_eq!(Column::TotalChips.num_value(&both), Some(190.0)); } + #[test] + fn hashboards_num_value_is_board_count_with_per_board_health() { + // With per-board health present (the normal live-scan case), the Boards + // filter must still compare the detected board count, not the composite + // sort score online*100+total (round 18 #12). The `both` fixture above + // leaves board_status empty, so it never exercised this path. + let r = MinerRow { + hashboards: Some(3), + expected_hashboards: Some(3), + board_status: vec![BoardHealth::Ok, BoardHealth::Ok, BoardHealth::Ok], + ..Default::default() + }; + assert_eq!(Column::Hashboards.num_value(&r), Some(3.0), "filter sees the board count, not 303"); + } + #[test] fn cooling_column_joins_fan_rpms_and_sorts_by_min() { let r = MinerRow { fan_rpms: vec![4200.0, 3990.0, 4500.0], ..Default::default() }; diff --git a/crates/alkane-gui/src/restore.rs b/crates/alkane-gui/src/restore.rs index ac89ed48..108df971 100644 --- a/crates/alkane-gui/src/restore.rs +++ b/crates/alkane-gui/src/restore.rs @@ -77,7 +77,8 @@ pub fn start_restore( } let tc = cancel.clone(); - let _ = std::thread::Builder::new() + let err_tx = tx.clone(); + let spawned = std::thread::Builder::new() .name("restore-stock".into()) .spawn(move || { let _ = tx.send(RestoreMsg::Started); @@ -92,6 +93,16 @@ pub fn start_restore( } let _ = tx.send(RestoreMsg::Done); }); + if spawned.is_err() { + // Never leave the restore subsystem wedged (round 18 #12): if the worker + // thread can't start, emit a failure + Done so the drain clears the handle. + let _ = err_tx.send(RestoreMsg::Result { + ip: String::new(), + ok: false, + detail: "could not start the restore worker thread".into(), + }); + let _ = err_tx.send(RestoreMsg::Done); + } RestoreHandle { rx, cancel } } @@ -166,7 +177,21 @@ fn restore_luxos(ip: &str) -> (bool, String) { Ok(resp) if resp.contains("350") || resp.to_lowercase().contains("uninstall") => { (true, "uninstalling LuxOS (reboots to stock)".into()) } + // The miner reboots as it reverts, so the reply is often dropped/empty + // after the command is accepted. The logon above already proved the miner + // was reachable, so an empty reply or a dropped connection here is the + // expected reboot, not a failure (round 18 #12). + Ok(resp) if resp.trim().is_empty() => { + (true, "uninstall accepted (miner rebooting to stock)".into()) + } Ok(resp) => (false, format!("uninstallluxos returned: {}", resp.trim())), + Err(e) + if ["closed", "reset", "timed out", "broken pipe", "eof"] + .iter() + .any(|m| e.to_lowercase().contains(m)) => + { + (true, "RPC dropped (miner rebooting to stock)".into()) + } Err(e) => (false, format!("uninstallluxos failed: {e}")), } } diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index df90f715..af901f6e 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -508,11 +508,13 @@ fn board_index_from_text(text: &str) -> Option { let mut from = 0; while let Some(rel) = lower[from..].find(kw) { let after = &lower[from + rel + kw.len()..]; - let digits: String = after - .trim_start_matches(|c: char| !c.is_ascii_digit()) - .chars() - .take_while(|c| c.is_ascii_digit()) - .collect(); + // The number must IMMEDIATELY follow the keyword (after only separators + // like " #-:._="), so "Chain 2 ..." -> 2 but "hashboard error, temp 65" + // does not grab the temperature 65 far past the keyword (round 18 #12). + let rest = after.trim_start_matches(|c: char| { + c.is_whitespace() || matches!(c, ':' | '#' | '-' | '_' | '.' | '=' | '(') + }); + let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); if let Ok(n) = digits.parse::() { return Some(n); } @@ -574,6 +576,16 @@ mod board_index_tests { assert_eq!(board_index_from_text("Environment temperature is too high."), None); assert_eq!(board_index_from_text("Power current error."), None); } + + #[test] + fn does_not_grab_an_unrelated_number_far_past_the_keyword() { + // The number must immediately follow the keyword: a later temperature/count + // must not be mistaken for the board index (round 18 #12). + assert_eq!(board_index_from_text("hashboard error, chip temp 65C"), None); + assert_eq!(board_index_from_text("board voltage low, 12 chips offline"), None); + // A real "board " still resolves even with trailing numbers. + assert_eq!(board_index_from_text("Chain 2 has 3 dead chips"), Some(2)); + } } /// Infer whether an Antminer's hashboards carry a per-board PIC MCU from the @@ -1833,7 +1845,9 @@ mod tests { #[test] fn auto_secs_round_trip_and_defaults() { // config_path() reads $HOME; point it at a private temp dir. HOME is - // process-global, so this stays one test and restores HOME afterward. + // process-global, so serialise against other HOME-mutating tests and + // restore HOME afterward (round 18 #12). + let _home = crate::model::HOME_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let prev = std::env::var_os("HOME"); let dir = std::env::temp_dir().join(format!("alkane-test-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 2b304638..1c6a0ef6 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -1899,6 +1899,12 @@ impl App { wx_rs::set_status_text("firmware flash in progress -- wait for it to finish"); return; } + // A restore-to-stock is reverting + rebooting miners; a config action mid- + // revert could hit a unit in an undefined state (round 18 #12). + if self.restore.is_some() { + wx_rs::set_status_text("restore-to-stock in progress -- wait for it to finish"); + return; + } if let Some(old) = self.action.take() { old.stop(); } @@ -2123,10 +2129,10 @@ impl App { let mut oks = 0usize; let mut fails: Vec = Vec::new(); let mut op_clear: Vec = Vec::new(); - while let Ok(msg) = h.rx.try_recv() { - match msg { - restore::RestoreMsg::Started => {} - restore::RestoreMsg::Result { ip, ok, detail } => { + loop { + match h.rx.try_recv() { + Ok(restore::RestoreMsg::Started) => {} + Ok(restore::RestoreMsg::Result { ip, ok, detail }) => { op_clear.push(ip.clone()); if ok { oks += 1; @@ -2134,7 +2140,17 @@ impl App { fails.push(format!("{ip}: {detail}")); } } - restore::RestoreMsg::Done => done = true, + Ok(restore::RestoreMsg::Done) => { + done = true; + break; + } + Err(std::sync::mpsc::TryRecvError::Empty) => break, + // The worker thread ended without a Done (e.g. it never started): + // finalise so the restore subsystem can't wedge (round 18 #12). + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + done = true; + break; + } } } for ip in &op_clear { @@ -2275,8 +2291,8 @@ impl App { ID_CTX_POOLS => return self.build_pools_dialog(), ID_CTX_FLASH => { // A flash needs exclusive hardware access; don't even prompt if - // any scan / refresh / action is running (re-checked at confirm). - if self.flashing || self.scanning || self.action.is_some() || self.refresh.is_some() { + // any scan / refresh / action / restore is running (re-checked at confirm). + if self.flashing || self.scanning || self.action.is_some() || self.refresh.is_some() || self.restore.is_some() { wx_rs::set_status_text("busy (scan/action in progress) -- try again once it finishes"); return None; } @@ -2683,7 +2699,7 @@ impl App { // started while the dialog was open. A flash must never race another // network operation on the same miner, so refuse rather than run the // prior handle's `stop()` (which does not join the in-flight upload). - if self.flashing || self.scanning || self.action.is_some() || self.refresh.is_some() { + if self.flashing || self.scanning || self.action.is_some() || self.refresh.is_some() || self.restore.is_some() { wx_rs::set_status_text("busy (scan/action started) -- flash cancelled, try again"); return; }