summaryrefslogtreecommitdiffstats
path: root/src/hash.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/hash.rs')
-rw-r--r--src/hash.rs19
1 files changed, 13 insertions, 6 deletions
diff --git a/src/hash.rs b/src/hash.rs
index 5243520..0321437 100644
--- a/src/hash.rs
+++ b/src/hash.rs
@@ -69,10 +69,17 @@ pub fn recipe_hash(entries: &[(String, String)]) -> String {
hex::encode(h.finalize())
}
-/// Canonical JSON used for identity digests. Key order in serde_json maps is
-/// not stable across object construction, so we serialize through a
-/// `BTreeMap`-preserving path: callers pass already-canonical values (arrays of
-/// objects with a fixed field order) and we hash the compact rendering.
-pub fn canonical_json<T: serde::Serialize>(v: &T) -> String {
- serde_json::to_string(v).unwrap_or_else(|_| "{}".into())
+/// Serialize a value to canonical JSON: compact, with every object's keys in
+/// sorted order, so equal values always produce equal bytes.
+///
+/// The ordering is not free in `serde_json` โ€” a struct serializes in field
+/// declaration order and a map in whatever order it happens to hold โ€” so the
+/// value is routed through `serde_json::Value`, whose map is a `BTreeMap`.
+/// That makes the name true rather than aspirational.
+///
+/// A serialization failure is an error. It used to be `"{}"`, which meant every
+/// value that failed to serialize hashed to the same digest โ€” and this is the
+/// function behind `Identity::hash`, the value an approval echoes (ยง6 M-2).
+pub fn canonical_json<T: serde::Serialize>(v: &T) -> Result<String, serde_json::Error> {
+ serde_json::to_string(&serde_json::to_value(v)?)
}