Skip to main content

helm_rs/schema/
mod.rs

1//! `values.schema.json` validation, mirroring Helm v4.3.0 `ValidateAgainstSchema`
2//! (`pkg/chart/common/util/jsonschema.go`).
3//!
4//! - Helm validates the *final* (coalesced) values; [`validate`] takes values as already final.
5//!   [`final_values`] does Helm's coalescing for a chart without subcharts.
6//! - A chart's own schema validates the whole values mapping, then every subchart's schema
7//!   validates `values[<subchart name or alias>]`; a subchart with no values (or `null`) is
8//!   skipped, one with non-mapping values is a violation.
9//! - Schemas are JSON Schema; without `$schema` draft 2020-12 applies (as in Helm's
10//!   `santhosh-tekuri/jsonschema` v6), and `$schema` selects draft 4, 6, 7, 2019-09 or 2020-12.
11//! - Not mirrored: Helm validates after `ProcessDependencies` has dropped disabled subcharts
12//!   (conditions, tags, `enabled`) and renamed aliased ones. That needs a semver constraint
13//!   engine and full multi-chart coalescing, so it stays with Helm: pass a chart whose disabled
14//!   subcharts are already removed. Aliases are honoured through `Chart.yaml`.
15//! - `$ref`: see [`Error::RemoteRef`] and the `schema-remote-refs` feature.
16//! - [`generate()`](fn@generate) writes a `values.schema.json` from an annotated `values.yaml`, like helm-schema.
17
18mod coalesce;
19pub mod generate;
20mod resolver;
21
22pub use generate::{
23    Annotation, GenerateError, GenerateOptions, SkipField, annotations, generate, generate_chart,
24};
25
26use std::fmt;
27
28use serde_json::Value;
29
30use crate::chart::Chart;
31
32/// One schema violation.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct Violation {
35    /// JSON pointer of the offending value in the values, `""` for the root.
36    pub path: String,
37    /// What is wrong with it.
38    pub message: String,
39}
40
41/// The violations found in the values of one chart.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ChartViolations {
44    /// The chart, or the subchart's key (alias) in the values.
45    pub chart: String,
46    /// The violations, ordered by path.
47    pub violations: Vec<Violation>,
48}
49
50/// Why values failed schema validation.
51#[derive(Debug, thiserror::Error)]
52pub enum Error {
53    /// The values do not meet the schema of one or more charts.
54    #[error("{}", Report(.0))]
55    Invalid(Vec<ChartViolations>),
56    /// A schema refers to a `file://`, `http://` or `https://` resource and the
57    /// `schema-remote-refs` feature is off.
58    #[error(
59        "values.schema.json of chart {chart} refers to {uri}; resolving remote references needs the `schema-remote-refs` feature"
60    )]
61    RemoteRef {
62        /// The chart whose schema holds the reference.
63        chart: String,
64        /// The reference that was refused.
65        uri: String,
66    },
67    /// The operation does not apply to this input.
68    #[error("{0}")]
69    Unsupported(&'static str),
70}
71
72/// Formats violations like Helm: a header line, then `name:` and `- at '<path>': <message>`.
73struct Report<'a>(&'a [ChartViolations]);
74
75impl fmt::Display for Report<'_> {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        writeln!(
78            f,
79            "values don't meet the specifications of the schema(s) in the following chart(s):"
80        )?;
81
82        for chart in self.0 {
83            writeln!(f, "{}:", chart.chart)?;
84
85            for v in &chart.violations {
86                if v.path.is_empty() && !v.message.starts_with("missing") {
87                    writeln!(f, "{}", v.message)?;
88                } else {
89                    writeln!(f, "- at '{}': {}", v.path, v.message)?;
90                }
91            }
92        }
93
94        Ok(())
95    }
96}
97
98/// Validates final `values` against the schema of `chart` and of its subcharts.
99///
100/// # Errors
101/// [`Error::Invalid`] lists every violation of every chart, [`Error::RemoteRef`] reports a
102/// reference that cannot be resolved.
103pub fn validate(chart: &Chart, values: &Value) -> Result<(), Error> {
104    let mut failures = Vec::new();
105
106    collect(chart, chart.name(), values, &mut failures)?;
107
108    if failures.is_empty() {
109        return Ok(());
110    }
111
112    Err(Error::Invalid(failures))
113}
114
115/// Helm's `CoalesceValues` of `user_values` over the chart's defaults, for a chart without
116/// subcharts: mappings merge, scalars and lists are replaced, a user `null` removes a default.
117///
118/// Subchart defaults, `global` and condition handling need Helm's multi-chart pipeline and are
119/// not reimplemented; a chart with loaded subcharts is refused.
120///
121/// # Errors
122/// [`Error::Unsupported`] for charts with subcharts or non-mapping user values.
123pub fn final_values(chart: &Chart, user_values: &Value) -> Result<Value, Error> {
124    if !chart.dependencies.is_empty() {
125        return Err(Error::Unsupported(
126            "final values of a chart with subcharts need Helm's coalescing; use the backend",
127        ));
128    }
129
130    coalesce::coalesce(chart, user_values)
131}
132
133/// Appends the violations of `chart` and, recursively, of its subcharts.
134fn collect(
135    chart: &Chart,
136    label: &str,
137    values: &Value,
138    out: &mut Vec<ChartViolations>,
139) -> Result<(), Error> {
140    let violations = check_one(chart, label, values)?;
141
142    if !violations.is_empty() {
143        out.push(ChartViolations {
144            chart: label.to_owned(),
145            violations,
146        });
147    }
148
149    for sub in &chart.dependencies {
150        for key in keys_of(chart, sub) {
151            match values.get(&key) {
152                None | Some(Value::Null) => {}
153                Some(inner @ Value::Object(_)) => collect(sub, &key, inner, out)?,
154                Some(other) => out.push(ChartViolations {
155                    chart: key,
156                    violations: vec![Violation {
157                        path: String::new(),
158                        message: format!(
159                            "invalid type for values: expected object (map), got {}",
160                            go_type(other)
161                        ),
162                    }],
163                }),
164            }
165        }
166    }
167
168    Ok(())
169}
170
171/// The keys a subchart's values live under: each alias declared for it, else its name.
172fn keys_of(parent: &Chart, sub: &Chart) -> Vec<String> {
173    let declared: Vec<String> = parent
174        .metadata
175        .dependencies
176        .iter()
177        .flatten()
178        .filter(|d| d.name == sub.name())
179        .map(|d| {
180            if d.alias.is_empty() {
181                d.name.clone()
182            } else {
183                d.alias.clone()
184            }
185        })
186        .collect();
187
188    if declared.is_empty() {
189        vec![sub.name().to_owned()]
190    } else {
191        declared
192    }
193}
194
195/// The Go type name Helm prints for a non-mapping value (`%T` of a decoded JSON value).
196fn go_type(value: &Value) -> &'static str {
197    match value {
198        Value::Bool(_) => "bool",
199        Value::Number(_) => "float64",
200        Value::String(_) => "string",
201        Value::Array(_) => "[]interface {}",
202        _ => "map[string]interface {}",
203    }
204}
205
206/// Validates `values` against the chart's own schema, if it has one.
207fn check_one(chart: &Chart, label: &str, values: &Value) -> Result<Vec<Violation>, Error> {
208    let Some(raw) = &chart.schema_raw else {
209        return Ok(Vec::new());
210    };
211    let whole = |message: String| {
212        vec![Violation {
213            path: String::new(),
214            message,
215        }]
216    };
217    let schema: Value = match serde_json::from_slice(raw) {
218        Ok(schema) => schema,
219        Err(e) => return Ok(whole(e.to_string())),
220    };
221    let (resolver, refused) = resolver::Resolver::new();
222    let validator = jsonschema::options()
223        .with_base_uri("file:///values.schema.json")
224        .with_retriever(resolver)
225        .build(&schema);
226    let validator = match validator {
227        Ok(validator) => validator,
228        Err(e) => {
229            let uri = refused.lock().expect("lock is not poisoned").take();
230
231            return match uri {
232                Some(uri) => Err(Error::RemoteRef {
233                    chart: label.to_owned(),
234                    uri,
235                }),
236                None => Ok(whole(e.to_string())),
237            };
238        }
239    };
240    let mut violations: Vec<Violation> = validator
241        .iter_errors(values)
242        .map(|e| Violation {
243            path: e.instance_path().to_string(),
244            message: e.to_string(),
245        })
246        .collect();
247
248    violations.sort_by(|a, b| a.path.cmp(&b.path));
249
250    Ok(violations)
251}
252
253#[cfg(test)]
254mod tests;