GITv
master
setup.rs116 lines, 5.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//! 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::<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 = 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(())
}