os: add console login (local account + session cookie), wardenOS-style
Gate the web console behind a sign-in, modeled on wardenOS's local auth (spec d05): a local account whose password is stored only as a salted KDF hash, and a `wsid` session cookie issued on login. wardenOS uses Argon2 from warden-verifier; alkane-os is dependency-light, so auth.rs implements PBKDF2-HMAC-SHA256 on the crate's own pure-Rust SHA-256 (pow::sha256) - a standard password KDF with no new dependency (RFC 4231 / PBKDF2 test vectors included). Factory account is admin/admin, persisted to /etc/alkane/auth.json when writable. OIDC and FLARE bundle users are out of scope (no portal here). - auth.rs: Account (salt+iters+hash), Auth (account + live sessions), login -> wsid, valid, logout. Iterations tuned for the pure-Rust hash so a login stays sub-second on a slow board while staying strong as defense-in-depth behind SSH. - web.rs: WebContext gains the Auth; the request parser reads the wsid cookie; route() gates everything behind a live session EXCEPT the read-only miner-state JSON (/api/hardware|summary|control), which stays open as the interface of record (also on the cgminer socket). /login, POST /auth/local (CSRF-checked, sets the HttpOnly SameSite=Lax cookie) and POST /auth/logout added. - console.rs: login_page - a standalone flare-ui card. Verified on --serve-sim: unauthenticated GET / serves the login page, admin/admin issues a session and the console renders, host/mutation endpoints 401 without a session, miner-state reads stay open. 203 lib tests pass, full suite green, clippy -D warnings clean, no emojis. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BdKQBPjAXpCwmigUov5eQk
This commit is contained in:
+301
@@ -0,0 +1,301 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Web console authentication: a local account and session cookies.
|
||||
//!
|
||||
//! Modeled on wardenOS's web auth (spec d05): a local account whose password is
|
||||
//! stored only as a salted KDF hash, and a `wsid` session cookie issued on
|
||||
//! login. wardenOS uses Argon2 from its `warden-verifier` crate; alkane-os is
|
||||
//! dependency-light, so this uses PBKDF2-HMAC-SHA256 built on the crate's own
|
||||
//! pure-Rust SHA-256 (`pow::sha256`) - a standard password KDF with no new
|
||||
//! dependency. OIDC and FLARE bundle users are out of scope (no portal here).
|
||||
//!
|
||||
//! The box is guarded by SSH; this login is defense-in-depth for the console on
|
||||
//! a shared network, and the factory account is `admin` / `admin`, which the
|
||||
//! operator is expected to change.
|
||||
|
||||
use crate::pow::sha256;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// PBKDF2 iterations. A compromise for the crate's pure-Rust SHA-256: strong
|
||||
/// enough as defense-in-depth behind SSH, while a single login stays well under
|
||||
/// a second even on a slow control board.
|
||||
const PBKDF2_ITERS: u32 = 50_000;
|
||||
/// How long a session cookie stays valid.
|
||||
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)
|
||||
}
|
||||
|
||||
/// 16 random bytes as hex, from the OS CSPRNG (fixed fallback only if unreadable).
|
||||
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;
|
||||
}
|
||||
}
|
||||
format!("fallback{}", now_unix())
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
s.push_str(&format!("{b:02x}"));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn unhex(text: &str) -> Vec<u8> {
|
||||
(0..text.len() / 2)
|
||||
.filter_map(|i| u8::from_str_radix(text.get(i * 2..i * 2 + 2)?, 16).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// HMAC-SHA256 over the crate's SHA-256.
|
||||
fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
|
||||
const BLOCK: usize = 64;
|
||||
let mut k = [0_u8; BLOCK];
|
||||
if key.len() > BLOCK {
|
||||
k[..32].copy_from_slice(&sha256(key));
|
||||
} else {
|
||||
k[..key.len()].copy_from_slice(key);
|
||||
}
|
||||
let mut ipad = [0x36_u8; BLOCK];
|
||||
let mut opad = [0x5c_u8; BLOCK];
|
||||
for i in 0..BLOCK {
|
||||
ipad[i] ^= k[i];
|
||||
opad[i] ^= k[i];
|
||||
}
|
||||
let mut inner = Vec::with_capacity(BLOCK + msg.len());
|
||||
inner.extend_from_slice(&ipad);
|
||||
inner.extend_from_slice(msg);
|
||||
let ih = sha256(&inner);
|
||||
let mut outer = Vec::with_capacity(BLOCK + 32);
|
||||
outer.extend_from_slice(&opad);
|
||||
outer.extend_from_slice(&ih);
|
||||
sha256(&outer)
|
||||
}
|
||||
|
||||
/// PBKDF2-HMAC-SHA256 producing one 32-byte block (dkLen == hLen).
|
||||
fn pbkdf2_sha256(password: &[u8], salt: &[u8], iters: u32) -> [u8; 32] {
|
||||
let mut block1 = salt.to_vec();
|
||||
block1.extend_from_slice(&1_u32.to_be_bytes());
|
||||
let mut u = hmac_sha256(password, &block1);
|
||||
let mut t = u;
|
||||
for _ in 1..iters.max(1) {
|
||||
u = hmac_sha256(password, &u);
|
||||
for i in 0..32 {
|
||||
t[i] ^= u[i];
|
||||
}
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// Constant-time comparison of two byte slices.
|
||||
fn ct_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut diff = 0_u8;
|
||||
for i in 0..a.len() {
|
||||
diff |= a[i] ^ b[i];
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
/// The stored local account.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Account {
|
||||
user: String,
|
||||
salt: Vec<u8>,
|
||||
iters: u32,
|
||||
hash: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Account {
|
||||
fn factory() -> Self {
|
||||
Self::with_password("admin", "admin")
|
||||
}
|
||||
|
||||
fn with_password(user: &str, password: &str) -> Self {
|
||||
let salt = unhex(&rand_hex());
|
||||
let hash = pbkdf2_sha256(password.as_bytes(), &salt, PBKDF2_ITERS).to_vec();
|
||||
Self {
|
||||
user: user.to_string(),
|
||||
salt,
|
||||
iters: PBKDF2_ITERS,
|
||||
hash,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"user": self.user,
|
||||
"salt": hex(&self.salt),
|
||||
"iters": self.iters,
|
||||
"hash": hex(&self.hash),
|
||||
})
|
||||
}
|
||||
|
||||
fn from_json(v: &Value) -> Option<Self> {
|
||||
Some(Self {
|
||||
user: v.get("user")?.as_str()?.to_string(),
|
||||
salt: unhex(v.get("salt")?.as_str()?),
|
||||
iters: v.get("iters")?.as_u64()? as u32,
|
||||
hash: unhex(v.get("hash")?.as_str()?),
|
||||
})
|
||||
}
|
||||
|
||||
fn verify(&self, user: &str, password: &str) -> bool {
|
||||
let candidate = pbkdf2_sha256(password.as_bytes(), &self.salt, self.iters);
|
||||
// Compare the user name too, but not in constant time (it is not secret).
|
||||
user == self.user && ct_eq(&candidate, &self.hash)
|
||||
}
|
||||
}
|
||||
|
||||
/// The console auth state: one local account and the live sessions.
|
||||
pub struct Auth {
|
||||
account: Account,
|
||||
sessions: Mutex<HashMap<String, u64>>,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
/// Load the account from `AUTH_FILE`, creating the factory `admin`/`admin`
|
||||
/// account (persisted when the path is writable) on first run.
|
||||
pub fn load() -> Self {
|
||||
Self::load_from(Path::new(AUTH_FILE))
|
||||
}
|
||||
|
||||
pub fn load_from(path: &Path) -> Self {
|
||||
let account = fs::read_to_string(path)
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str::<Value>(&t).ok())
|
||||
.and_then(|v| Account::from_json(&v))
|
||||
.unwrap_or_else(|| {
|
||||
let account = Account::factory();
|
||||
persist(path, &account);
|
||||
account
|
||||
});
|
||||
Self {
|
||||
account,
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
path: path.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a login. On success return a fresh `wsid`.
|
||||
pub fn login(&self, user: &str, password: &str) -> Option<String> {
|
||||
if !self.account.verify(user, password) {
|
||||
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());
|
||||
}
|
||||
Some(wsid)
|
||||
}
|
||||
|
||||
/// True when `wsid` names a live, unexpired session.
|
||||
pub fn valid(&self, wsid: &str) -> bool {
|
||||
if wsid.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let now = now_unix();
|
||||
let mut sessions = match self.sessions.lock() {
|
||||
Ok(s) => s,
|
||||
Err(_) => return false,
|
||||
};
|
||||
sessions.retain(|_, &mut exp| exp > now);
|
||||
sessions.get(wsid).is_some_and(|&exp| exp > now)
|
||||
}
|
||||
|
||||
/// End a session.
|
||||
pub fn logout(&self, wsid: &str) {
|
||||
if let Ok(mut s) = self.sessions.lock() {
|
||||
s.remove(wsid);
|
||||
}
|
||||
}
|
||||
|
||||
/// The path the account is stored at (for diagnostics).
|
||||
pub fn store_path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
fn persist(path: &Path, account: &Account) {
|
||||
if let Some(parent) = path.parent() {
|
||||
if fs::create_dir_all(parent).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let _ = fs::write(path, serde_json::to_string_pretty(&account.to_json()).unwrap_or_default());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hmac_matches_rfc4231_case_2() {
|
||||
// RFC 4231 test case 2: key "Jefe", data "what do ya want for nothing?".
|
||||
let mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
|
||||
assert_eq!(
|
||||
hex(&mac),
|
||||
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pbkdf2_matches_a_known_vector() {
|
||||
// RFC 7914 / standard PBKDF2-HMAC-SHA256: P="passwd", S="salt", c=1.
|
||||
let dk = pbkdf2_sha256(b"passwd", b"salt", 1);
|
||||
assert_eq!(&hex(&dk)[..16], "55ac046e56e3089f");
|
||||
}
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let mut p = std::env::temp_dir();
|
||||
p.push(format!("alkane-auth-{name}-{}.json", std::process::id()));
|
||||
let _ = fs::remove_file(&p);
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factory_account_accepts_admin_admin_and_rejects_others() {
|
||||
let auth = Auth::load_from(&temp("factory"));
|
||||
assert!(auth.login("admin", "admin").is_some());
|
||||
assert!(auth.login("admin", "wrong").is_none());
|
||||
assert!(auth.login("root", "admin").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_is_valid_until_logout() {
|
||||
let auth = Auth::load_from(&temp("session"));
|
||||
let wsid = auth.login("admin", "admin").expect("login");
|
||||
assert!(auth.valid(&wsid));
|
||||
assert!(!auth.valid("not-a-session"));
|
||||
auth.logout(&wsid);
|
||||
assert!(!auth.valid(&wsid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_account_persists_and_reloads() {
|
||||
let path = temp("persist");
|
||||
let _ = Auth::load_from(&path);
|
||||
assert!(path.exists(), "the factory account should be written");
|
||||
let again = Auth::load_from(&path);
|
||||
assert!(again.login("admin", "admin").is_some());
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,53 @@ pub fn page(
|
||||
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,
|
||||
/// modeled on wardenOS's local login.
|
||||
pub fn login_page(csrf: &str, error: Option<&str>) -> Markup {
|
||||
html! {
|
||||
(maud::DOCTYPE)
|
||||
html lang="en" {
|
||||
head {
|
||||
meta charset="utf-8";
|
||||
meta name="viewport" content="width=device-width, initial-scale=1";
|
||||
title { "Alkane OS - Sign in" }
|
||||
link rel="stylesheet" href="/assets/tokens.css";
|
||||
link rel="stylesheet" href="/assets/components.css";
|
||||
link rel="stylesheet" href="/assets/theme.css";
|
||||
}
|
||||
body class="bf-shell" {
|
||||
main class="bf-main" {
|
||||
section class="bf-card" {
|
||||
h1 class="bf-text-title" { "Alkane OS" }
|
||||
@if let Some(message) = error {
|
||||
p class="bf-field-error bf-text-body" role="alert" { (message) }
|
||||
}
|
||||
form class="bf-form" method="post" action="/auth/local" {
|
||||
input type="hidden" name="csrf" value=(csrf);
|
||||
div class="bf-field" {
|
||||
label {
|
||||
span class="bf-field-label bf-text-label" { "User" }
|
||||
input class="bf-input" type="text" name="user" autocomplete="username";
|
||||
}
|
||||
}
|
||||
div class="bf-field" {
|
||||
label {
|
||||
span class="bf-field-label bf-text-label" { "Password" }
|
||||
input class="bf-input" type="password" name="password" autocomplete="current-password";
|
||||
}
|
||||
}
|
||||
div class="bf-actions" {
|
||||
button type="submit" class="bf-btn bf-btn-primary bf-text-button" { "Sign in" }
|
||||
}
|
||||
}
|
||||
p class="bf-text-body-sm" { "Factory login is admin / admin. Change it after first sign-in." }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tab_title(nav: &VisibleNav, section: &str, tab: &str) -> String {
|
||||
nav.sections
|
||||
.iter()
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! the pairing already mines. Hardware backends are supplied by SDK images.
|
||||
|
||||
pub mod app;
|
||||
pub mod auth;
|
||||
pub mod bm1362;
|
||||
pub mod bus;
|
||||
pub mod console;
|
||||
|
||||
+166
-23
@@ -14,6 +14,7 @@
|
||||
//! 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::bus::Bus;
|
||||
use crate::console;
|
||||
use crate::registry::{topics, verbs};
|
||||
@@ -33,11 +34,13 @@ const CLIENT_TIMEOUT: Duration = Duration::from_millis(2000);
|
||||
const TOKEN_FILE: &str = "/var/lib/alkane/ui-token";
|
||||
const LOG_FILE: &str = "/var/log/messages";
|
||||
|
||||
/// What the HTTP edge needs: the bus (its only way to touch the machine) and the
|
||||
/// per-process CSRF token for browser forms.
|
||||
/// What the HTTP edge needs: the bus (its only way to touch the machine), the
|
||||
/// per-process CSRF token for browser forms, and the console auth (local account
|
||||
/// plus live sessions).
|
||||
pub struct WebContext {
|
||||
pub bus: Arc<Bus>,
|
||||
pub csrf: String,
|
||||
pub auth: Arc<Auth>,
|
||||
}
|
||||
|
||||
impl WebContext {
|
||||
@@ -45,6 +48,7 @@ impl WebContext {
|
||||
Arc::new(Self {
|
||||
bus,
|
||||
csrf: fresh_csrf(),
|
||||
auth: Arc::new(Auth::load()),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -89,6 +93,7 @@ struct Request {
|
||||
path: String,
|
||||
query: String,
|
||||
body: String,
|
||||
wsid: Option<String>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
@@ -183,6 +188,16 @@ pub fn handle(mut stream: TcpStream, ctx: &WebContext) -> io::Result<()> {
|
||||
if length > MAX_BODY {
|
||||
return respond(&mut stream, 413, "text/plain", b"body too large");
|
||||
}
|
||||
let wsid = head.lines().find_map(|line| {
|
||||
let (name, value) = line.split_once(':')?;
|
||||
if !name.eq_ignore_ascii_case("cookie") {
|
||||
return None;
|
||||
}
|
||||
value.split(';').find_map(|pair| {
|
||||
let (k, v) = pair.split_once('=')?;
|
||||
(k.trim() == "wsid").then(|| v.trim().to_string())
|
||||
})
|
||||
});
|
||||
let mut body = raw[head_end..].to_vec();
|
||||
while body.len() < length {
|
||||
let count = stream.read(&mut chunk)?;
|
||||
@@ -196,11 +211,50 @@ pub fn handle(mut stream: TcpStream, ctx: &WebContext) -> io::Result<()> {
|
||||
path,
|
||||
query,
|
||||
body: String::from_utf8_lossy(&body).into_owned(),
|
||||
wsid,
|
||||
};
|
||||
route(&mut stream, ctx, &request)
|
||||
}
|
||||
|
||||
fn route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Result<()> {
|
||||
let method = request.method.as_str();
|
||||
let path = request.path.as_str();
|
||||
|
||||
// Stylesheets are public: the login page needs them before any session.
|
||||
if let Some(name) = path.strip_prefix("/assets/") {
|
||||
for (file, css) in crate::dashboard::Dashboard::stylesheets() {
|
||||
if name == file {
|
||||
return respond(stream, 200, "text/css; charset=utf-8", css.as_bytes());
|
||||
}
|
||||
}
|
||||
return respond(stream, 404, "text/plain", b"not found");
|
||||
}
|
||||
// Public auth endpoints.
|
||||
if method == "GET" && path == "/login" {
|
||||
return login(stream, ctx, None);
|
||||
}
|
||||
if method == "POST" && path == "/auth/local" {
|
||||
return auth_local(stream, ctx, request);
|
||||
}
|
||||
|
||||
// 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 authed = request.wsid.as_deref().is_some_and(|w| ctx.auth.valid(w));
|
||||
if !authed && !open_api {
|
||||
if method == "GET" && !path.starts_with("/api/") {
|
||||
return login(stream, ctx, None);
|
||||
}
|
||||
return respond(stream, 401, "text/plain", b"sign in at /login");
|
||||
}
|
||||
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");
|
||||
}
|
||||
|
||||
if dashboard_route(stream, ctx, request)? {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -283,14 +337,6 @@ fn route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Res
|
||||
/// routes keep working.
|
||||
fn dashboard_route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Result<bool> {
|
||||
let path = request.path.clone();
|
||||
if let Some(name) = path.strip_prefix("/assets/") {
|
||||
for (file, css) in crate::dashboard::Dashboard::stylesheets() {
|
||||
if name == file {
|
||||
return respond(stream, 200, "text/css; charset=utf-8", css.as_bytes()).map(|_| true);
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
if request.method == "POST" {
|
||||
return match path.as_str() {
|
||||
"/settings" => settings_submit(stream, ctx, request).map(|_| true),
|
||||
@@ -397,6 +443,37 @@ fn redirect(stream: &mut TcpStream, location: &str) -> io::Result<()> {
|
||||
stream.flush()
|
||||
}
|
||||
|
||||
fn redirect_cookie(stream: &mut TcpStream, location: &str, cookie: &str) -> io::Result<()> {
|
||||
let header = format!(
|
||||
"HTTP/1.1 303 See Other\r\nLocation: {location}\r\nSet-Cookie: {cookie}\r\nContent-Length: 0\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n"
|
||||
);
|
||||
stream.write_all(header.as_bytes())?;
|
||||
stream.flush()
|
||||
}
|
||||
|
||||
/// Render the sign-in page.
|
||||
fn login(stream: &mut TcpStream, ctx: &WebContext, error: Option<&str>) -> io::Result<()> {
|
||||
let html = console::login_page(&ctx.csrf, error).into_string();
|
||||
respond(stream, 200, "text/html; charset=utf-8", html.as_bytes())
|
||||
}
|
||||
|
||||
/// Verify a local login and, on success, issue the session cookie.
|
||||
fn auth_local(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Result<()> {
|
||||
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();
|
||||
match ctx.auth.login(&user, &password) {
|
||||
Some(wsid) => redirect_cookie(
|
||||
stream,
|
||||
"/",
|
||||
&format!("wsid={wsid}; HttpOnly; SameSite=Lax; Path=/"),
|
||||
),
|
||||
None => login(stream, ctx, Some("Wrong user name or password.")),
|
||||
}
|
||||
}
|
||||
|
||||
fn json_response(stream: &mut TcpStream, value: &Value) -> io::Result<()> {
|
||||
respond(stream, 200, "application/json", value.to_string().as_bytes())
|
||||
}
|
||||
@@ -763,32 +840,57 @@ fn respond(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::auth::Auth;
|
||||
use crate::control::Control;
|
||||
use crate::management::MiningStatus;
|
||||
use crate::service;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// A context whose bus has the miner service registered and state published
|
||||
/// once, with the test holding the `Control` so it can assert operator state.
|
||||
fn context() -> (Arc<WebContext>, Arc<Control>) {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn auth_temp() -> PathBuf {
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!("alkane-webauth-{}-{n}.json", std::process::id()))
|
||||
}
|
||||
|
||||
/// A context with the miner service registered, state published once, and a
|
||||
/// live session. Returns the `Control` (to assert operator state) and the wsid.
|
||||
fn context() -> (Arc<WebContext>, Arc<Control>, String) {
|
||||
let bus = Bus::new();
|
||||
let control = Arc::new(Control::default());
|
||||
let status = Arc::new(MiningStatus::new());
|
||||
service::register(&bus, Arc::clone(&status), Arc::clone(&control));
|
||||
service::publish(&bus, &status, &control);
|
||||
let auth = Arc::new(Auth::load_from(&auth_temp()));
|
||||
let wsid = auth.login("admin", "admin").expect("factory login");
|
||||
(
|
||||
Arc::new(WebContext {
|
||||
bus,
|
||||
csrf: "test-csrf".to_string(),
|
||||
auth,
|
||||
}),
|
||||
control,
|
||||
wsid,
|
||||
)
|
||||
}
|
||||
|
||||
fn client(request: &str) -> String {
|
||||
client_ctx(request, context().0)
|
||||
fn with_cookie(request: &str, wsid: &str) -> String {
|
||||
request.replacen("\r\n", &format!("\r\nCookie: wsid={wsid}\r\n"), 1)
|
||||
}
|
||||
|
||||
fn client_ctx(request: &str, ctx: Arc<WebContext>) -> String {
|
||||
/// Send an authenticated request against a fresh context.
|
||||
fn client(request: &str) -> String {
|
||||
let (ctx, _control, wsid) = context();
|
||||
send(&with_cookie(request, &wsid), ctx)
|
||||
}
|
||||
|
||||
/// Send a request with no session, against a fresh context.
|
||||
fn client_anon(request: &str) -> String {
|
||||
send(request, context().0)
|
||||
}
|
||||
|
||||
fn send(request: &str, ctx: Arc<WebContext>) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let worker = std::thread::spawn(move || {
|
||||
@@ -886,20 +988,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn start_requires_the_csrf_token() {
|
||||
let (ctx, control) = context();
|
||||
let reply = client_ctx(&post("/control/start", "csrf=wrong"), ctx);
|
||||
let (ctx, control, wsid) = context();
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_and_stop_with_a_good_token_switch_the_runtime() {
|
||||
let (ctx, control) = context();
|
||||
let reply = client_ctx(&post("/control/start", "csrf=test-csrf"), Arc::clone(&ctx));
|
||||
let (ctx, control, wsid) = context();
|
||||
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 = client_ctx(&post("/control/stop", "csrf=test-csrf"), 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");
|
||||
}
|
||||
@@ -907,9 +1009,9 @@ mod tests {
|
||||
#[test]
|
||||
fn a_tuning_form_switches_the_live_target() {
|
||||
use crate::tuning::TuningTarget;
|
||||
let (ctx, control) = context();
|
||||
let (ctx, control, wsid) = context();
|
||||
let body = "csrf=test-csrf&__section=settings&__tab=tuning&tuning.mode=ambient&tuning.ambient_margin_c=18";
|
||||
let reply = client_ctx(&post("/settings", body), ctx);
|
||||
let reply = send(&with_cookie(&post("/settings", body), &wsid), ctx);
|
||||
assert!(
|
||||
reply.starts_with("HTTP/1.1 303") || reply.starts_with("HTTP/1.1 422"),
|
||||
"{reply}"
|
||||
@@ -918,4 +1020,45 @@ mod tests {
|
||||
assert_eq!(control.target(), TuningTarget::AmbientC { margin_mc: 18_000 });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unauthenticated_get_serves_the_login_page() {
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gated_api_requires_a_session() {
|
||||
// Miner-state reads are open, but host reads need a session.
|
||||
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}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_credentials_are_rejected() {
|
||||
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"));
|
||||
assert!(reply.starts_with("HTTP/1.1 303"), "{reply}");
|
||||
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));
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user