helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! `values.schema.json` validation, mirroring Helm v4.3.0 `ValidateAgainstSchema`
//! (`pkg/chart/common/util/jsonschema.go`).
//!
//! - Helm validates the *final* (coalesced) values; [`validate`] takes values as already final.
//!   [`final_values`] does Helm's coalescing for a chart without subcharts.
//! - A chart's own schema validates the whole values mapping, then every subchart's schema
//!   validates `values[<subchart name or alias>]`; a subchart with no values (or `null`) is
//!   skipped, one with non-mapping values is a violation.
//! - Schemas are JSON Schema; without `$schema` draft 2020-12 applies (as in Helm's
//!   `santhosh-tekuri/jsonschema` v6), and `$schema` selects draft 4, 6, 7, 2019-09 or 2020-12.
//! - Not mirrored: Helm validates after `ProcessDependencies` has dropped disabled subcharts
//!   (conditions, tags, `enabled`) and renamed aliased ones. That needs a semver constraint
//!   engine and full multi-chart coalescing, so it stays with Helm: pass a chart whose disabled
//!   subcharts are already removed. Aliases are honoured through `Chart.yaml`.
//! - `$ref`: see [`Error::RemoteRef`] and the `schema-remote-refs` feature.
//! - [`generate()`](fn@generate) writes a `values.schema.json` from an annotated `values.yaml`, like helm-schema.

mod coalesce;
pub mod generate;
mod resolver;

pub use generate::{
    Annotation, GenerateError, GenerateOptions, SkipField, annotations, generate, generate_chart,
};

use std::fmt;

use serde_json::Value;

use crate::chart::Chart;

/// One schema violation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
    /// JSON pointer of the offending value in the values, `""` for the root.
    pub path: String,
    /// What is wrong with it.
    pub message: String,
}

/// The violations found in the values of one chart.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChartViolations {
    /// The chart, or the subchart's key (alias) in the values.
    pub chart: String,
    /// The violations, ordered by path.
    pub violations: Vec<Violation>,
}

/// Why values failed schema validation.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The values do not meet the schema of one or more charts.
    #[error("{}", Report(.0))]
    Invalid(Vec<ChartViolations>),
    /// A schema refers to a `file://`, `http://` or `https://` resource and the
    /// `schema-remote-refs` feature is off.
    #[error(
        "values.schema.json of chart {chart} refers to {uri}; resolving remote references needs the `schema-remote-refs` feature"
    )]
    RemoteRef {
        /// The chart whose schema holds the reference.
        chart: String,
        /// The reference that was refused.
        uri: String,
    },
    /// The operation does not apply to this input.
    #[error("{0}")]
    Unsupported(&'static str),
}

/// Formats violations like Helm: a header line, then `name:` and `- at '<path>': <message>`.
struct Report<'a>(&'a [ChartViolations]);

impl fmt::Display for Report<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "values don't meet the specifications of the schema(s) in the following chart(s):"
        )?;

        for chart in self.0 {
            writeln!(f, "{}:", chart.chart)?;

            for v in &chart.violations {
                if v.path.is_empty() && !v.message.starts_with("missing") {
                    writeln!(f, "{}", v.message)?;
                } else {
                    writeln!(f, "- at '{}': {}", v.path, v.message)?;
                }
            }
        }

        Ok(())
    }
}

/// Validates final `values` against the schema of `chart` and of its subcharts.
///
/// # Errors
/// [`Error::Invalid`] lists every violation of every chart, [`Error::RemoteRef`] reports a
/// reference that cannot be resolved.
pub fn validate(chart: &Chart, values: &Value) -> Result<(), Error> {
    let mut failures = Vec::new();

    collect(chart, chart.name(), values, &mut failures)?;

    if failures.is_empty() {
        return Ok(());
    }

    Err(Error::Invalid(failures))
}

/// Helm's `CoalesceValues` of `user_values` over the chart's defaults, for a chart without
/// subcharts: mappings merge, scalars and lists are replaced, a user `null` removes a default.
///
/// Subchart defaults, `global` and condition handling need Helm's multi-chart pipeline and are
/// not reimplemented; a chart with loaded subcharts is refused.
///
/// # Errors
/// [`Error::Unsupported`] for charts with subcharts or non-mapping user values.
pub fn final_values(chart: &Chart, user_values: &Value) -> Result<Value, Error> {
    if !chart.dependencies.is_empty() {
        return Err(Error::Unsupported(
            "final values of a chart with subcharts need Helm's coalescing; use the backend",
        ));
    }

    coalesce::coalesce(chart, user_values)
}

/// Appends the violations of `chart` and, recursively, of its subcharts.
fn collect(
    chart: &Chart,
    label: &str,
    values: &Value,
    out: &mut Vec<ChartViolations>,
) -> Result<(), Error> {
    let violations = check_one(chart, label, values)?;

    if !violations.is_empty() {
        out.push(ChartViolations {
            chart: label.to_owned(),
            violations,
        });
    }

    for sub in &chart.dependencies {
        for key in keys_of(chart, sub) {
            match values.get(&key) {
                None | Some(Value::Null) => {}
                Some(inner @ Value::Object(_)) => collect(sub, &key, inner, out)?,
                Some(other) => out.push(ChartViolations {
                    chart: key,
                    violations: vec![Violation {
                        path: String::new(),
                        message: format!(
                            "invalid type for values: expected object (map), got {}",
                            go_type(other)
                        ),
                    }],
                }),
            }
        }
    }

    Ok(())
}

/// The keys a subchart's values live under: each alias declared for it, else its name.
fn keys_of(parent: &Chart, sub: &Chart) -> Vec<String> {
    let declared: Vec<String> = parent
        .metadata
        .dependencies
        .iter()
        .flatten()
        .filter(|d| d.name == sub.name())
        .map(|d| {
            if d.alias.is_empty() {
                d.name.clone()
            } else {
                d.alias.clone()
            }
        })
        .collect();

    if declared.is_empty() {
        vec![sub.name().to_owned()]
    } else {
        declared
    }
}

/// The Go type name Helm prints for a non-mapping value (`%T` of a decoded JSON value).
fn go_type(value: &Value) -> &'static str {
    match value {
        Value::Bool(_) => "bool",
        Value::Number(_) => "float64",
        Value::String(_) => "string",
        Value::Array(_) => "[]interface {}",
        _ => "map[string]interface {}",
    }
}

/// Validates `values` against the chart's own schema, if it has one.
fn check_one(chart: &Chart, label: &str, values: &Value) -> Result<Vec<Violation>, Error> {
    let Some(raw) = &chart.schema_raw else {
        return Ok(Vec::new());
    };
    let whole = |message: String| {
        vec![Violation {
            path: String::new(),
            message,
        }]
    };
    let schema: Value = match serde_json::from_slice(raw) {
        Ok(schema) => schema,
        Err(e) => return Ok(whole(e.to_string())),
    };
    let (resolver, refused) = resolver::Resolver::new();
    let validator = jsonschema::options()
        .with_base_uri("file:///values.schema.json")
        .with_retriever(resolver)
        .build(&schema);
    let validator = match validator {
        Ok(validator) => validator,
        Err(e) => {
            let uri = refused.lock().expect("lock is not poisoned").take();

            return match uri {
                Some(uri) => Err(Error::RemoteRef {
                    chart: label.to_owned(),
                    uri,
                }),
                None => Ok(whole(e.to_string())),
            };
        }
    };
    let mut violations: Vec<Violation> = validator
        .iter_errors(values)
        .map(|e| Violation {
            path: e.instance_path().to_string(),
            message: e.to_string(),
        })
        .collect();

    violations.sort_by(|a, b| a.path.cmp(&b.path));

    Ok(violations)
}

#[cfg(test)]
mod tests;