Skip to main content

helm_rs/chart/metadata/
mod.rs

1//! `Chart.yaml` and `Chart.lock`, mirroring Helm v4.3.0 `pkg/chart/v2` (`metadata.go`,
2//! `dependency.go`); `internal/chart/v3` is identical for these types.
3
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7/// A chart maintainer (`Chart.yaml` `maintainers`).
8#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(default)]
10pub struct Maintainer {
11    /// User or organisation name.
12    #[serde(skip_serializing_if = "String::is_empty")]
13    pub name: String,
14    /// Optional contact email.
15    #[serde(skip_serializing_if = "String::is_empty")]
16    pub email: String,
17    /// Optional URL.
18    #[serde(skip_serializing_if = "String::is_empty")]
19    pub url: String,
20}
21
22/// A chart dependency, in `Chart.yaml` `dependencies` and `Chart.lock`.
23///
24/// Field order matters: [`hash_dependencies`](super::digest::hash_dependencies) serialises it
25/// exactly like Go's `json.Marshal` of Helm's struct.
26#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
27#[serde(default)]
28pub struct Dependency {
29    /// Name; must match the dependency's own `Chart.yaml`.
30    pub name: String,
31    /// Version or version range (a lock holds exactly one version).
32    #[serde(skip_serializing_if = "String::is_empty")]
33    pub version: String,
34    /// Repository URL, `file://` path, `oci://` reference or `@alias`.
35    pub repository: String,
36    /// Values path that enables or disables the dependency.
37    #[serde(skip_serializing_if = "String::is_empty")]
38    pub condition: String,
39    /// Tags grouping dependencies for enabling together.
40    #[serde(skip_serializing_if = "Vec::is_empty")]
41    #[serde(deserialize_with = "crate::go_json::null_default")]
42    pub tags: Vec<String>,
43    /// Whether the chart is loaded.
44    #[serde(skip_serializing_if = "is_false")]
45    pub enabled: bool,
46    /// Values to import: a child key string, or a `{child, parent}` mapping.
47    #[serde(rename = "import-values", skip_serializing_if = "Vec::is_empty")]
48    #[serde(deserialize_with = "crate::go_json::null_default")]
49    pub import_values: Vec<Value>,
50    /// Alias the dependency is rendered under.
51    #[serde(skip_serializing_if = "String::is_empty")]
52    pub alias: String,
53}
54
55/// The `Chart.yaml` model. A YAML `null` inside `maintainers` or `dependencies` is kept as
56/// `None` so that [`Metadata::validate`] can reject it like Helm.
57#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
58#[serde(default)]
59pub struct Metadata {
60    /// Chart name. Required.
61    #[serde(skip_serializing_if = "String::is_empty")]
62    pub name: String,
63    /// Project home page.
64    #[serde(skip_serializing_if = "String::is_empty")]
65    pub home: String,
66    /// Source code URLs.
67    #[serde(skip_serializing_if = "Vec::is_empty")]
68    #[serde(deserialize_with = "crate::go_json::null_default")]
69    pub sources: Vec<String>,
70    /// Chart version, semver 2 (leniently: `1`, `v1.2` are accepted). Required.
71    #[serde(skip_serializing_if = "String::is_empty")]
72    pub version: String,
73    /// One-sentence description.
74    #[serde(skip_serializing_if = "String::is_empty")]
75    pub description: String,
76    /// Keywords.
77    #[serde(skip_serializing_if = "Vec::is_empty")]
78    #[serde(deserialize_with = "crate::go_json::null_default")]
79    pub keywords: Vec<String>,
80    /// Maintainers.
81    #[serde(skip_serializing_if = "Vec::is_empty")]
82    #[serde(deserialize_with = "crate::go_json::null_default")]
83    pub maintainers: Vec<Option<Maintainer>>,
84    /// Icon URL.
85    #[serde(skip_serializing_if = "String::is_empty")]
86    pub icon: String,
87    /// Chart API version: `v1`, `v2` (`v3` loads but Helm 4.3 actions reject it). Required.
88    #[serde(rename = "apiVersion", skip_serializing_if = "String::is_empty")]
89    pub api_version: String,
90    /// Condition that enables the chart (a string, as in Helm's `Metadata`).
91    #[serde(skip_serializing_if = "String::is_empty")]
92    pub condition: String,
93    /// Tags that enable the chart (a string, as in Helm's `Metadata`).
94    #[serde(skip_serializing_if = "String::is_empty")]
95    pub tags: String,
96    /// Version of the application the chart deploys.
97    #[serde(rename = "appVersion", skip_serializing_if = "String::is_empty")]
98    pub app_version: String,
99    /// Whether the chart is deprecated.
100    #[serde(skip_serializing_if = "is_false")]
101    pub deprecated: bool,
102    /// Annotations, uninterpreted by Helm.
103    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
104    #[serde(deserialize_with = "crate::go_json::null_default")]
105    pub annotations: std::collections::BTreeMap<String, String>,
106    /// Semver constraint on the Kubernetes version.
107    #[serde(rename = "kubeVersion", skip_serializing_if = "String::is_empty")]
108    pub kube_version: String,
109    /// Dependencies (apiVersion v2; v1 charts use `requirements.yaml`).
110    #[serde(skip_serializing_if = "Vec::is_empty")]
111    #[serde(deserialize_with = "crate::go_json::null_default")]
112    pub dependencies: Vec<Option<Dependency>>,
113    /// `application` (default) or `library`.
114    #[serde(rename = "type", skip_serializing_if = "String::is_empty")]
115    pub chart_type: String,
116}
117
118/// The `Chart.lock` model.
119#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
120#[serde(default)]
121pub struct Lock {
122    /// When the lock was generated, RFC 3339 text (Go's `time.Time`).
123    #[serde(deserialize_with = "crate::go_json::null_default")]
124    pub generated: String,
125    /// `sha256:` hash of the requested and locked dependencies; see
126    /// [`hash_dependencies`](super::digest::hash_dependencies).
127    pub digest: String,
128    /// Locked dependencies.
129    #[serde(deserialize_with = "crate::go_json::null_default")]
130    pub dependencies: Vec<Option<Dependency>>,
131}
132
133/// A violation found by [`Metadata::validate`]; the text is Helm's `ValidationError`.
134#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
135#[error("validation: {0}")]
136pub struct ValidationError(pub String);
137
138/// `serde` helper: omit `false`; the reference is what `skip_serializing_if` passes.
139#[allow(clippy::trivially_copy_pass_by_ref)]
140fn is_false(value: &bool) -> bool {
141    !*value
142}
143
144/// Replaces whitespace with a space and drops non-printable characters (Go `sanitizeString`).
145fn sanitize(text: &str) -> String {
146    text.chars()
147        .filter_map(|c| {
148            if c.is_whitespace() {
149                Some(' ')
150            } else if c.is_control() || c == '\u{feff}' {
151                None
152            } else {
153                Some(c)
154            }
155        })
156        .collect()
157}
158
159/// Reports whether `version` is accepted by `semver.NewVersion` of Masterminds semver v3, which
160/// is [`Version::parse`](crate::version::Version::parse).
161#[must_use]
162pub fn is_valid_semver(version: &str) -> bool {
163    crate::version::Version::parse(version).is_ok()
164}
165
166impl Metadata {
167    /// Sanitises string fields and checks the metadata like Helm's `Metadata.Validate`.
168    ///
169    /// Like Helm this normalises in place (whitespace becomes a space, non-printable characters
170    /// are dropped) before checking apiVersion, name (`.`, `..` and path separators are
171    /// rejected), semver version, type, maintainers and dependencies (alias characters, a name
172    /// or alias used twice).
173    ///
174    /// # Errors
175    /// The first violation, with Helm's message.
176    pub fn validate(&mut self) -> Result<(), ValidationError> {
177        for field in [
178            &mut self.name,
179            &mut self.description,
180            &mut self.home,
181            &mut self.icon,
182            &mut self.condition,
183            &mut self.tags,
184            &mut self.app_version,
185            &mut self.kube_version,
186        ] {
187            *field = sanitize(field);
188        }
189        for text in self.sources.iter_mut().chain(&mut self.keywords) {
190            *text = sanitize(text);
191        }
192
193        let fail = |message: String| Err(ValidationError(message));
194
195        if self.api_version.is_empty() {
196            return fail("chart.metadata.apiVersion is required".into());
197        }
198        if self.name.is_empty() {
199            return fail("chart.metadata.name is required".into());
200        }
201        if self.name == "." || self.name == ".." {
202            return fail(format!(
203                "chart.metadata.name {:?} is not allowed",
204                self.name
205            ));
206        }
207        if self.name.contains('/') {
208            return fail(format!("chart.metadata.name {:?} is invalid", self.name));
209        }
210        if self.version.is_empty() {
211            return fail("chart.metadata.version is required".into());
212        }
213        if !is_valid_semver(&self.version) {
214            return fail(format!(
215                "chart.metadata.version {:?} is invalid",
216                self.version
217            ));
218        }
219        if !matches!(self.chart_type.as_str(), "" | "application" | "library") {
220            return fail("chart.metadata.type must be application or library".into());
221        }
222
223        for maintainer in &mut self.maintainers {
224            let Some(m) = maintainer else {
225                return fail("maintainers must not contain empty or null nodes".into());
226            };
227
228            m.name = sanitize(&m.name);
229            m.email = sanitize(&m.email);
230            m.url = sanitize(&m.url);
231        }
232
233        let mut seen: Vec<String> = Vec::new();
234
235        for dependency in &mut self.dependencies {
236            let Some(d) = dependency else {
237                return fail("dependencies must not contain empty or null nodes".into());
238            };
239
240            d.validate()?;
241
242            let key = if d.alias.is_empty() {
243                &d.name
244            } else {
245                &d.alias
246            };
247
248            if seen.contains(key) {
249                return fail(format!(
250                    "more than one dependency with name or alias {key:?}"
251                ));
252            }
253            seen.push(key.clone());
254        }
255
256        Ok(())
257    }
258}
259
260impl Dependency {
261    /// Sanitises the fields and checks the alias, like Helm's `Dependency.Validate`.
262    ///
263    /// # Errors
264    /// When the alias contains anything but letters, digits, `_` and `-`.
265    pub fn validate(&mut self) -> Result<(), ValidationError> {
266        for field in [
267            &mut self.name,
268            &mut self.version,
269            &mut self.repository,
270            &mut self.condition,
271        ] {
272            *field = sanitize(field);
273        }
274        for tag in &mut self.tags {
275            *tag = sanitize(tag);
276        }
277
278        let alias_ok = self
279            .alias
280            .bytes()
281            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
282
283        if !alias_ok {
284            return Err(ValidationError(format!(
285                "dependency {:?} has disallowed characters in the alias",
286                self.name
287            )));
288        }
289
290        Ok(())
291    }
292}
293
294#[cfg(test)]
295mod tests;