//! The people who use the workspace's web page: their accounts, what each may //! do, how they log in, and the page's login sessions. //! //! * **Accounts** are made and changed by an admin from the CLI (`midas //! account add|list|role|reset|remove`). A new account, or one reset, gets a //! **setup link**, good for a day: its holder chooses a password, adds the //! one-time-code secret to an authenticator app (a QR code), proves it with a //! first code, and is shown ten **recovery codes**, once. //! * **Logging in** takes all three: name, password, and a code from the app //! (or a recovery code, which is used up). Passwords are kept as argon2id //! hashes; codes are TOTP (RFC 6238: SHA-1, 30 s, six digits, one step either //! side), and a code that worked once is refused after. Five failures in a //! row lock the account for a quarter of an hour; every login and failure is //! in the log. //! * **Roles**, each including the ones before it: `viewer` sees the page, //! `operator` changes the workspace (drain, release, deploy, decide), `steer` //! types into agent sessions — which is running code — and `admin` manages //! accounts. //! * **Sessions** are a random token in an HttpOnly cookie, kept here only as //! its SHA-256: twelve hours from the last use, a week at most. //! //! Machines and agents keep their caller keys (hub.rs): they cannot type a //! code. A request through the web proxy is only ever a person's, so the hub //! takes a session there and never a key. //! //! State in `accounts.json` beside the registry, under its own lock. use std::fs::File; use std::path::PathBuf; use anyhow::{bail, Context, Result}; use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}; use argon2::Argon2; use hmac::{Hmac, Mac}; use serde_json::{json, Map, Value}; use sha2::{Digest, Sha256}; use crate::events; use crate::registry::{self, now}; use crate::store; /// How long a setup link works. const SETUP_S: i64 = 86400; /// A login session lasts this long from its last use, and never longer than `SESSION_MAX_S`. const SESSION_IDLE_S: i64 = 12 * 3600; const SESSION_MAX_S: i64 = 7 * 86400; /// Failed logins in a row before the account is locked, and for how long. const FAILURES: i64 = 5; const LOCK_S: i64 = 15 * 60; const MIN_PASSWORD: usize = 12; const RECOVERY_CODES: usize = 10; const TOTP_STEP: i64 = 30; /// Who may do what, each role including the ones before it. pub const ROLES: &[&str] = &["viewer", "operator", "steer", "admin"]; /// A role's rank, for `at_least`. pub fn rank(role: &str) -> Option { ROLES.iter().position(|r| *r == role) } pub fn at_least(role: &str, needed: &str) -> bool { matches!((rank(role), rank(needed)), (Some(a), Some(b)) if a >= b) } // ── The file ───────────────────────────────────────────────────────────────── struct Store(store::Store); fn path() -> PathBuf { registry::root().join("accounts.json") } impl Store { fn open() -> Result { // Hashes and secrets: the hub's user only. let mut s = store::Store::open(path())?.private(); store::objects(&mut s.data, &["accounts", "sessions"]); Ok(Self(s)) } fn save(&self) -> Result<()> { self.0.save() } fn accounts(&mut self) -> &mut Map { self.0.data["accounts"].as_object_mut().expect("normalised in open") } fn sessions(&mut self) -> &mut Map { self.0.data["sessions"].as_object_mut().expect("normalised in open") } fn account(&mut self, name: &str) -> Result<&mut Value> { self.accounts().get_mut(name).with_context(|| format!("no account {name}")) } } // ── Small pieces ───────────────────────────────────────────────────────────── pub fn random(n: usize) -> Result> { let mut buf = vec![0u8; n]; std::io::Read::read_exact(&mut File::open("/dev/urandom")?, &mut buf)?; Ok(buf) } pub fn token() -> Result { Ok(data_encoding::HEXLOWER.encode(&random(32)?)) } pub fn sha256(s: &str) -> String { data_encoding::HEXLOWER.encode(&Sha256::digest(s.as_bytes())) } /// The code an authenticator shows for `secret` at time step `step` (RFC 4226/6238). pub fn hotp(secret: &[u8], step: u64, digits: u32) -> u32 { let mut mac = Hmac::::new_from_slice(secret).expect("HMAC takes a key of any length"); mac.update(&step.to_be_bytes()); let h = mac.finalize().into_bytes(); let off = (h[19] & 0x0f) as usize; let bin = u32::from_be_bytes([h[off] & 0x7f, h[off + 1], h[off + 2], h[off + 3]]); bin % 10u32.pow(digits) } /// The step a six-digit `code` is good for at `t`, if any: this step or one /// either side, for clocks a little apart. fn totp_step(secret_b32: &str, code: &str, t: i64) -> Option { let code: u32 = code.trim().replace(' ', "").parse().ok()?; let secret = data_encoding::BASE32_NOPAD.decode(secret_b32.as_bytes()).ok()?; let step = t / TOTP_STEP; (step - 1..=step + 1).find(|s| *s >= 0 && hotp(&secret, *s as u64, 6) == code) } fn hash_password(pw: &str) -> Result { let salt = SaltString::encode_b64(&random(16)?).map_err(|e| anyhow::anyhow!("salt: {e}"))?; Ok(Argon2::default().hash_password(pw.as_bytes(), &salt).map_err(|e| anyhow::anyhow!("hashing: {e}"))?.to_string()) } fn password_ok(pw: &str, phc: &str) -> bool { PasswordHash::new(phc).is_ok_and(|h| Argon2::default().verify_password(pw.as_bytes(), &h).is_ok()) } /// A hash to check against when the account does not exist, so the time a /// login takes does not say whether the name is known. fn decoy() -> &'static str { static DECOY: std::sync::OnceLock = std::sync::OnceLock::new(); DECOY.get_or_init(|| hash_password("not a password anyone has").unwrap_or_default()) } fn name_ok(name: &str) -> bool { !name.is_empty() && name.len() <= 40 && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_') } fn role_ok(role: &str) -> Result<()> { if rank(role).is_none() { bail!("a role is one of {}", ROLES.join(", ")); } Ok(()) } // ── Admin's side ───────────────────────────────────────────────────────────── /// A setup for `name`: a fresh one-time-code secret and a link token. Returns the token. fn new_setup(a: &mut Value) -> Result { let t = token()?; a["setup"] = json!({"hash": sha256(&t), "expires": now() + SETUP_S, "totp": data_encoding::BASE32_NOPAD.encode(&random(20)?)}); Ok(t) } /// A new account. Returns its setup token: the link is `/setup/`. pub fn add(name: &str, role: &str, by: &str) -> Result { if !name_ok(name) { bail!("an account's name is lowercase letters, digits, - and _"); } role_ok(role)?; let mut s = Store::open()?; if s.accounts().contains_key(name) { bail!("there is an account {name} already (midas account reset {name} sends a new setup link)"); } let mut a = json!({"role": role, "created_at": now(), "created_by": by, "password": null, "totp": null, "recovery": []}); let t = new_setup(&mut a)?; s.accounts().insert(name.to_string(), a); s.save()?; events::emit("account_added", json!({"actor": by, "account": name, "role": role})); Ok(t) } /// Start over: no password, no code secret, no recovery codes, no sessions, /// and a new setup link (a lost phone, a leaked password). Returns its token. pub fn reset(name: &str, by: &str) -> Result { let mut s = Store::open()?; let a = s.account(name)?; for k in ["password", "totp"] { a[k] = Value::Null; } a["recovery"] = json!([]); a["failures"] = json!(0); a["locked_until"] = Value::Null; let t = new_setup(a)?; s.sessions().retain(|_, v| v["account"] != name); s.save()?; events::emit("account_reset", json!({"actor": by, "account": name})); Ok(t) } pub fn set_role(name: &str, role: &str, by: &str) -> Result<()> { role_ok(role)?; let mut s = Store::open()?; s.account(name)?["role"] = json!(role); s.sessions().iter_mut().filter(|(_, v)| v["account"] == name).for_each(|(_, v)| v["role"] = json!(role)); s.save()?; events::emit("account_role", json!({"actor": by, "account": name, "role": role})); Ok(()) } pub fn remove(name: &str, by: &str) -> Result<()> { let mut s = Store::open()?; if s.accounts().remove(name).is_none() { bail!("no account {name}"); } s.sessions().retain(|_, v| v["account"] != name); s.save()?; events::emit("account_removed", json!({"actor": by, "account": name})); Ok(()) } /// Every account, without its secrets. pub fn list() -> Result { let mut s = Store::open()?; let t = now(); let live: Vec<(String, i64)> = s.0.data["sessions"].as_object().into_iter().flatten() .filter(|(_, v)| live(v, t)).map(|(_, v)| (v["account"].as_str().unwrap_or("").to_string(), v["seen"].as_i64().unwrap_or(0))).collect(); Ok(json!(s.accounts().iter().map(|(n, a)| { let seen = live.iter().filter(|(o, _)| o == n).map(|(_, at)| *at).max(); json!({"name": n, "role": a["role"], "created_at": a["created_at"], "created_by": a["created_by"], "ready": a["password"].is_string() && a["totp"].is_string(), "setup_pending": a["setup"].is_object(), "locked": a["locked_until"].as_i64().is_some_and(|u| u > t), "recovery_left": a["recovery"].as_array().map_or(0, Vec::len), "last_seen": seen}) }).collect::>())) } // ── Setting up ─────────────────────────────────────────────────────────────── fn setup_for<'a>(s: &'a mut Store, token: &str) -> Result<(String, &'a mut Value)> { let h = sha256(token); let t = now(); let name = s.0.data["accounts"].as_object().into_iter().flatten() .find(|(_, a)| a["setup"]["hash"] == h.as_str() && a["setup"]["expires"].as_i64().is_some_and(|e| e > t)) .map(|(n, _)| n.clone()); let Some(name) = name else { bail!("this setup link is not valid (any more): ask an admin for a new one") }; let a = s.account(&name)?; Ok((name, a)) } /// What the setup page shows: the account, and the secret as text, as an /// `otpauth://` link and as a QR code (SVG). pub fn setup_info(token: &str, issuer: &str) -> Result { let mut s = Store::open()?; let (name, a) = setup_for(&mut s, token)?; let secret = a["setup"]["totp"].as_str().unwrap_or("").to_string(); let label = format!("{issuer}:{name}"); let uri = format!("otpauth://totp/{}?secret={secret}&issuer={}&algorithm=SHA1&digits=6&period=30", pct(&label), pct(issuer)); let qr = qrcode::QrCode::new(uri.as_bytes())? .render::().min_dimensions(200, 200).quiet_zone(true).build(); Ok(json!({"name": name, "role": a["role"], "secret": secret, "uri": uri, "qr_svg": qr})) } /// Finish setting up: the password, and a first code that proves the app has /// the secret. Returns the recovery codes, shown this once. pub fn setup_complete(token: &str, password: &str, code: &str) -> Result> { if password.chars().count() < MIN_PASSWORD { bail!("a password of at least {MIN_PASSWORD} characters"); } let mut s = Store::open()?; let (name, a) = setup_for(&mut s, token)?; let secret = a["setup"]["totp"].as_str().unwrap_or("").to_string(); let Some(step) = totp_step(&secret, code, now()) else { bail!("that code does not match: check the app's clock, and that it added this account's secret"); }; let codes: Vec = (0..RECOVERY_CODES).map(|_| random(5).map(|b| { let c = data_encoding::BASE32_NOPAD.encode(&b).to_ascii_lowercase(); format!("{}-{}", &c[..4], &c[4..]) })).collect::>()?; a["password"] = json!(hash_password(password)?); a["totp"] = json!(secret); a["totp_last_step"] = json!(step); a["recovery"] = json!(codes.iter().map(|c| sha256(c)).collect::>()); a["failures"] = json!(0); if let Some(o) = a.as_object_mut() { o.remove("setup"); } s.save()?; events::emit("account_ready", json!({"actor": name, "account": name})); Ok(codes) } fn pct(s: &str) -> String { s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect() } // ── Logging in ─────────────────────────────────────────────────────────────── /// Name, password and code (or a recovery code) → a session token. Every /// refusal says the same thing: which part was wrong is not for a guesser. pub fn login(name: &str, password: &str, code: &str, peer: &str) -> Result<(String, String)> { const NO: &str = "that name, password and code do not go together"; let t = now(); let mut s = Store::open()?; let Some(a) = s.accounts().get(name).cloned() else { let _ = password_ok(password, decoy()); events::emit("login_failed", json!({"account": name, "peer": peer, "why": "no such account"})); bail!(NO); }; if let Some(until) = a["locked_until"].as_i64().filter(|u| *u > t) { events::emit("login_failed", json!({"account": name, "peer": peer, "why": "locked"})); bail!("too many failed logins: try again in {} minutes", (until - t + 59) / 60); } let pw_ok = a["password"].as_str().is_some_and(|h| password_ok(password, h)); let step = a["totp"].as_str().and_then(|sec| totp_step(sec, code, t)) .filter(|st| *st > a["totp_last_step"].as_i64().unwrap_or(-1)); let recovery = (step.is_none() && pw_ok).then(|| sha256(code.trim().to_ascii_lowercase().as_str())) .filter(|h| a["recovery"].as_array().is_some_and(|r| r.iter().any(|x| x == h.as_str()))); let acc = s.account(name)?; if !pw_ok || (step.is_none() && recovery.is_none()) { let n = acc["failures"].as_i64().unwrap_or(0) + 1; acc["failures"] = json!(n); if n >= FAILURES { acc["locked_until"] = json!(t + LOCK_S); acc["failures"] = json!(0); } s.save()?; events::emit("login_failed", json!({"account": name, "peer": peer, "why": if pw_ok { "code" } else { "password" }, "locked": n >= FAILURES})); bail!(NO); } acc["failures"] = json!(0); acc["locked_until"] = Value::Null; if let Some(st) = step { acc["totp_last_step"] = json!(st); } if let Some(h) = &recovery { if let Some(r) = acc["recovery"].as_array_mut() { r.retain(|x| x != h.as_str()); } } let role = acc["role"].as_str().unwrap_or("viewer").to_string(); let left = acc["recovery"].as_array().map_or(0, Vec::len); let tok = token()?; s.sessions().retain(|_, v| live(v, t)); s.sessions().insert(sha256(&tok), json!({"account": name, "role": role, "created": t, "seen": t, "peer": peer})); s.save()?; events::emit("login", json!({"actor": name, "account": name, "peer": peer, "with": if recovery.is_some() { "recovery code" } else { "code" }, "recovery_left": recovery.is_some().then_some(left)})); Ok((tok, role)) } fn live(v: &Value, t: i64) -> bool { t - v["seen"].as_i64().unwrap_or(0) < SESSION_IDLE_S && t - v["created"].as_i64().unwrap_or(0) < SESSION_MAX_S } /// The account and role a session token is, while it lasts. Its use keeps it /// alive (written at most once a minute). pub fn session(tok: &str) -> Option<(String, String)> { if tok.len() != 64 { return None; } let h = sha256(tok); let t = now(); let mut s = Store::open().ok()?; let v = s.0.data["sessions"].get(&h)?.clone(); if !live(&v, t) { s.sessions().remove(&h); let _ = s.save(); return None; } if t - v["seen"].as_i64().unwrap_or(0) >= 60 { s.sessions()[&h]["seen"] = json!(t); let _ = s.save(); } Some((v["account"].as_str()?.to_string(), v["role"].as_str()?.to_string())) } pub fn logout(tok: &str) { if let Ok(mut s) = Store::open() { if let Some(v) = s.sessions().remove(&sha256(tok)) { let _ = s.save(); events::emit("logout", json!({"actor": v["account"], "account": v["account"]})); } } } #[cfg(test)] mod tests { use super::*; #[test] fn hotp_and_totp_match_the_rfcs() { // RFC 4226 appendix D, and RFC 6238 appendix B (SHA-1, eight digits). let secret = b"12345678901234567890"; let want = [755224, 287082, 359152, 969429, 338314, 254676, 287922, 162583, 399871, 520489]; for (i, w) in want.iter().enumerate() { assert_eq!(hotp(secret, i as u64, 6), *w); } for (t, w) in [(59u64, 94287082), (1111111109, 7081804), (1234567890, 89005924), (20000000000, 65353130)] { assert_eq!(hotp(secret, t / 30, 8), w, "T={t}"); } let b32 = data_encoding::BASE32_NOPAD.encode(secret); assert_eq!(totp_step(&b32, "287082", 59), Some(1)); assert_eq!(totp_step(&b32, "287 082", 59 + 30), Some(1), "a step late, spaces allowed"); assert_eq!(totp_step(&b32, "287082", 59 + 90), None); } #[test] fn roles_include_the_ones_before() { assert!(at_least("admin", "steer") && at_least("operator", "viewer") && at_least("steer", "steer")); assert!(!at_least("operator", "steer") && !at_least("nobody", "viewer") && !at_least("admin", "nobody")); } }