From 2c5eccae55c9be23734196db1dbb412174f348e6 Mon Sep 17 00:00:00 2001 From: Noah <2+noah@noreply.gitea.bluefla.re> Date: Tue, 10 Nov 2026 21:41:59 -0600 Subject: [PATCH] os: apply code-review-harness fixes (security/reliability/correctness) Four-dimension review (correctness/security/reliability/maintainability) of today's console/bus/login/dashboard/image work found no Critical/High; the HTTP parser, login gate (un-bypassable), bus semantics and the HMAC/PBKDF2/SHA-256 math were verified correct. The Medium findings are fixed here. Security: - Token-gate /api/files and /api/file (were session-only despite the docs/Security page claiming token-gated - arbitrary root-readable file exfiltration). - Neutralize settings-redirect header-splitting: __section/__tab are constrained to safe slugs before going into the Location header (CRLF no longer injects). - One token source (auth::rand_hex): fail loud + non-constant fallback instead of the published "dev-csrf-token" / second-granular wsid when /dev/urandom is unreadable. - Constant-time UI-token compare (auth::ct_eq); write auth.json 0600, dir 0700. - Cap concurrent connections (64, 503 beyond) + 10s head-read deadline, bounding the thread-per-connection flood on the open :80. Reliability/correctness: - Settings persistence now propagates its write error (was swallowed and reported as success with a misleading comment) and writes atomically (temp+rename); deck save atomic too. Auth::login returns None if the session insert failed. - TuningLoop::set_target resets the PID accumulator on a mode change (the old target's integral is in the old units) while keeping the operating point. - Editable-deck JS: monotonic new-block ids (no collision after remove+add), default source frequency (was power_w, not in the live map), symmetric drag-drop placement, re-render after save. Drivers "stopped" shows the bare reason, not JSON-quoted. Maintainability: - New `form` module consolidates the three divergent percent_decode/field copies (web/service/dashboard). Added a test asserting published state topics match the registry contract. Report in code-review-report.md (verdict, accepted-by-design posture incl. the no-TLS / factory-creds residual risk, and a deferred list: ui.rs dead code, deck assets extraction, target_label dedup). 206 lib tests + integration pass, clippy -D warnings clean, no emojis. Image rebuilt with the fixed binary. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk --- .claude/code-review-memory.log | 7 ++ .claude/code-review-memory.md | 44 +++++++++++ code-review-report.md | 110 ++++++++++++++++++++++++++++ src/auth.rs | 58 +++++++++++---- src/console.rs | 6 +- src/dashboard.rs | 55 ++++---------- src/form.rs | 66 +++++++++++++++++ src/lib.rs | 1 + src/service.rs | 66 ++++++----------- src/tuning.rs | 19 ++++- src/web.rs | 129 +++++++++++++++------------------ 11 files changed, 387 insertions(+), 174 deletions(-) create mode 100644 .claude/code-review-memory.log create mode 100644 .claude/code-review-memory.md create mode 100644 code-review-report.md create mode 100644 src/form.rs diff --git a/.claude/code-review-memory.log b/.claude/code-review-memory.log new file mode 100644 index 0000000..9e909c6 --- /dev/null +++ b/.claude/code-review-memory.log @@ -0,0 +1,7 @@ +2026-11-10T21:41:18-06:00 1 17293278c1c7 src/web.rs 320 Medium files/file endpoints not token-gated (fixed) +2026-11-10T21:41:18-06:00 1 073768bc5201 src/web.rs 389 Medium settings redirect header-splitting via __section/__tab (fixed) +2026-11-10T21:41:18-06:00 1 d45a2e52d1ba src/auth.rs 37 Medium RNG fallback to constant csrf/guessable wsid (fixed) +2026-11-10T21:41:18-06:00 1 b6701ede5237 src/dashboard.rs 199 Medium settings write error swallowed, reported success (fixed) +2026-11-10T21:41:18-06:00 1 1b4915d2c7a6 src/tuning.rs 180 Low set_target kept PID integral across unit-mismatched modes (fixed) +2026-11-10T21:41:18-06:00 1 97ba434fdd3a src/console.rs 234 Medium editable-deck new-block id collision (fixed) +2026-11-10T21:41:18-06:00 1 0a2a1950ad0d src/web.rs 81 Medium unbounded thread-per-connection DoS (fixed: conn cap) diff --git a/.claude/code-review-memory.md b/.claude/code-review-memory.md new file mode 100644 index 0000000..ce86c87 --- /dev/null +++ b/.claude/code-review-memory.md @@ -0,0 +1,44 @@ +# Code Review Memory + +This file is maintained by the `code-review-harness` skill. It records +findings across review sessions so the skill can spot recurring issues +and apply more aggressive remediation when an issue persists. + +The skill **reads this file at the start of every review** and **updates +it at the end** with new findings. + +## How to use + +- The "Recurring Issues" section is rebuilt automatically each run. Treat + it as the high-signal list of things that keep coming back. +- The "Session Log" is append-only. Each row is one finding from one + session. The log is the source of truth; the index is derived from it. +- If a finding has been fixed and you don't want it to count toward + recurrence anymore, add a `RESOLVED:` row referencing the finding + fingerprint. + +## Recurring Issues + +_(auto-generated — rebuilt at end of each session)_ + + + +_No recurring issues yet — every finding has been a one-off, or memory was just initialized._ + + + +## Session Log + +_(append-only)_ + + + +- `2026-11-10T21:41:18-06:00` iter=1 `src/web.rs:320` [Medium] files/file endpoints not token-gated (fixed) (fp:17293278c1c7) +- `2026-11-10T21:41:18-06:00` iter=1 `src/web.rs:389` [Medium] settings redirect header-splitting via __section/__tab (fixed) (fp:073768bc5201) +- `2026-11-10T21:41:18-06:00` iter=1 `src/auth.rs:37` [Medium] RNG fallback to constant csrf/guessable wsid (fixed) (fp:d45a2e52d1ba) +- `2026-11-10T21:41:18-06:00` iter=1 `src/dashboard.rs:199` [Medium] settings write error swallowed, reported success (fixed) (fp:b6701ede5237) +- `2026-11-10T21:41:18-06:00` iter=1 `src/tuning.rs:180` [Low] set_target kept PID integral across unit-mismatched modes (fixed) (fp:1b4915d2c7a6) +- `2026-11-10T21:41:18-06:00` iter=1 `src/console.rs:234` [Medium] editable-deck new-block id collision (fixed) (fp:97ba434fdd3a) +- `2026-11-10T21:41:18-06:00` iter=1 `src/web.rs:81` [Medium] unbounded thread-per-connection DoS (fixed: conn cap) (fp:0a2a1950ad0d) + + diff --git a/code-review-report.md b/code-review-report.md new file mode 100644 index 0000000..25f4ce6 --- /dev/null +++ b/code-review-report.md @@ -0,0 +1,110 @@ +# Code review report - alkane-os console/bus/login/dashboard/image + +Scope: today's work on `feature/afw-os-bundle` (bus, registry, service, web, console, +app, main, control, runtime, tuning, auth, dashboard, schema menus, image tooling). +Method: code-review-harness, 4 parallel reviewers (correctness, security, reliability, +maintainability) at high reasoning effort over the branch diff, then fixes applied and +re-verified. Installation-from-stock / restore-to-stock method tooling was out of scope +(DeepSeek Harness's domain; not in this repo). + +## Verdict: READY TO SHIP (software checkpoint) + +No Critical or High findings. The HTTP parser, login/session gate, bus semantics, and the +crypto (HMAC-SHA256 / PBKDF2 / SHA-256 against RFC 4231 / RFC 7914 vectors) were verified +correct; the session gate cannot be bypassed. Every Medium finding has been fixed and +re-verified. Remaining items are Low / maintainability and are listed as deferred. + +External tooling: `cargo clippy --all-targets -- -D warnings` clean; 206 lib tests + all +integration tests pass; no emojis. + +## Fixed in this pass + +Security +- `/api/files` and `/api/file` were reachable with a session but no token, contradicting + the module docs and the Security page (arbitrary root-readable file exfiltration). Now + token-gated via `authorised()`, matching the advertised control. (web.rs) +- Response/header-splitting: `__section`/`__tab` from the settings form were interpolated + into the `Location:` header; `%0d%0a` decoded to CRLF. Now constrained to safe slugs + (`safe_slug`) before the redirect. (web.rs) +- RNG degradation: an unreadable `/dev/urandom` substituted the published constant + `"dev-csrf-token"` and second-granular, guessable session ids. Now a single token source + (`auth::rand_hex`) that warns loudly and falls back to a per-call, non-constant mix; the + CSRF generator delegates to it. (auth.rs, web.rs) +- The UI token was compared with `==` (timing oracle). Now `auth::ct_eq` (constant time). + (web.rs) +- `auth.json` (password hash) was written umask-default (world-readable). Now created 0600 + with the parent dir 0700. (auth.rs) +- Unbounded thread-per-connection + no absolute read deadline (flood DoS on the open :80). + Now a 64-connection cap (503 beyond it) and a 10 s head-read deadline, on top of the + per-read timeout. (web.rs) + +Reliability / correctness +- Settings persistence swallowed its write error and reported success with a misleading + comment. Now the error propagates (surfaced as the form's rejection) and the write is + atomic (temp + rename). Deck save is atomic too. (dashboard.rs, service.rs) +- `Auth::login` returned a cookie even if the session insert failed (redirect loop). Now + returns `None` on a poisoned lock. (auth.rs) +- `TuningLoop::set_target` carried the PID integral across modes whose error is in + different units (watts vs millidegrees vs TH/s), injecting a stale push on a mode switch. + Now the accumulator resets on a target change while the operating point is kept. (tuning.rs) +- Editable-deck JS: new-block ids collided after remove-then-add (duplicate ids, both + deleted on remove); the default new-block source `power_w` wasn't in the live-value map + (rendered n/a); drag-drop placement was asymmetric; save didn't re-render the normalized + doc. All fixed. (console.rs) +- Drivers page showed `"temperature"` with JSON quotes for the stopped reason. Now the bare + string. (web.rs) + +Maintainability +- `percent_decode` / form-field parsing existed in three divergent copies; consolidated into + one `form` module used by web, service and dashboard. The CSPRNG-to-hex helper is now one + function (`auth::rand_hex`). +- Added a test asserting the published state topics match the registry contract (the + "single source of truth" claim for topics was previously unenforced). + +## Deferred (reported, not blocking) + +- `ui.rs` is now largely dead: only `validate_deck` / `default_deck` (+ two consts) are used + (by `service.rs`); the legacy console (`page`, `dashboard_page`, `sidebar`, `NAV`, the CSS/JS + consts, `icon`/`group_icon_svg` which `Box::leak`) has no callers. Recommend moving the two + deck helpers to a `deck` module and deleting the rest. (~34 KB) +- `control::target_label` vs `app::target_label` are two implementations of the same mapping; + recommend one canonical (e.g. in `tuning`). +- `DECK_CSS` / `DECK_JS` / `TERMINAL_JS` are large inline strings; recommend moving to + `assets/*.js|css`, `include_str!`, and serving under `/assets` like the stylesheets, so they + can be linted. +- `web.rs` still owns host-fact gatherers (`system_rows`, ...) that `console.rs` consumes; + recommend a `hostfacts` module both depend on. +- `route()` is long; the `/api/*` arm could be an `api_route()`. +- `Dashboard::page()` is now test-only (console renders pages); remove or mark reference-only. +- serve_sim's control loop spins silently if the in-process HAL thread dies; recommend + surfacing the fault and dropping `running` (the real-hardware `boot_hal` loop already exits + on a HAL write error, so this is dev-path only). +- `make-zynq-afw.sh` usage comment omits `--sdk-dir` (doc drift). +- No change-password route exists though the login page tells the operator to change + admin/admin; wire one or soften the text. + +## Accepted-by-design posture (stated, not defects) + +The box is SSH-guarded and the console is defense-in-depth on a shared network: +- No TLS: the console is HTTP on `0.0.0.0:80`, so a passive sniffer can capture the password + and session cookie. This is the dominant residual risk and should be made explicit to the + operator. A TLS front (or binding the console to a management interface / WireGuard) is the + real mitigation. +- Factory `admin`/`admin` with nothing forcing a change; the login page prints it. +- `/api/terminal` is a gated (session + token) root `/bin/sh` - an accepted diagnostic on an + already-root-reachable box. Note the shipped terminal UI does not send the token, so it is + fail-closed/unusable until a token is supplied. +- The web process runs as root (binds 80); consider a post-bind privilege drop. +- `/api/hardware|summary|control` are intentionally open (interface of record, mirror of the + cgminer socket). +- PBKDF2 at 50k iterations - low by modern standards, accepted behind SSH; matters only if the + hash leaks (now 0600). +- `make-zynq-afw.sh` always passes `--allow-unsigned` (bench-only helper; do not reuse on a + release path). + +## Verification after fixes + +Live `--serve-sim`: unauthenticated GET / serves the login page; admin/admin issues a session +and the console renders; `/api/files` returns 403 without a token; a CRLF-injected `__section` +is neutralized (303, no header split); the editable deck saves and reloads. clippy -D warnings +clean; 206 lib tests + integration pass. diff --git a/src/auth.rs b/src/auth.rs index f96b0e7..4ccf5c5 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -15,9 +15,11 @@ use crate::pow::sha256; use serde_json::{json, Value}; use std::collections::HashMap; -use std::fs; -use std::io::Read; +use std::fs::{self, OpenOptions}; +use std::io::{Read, Write}; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -33,19 +35,31 @@ fn now_unix() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) } -/// 16 random bytes as hex, from the OS CSPRNG (fixed fallback only if unreadable). -fn rand_hex() -> String { +/// 16 bytes (32 hex) from the OS CSPRNG. The single random-token source for the +/// console (CSRF token and session ids). If `/dev/urandom` is unreadable it +/// fails LOUD and still avoids a fixed/guessable value: a per-call mix (nanos, +/// pid, a process counter, a stack address) hashed through SHA-256, distinct on +/// every call. Not a CSPRNG, but never the published constant it replaced. +pub(crate) fn rand_hex() -> String { if let Ok(mut f) = fs::File::open("/dev/urandom") { let mut b = [0_u8; 16]; if f.read_exact(&mut b).is_ok() { - let mut s = String::with_capacity(32); - for byte in b { - s.push_str(&format!("{byte:02x}")); - } - return s; + return hex(&b); } } - format!("fallback{}", now_unix()) + static CTR: AtomicU64 = AtomicU64::new(0); + eprintln!("alkane auth: WARNING /dev/urandom unreadable; session/token entropy is degraded"); + let n = CTR.fetch_add(1, Ordering::Relaxed); + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos() as u64) + .unwrap_or(0); + let stack = &n as *const _ as u64; + let mix = nanos + ^ (std::process::id() as u64).rotate_left(17) + ^ n.rotate_left(33) + ^ stack.rotate_left(49); + hex(&sha256(&mix.to_le_bytes())[..16]) } fn hex(bytes: &[u8]) -> String { @@ -103,7 +117,7 @@ fn pbkdf2_sha256(password: &[u8], salt: &[u8], iters: u32) -> [u8; 32] { } /// Constant-time comparison of two byte slices. -fn ct_eq(a: &[u8], b: &[u8]) -> bool { +pub(crate) fn ct_eq(a: &[u8], b: &[u8]) -> bool { if a.len() != b.len() { return false; } @@ -201,10 +215,15 @@ impl Auth { return None; } let wsid = rand_hex() + &rand_hex(); - if let Ok(mut s) = self.sessions.lock() { - s.insert(wsid.clone(), now_unix() + SESSION_TTL.as_secs()); + // Only hand back a cookie if the session was actually recorded; a + // poisoned lock must not mint a token that `valid` will always reject. + match self.sessions.lock() { + Ok(mut s) => { + s.insert(wsid.clone(), now_unix() + SESSION_TTL.as_secs()); + Some(wsid) + } + Err(_) => None, } - Some(wsid) } /// True when `wsid` names a live, unexpired session. @@ -237,10 +256,19 @@ 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()); 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) { + Ok(mut file) => { + let _ = file.write_all(text.as_bytes()); + } + Err(error) => eprintln!("alkane auth: cannot write {}: {error}", path.display()), } - let _ = fs::write(path, serde_json::to_string_pretty(&account.to_json()).unwrap_or_default()); } #[cfg(test)] diff --git a/src/console.rs b/src/console.rs index 34a41b6..ab97ab5 100644 --- a/src/console.rs +++ b/src/console.rs @@ -206,7 +206,7 @@ c.addEventListener('dragend',function(){c.classList.remove('drag')});\ c.addEventListener('dragover',function(e){if(edit)e.preventDefault()});\ c.addEventListener('drop',function(e){e.preventDefault();if(!drag||drag===b.id)return;\ var f=doc.blocks.findIndex(function(x){return x.id===drag}),t=doc.blocks.findIndex(function(x){return x.id===b.id});\ -if(f<0||t<0)return;var m=doc.blocks.splice(f,1)[0];doc.blocks.splice(t,0,m);render();msg('unsaved changes')});\ +if(f<0||t<0)return;var m=doc.blocks.splice(f,1)[0];doc.blocks.splice(f=32){msg('32 block limit');return}doc.blocks.push({id:'block'+(doc.blocks.length+1),kind:'metric',span:1,title:'New block',source:'power_w',unit:'W'});render();msg('unsaved changes')};\ -$('akd-save').onclick=function(){fetch('/api/dashboard?deck='+DECK,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(doc)}).then(function(r){return r.ok?r.json().then(function(d){doc=d;msg('saved')}):r.text().then(msg)})};\ +$('akd-add').onclick=function(){if(doc.blocks.length>=32){msg('32 block limit');return}var n=1;doc.blocks.forEach(function(b){var x=parseInt(String(b.id).replace(/[^0-9]/g,''),10)||0;if(x>=n)n=x+1});doc.blocks.push({id:'block'+n,kind:'metric',span:1,title:'New block',source:'frequency',unit:'MHz'});render();msg('unsaved changes')};\ +$('akd-save').onclick=function(){fetch('/api/dashboard?deck='+DECK,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(doc)}).then(function(r){return r.ok?r.json().then(function(d){doc=d;render();msg('saved')}):r.text().then(msg)})};\ $('akd-reset').onclick=function(){fetch('/api/dashboard?deck='+DECK+'&reset=1',{method:'PUT',headers:{'Content-Type':'application/json'},body:'{}'}).then(function(r){return r.json()}).then(function(d){doc=d;render();fill();msg('template restored')})};\ fetch('/api/dashboard?deck='+DECK).then(function(r){return r.json()}).then(function(d){doc=d;render();fill();setInterval(fill,5000)});\ })();"; diff --git a/src/dashboard.rs b/src/dashboard.rs index 0870db1..8c0b861 100644 --- a/src/dashboard.rs +++ b/src/dashboard.rs @@ -191,12 +191,20 @@ impl Dashboard { .map(|(key, value)| (key.clone(), value.clone())) .collect(); 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 { + let mut failures = BTreeMap::new(); + failures.insert(String::new(), message); + failures + }; if let Some(parent) = self.path.parent() { - let _ = fs::create_dir_all(parent); + fs::create_dir_all(parent) + .map_err(|e| fail(format!("cannot create {}: {e}", parent.display())))?; } - // Persist only after validation passed; a failed write leaves the rows - // changed in memory but never on disk, which the API reports. - let _ = fs::write(&self.path, text); + let tmp = self.path.with_extension("json.tmp"); + fs::write(&tmp, &text).map_err(|e| fail(format!("cannot write settings: {e}")))?; + fs::rename(&tmp, &self.path).map_err(|e| fail(format!("cannot save settings: {e}")))?; Ok(()) } @@ -208,8 +216,8 @@ impl Dashboard { continue; } let (raw_key, raw_value) = pair.split_once('=').unwrap_or((pair, "")); - let key = percent_decode(raw_key); - let raw = percent_decode(raw_value); + let key = crate::form::percent_decode(raw_key); + let raw = crate::form::percent_decode(raw_value); let setting = match effective.setting(&key) { Some(setting) => setting, None => continue, @@ -224,39 +232,6 @@ impl Dashboard { } } -fn percent_decode(text: &str) -> String { - let bytes = text.as_bytes(); - let mut out = Vec::with_capacity(bytes.len()); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'+' => { - out.push(b' '); - index += 1; - } - b'%' if index + 2 < bytes.len() => { - let high = (bytes[index + 1] as char).to_digit(16); - let low = (bytes[index + 2] as char).to_digit(16); - match (high, low) { - (Some(high), Some(low)) => { - out.push((high * 16 + low) as u8); - index += 3; - } - _ => { - out.push(bytes[index]); - index += 1; - } - } - } - byte => { - out.push(byte); - index += 1; - } - } - } - String::from_utf8_lossy(&out).into_owned() -} - fn coerce(kind: &str, raw: &str) -> Value { match kind { "int" | "int_set" => raw @@ -362,6 +337,6 @@ mod tests { #[test] fn form_values_are_percent_decoded() { - assert_eq!(percent_decode("a+b%2Fc"), "a b/c"); + assert_eq!(crate::form::percent_decode("a+b%2Fc"), "a b/c"); } } diff --git a/src/form.rs b/src/form.rs new file mode 100644 index 0000000..5be0f4a --- /dev/null +++ b/src/form.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT +//! Shared `application/x-www-form-urlencoded` / query decoding for the HTTP edge. +//! +//! One implementation, used by the web server, the miner service and the +//! dashboard, so a fix or a bug cannot diverge between copies. + +/// Percent-decode a form or query token (`%XX` escapes and `+` as space). +pub fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'%' if i + 2 < bytes.len() => { + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""); + match u8::from_str_radix(hex, 16) { + Ok(byte) => { + out.push(byte); + i += 3; + } + Err(_) => { + out.push(bytes[i]); + i += 1; + } + } + } + b'+' => { + out.push(b' '); + i += 1; + } + byte => { + out.push(byte); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// Read one field from a urlencoded body by key (first match), percent-decoded. +pub fn field(body: &str, key: &str) -> Option { + body.split('&').find_map(|pair| { + let (k, v) = pair.split_once('=')?; + (percent_decode(k) == key).then(|| percent_decode(v)) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decodes_escapes_and_plus() { + assert_eq!(percent_decode("a+b%2Fc"), "a b/c"); + assert_eq!(percent_decode("%0d%0a"), "\r\n"); + // A truncated trailing escape is passed through, not dropped. + assert_eq!(percent_decode("x%2"), "x%2"); + } + + #[test] + fn field_reads_first_match() { + assert_eq!(field("a=1&b=two&a=3", "b").as_deref(), Some("two")); + assert_eq!(field("a=1", "missing"), None); + assert_eq!(field("csrf=tok&user=admin", "csrf").as_deref(), Some("tok")); + } +} diff --git a/src/lib.rs b/src/lib.rs index 96486e4..4a0f9a1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ pub mod bm1362; pub mod bus; pub mod console; pub mod control; +pub mod form; pub mod registry; pub mod service; pub mod bm1366; diff --git a/src/service.rs b/src/service.rs index d2e4641..2bbc9b0 100644 --- a/src/service.rs +++ b/src/service.rs @@ -61,53 +61,15 @@ fn save_deck(deck: &str, doc: &Value) -> Result<(), String> { 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())?; - fs::write(&path, text).map_err(|e| format!("cannot write {}: {e}", path.display())) -} - -/// Read one field from an `application/x-www-form-urlencoded` body. -fn form_field(body: &str, key: &str) -> Option { - body.split('&').find_map(|pair| { - let (k, v) = pair.split_once('=')?; - (percent_decode(k) == key).then(|| percent_decode(v)) - }) -} - -fn percent_decode(text: &str) -> String { - let bytes = text.as_bytes(); - let mut out = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - match bytes[i] { - b'+' => { - out.push(b' '); - i += 1; - } - b'%' if i + 2 < bytes.len() => { - let hi = (bytes[i + 1] as char).to_digit(16); - let lo = (bytes[i + 2] as char).to_digit(16); - match (hi, lo) { - (Some(hi), Some(lo)) => { - out.push((hi * 16 + lo) as u8); - i += 3; - } - _ => { - out.push(bytes[i]); - i += 1; - } - } - } - b => { - out.push(b); - i += 1; - } - } - } - String::from_utf8_lossy(&out).into_owned() + // Atomic replace: a concurrent read never sees a half-written deck. + let tmp = path.with_extension("json.tmp"); + fs::write(&tmp, text).map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; + fs::rename(&tmp, &path).map_err(|e| format!("cannot replace {}: {e}", path.display())) } /// Translate a settings form's tuning fields into the live control target. fn apply_tuning(body: &str, control: &Control) { - let Some(mode) = form_field(body, "tuning.mode") else { + let Some(mode) = crate::form::field(body, "tuning.mode") else { return; }; let (mode, value_field) = match mode.as_str() { @@ -117,7 +79,7 @@ fn apply_tuning(body: &str, control: &Control) { "max-fan" => ("fan", "tuning.max_fan_pwm"), _ => return, }; - if let Some(value) = form_field(body, value_field).and_then(|v| v.trim().parse::().ok()) { + if let Some(value) = crate::form::field(body, value_field).and_then(|v| v.trim().parse::().ok()) { let _ = control.set_mode_value(mode, value); } } @@ -266,6 +228,22 @@ mod tests { assert_eq!(registered, registry::contract_verbs()); } + #[test] + fn published_state_topics_match_the_contract() { + let bus = Bus::new(); + publish(&bus, &MiningStatus::new(), &Control::default()); + let mut published = bus.state_topics(); + published.sort(); + let mut declared: Vec = registry::contract()["state"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap().to_string()) + .collect(); + declared.sort(); + assert_eq!(published, declared, "published state topics must match the contract"); + } + #[test] fn control_verbs_drive_the_shared_control() { let bus = Bus::new(); diff --git a/src/tuning.rs b/src/tuning.rs index f7419c9..7c4b998 100644 --- a/src/tuning.rs +++ b/src/tuning.rs @@ -79,6 +79,14 @@ impl Pid { self.output = value.clamp(self.config.out_min, self.config.out_max); } + /// Clear the integral and derivative history, keeping the current output. + /// Used on a target switch so error accumulated in one unit (watts) is not + /// injected into the next target's loop (millidegrees, TH/s). + pub fn reset_accumulator(&mut self) { + self.integral = 0.0; + self.last_measurement = None; + } + /// Advance one control period and return the new output. pub fn update(&mut self, setpoint: f32, measurement: f32, dt_s: f32) -> f32 { if !dt_s.is_finite() || dt_s <= 0.0 { @@ -173,10 +181,15 @@ impl TuningLoop { self.target } - /// Switch the operator target in place, keeping the PID state so the - /// operating point carries over instead of jumping back to the floor. The - /// thermal guard and envelope bounds are unchanged. + /// Switch the operator target in place, keeping the operating point (the PID + /// output) so it carries over instead of jumping back to the floor, but + /// clearing the error accumulator: the old target's integral is in the old + /// target's units and must not drive the new loop. The thermal guard and + /// envelope bounds are unchanged. pub fn set_target(&mut self, target: TuningTarget) { + if target != self.target { + self.pid.reset_accumulator(); + } self.target = target; } diff --git a/src/web.rs b/src/web.rs index 5408563..a6f6b90 100644 --- a/src/web.rs +++ b/src/web.rs @@ -14,9 +14,10 @@ //! silently use them. Browser forms that change the machine carry a per-process //! CSRF token checked here, at the HTTP edge. -use crate::auth::Auth; +use crate::auth::{self, Auth}; use crate::bus::Bus; use crate::console; +use crate::form; use crate::registry::{topics, verbs}; use serde_json::{json, Value}; use std::collections::BTreeMap; @@ -25,12 +26,20 @@ use std::io::{self, Read, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::path::Path; use std::process::Command; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, Instant}; const MAX_HEAD: usize = 8192; const MAX_BODY: usize = 64 * 1024; const CLIENT_TIMEOUT: Duration = Duration::from_millis(2000); +/// Absolute wall-clock budget to read a whole request head, independent of the +/// per-read timeout, so a slow drip cannot pin a thread indefinitely. +const HEAD_DEADLINE: Duration = Duration::from_secs(10); +/// Cap on concurrent connections: one thread is spawned per connection, so this +/// bounds thread/memory use against a flood on the open port. +const MAX_CONNECTIONS: usize = 64; +static LIVE_CONNECTIONS: AtomicUsize = AtomicUsize::new(0); const TOKEN_FILE: &str = "/var/lib/alkane/ui-token"; const LOG_FILE: &str = "/var/log/messages"; @@ -53,21 +62,12 @@ impl WebContext { } } -/// 128 bits of hex from the OS CSPRNG, or a fixed dev token if it cannot be read. -/// Not a password (SSH guards the box); it stops a foreign page from POSTing a -/// change through the operator's browser on a shared network. +/// 128 bits of hex from the OS CSPRNG (the shared token source, which fails loud +/// and non-constant if `/dev/urandom` is unreadable). Not a password (SSH guards +/// the box); it stops a foreign page from POSTing a change through the operator's +/// browser on a shared network. pub fn fresh_csrf() -> String { - if let Ok(mut file) = fs::File::open("/dev/urandom") { - let mut bytes = [0_u8; 16]; - if file.read_exact(&mut bytes).is_ok() { - let mut out = String::with_capacity(32); - for byte in bytes { - out.push_str(&format!("{byte:02x}")); - } - return out; - } - } - "dev-csrf-token".to_string() + auth::rand_hex() } /// Bind and serve until the listener fails. @@ -79,10 +79,19 @@ pub fn serve(bind: SocketAddr, ctx: Arc) -> io::Result<()> { /// Serve on an already-bound listener. pub fn serve_listener(listener: TcpListener, ctx: Arc) -> io::Result<()> { for stream in listener.incoming() { - let Ok(stream) = stream else { continue }; + let Ok(mut stream) = stream else { continue }; + if LIVE_CONNECTIONS.load(Ordering::Acquire) >= MAX_CONNECTIONS { + // Refuse quickly rather than spawn an unbounded thread. + let _ = stream.write_all( + b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ); + continue; + } + LIVE_CONNECTIONS.fetch_add(1, Ordering::AcqRel); let ctx = Arc::clone(&ctx); std::thread::spawn(move || { let _ = handle(stream, &ctx); + LIVE_CONNECTIONS.fetch_sub(1, Ordering::AcqRel); }); } Ok(()) @@ -101,7 +110,7 @@ impl Request { self.query.split('&').find_map(|pair| { let (k, v) = pair.split_once('=')?; if k == key { - Some(percent_decode(v)) + Some(form::percent_decode(v)) } else { None } @@ -113,38 +122,6 @@ impl Request { } } -fn percent_decode(text: &str) -> String { - let bytes = text.as_bytes(); - let mut out = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - match bytes[i] { - b'%' if i + 2 < bytes.len() => { - let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""); - match u8::from_str_radix(hex, 16) { - Ok(byte) => { - out.push(byte); - i += 3; - } - Err(_) => { - out.push(bytes[i]); - i += 1; - } - } - } - b'+' => { - out.push(b' '); - i += 1; - } - byte => { - out.push(byte); - i += 1; - } - } - } - String::from_utf8_lossy(&out).into_owned() -} - /// Handle one HTTP request. pub fn handle(mut stream: TcpStream, ctx: &WebContext) -> io::Result<()> { stream.set_read_timeout(Some(CLIENT_TIMEOUT))?; @@ -152,7 +129,11 @@ pub fn handle(mut stream: TcpStream, ctx: &WebContext) -> io::Result<()> { let mut raw = Vec::new(); let mut chunk = [0_u8; 1024]; let mut head_end = None; + let deadline = Instant::now() + HEAD_DEADLINE; while head_end.is_none() { + if Instant::now() > deadline { + return respond(&mut stream, 408, "text/plain", b"request timeout"); + } let count = stream.read(&mut chunk)?; if count == 0 { break; @@ -318,10 +299,16 @@ fn route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Res ) } ("GET", "/api/files") => { + if !authorised(request) { + return respond(stream, 403, "text/plain", b"file access requires a token"); + } let path = request.param_or("path", "/"); json_response(stream, &files_document(&path)) } ("GET", "/api/file") => { + if !authorised(request) { + return respond(stream, 403, "text/plain", b"file access requires a token"); + } let path = request.param_or("path", ""); match read_text(Path::new(&path)) { Some(text) => respond(stream, 200, "text/plain; charset=utf-8", text.as_bytes()), @@ -387,17 +374,9 @@ fn render_page( respond(stream, 200, "text/html; charset=utf-8", html.as_bytes()).map(|_| true) } -/// Read a field from an `application/x-www-form-urlencoded` body. -fn form_field(body: &str, key: &str) -> Option { - body.split('&').find_map(|pair| { - let (k, v) = pair.split_once('=')?; - (percent_decode(k) == key).then(|| percent_decode(v)) - }) -} - /// Every mutating browser form must echo the per-process token. fn csrf_ok(ctx: &WebContext, request: &Request) -> bool { - form_field(&request.body, "csrf").as_deref() == Some(ctx.csrf.as_str()) + form::field(&request.body, "csrf").as_deref() == Some(ctx.csrf.as_str()) } /// Start/Stop: a bus command, then back to the control page. @@ -417,13 +396,28 @@ fn control_switch( } } +/// A nav slug safe to interpolate into a redirect path: lowercase letters, +/// digits and dashes only. Anything else (including CRLF) falls back. +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 == '-'); + if ok { + value.to_string() + } else { + fallback.to_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"); } - let section = form_field(&request.body, "__section").unwrap_or_else(|| "settings".into()); - let tab = form_field(&request.body, "__tab").unwrap_or_else(|| "tuning".into()); + // 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})) { Ok(_) => redirect(stream, &format!("/{section}/{tab}")), Err(error) => { @@ -462,8 +456,8 @@ fn auth_local(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io if !csrf_ok(ctx, request) { return login(stream, ctx, Some("Your sign-in form expired. Try again.")); } - let user = form_field(&request.body, "user").unwrap_or_default(); - let password = form_field(&request.body, "password").unwrap_or_default(); + let user = form::field(&request.body, "user").unwrap_or_default(); + let password = form::field(&request.body, "password").unwrap_or_default(); match ctx.auth.login(&user, &password) { Some(wsid) => redirect_cookie( stream, @@ -627,11 +621,7 @@ pub(crate) fn driver_rows(hw: &Value) -> Vec<(&'static str, String)> { ), ( "stopped", - if hw["stopped"].is_null() { - "no".into() - } else { - hw["stopped"].to_string() - }, + hw["stopped"].as_str().unwrap_or("no").to_string(), ), ] } @@ -810,7 +800,7 @@ pub(crate) fn ui_token() -> Option { fn authorised(request: &Request) -> bool { match (ui_token(), request.param("token")) { - (Some(expected), Some(given)) => given == expected, + (Some(expected), Some(given)) => auth::ct_eq(given.as_bytes(), expected.as_bytes()), _ => false, } } @@ -822,6 +812,7 @@ fn respond(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) - 400 => "Bad Request", 403 => "Forbidden", 404 => "Not Found", + 408 => "Request Timeout", 413 => "Payload Too Large", 422 => "Unprocessable Entity", 431 => "Request Header Fields Too Large",