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;
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(())
}
pub(crate) fn oci_host(reference: &str) -> &str {
let host = reference.strip_prefix("oci://").unwrap_or(reference);
host.split('/').next().unwrap_or(host)
}
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)
}
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(())
}
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"),
}
}
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)
}