reeve-cli 1.1.1

Localhost web dev stack manager: web servers, per-vhost PHP versions, SSL, and DNS — RunCloud, scaled down.
//! Local SSL via a shared mkcert CA. The CA is installed once into the system
//! trust store; per-vhost certs are minted from it into `certs/`, so every
//! backend trusts the same root and browsers show no warning.

use crate::brew::Brew;
use crate::paths;
use anyhow::{bail, Context, Result};
use std::path::PathBuf;
use std::process::Command;

fn mkcert_bin(brew: &Brew) -> PathBuf {
    brew.bin("mkcert")
}

/// Platform-specific tail for the `mkcert -install` failure hint. On Linux the
/// CA copy into `/usr/local/share/ca-certificates` needs root, and browser
/// (NSS) trust needs `certutil` from `libnss3-tools`.
fn trust_hint() -> &'static str {
    #[cfg(target_os = "linux")]
    {
        " On Linux, run `sudo mkcert -install`; install `libnss3-tools` (apt) \
          or `nss` (brew) first so Chromium/Firefox trust it too."
    }
    #[cfg(not(target_os = "linux"))]
    {
        ""
    }
}

/// Ensure the mkcert formula is installed.
pub fn ensure_installed(brew: &Brew) -> Result<()> {
    if !brew.is_installed("mkcert") {
        println!("Installing mkcert…");
        brew.install("mkcert")?;
    }
    Ok(())
}

/// Path to the mkcert CA root directory (`mkcert -CAROOT`).
pub fn caroot(brew: &Brew) -> Result<PathBuf> {
    let out = Command::new(mkcert_bin(brew))
        .arg("-CAROOT")
        .output()
        .context("Failed to run `mkcert -CAROOT`")?;
    if !out.status.success() {
        bail!("`mkcert -CAROOT` failed");
    }
    Ok(PathBuf::from(
        String::from_utf8_lossy(&out.stdout).trim().to_string(),
    ))
}

/// The CA root certificate path (`rootCA.pem`), if it exists. Useful for
/// `curl --cacert` verification and for pointing tools at the trust anchor.
pub fn ca_cert(brew: &Brew) -> Result<PathBuf> {
    Ok(caroot(brew)?.join("rootCA.pem"))
}

/// Chromium's own certificate store on Linux — separate from the system trust
/// store, and the one browsers actually read.
#[cfg(target_os = "linux")]
fn nssdb_dir() -> Option<PathBuf> {
    dirs::home_dir().map(|h| h.join(".pki/nssdb"))
}

/// Create Chromium's NSS database if it doesn't exist yet, so `mkcert -install`
/// has somewhere to put the CA.
///
/// On Linux the system trust store and the browser trust store are different
/// things: `mkcert -install` adds the CA to the system anchors (which is what
/// curl and `openssl verify` see), but Chromium and Firefox read an NSS
/// database instead. mkcert only touches that database if it already exists,
/// and it exists only once the browser has been run — so on a fresh machine
/// `ssl trust` reports success, `doctor` passes, and the browser still says
/// "Not secure". Creating the empty database first closes that gap.
///
/// Best-effort: without `certutil` (the `nss` / `libnss3-tools` package) there
/// is nothing to create it with, and `trust_hint()` already says so.
#[cfg(target_os = "linux")]
fn ensure_nssdb() {
    let Some(db) = nssdb_dir() else {
        return;
    };
    if db.join("cert9.db").exists() || db.join("cert8.db").exists() {
        return;
    }
    if std::fs::create_dir_all(&db).is_err() {
        return;
    }
    let _ = Command::new("certutil")
        .args(["-d", &format!("sql:{}", db.display())])
        .args(["-N", "--empty-password"])
        .output();
}

#[cfg(not(target_os = "linux"))]
fn ensure_nssdb() {}

/// Whether the CA is in the store browsers actually read. On Linux that's the
/// NSS database, not the system anchors — see `ensure_nssdb`. Elsewhere the
/// system trust store is the browser trust store, so this matches `is_trusted`.
#[cfg(target_os = "linux")]
pub fn is_browser_trusted() -> bool {
    let Some(db) = nssdb_dir() else {
        return false;
    };
    Command::new("certutil")
        .args(["-d", &format!("sql:{}", db.display())])
        .arg("-L")
        .output()
        .map(|o| String::from_utf8_lossy(&o.stdout).contains("mkcert development CA"))
        .unwrap_or(false)
}

/// Ensure mkcert's local CA exists and is installed into the trust store.
/// `mkcert -install` is idempotent; on macOS the first run may prompt for
/// admin authorization to add the root to the System keychain. Output is
/// captured (not inherited) so it never corrupts the TUI's alternate screen.
/// Returns `true` if the CA was newly installed, `false` if it was already
/// present in the trust store.
pub fn ensure_ca(brew: &Brew) -> Result<bool> {
    ensure_installed(brew)?;
    // Give mkcert a browser store to install into before asking it to install.
    ensure_nssdb();
    let out = Command::new(mkcert_bin(brew))
        .arg("-install")
        .output()
        .context("Failed to run `mkcert -install`")?;
    if !out.status.success() {
        bail!(
            "`mkcert -install` failed: {}. You may need to authorize adding the \
             CA to your trust store, then re-run.{}",
            String::from_utf8_lossy(&out.stderr).trim(),
            trust_hint()
        );
    }
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    // mkcert reports each store it touched: "is now installed" when it added
    // the CA, "is already installed" when it didn't. On Linux there are two
    // stores (system anchors and the browser's NSS database), so testing for
    // the negative would call it unchanged whenever either one was already
    // done — including the run that just added it to the browser.
    Ok(combined.contains("now installed"))
}

/// Remove the mkcert local CA from the trust store (`mkcert -uninstall`). Leaves
/// the CA files on disk, so a later `trust` re-installs the same root.
pub fn uninstall_ca(brew: &Brew) -> Result<()> {
    let out = Command::new(mkcert_bin(brew))
        .arg("-uninstall")
        .output()
        .context("Failed to run `mkcert -uninstall`")?;
    if !out.status.success() {
        bail!(
            "`mkcert -uninstall` failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(())
}

/// Whether the mkcert root CA is actually present in the macOS System keychain
/// (not merely generated on disk) — the real "is local HTTPS trusted" check.
#[cfg(target_os = "macos")]
pub fn is_trusted(brew: &Brew) -> bool {
    // mkcert's CA common name is "mkcert <user>@<host> …"; find it by the
    // stable "mkcert" prefix in the System keychain.
    let _ = brew;
    Command::new("security")
        .args([
            "find-certificate",
            "-c",
            "mkcert",
            "/Library/Keychains/System.keychain",
        ])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Whether the mkcert root CA is actually installed into the Linux system trust
/// store. `openssl verify -CApath /etc/ssl/certs` exits 0 only when the CA chain
/// verifies against the installed bundle, so it tests real trust (not just that
/// the CA was generated on disk).
#[cfg(target_os = "linux")]
pub fn is_trusted(brew: &Brew) -> bool {
    let Ok(root) = ca_cert(brew) else {
        return false;
    };
    if !root.exists() {
        return false;
    }
    Command::new("openssl")
        .arg("verify")
        .args(["-CApath", "/etc/ssl/certs"])
        .arg(&root)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Certificate + key paths for a host (the convention the backends expect).
pub fn cert_paths(host: &str) -> Result<(PathBuf, PathBuf)> {
    let dir = paths::certs_dir()?;
    Ok((
        dir.join(format!("{host}.pem")),
        dir.join(format!("{host}-key.pem")),
    ))
}

/// Mint a certificate for `host` from the shared CA into `certs/`.
pub fn mint(brew: &Brew, host: &str) -> Result<()> {
    ensure_installed(brew)?;
    paths::ensure_dirs()?;
    let (cert, key) = cert_paths(host)?;
    // Capture (don't inherit) stdio: mkcert is chatty, and inherited output
    // would corrupt the TUI's alternate screen when minting during `apply`.
    let out = Command::new(mkcert_bin(brew))
        .arg("-cert-file")
        .arg(&cert)
        .arg("-key-file")
        .arg(&key)
        .arg(host)
        .output()
        .with_context(|| format!("Failed to run mkcert for {host}"))?;
    if !out.status.success() {
        bail!(
            "mkcert failed to mint a certificate for {host}: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(())
}

/// True if both cert and key already exist for a host.
pub fn exists(host: &str) -> bool {
    cert_paths(host)
        .map(|(c, k)| c.exists() && k.exists())
        .unwrap_or(false)
}