helm_rs/chart/digest/mod.rs
1//! Digests: the SHA-256 of a chart archive, the `Chart.lock` dependency hash Helm computes, and
2//! helm-rs's own content digest of a loaded chart.
3
4use std::path::Path;
5
6use base64::Engine;
7use base64::engine::general_purpose::STANDARD;
8use serde::Serialize;
9use serde::ser::{SerializeMap, Serializer};
10use serde_json::Value;
11use sha2::{Digest, Sha256};
12
13use super::{Chart, Dependency, Error, File};
14
15/// SHA-256 of the archive at `path`, lowercase hex.
16///
17/// This is Helm's `provenance.DigestFile`, the value `helm repo index` writes as `digest:` in
18/// `index.yaml` and `helm package --sign` records in the provenance file (prefixed `sha256:`).
19///
20/// # Errors
21/// When the file cannot be read.
22pub fn archive_digest(path: impl AsRef<Path>) -> Result<String, Error> {
23 let path = path.as_ref();
24 let io = |source| Error::Io {
25 path: path.to_owned(),
26 source,
27 };
28 let mut file = std::fs::File::open(path).map_err(io)?;
29 let mut hasher = Sha256::new();
30
31 std::io::copy(&mut file, &mut hasher).map_err(io)?;
32
33 Ok(hex(&hasher.finalize()))
34}
35
36/// A JSON value serialised with object keys in sorted order, whatever order the map keeps.
37struct Sorted<'a>(&'a Value);
38
39impl Serialize for Sorted<'_> {
40 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
41 match self.0 {
42 Value::Object(map) => {
43 let mut entries: Vec<_> = map.iter().collect();
44 let mut out = serializer.serialize_map(Some(entries.len()))?;
45
46 entries.sort_by_key(|(key, _)| key.as_str());
47
48 for (key, value) in entries {
49 out.serialize_entry(key, &Sorted(value))?;
50 }
51
52 out.end()
53 }
54 Value::Array(items) => serializer.collect_seq(items.iter().map(Sorted)),
55 other => other.serialize(serializer),
56 }
57 }
58}
59
60/// What the content digest hashes: one chart, reduced to what affects rendering and install.
61#[derive(Serialize)]
62struct Canonical<'a> {
63 metadata: Sorted<'a>,
64 lock: Sorted<'a>,
65 values: Sorted<'a>,
66 schema: Option<String>,
67 templates: Vec<(&'a str, String)>,
68 files: Vec<(&'a str, String)>,
69 dependencies: Vec<(&'a str, String)>,
70}
71
72/// The files as `(path, base64 bytes)`, sorted by path.
73fn sorted_files(files: &[File]) -> Vec<(&str, String)> {
74 let mut out: Vec<_> = files
75 .iter()
76 .map(|f| (f.name.as_str(), STANDARD.encode(&f.data)))
77 .collect();
78
79 out.sort();
80
81 out
82}
83
84impl Chart {
85 /// A digest of the chart's content: `sha256:` plus lowercase hex.
86 ///
87 /// Unlike [`archive_digest`], which hashes the bytes of one `.tgz` exactly as Helm does, this
88 /// is helm-rs's own: it hashes what the loaded chart contains, so the same chart gives the
89 /// same digest as a directory and as a packaged archive, and changes whenever its content
90 /// does even if `version` stays the same.
91 ///
92 /// It covers `Chart.yaml` as loaded, the lock, every template, the parsed values, the raw
93 /// schema, every other file (`crds/` included, by path and bytes) and every subchart,
94 /// recursively and by name. Because values are hashed parsed, edits to `values.yaml` that
95 /// change only comments or whitespace do not change the digest. Modification times and
96 /// anything specific to a directory or an archive are left out, and files a directory's
97 /// `.helmignore` excludes are never loaded, so they do not count either.
98 ///
99 /// The input is the JSON of a private struct with sorted keys and sorted paths, with file
100 /// bytes in base64. JSON strings are self-delimiting, so no two different charts produce the
101 /// same input.
102 ///
103 /// ```
104 /// # fn main() -> Result<(), helm_rs::chart::Error> {
105 /// use helm_rs::chart::Chart;
106 ///
107 /// let chart = Chart::load("tests/fixtures/chart/basic")?;
108 ///
109 /// assert!(chart.digest().starts_with("sha256:"));
110 /// assert_eq!(chart.digest(), chart.digest());
111 /// # Ok(())
112 /// # }
113 /// ```
114 ///
115 /// # Panics
116 /// Never: the canonical form always serialises.
117 #[must_use]
118 pub fn digest(&self) -> String {
119 let metadata = serde_json::to_value(&self.metadata).expect("metadata serialises");
120 let lock = serde_json::to_value(&self.lock).expect("lock serialises");
121 let mut dependencies: Vec<_> = self
122 .dependencies
123 .iter()
124 .map(|d| (d.name(), d.digest()))
125 .collect();
126
127 dependencies.sort();
128
129 let canonical = Canonical {
130 metadata: Sorted(&metadata),
131 lock: Sorted(&lock),
132 values: Sorted(&self.values),
133 schema: self.schema_raw.as_deref().map(|s| STANDARD.encode(s)),
134 templates: sorted_files(&self.templates),
135 files: sorted_files(&self.files),
136 dependencies,
137 };
138 let json = serde_json::to_vec(&canonical).expect("canonical form serialises");
139
140 format!("sha256:{}", sha256(&json))
141 }
142}
143
144/// The `digest:` of `Chart.lock` for a chart: Helm's `resolver.HashReq`.
145///
146/// It is `sha256:` plus the SHA-256 of the JSON of `[requested, locked]` as Go's `json.Marshal`
147/// writes it (field order of the Go struct, empty fields omitted, `<`, `>` and `&` escaped, an
148/// empty list written `null`). Compare it with `Chart.lock`'s digest to tell whether the lock
149/// is stale. Helm only compares hashes it generated itself.
150///
151/// # Panics
152/// Never: the dependency model always serialises.
153#[must_use]
154pub fn hash_dependencies(
155 requested: &[Option<Dependency>],
156 locked: &[Option<Dependency>],
157) -> String {
158 let json = serde_json::to_string(&[nil_if_empty(requested), nil_if_empty(locked)])
159 .expect("dependencies serialise");
160
161 format!("sha256:{}", sha256(&go_escape(&json)))
162}
163
164/// The Helm 2 flavour of the lock digest, `resolver.HashV2Req`, still accepted for `apiVersion: v1`
165/// charts.
166///
167/// # Panics
168/// Never: the dependency model always serialises.
169#[must_use]
170pub fn hash_dependencies_v2(requested: &[Option<Dependency>]) -> String {
171 let json =
172 serde_json::to_string(&serde_json::json!({ "dependencies": nil_if_empty(requested) }))
173 .expect("dependencies serialise");
174
175 format!("sha256:{}", sha256(&go_escape(&json)))
176}
177
178/// Go marshals a nil slice as `null`; an empty list is nil for all practical charts.
179fn nil_if_empty(list: &[Option<Dependency>]) -> Option<&[Option<Dependency>]> {
180 (!list.is_empty()).then_some(list)
181}
182
183/// Applies Go's HTML-safe escaping, which only ever occurs inside JSON strings.
184fn go_escape(json: &str) -> Vec<u8> {
185 json.replace('<', "\\u003c")
186 .replace('>', "\\u003e")
187 .replace('&', "\\u0026")
188 .replace('\u{2028}', "\\u2028")
189 .replace('\u{2029}', "\\u2029")
190 .into_bytes()
191}
192
193/// SHA-256 of `data` as lowercase hex.
194fn sha256(data: &[u8]) -> String {
195 hex(&Sha256::digest(data))
196}
197
198/// Lowercase hex of `bytes`.
199fn hex(bytes: &[u8]) -> String {
200 use std::fmt::Write;
201
202 bytes.iter().fold(String::new(), |mut out, b| {
203 write!(out, "{b:02x}").expect("writing to a string");
204
205 out
206 })
207}
208
209#[cfg(test)]
210mod tests;