//! 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; 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::().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 = gitv_core::open_dir(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(()) }