This commit is contained in:
gru committed 2026-10-03 00:27:09 +01:00
commit 5e23e9af02
240 files changed
+99957

No files matched your search

+143
View File
@@ -0,0 +1,143 @@
//! Local filesystem authority. The process owner can initialize or recover the sole admin.
use anyhow::{ensure, Context, Result};
use fs2::FileExt;
use rand::{rngs::OsRng, RngCore};
use std::{
fs::{self, File, OpenOptions},
io::Write,
path::Path,
};
fn private_options() -> OpenOptions {
let mut options = OpenOptions::new();
options.write(true).read(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
options
}
pub fn prepare_directory(path: &Path) -> Result<()> {
if !path.exists() {
fs::create_dir_all(path).context("cannot create data directory")?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
}
}
let meta = fs::symlink_metadata(path)?;
ensure!(
meta.is_dir() && !meta.file_type().is_symlink(),
"data directory must not be a symlink"
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
ensure!(
meta.permissions().mode() & 0o077 == 0,
"data directory must be private: chmod 700 {}",
path.display()
);
}
Ok(())
}
pub fn lock_directory(path: &Path) -> Result<File> {
let file = private_options()
.create(true)
.truncate(false)
.open(path.join("process.lock"))?;
file.try_lock_exclusive()
.context("another RustProxy process already owns this data directory")?;
Ok(file)
}
pub fn load_setup_token(dir: &Path) -> Result<String> {
let path = dir.join("setup-token");
let meta = fs::symlink_metadata(&path).context("setup token does not exist")?;
ensure!(
meta.is_file() && !meta.file_type().is_symlink(),
"token must be a regular file"
);
ensure!(meta.len() <= 128, "invalid setup token file");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
ensure!(
meta.permissions().mode() & 0o077 == 0,
"token permissions must be 600"
);
}
let token = fs::read_to_string(path)?.trim().to_owned();
ensure!(
token.len() == 64 && token.bytes().all(|b| b.is_ascii_hexdigit()),
"invalid setup token"
);
Ok(token)
}
pub fn load_or_create_setup_token(dir: &Path) -> Result<String> {
let path = dir.join("setup-token");
if path.try_exists()? {
return load_setup_token(dir);
}
let mut bytes = [0u8; 32];
OsRng.fill_bytes(&mut bytes);
let token: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
let mut file = match private_options().create_new(true).open(&path) {
Ok(file) => file,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
return load_setup_token(dir);
}
Err(error) => return Err(error.into()),
};
writeln!(file, "{token}")?;
file.sync_all()?;
Ok(token)
}
/// Validate database/WAL paths before opening SQLite. The private parent directory is
/// the local CLI authorization boundary; files owned by the same OS user are trusted.
pub fn prepare_database(path: &Path) -> Result<()> {
if !path.try_exists()? {
private_options().create_new(true).open(path)?.sync_all()?;
}
for suffix in ["", "-wal", "-shm"] {
let mut name = path.as_os_str().to_os_string();
name.push(suffix);
let candidate = std::path::PathBuf::from(name);
match fs::symlink_metadata(&candidate) {
Ok(meta) => {
ensure!(
meta.is_file() && !meta.file_type().is_symlink(),
"database files must be regular files"
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
ensure!(
meta.permissions().mode() & 0o077 == 0,
"database files must be private (chmod 600)"
);
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn setup_token_can_be_generated_before_database_or_server() {
let dir = tempfile::tempdir().unwrap();
let first = load_or_create_setup_token(dir.path()).unwrap();
assert_eq!(first.len(), 64);
assert!(first.bytes().all(|b| b.is_ascii_hexdigit()));
assert!(!dir.path().join("config.sqlite3").exists());
assert_eq!(load_or_create_setup_token(dir.path()).unwrap(), first);
assert_eq!(load_setup_token(dir.path()).unwrap(), first);
}
}
+555
View File
@@ -0,0 +1,555 @@
//! Password authentication is confined to the control plane.
//! Expensive Argon2 work runs on bounded blocking workers, not Tokio network workers.
mod files;
mod store;
use crate::{db::Store, runtime::ApiError};
use anyhow::{ensure, Context, Result};
use argon2::{
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
Algorithm, Argon2, Params, Version,
};
pub use files::{
load_or_create_setup_token, load_setup_token, lock_directory, prepare_database,
prepare_directory,
};
use http::{header::COOKIE, HeaderMap, StatusCode};
use rand::{rngs::OsRng, RngCore};
use sha2::{Digest, Sha256};
use std::{
path::PathBuf,
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
pub use store::AdminRecord;
use subtle::ConstantTimeEq;
use tokio::sync::Semaphore;
use zeroize::Zeroizing;
pub const COOKIE_NAME: &str = "rustproxy_session";
pub const SESSION_SECONDS: i64 = 30 * 24 * 60 * 60;
pub const IDLE_SECONDS: i64 = SESSION_SECONDS;
#[derive(Clone)]
pub struct Session {
pub token_hash: String,
pub csrf: String,
pub username: String,
pub expires_at: i64,
pub generation: i64,
}
pub struct SessionToken {
pub secret: String,
pub session: Session,
}
pub struct Auth {
pub store: Store,
data_dir: PathBuf,
setup_token: Option<String>,
dummy_hash: String,
workers: Arc<Semaphore>,
}
pub fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
.min(i64::MAX as u64) as i64
}
pub fn random_secret() -> String {
let mut bytes = [0_u8; 32];
OsRng.fill_bytes(&mut bytes);
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn secret_hash(secret: &str) -> String {
format!("{:x}", Sha256::digest(secret.as_bytes()))
}
pub fn equal_secret(candidate: &str, expected: &str) -> bool {
candidate.len() == expected.len() && bool::from(candidate.as_bytes().ct_eq(expected.as_bytes()))
}
pub fn valid_secret(value: &str) -> bool {
value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit())
}
pub fn cookie_secret(headers: &HeaderMap) -> Option<String> {
let mut found = None;
for value in headers.get_all(COOKIE).iter() {
for part in value.to_str().ok()?.split(';') {
let Some((key, value)) = part.trim().split_once('=') else {
continue;
};
if key == COOKIE_NAME {
if found.is_some() || !valid_secret(value) {
return None;
}
found = Some(value.to_owned());
}
}
}
found
}
pub fn session_cookie(secret: &str, secure: bool, max_age_seconds: i64) -> String {
let max_age_seconds = max_age_seconds.max(1);
format!(
"{COOKIE_NAME}={secret}; Path=/; HttpOnly; SameSite=Strict; Max-Age={max_age_seconds}{}",
if secure { "; Secure" } else { "" }
)
}
pub fn expired_cookie(secure: bool) -> String {
format!(
"{COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0{}",
if secure { "; Secure" } else { "" }
)
}
pub fn username(value: &str) -> Result<String> {
let value = value.trim().to_ascii_lowercase();
ensure!(
(3..=64).contains(&value.len())
&& value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')),
"auth.invalid_username"
);
Ok(value)
}
pub fn validate_password(value: &str) -> Result<()> {
ensure!(
(12..=128).contains(&value.len()) && !value.contains(['\n', '\r', '\0']),
"auth.password_policy"
);
Ok(())
}
pub(crate) fn hash_sync(password: &str) -> Result<String> {
let params = Params::new(19_456, 2, 1, None).context("Argon2 parameters")?;
let salt = SaltString::generate(&mut OsRng);
Ok(Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
.hash_password(password.as_bytes(), &salt)?
.to_string())
}
fn verify_sync(password: &str, encoded: &str) -> bool {
PasswordHash::new(encoded).ok().is_some_and(|hash| {
Argon2::default()
.verify_password(password.as_bytes(), &hash)
.is_ok()
})
}
pub async fn hash_password_offline(password: String) -> Result<String> {
validate_password(&password)?;
let password = Zeroizing::new(password);
tokio::task::spawn_blocking(move || hash_sync(&password))
.await
.context("password worker failed")?
}
pub fn internal(error: impl std::fmt::Display) -> ApiError {
tracing::error!(%error, "admin operation failed");
ApiError(StatusCode::SERVICE_UNAVAILABLE, "auth.unavailable".into())
}
fn failure(status: StatusCode, code: &str) -> ApiError {
ApiError(status, code.into())
}
impl Auth {
pub async fn new(store: Store, data_dir: PathBuf) -> Result<Arc<Self>> {
let setup_token = if store.admin_record().await?.is_none() {
Some(load_or_create_setup_token(&data_dir)?)
} else {
None
};
// Generate valid dummy work for unknown usernames. This happens only at startup.
let dummy_hash = hash_password_offline(random_secret()).await?;
Ok(Arc::new(Self {
store,
data_dir,
setup_token,
dummy_hash,
workers: Arc::new(Semaphore::new(2)),
}))
}
async fn attempt(&self) -> Result<(), ApiError> {
if !self
.store
.consume_auth_attempt(now())
.await
.map_err(internal)?
{
return Err(failure(StatusCode::TOO_MANY_REQUESTS, "auth.rate_limited"));
}
Ok(())
}
async fn hash(&self, password: String) -> Result<String, ApiError> {
validate_password(&password)
.map_err(|_| failure(StatusCode::UNPROCESSABLE_ENTITY, "auth.password_policy"))?;
let permit = self
.workers
.clone()
.try_acquire_owned()
.map_err(|_| failure(StatusCode::TOO_MANY_REQUESTS, "auth.busy"))?;
let password = Zeroizing::new(password);
tokio::task::spawn_blocking(move || {
let _permit = permit;
hash_sync(&password)
})
.await
.map_err(internal)?
.map_err(internal)
}
async fn verify(&self, password: String, encoded: String) -> Result<bool, ApiError> {
if password.len() > 128 {
return Ok(false);
}
let permit = self
.workers
.clone()
.try_acquire_owned()
.map_err(|_| failure(StatusCode::TOO_MANY_REQUESTS, "auth.busy"))?;
let password = Zeroizing::new(password);
tokio::task::spawn_blocking(move || {
let _permit = permit;
verify_sync(&password, &encoded)
})
.await
.map_err(internal)
}
pub async fn setup(
&self,
supplied_token: &str,
name: &str,
password: String,
) -> Result<(), ApiError> {
self.attempt().await?;
if self.store.admin_record().await.map_err(internal)?.is_some() {
return Err(failure(StatusCode::CONFLICT, "auth.already_initialized"));
}
if !self
.setup_token
.as_ref()
.is_some_and(|expected| equal_secret(supplied_token, expected))
{
self.store
.audit("anonymous", "setup.denied", "invalid setup capability")
.await
.map_err(internal)?;
return Err(failure(StatusCode::FORBIDDEN, "auth.invalid_setup_token"));
}
let name = username(name)
.map_err(|_| failure(StatusCode::UNPROCESSABLE_ENTITY, "auth.invalid_username"))?;
let hash = self.hash(password).await?;
if !self
.store
.initialize_admin(&name, &hash, "browser setup")
.await
.map_err(internal)?
{
return Err(failure(StatusCode::CONFLICT, "auth.already_initialized"));
}
self.remove_bootstrap_files().await;
Ok(())
}
pub async fn remove_bootstrap_files(&self) {
for name in ["setup-token", "admin-token"] {
match tokio::fs::remove_file(self.data_dir.join(name)).await {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
tracing::warn!(%error, file = name, "unused bootstrap file could not be removed; it has no authority after setup")
}
}
}
}
pub async fn login(
&self,
name: &str,
password: String,
previous: Option<&str>,
session_seconds: i64,
) -> Result<SessionToken, ApiError> {
self.attempt().await?;
let record = self.store.admin_record().await.map_err(internal)?;
let candidate = username(name).unwrap_or_default();
let matches = record.as_ref().is_some_and(|r| r.username == candidate);
let hash = record
.as_ref()
.filter(|_| matches)
.map(|r| r.password_hash.clone())
.unwrap_or_else(|| self.dummy_hash.clone());
let verified = self.verify(password, hash).await?;
if !verified || !matches {
self.store
.audit("anonymous", "login.denied", "invalid credentials")
.await
.map_err(internal)?;
return Err(failure(
StatusCode::UNAUTHORIZED,
"auth.invalid_credentials",
));
}
let record =
record.ok_or_else(|| failure(StatusCode::UNAUTHORIZED, "auth.invalid_credentials"))?;
self.store
.create_browser_session(record.generation, previous, session_seconds)
.await
.map_err(internal)?
.ok_or_else(|| failure(StatusCode::UNAUTHORIZED, "auth.credentials_changed"))
}
pub async fn change_password(
&self,
session: &Session,
current: String,
replacement: String,
) -> Result<(), ApiError> {
self.attempt().await?;
let record = self
.store
.admin_record()
.await
.map_err(internal)?
.ok_or_else(|| failure(StatusCode::UNAUTHORIZED, "auth.required"))?;
if record.generation != session.generation
|| !self.verify(current, record.password_hash).await?
{
return Err(failure(
StatusCode::UNAUTHORIZED,
"auth.invalid_credentials",
));
}
let hash = self.hash(replacement).await?;
if !self
.store
.reset_admin_password(&hash, session.generation, "browser password change")
.await
.map_err(internal)?
{
return Err(failure(StatusCode::CONFLICT, "auth.credentials_changed"));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_independent_argon2id_fixture() {
let fixture: serde_json::Value =
serde_json::from_str(include_str!("../../tests/fixtures/argon2id.json")).unwrap();
assert!(verify_sync(
fixture["password"].as_str().unwrap(),
fixture["hash"].as_str().unwrap()
));
assert!(!verify_sync(
"incorrect fixture password",
fixture["hash"].as_str().unwrap()
));
}
#[test]
fn password_and_username_policy() {
assert_eq!(username(" Owner.Name ").unwrap(), "owner.name");
assert!(username("a").is_err());
assert!(username("a b").is_err());
assert!(validate_password("a sufficiently long password").is_ok());
assert!(validate_password("admin").is_err());
assert!(validate_password(&"a".repeat(129)).is_err());
}
#[test]
fn cookies_reject_ambiguity_and_tokens_are_hashed() {
let s = random_secret();
let mut headers = HeaderMap::new();
headers.insert(COOKIE, format!("{COOKIE_NAME}={s}").parse().unwrap());
assert_eq!(cookie_secret(&headers), Some(s.clone()));
headers.append(COOKIE, format!("{COOKIE_NAME}={s}").parse().unwrap());
assert!(cookie_secret(&headers).is_none());
assert_ne!(secret_hash(&s), s);
assert_eq!(secret_hash(&s).len(), 64);
}
#[tokio::test]
async fn passwords_are_argon2id_salted_and_verifiable() {
let password = "correct horse battery staple";
let a = hash_password_offline(password.into()).await.unwrap();
let b = hash_password_offline(password.into()).await.unwrap();
assert!(a.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"));
assert_ne!(a, b);
assert!(verify_sync(password, &a));
assert!(!verify_sync("incorrect", &a));
}
#[tokio::test]
async fn setup_race_creates_exactly_one_admin() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open(&dir.path().join("db"), &crate::config::Config::default())
.await
.unwrap();
let (a, b) = tokio::join!(
store.initialize_admin("one", "test-hash", "test"),
store.initialize_admin("two", "test-hash", "test")
);
assert_eq!(a.unwrap() as u8 + b.unwrap() as u8, 1);
assert_eq!(store.recent_audit().await.unwrap().len(), 1);
store.close().await;
}
#[tokio::test]
async fn sessions_expire_rotate_and_reset_blocks_old_login_generation() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open(&dir.path().join("db"), &crate::config::Config::default())
.await
.unwrap();
store
.initialize_admin("owner", "test-hash", "test")
.await
.unwrap();
let first = store
.create_session(1, "browser", None)
.await
.unwrap()
.unwrap();
assert!(store
.session_at(&first.secret, now())
.await
.unwrap()
.is_some());
let next = store
.create_session(1, "browser", Some(&first.secret))
.await
.unwrap()
.unwrap();
assert!(store
.session_at(&first.secret, now())
.await
.unwrap()
.is_none());
assert!(store
.session_at(&next.secret, now() + IDLE_SECONDS + 1)
.await
.unwrap()
.is_none());
let alive = store
.create_session(1, "browser", None)
.await
.unwrap()
.unwrap();
assert!(store
.reset_admin_password("new-hash", 1, "test")
.await
.unwrap());
assert!(store
.session_at(&alive.secret, now())
.await
.unwrap()
.is_none());
assert!(store
.create_session(1, "browser", None)
.await
.unwrap()
.is_none());
assert!(store
.create_session(2, "browser", None)
.await
.unwrap()
.is_some());
store.close().await;
}
#[test]
fn session_cookie_uses_configured_remaining_lifetime() {
let cookie = session_cookie("abc", true, 7 * 24 * 60 * 60);
assert!(cookie.contains("Max-Age=604800"));
assert!(cookie.ends_with("; Secure"));
let short = session_cookie("abc", false, 0);
assert!(short.contains("Max-Age=1"));
assert!(!short.contains("; Secure"));
}
#[tokio::test]
async fn browser_session_lifetime_is_configurable_without_sliding_expiry() {
const DAY: i64 = 24 * 60 * 60;
let dir = tempfile::tempdir().unwrap();
let store = Store::open(&dir.path().join("db"), &crate::config::Config::default())
.await
.unwrap();
store
.initialize_admin("owner", "test-hash", "test")
.await
.unwrap();
assert!(store
.create_browser_session(1, None, 6 * DAY)
.await
.is_err());
assert!(store
.create_browser_session(1, None, 31 * DAY)
.await
.is_err());
let issued = store
.create_browser_session(1, None, 7 * DAY)
.await
.unwrap()
.unwrap();
let seven_day_expiry = issued.session.expires_at;
let extended = store
.session_at_with_browser_lifetime(&issued.secret, now(), 30 * DAY)
.await
.unwrap()
.unwrap();
assert_eq!(extended.expires_at, seven_day_expiry + 23 * DAY);
let checked_again = store
.session_at_with_browser_lifetime(&issued.secret, seven_day_expiry + DAY, 30 * DAY)
.await
.unwrap()
.unwrap();
assert_eq!(checked_again.expires_at, extended.expires_at);
assert!(store
.session_at_with_browser_lifetime(&issued.secret, extended.expires_at, 30 * DAY,)
.await
.unwrap()
.is_none());
store.close().await;
}
#[tokio::test]
async fn throttle_is_persistent_bounded_and_recovers() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("db");
let store = Store::open(&file, &crate::config::Config::default())
.await
.unwrap();
for _ in 0..10 {
assert!(store.consume_auth_attempt(1000).await.unwrap());
}
assert!(!store.consume_auth_attempt(1001).await.unwrap());
store.close().await;
let store = Store::open(&file, &crate::config::Config::default())
.await
.unwrap();
assert!(!store.consume_auth_attempt(1020).await.unwrap());
assert!(store.consume_auth_attempt(1060).await.unwrap());
store.close().await;
}
#[tokio::test]
async fn browser_session_count_is_bounded() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open(&dir.path().join("db"), &crate::config::Config::default())
.await
.unwrap();
store
.initialize_admin("owner", "test-hash", "test")
.await
.unwrap();
let first = store
.create_session(1, "browser", None)
.await
.unwrap()
.unwrap();
for _ in 0..20 {
store
.create_session(1, "browser", None)
.await
.unwrap()
.unwrap();
}
let count: i64 = sqlx::query_scalar("SELECT count(*) FROM admin_sessions")
.fetch_one(&store.pool)
.await
.unwrap();
assert_eq!(count, 16);
assert!(store
.session_at(&first.secret, now())
.await
.unwrap()
.is_none());
store.close().await;
}
}
+256
View File
@@ -0,0 +1,256 @@
//! Transactional administrator operations. Login/reset races are guarded by generation CAS.
use super::{now, random_secret, secret_hash, Session, SessionToken, SESSION_SECONDS};
use crate::db::{audit_tx, Store};
use anyhow::{ensure, Result};
use sqlx::Row;
#[derive(Debug, Clone)]
pub struct AdminRecord {
pub username: String,
pub password_hash: String,
pub generation: i64,
}
impl Store {
pub async fn admin_record(&self) -> Result<Option<AdminRecord>> {
sqlx::query("SELECT username, password_hash, generation FROM administrator WHERE id = 1")
.fetch_optional(&self.pool)
.await?
.map(|row| {
Ok(AdminRecord {
username: row.try_get("username")?,
password_hash: row.try_get("password_hash")?,
generation: row.try_get("generation")?,
})
})
.transpose()
}
pub async fn initialize_admin(&self, username: &str, hash: &str, source: &str) -> Result<bool> {
let mut tx = self.pool.begin().await?;
let inserted = sqlx::query("INSERT OR IGNORE INTO administrator(id, username, password_hash, generation, created_at) VALUES(1, ?, ?, 1, ?)")
.bind(username).bind(hash).bind(now()).execute(&mut *tx).await?;
if inserted.rows_affected() != 1 {
return Ok(false);
}
audit_tx(&mut tx, username, "admin.initialize", source).await?;
tx.commit().await?;
Ok(true)
}
/// One persisted global bucket for the single administration listener.
/// Fixed upper bound: 10 attempts per 60-second window, including successful attempts.
/// Unknown usernames use the same bucket and password work as known usernames.
pub async fn consume_auth_attempt(&self, time: i64) -> Result<bool> {
let changed = sqlx::query("UPDATE auth_throttle SET attempts = CASE WHEN window_start <= ? THEN 1 ELSE attempts + 1 END, window_start = CASE WHEN window_start <= ? THEN ? ELSE window_start END WHERE id = 1 AND (window_start <= ? OR attempts < 10)")
.bind(time - 60).bind(time - 60).bind(time).bind(time - 60)
.execute(&self.pool).await?;
Ok(changed.rows_affected() == 1)
}
/// The first UPDATE obtains SQLite's write lock and validates the credential generation.
/// A reset committed during password verification prevents insertion of a stale session.
pub async fn create_session(
&self,
generation: i64,
kind: &str,
previous: Option<&str>,
) -> Result<Option<SessionToken>> {
self.create_session_with_lifetime(generation, kind, previous, SESSION_SECONDS, 60)
.await
}
pub async fn create_browser_session(
&self,
generation: i64,
previous: Option<&str>,
session_seconds: i64,
) -> Result<Option<SessionToken>> {
ensure!(
(7 * 24 * 60 * 60..=30 * 24 * 60 * 60).contains(&session_seconds),
"browser session lifetime must be 7..30 days"
);
self.create_session_with_lifetime(generation, "browser", previous, session_seconds, 60)
.await
}
pub async fn create_live_log_session(
&self,
generation: i64,
) -> Result<Option<SessionToken>> {
self.create_session_with_lifetime(generation, "cli", None, SESSION_SECONDS, 8 * 60 * 60)
.await
}
async fn create_session_with_lifetime(
&self,
generation: i64,
kind: &str,
previous: Option<&str>,
browser_lifetime: i64,
cli_lifetime: i64,
) -> Result<Option<SessionToken>> {
let time = now();
let secret = random_secret();
let hash = secret_hash(&secret);
let csrf = random_secret();
let lifetime = if kind == "cli" { cli_lifetime } else { browser_lifetime };
let mut tx = self.pool.begin().await?;
let valid = sqlx::query(
"UPDATE administrator SET generation = generation WHERE id = 1 AND generation = ?",
)
.bind(generation)
.execute(&mut *tx)
.await?;
if valid.rows_affected() == 0 {
return Ok(None);
}
let username: String =
sqlx::query_scalar("SELECT username FROM administrator WHERE id = 1")
.fetch_one(&mut *tx)
.await?;
sqlx::query("DELETE FROM admin_sessions WHERE expires_at <= ? OR (kind = 'browser' AND created_at + ? <= ?)")
.bind(time)
.bind(browser_lifetime)
.bind(time)
.execute(&mut *tx)
.await?;
if let Some(previous) = previous {
sqlx::query("DELETE FROM admin_sessions WHERE token_hash = ?")
.bind(secret_hash(previous))
.execute(&mut *tx)
.await?;
}
// Independent caps avoid a local CLI burst evicting all browser sessions.
let cap = if kind == "cli" { 8_i64 } else { 16_i64 };
sqlx::query("DELETE FROM admin_sessions WHERE token_hash IN (SELECT token_hash FROM admin_sessions WHERE kind = ? ORDER BY created_at DESC, rowid DESC LIMIT -1 OFFSET ?)")
.bind(kind).bind(cap - 1).execute(&mut *tx).await?;
sqlx::query("INSERT INTO admin_sessions(token_hash, csrf_token, generation, created_at, last_seen, expires_at, kind) VALUES(?, ?, ?, ?, ?, ?, ?)")
.bind(&hash).bind(&csrf).bind(generation).bind(time).bind(time).bind(time + lifetime)
.bind(kind).execute(&mut *tx).await?;
audit_tx(&mut tx, &username, "session.create", kind).await?;
tx.commit().await?;
Ok(Some(SessionToken {
secret,
session: Session {
token_hash: hash,
csrf,
username,
expires_at: time + lifetime,
generation,
},
}))
}
pub async fn session_at(&self, secret: &str, time: i64) -> Result<Option<Session>> {
self.session_at_with_browser_lifetime(secret, time, SESSION_SECONDS)
.await
}
pub async fn session_at_with_browser_lifetime(
&self,
secret: &str,
time: i64,
browser_lifetime: i64,
) -> Result<Option<Session>> {
ensure!(
(7 * 24 * 60 * 60..=30 * 24 * 60 * 60).contains(&browser_lifetime),
"browser session lifetime must be 7..30 days"
);
let hash = secret_hash(secret);
// A browser session is bounded by the currently configured lifetime. If the
// setting was increased while an older still-valid session exists, extend its
// absolute expiry from its original creation time without turning it into a
// sliding/immortal session. CLI capabilities keep the fixed expiry chosen
// when they are created (60 seconds for one-shot admin commands, longer
// for the bounded local live-log viewer).
let row = sqlx::query("UPDATE admin_sessions SET last_seen = ?, expires_at = CASE WHEN kind = 'browser' THEN created_at + ? ELSE expires_at END WHERE token_hash = ? AND expires_at > ? AND (kind <> 'browser' OR created_at + ? > ?) AND generation = (SELECT generation FROM administrator WHERE id = 1) RETURNING csrf_token, expires_at, generation, (SELECT username FROM administrator WHERE id = 1) AS username")
.bind(time)
.bind(browser_lifetime)
.bind(&hash)
.bind(time)
.bind(browser_lifetime)
.bind(time)
.fetch_optional(&self.pool).await?;
row.map(|row| {
Ok(Session {
token_hash: hash,
csrf: row.try_get("csrf_token")?,
username: row.try_get("username")?,
expires_at: row.try_get("expires_at")?,
generation: row.try_get("generation")?,
})
})
.transpose()
}
pub async fn admin_preferences(&self, username: &str) -> Result<Option<String>> {
sqlx::query_scalar(
"SELECT preferences.document FROM admin_preferences AS preferences JOIN administrator AS admin ON admin.id = preferences.administrator_id WHERE admin.id = 1 AND admin.username = ?",
)
.bind(username)
.fetch_optional(&self.pool)
.await
.map_err(Into::into)
}
pub async fn save_admin_preferences(&self, username: &str, document: &str) -> Result<bool> {
ensure!(
(2..=4096).contains(&document.len()),
"administrator preferences document is too large"
);
let result = sqlx::query(
"INSERT INTO admin_preferences(administrator_id, document) SELECT id, ? FROM administrator WHERE id = 1 AND username = ? ON CONFLICT(administrator_id) DO UPDATE SET document = excluded.document",
)
.bind(document)
.bind(username)
.execute(&self.pool)
.await?;
Ok(result.rows_affected() == 1)
}
pub async fn end_session(&self, session: &Session) -> Result<()> {
let mut tx = self.pool.begin().await?;
sqlx::query("DELETE FROM admin_sessions WHERE token_hash = ?")
.bind(&session.token_hash)
.execute(&mut *tx)
.await?;
audit_tx(
&mut tx,
&session.username,
"session.logout",
"current session",
)
.await?;
tx.commit().await?;
Ok(())
}
/// expected_generation protects browser password changes against simultaneous resets.
/// CLI passes the generation it read, so even two offline recoveries cannot silently win.
pub async fn reset_admin_password(
&self,
hash: &str,
expected_generation: i64,
source: &str,
) -> Result<bool> {
let mut tx = self.pool.begin().await?;
let result = sqlx::query("UPDATE administrator SET password_hash = ?, generation = generation + 1 WHERE id = 1 AND generation = ? AND generation < 9223372036854775807")
.bind(hash).bind(expected_generation).execute(&mut *tx).await?;
if result.rows_affected() == 0 {
return Ok(false);
}
let username: String =
sqlx::query_scalar("SELECT username FROM administrator WHERE id = 1")
.fetch_one(&mut *tx)
.await?;
sqlx::query("DELETE FROM admin_sessions")
.execute(&mut *tx)
.await?;
sqlx::query("UPDATE auth_throttle SET window_start = 0, attempts = 0 WHERE id = 1")
.execute(&mut *tx)
.await?;
audit_tx(&mut tx, &username, "admin.password_reset", source).await?;
tx.commit().await?;
Ok(true)
}
pub async fn revoke_all_sessions(&self, actor: &str) -> Result<()> {
let mut tx = self.pool.begin().await?;
sqlx::query("UPDATE administrator SET generation = generation + 1 WHERE id = 1 AND generation < 9223372036854775807")
.execute(&mut *tx).await?;
sqlx::query("DELETE FROM admin_sessions")
.execute(&mut *tx)
.await?;
audit_tx(&mut tx, actor, "session.revoke_all", "all sessions").await?;
tx.commit().await?;
Ok(())
}
}