1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
|
use crate::nixbase32;
use crate::nixhash::{HashAlgo, NixHash};
use serde::de::Unexpected;
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{Map, Value};
use std::borrow::Cow;
use super::algos::SUPPORTED_ALGOS;
use super::decode_digest;
/// A Nix CAHash describes a content-addressed hash of a path.
///
/// The way Nix prints it as a string is a bit confusing, but there's essentially
/// three modes, `Flat`, `Nar` and `Text`.
/// `Flat` and `Nar` support all 4 algos that [NixHash] supports
/// (sha1, md5, sha256, sha512), `Text` only supports sha256.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CAHash {
Flat(NixHash), // "fixed flat"
Nar(NixHash), // "fixed recursive"
Text([u8; 32]), // "text", only supports sha256
}
/// Representation for the supported hash modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HashMode {
Flat,
Nar,
Text,
}
impl CAHash {
pub fn hash(&self) -> Cow<NixHash> {
match *self {
CAHash::Flat(ref digest) => Cow::Borrowed(digest),
CAHash::Nar(ref digest) => Cow::Borrowed(digest),
CAHash::Text(digest) => Cow::Owned(NixHash::Sha256(digest)),
}
}
pub fn mode(&self) -> HashMode {
match self {
CAHash::Flat(_) => HashMode::Flat,
CAHash::Nar(_) => HashMode::Nar,
CAHash::Text(_) => HashMode::Text,
}
}
/// Returns a colon-separated string consisting of mode, recursiveness and
/// hash algo. Used as a prefix in various string representations.
pub fn algo_str(&self) -> &'static str {
match self.mode() {
HashMode::Flat => match self.hash().as_ref() {
NixHash::Md5(_) => "fixed:md5",
NixHash::Sha1(_) => "fixed:sha1",
NixHash::Sha256(_) => "fixed:sha256",
NixHash::Sha512(_) => "fixed:sha512",
},
HashMode::Nar => match self.hash().as_ref() {
NixHash::Md5(_) => "fixed:r:md5",
NixHash::Sha1(_) => "fixed:r:sha1",
NixHash::Sha256(_) => "fixed:r:sha256",
NixHash::Sha512(_) => "fixed:r:sha512",
},
HashMode::Text => "text:sha256",
}
}
/// Constructs a [CAHash] from the textual representation,
/// which is one of the three:
/// - `text:sha256:$nixbase32sha256digest`
/// - `fixed:r:$algo:$nixbase32digest`
/// - `fixed:$algo:$nixbase32digest`
/// which is the format that's used in the NARInfo for example.
pub fn from_nix_hex_str(s: &str) -> Option<Self> {
let (tag, s) = s.split_once(':')?;
match tag {
"text" => {
let digest = s.strip_prefix("sha256:")?;
let digest = nixbase32::decode_fixed(digest).ok()?;
Some(CAHash::Text(digest))
}
"fixed" => {
if let Some(s) = s.strip_prefix("r:") {
NixHash::from_nix_hex_str(s).map(CAHash::Nar)
} else {
NixHash::from_nix_hex_str(s).map(CAHash::Flat)
}
}
_ => None,
}
}
/// Formats a [CAHash] in the Nix default hash format, which is the format
/// that's used in NARInfos for example.
pub fn to_nix_nixbase32_string(&self) -> String {
format!(
"{}:{}",
self.algo_str(),
nixbase32::encode(self.hash().digest_as_bytes())
)
}
/// This takes a serde_json::Map and turns it into this structure. This is necessary to do such
/// shenigans because we have external consumers, like the Derivation parser, who would like to
/// know whether we have a invalid or a missing NixHashWithMode structure in another structure,
/// e.g. Output.
/// This means we have this combinatorial situation:
/// - no hash, no hashAlgo: no [CAHash] so we return Ok(None).
/// - present hash, missing hashAlgo: invalid, we will return missing_field
/// - missing hash, present hashAlgo: same
/// - present hash, present hashAlgo: either we return ourselves or a type/value validation
/// error.
/// This function is for internal consumption regarding those needs until we have a better
/// solution. Now this is said, let's explain how this works.
///
/// We want to map the serde data model into a [CAHash].
///
/// The serde data model has a `hash` field (containing a digest in nixbase32),
/// and a `hashAlgo` field, containing the stringified hash algo.
/// In case the hash is recursive, hashAlgo also has a `r:` prefix.
///
/// This is to match how `nix show-derivation` command shows them in JSON
/// representation.
pub(crate) fn from_map<'de, D>(map: &Map<String, Value>) -> Result<Option<Self>, D::Error>
where
D: Deserializer<'de>,
{
// If we don't have hash neither hashAlgo, let's just return None.
if !map.contains_key("hash") && !map.contains_key("hashAlgo") {
return Ok(None);
}
let hash_algo_v = map.get("hashAlgo").ok_or_else(|| {
serde::de::Error::missing_field(
"couldn't extract `hashAlgo` key, but `hash` key present",
)
})?;
let hash_algo = hash_algo_v.as_str().ok_or_else(|| {
serde::de::Error::invalid_type(Unexpected::Other(&hash_algo_v.to_string()), &"a string")
})?;
let (mode_is_nar, hash_algo) = if let Some(s) = hash_algo.strip_prefix("r:") {
(true, s)
} else {
(false, hash_algo)
};
let hash_algo = HashAlgo::try_from(hash_algo).map_err(|e| {
serde::de::Error::invalid_value(
Unexpected::Other(&e.to_string()),
&format!("one of {}", SUPPORTED_ALGOS.join(",")).as_str(),
)
})?;
let hash_v = map.get("hash").ok_or_else(|| {
serde::de::Error::missing_field(
"couldn't extract `hash` key but `hashAlgo` key present",
)
})?;
let hash = hash_v.as_str().ok_or_else(|| {
serde::de::Error::invalid_type(Unexpected::Other(&hash_v.to_string()), &"a string")
})?;
let hash = decode_digest(hash.as_bytes(), hash_algo)
.map_err(|e| serde::de::Error::custom(e.to_string()))?;
if mode_is_nar {
Ok(Some(Self::Nar(hash)))
} else {
Ok(Some(Self::Flat(hash)))
}
}
}
impl Serialize for CAHash {
/// map a CAHash into the serde data model.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(2))?;
match self {
CAHash::Flat(h) => {
map.serialize_entry("hash", &nixbase32::encode(h.digest_as_bytes()))?;
map.serialize_entry("hashAlgo", &h.algo())?;
}
CAHash::Nar(h) => {
map.serialize_entry("hash", &nixbase32::encode(h.digest_as_bytes()))?;
map.serialize_entry("hashAlgo", &format!("r:{}", &h.algo()))?;
}
// It is not legal for derivations to use this (which is where
// we're currently exercising [Serialize] mostly,
// but it's still good to be able to serialize other CA hashes too.
CAHash::Text(h) => {
map.serialize_entry("hash", &nixbase32::encode(h.as_ref()))?;
map.serialize_entry("hashAlgo", "text")?;
}
};
map.end()
}
}
impl<'de> Deserialize<'de> for CAHash {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = Self::from_map::<D>(&Map::deserialize(deserializer)?)?;
match value {
None => Err(serde::de::Error::custom("couldn't parse as map")),
Some(v) => Ok(v),
}
}
}
#[cfg(test)]
mod tests {
use crate::{derivation::CAHash, nixhash};
#[test]
fn serialize_flat() {
let json_bytes = r#"{
"hash": "1fnf2m46ya7r7afkcb8ba2j0sc4a85m749sh9jz64g4hx6z3r088",
"hashAlgo": "sha256"
}"#;
let hash = CAHash::Flat(
nixhash::from_nix_str(
"sha256:08813cbee9903c62be4c5027726a418a300da4500b2d369d3af9286f4815ceba",
)
.unwrap(),
);
let serialized = serde_json::to_string_pretty(&hash).unwrap();
assert_eq!(serialized, json_bytes);
}
#[test]
fn serialize_nar() {
let json_bytes = r#"{
"hash": "1fnf2m46ya7r7afkcb8ba2j0sc4a85m749sh9jz64g4hx6z3r088",
"hashAlgo": "r:sha256"
}"#;
let hash = CAHash::Nar(
nixhash::from_nix_str(
"sha256:08813cbee9903c62be4c5027726a418a300da4500b2d369d3af9286f4815ceba",
)
.unwrap(),
);
let serialized = serde_json::to_string_pretty(&hash).unwrap();
assert_eq!(serialized, json_bytes);
}
#[test]
fn deserialize_flat() {
let json_bytes = r#"
{
"hash": "08813cbee9903c62be4c5027726a418a300da4500b2d369d3af9286f4815ceba",
"hashAlgo": "sha256"
}"#;
let hash: CAHash = serde_json::from_str(json_bytes).expect("must parse");
assert_eq!(
hash,
CAHash::Flat(
nixhash::from_nix_str(
"sha256:08813cbee9903c62be4c5027726a418a300da4500b2d369d3af9286f4815ceba"
)
.unwrap()
)
);
}
#[test]
fn deserialize_hex() {
let json_bytes = r#"
{
"hash": "08813cbee9903c62be4c5027726a418a300da4500b2d369d3af9286f4815ceba",
"hashAlgo": "r:sha256"
}"#;
let hash: CAHash = serde_json::from_str(json_bytes).expect("must parse");
assert_eq!(
hash,
CAHash::Nar(
nixhash::from_nix_str(
"sha256:08813cbee9903c62be4c5027726a418a300da4500b2d369d3af9286f4815ceba"
)
.unwrap()
)
);
}
#[test]
fn deserialize_nixbase32() {
let json_bytes = r#"
{
"hash": "1fnf2m46ya7r7afkcb8ba2j0sc4a85m749sh9jz64g4hx6z3r088",
"hashAlgo": "r:sha256"
}"#;
let hash: CAHash = serde_json::from_str(json_bytes).expect("must parse");
assert_eq!(
hash,
CAHash::Nar(
nixhash::from_nix_str(
"sha256:08813cbee9903c62be4c5027726a418a300da4500b2d369d3af9286f4815ceba"
)
.unwrap()
)
);
}
#[test]
fn deserialize_base64() {
let json_bytes = r#"
{
"hash": "CIE8vumQPGK+TFAncmpBijANpFALLTadOvkob0gVzro=",
"hashAlgo": "r:sha256"
}"#;
let hash: CAHash = serde_json::from_str(json_bytes).expect("must parse");
assert_eq!(
hash,
CAHash::Nar(
nixhash::from_nix_str(
"sha256:08813cbee9903c62be4c5027726a418a300da4500b2d369d3af9286f4815ceba"
)
.unwrap()
)
);
}
#[test]
fn serialize_deserialize_nar() {
let json_bytes = r#"
{
"hash": "08813cbee9903c62be4c5027726a418a300da4500b2d369d3af9286f4815ceba",
"hashAlgo": "r:sha256"
}"#;
let hash: CAHash = serde_json::from_str(json_bytes).expect("must parse");
let serialized = serde_json::to_string(&hash).expect("Serialize");
let hash2: CAHash = serde_json::from_str(&serialized).expect("must parse again");
assert_eq!(hash, hash2);
}
#[test]
fn serialize_deserialize_flat() {
let json_bytes = r#"
{
"hash": "08813cbee9903c62be4c5027726a418a300da4500b2d369d3af9286f4815ceba",
"hashAlgo": "sha256"
}"#;
let hash: CAHash = serde_json::from_str(json_bytes).expect("must parse");
let serialized = serde_json::to_string(&hash).expect("Serialize");
let hash2: CAHash = serde_json::from_str(&serialized).expect("must parse again");
assert_eq!(hash, hash2);
}
}
|