helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! The chart download flags every chart-fetching command shares, and the private registry config
//! that carries an OCI password.

use std::path::{Path, PathBuf};

use base64::{Engine, engine::general_purpose::STANDARD};
use serde_json::{Value, json};

use super::Invocation;
use crate::chart::Chart;
use crate::command::{ChartPathOptions, ChartRef};
use crate::error::{Error, Result};
use crate::options::Secret;

/// Writes the chart download flags. A password is delivered through a temporary registry config
/// (see [`ChartPathOptions`]), never as `--password`.
pub(crate) fn chart_path(
    inv: &mut Invocation,
    chart: &ChartRef,
    o: &ChartPathOptions,
) -> Result<()> {
    let mut username = o.username.as_deref();

    if let Some(password) = &o.password {
        let ChartRef::Oci(reference) = chart else {
            return Err(Error::InvalidCommand(
                "Helm 4.3 reads a chart repository password only from --password or the \
                 repository config; add the repository with a password and reference the chart \
                 as repo/chart"
                    .to_owned(),
            ));
        };
        let user = username.take().ok_or_else(|| {
            Error::InvalidCommand("a registry password needs a username".to_owned())
        })?;

        registry_auth(inv, &[oci_host(reference)], user, password)?;
    }

    inv.option("--version", o.version.as_ref());
    inv.switch("--verify", o.verify);
    inv.option("--keyring", o.keyring.as_ref());
    inv.option("--repo", o.repo.as_ref());
    inv.option("--username", username);
    inv.option("--cert-file", o.cert_file.as_ref());
    inv.option("--key-file", o.key_file.as_ref());
    inv.option("--ca-file", o.ca_file.as_ref());
    inv.switch("--insecure-skip-tls-verify", o.insecure_skip_tls_verify);
    inv.switch("--plain-http", o.plain_http);
    inv.switch("--pass-credentials", o.pass_credentials);

    Ok(())
}

/// The registry host of an `oci://host/path` reference (or of `host/path`).
pub(crate) fn oci_host(reference: &str) -> &str {
    let host = reference.strip_prefix("oci://").unwrap_or(reference);

    host.split('/').next().unwrap_or(host)
}

/// The registry hosts of the `oci://` dependencies the charts at `paths` declare or lock, each
/// once.
pub(crate) fn oci_hosts<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Result<Vec<String>> {
    let mut hosts: Vec<String> = Vec::new();

    for path in paths {
        let chart = Chart::load(path)?;
        let locked = chart.lock.iter().flat_map(|lock| &lock.dependencies);

        for dependency in chart.metadata.dependencies.iter().chain(locked).flatten() {
            let Some(rest) = dependency.repository.strip_prefix("oci://") else {
                continue;
            };
            let host = oci_host(rest);

            if !hosts.iter().any(|known| known == host) {
                hosts.push(host.to_owned());
            }
        }
    }

    Ok(hosts)
}

/// Gives Helm the credentials of `username` for every registry in `hosts` without putting the
/// password in argv: writes one `0600` temporary registry config, a copy of the effective one with
/// an `auths` entry per host, and passes it as `--registry-config`.
pub(crate) fn registry_auth(
    inv: &mut Invocation,
    hosts: &[&str],
    username: &str,
    password: &Secret,
) -> Result<()> {
    let auth = STANDARD.encode(format!("{username}:{}", password.expose()));
    let mut config = read_registry_config(&effective_registry_config(inv))?;

    for host in hosts {
        config["auths"][*host] = json!({ "auth": auth });
    }

    let path = inv.temp_file(&serde_json::to_vec(&config)?)?;

    inv.option("--registry-config", Some(&path));

    Ok(())
}

/// The registry config Helm would read: the last `--registry-config` of the invocation, else
/// `registry/config.json` below `HELM_CONFIG_HOME`, `$XDG_CONFIG_HOME/helm` or the platform
/// default (`pkg/helmpath/lazypath.go`, v4.3.0).
fn effective_registry_config(inv: &Invocation) -> PathBuf {
    let flag = inv
        .args
        .iter()
        .rposition(|arg| arg == "--registry-config")
        .and_then(|at| inv.args.get(at + 1));
    let config_home = inv
        .env
        .iter()
        .find(|(key, _)| key == "HELM_CONFIG_HOME")
        .map(|(_, value)| PathBuf::from(value));
    let xdg = std::env::var_os("XDG_CONFIG_HOME")
        .filter(|value| !value.is_empty())
        .map(|value| PathBuf::from(value).join("helm"));
    let home = std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_default();
    let platform = if cfg!(target_os = "macos") {
        home.join("Library/Preferences/helm")
    } else {
        home.join(".config/helm")
    };

    match flag {
        Some(path) => PathBuf::from(path),
        None => config_home
            .or(xdg)
            .unwrap_or(platform)
            .join("registry/config.json"),
    }
}

/// Reads a docker-style registry config as a JSON object with an `auths` object; a missing file
/// is an empty config. Other keys (credential helpers) are kept.
fn read_registry_config(path: &Path) -> Result<Value> {
    let mut config = match std::fs::read(path) {
        Ok(bytes) => serde_json::from_slice(&bytes)?,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => json!({}),
        Err(e) => return Err(e.into()),
    };

    if !config.is_object() {
        return Err(Error::InvalidCommand(format!(
            "the registry config {} is not a JSON object",
            path.display()
        )));
    }

    if !config["auths"].is_object() {
        config["auths"] = json!({});
    }

    Ok(config)
}