eclipse-cli 0.13.4

Command-line interface for eclipse
//! `eclipse web passwd`: set the dashboard's human sign-in, without ever writing the password down.
//!
//! The password arrives from a terminal with echo off (or from stdin when the input is a pipe), is
//! hashed with PBKDF2-HMAC-SHA256 at `eclipse_core::auth::ITERATIONS`, and only the hash reaches
//! `.env`. Nothing here prints the password or the hash: `--verbose`-free by construction, because
//! the one thing this command must never do is put a secret in a scrollback buffer or a CI log.

use crate::ui::Style;
use anyhow::{bail, Context, Result};
use eclipse_core::auth;
use std::io::Write;

/// What `eclipse web passwd` was asked to do.
pub struct Request {
    pub user: Option<String>,
    /// Read the password from stdin instead of the terminal — for a script or a container.
    pub stdin: bool,
}

/// Run the verb and return the lines to print.
///
/// `env` is the process environment lookup the rest of the CLI uses, so `.env` is found where the
/// loader will look for it rather than beside the current directory.
pub fn passwd(
    req: &Request,
    env: eclipse_core::config::EnvFn<'_>,
    style: &Style,
) -> Result<Vec<String>> {
    let dir = eclipse_core::config::config_dir(env)
        .context("no config directory: set ECLIPSE_HOME so there is a `.env` to write")?;
    let path = dir.join(".env");

    // The user is kept when only the password is being reset: retyping a name to change a password
    // is a chance to typo it.
    let existing = std::fs::read_to_string(&path).unwrap_or_default();
    let current_user = parse_var(&existing, auth::USER_VAR);
    let user = match (&req.user, current_user) {
        (Some(user), _) => user.clone(),
        (None, Some(user)) => user,
        (None, None) => {
            // Nothing can answer a prompt when stdin is a pipe — and a piped `web passwd --stdin`
            // has the password as its first line, so prompting read *that* as the username and then
            // quoted it back in the rejection (`#597`).
            if req.stdin || !is_tty() {
                bail!(
                    "no username: pass `--user <name>`, or set {} in .env. This invocation reads \
                     its password from stdin, so it cannot also ask for a name",
                    auth::USER_VAR
                );
            }
            let typed = prompt("User: ")?;
            if typed.trim().is_empty() {
                bail!("a username is required: it is half of the sign-in");
            }
            typed.trim().to_string()
        }
    };
    // A name with a space or a `#` would need quoting in `.env`, and getting that wrong turns a
    // working login into a file that silently says something else. Refused, with the reason — and
    // with the offending *character*, never the value: this arm is reachable by something that was
    // meant as a password, and printing what was typed is how it reached a CI log (`#597`).
    if let Some(bad) = user
        .chars()
        .find(|c| c.is_whitespace() || *c == '#' || *c == '"' || *c == '\'')
    {
        let named = if bad.is_whitespace() {
            "a space".to_string()
        } else {
            format!("`{bad}`")
        };
        bail!(
            "the username is not usable: it contains {named}. No spaces, quotes or `#` in a \
             username — they would need quoting in .env, and getting that wrong turns a working \
             login into a file that says something else"
        );
    }

    let password = if req.stdin || !is_tty() {
        let mut line = String::new();
        std::io::stdin()
            .read_line(&mut line)
            .context("reading the password from stdin")?;
        line.trim_end_matches(['\n', '\r']).to_string()
    } else {
        let first = prompt_quiet("Password: ")?;
        let again = prompt_quiet("Password again: ")?;
        if first != again {
            bail!("the two passwords differ; nothing was written");
        }
        first
    };
    if password.chars().count() < 8 {
        bail!(
            "the password must be at least 8 characters ({} given)",
            password.chars().count()
        );
    }

    let hash = auth::hash_password(&password)?;
    auth::write_env_vars(&path, &[(auth::USER_VAR, &user), (auth::HASH_VAR, &hash)])?;

    let mut out = vec![
        format!(
            "{} {} ({}, {} rounds)",
            style.bold("wrote"),
            path.display(),
            user,
            auth::ITERATIONS
        ),
        format!("  {}", auth::USER_VAR),
        format!("  {}", auth::HASH_VAR),
    ];
    out.push(String::new());
    out.push(
        "The password is not printed, not stored, and not in your shell history. Restart the \
         dashboard for it to take effect; until then `web.auth_token` is still the door."
            .to_string(),
    );
    Ok(out)
}

/// Print `prompt` and read one line, echo on. Used for the username only.
fn prompt(what: &str) -> Result<String> {
    print!("{what}");
    std::io::stdout().flush().ok();
    let mut line = String::new();
    std::io::stdin()
        .read_line(&mut line)
        .context("reading your answer")?;
    Ok(line.trim_end_matches(['\n', '\r']).to_string())
}

fn is_tty() -> bool {
    #[cfg(unix)]
    {
        // SAFETY: `isatty` only reads the descriptor's type.
        unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }
    }
    #[cfg(not(unix))]
    {
        true
    }
}

/// Read a line with the terminal's echo turned off, and turn it back on even when the read fails.
///
/// `libc` rather than a crate: the workspace has no password-prompt dependency that resolves
/// offline, and this is thirty lines of `termios`. The guard is a struct so a `return` on an I/O
/// error cannot leave the terminal in raw-echo-off — the failure mode that makes a shell look
/// broken rather than a command look wrong.
fn prompt_quiet(what: &str) -> Result<String> {
    print!("{what}");
    std::io::stdout().flush().ok();
    #[cfg(unix)]
    let _guard = EchoOff::new();
    let mut line = String::new();
    std::io::stdin()
        .read_line(&mut line)
        .context("reading the password")?;
    println!();
    Ok(line.trim_end_matches(['\n', '\r']).to_string())
}

#[cfg(unix)]
struct EchoOff {
    saved: Option<libc::termios>,
}

#[cfg(unix)]
impl EchoOff {
    fn new() -> Self {
        // SAFETY: `tcgetattr`/`tcsetattr` are called on stdin with a correctly sized `termios`,
        // and the saved copy is restored in `Drop`.
        unsafe {
            let mut term: libc::termios = std::mem::zeroed();
            if libc::tcgetattr(libc::STDIN_FILENO, &mut term) != 0 {
                return Self { saved: None };
            }
            let saved = term;
            term.c_lflag &= !libc::ECHO;
            libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &term);
            Self { saved: Some(saved) }
        }
    }
}

#[cfg(unix)]
impl Drop for EchoOff {
    fn drop(&mut self) {
        if let Some(saved) = self.saved {
            // SAFETY: restoring the exact attributes that were read a moment ago.
            unsafe {
                libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &saved);
            }
        }
    }
}

/// `KEY=value` in `.env` text, unquoted or quoted, without going through the strict parser: this
/// is a *read* for a default value, and a file the strict parser rejects should not stop somebody
/// from setting a password (the write below fixes the line it touches).
fn parse_var(text: &str, key: &str) -> Option<String> {
    for line in text.lines() {
        let line = line.trim();
        let body = line.strip_prefix("export ").unwrap_or(line).trim_start();
        let Some(rest) = body.strip_prefix(key) else {
            continue;
        };
        let Some(value) = rest.strip_prefix('=') else {
            continue;
        };
        let value = value.trim();
        let value = value
            .strip_prefix('"')
            .and_then(|v| v.strip_suffix('"'))
            .or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
            .unwrap_or(value);
        if !value.is_empty() {
            return Some(value.to_string());
        }
    }
    None
}