summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/db/model.rs9
-rw-r--r--src/db/queries.rs2
-rw-r--r--src/hash.rs19
-rw-r--r--src/pipeline/mod.rs4
-rw-r--r--src/pipeline/steps.rs2
-rw-r--r--src/watch/detect.rs2
-rw-r--r--tests/hash.rs83
-rw-r--r--tests/vcs.rs2
8 files changed, 108 insertions, 15 deletions
diff --git a/src/db/model.rs b/src/db/model.rs
index 07065c5..e962d6f 100644
--- a/src/db/model.rs
+++ b/src/db/model.rs
@@ -58,11 +58,14 @@ impl Identity {
/// The hash that makes I3 a fact: two byte-identical inputs never produce
/// two candidates, and any change to what becomes a byte in the artifact
/// produces a new one.
+ ///
/// A digest of the canonical JSON of the identity tuple. This is the value
/// an approval must echo: two candidates share an `identity_hash` only if
- /// every pin, digest and version in them is identical.
- pub fn hash(&self) -> String {
- format!("sha256:{}", hash::hex(hash::canonical_json(self).as_bytes()))
+ /// every pin, digest and version in them is identical. A value that cannot
+ /// be serialized is an error rather than a digest — a shared fallback digest
+ /// would be the one way two identities could collide by accident.
+ pub fn hash(&self) -> crate::error::Result<String> {
+ Ok(format!("sha256:{}", hash::hex(hash::canonical_json(self)?.as_bytes())))
}
}
diff --git a/src/db/queries.rs b/src/db/queries.rs
index fa530b4..ca73e5f 100644
--- a/src/db/queries.rs
+++ b/src/db/queries.rs
@@ -833,7 +833,7 @@ pub fn put_world_snapshot(writer: &Writer, members: &[WorldMember]) -> Result<i6
let mut sorted = members.to_vec();
sorted.sort();
sorted.dedup();
- let hash = crate::hash::canonical_json(&sorted);
+ let hash = crate::hash::canonical_json(&sorted)?;
let json = serde_json::to_string(&sorted)?;
let at = time::now();
writer.tx(move |tx| {
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)?)
}
diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs
index 459cea6..8f4012e 100644
--- a/src/pipeline/mod.rs
+++ b/src/pipeline/mod.rs
@@ -279,7 +279,7 @@ pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result<
let pb = db::get_pkgbase_by_id(db, c.pkgbase_id)?
.ok_or_else(|| Error::not_found("pkgbase"))?;
let world = publish::index_world(db)?;
- let world_hash = crate::hash::canonical_json(&world);
+ let world_hash = crate::hash::canonical_json(&world)?;
let id = builds::build_id(&pb.name, &c.identity_hash, &world_hash, &cfg.build_profile);
let world_id = db::put_world_snapshot(&db.writer, &world)?;
builds::enqueue(db, &id, pb.id, Some(c.id), "new_version", Some(world_id), &cfg.build_profile, 0)?;
@@ -298,7 +298,7 @@ pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<St
rel.aur_commit, rel.recipe_hash
));
let world = publish::index_world(db)?;
- let world_hash = crate::hash::canonical_json(&world);
+ let world_hash = crate::hash::canonical_json(&world)?;
let id = builds::build_id(pkgbase, &identity, &world_hash, &cfg.build_profile);
let world_id = db::put_world_snapshot(&db.writer, &world)?;
builds::enqueue(db, &id, pb.id, None, "manual_rebuild", Some(world_id), &cfg.build_profile, 1)?;
diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs
index 50e41d3..6bdf12c 100644
--- a/src/pipeline/steps.rs
+++ b/src/pipeline/steps.rs
@@ -103,7 +103,7 @@ fn plan(ctx: &Ctx) -> Result<StepResult> {
return Ok(StepResult::Blocked(missing));
}
let world = crate::pipeline::publish::index_world(&ctx.db)?;
- let hash = crate::hash::canonical_json(&world);
+ let hash = crate::hash::canonical_json(&world)?;
ctx.log_line(&format!(
" deps: {} ours/official, {} from official repos, world {}",
wanted.len() - official,
diff --git a/src/watch/detect.rs b/src/watch/detect.rs
index 3134e19..71d1b29 100644
--- a/src/watch/detect.rs
+++ b/src/watch/detect.rs
@@ -174,7 +174,7 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor
upstream_pins: pins.clone(),
source_digests: digests.clone(),
};
- let identity_hash = identity.hash();
+ let identity_hash = identity.hash()?;
let snap_id = db::put_snapshot(
&db.writer,
pb.id,
diff --git a/tests/hash.rs b/tests/hash.rs
new file mode 100644
index 0000000..427f8ae
--- /dev/null
+++ b/tests/hash.rs
@@ -0,0 +1,83 @@
+//! The digest helpers (§3, §5.1a).
+//!
+//! `sha256` hex is the currency of identity and provenance here, and one of
+//! those digests — `Identity::hash` — is the value a reviewer's approval echoes
+//! back. Everything that guards "we published what we reviewed" rests on that
+//! digest being a function of the identity and of nothing else: not of the
+//! order fields were declared in, and never of whether serialization happened
+//! to fail.
+
+use std::collections::HashMap;
+
+use aur_build::db::model::Identity;
+use aur_build::hash;
+
+/// A value that refuses to be serialized, which is the input the old
+/// implementation answered with `"{}"` — a digest every failed value shared.
+struct Unserializable;
+
+impl serde::Serialize for Unserializable {
+ fn serialize<S: serde::Serializer>(&self, _s: S) -> Result<S::Ok, S::Error> {
+ Err(serde::ser::Error::custom("this value cannot be serialized"))
+ }
+}
+
+#[test]
+fn a_value_that_cannot_be_serialized_is_an_error_not_an_empty_object() {
+ let err = hash::canonical_json(&Unserializable).unwrap_err();
+ assert!(err.to_string().contains("cannot be serialized"), "the failure was swallowed: {err}");
+ // The point of propagating: two different unserializable values now fail
+ // loudly instead of hashing to the same digest as each other.
+ assert!(hash::canonical_json(&Unserializable).is_err());
+}
+
+#[test]
+fn the_rendering_is_canonical_in_fact_not_in_name() {
+ // Same fields, different declaration order: routed through `Value`, both
+ // come out with the keys sorted, so the bytes — and any digest of them —
+ // are the same.
+ #[derive(serde::Serialize)]
+ struct Ab {
+ alpha: String,
+ beta: String,
+ }
+ #[derive(serde::Serialize)]
+ struct Ba {
+ beta: String,
+ alpha: String,
+ }
+ let ab = hash::canonical_json(&Ab { alpha: "1".into(), beta: "2".into() }).unwrap();
+ let ba = hash::canonical_json(&Ba { beta: "2".into(), alpha: "1".into() }).unwrap();
+ assert_eq!(ab, ba, "field declaration order leaked into the rendering: {ab} vs {ba}");
+ assert_eq!(ab, r#"{"alpha":"1","beta":"2"}"#, "not the compact sorted rendering");
+
+ // Same for a map assembled in an arbitrary order.
+ let mut one = HashMap::new();
+ one.insert("z", 1);
+ one.insert("m", 2);
+ one.insert("a", 3);
+ let mut two = HashMap::new();
+ two.insert("a", 3);
+ two.insert("m", 2);
+ two.insert("z", 1);
+ assert_eq!(hash::canonical_json(&one).unwrap(), hash::canonical_json(&two).unwrap());
+}
+
+#[test]
+fn the_identity_digest_is_a_function_of_the_identity_alone() {
+ let base = Identity {
+ aur_commit: "cafe123".into(),
+ epoch: "0".into(),
+ pkgver: "1.2.3".into(),
+ pkgrel: "1".into(),
+ upstream_pins: vec![],
+ source_digests: vec![],
+ };
+ let hash_of = |i: &Identity| i.hash().unwrap();
+ assert!(hash_of(&base).starts_with("sha256:"));
+ assert_eq!(hash_of(&base), hash_of(&base.clone()), "the same identity hashed twice, twice differently");
+ // Every element of the tuple is part of the key (§5.1a).
+ assert_ne!(hash_of(&base), hash_of(&Identity { pkgrel: "2".into(), ..base.clone() }));
+ assert_ne!(hash_of(&base), hash_of(&Identity { epoch: "1".into(), ..base.clone() }));
+ assert_ne!(hash_of(&base), hash_of(&Identity { aur_commit: "cafe124".into(), ..base.clone() }));
+}
diff --git a/tests/vcs.rs b/tests/vcs.rs
index 2572c60..df0d756 100644
--- a/tests/vcs.rs
+++ b/tests/vcs.rs
@@ -108,7 +108,7 @@ fn stage_b_resolves_pkgver_and_captures_the_pins() {
source_digests: vec![],
};
let without = Identity { upstream_pins: vec![], ..with_pins.clone() };
- assert_ne!(with_pins.hash(), without.hash(), "pins must be in identity_hash");
+ assert_ne!(with_pins.hash().unwrap(), without.hash().unwrap(), "pins must be in identity_hash");
}
#[test]