// SPDX-License-Identifier: CPAL-1.0 // Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution // License 1.0: see LICENSE (its Exhibit A is this file's notice). //! API tokens. A token is `ian__`: a 16-hex-digit id (for listing and lookup) //! and 32 random bytes. Control stores only SHA-256 of the whole token, in `tokens.json` //! (mode 0600), and compares in constant time. //! //! A fast hash is enough here: the secret has 256 bits of entropy, so nobody can find a //! preimage by guessing, slow or fast; slow password hashes only help low-entropy secrets //! that people pick. The comparison is constant-time anyway (it compares hashes of the //! presented value, so even a timing leak would say nothing about a stored hash's preimage). //! //! The value is shown once, in the response that creates it (or by `ianitor-control token //! create`), and never logged. Revoked and expired tokens stay listed so a script gets a //! precise message ("revoked on …"). use std::path::{Path, PathBuf}; use base64::Engine as _; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use serde::{Deserialize, Serialize}; use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct TokenRecord { pub id: String, pub name: String, pub sha256: String, pub created_at: u64, pub expires_at: Option, pub last_used_at: Option, pub revoked_at: Option, } #[derive(Debug, Default, Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct TokenFile { tokens: Vec, } /// Why a presented token was refused. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Refusal { Missing, Unknown, Expired(u64), Revoked(u64), } pub const MAX_TOKENS: usize = 200; const LAST_USED_GRANULARITY: u64 = 60; pub struct Tokens { path: PathBuf, /// Serialises read-modify-write of the file inside this process. lock: std::sync::Mutex<()>, } struct StoreGuard<'a> { _m: std::sync::MutexGuard<'a, ()>, _f: std::fs::File, } pub fn valid_name(n: &str) -> bool { let n = n.trim(); !n.is_empty() && n.chars().count() <= 64 && n.chars() .all(|c| c.is_ascii_alphanumeric() || " ._-".contains(c)) } impl Tokens { pub fn new(state_dir: &Path) -> Tokens { Tokens { path: state_dir.join("tokens.json"), lock: std::sync::Mutex::new(()), } } /// Exclusive access to `tokens.json` for one read-modify-write: a mutex inside this /// process and an advisory lock on `tokens.lock` across processes (the CLI and the /// server), released when the guard is dropped, also if the process dies. fn guard(&self) -> Result, String> { let m = self .lock .lock() .map_err(|_| "token store unavailable".to_owned())?; let path = self.path.with_file_name("tokens.lock"); if let Some(dir) = path.parent() { std::fs::create_dir_all(dir) .map_err(|e| format!("cannot create {}: {e}", dir.display()))?; } let f = std::fs::OpenOptions::new() .create(true) .truncate(false) .write(true) .open(&path) .map_err(|e| format!("cannot open {}: {e}", path.display()))?; f.lock() .map_err(|e| format!("cannot lock {}: {e}", path.display()))?; Ok(StoreGuard { _m: m, _f: f }) } fn load(&self) -> Result { Ok(read_json(&self.path)?.unwrap_or_default()) } fn save(&self, f: &TokenFile) -> Result<(), String> { write_json(&self.path, f) } /// Create a token; returns the record and the value (shown once). pub fn create( &self, name: &str, expires_at: Option, ) -> Result<(TokenRecord, String), String> { let _g = self.guard()?; if !valid_name(name) { return Err("token.name".into()); } let mut f = self.load()?; if f.tokens.iter().filter(|t| t.revoked_at.is_none()).count() >= MAX_TOKENS { return Err("too many tokens; revoke some first".into()); } let id = hex(&random::<8>().map_err(|e| e.to_string())?); let secret = URL_SAFE_NO_PAD.encode(random::<32>().map_err(|e| e.to_string())?); let value = format!("ian_{id}_{secret}"); let rec = TokenRecord { id, name: name.trim().to_owned(), sha256: sha256_hex(value.as_bytes()), created_at: now(), expires_at, last_used_at: None, revoked_at: None, }; f.tokens.push(rec.clone()); self.save(&f)?; Ok((rec, value)) } pub fn list(&self) -> Result, String> { let _g = self.guard()?; Ok(self.load()?.tokens) } pub fn revoke(&self, id: &str) -> Result, String> { let _g = self.guard()?; let mut f = self.load()?; let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else { return Ok(None); }; if t.revoked_at.is_none() { t.revoked_at = Some(now()); } let r = t.clone(); self.save(&f)?; Ok(Some(r)) } pub fn rename(&self, id: &str, name: &str) -> Result, String> { let _g = self.guard()?; if !valid_name(name) { return Err("token.name".into()); } let mut f = self.load()?; let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else { return Ok(None); }; t.name = name.trim().to_owned(); let r = t.clone(); self.save(&f)?; Ok(Some(r)) } /// Check a presented `Authorization` value. The token never appears in an error. pub fn check(&self, header: Option<&str>) -> Result { let Some(h) = header else { return Err(Refusal::Missing); }; let Some(value) = h.strip_prefix("Bearer ").map(str::trim) else { return Err(Refusal::Unknown); }; let id = value .strip_prefix("ian_") .and_then(|r| r.split_once('_')) .map(|(id, _)| id) .filter(|id| id.len() == 16) .ok_or(Refusal::Unknown)?; let _g = self.guard().map_err(|_| Refusal::Unknown)?; let mut f = self.load().map_err(|_| Refusal::Unknown)?; let presented = sha256_hex(value.as_bytes()); let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else { return Err(Refusal::Unknown); }; if !ct_eq(t.sha256.as_bytes(), presented.as_bytes()) { return Err(Refusal::Unknown); } if let Some(r) = t.revoked_at { return Err(Refusal::Revoked(r)); } let n = now(); if let Some(e) = t.expires_at && n >= e { return Err(Refusal::Expired(e)); } let rec = t.clone(); if t.last_used_at .is_none_or(|l| n.saturating_sub(l) >= LAST_USED_GRANULARITY) { t.last_used_at = Some(n); if let Err(e) = self.save(&f) { log::warn!(target: "ianitor::tokens", "cannot record token use: {e}"); } } Ok(rec) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn create_check_revoke() { let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id())); let t = Tokens::new(&d); let (rec, value) = t.create("laptop", None).unwrap(); assert!(value.starts_with("ian_")); let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap(); assert!(!stored.contains(&value[21..]), "only the hash is stored"); assert_eq!( t.check(Some(&format!("Bearer {value}"))).unwrap().id, rec.id ); assert_eq!(t.check(None).unwrap_err(), Refusal::Missing); assert_eq!(t.check(Some(&value)).unwrap_err(), Refusal::Unknown); let mut wrong = value.clone(); wrong.pop(); wrong.push('x'); assert_eq!( t.check(Some(&format!("Bearer {wrong}"))).unwrap_err(), Refusal::Unknown ); t.revoke(&rec.id).unwrap(); assert!(matches!( t.check(Some(&format!("Bearer {value}"))).unwrap_err(), Refusal::Revoked(_) )); let (_, v2) = t.create("old", Some(1)).unwrap(); assert_eq!( t.check(Some(&format!("Bearer {v2}"))).unwrap_err(), Refusal::Expired(1) ); let _ = std::fs::remove_dir_all(&d); } }