Harden web sign-in, credential updates, and service ownership
Browse files- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 12:57
- Commit
- f7a081739cd0
- Parent
- 7411787
6 files changed +732−141
+1−1
| @@ -23,7 +23,7 @@ It prints a generated password (20 random characters, shown only this once), the | ||
| - **Change the password** under Account once signed in (it asks for the current password and a code), or on the server with `gitv-web password`. Either way every other session is signed out. | ||
| - **Lost the authenticator?** Run `gitv-web setup --force` on the server for a new password and secret. | ||
| - The account lives in `/var/lib/gitv-web/login` (or `$GITV_WEB_AUTH`), readable only by its owner. The password is stored as an Argon2id hash. | ||
| - The account lives in `/var/lib/gitv-web/login` (or `$GITV_WEB_AUTH`), readable only by its owner. Root-run setup hands the default service directory to `gitv-web`. If you point `GITV_WEB_AUTH` into an existing custom directory, give the service write and search access there first. The password is stored as an Argon2id hash. | ||
| - Sessions last 12 hours and end when the browser restarts. The session cookie is `Secure`, so the browser must be reached over HTTPS (or on `localhost`). | ||
| - After five failed attempts sign-in locks for a minute, doubling with each further failure up to 15 minutes. A code works once. | ||
+338−23
| @@ -63,6 +63,186 @@ pub enum AuthError { | ||
| Hash(String), | ||
| #[error("couldn't get random bytes: {0}")] | ||
| Random(String), | ||
| #[error("the account changed meanwhile (someone else changed the password or reset it); nothing was saved")] | ||
| Changed, | ||
| #[error("use a user name of 1 to {MAX_USER} visible characters, without spaces")] | ||
| BadUser, | ||
| #[error("couldn't hand {} to the service account: {source}", path.display())] | ||
| Ownership { path: PathBuf, source: nix::errno::Errno }, | ||
| } | ||
| /// Longest account name accepted, in characters. | ||
| pub const MAX_USER: usize = 64; | ||
| /// Check an account name: 1 to [`MAX_USER`] characters, none of them whitespace or control | ||
| /// characters, so it reads back from the account file exactly as written. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::BadUser`] otherwise. | ||
| pub fn check_user(user: &str) -> Result<(), AuthError> { | ||
| let length = user.chars().count(); | ||
| let visible = user.chars().all(|c| !c.is_whitespace() && !c.is_control()); | ||
| if (1..=MAX_USER).contains(&length) && visible { Ok(()) } else { Err(AuthError::BadUser) } | ||
| } | ||
| /// Who files written for the web service must belong to. `None` leaves them with whoever | ||
| /// writes them; a root-run command passes the service account's ids (see [`service_owner`]). | ||
| pub type Owner = Option<(nix::unistd::Uid, nix::unistd::Gid)>; | ||
| /// Run as root, the `gitv-web` service account, which must own everything it reads and | ||
| /// changes; otherwise (or without that account) `None`. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::Read`] if the account database can't be read. | ||
| pub fn service_owner() -> Result<Owner, AuthError> { | ||
| if !nix::unistd::geteuid().is_root() { | ||
| return Ok(None); | ||
| } | ||
| let user = nix::unistd::User::from_name("gitv-web") | ||
| .map_err(|e| AuthError::Read { path: PathBuf::from("/etc/passwd"), source: e.into() })?; | ||
| Ok(user.map(|u| (u.uid, u.gid))) | ||
| } | ||
| /// Give an open file to `owner`, through its handle. | ||
| fn hand_over(file: &fs::File, path: &Path, owner: Owner) -> Result<(), AuthError> { | ||
| let Some((uid, gid)) = owner else { return Ok(()) }; | ||
| nix::unistd::fchown(file, Some(uid), Some(gid)) | ||
| .map_err(|source| AuthError::Ownership { path: path.to_path_buf(), source }) | ||
| } | ||
| /// How [`Credentials`] are published. | ||
| enum Publish { | ||
| Replace, | ||
| OnlyIfAbsent, | ||
| } | ||
| /// A hidden name beside `path` that no other writer, in this process or another, will use. | ||
| fn unique_sibling(path: &Path, purpose: &str) -> Result<PathBuf, AuthError> { | ||
| let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); | ||
| let nonce = data_encoding::HEXLOWER.encode(&random_bytes::<8>()?); | ||
| Ok(path.with_file_name(format!(".{name}.{purpose}-{}-{nonce}", std::process::id()))) | ||
| } | ||
| /// Exclusive permission to change the account file, held by every writer (`setup`, | ||
| /// `password`, the web Account page) across processes, so their read-check-write steps can't | ||
| /// interleave. Released when dropped. | ||
| pub struct WriteLock { | ||
| _lock: nix::fcntl::Flock<fs::File>, | ||
| } | ||
| /// Take the account file's [`WriteLock`], waiting for any other writer to finish. The lock file | ||
| /// is given to `owner`, so a root-run command never leaves one the service can't open. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::Write`] if the lock file can't be opened or locked. | ||
| pub fn lock_for_writing(path: &Path, owner: Owner) -> Result<WriteLock, AuthError> { | ||
| let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); | ||
| let lock_path = path.with_file_name(format!(".{name}.lock")); | ||
| let file = fs::File::options() | ||
| .create(true) | ||
| .append(true) | ||
| .mode(0o600) | ||
| .open(&lock_path) | ||
| .map_err(|source| AuthError::Write { path: lock_path.clone(), source })?; | ||
| // The service must be able to take this lock too, to save password changes. | ||
| hand_over(&file, &lock_path, owner)?; | ||
| let lock = nix::fcntl::Flock::lock(file, nix::fcntl::FlockArg::LockExclusive) | ||
| .map_err(|(_, e)| AuthError::Write { path: lock_path, source: e.into() })?; | ||
| Ok(WriteLock { _lock: lock }) | ||
| } | ||
| /// Change the password, but only if the account is still the one that authorized the change: | ||
| /// `authorized` is the [fingerprint](Credentials::fingerprint) the caller checked. A reset or | ||
| /// another change in between makes this refuse rather than overwrite it. Returns the new | ||
| /// fingerprint. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::Changed`] if the account changed since it was checked, a password outside | ||
| /// the rules, or any error reading or writing the file. | ||
| pub fn change_password( | ||
| path: &Path, | ||
| authorized: [u8; 32], | ||
| new_password: &str, | ||
| owner: Owner, | ||
| ) -> Result<[u8; 32], AuthError> { | ||
| check_new_password(new_password)?; | ||
| let _lock = lock_for_writing(path, owner)?; | ||
| let mut credentials = Credentials::load(path)?; | ||
| if credentials.fingerprint() != authorized { | ||
| return Err(AuthError::Changed); | ||
| } | ||
| credentials.set_password(new_password)?; | ||
| credentials.save(path, owner)?; | ||
| Ok(credentials.fingerprint()) | ||
| } | ||
| /// Check an authenticator code and use it up, for good: the last accepted time step is kept in | ||
| /// a file beside the account (tied to the authenticator secret), read and written under the | ||
| /// [`WriteLock`], so a code works once across restarts and across processes. Returns whether | ||
| /// the code was accepted. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::Write`] or [`AuthError::Read`] if the record can't be read or written; the | ||
| /// code is then not accepted. | ||
| pub fn consume_code(path: &Path, credentials: &Credentials, code: &str, unix_seconds: u64) -> Result<bool, AuthError> { | ||
| let _lock = lock_for_writing(path, None)?; | ||
| let record = sibling(path, "used"); | ||
| let secret_id = data_encoding::HEXLOWER.encode(&Sha256::digest(&credentials.totp_secret)); | ||
| let last_step = match fs::read_to_string(&record) { | ||
| Ok(text) => text | ||
| .split_once(' ') | ||
| .filter(|(id, _)| *id == secret_id) | ||
| .and_then(|(_, step)| step.trim().parse::<u64>().ok()) | ||
| .unwrap_or(0), | ||
| Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, | ||
| Err(source) => return Err(AuthError::Read { path: record, source }), | ||
| }; | ||
| let Some(step) = credentials.verify_code(code, unix_seconds, last_step) else { return Ok(false) }; | ||
| write_replacing(&record, format!("{secret_id} {step}\n").as_bytes(), None)?; | ||
| Ok(true) | ||
| } | ||
| /// `.NAME.SUFFIX` beside `path`. | ||
| fn sibling(path: &Path, suffix: &str) -> PathBuf { | ||
| let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); | ||
| path.with_file_name(format!(".{name}.{suffix}")) | ||
| } | ||
| /// Write `contents` to `path` atomically through a unique temporary file, private to its | ||
| /// owner, replacing what's there. | ||
| fn write_replacing(path: &Path, contents: &[u8], owner: Owner) -> Result<(), AuthError> { | ||
| write_atomically(path, contents, owner, Publish::Replace) | ||
| } | ||
| /// Write through a unique temporary file, given to `owner` by handle before it's published, so | ||
| /// the published file is never anyone else's even for a moment. | ||
| fn write_atomically(path: &Path, contents: &[u8], owner: Owner, mode: Publish) -> Result<(), AuthError> { | ||
| let write_error = |source| AuthError::Write { path: path.to_path_buf(), source }; | ||
| let temporary = unique_sibling(path, "tmp")?; | ||
| // Created exclusively under a name no other writer uses; only then is it ours to clean up. | ||
| let mut file = | ||
| fs::File::options().write(true).create_new(true).mode(0o600).open(&temporary).map_err(write_error)?; | ||
| let written = (|| { | ||
| file.write_all(contents).map_err(write_error)?; | ||
| file.sync_all().map_err(write_error)?; | ||
| hand_over(&file, path, owner)?; | ||
| let flags = match mode { | ||
| Publish::Replace => nix::fcntl::RenameFlags::empty(), | ||
| // One atomic step that fails if the name exists, instead of a rename (which would | ||
| // replace it) or a link-then-unlink (whose second step could fail after success). | ||
| Publish::OnlyIfAbsent => nix::fcntl::RenameFlags::RENAME_NOREPLACE, | ||
| }; | ||
| nix::fcntl::renameat2(nix::fcntl::AT_FDCWD, &temporary, nix::fcntl::AT_FDCWD, path, flags).map_err( | ||
| |e| match e { | ||
| nix::errno::Errno::EEXIST => AuthError::AlreadySetUp(path.to_path_buf()), | ||
| e => write_error(e.into()), | ||
| }, | ||
| ) | ||
| })(); | ||
| if written.is_err() { | ||
| let _ = fs::remove_file(&temporary); | ||
| } | ||
| written | ||
| } | ||
| /// Where the account file lives: `$GITV_WEB_AUTH`, or `/var/lib/gitv-web/login`. | ||
| @@ -153,9 +333,11 @@ impl Credentials { | ||
| /// A new account with a new random TOTP secret. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::PasswordTooShort`]/[`AuthError::PasswordTooLong`] for a password outside the | ||
| /// rules, [`AuthError::Hash`] or [`AuthError::Random`] if hashing or randomness fails. | ||
| /// [`AuthError::BadUser`] for an unusable name, [`AuthError::PasswordTooShort`]/ | ||
| /// [`AuthError::PasswordTooLong`] for a password outside the rules, [`AuthError::Hash`] or | ||
| /// [`AuthError::Random`] if hashing or randomness fails. | ||
| pub fn new(user: &str, password: &str) -> Result<Credentials, AuthError> { | ||
| check_user(user)?; | ||
| check_new_password(password)?; | ||
| Ok(Credentials { | ||
| user: user.to_string(), | ||
| @@ -181,7 +363,7 @@ impl Credentials { | ||
| let field = |name: &str| { | ||
| text.lines().filter(|l| !l.starts_with('#')).find_map(|l| l.strip_prefix(name)?.strip_prefix('=')) | ||
| }; | ||
| let user = field("user").filter(|u| !u.is_empty()).ok_or("no user")?; | ||
| let user = field("user").filter(|u| check_user(u).is_ok()).ok_or("no valid user")?; | ||
| let password_hash = field("password").ok_or("no password")?; | ||
| PasswordHash::new(password_hash).map_err(|_| "the password hash isn't a PHC string")?; | ||
| let totp_secret = | ||
| @@ -192,31 +374,34 @@ impl Credentials { | ||
| Ok(Credentials { user: user.to_string(), password_hash: password_hash.to_string(), totp_secret }) | ||
| } | ||
| /// Write the account file atomically, readable and writable by its owner only. | ||
| /// Write the account file atomically, replacing any existing one, readable and writable by | ||
| /// its owner only, and given to `owner` before it's published. Hold a [`WriteLock`] around | ||
| /// the read-check-write that leads here. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::Write`] if the file or its temporary can't be written or renamed. | ||
| pub fn save(&self, path: &Path) -> Result<(), AuthError> { | ||
| let write_error = |source| AuthError::Write { path: path.to_path_buf(), source }; | ||
| let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); | ||
| let temporary = path.with_file_name(format!(".{name}.{}", std::process::id())); | ||
| let contents = format!( | ||
| /// [`AuthError::Write`] if the file can't be written or renamed, [`AuthError::Ownership`] | ||
| /// if it can't be handed over. | ||
| pub fn save(&self, path: &Path, owner: Owner) -> Result<(), AuthError> { | ||
| write_replacing(path, self.serialize().as_bytes(), owner) | ||
| } | ||
| /// Like [`Credentials::save`], but only if no account file exists yet, so two first-time | ||
| /// setups can't both succeed with different accounts. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::AlreadySetUp`] if an account file appeared, or as [`Credentials::save`]. | ||
| pub fn save_new(&self, path: &Path, owner: Owner) -> Result<(), AuthError> { | ||
| write_atomically(path, self.serialize().as_bytes(), owner, Publish::OnlyIfAbsent) | ||
| } | ||
| fn serialize(&self) -> String { | ||
| format!( | ||
| "# GITv web sign-in. Keep this private: anyone who can read it can attack the password offline.\n\ | ||
| user={}\npassword={}\ntotp={}\n", | ||
| self.user, | ||
| self.password_hash, | ||
| self.totp_secret_base32() | ||
| ); | ||
| let written = (|| { | ||
| let mut file = fs::File::options().write(true).create_new(true).mode(0o600).open(&temporary)?; | ||
| file.write_all(contents.as_bytes())?; | ||
| file.sync_all()?; | ||
| fs::rename(&temporary, path) | ||
| })(); | ||
| if written.is_err() { | ||
| let _ = fs::remove_file(&temporary); | ||
| } | ||
| written.map_err(write_error) | ||
| ) | ||
| } | ||
| /// The account name. | ||
| @@ -450,7 +635,7 @@ mod tests { | ||
| let dir = scratch("round-trip"); | ||
| let path = dir.join("login"); | ||
| let credentials = account(); | ||
| credentials.save(&path).unwrap(); | ||
| credentials.save(&path, None).unwrap(); | ||
| let loaded = Credentials::load(&path).unwrap(); | ||
| assert_eq!(loaded.fingerprint(), credentials.fingerprint()); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| @@ -460,7 +645,7 @@ mod tests { | ||
| fn is_private_to_its_owner() { | ||
| let dir = scratch("private"); | ||
| let path = dir.join("login"); | ||
| account().save(&path).unwrap(); | ||
| account().save(&path, None).unwrap(); | ||
| assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| @@ -490,6 +675,136 @@ mod tests { | ||
| } | ||
| } | ||
| mod writers { | ||
| use super::*; | ||
| fn scratch(name: &str) -> PathBuf { | ||
| let dir = std::env::temp_dir().join(format!("gitv-auth-w-{name}-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| #[test] | ||
| fn a_change_authorized_against_an_older_account_is_refused() { | ||
| let dir = scratch("stale"); | ||
| let path = dir.join("login"); | ||
| let before = account(); | ||
| before.save(&path, None).unwrap(); | ||
| let authorized = before.fingerprint(); | ||
| // An operator resets the account in between. | ||
| let reset = Credentials::new("Um9i", "the operator's reset").unwrap(); | ||
| reset.save(&path, None).unwrap(); | ||
| let result = change_password(&path, authorized, "the user's new password", None); | ||
| assert!(matches!(result, Err(AuthError::Changed)), "the stale change went through"); | ||
| assert!( | ||
| Credentials::load(&path).unwrap().verify_password("the operator's reset"), | ||
| "the reset was overwritten" | ||
| ); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn a_current_change_is_saved() { | ||
| let dir = scratch("current"); | ||
| let path = dir.join("login"); | ||
| let credentials = account(); | ||
| credentials.save(&path, None).unwrap(); | ||
| let fingerprint = change_password(&path, credentials.fingerprint(), "a fresh password", None).unwrap(); | ||
| let saved = Credentials::load(&path).unwrap(); | ||
| assert!(saved.verify_password("a fresh password") && saved.fingerprint() == fingerprint); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn save_new_never_replaces_an_account() { | ||
| let dir = scratch("new"); | ||
| let path = dir.join("login"); | ||
| account().save_new(&path, None).unwrap(); | ||
| let second = Credentials::new("Um9i", "a different account").unwrap(); | ||
| assert!(matches!(second.save_new(&path, None), Err(AuthError::AlreadySetUp(_)))); | ||
| assert!(Credentials::load(&path).unwrap().verify_password("correct horse battery")); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn concurrent_saves_in_one_process_all_land_whole() { | ||
| let dir = scratch("concurrent"); | ||
| let path = dir.join("login"); | ||
| let saves: Vec<_> = (0..8) | ||
| .map(|_| { | ||
| let path = path.clone(); | ||
| std::thread::spawn(move || account().save(&path, None)) | ||
| }) | ||
| .collect(); | ||
| for save in saves { | ||
| save.join().unwrap().unwrap(); | ||
| } | ||
| assert!(Credentials::load(&path).is_ok()); | ||
| let leftovers: Vec<_> = fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect(); | ||
| assert_eq!(leftovers, [std::ffi::OsString::from("login")], "temporaries were left behind"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| } | ||
| mod users { | ||
| use super::*; | ||
| #[test] | ||
| fn ordinary_names_are_accepted() { | ||
| for user in ["Um9i", "ada", "a.b-c_d", &"x".repeat(MAX_USER)] { | ||
| assert!(check_user(user).is_ok(), "{user}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn names_that_would_not_read_back_are_refused() { | ||
| for user in ["", "two words", "line\nbreak", "tab\t", " leading", &"x".repeat(MAX_USER + 1), "bell\u{7}"] { | ||
| assert!(matches!(check_user(user), Err(AuthError::BadUser)), "{user:?}"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn an_account_with_a_bad_name_is_never_created() { | ||
| assert!(matches!(Credentials::new("", "a long enough password"), Err(AuthError::BadUser))); | ||
| } | ||
| } | ||
| mod codes_across_processes { | ||
| use super::*; | ||
| fn scratch(name: &str) -> PathBuf { | ||
| let dir = std::env::temp_dir().join(format!("gitv-auth-c-{name}-{}", std::process::id())); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| fs::create_dir_all(&dir).unwrap(); | ||
| dir | ||
| } | ||
| #[test] | ||
| fn a_code_is_accepted_once_even_by_a_fresh_reader() { | ||
| let dir = scratch("once"); | ||
| let path = dir.join("login"); | ||
| account().save(&path, None).unwrap(); | ||
| assert!(consume_code(&path, &account(), "287082", 59).unwrap()); | ||
| // Nothing in memory carries over: the record on disk refuses it. | ||
| assert!(!consume_code(&path, &account(), "287082", 59).unwrap()); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn a_new_authenticator_secret_starts_afresh() { | ||
| let dir = scratch("fresh"); | ||
| let path = dir.join("login"); | ||
| account().save(&path, None).unwrap(); | ||
| assert!(consume_code(&path, &account(), "287082", 59).unwrap()); | ||
| let mut replaced = account(); | ||
| replaced.totp_secret = b"another secret of twenty".to_vec(); | ||
| let code = format!("{:06}", totp_code(&replaced.totp_secret, 1)); | ||
| assert!(consume_code(&path, &replaced, &code, 59).unwrap(), "the old secret's record blocked the new one"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| } | ||
| mod otpauth_uri { | ||
| use super::*; | ||
+249−107
| @@ -6,13 +6,14 @@ | ||
| //! or with `gitv-web password`, ends every other session. | ||
| use std::collections::HashMap; | ||
| use std::os::unix::fs::{DirBuilderExt, MetadataExt}; | ||
| use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; | ||
| use std::os::unix::process::CommandExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::sync::{Arc, Mutex}; | ||
| use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; | ||
| use axum::Extension; | ||
| use axum::extract::{Form, RawQuery, Request, State}; | ||
| use axum::extract::{Form, FromRequest, RawQuery, Request, State}; | ||
| use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; | ||
| use axum::middleware::Next; | ||
| use axum::response::{IntoResponse, Response}; | ||
| @@ -44,6 +45,34 @@ pub struct Login { | ||
| /// Sessions by the SHA-256 of their token: the token itself is never stored. | ||
| sessions: Mutex<HashMap<[u8; 32], Session>>, | ||
| guard: Mutex<Guard>, | ||
| /// Password checks running at once. Argon2 is deliberately costly in memory and time, and | ||
| /// the sign-in form is open to anyone, so a burst of guesses queues here. | ||
| hashing: Arc<tokio::sync::Semaphore>, | ||
| /// Sign-in attempts admitted at once, waiting or running. Past this, more are turned away | ||
| /// before their bodies are even read, so a flood can't pile up passwords in memory. | ||
| admission: Arc<tokio::sync::Semaphore>, | ||
| /// Password checks started, for tests to confirm the bound holds. | ||
| #[cfg(test)] | ||
| checks_started: std::sync::atomic::AtomicUsize, | ||
| } | ||
| /// Sign-in attempts admitted at once (see [`Login::admission`]). | ||
| const ADMITTED_ATTEMPTS: usize = 32; | ||
| /// Largest sign-in or account form accepted, in bytes: far more than the fields need. | ||
| pub const FORM_LIMIT: usize = 8 * 1024; | ||
| /// Password checks allowed to run at once. | ||
| const CONCURRENT_CHECKS: usize = 2; | ||
| /// What checking a password and code found. | ||
| enum Checked { | ||
| Right, | ||
| Wrong, | ||
| /// Sign-in was locked by the time this attempt's turn came. | ||
| Locked(Duration), | ||
| /// The record of used codes couldn't be read or written, so no code can be trusted. | ||
| Unavailable, | ||
| } | ||
| /// The account file as last read, and how to tell whether it has changed since. | ||
| @@ -65,8 +94,6 @@ struct Session { | ||
| struct Guard { | ||
| failures: u32, | ||
| locked_until: Option<Instant>, | ||
| /// The last TOTP step used, so a code works once. | ||
| last_step: u64, | ||
| } | ||
| /// What [`require_login`] hands a signed-in request. | ||
| @@ -79,12 +106,20 @@ pub struct SignedIn { | ||
| impl Login { | ||
| /// Sign-in backed by the account file at [`auth_path`]. | ||
| pub fn new() -> Arc<Login> { | ||
| Arc::new(Login { | ||
| path: auth_path(), | ||
| Arc::new(Login::at(auth_path())) | ||
| } | ||
| fn at(path: PathBuf) -> Login { | ||
| Login { | ||
| path, | ||
| loaded: Mutex::new(None), | ||
| sessions: Mutex::new(HashMap::new()), | ||
| guard: Mutex::new(Guard::default()), | ||
| }) | ||
| hashing: Arc::new(tokio::sync::Semaphore::new(CONCURRENT_CHECKS)), | ||
| admission: Arc::new(tokio::sync::Semaphore::new(ADMITTED_ATTEMPTS)), | ||
| #[cfg(test)] | ||
| checks_started: std::sync::atomic::AtomicUsize::new(0), | ||
| } | ||
| } | ||
| /// The account, re-read whenever the file changes (so `gitv-web password` takes effect | ||
| @@ -137,12 +172,12 @@ impl Login { | ||
| guard.locked_until.and_then(|until| until.checked_duration_since(Instant::now())) | ||
| } | ||
| fn last_step(&self) -> u64 { | ||
| self.guard.lock().unwrap_or_else(|e| e.into_inner()).last_step | ||
| #[cfg(test)] | ||
| fn record_failure(&self) { | ||
| Self::fail(&mut self.guard.lock().unwrap_or_else(|e| e.into_inner())); | ||
| } | ||
| fn record_failure(&self) { | ||
| let mut guard = self.guard.lock().unwrap_or_else(|e| e.into_inner()); | ||
| fn fail(guard: &mut Guard) { | ||
| guard.failures += 1; | ||
| // The first FREE_FAILURES are free; each one after locks for longer. | ||
| if let Some(over) = guard.failures.checked_sub(FREE_FAILURES + 1) { | ||
| @@ -151,32 +186,58 @@ impl Login { | ||
| } | ||
| } | ||
| fn record_success(&self, step: u64) { | ||
| let mut guard = self.guard.lock().unwrap_or_else(|e| e.into_inner()); | ||
| guard.failures = 0; | ||
| guard.locked_until = None; | ||
| guard.last_step = guard.last_step.max(step); | ||
| } | ||
| /// Check a password and authenticator code, counting failures and using up the code. | ||
| async fn check(&self, credentials: &Arc<Credentials>, user: Option<String>, password: String, code: &str) -> bool { | ||
| // Argon2 is deliberately slow: off the async threads. | ||
| let creds = Arc::clone(credentials); | ||
| let password_ok = tokio::task::spawn_blocking(move || { | ||
| /// | ||
| /// Waits for one of [`CONCURRENT_CHECKS`] slots first, then looks at the lock again, since | ||
| /// failures may have locked sign-in while this attempt waited. The hashing job holds its | ||
| /// slot until it has recorded its result, so no waiting attempt can start between a failure | ||
| /// and the lock it causes, and a cancelled request still counts. | ||
| async fn check( | ||
| self: &Arc<Self>, | ||
| credentials: &Arc<Credentials>, | ||
| user: Option<String>, | ||
| password: String, | ||
| code: &str, | ||
| ) -> Checked { | ||
| let Ok(permit) = Arc::clone(&self.hashing).acquire_owned().await else { return Checked::Wrong }; | ||
| if let Some(wait) = self.locked_for() { | ||
| return Checked::Locked(wait); | ||
| } | ||
| #[cfg(test)] | ||
| self.checks_started.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| let (login, creds, code) = (Arc::clone(self), Arc::clone(credentials), code.to_string()); | ||
| tokio::task::spawn_blocking(move || { | ||
| let _permit = permit; | ||
| let user_ok = user.is_none_or(|u| creds.user_matches(&u)); | ||
| creds.verify_password(&password) && user_ok | ||
| let password_ok = creds.verify_password(&password) && user_ok; | ||
| login.settle(&creds, password_ok, &code) | ||
| }) | ||
| .await | ||
| .unwrap_or(false); | ||
| let step = credentials.verify_code(code, unix_now(), self.last_step()); | ||
| match step.filter(|_| password_ok) { | ||
| Some(step) => { | ||
| self.record_success(step); | ||
| true | ||
| } | ||
| None => { | ||
| self.record_failure(); | ||
| false | ||
| .unwrap_or(Checked::Wrong) | ||
| } | ||
| /// Record a check's result. The code is checked and used up in one step, under the account | ||
| /// file's lock and recorded on disk, so it works once: across simultaneous requests, | ||
| /// restarts and processes alike. | ||
| fn settle(&self, credentials: &Credentials, password_ok: bool, code: &str) -> Checked { | ||
| let mut guard = self.guard.lock().unwrap_or_else(|e| e.into_inner()); | ||
| let code_ok = password_ok | ||
| && match gitv::auth::consume_code(&self.path, credentials, code, unix_now()) { | ||
| Ok(accepted) => accepted, | ||
| Err(error) => { | ||
| eprintln!("gitv-web: checking an authenticator code: {error}"); | ||
| return Checked::Unavailable; | ||
| } | ||
| }; | ||
| if code_ok { | ||
| guard.failures = 0; | ||
| guard.locked_until = None; | ||
| Checked::Right | ||
| } else { | ||
| Self::fail(&mut guard); | ||
| match guard.locked_until.and_then(|until| until.checked_duration_since(Instant::now())) { | ||
| Some(wait) => Checked::Locked(wait), | ||
| None => Checked::Wrong, | ||
| } | ||
| } | ||
| } | ||
| @@ -198,11 +259,6 @@ fn unix_now() -> u64 { | ||
| SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) | ||
| } | ||
| /// Paths anyone may load: the sign-in page and what it needs to look right. | ||
| fn is_public(path: &str) -> bool { | ||
| matches!(path, "/login" | "/style.css" | "/favicon.svg") || path.starts_with("/fonts/") | ||
| } | ||
| /// Where to go after signing in: a path on this site, never another site (`//evil.example`). | ||
| fn safe_next(next: &str) -> &str { | ||
| let local = next.starts_with('/') && !next.starts_with("//") && !next.starts_with("/\\"); | ||
| @@ -236,11 +292,10 @@ fn not_set_up() -> Response { | ||
| ) | ||
| } | ||
| /// Let signed-in requests through; send everyone else to the sign-in page. | ||
| /// Let signed-in requests through; send everyone else to the sign-in page. This wraps every | ||
| /// route except the few public ones, which are routed separately by exact path, so no prefix | ||
| /// rule can ever make a repository page public. | ||
| pub async fn require_login(State(login): State<Arc<Login>>, mut request: Request, next: Next) -> Response { | ||
| if is_public(request.uri().path()) { | ||
| return next.run(request).await; | ||
| } | ||
| let credentials = match login.credentials() { | ||
| Ok(credentials) => credentials, | ||
| Err(AuthError::NotSetUp(_)) => return not_set_up(), | ||
| @@ -322,10 +377,21 @@ pub async fn sign_in_form(State(login): State<Arc<Login>>, headers: HeaderMap, R | ||
| sign_in_page(StatusCode::OK, &next, "") | ||
| } | ||
| pub async fn sign_in(State(login): State<Arc<Login>>, Form(form): Form<SignInForm>) -> Response { | ||
| pub async fn sign_in(State(login): State<Arc<Login>>, request: Request) -> Response { | ||
| // Turned away before the body is read when too many attempts are already waiting. | ||
| let Ok(_admitted) = Arc::clone(&login.admission).try_acquire_owned() else { | ||
| return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, "/", "Sign-in is busy. Try again in a moment."); | ||
| }; | ||
| if let Some(wait) = login.locked_for() { | ||
| return locked_page(wait); | ||
| } | ||
| // Too large (over FORM_LIMIT) or malformed: refused with the rejection's own status. | ||
| let form = match Form::<SignInForm>::from_request(request, &()).await { | ||
| Ok(Form(form)) => form, | ||
| Err(rejection) => { | ||
| return sign_in_page(rejection.status(), "/", "That sign-in form wasn’t accepted. Try again."); | ||
| } | ||
| }; | ||
| let credentials = match login.credentials() { | ||
| Ok(credentials) => credentials, | ||
| Err(AuthError::NotSetUp(_)) => return not_set_up(), | ||
| @@ -334,12 +400,16 @@ pub async fn sign_in(State(login): State<Arc<Login>>, Form(form): Form<SignInFor | ||
| return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now."); | ||
| } | ||
| }; | ||
| if !login.check(&credentials, Some(form.user), form.password, &form.code).await { | ||
| match login.check(&credentials, Some(form.user), form.password, &form.code).await { | ||
| Checked::Right => {} | ||
| Checked::Locked(wait) => return locked_page(wait), | ||
| Checked::Unavailable => { | ||
| return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now."); | ||
| } | ||
| // One message for every mistake, so a guess reveals nothing about which part was wrong. | ||
| return match login.locked_for() { | ||
| Some(wait) => locked_page(wait), | ||
| None => sign_in_page(StatusCode::UNAUTHORIZED, &form.next, "That username, password or code isn’t right."), | ||
| }; | ||
| Checked::Wrong => { | ||
| return sign_in_page(StatusCode::UNAUTHORIZED, &form.next, "That username, password or code isn’t right."); | ||
| } | ||
| } | ||
| match login.start_session(credentials.fingerprint()) { | ||
| Ok(cookie) => redirect(safe_next(&form.next), Some(cookie)), | ||
| @@ -449,20 +519,32 @@ pub async fn change_password( | ||
| if let Err(error) = check_new_password(&form.new) { | ||
| return refuse(StatusCode::BAD_REQUEST, &format!("Choose a different new password: {error}.")); | ||
| } | ||
| if !login.check(&credentials, None, form.current, &form.code).await { | ||
| return refuse(StatusCode::UNAUTHORIZED, "That current password or code isn’t right."); | ||
| } | ||
| let path = login.path.clone(); | ||
| let new = form.new; | ||
| let saved = tokio::task::spawn_blocking(move || { | ||
| let mut updated = Credentials::load(&path)?; | ||
| updated.set_password(&new)?; | ||
| updated.save(&path)?; | ||
| Ok::<_, AuthError>(updated.fingerprint()) | ||
| }) | ||
| .await; | ||
| match login.check(&credentials, None, form.current, &form.code).await { | ||
| Checked::Right => {} | ||
| Checked::Locked(wait) => { | ||
| let minutes = wait.as_secs().div_ceil(60).max(1); | ||
| return refuse( | ||
| StatusCode::TOO_MANY_REQUESTS, | ||
| &format!("Too many failed attempts. Try again in {minutes} minutes."), | ||
| ); | ||
| } | ||
| Checked::Wrong => return refuse(StatusCode::UNAUTHORIZED, "That current password or code isn’t right."), | ||
| Checked::Unavailable => { | ||
| return refuse(StatusCode::SERVICE_UNAVAILABLE, "Changing the password is unavailable right now."); | ||
| } | ||
| } | ||
| // Saved only if the account is still the one just checked: an operator's reset in the | ||
| // meantime wins, rather than being overwritten by a change authorized against the old one. | ||
| let (path, authorized, new) = (login.path.clone(), credentials.fingerprint(), form.new); | ||
| let saved = tokio::task::spawn_blocking(move || gitv::auth::change_password(&path, authorized, &new, None)).await; | ||
| let fingerprint = match saved { | ||
| Ok(Ok(fingerprint)) => fingerprint, | ||
| Ok(Err(AuthError::Changed)) => { | ||
| return refuse( | ||
| StatusCode::CONFLICT, | ||
| "The account was changed while you were doing this, so nothing was saved. Sign in again.", | ||
| ); | ||
| } | ||
| Ok(Err(error)) => { | ||
| eprintln!("gitv-web: changing the password: {error}"); | ||
| return refuse(StatusCode::INTERNAL_SERVER_ERROR, "The password couldn’t be saved. It hasn’t changed."); | ||
| @@ -493,15 +575,26 @@ pub async fn change_password( | ||
| /// [`AuthError::AlreadySetUp`] if the account exists and `force` isn't set, or any error from | ||
| /// creating and saving it. | ||
| pub fn setup(user: &str, force: bool) -> Result<(), AuthError> { | ||
| // A bad name is refused before anything is made, so --force can't swap a working account | ||
| // for one that won't load. | ||
| gitv::auth::check_user(user)?; | ||
| let path = auth_path(); | ||
| // Run as root, everything is made for the service account, which must read the account | ||
| // and take its lock to save password changes. | ||
| let owner = gitv::auth::service_owner()?; | ||
| prepare_directory(&path, owner)?; | ||
| let _lock = gitv::auth::lock_for_writing(&path, owner)?; | ||
| if path.exists() && !force { | ||
| return Err(AuthError::AlreadySetUp(path)); | ||
| } | ||
| prepare_directory(&path)?; | ||
| let password = generate_password()?; | ||
| let credentials = Credentials::new(user, &password)?; | ||
| credentials.save(&path)?; | ||
| give_to_service(&path); | ||
| // Without --force, publishing itself refuses to replace an account, whatever the lock. | ||
| if force { | ||
| credentials.save(&path, owner)? | ||
| } else { | ||
| credentials.save_new(&path, owner)? | ||
| } | ||
| println!("Web sign-in is set up for {user} in {}.\n", path.display()); | ||
| println!(" Password: {password}"); | ||
| println!(" 2FA secret: {}\n", credentials.totp_secret_base32()); | ||
| @@ -520,7 +613,7 @@ pub fn setup(user: &str, force: bool) -> Result<(), AuthError> { | ||
| /// [`AuthError::NotSetUp`] before `setup`, a password outside the rules, or a mismatch. | ||
| pub fn change_password_at_terminal() -> Result<(), String> { | ||
| let path = auth_path(); | ||
| let mut credentials = Credentials::load(&path).map_err(|e| e.to_string())?; | ||
| let credentials = Credentials::load(&path).map_err(|e| e.to_string())?; | ||
| let first = rpassword::prompt_password(format!("New web password for {}: ", credentials.user())) | ||
| .map_err(|e| format!("couldn't read the password (run this in a terminal): {e}"))?; | ||
| check_new_password(&first).map_err(|e| e.to_string())?; | ||
| @@ -528,36 +621,59 @@ pub fn change_password_at_terminal() -> Result<(), String> { | ||
| if first != second { | ||
| return Err("the passwords differ; nothing changed".into()); | ||
| } | ||
| credentials.set_password(&first).map_err(|e| e.to_string())?; | ||
| credentials.save(&path).map_err(|e| e.to_string())?; | ||
| give_to_service(&path); | ||
| // Typing took a while: apply the change only to the account that was loaded before it. | ||
| let owner = gitv::auth::service_owner().map_err(|e| e.to_string())?; | ||
| gitv::auth::change_password(&path, credentials.fingerprint(), &first, owner).map_err(|e| e.to_string())?; | ||
| println!("Password changed for {}. Every session has been signed out.", credentials.user()); | ||
| Ok(()) | ||
| } | ||
| /// Create the account file's directory if needed, private to its owner. | ||
| fn prepare_directory(path: &Path) -> Result<(), AuthError> { | ||
| let Some(directory) = path.parent().filter(|d| !d.as_os_str().is_empty()) else { return Ok(()) }; | ||
| /// Create the account file's directory if needed, private to its owner and given to `owner`. | ||
| fn prepare_directory(path: &Path, owner: gitv::auth::Owner) -> Result<(), AuthError> { | ||
| let directory = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); | ||
| let write_error = |source| AuthError::Write { path: directory.to_owned(), source }; | ||
| // Only hand over a leaf we created or the dedicated service directory. An override | ||
| // can point into a shared directory whose ownership must stay with its administrator. | ||
| let mut created = false; | ||
| if !directory.exists() { | ||
| std::fs::DirBuilder::new() | ||
| .recursive(true) | ||
| .mode(0o700) | ||
| .create(directory) | ||
| .map_err(|source| AuthError::Write { path: directory.to_path_buf(), source })?; | ||
| give_to_service(directory); | ||
| } | ||
| Ok(()) | ||
| } | ||
| /// Run as root, hand a file to the `gitv-web` service account so the server can read it (and | ||
| /// save password changes). Without that account, or as anyone else, leave it as is. | ||
| fn give_to_service(path: &Path) { | ||
| if !nix::unistd::geteuid().is_root() { | ||
| return; | ||
| if let Some(parent) = directory.parent().filter(|p| !p.as_os_str().is_empty()) { | ||
| std::fs::DirBuilder::new().recursive(true).mode(0o700).create(parent).map_err(write_error)?; | ||
| } | ||
| match std::fs::DirBuilder::new().mode(0o700).create(directory) { | ||
| Ok(()) => created = true, | ||
| Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} | ||
| Err(e) => return Err(write_error(e)), | ||
| } | ||
| } | ||
| if let Ok(Some(user)) = nix::unistd::User::from_name("gitv-web") { | ||
| let _ = std::os::unix::fs::chown(path, Some(user.uid.as_raw()), Some(user.gid.as_raw())); | ||
| if let Some((uid, gid)) = owner { | ||
| if created || directory == Path::new("/var/lib/gitv-web") { | ||
| let dir = std::fs::File::options() | ||
| .read(true) | ||
| .custom_flags(nix::libc::O_DIRECTORY | nix::libc::O_NOFOLLOW) | ||
| .open(directory) | ||
| .map_err(write_error)?; | ||
| nix::unistd::fchown(&dir, Some(uid), Some(gid)) | ||
| .map_err(|source| AuthError::Ownership { path: directory.to_owned(), source })?; | ||
| } | ||
| // Check as the service, including traversal of ancestors and filesystem ACLs. | ||
| let accessible = std::process::Command::new("/usr/bin/test") | ||
| .arg("-w") | ||
| .arg(directory) | ||
| .arg("-a") | ||
| .arg("-x") | ||
| .arg(directory) | ||
| .uid(uid.as_raw()) | ||
| .gid(gid.as_raw()) | ||
| .status() | ||
| .map_err(write_error)?; | ||
| if !accessible.success() { | ||
| return Err(write_error(std::io::Error::new( | ||
| std::io::ErrorKind::PermissionDenied, | ||
| "gitv-web needs write and search access to the account directory and search access to its parents", | ||
| ))); | ||
| } | ||
| } | ||
| Ok(()) | ||
| } | ||
| #[cfg(test)] | ||
| @@ -580,30 +696,52 @@ mod tests { | ||
| } | ||
| } | ||
| mod is_public { | ||
| use super::*; | ||
| #[test] | ||
| fn covers_only_the_sign_in_page_and_its_assets() { | ||
| for path in ["/login", "/style.css", "/favicon.svg", "/fonts/text.woff2"] { | ||
| assert!(is_public(path), "{path}"); | ||
| } | ||
| for path in ["/", "/account", "/logout", "/ada/site/tree", "/login/../ada", "/loginx"] { | ||
| assert!(!is_public(path), "{path}"); | ||
| } | ||
| } | ||
| } | ||
| mod lock { | ||
| use super::*; | ||
| fn login() -> Login { | ||
| Login { | ||
| path: PathBuf::new(), | ||
| loaded: Mutex::new(None), | ||
| sessions: Mutex::new(HashMap::new()), | ||
| guard: Mutex::new(Guard::default()), | ||
| Login::at(PathBuf::new()) | ||
| } | ||
| #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| async fn a_burst_of_guesses_hashes_only_until_the_lock_falls() { | ||
| let login = Arc::new(login()); | ||
| let credentials = Arc::new(Credentials::new("Um9i", "the real password").unwrap()); | ||
| let guesses: Vec<_> = (0..20) | ||
| .map(|_| { | ||
| let (login, credentials) = (Arc::clone(&login), Arc::clone(&credentials)); | ||
| tokio::spawn(async move { login.check(&credentials, None, "a wrong guess".into(), "123456").await }) | ||
| }) | ||
| .collect(); | ||
| for guess in guesses { | ||
| let _ = guess.await; | ||
| } | ||
| // Five free failures lock sign-in on the sixth; at most the other slot's check was | ||
| // already running then. Everyone still waiting sees the lock and hashes nothing. | ||
| let started = login.checks_started.load(std::sync::atomic::Ordering::Relaxed); | ||
| assert!(started <= FREE_FAILURES as usize + CONCURRENT_CHECKS, "{started} password checks ran"); | ||
| } | ||
| #[tokio::test] | ||
| async fn a_full_queue_turns_sign_ins_away_unread() { | ||
| // A real account, so an attempt that got through would be judged (and fail). | ||
| let dir = std::env::temp_dir().join(format!("gitv-web-admission-{}", std::process::id())); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| std::fs::create_dir_all(&dir).unwrap(); | ||
| Credentials::new("Um9i", "the real password").unwrap().save(&dir.join("login"), None).unwrap(); | ||
| let login = Arc::new(Login::at(dir.join("login"))); | ||
| let _taken: Vec<_> = | ||
| (0..ADMITTED_ATTEMPTS).map(|_| Arc::clone(&login.admission).try_acquire_owned().unwrap()).collect(); | ||
| let request = Request::builder() | ||
| .method("POST") | ||
| .uri("/login") | ||
| .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| .body(axum::body::Body::from("user=Um9i&password=guess&code=123456")) | ||
| .unwrap(); | ||
| let response = sign_in(State(Arc::clone(&login)), request).await; | ||
| assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); | ||
| assert_eq!(login.guard.lock().unwrap().failures, 0, "the attempt was judged anyway"); | ||
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| @@ -631,7 +769,11 @@ mod tests { | ||
| fn success_clears_it() { | ||
| let login = login(); | ||
| (0..=FREE_FAILURES).for_each(|_| login.record_failure()); | ||
| login.record_success(1); | ||
| { | ||
| let mut guard = login.guard.lock().unwrap(); | ||
| guard.failures = 0; | ||
| guard.locked_until = None; | ||
| } | ||
| assert!(login.locked_for().is_none()); | ||
| } | ||
| } | ||
| @@ -17,6 +17,7 @@ use std::sync::{Arc, LazyLock, Mutex}; | ||
| use std::time::{SystemTime, UNIX_EPOCH}; | ||
| use axum::Router; | ||
| use axum::extract::DefaultBodyLimit; | ||
| use axum::extract::{Path, RawQuery}; | ||
| use axum::http::{StatusCode, header}; | ||
| use axum::response::{IntoResponse, Redirect, Response}; | ||
| @@ -1444,16 +1445,25 @@ fn serve(port: u16) -> Result<(), String> { | ||
| // Load the syntax definitions now rather than on the first visitor's request. | ||
| tokio::task::spawn_blocking(render::warm_up); | ||
| let login = login::Login::new(); | ||
| let app = Router::new() | ||
| .route("/", get(|| blocking(view_index))) | ||
| // Anyone may load these exact paths: the sign-in page and what it needs to look right. | ||
| let public = Router::new() | ||
| .route("/style.css", get(|| async { stylesheet() })) | ||
| .route("/favicon.svg", get(|| async { static_file("image/svg+xml", FAVICON.as_bytes()) })) | ||
| .route("/fonts/display.woff2", get(|| async { static_file("font/woff2", FONT_DISPLAY) })) | ||
| .route("/fonts/text.woff2", get(|| async { static_file("font/woff2", FONT_TEXT) })) | ||
| .route("/fonts/mono.woff2", get(|| async { static_file("font/woff2", FONT_MONO) })) | ||
| .route("/login", get(login::sign_in_form).post(login::sign_in)) | ||
| .route("/logout", post(login::sign_out)) | ||
| .route("/account", get(login::account).post(login::change_password)) | ||
| .route( | ||
| "/login", | ||
| get(login::sign_in_form).post(login::sign_in).layer(DefaultBodyLimit::max(login::FORM_LIMIT)), | ||
| ); | ||
| // Everything else, including any path not matched above, needs a session. | ||
| let private = Router::new() | ||
| .route("/", get(|| blocking(view_index))) | ||
| .route("/logout", post(login::sign_out).layer(DefaultBodyLimit::max(login::FORM_LIMIT))) | ||
| .route( | ||
| "/account", | ||
| get(login::account).post(login::change_password).layer(DefaultBodyLimit::max(login::FORM_LIMIT)), | ||
| ) | ||
| .route( | ||
| "/{owner}/{name}", | ||
| get(|Path((o, n)): Path<(String, String)>, RawQuery(q): RawQuery| { | ||
| @@ -1467,9 +1477,8 @@ fn serve(port: u16) -> Result<(), String> { | ||
| }), | ||
| ) | ||
| .fallback(|| async { View::Missing }) | ||
| // Every route above, and the fallback, sits behind the sign-in check. | ||
| .layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::require_login)) | ||
| .with_state(login); | ||
| .layer(axum::middleware::from_fn_with_state(Arc::clone(&login), login::require_login)); | ||
| let app = public.merge(private).with_state(login); | ||
| let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)) | ||
| .await | ||
| .map_err(|e| format!("can't listen on port {port}: {e}"))?; | ||
+117−1
| @@ -14,6 +14,8 @@ fn repos() -> &'static PathBuf { | ||
| REPOS.get_or_init(|| { | ||
| let host = Host::new("auth-host"); | ||
| assert!(host.admin(&["create", "ada", "notes"]).status.success()); | ||
| // An owner named like a public asset folder: its repositories are still private. | ||
| assert!(host.admin(&["create", "fonts", "notes"]).status.success()); | ||
| host.repos.clone() | ||
| }) | ||
| } | ||
| @@ -43,6 +45,15 @@ mod signed_out { | ||
| } | ||
| } | ||
| #[test] | ||
| fn an_owner_named_like_an_asset_folder_stays_private() { | ||
| let s = Server::start_signed_out(repos()); | ||
| for path in ["/fonts/notes/tree", "/fonts/notes", "/fonts/notes/log", "/fonts/text.woff2/x"] { | ||
| let response = s.get_signed_out(path); | ||
| assert_eq!(response.status, 303, "{path} was served signed out"); | ||
| } | ||
| } | ||
| #[test] | ||
| fn writes_are_refused_before_anything_else() { | ||
| let s = Server::start_signed_out(repos()); | ||
| @@ -120,6 +131,65 @@ mod signing_in { | ||
| assert_eq!(sign_in(&s, "Um9i", &s.account.password, &code, "/").status, 401); | ||
| } | ||
| #[test] | ||
| fn a_code_sent_by_many_requests_at_once_lets_one_in() { | ||
| let s = Server::start_signed_out(repos()); | ||
| let code = s.account.code(0); | ||
| let statuses: Vec<u16> = std::thread::scope(|scope| { | ||
| let attempts: Vec<_> = | ||
| (0..8).map(|_| scope.spawn(|| sign_in(&s, "Um9i", &s.account.password, &code, "/").status)).collect(); | ||
| attempts.into_iter().map(|a| a.join().unwrap()).collect() | ||
| }); | ||
| assert_eq!(statuses.iter().filter(|s| **s == 303).count(), 1, "{statuses:?}"); | ||
| } | ||
| #[test] | ||
| fn a_burst_of_guesses_meets_the_lock() { | ||
| let s = Server::start_signed_out(repos()); | ||
| let statuses: Vec<u16> = std::thread::scope(|scope| { | ||
| let attempts: Vec<_> = | ||
| (0..20).map(|_| scope.spawn(|| sign_in(&s, "Um9i", "a wrong guess", "123456", "/").status)).collect(); | ||
| attempts.into_iter().map(|a| a.join().unwrap()).collect() | ||
| }); | ||
| // Five free failures, plus at most the two checks already hashing when the lock fell. | ||
| let judged = statuses.iter().filter(|s| **s == 401).count(); | ||
| assert!(judged <= 5 + 2, "{judged} guesses were checked: {statuses:?}"); | ||
| assert!(statuses.iter().all(|s| *s == 401 || *s == 429), "{statuses:?}"); | ||
| } | ||
| #[test] | ||
| fn a_used_code_stays_used_after_a_restart() { | ||
| let first = Server::start_signed_out(repos()); | ||
| let code = first.account.code(0); | ||
| assert_eq!(sign_in(&first, "Um9i", &first.account.password, &code, "/").status, 303); | ||
| let account = first.account.clone(); | ||
| drop(first); | ||
| let restarted = Server::start_signed_out_as(repos(), account); | ||
| assert_eq!(sign_in(&restarted, "Um9i", &restarted.account.password, &code, "/").status, 401); | ||
| } | ||
| #[test] | ||
| fn two_servers_on_one_account_accept_a_code_once() { | ||
| let one = Server::start_signed_out(repos()); | ||
| let two = Server::start_signed_out_as(repos(), one.account.clone()); | ||
| let code = one.account.code(0); | ||
| let statuses: Vec<u16> = std::thread::scope(|scope| { | ||
| let attempts: Vec<_> = [&one, &two, &one, &two] | ||
| .into_iter() | ||
| .map(|s| scope.spawn(|| sign_in(s, "Um9i", &s.account.password, &code, "/").status)) | ||
| .collect(); | ||
| attempts.into_iter().map(|a| a.join().unwrap()).collect() | ||
| }); | ||
| assert_eq!(statuses.iter().filter(|s| **s == 303).count(), 1, "{statuses:?}"); | ||
| } | ||
| #[test] | ||
| fn oversized_forms_are_refused_unread() { | ||
| let s = Server::start_signed_out(repos()); | ||
| let huge = "x".repeat(64 * 1024); | ||
| assert_eq!(sign_in(&s, "Um9i", &huge, "123456", "/").status, 413); | ||
| } | ||
| #[test] | ||
| fn the_next_code_still_works_after_one_is_used() { | ||
| let s = Server::start_signed_out(repos()); | ||
| @@ -301,7 +371,7 @@ mod changing_the_password { | ||
| // What `gitv-web password` does: rewrite the account file with a new password. | ||
| let mut credentials = gitv::auth::Credentials::load(&s.account.file).unwrap(); | ||
| credentials.set_password("changed on the server").unwrap(); | ||
| credentials.save(&s.account.file).unwrap(); | ||
| credentials.save(&s.account.file, None).unwrap(); | ||
| assert_eq!(s.get("/").status, 303); | ||
| } | ||
| } | ||
| @@ -309,6 +379,17 @@ mod changing_the_password { | ||
| mod setup { | ||
| use super::*; | ||
| #[test] | ||
| fn root_setup_refuses_an_unwritable_custom_directory_before_publication() { | ||
| let Some(_) = gitv::auth::service_owner().unwrap() else { return }; | ||
| let dir = scratch("auth-setup-root-owned"); | ||
| std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap(); | ||
| let out = Command::new(common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", dir.join("login")).output().unwrap(); | ||
| assert!(!out.status.success()); | ||
| assert!(stderr(&out).contains("write and search access")); | ||
| assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0); | ||
| } | ||
| #[test] | ||
| fn refuses_to_replace_an_account_without_force() { | ||
| let dir = scratch("auth-setup-twice"); | ||
| @@ -318,6 +399,24 @@ mod setup { | ||
| assert!(stderr(&out).contains("already set up"), "{}", stderr(&out)); | ||
| } | ||
| #[test] | ||
| fn two_setups_at_once_leave_one_account() { | ||
| let dir = scratch("auth-setup-race"); | ||
| let file = dir.join("login"); | ||
| let results: Vec<bool> = std::thread::scope(|scope| { | ||
| let runs: Vec<_> = (0..4) | ||
| .map(|_| { | ||
| scope.spawn(|| { | ||
| Command::new(common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", &file).output().unwrap() | ||
| }) | ||
| }) | ||
| .collect(); | ||
| runs.into_iter().map(|r| r.join().unwrap().status.success()).collect() | ||
| }); | ||
| assert_eq!(results.iter().filter(|ok| **ok).count(), 1, "{results:?}"); | ||
| assert!(gitv::auth::Credentials::load(&file).is_ok()); | ||
| } | ||
| #[test] | ||
| fn with_force_replaces_it_and_signs_everyone_out() { | ||
| let s = Server::start(repos()); | ||
| @@ -330,6 +429,23 @@ mod setup { | ||
| assert_eq!(s.get("/").status, 303); | ||
| } | ||
| #[test] | ||
| fn refuses_user_names_that_would_not_read_back_and_keeps_the_account() { | ||
| let dir = scratch("auth-setup-bad-user"); | ||
| let account = common::Account::create(&dir); | ||
| for user in ["", "two words", "line\nbreak"] { | ||
| let out = Command::new(common::GITV_WEB) | ||
| .args(["setup", "--force", "--user", user]) | ||
| .env("GITV_WEB_AUTH", &account.file) | ||
| .output() | ||
| .unwrap(); | ||
| assert!(!out.status.success(), "{user:?} was accepted"); | ||
| assert!(stderr(&out).contains("user name"), "{}", stderr(&out)); | ||
| } | ||
| let kept = gitv::auth::Credentials::load(&account.file).unwrap(); | ||
| assert!(kept.verify_password(&account.password), "a refused setup replaced the account"); | ||
| } | ||
| #[test] | ||
| fn uses_um9i_by_default() { | ||
| let dir = scratch("auth-setup-user"); | ||
+10−1
| @@ -132,6 +132,7 @@ pub fn stderr(output: &Output) -> String { | ||
| } | ||
| /// A web account made by `gitv-web setup`: where it's stored, and what it printed. | ||
| #[derive(Clone)] | ||
| pub struct Account { | ||
| pub file: PathBuf, | ||
| pub password: String, | ||
| @@ -201,6 +202,11 @@ impl Server { | ||
| Server::start_with(repos, None) | ||
| } | ||
| /// A server using an existing account (another server's, say), not signed in. | ||
| pub fn start_signed_out_as(repos: &Path, account: Account) -> Server { | ||
| Server::launch(repos, None, account) | ||
| } | ||
| /// Sign in with the account's password and the current code, keeping the cookie. | ||
| pub fn sign_in_now(&mut self) { | ||
| let code = self.account.code(0); | ||
| @@ -212,7 +218,10 @@ impl Server { | ||
| } | ||
| fn start_with(repos: &Path, limit: Option<u64>) -> Server { | ||
| let account = Account::create(&account_dir()); | ||
| Server::launch(repos, limit, Account::create(&account_dir())) | ||
| } | ||
| fn launch(repos: &Path, limit: Option<u64>, account: Account) -> Server { | ||
| let mut command = Command::new(GITV_WEB); | ||
| if let Some(limit) = limit { | ||
| use std::os::unix::process::CommandExt; | ||