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

+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;
}
}