helm_rs/chart/mod.rs
1//! Charts as data: `Chart.yaml`, `Chart.lock`, values, schema, templates and subcharts, loaded
2//! natively from a directory or a `.tgz` archive without the `helm` binary.
3//!
4//! Everything mirrors Helm v4.3.0 (`pkg/chart/loader`, `pkg/chart/v2`, `pkg/ignore`):
5//!
6//! - Helm 4.3's loader dispatches on `apiVersion`: `v1`, `v2` and a missing one load as v2 charts,
7//! `v3` loads as an (internal, experimental) v3 chart, anything else is rejected. v3 differs in
8//! defaulting `apiVersion` to `v3` and not understanding `requirements.yaml`. Helm 4.3's actions
9//! (`install`, `template`, ...) still reject v3 charts.
10//! - A directory honours `.helmignore` (plus the default `templates/.?*`); an archive does not.
11//! - Loading stops at 100 MiB of decompressed content; archive paths are checked for absolute
12//! paths, `..`, drive letters and a stray top-level `Chart.yaml`.
13//! - A leading UTF-8 byte order mark is dropped from every file.
14
15mod digest;
16mod fetch;
17mod ignore;
18mod loader;
19mod metadata;
20mod yaml;
21
22use std::path::{Path, PathBuf};
23
24use jiff::Timestamp;
25use serde::{Deserialize, Serialize};
26use serde_json::{Map, Value};
27
28use crate::go_json;
29
30pub use digest::{archive_digest, hash_dependencies, hash_dependencies_v2};
31pub use ignore::{HELM_IGNORE, IgnoreError, Rules};
32pub use loader::MAX_DECOMPRESSED_SIZE;
33pub use metadata::{Dependency, Lock, Maintainer, Metadata, ValidationError, is_valid_semver};
34pub use yaml::YamlError;
35
36/// Everything that can go wrong reading a chart.
37#[derive(Debug, thiserror::Error)]
38pub enum Error {
39 /// A file or directory could not be read.
40 #[error("{path}: {source}")]
41 Io {
42 /// The path involved.
43 path: PathBuf,
44 /// The underlying error.
45 source: std::io::Error,
46 },
47 /// A directory has no readable `Chart.yaml`.
48 #[error("unable to detect chart at {path}: {source}")]
49 NoChart {
50 /// The `Chart.yaml` that was looked for.
51 path: PathBuf,
52 /// The underlying error.
53 source: std::io::Error,
54 },
55 /// A file of the chart is not valid YAML or does not fit its model.
56 #[error("cannot load {file}: {detail}")]
57 Load {
58 /// The chart file, for example `Chart.yaml`.
59 file: String,
60 /// What was wrong with it.
61 detail: String,
62 },
63 /// The chart's metadata failed validation.
64 #[error(transparent)]
65 Validation(#[from] ValidationError),
66 /// The `apiVersion` is not one Helm 4.3 loads.
67 #[error("unsupported chart version")]
68 UnsupportedApiVersion,
69 /// The chart has no `Chart.yaml`.
70 #[error("Chart.yaml file is missing")]
71 MissingChartYaml,
72 /// The file is not a gzip archive.
73 #[error("{0}")]
74 NotAnArchive(String),
75 /// The archive holds no files.
76 #[error("no files in chart archive")]
77 EmptyArchive,
78 /// The archive or chart directory is unsafe or malformed.
79 #[error("{0}")]
80 Archive(String),
81 /// The chart is larger than [`MAX_DECOMPRESSED_SIZE`].
82 #[error("decompressed chart is larger than the maximum size {limit}")]
83 TooLarge {
84 /// The limit that was exceeded, in bytes.
85 limit: i64,
86 },
87 /// A symlink in the chart directory leads back to a directory that is being walked.
88 #[error("symlink cycle in chart directory at {}", .path.display())]
89 SymlinkCycle {
90 /// The directory that was entered a second time.
91 path: PathBuf,
92 },
93 /// A `.helmignore` rule is invalid.
94 #[error("invalid .helmignore: {0}")]
95 Ignore(#[from] IgnoreError),
96 /// A subchart could not be loaded.
97 #[error("error unpacking subchart {name} in {parent}: {source}")]
98 Subchart {
99 /// The entry under `charts/`.
100 name: String,
101 /// The parent chart's name.
102 parent: String,
103 /// Why it failed.
104 source: Box<Error>,
105 },
106}
107
108/// A file of a chart: its path relative to the chart root, slash separated, and its bytes.
109///
110/// Serializes as Helm's `common.File` (`name`, base64 `data`, `modtime`).
111#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
112pub struct File {
113 /// Path relative to the chart root, for example `templates/deployment.yaml`.
114 #[serde(default)]
115 pub name: String,
116 /// Content, without a leading byte order mark.
117 #[serde(default, with = "go_json::bytes")]
118 pub data: Vec<u8>,
119 /// The modification time Helm recorded; the loader leaves it unset.
120 #[serde(
121 default,
122 rename = "modtime",
123 with = "go_json::omit_zero",
124 skip_serializing_if = "Option::is_none"
125 )]
126 pub mod_time: Option<Timestamp>,
127}
128
129/// A chart: loaded from a directory or archive, or decoded from the chart embedded in a release
130/// record (Go `chart.Chart` JSON, which [`Serialize`] and [`Deserialize`] mirror exactly).
131///
132/// The record does not carry `values_raw` or the subcharts, so those stay empty after decoding.
133#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
134pub struct Chart {
135 /// `Chart.yaml`, validated and sanitised.
136 #[serde(default, deserialize_with = "go_json::null_default")]
137 pub metadata: Metadata,
138 /// `Chart.lock` (or `requirements.lock`).
139 #[serde(default)]
140 pub lock: Option<Lock>,
141 /// The files under `templates/` (partials and `NOTES.txt` included).
142 #[serde(default, deserialize_with = "go_json::null_default")]
143 pub templates: Vec<File>,
144 /// Parsed `values.yaml` with Helm's YAML semantics; `{}` when absent (`null` in records of
145 /// charts without values).
146 #[serde(default)]
147 pub values: Value,
148 /// The bytes of `values.schema.json`. Helm parses it only when validating, so loading does
149 /// not fail on invalid JSON; see [`Chart::schema`].
150 #[serde(default, rename = "schema", with = "go_json::option_bytes")]
151 pub schema_raw: Option<Vec<u8>>,
152 /// The modification time of the schema (Go's zero time reads as `None`).
153 #[serde(default, rename = "schemamodtime", with = "go_json::always")]
154 pub schema_mod_time: Option<Timestamp>,
155 /// Every other file, as in Helm: README, LICENSE, `crds/`, `*.prov` of subcharts, ...
156 /// (v1 charts also keep `requirements.yaml` and `requirements.lock` here).
157 #[serde(default, deserialize_with = "go_json::null_default")]
158 pub files: Vec<File>,
159 /// The modification time of the chart.
160 #[serde(
161 default,
162 rename = "modtime",
163 with = "go_json::omit_zero",
164 skip_serializing_if = "Option::is_none"
165 )]
166 pub mod_time: Option<Timestamp>,
167 /// The bytes of `values.yaml`, comments and all (what `helm show values` prints). Not part
168 /// of a release record.
169 #[serde(skip)]
170 pub values_raw: Option<Vec<u8>>,
171 /// Subcharts from `charts/`, directories and `.tgz` archives, loaded recursively. Helm keeps
172 /// them unexported, so a release record has none.
173 #[serde(skip)]
174 pub dependencies: Vec<Chart>,
175}
176
177impl Chart {
178 /// Loads a chart from a directory or a `.tgz` archive, detecting which.
179 ///
180 /// # Errors
181 /// See [`Error`].
182 pub fn load(path: impl AsRef<Path>) -> Result<Self, Error> {
183 loader::load(path.as_ref(), MAX_DECOMPRESSED_SIZE)
184 }
185
186 /// Loads a chart from the bytes of a `.tgz` archive.
187 ///
188 /// # Errors
189 /// See [`Error`].
190 pub fn load_archive(bytes: &[u8]) -> Result<Self, Error> {
191 loader::load_archive_bytes(bytes, MAX_DECOMPRESSED_SIZE)
192 }
193
194 /// The chart name.
195 #[must_use]
196 pub fn name(&self) -> &str {
197 &self.metadata.name
198 }
199
200 /// The chart's own default values (`values.yaml`), without any subchart or user values.
201 #[must_use]
202 pub fn default_values(&self) -> &Value {
203 &self.values
204 }
205
206 /// The parsed `values.schema.json`, if the chart has one.
207 ///
208 /// # Errors
209 /// Fails when the file is not valid JSON.
210 pub fn schema(&self) -> Result<Option<Value>, serde_json::Error> {
211 self.schema_raw
212 .as_deref()
213 .map(serde_json::from_slice)
214 .transpose()
215 }
216
217 /// The CRD manifests of this chart: `crds/` files ending in `.yaml`, `.yml` or `.json`.
218 pub fn crds(&self) -> impl Iterator<Item = &File> {
219 self.files.iter().filter(|f| {
220 let lower = f.name.to_ascii_lowercase();
221
222 f.name.starts_with("crds/")
223 && [".yaml", ".yml", ".json"]
224 .iter()
225 .any(|e| lower.ends_with(e))
226 })
227 }
228
229 /// Reports whether `Chart.lock` is out of date with `Chart.yaml`, like `helm dependency build`
230 /// ("the lock file (Chart.lock) is out of sync with the dependencies file"). `None` without a
231 /// lock. Exact only when repositories are written as URLs: Helm resolves `@alias` names from
232 /// its repository config before hashing.
233 #[must_use]
234 pub fn lock_is_stale(&self) -> Option<bool> {
235 let lock = self.lock.as_ref()?;
236 let current = hash_dependencies(&self.metadata.dependencies, &lock.dependencies);
237 let v1 = self.metadata.api_version == "v1"
238 && hash_dependencies_v2(&self.metadata.dependencies) == lock.digest;
239
240 Some(current != lock.digest && !v1)
241 }
242}
243
244/// Reads a values file (`.yaml` or `.json`) the way Helm reads `-f` files and `values.yaml`.
245///
246/// Documents are merged in order (maps deep-merged, anything else replaced), an empty file is
247/// `{}`, and the top level must be a mapping. YAML is read with Helm's YAML 1.1 and number
248/// semantics: `yes`/`no`/`on`/`off` are booleans, `0777` is octal, integers beyond 2^53 become
249/// floats.
250///
251/// # Errors
252/// On unreadable, malformed or non-mapping input.
253pub fn read_values_file(path: impl AsRef<Path>) -> Result<Value, Error> {
254 let path = path.as_ref();
255 let data = std::fs::read(path).map_err(|source| Error::Io {
256 path: path.to_owned(),
257 source,
258 })?;
259
260 read_values(&data)
261}
262
263/// Parses the text of a values file; see [`read_values_file`].
264///
265/// # Errors
266/// On malformed or non-mapping input.
267pub fn read_values(data: &[u8]) -> Result<Value, Error> {
268 parse_values(data).map_err(|e| Error::Load {
269 file: "values".into(),
270 detail: e.to_string(),
271 })
272}
273
274/// Merges all YAML documents of a values file.
275fn parse_values(data: &[u8]) -> Result<Value, YamlError> {
276 let mut values = Map::new();
277
278 for document in yaml::parse_documents(data)? {
279 merge_maps(&mut values, yaml::into_map(document)?);
280 }
281
282 Ok(Value::Object(values))
283}
284
285/// Helm's `MergeMaps`: keys of `b` win, mappings present in both are merged recursively.
286fn merge_maps(a: &mut Map<String, Value>, b: Map<String, Value>) {
287 for (key, value) in b {
288 match (a.get_mut(&key), value) {
289 (Some(Value::Object(existing)), Value::Object(incoming)) => {
290 merge_maps(existing, incoming);
291 }
292 (_, value) => {
293 a.insert(key, value);
294 }
295 }
296 }
297}
298
299#[cfg(test)]
300mod tests;