Skip to main content

subc_config/
canonical.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use sha2::{Digest as _, Sha256};
4use std::fmt;
5
6/// Domain purposes are fixed protocol strings, not caller-selected labels.
7pub const PURPOSE_VALUE: &str = "value";
8pub const PURPOSE_SCHEMA: &str = "schema";
9pub const PURPOSE_DECLARATION: &str = "declaration";
10pub const PURPOSE_REVIEW: &str = "review";
11pub const PURPOSE_APPLY_PLAN: &str = "apply-plan";
12pub const PURPOSE_PLAN: &str = "plan";
13pub const PURPOSE_CHANGESET: &str = "changeset";
14pub const PURPOSE_GENERATION: &str = "generation";
15pub const PURPOSE_SNAPSHOT: &str = "snapshot";
16pub const DIGEST_VERSION: u32 = 1;
17const SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
18
19#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum CanonicalError {
22    NumberNotLossless,
23    InvalidDigest,
24    UnknownPurpose,
25    Serialization,
26}
27
28impl fmt::Display for CanonicalError {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        write!(f, "{self:?}")
31    }
32}
33impl std::error::Error for CanonicalError {}
34
35/// A full SHA-256, encoded as `sha256:` followed by 64 lowercase hex characters.
36#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
37#[serde(try_from = "String", into = "String")]
38#[non_exhaustive]
39pub struct Digest(String);
40
41impl Digest {
42    pub fn new(encoded: impl Into<String>) -> Result<Self, CanonicalError> {
43        let encoded = encoded.into();
44        let hex = encoded
45            .strip_prefix("sha256:")
46            .ok_or(CanonicalError::InvalidDigest)?;
47        if hex.len() != 64
48            || !hex
49                .bytes()
50                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
51        {
52            return Err(CanonicalError::InvalidDigest);
53        }
54        Ok(Self(encoded))
55    }
56    pub fn as_str(&self) -> &str {
57        &self.0
58    }
59}
60impl TryFrom<String> for Digest {
61    type Error = CanonicalError;
62    fn try_from(s: String) -> Result<Self, Self::Error> {
63        Self::new(s)
64    }
65}
66impl From<Digest> for String {
67    fn from(d: Digest) -> Self {
68        d.0
69    }
70}
71impl fmt::Display for Digest {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(&self.0)
74    }
75}
76
77/// Exact file bytes use plain SHA-256, independently of parsed-value envelopes.
78pub fn raw_digest(bytes: &[u8]) -> Digest {
79    let hash = Sha256::digest(bytes);
80    let mut text = String::from("sha256:");
81    for byte in hash {
82        use std::fmt::Write;
83        write!(text, "{byte:02x}").expect("writing a String");
84    }
85    Digest(text)
86}
87
88/// SHA-256 of the RFC 8785 envelope `{domain, version, value}`.
89pub fn digest(purpose: &str, value: &Value) -> Result<Digest, CanonicalError> {
90    if ![
91        PURPOSE_VALUE,
92        PURPOSE_SCHEMA,
93        PURPOSE_DECLARATION,
94        PURPOSE_REVIEW,
95        PURPOSE_APPLY_PLAN,
96        PURPOSE_PLAN,
97        PURPOSE_CHANGESET,
98        PURPOSE_GENERATION,
99        PURPOSE_SNAPSHOT,
100    ]
101    .contains(&purpose)
102    {
103        return Err(CanonicalError::UnknownPurpose);
104    }
105    let envelope = serde_json::json!({"domain":format!("subc-config/{purpose}"), "version":DIGEST_VERSION, "value":value});
106    Ok(raw_digest(&canonical_json(&envelope)?))
107}
108
109/// RFC 8785 with the config-gate lossless-number restriction. Keys sort by UTF-16,
110/// not Rust's UTF-8 string order, even when serde_json's preserve_order is unified.
111pub fn canonical_json(value: &Value) -> Result<Vec<u8>, CanonicalError> {
112    let mut output = Vec::new();
113    write_value(value, &mut output)?;
114    Ok(output)
115}
116
117fn write_value(value: &Value, out: &mut Vec<u8>) -> Result<(), CanonicalError> {
118    match value {
119        Value::Null => out.extend_from_slice(b"null"),
120        Value::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
121        Value::String(s) => {
122            out.extend(serde_json::to_vec(s).map_err(|_| CanonicalError::Serialization)?)
123        }
124        Value::Number(n) => {
125            let number = n.as_f64().ok_or(CanonicalError::NumberNotLossless)?;
126            if !number.is_finite() || (number.fract() == 0.0 && number.abs() > SAFE_INTEGER) {
127                return Err(CanonicalError::NumberNotLossless);
128            }
129            out.extend_from_slice(ecmascript_number(number).as_bytes());
130        }
131        Value::Array(a) => {
132            out.push(b'[');
133            for (i, item) in a.iter().enumerate() {
134                if i != 0 {
135                    out.push(b',');
136                }
137                write_value(item, out)?;
138            }
139            out.push(b']');
140        }
141        Value::Object(o) => {
142            out.push(b'{');
143            let mut entries: Vec<_> = o.iter().collect();
144            entries.sort_unstable_by(|(a, _), (b, _)| a.encode_utf16().cmp(b.encode_utf16()));
145            for (i, (key, item)) in entries.into_iter().enumerate() {
146                if i != 0 {
147                    out.push(b',');
148                }
149                out.extend(serde_json::to_vec(key).map_err(|_| CanonicalError::Serialization)?);
150                out.push(b':');
151                write_value(item, out)?;
152            }
153            out.push(b'}');
154        }
155    }
156    Ok(())
157}
158
159// Ryu supplies the shortest round-tripping digits. ECMAScript places the decimal
160// point and switches to scientific notation at 1e-6 and 1e21, unlike ryu's display.
161fn ecmascript_number(n: f64) -> String {
162    if n == 0.0 {
163        return "0".into();
164    }
165    let mut buffer = ryu::Buffer::new();
166    let printed = buffer.format_finite(n.abs());
167    let (mantissa, exponent) = printed.split_once('e').unwrap_or((printed, "0"));
168    let exponent: i32 = exponent.parse().expect("ryu exponent");
169    let dot = mantissa.find('.').unwrap_or(mantissa.len()) as i32;
170    let mut digits: String = mantissa.chars().filter(|c| *c != '.').collect();
171    let mut point = dot + exponent;
172    while digits.starts_with('0') {
173        digits.remove(0);
174        point -= 1;
175    }
176    while digits.ends_with('0') {
177        digits.pop();
178    }
179    let mut result = if n < 0.0 {
180        "-".to_owned()
181    } else {
182        String::new()
183    };
184    let k = digits.len() as i32;
185    if k <= point && point <= 21 {
186        result.push_str(&digits);
187        result.extend(std::iter::repeat_n('0', (point - k) as usize));
188    } else if 0 < point && point <= 21 {
189        result.push_str(&digits[..point as usize]);
190        result.push('.');
191        result.push_str(&digits[point as usize..]);
192    } else if -6 < point && point <= 0 {
193        result.push_str("0.");
194        result.extend(std::iter::repeat_n('0', (-point) as usize));
195        result.push_str(&digits);
196    } else {
197        result.push_str(&digits[..1]);
198        if k > 1 {
199            result.push('.');
200            result.push_str(&digits[1..]);
201        }
202        result.push('e');
203        let e = point - 1;
204        if e >= 0 {
205            result.push('+');
206        }
207        result.push_str(&e.to_string());
208    }
209    result
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215    use serde_json::json;
216
217    #[test]
218    fn canonical_contract_keys_and_envelope() {
219        let value = json!({"\u{e000}":1,"\u{10000}":2,"a":["\n",false]});
220        assert_eq!(
221            String::from_utf8(canonical_json(&value).unwrap()).unwrap(),
222            "{\"a\":[\"\\n\",false],\"𐀀\":2,\"\":1}"
223        );
224        assert_eq!(
225            raw_digest(b"abc").as_str(),
226            "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
227        );
228        let expected =
229            raw_digest(b"{\"domain\":\"subc-config/value\",\"value\":false,\"version\":1}");
230        assert_eq!(digest(PURPOSE_VALUE, &json!(false)).unwrap(), expected);
231        assert_ne!(digest(PURPOSE_SCHEMA, &json!(false)).unwrap(), expected);
232    }
233
234    #[test]
235    fn canonical_contract_rfc8785_appendix_b() {
236        // RFC 8785 Appendix B. Integral values outside the agreed config range
237        // still exercise ES formatting here, but the public canonicalizer refuses them.
238        let cases = [
239            (0x0000000000000000, "0"),
240            (0x8000000000000000, "0"),
241            (0x0000000000000001, "5e-324"),
242            (0x8000000000000001, "-5e-324"),
243            (0x7fefffffffffffff, "1.7976931348623157e+308"),
244            (0xffefffffffffffff, "-1.7976931348623157e+308"),
245            (0x4340000000000000, "9007199254740992"),
246            (0xc340000000000000, "-9007199254740992"),
247            (0x4430000000000000, "295147905179352830000"),
248            (0x44b52d02c7e14af5, "9.999999999999997e+22"),
249            (0x44b52d02c7e14af6, "1e+23"),
250            (0x44b52d02c7e14af7, "1.0000000000000001e+23"),
251            (0x444b1ae4d6e2ef4e, "999999999999999700000"),
252            (0x444b1ae4d6e2ef4f, "999999999999999900000"),
253            (0x444b1ae4d6e2ef50, "1e+21"),
254            (0x3eb0c6f7a0b5ed8c, "9.999999999999997e-7"),
255            (0x3eb0c6f7a0b5ed8d, "0.000001"),
256            (0x41b3de4355555553, "333333333.3333332"),
257            (0x41b3de4355555554, "333333333.33333325"),
258            (0x41b3de4355555555, "333333333.3333333"),
259            (0x41b3de4355555556, "333333333.3333334"),
260            (0x41b3de4355555557, "333333333.33333343"),
261            (0xbecbf647612f3696, "-0.0000033333333333333333"),
262            (0x43143ff3c1cb0959, "1424953923781206.2"),
263        ];
264        for (bits, expected) in cases {
265            let number = f64::from_bits(bits);
266            assert_eq!(ecmascript_number(number), expected, "{bits:016x}");
267            if number.fract() == 0.0 && number.abs() > SAFE_INTEGER {
268                assert_eq!(
269                    canonical_json(&json!(number)),
270                    Err(CanonicalError::NumberNotLossless)
271                );
272            } else {
273                assert_eq!(canonical_json(&json!(number)).unwrap(), expected.as_bytes());
274            }
275        }
276        for n in [
277            json!(9_007_199_254_740_992_u64),
278            json!(-9_007_199_254_740_992_i64),
279        ] {
280            assert!(canonical_json(&n).is_err());
281        }
282    }
283}