helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Digests Helm computes: the SHA-256 of a chart archive and the `Chart.lock` dependency hash.

use std::path::Path;

use sha2::{Digest, Sha256};

use super::{Dependency, Error};

/// SHA-256 of the archive at `path`, lowercase hex.
///
/// This is Helm's `provenance.DigestFile`, the value `helm repo index` writes as `digest:` in
/// `index.yaml` and `helm package --sign` records in the provenance file (prefixed `sha256:`).
///
/// # Errors
/// When the file cannot be read.
pub fn archive_digest(path: impl AsRef<Path>) -> Result<String, Error> {
    let path = path.as_ref();
    let io = |source| Error::Io {
        path: path.to_owned(),
        source,
    };
    let mut file = std::fs::File::open(path).map_err(io)?;
    let mut hasher = Sha256::new();

    std::io::copy(&mut file, &mut hasher).map_err(io)?;

    Ok(hex(&hasher.finalize()))
}

/// The `digest:` of `Chart.lock` for a chart: Helm's `resolver.HashReq`.
///
/// It is `sha256:` plus the SHA-256 of the JSON of `[requested, locked]` as Go's `json.Marshal`
/// writes it (field order of the Go struct, empty fields omitted, `<`, `>` and `&` escaped, an
/// empty list written `null`). Compare it with `Chart.lock`'s digest to tell whether the lock
/// is stale. Helm only compares hashes it generated itself.
///
/// # Panics
/// Never: the dependency model always serialises.
#[must_use]
pub fn hash_dependencies(
    requested: &[Option<Dependency>],
    locked: &[Option<Dependency>],
) -> String {
    let json = serde_json::to_string(&[nil_if_empty(requested), nil_if_empty(locked)])
        .expect("dependencies serialise");

    format!("sha256:{}", sha256(&go_escape(&json)))
}

/// The Helm 2 flavour of the lock digest, `resolver.HashV2Req`, still accepted for `apiVersion: v1`
/// charts.
///
/// # Panics
/// Never: the dependency model always serialises.
#[must_use]
pub fn hash_dependencies_v2(requested: &[Option<Dependency>]) -> String {
    let json =
        serde_json::to_string(&serde_json::json!({ "dependencies": nil_if_empty(requested) }))
            .expect("dependencies serialise");

    format!("sha256:{}", sha256(&go_escape(&json)))
}

/// Go marshals a nil slice as `null`; an empty list is nil for all practical charts.
fn nil_if_empty(list: &[Option<Dependency>]) -> Option<&[Option<Dependency>]> {
    (!list.is_empty()).then_some(list)
}

/// Applies Go's HTML-safe escaping, which only ever occurs inside JSON strings.
fn go_escape(json: &str) -> Vec<u8> {
    json.replace('<', "\\u003c")
        .replace('>', "\\u003e")
        .replace('&', "\\u0026")
        .replace('\u{2028}', "\\u2028")
        .replace('\u{2029}', "\\u2029")
        .into_bytes()
}

/// SHA-256 of `data` as lowercase hex.
fn sha256(data: &[u8]) -> String {
    hex(&Sha256::digest(data))
}

/// Lowercase hex of `bytes`.
fn hex(bytes: &[u8]) -> String {
    use std::fmt::Write;

    bytes.iter().fold(String::new(), |mut out, b| {
        write!(out, "{b:02x}").expect("writing to a string");

        out
    })
}

#[cfg(test)]
mod tests;