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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk
This commit is contained in:
+43
-15
@@ -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)]
|
||||
|
||||
+3
-3
@@ -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<t?t-1:t,0,m);render();msg('unsaved changes')});\
|
||||
var h=document.createElement('h3');h.textContent=b.title||b.id;\
|
||||
if(edit){var x=document.createElement('span');x.className='akd-rm';x.textContent='x';x.title='remove';\
|
||||
x.onclick=function(){doc.blocks=doc.blocks.filter(function(y){return y.id!==b.id});render();msg('unsaved changes')};h.appendChild(x)}\
|
||||
@@ -231,8 +231,8 @@ fetch('/api/hardware').then(function(r){return r.json()}).then(function(h){hw=h;
|
||||
fetch('/api/summary').then(function(r){return r.json()}).then(function(x){sm=x;paint()}).catch(function(){})}\
|
||||
function setEdit(on){edit=on;['akd-add','akd-save','akd-reset'].forEach(function(i){$(i).hidden=!on});$('akd-edit').textContent=on?'Done':'Edit';render()}\
|
||||
$('akd-edit').onclick=function(){setEdit(!edit)};\
|
||||
$('akd-add').onclick=function(){if(doc.blocks.length>=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)});\
|
||||
})();</script>";
|
||||
|
||||
+15
-40
@@ -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<String, String> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
+66
@@ -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<String> {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
+22
-44
@@ -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<String> {
|
||||
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::<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);
|
||||
}
|
||||
}
|
||||
@@ -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<String> = 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();
|
||||
|
||||
+16
-3
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+60
-69
@@ -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<WebContext>) -> io::Result<()> {
|
||||
/// Serve on an already-bound listener.
|
||||
pub fn serve_listener(listener: TcpListener, ctx: Arc<WebContext>) -> 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<String> {
|
||||
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<String> {
|
||||
|
||||
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",
|
||||
|
||||
Reference in New Issue
Block a user