helm-rs 0.1.2

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

use std::path::Path;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::Serialize;
use serde::ser::{SerializeMap, Serializer};
use serde_json::Value;
use sha2::{Digest, Sha256};

use super::{Chart, Dependency, Error, File};

/// 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()))
}

/// A JSON value serialised with object keys in sorted order, whatever order the map keeps.
struct Sorted<'a>(&'a Value);

impl Serialize for Sorted<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self.0 {
            Value::Object(map) => {
                let mut entries: Vec<_> = map.iter().collect();
                let mut out = serializer.serialize_map(Some(entries.len()))?;

                entries.sort_by_key(|(key, _)| key.as_str());

                for (key, value) in entries {
                    out.serialize_entry(key, &Sorted(value))?;
                }

                out.end()
            }
            Value::Array(items) => serializer.collect_seq(items.iter().map(Sorted)),
            other => other.serialize(serializer),
        }
    }
}

/// What the content digest hashes: one chart, reduced to what affects rendering and install.
#[derive(Serialize)]
struct Canonical<'a> {
    metadata: Sorted<'a>,
    lock: Sorted<'a>,
    values: Sorted<'a>,
    schema: Option<String>,
    templates: Vec<(&'a str, String)>,
    files: Vec<(&'a str, String)>,
    dependencies: Vec<(&'a str, String)>,
}

/// The files as `(path, base64 bytes)`, sorted by path.
fn sorted_files(files: &[File]) -> Vec<(&str, String)> {
    let mut out: Vec<_> = files
        .iter()
        .map(|f| (f.name.as_str(), STANDARD.encode(&f.data)))
        .collect();

    out.sort();

    out
}

impl Chart {
    /// A digest of the chart's content: `sha256:` plus lowercase hex.
    ///
    /// Unlike [`archive_digest`], which hashes the bytes of one `.tgz` exactly as Helm does, this
    /// is helm-rs's own: it hashes what the loaded chart contains, so the same chart gives the
    /// same digest as a directory and as a packaged archive, and changes whenever its content
    /// does even if `version` stays the same.
    ///
    /// It covers `Chart.yaml` as loaded, the lock, every template, the parsed values, the raw
    /// schema, every other file (`crds/` included, by path and bytes) and every subchart,
    /// recursively and by name. Because values are hashed parsed, edits to `values.yaml` that
    /// change only comments or whitespace do not change the digest. Modification times and
    /// anything specific to a directory or an archive are left out, and files a directory's
    /// `.helmignore` excludes are never loaded, so they do not count either.
    ///
    /// The input is the JSON of a private struct with sorted keys and sorted paths, with file
    /// bytes in base64. JSON strings are self-delimiting, so no two different charts produce the
    /// same input.
    ///
    /// ```
    /// # fn main() -> Result<(), helm_rs::chart::Error> {
    /// use helm_rs::chart::Chart;
    ///
    /// let chart = Chart::load("tests/fixtures/chart/basic")?;
    ///
    /// assert!(chart.digest().starts_with("sha256:"));
    /// assert_eq!(chart.digest(), chart.digest());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    /// Never: the canonical form always serialises.
    #[must_use]
    pub fn digest(&self) -> String {
        let metadata = serde_json::to_value(&self.metadata).expect("metadata serialises");
        let lock = serde_json::to_value(&self.lock).expect("lock serialises");
        let mut dependencies: Vec<_> = self
            .dependencies
            .iter()
            .map(|d| (d.name(), d.digest()))
            .collect();

        dependencies.sort();

        let canonical = Canonical {
            metadata: Sorted(&metadata),
            lock: Sorted(&lock),
            values: Sorted(&self.values),
            schema: self.schema_raw.as_deref().map(|s| STANDARD.encode(s)),
            templates: sorted_files(&self.templates),
            files: sorted_files(&self.files),
            dependencies,
        };
        let json = serde_json::to_vec(&canonical).expect("canonical form serialises");

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

/// 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;