Move the account commands out of the sign-in module
Browse fileslogin.rs held the web sign-in (handlers, sessions, throttling) and the command line's setup and password commands, which share no HTTP code. The commands and their directory preparation now live in setup.rs, unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 22:16
- Commit
- 7fc2fe7cb540
- Parent
- 1a2cc85
3 files changed +128−122
| @@ -4,11 +4,12 @@ | ||
| //! [`require_login`]. Sessions live in memory (a restart signs everyone out) and remember the | ||
| //! account's [fingerprint](gitv_web::auth::Credentials::fingerprint), so changing the password, here | ||
| //! or with `gitv-web password`, ends every other session. | ||
| //! | ||
| //! The command-line account commands (`setup`, `password`) are in `setup.rs`. | ||
| use std::collections::HashMap; | ||
| use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; | ||
| use std::os::unix::process::CommandExt; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::os::unix::fs::MetadataExt; | ||
| use std::path::PathBuf; | ||
| use std::sync::{Arc, Mutex}; | ||
| use std::time::{Duration, Instant}; | ||
| @@ -19,9 +20,7 @@ use axum::middleware::Next; | ||
| use axum::response::{IntoResponse, Response}; | ||
| use data_encoding::BASE64URL_NOPAD; | ||
| use gitv_core::{percent_decode, unix_now}; | ||
| use gitv_web::auth::{ | ||
| AuthError, Credentials, MIN_PASSWORD, auth_path, check_new_password, generate_password, random_bytes, | ||
| }; | ||
| use gitv_web::auth::{AuthError, Credentials, MIN_PASSWORD, auth_path, check_new_password, random_bytes}; | ||
| use serde::Deserialize; | ||
| use sha2::{Digest, Sha256}; | ||
| use subtle::ConstantTimeEq; | ||
| @@ -573,120 +572,6 @@ pub async fn change_password( | ||
| account_page(StatusCode::OK, &user, &signed_in, "Password changed. Other sessions have been signed out.", true) | ||
| } | ||
| // --------------------------------------------------------------------------------------------- | ||
| // Command line | ||
| /// `gitv-web setup`: create the account with a generated password and a new authenticator | ||
| /// secret, and print both, with a QR code for authenticator apps. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::AlreadySetUp`] if the account exists and `force` isn't set, or any error from | ||
| /// creating and saving it. | ||
| pub fn setup(user: Option<&str>, force: bool) -> Result<(), AuthError> { | ||
| let path = auth_path(); | ||
| // Replacing an account keeps its name unless told otherwise. | ||
| let existing = if force { Credentials::load(&path).ok().map(|c| c.user().to_string()) } else { None }; | ||
| let user = user.or(existing.as_deref()).unwrap_or(gitv_web::auth::DEFAULT_USER); | ||
| // A bad name is refused before anything is made, so --force can't swap a working account | ||
| // for one that won't load. | ||
| gitv_web::auth::check_user(user)?; | ||
| // 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_web::auth::service_owner()?; | ||
| prepare_directory(&path, owner)?; | ||
| let _lock = gitv_web::auth::lock_for_writing(&path, owner)?; | ||
| if path.exists() && !force { | ||
| return Err(AuthError::AlreadySetUp(path)); | ||
| } | ||
| let password = generate_password()?; | ||
| let credentials = Credentials::new(user, &password)?; | ||
| // 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()); | ||
| println!("Add the account to an authenticator app by scanning this code, or by entering the secret:\n"); | ||
| if let Ok(code) = qrcode::QrCode::new(credentials.otpauth_uri().as_bytes()) { | ||
| println!("{}", code.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build()); | ||
| } | ||
| println!("\n {}\n", credentials.otpauth_uri()); | ||
| println!("The password is shown only now. Change it after signing in, under Account, or with: gitv-web password"); | ||
| Ok(()) | ||
| } | ||
| /// `gitv-web password`: set a new password, typed twice at the terminal. Signs every session out. | ||
| /// | ||
| /// # Errors | ||
| /// [`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 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())?; | ||
| let second = rpassword::prompt_password("Repeat it: ").map_err(|e| e.to_string())?; | ||
| if first != second { | ||
| return Err("the passwords differ; nothing changed".into()); | ||
| } | ||
| // Typing took a while: apply the change only to the account that was loaded before it. | ||
| let owner = gitv_web::auth::service_owner().map_err(|e| e.to_string())?; | ||
| gitv_web::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 and given to `owner`. | ||
| fn prepare_directory(path: &Path, owner: gitv_web::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() { | ||
| 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 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)] | ||
| mod tests { | ||
| use super::*; | ||
| @@ -7,6 +7,7 @@ mod git_stream; | ||
| mod html; | ||
| mod login; | ||
| mod repository; | ||
| mod setup; | ||
| mod smart_http; | ||
| mod templates; | ||
| mod throttle; | ||
| @@ -209,8 +210,8 @@ async fn blocking(visitor: Visitor, f: impl FnOnce() -> View + Send + 'static) - | ||
| fn main() -> std::process::ExitCode { | ||
| let outcome = match Cli::parse().action { | ||
| Action::Serve { port } => serve(port), | ||
| Action::Setup { user, force } => login::setup(user.as_deref(), force).map_err(|e| e.to_string()), | ||
| Action::Password => login::change_password_at_terminal(), | ||
| Action::Setup { user, force } => setup::setup(user.as_deref(), force).map_err(|e| e.to_string()), | ||
| Action::Password => setup::change_password_at_terminal(), | ||
| }; | ||
| match outcome { | ||
| Ok(()) => std::process::ExitCode::SUCCESS, | ||
+120−0
| @@ -0,0 +1,120 @@ | ||
| //! The command line's account commands: `gitv-web setup` creates the web account, and | ||
| //! `gitv-web password` changes its password. Neither touches the running server, which | ||
| //! re-reads the account file whenever it changes. | ||
| use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; | ||
| use std::os::unix::process::CommandExt; | ||
| use std::path::Path; | ||
| use gitv_web::auth::{AuthError, Credentials, auth_path, check_new_password, generate_password}; | ||
| /// `gitv-web setup`: create the account with a generated password and a new authenticator | ||
| /// secret, and print both, with a QR code for authenticator apps. | ||
| /// | ||
| /// # Errors | ||
| /// [`AuthError::AlreadySetUp`] if the account exists and `force` isn't set, or any error from | ||
| /// creating and saving it. | ||
| pub fn setup(user: Option<&str>, force: bool) -> Result<(), AuthError> { | ||
| let path = auth_path(); | ||
| // Replacing an account keeps its name unless told otherwise. | ||
| let existing = if force { Credentials::load(&path).ok().map(|c| c.user().to_string()) } else { None }; | ||
| let user = user.or(existing.as_deref()).unwrap_or(gitv_web::auth::DEFAULT_USER); | ||
| // A bad name is refused before anything is made, so --force can't swap a working account | ||
| // for one that won't load. | ||
| gitv_web::auth::check_user(user)?; | ||
| // 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_web::auth::service_owner()?; | ||
| prepare_directory(&path, owner)?; | ||
| let _lock = gitv_web::auth::lock_for_writing(&path, owner)?; | ||
| if path.exists() && !force { | ||
| return Err(AuthError::AlreadySetUp(path)); | ||
| } | ||
| let password = generate_password()?; | ||
| let credentials = Credentials::new(user, &password)?; | ||
| // 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()); | ||
| println!("Add the account to an authenticator app by scanning this code, or by entering the secret:\n"); | ||
| if let Ok(code) = qrcode::QrCode::new(credentials.otpauth_uri().as_bytes()) { | ||
| println!("{}", code.render::<qrcode::render::unicode::Dense1x2>().quiet_zone(true).build()); | ||
| } | ||
| println!("\n {}\n", credentials.otpauth_uri()); | ||
| println!("The password is shown only now. Change it after signing in, under Account, or with: gitv-web password"); | ||
| Ok(()) | ||
| } | ||
| /// `gitv-web password`: set a new password, typed twice at the terminal. Signs every session out. | ||
| /// | ||
| /// # Errors | ||
| /// [`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 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())?; | ||
| let second = rpassword::prompt_password("Repeat it: ").map_err(|e| e.to_string())?; | ||
| if first != second { | ||
| return Err("the passwords differ; nothing changed".into()); | ||
| } | ||
| // Typing took a while: apply the change only to the account that was loaded before it. | ||
| let owner = gitv_web::auth::service_owner().map_err(|e| e.to_string())?; | ||
| gitv_web::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 and given to `owner`. | ||
| fn prepare_directory(path: &Path, owner: gitv_web::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() { | ||
| 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 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(()) | ||
| } | ||