style: rustfmt the console/runtime work (no behaviour change)
source-pr / source (pull_request) Canceled after 0s
source-pr / source (pull_request) Failing after 9s

The source-pr gate runs cargo fmt --check; the afw OS-bundle line had not been
formatted. Pure cargo fmt output. 250 tests pass; clippy -D warnings clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
This commit is contained in:
2026-11-12 14:53:52 -06:00
co-authored by Claude Opus 5.5
parent 32ab0d75ba
commit dce31c8784
12 changed files with 412 additions and 114 deletions
+1 -1
View File
@@ -5,6 +5,7 @@
//! that runs on a board. Servers are bound before they are spawned, which lets a caller discover
//! ephemeral ports instead of guessing them.
use crate::bus::Bus;
use crate::detect::{
run_detection, DetectionBackend, DetectionFailure, DetectionRequest, FanZone, ProbeBudget,
SensorTopology,
@@ -13,7 +14,6 @@ use crate::fanmap::{FanMap, MapThresholds, SweepConfig};
use crate::fanmap_store::ensure_map;
use crate::fault::FaultPolicy;
use crate::hal_wire::{HalClient, HalError};
use crate::bus::Bus;
use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus};
use crate::profiles::{ProfileDb, ProfileError};
use crate::runtime::MinerRuntime;
+15 -3
View File
@@ -32,7 +32,10 @@ const SESSION_TTL: Duration = Duration::from_secs(12 * 3600);
const AUTH_FILE: &str = "/etc/alkane/auth.json";
fn now_unix() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
/// 16 bytes (32 hex) from the OS CSPRNG. The single random-token source for the
@@ -256,14 +259,23 @@ impl Auth {
fn persist(path: &Path, account: &Account) {
if let Some(parent) = path.parent() {
if fs::create_dir_all(parent).is_err() {
eprintln!("alkane auth: cannot create {}; account not persisted", parent.display());
eprintln!(
"alkane auth: cannot create {}; account not persisted",
parent.display()
);
return;
}
let _ = fs::set_permissions(parent, fs::Permissions::from_mode(0o700));
}
// The file holds the password hash: create it 0600, not umask-default.
let text = serde_json::to_string_pretty(&account.to_json()).unwrap_or_default();
match OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(path) {
match OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)
{
Ok(mut file) => {
let _ = file.write_all(text.as_bytes());
}
+10 -2
View File
@@ -4,7 +4,11 @@
//! rather than the cost of a Rust binary at all.
fn main() {
let sections = [("dashboard", "Dashboard"), ("mining", "Mining"), ("settings", "Settings")];
let sections = [
("dashboard", "Dashboard"),
("mining", "Mining"),
("settings", "Settings"),
];
let body = maud::html! {
section class="bf-card" {
h1 class="bf-text-title" { "Alkane OS" }
@@ -17,5 +21,9 @@ fn main() {
}
html.push_str(&body.into_string());
html.push_str("</body></html>");
println!("{} {}", html.len(), serde_json::json!({"sections": sections.len()}));
println!(
"{} {}",
html.len(),
serde_json::json!({"sections": sections.len()})
);
}
+13 -3
View File
@@ -43,8 +43,13 @@ fn main() {
};
let visible = nav::visible(&schema.menus, &ctx);
let first = visible.first_tab().map(|(section, tab)| Active { section, tab });
let active = first.unwrap_or(Active { section: "", tab: "" });
let first = visible
.first_tab()
.map(|(section, tab)| Active { section, tab });
let active = first.unwrap_or(Active {
section: "",
tab: "",
});
let body = maud::html! {
section class="bf-card" {
@@ -60,7 +65,12 @@ fn main() {
println!("html_bytes {}", html.len());
println!("sections {}", visible.sections.len());
for section in &visible.sections {
println!("section {} ({}) tabs={}", section.slug, section.title, section.tabs.len());
println!(
"section {} ({}) tabs={}",
section.slug,
section.title,
section.tabs.len()
);
}
} else {
println!("{html}");
+15 -4
View File
@@ -119,7 +119,10 @@ impl Bus {
/// Read the last retained document for a topic, if any.
pub fn read_state(&self, topic: &str) -> Option<Value> {
self.state.read().ok().and_then(|map| map.get(topic).cloned())
self.state
.read()
.ok()
.and_then(|map| map.get(topic).cloned())
}
/// Read a retained document, or a fallback when nothing is published yet.
@@ -169,7 +172,10 @@ impl Bus {
/// True when a service owns the verb.
pub fn has_verb(&self, verb: &str) -> bool {
self.handlers.read().map(|m| m.contains_key(verb)).unwrap_or(false)
self.handlers
.read()
.map(|m| m.contains_key(verb))
.unwrap_or(false)
}
/// Every registered verb, sorted, for introspection and parity tests.
@@ -244,7 +250,9 @@ mod tests {
#[test]
fn a_handler_can_reject_and_the_code_is_preserved() {
let bus = Bus::new();
bus.register("control/set", |_| Err(BusError::Rejected("out of range".into())));
bus.register("control/set", |_| {
Err(BusError::Rejected("out of range".into()))
});
let err = bus.request("control/set", &json!({})).unwrap_err();
assert_eq!(err.code(), "E_REJECTED");
assert_eq!(err.message(), "out of range");
@@ -269,7 +277,10 @@ mod tests {
let recent = bus.recent_events(5);
assert_eq!(recent.len(), 5);
// oldest-first, and the very last is the newest emitted.
assert_eq!(recent.last().unwrap().body["i"], (EVENT_RING + 10 - 1) as i64);
assert_eq!(
recent.last().unwrap().body["i"],
(EVENT_RING + 10 - 1) as i64
);
assert!(recent[0].body["i"].as_i64().unwrap() < recent[1].body["i"].as_i64().unwrap());
}
}
+70 -18
View File
@@ -61,7 +61,13 @@ pub fn page(
("settings", "terminal") => terminal_card(),
_ => components::card(&title, readings::note("This page has no content yet.")),
};
shell::page("Alkane OS", &Dashboard::assets(), &nav, Active { section, tab }, body)
shell::page(
"Alkane OS",
&Dashboard::assets(),
&nav,
Active { section, tab },
body,
)
}
/// The sign-in page: a standalone card (no nav) styled with the flare-ui tokens,
@@ -137,11 +143,17 @@ fn num(doc: &Value, pointer: &str) -> Option<f64> {
}
fn text(doc: &Value, pointer: &str, fallback: &str) -> String {
doc.pointer(pointer).and_then(Value::as_str).unwrap_or(fallback).to_string()
doc.pointer(pointer)
.and_then(Value::as_str)
.unwrap_or(fallback)
.to_string()
}
fn active_chain_count(hw: &Value) -> usize {
hw.get("active_chains").and_then(Value::as_array).map(|a| a.len()).unwrap_or(0)
hw.get("active_chains")
.and_then(Value::as_array)
.map(|a| a.len())
.unwrap_or(0)
}
/// Run/stop badge: a fault stop wins over the operator switch.
@@ -255,7 +267,13 @@ fn alerts_card(hw: &Value) -> Markup {
fn control_card(hw: &Value, ctl: &Value, csrf: &str) -> Markup {
let (level, state) = run_state(hw, ctl);
let run = reading("run", "State", None, "", 0);
let freq = reading("frequency_mhz", "Chain frequency", num(hw, "/frequency_mhz"), "MHz", 0);
let freq = reading(
"frequency_mhz",
"Chain frequency",
num(hw, "/frequency_mhz"),
"MHz",
0,
);
components::card(
"Control",
html! {
@@ -285,10 +303,20 @@ fn hashboards_card(hw: &Value) -> Markup {
.map(|c| {
vec![
c.get("index").map(|v| v.to_string()).unwrap_or_default(),
c.get("chip").and_then(Value::as_str).unwrap_or("-").to_string(),
c.get("chips_found").map(|v| v.to_string()).unwrap_or_default(),
c.pointer("/eeprom/state").and_then(Value::as_str).unwrap_or("-").to_string(),
c.get("response_per_mille").map(|v| v.to_string()).unwrap_or_default(),
c.get("chip")
.and_then(Value::as_str)
.unwrap_or("-")
.to_string(),
c.get("chips_found")
.map(|v| v.to_string())
.unwrap_or_default(),
c.pointer("/eeprom/state")
.and_then(Value::as_str)
.unwrap_or("-")
.to_string(),
c.get("response_per_mille")
.map(|v| v.to_string())
.unwrap_or_default(),
]
})
.collect()
@@ -299,7 +327,10 @@ fn hashboards_card(hw: &Value) -> Markup {
if rows.is_empty() {
readings::note("No chains detected.")
} else {
readings::table(&["#", "chip", "chips", "eeprom", "response per mille"], &rows)
readings::table(
&["#", "chip", "chips", "eeprom", "response per mille"],
&rows,
)
},
)
}
@@ -313,24 +344,36 @@ fn power_card(hw: &Value) -> Markup {
"Voltage range".into(),
format!(
"{} - {} mV",
hw.pointer("/envelope/v_min_mv").map(|v| v.to_string()).unwrap_or_default(),
hw.pointer("/envelope/v_max_mv").map(|v| v.to_string()).unwrap_or_default()
hw.pointer("/envelope/v_min_mv")
.map(|v| v.to_string())
.unwrap_or_default(),
hw.pointer("/envelope/v_max_mv")
.map(|v| v.to_string())
.unwrap_or_default()
),
),
(
"Frequency range".into(),
format!(
"{} - {} MHz",
hw.pointer("/envelope/f_min_mhz").map(|v| v.to_string()).unwrap_or_default(),
hw.pointer("/envelope/f_max_mhz").map(|v| v.to_string()).unwrap_or_default()
hw.pointer("/envelope/f_min_mhz")
.map(|v| v.to_string())
.unwrap_or_default(),
hw.pointer("/envelope/f_max_mhz")
.map(|v| v.to_string())
.unwrap_or_default()
),
),
(
"Operating point".into(),
format!(
"{} mV / {} MHz",
hw.pointer("/operating_point/voltage_mv").map(|v| v.to_string()).unwrap_or_default(),
hw.pointer("/operating_point/frequency_mhz").map(|v| v.to_string()).unwrap_or_default()
hw.pointer("/operating_point/voltage_mv")
.map(|v| v.to_string())
.unwrap_or_default(),
hw.pointer("/operating_point/frequency_mhz")
.map(|v| v.to_string())
.unwrap_or_default()
),
),
("Target".into(), text(hw, "/target", "-")),
@@ -389,7 +432,10 @@ fn security_card() -> Markup {
}
fn services_card() -> Markup {
components::card("Services", readings::table(&["service", "running"], &web::service_rows()))
components::card(
"Services",
readings::table(&["service", "running"], &web::service_rows()),
)
}
fn monitor_card(hw: &Value) -> Markup {
@@ -410,8 +456,14 @@ fn files_card() -> Markup {
.iter()
.map(|e| {
vec![
e.get("name").and_then(Value::as_str).unwrap_or("-").to_string(),
e.get("kind").and_then(Value::as_str).unwrap_or("-").to_string(),
e.get("name")
.and_then(Value::as_str)
.unwrap_or("-")
.to_string(),
e.get("kind")
.and_then(Value::as_str)
.unwrap_or("-")
.to_string(),
e.get("size").map(|v| v.to_string()).unwrap_or_default(),
]
})
+67 -18
View File
@@ -18,10 +18,10 @@ use serde_json::{Map, Value};
use flare_ui::assets::PageAssets;
use flare_ui::nav::{self, AllowAll, AppSet, CapSet, NavContext, VisibleNav};
use flare_ui::url::Routes;
use flare_ui::render::{self, View};
use flare_ui::shell::{self, Active};
use flare_ui::tokens;
use flare_ui::url::Routes;
use wschema::effective::{self, Effective};
use wschema::model::{Document, Surface};
use wschema::validate::{Op, Rows};
@@ -158,7 +158,13 @@ impl Dashboard {
(card)
}
};
shell::page("Alkane OS", &Self::assets(), &nav, Active { section, tab }, body)
shell::page(
"Alkane OS",
&Self::assets(),
&nav,
Active { section, tab },
body,
)
}
/// Apply a submitted form body (`application/x-www-form-urlencoded`).
@@ -176,7 +182,13 @@ impl Dashboard {
}
};
let ops = self.parse_ops(effective, body);
let failures = render::validate_form(effective, &ops, &self.rows, wschema::validate::Origin::Web, None);
let failures = render::validate_form(
effective,
&ops,
&self.rows,
wschema::validate::Origin::Web,
None,
);
if !failures.is_empty() {
return Err(failures);
}
@@ -190,7 +202,8 @@ impl Dashboard {
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
let text = serde_json::to_string_pretty(&Value::Object(map)).unwrap_or_else(|_| "{}".into());
let text =
serde_json::to_string_pretty(&Value::Object(map)).unwrap_or_else(|_| "{}".into());
// Persist only after validation passed, atomically (temp + rename), and
// surface a write failure instead of reporting a false success.
let fail = |message: String| -> BTreeMap<String, String> {
@@ -250,7 +263,10 @@ mod tests {
fn temp_path(name: &str) -> PathBuf {
let mut path = std::env::temp_dir();
path.push(format!("alkane-dashboard-{name}-{}.json", std::process::id()));
path.push(format!(
"alkane-dashboard-{name}-{}.json",
std::process::id()
));
let _ = fs::remove_file(&path);
path
}
@@ -286,7 +302,10 @@ mod tests {
"profiles.db",
"system.name",
] {
assert!(effective.setting(path).is_some(), "{path} is missing from the schema");
assert!(
effective.setting(path).is_some(),
"{path} is missing from the schema"
);
}
assert_eq!(effective.doc.settings.len(), 20);
}
@@ -294,24 +313,42 @@ mod tests {
#[test]
fn a_page_renders_its_settings_with_inputs() {
let dash = Dashboard::load(temp_path("page"));
let html = dash.page("settings", "tuning", &BTreeMap::new()).into_string();
assert!(html.contains("bf-sidebar"), "the unified sidebar is missing");
let html = dash
.page("settings", "tuning", &BTreeMap::new())
.into_string();
assert!(
html.contains("bf-sidebar"),
"the unified sidebar is missing"
);
assert!(html.contains("bf-tabs"), "the tab strip is missing");
assert!(html.contains("Tuning target"), "a settings label is missing");
assert!(
html.contains("Tuning target"),
"a settings label is missing"
);
assert!(html.contains("tuning.power_w"), "the field path is missing");
assert!(html.contains("name=\"tuning.mode\""), "the mode field is missing");
assert!(
html.contains("name=\"tuning.mode\""),
"the mode field is missing"
);
}
#[test]
fn a_valid_submission_is_persisted_and_reloaded() {
let path = temp_path("submit");
let mut dash = Dashboard::load(&path);
dash.submit("tuning.power_w=1500&system.name=s19jpro").expect("valid form");
assert_eq!(dash.rows().get("tuning.power_w"), Some(&serde_json::json!(1500)));
dash.submit("tuning.power_w=1500&system.name=s19jpro")
.expect("valid form");
assert_eq!(
dash.rows().get("tuning.power_w"),
Some(&serde_json::json!(1500))
);
let stored = fs::read_to_string(&path).expect("settings file written");
assert!(stored.contains("\"tuning.power_w\": 1500"), "{stored}");
let reloaded = Dashboard::load(&path);
assert_eq!(reloaded.rows().get("system.name"), Some(&serde_json::json!("s19jpro")));
assert_eq!(
reloaded.rows().get("system.name"),
Some(&serde_json::json!("s19jpro"))
);
let _ = fs::remove_file(&path);
}
@@ -319,9 +356,17 @@ mod tests {
fn an_out_of_range_value_is_rejected_and_nothing_is_written() {
let path = temp_path("reject");
let mut dash = Dashboard::load(&path);
let failures = dash.submit("tuning.power_w=99999").expect_err("must be rejected");
assert!(failures.keys().any(|key| key.contains("tuning.power_w")), "{failures:?}");
assert!(!path.exists(), "a rejected submission must not be persisted");
let failures = dash
.submit("tuning.power_w=99999")
.expect_err("must be rejected");
assert!(
failures.keys().any(|key| key.contains("tuning.power_w")),
"{failures:?}"
);
assert!(
!path.exists(),
"a rejected submission must not be persisted"
);
assert_eq!(dash.rows().get("tuning.power_w"), None);
}
@@ -329,9 +374,13 @@ mod tests {
fn unknown_form_keys_are_ignored() {
let path = temp_path("unknown");
let mut dash = Dashboard::load(&path);
dash.submit("not.a.setting=1&tuning.ceiling_mc=650").expect("known key applies");
dash.submit("not.a.setting=1&tuning.ceiling_mc=650")
.expect("known key applies");
assert_eq!(dash.rows().get("not.a.setting"), None);
assert_eq!(dash.rows().get("tuning.ceiling_mc"), Some(&serde_json::json!(650)));
assert_eq!(
dash.rows().get("tuning.ceiling_mc"),
Some(&serde_json::json!(650))
);
let _ = fs::remove_file(&path);
}
+7 -7
View File
@@ -6,21 +6,19 @@
pub mod app;
pub mod auth;
pub mod bm1362;
pub mod bus;
pub mod console;
pub mod control;
pub mod form;
pub mod registry;
pub mod service;
pub mod bm1366;
pub mod bm1370;
pub mod bm13xx;
pub mod detect;
pub mod bus;
pub mod console;
pub mod control;
pub mod dashboard;
pub mod detect;
pub mod difficulty;
pub mod fanmap;
pub mod fanmap_store;
pub mod fault;
pub mod form;
pub mod hal_conformance;
pub mod hal_sim;
pub mod hal_wire;
@@ -28,8 +26,10 @@ pub mod management;
pub mod miner;
pub mod pow;
pub mod profiles;
pub mod registry;
pub mod runtime;
pub mod scrypt_pow;
pub mod service;
pub mod split;
pub mod stratum_client;
pub mod stratum_link;
+1 -1
View File
@@ -2,7 +2,6 @@
use alkane_os::app;
use alkane_os::bus::Bus;
use alkane_os::control::Control;
use alkane_os::service;
use alkane_os::detect::{
ChipModel as DetectedChip, DetectionBackend, EepromState, Envelope, ProbeBudget, ProbeOutcome,
PsuCapability, SensorTopology,
@@ -11,6 +10,7 @@ use alkane_os::hal_wire::HalClient;
use alkane_os::management::MiningStatus;
use alkane_os::miner::{Bm1366Miner, ChipModel};
use alkane_os::runtime::{Tick, TickOutcome};
use alkane_os::service;
use alkane_os::stratum_client::{PoolConnection, PoolEvent};
use alkane_os::target_matrix;
use alkane_os::tuning::{PidConfig, TuningTarget};
+5 -1
View File
@@ -67,7 +67,11 @@ pub fn contract() -> Value {
pub fn contract_verbs() -> Vec<String> {
let mut v: Vec<String> = contract()["verbs"]
.as_array()
.map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect())
.map(|a| {
a.iter()
.filter_map(|x| x.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default();
v.sort();
v
+47 -13
View File
@@ -58,7 +58,8 @@ pub(crate) fn load_deck(deck: &str) -> Value {
fn save_deck(deck: &str, doc: &Value) -> Result<(), String> {
let path = deck_path(deck);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
fs::create_dir_all(parent)
.map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
}
let text = serde_json::to_string_pretty(doc).map_err(|e| e.to_string())?;
// Atomic replace: a concurrent read never sees a half-written deck.
@@ -79,7 +80,9 @@ fn apply_tuning(body: &str, control: &Control) {
"max-fan" => ("fan", "tuning.max_fan_pwm"),
_ => return,
};
if let Some(value) = crate::form::field(body, value_field).and_then(|v| v.trim().parse::<f32>().ok()) {
if let Some(value) =
crate::form::field(body, value_field).and_then(|v| v.trim().parse::<f32>().ok())
{
let _ = control.set_mode_value(mode, value);
}
}
@@ -97,7 +100,10 @@ struct MinerService {
impl MinerService {
fn republish_control(&self) {
if let Some(bus) = self.bus.upgrade() {
bus.publish_state(topics::CONTROL, control_document(&self.status, &self.control));
bus.publish_state(
topics::CONTROL,
control_document(&self.status, &self.control),
);
}
}
}
@@ -137,7 +143,9 @@ pub fn register(bus: &Arc<Bus>, status: Arc<MiningStatus>, control: Arc<Control>
.and_then(Value::as_f64)
.ok_or_else(|| BusError::BadRequest("value is required".into()))?
as f32;
s.control.set_mode_value(mode, value).map_err(BusError::Rejected)?;
s.control
.set_mode_value(mode, value)
.map_err(BusError::Rejected)?;
s.republish_control();
Ok(json!({
"target": control::target_label(s.control.target()),
@@ -168,11 +176,17 @@ pub fn register(bus: &Arc<Bus>, status: Arc<MiningStatus>, control: Arc<Control>
});
}
bus.register(verbs::DASHBOARD_LOAD, |body| {
let deck = body.get("deck").and_then(Value::as_str).unwrap_or("dashboard");
let deck = body
.get("deck")
.and_then(Value::as_str)
.unwrap_or("dashboard");
Ok(load_deck(deck))
});
bus.register(verbs::DASHBOARD_SAVE, |body| {
let deck = body.get("deck").and_then(Value::as_str).unwrap_or("dashboard");
let deck = body
.get("deck")
.and_then(Value::as_str)
.unwrap_or("dashboard");
let doc = body
.get("doc")
.ok_or_else(|| BusError::BadRequest("doc is required".into()))?;
@@ -181,7 +195,10 @@ pub fn register(bus: &Arc<Bus>, status: Arc<MiningStatus>, control: Arc<Control>
Ok(validated)
});
bus.register(verbs::DASHBOARD_RESET, |body| {
let deck = body.get("deck").and_then(Value::as_str).unwrap_or("dashboard");
let deck = body
.get("deck")
.and_then(Value::as_str)
.unwrap_or("dashboard");
let doc = ui::default_deck(deck);
save_deck(deck, &doc).map_err(BusError::Rejected)?;
Ok(doc)
@@ -220,7 +237,11 @@ mod tests {
#[test]
fn registered_verbs_match_the_contract() {
let bus = Bus::new();
register(&bus, Arc::new(MiningStatus::new()), Arc::new(Control::default()));
register(
&bus,
Arc::new(MiningStatus::new()),
Arc::new(Control::default()),
);
let mut registered = bus.verbs();
registered.sort();
// Every registered verb is declared in the contract (nothing undocumented),
@@ -241,7 +262,10 @@ mod tests {
.map(|v| v.as_str().unwrap().to_string())
.collect();
declared.sort();
assert_eq!(published, declared, "published state topics must match the contract");
assert_eq!(
published, declared,
"published state topics must match the contract"
);
}
#[test]
@@ -253,8 +277,11 @@ mod tests {
assert!(control.running());
bus.request(verbs::CONTROL_STOP, &json!({})).unwrap();
assert!(!control.running());
bus.request(verbs::CONTROL_SET_TARGET, &json!({"mode": "ambient", "value": 18.0}))
.unwrap();
bus.request(
verbs::CONTROL_SET_TARGET,
&json!({"mode": "ambient", "value": 18.0}),
)
.unwrap();
assert_eq!(
control.target(),
crate::tuning::TuningTarget::AmbientC { margin_mc: 18_000 }
@@ -264,9 +291,16 @@ mod tests {
#[test]
fn set_target_rejects_a_bad_mode() {
let bus = Bus::new();
register(&bus, Arc::new(MiningStatus::new()), Arc::new(Control::default()));
register(
&bus,
Arc::new(MiningStatus::new()),
Arc::new(Control::default()),
);
let err = bus
.request(verbs::CONTROL_SET_TARGET, &json!({"mode": "bogus", "value": 1.0}))
.request(
verbs::CONTROL_SET_TARGET,
&json!({"mode": "bogus", "value": 1.0}),
)
.unwrap_err();
assert_eq!(err.code(), "E_REJECTED");
}
+161 -43
View File
@@ -221,8 +221,8 @@ fn route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Res
// The read-only miner-state JSON stays open (it is the interface of record
// and is already exposed on the cgminer socket). Everything else - the HTML
// console, host reads, and every mutation - needs a live session.
let open_api = method == "GET"
&& matches!(path, "/api/hardware" | "/api/summary" | "/api/control");
let open_api =
method == "GET" && matches!(path, "/api/hardware" | "/api/summary" | "/api/control");
let authed = request.wsid.as_deref().is_some_and(|w| ctx.auth.valid(w));
if !authed && !open_api {
if method == "GET" && !path.starts_with("/api/") {
@@ -233,7 +233,11 @@ fn route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Res
if method == "POST" && path == "/auth/logout" {
let wsid = request.wsid.clone().unwrap_or_default();
ctx.auth.logout(&wsid);
return redirect_cookie(stream, "/login", "wsid=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0");
return redirect_cookie(
stream,
"/login",
"wsid=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0",
);
}
if dashboard_route(stream, ctx, request)? {
@@ -241,15 +245,19 @@ fn route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Res
}
let bus = &ctx.bus;
match (request.method.as_str(), request.path.as_str()) {
("GET", "/api/hardware") => {
json_response(stream, &bus.read_state_or(topics::HARDWARE, json!({"available": false})))
}
("GET", "/api/hardware") => json_response(
stream,
&bus.read_state_or(topics::HARDWARE, json!({"available": false})),
),
("GET", "/api/summary") => {
json_response(stream, &bus.read_state_or(topics::SUMMARY, json!({})))
}
("GET", "/api/control") => json_response(
stream,
&bus.read_state_or(topics::CONTROL, json!({"running": false, "available": false})),
&bus.read_state_or(
topics::CONTROL,
json!({"running": false, "available": false}),
),
),
("GET", "/api/dashboard") => {
let deck = request.param_or("deck", "dashboard");
@@ -264,7 +272,9 @@ fn route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Res
bus.request(verbs::DASHBOARD_RESET, &json!({"deck": deck}))
} else {
match serde_json::from_str::<Value>(&request.body) {
Ok(doc) => bus.request(verbs::DASHBOARD_SAVE, &json!({"deck": deck, "doc": doc})),
Ok(doc) => {
bus.request(verbs::DASHBOARD_SAVE, &json!({"deck": deck, "doc": doc}))
}
Err(error) => {
return respond(stream, 400, "text/plain", error.to_string().as_bytes())
}
@@ -273,8 +283,17 @@ fn route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Res
match result {
Ok(doc) => json_response(stream, &doc),
Err(error) => {
let code = if error.code() == "E_REJECTED" { 400 } else { 500 };
respond(stream, code, "application/json", error.envelope().to_string().as_bytes())
let code = if error.code() == "E_REJECTED" {
400
} else {
500
};
respond(
stream,
code,
"application/json",
error.envelope().to_string().as_bytes(),
)
}
}
}
@@ -322,7 +341,11 @@ fn route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Res
/// Serve the schema-driven console (nav GET) and the browser command forms
/// (`/settings`, `/control/*`). Returns `false` for anything else so the API
/// routes keep working.
fn dashboard_route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Result<bool> {
fn dashboard_route(
stream: &mut TcpStream,
ctx: &WebContext,
request: &Request,
) -> io::Result<bool> {
let path = request.path.clone();
if request.method == "POST" {
return match path.as_str() {
@@ -353,10 +376,13 @@ fn dashboard_route(stream: &mut TcpStream, ctx: &WebContext, request: &Request)
Some(section) => section,
None => return Ok(false),
};
let tab = parts
.next()
.map(str::to_string)
.unwrap_or_else(|| known.tabs.first().map(|tab| tab.slug.clone()).unwrap_or_default());
let tab = parts.next().map(str::to_string).unwrap_or_else(|| {
known
.tabs
.first()
.map(|tab| tab.slug.clone())
.unwrap_or_default()
});
if !known.tabs.iter().any(|t| t.slug == tab) {
return Ok(false);
}
@@ -387,9 +413,18 @@ fn control_switch(
running: bool,
) -> io::Result<()> {
if !csrf_ok(ctx, request) {
return respond(stream, 403, "text/plain", b"stale control token; reload the page");
return respond(
stream,
403,
"text/plain",
b"stale control token; reload the page",
);
}
let verb = if running { verbs::CONTROL_START } else { verbs::CONTROL_STOP };
let verb = if running {
verbs::CONTROL_START
} else {
verbs::CONTROL_STOP
};
match ctx.bus.request(verb, &json!({})) {
Ok(_) => redirect(stream, "/mining/overview"),
Err(error) => respond(stream, 500, "text/plain", error.to_string().as_bytes()),
@@ -401,7 +436,9 @@ fn control_switch(
fn safe_slug(value: &str, fallback: &str) -> String {
let ok = !value.is_empty()
&& value.len() <= 32
&& value.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
&& value
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
if ok {
value.to_string()
} else {
@@ -412,13 +449,27 @@ fn safe_slug(value: &str, fallback: &str) -> String {
/// Apply a settings form through the bus: persist the rows and drive the runtime.
fn settings_submit(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Result<()> {
if !csrf_ok(ctx, request) {
return respond(stream, 403, "text/plain", b"stale control token; reload the page");
return respond(
stream,
403,
"text/plain",
b"stale control token; reload the page",
);
}
// The redirect target is built from these, so constrain them to safe slugs
// (no CRLF/path tricks into the Location header).
let section = safe_slug(&form::field(&request.body, "__section").unwrap_or_default(), "settings");
let tab = safe_slug(&form::field(&request.body, "__tab").unwrap_or_default(), "tuning");
match ctx.bus.request(verbs::SETTINGS_APPLY, &json!({"form": request.body})) {
let section = safe_slug(
&form::field(&request.body, "__section").unwrap_or_default(),
"settings",
);
let tab = safe_slug(
&form::field(&request.body, "__tab").unwrap_or_default(),
"tuning",
);
match ctx
.bus
.request(verbs::SETTINGS_APPLY, &json!({"form": request.body}))
{
Ok(_) => redirect(stream, &format!("/{section}/{tab}")),
Err(error) => {
let mut errors = BTreeMap::new();
@@ -469,7 +520,12 @@ fn auth_local(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io
}
fn json_response(stream: &mut TcpStream, value: &Value) -> io::Result<()> {
respond(stream, 200, "application/json", value.to_string().as_bytes())
respond(
stream,
200,
"application/json",
value.to_string().as_bytes(),
)
}
// --- page data (host facts the console renders) ------------------------------
@@ -605,7 +661,10 @@ pub(crate) fn driver_rows(hw: &Value) -> Vec<(&'static str, String)> {
),
(
"board profile",
hw["profile"].as_str().unwrap_or("not identified").to_string(),
hw["profile"]
.as_str()
.unwrap_or("not identified")
.to_string(),
),
(
"power supply",
@@ -613,11 +672,19 @@ pub(crate) fn driver_rows(hw: &Value) -> Vec<(&'static str, String)> {
),
(
"chains detected",
hw["chains"].as_array().map(|c| c.len()).unwrap_or(0).to_string(),
hw["chains"]
.as_array()
.map(|c| c.len())
.unwrap_or(0)
.to_string(),
),
(
"chains active",
hw["active_chains"].as_array().map(|c| c.len()).unwrap_or(0).to_string(),
hw["active_chains"]
.as_array()
.map(|c| c.len())
.unwrap_or(0)
.to_string(),
),
(
"stopped",
@@ -636,7 +703,12 @@ pub(crate) fn security_rows() -> Vec<(&'static str, String)> {
})
.unwrap_or_else(|_| "unreadable".into());
let keys = fs::read_to_string("/root/.ssh/authorized_keys")
.map(|text| text.lines().filter(|l| !l.trim().is_empty()).count().to_string())
.map(|text| {
text.lines()
.filter(|l| !l.trim().is_empty())
.count()
.to_string()
})
.unwrap_or_else(|_| "0".into());
let dropbear = if running("dropbear") {
"running"
@@ -908,9 +980,18 @@ mod tests {
let reply = client("GET / HTTP/1.1\r\nHost: x\r\n\r\n");
assert!(reply.starts_with("HTTP/1.1 200 OK"));
assert!(reply.contains("text/html"));
assert!(reply.contains("bf-sidebar"), "the flare-ui sidebar is missing");
assert!(reply.contains("Mining"), "the Mining section link is missing");
assert!(reply.contains("Settings"), "the Settings section link is missing");
assert!(
reply.contains("bf-sidebar"),
"the flare-ui sidebar is missing"
);
assert!(
reply.contains("Mining"),
"the Mining section link is missing"
);
assert!(
reply.contains("Settings"),
"the Settings section link is missing"
);
}
#[test]
@@ -961,7 +1042,10 @@ mod tests {
let body = reply.split("\r\n\r\n").nth(1).unwrap_or("");
let doc: Value = serde_json::from_str(body).unwrap_or_else(|_| json!({}));
assert_eq!(doc["version"], 1);
assert!(doc["blocks"].as_array().map(|b| !b.is_empty()).unwrap_or(false));
assert!(doc["blocks"]
.as_array()
.map(|b| !b.is_empty())
.unwrap_or(false));
}
#[test]
@@ -977,14 +1061,18 @@ mod tests {
#[test]
fn the_terminal_is_forbidden_without_a_token() {
std::env::remove_var("ALKANE_UI_TOKEN");
let reply = client("POST /api/terminal?cmd=id HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\n\r\n");
let reply =
client("POST /api/terminal?cmd=id HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\n\r\n");
assert!(reply.starts_with("HTTP/1.1 403"), "{reply}");
}
#[test]
fn start_requires_the_csrf_token() {
let (ctx, control, wsid) = context();
let reply = send(&with_cookie(&post("/control/start", "csrf=wrong"), &wsid), ctx);
let reply = send(
&with_cookie(&post("/control/start", "csrf=wrong"), &wsid),
ctx,
);
assert!(reply.starts_with("HTTP/1.1 403"), "{reply}");
assert!(!control.running(), "a stale token must not start mining");
}
@@ -992,11 +1080,17 @@ mod tests {
#[test]
fn start_and_stop_with_a_good_token_switch_the_runtime() {
let (ctx, control, wsid) = context();
let reply = send(&with_cookie(&post("/control/start", "csrf=test-csrf"), &wsid), Arc::clone(&ctx));
let reply = send(
&with_cookie(&post("/control/start", "csrf=test-csrf"), &wsid),
Arc::clone(&ctx),
);
assert!(reply.starts_with("HTTP/1.1 303"), "{reply}");
assert!(reply.contains("Location: /mining/overview"));
assert!(control.running(), "a good token must start mining");
let reply = send(&with_cookie(&post("/control/stop", "csrf=test-csrf"), &wsid), ctx);
let reply = send(
&with_cookie(&post("/control/stop", "csrf=test-csrf"), &wsid),
ctx,
);
assert!(reply.starts_with("HTTP/1.1 303"), "{reply}");
assert!(!control.running(), "stop must clear the run flag");
}
@@ -1012,7 +1106,10 @@ mod tests {
"{reply}"
);
if reply.starts_with("HTTP/1.1 303") {
assert_eq!(control.target(), TuningTarget::AmbientC { margin_mc: 18_000 });
assert_eq!(
control.target(),
TuningTarget::AmbientC { margin_mc: 18_000 }
);
}
}
@@ -1021,7 +1118,10 @@ mod tests {
let reply = client_anon("GET / HTTP/1.1\r\nHost: x\r\n\r\n");
assert!(reply.starts_with("HTTP/1.1 200 OK"));
assert!(reply.contains("Sign in"), "the login page is missing");
assert!(!reply.contains("bf-sidebar"), "the console must not render before login");
assert!(
!reply.contains("bf-sidebar"),
"the console must not render before login"
);
}
#[test]
@@ -1030,30 +1130,48 @@ mod tests {
let reply = client_anon("GET /api/files?path=/ HTTP/1.1\r\nHost: x\r\n\r\n");
assert!(reply.starts_with("HTTP/1.1 401"), "{reply}");
let open = client_anon("GET /api/hardware HTTP/1.1\r\nHost: x\r\n\r\n");
assert!(open.starts_with("HTTP/1.1 200"), "miner state must stay open: {open}");
assert!(
open.starts_with("HTTP/1.1 200"),
"miner state must stay open: {open}"
);
}
#[test]
fn bad_credentials_are_rejected() {
let reply = client_anon(&post("/auth/local", "csrf=test-csrf&user=admin&password=wrong"));
let reply = client_anon(&post(
"/auth/local",
"csrf=test-csrf&user=admin&password=wrong",
));
assert!(reply.starts_with("HTTP/1.1 200 OK"));
assert!(reply.contains("Wrong user name or password"), "{reply}");
}
#[test]
fn factory_login_sets_a_session_cookie() {
let reply = client_anon(&post("/auth/local", "csrf=test-csrf&user=admin&password=admin"));
let reply = client_anon(&post(
"/auth/local",
"csrf=test-csrf&user=admin&password=admin",
));
assert!(reply.starts_with("HTTP/1.1 303"), "{reply}");
assert!(reply.contains("Set-Cookie: wsid="), "no session cookie issued");
assert!(
reply.contains("Set-Cookie: wsid="),
"no session cookie issued"
);
}
#[test]
fn logout_ends_the_session() {
let (ctx, _control, wsid) = context();
assert!(ctx.auth.valid(&wsid));
let reply = send(&with_cookie(&post("/auth/logout", ""), &wsid), Arc::clone(&ctx));
let reply = send(
&with_cookie(&post("/auth/logout", ""), &wsid),
Arc::clone(&ctx),
);
assert!(reply.starts_with("HTTP/1.1 303"), "{reply}");
assert!(reply.contains("Max-Age=0"), "the cookie must be cleared");
assert!(!ctx.auth.valid(&wsid), "the session must be gone after logout");
assert!(
!ctx.auth.valid(&wsid),
"the session must be gone after logout"
);
}
}