Skip to main content

vouch_core/
jcs.rs

1//! JSON Canonicalization Scheme (JCS) per RFC 8785.
2//!
3//! Byte-exact port of the TypeScript SDK `canonicalize()`
4//! (packages/sdk-ts/src/jcs.ts) and `vouch/jcs.py`. Rules:
5//!   - object members are sorted by UTF-16 code-unit order (matching ECMAScript
6//!     Array.prototype.sort, which the reference SDK uses; for BMP code points
7//!     this equals the code-point order RFC 8785 3.2 requires),
8//!   - strings are escaped per JSON.stringify,
9//!   - numbers use ECMAScript ToString, and -0 normalizes to 0.
10//!
11//! Cross-implementation interop is REQUIRED: this MUST produce byte-identical
12//! output to the TypeScript and Python implementations for the same input.
13
14#[allow(unused_imports)]
15use crate::prelude::*;
16
17use core::cmp::Ordering;
18use serde_json::Value;
19
20/// Canonicalize a JSON value to its RFC 8785 UTF-8 byte sequence (for hashing
21/// and signing).
22pub fn canonicalize(value: &Value) -> Vec<u8> {
23    canonicalize_to_string(value).into_bytes()
24}
25
26/// Canonicalize to a string (useful for debugging and vector comparison).
27pub fn canonicalize_to_string(value: &Value) -> String {
28    let mut out = String::new();
29    serialize(value, &mut out);
30    out
31}
32
33/// Writes `value` in canonical form. It walks the value with its own stack
34/// instead of recursing, so the call stack it needs does not grow with how
35/// deeply the value nests (on a microcontroller that matters).
36fn serialize(value: &Value, out: &mut String) {
37    enum Frame<'a> {
38        Array(core::slice::Iter<'a, Value>, bool),
39        Object(&'a serde_json::Map<String, Value>, Vec<&'a String>, usize),
40    }
41    let mut stack: Vec<Frame<'_>> = Vec::new();
42    let mut next: Option<&Value> = Some(value);
43    loop {
44        if let Some(v) = next.take() {
45            match v {
46                Value::Null => out.push_str("null"),
47                Value::Bool(true) => out.push_str("true"),
48                Value::Bool(false) => out.push_str("false"),
49                Value::Number(n) => out.push_str(&format_number(n)),
50                Value::String(s) => escape_string(s, out),
51                Value::Array(items) => {
52                    out.push('[');
53                    stack.push(Frame::Array(items.iter(), true));
54                }
55                Value::Object(map) => {
56                    let mut keys: Vec<&String> = map.keys().collect();
57                    keys.sort_by(|a, b| utf16_cmp(a, b));
58                    out.push('{');
59                    stack.push(Frame::Object(map, keys, 0));
60                }
61            }
62        }
63        let Some(top) = stack.last_mut() else {
64            break;
65        };
66        match top {
67            Frame::Array(items, first) => match items.next() {
68                Some(item) => {
69                    if !*first {
70                        out.push(',');
71                    }
72                    *first = false;
73                    next = Some(item);
74                }
75                None => {
76                    out.push(']');
77                    stack.pop();
78                }
79            },
80            Frame::Object(map, keys, i) => {
81                if *i < keys.len() {
82                    if *i > 0 {
83                        out.push(',');
84                    }
85                    let k = keys[*i];
86                    escape_string(k, out);
87                    out.push(':');
88                    next = Some(&map[k]);
89                    *i += 1;
90                } else {
91                    out.push('}');
92                    stack.pop();
93                }
94            }
95        }
96    }
97}
98
99/// Compare two strings by their UTF-16 code-unit sequence (ECMAScript string
100/// ordering, used by the reference SDK's `Object.keys(obj).sort()`).
101fn utf16_cmp(a: &str, b: &str) -> Ordering {
102    a.encode_utf16().cmp(b.encode_utf16())
103}
104
105/// JSON string escaping matching ECMAScript JSON.stringify. serde_json escapes
106/// identically for the relevant cases (quote, backslash, control chars as
107/// \b \t \n \f \r or \u00xx; non-ASCII emitted raw as UTF-8), so it is reused
108/// as a single source of truth.
109fn escape_string(s: &str, out: &mut String) {
110    let encoded = serde_json::to_string(s).expect("a string is always serializable");
111    out.push_str(&encoded);
112}
113
114/// Number formatting per RFC 8785 3.2.2.5 (ECMAScript ToString), matching
115/// jcs.ts `formatNumber`.
116fn format_number(n: &serde_json::Number) -> String {
117    if let Some(i) = n.as_i64() {
118        return i.to_string();
119    }
120    if let Some(u) = n.as_u64() {
121        return u.to_string();
122    }
123    let f = n.as_f64().expect("a serde_json number is i64, u64, or f64");
124    if f == 0.0 {
125        // Normalizes both 0.0 and -0.0 to "0" (RFC 8785).
126        return "0".to_string();
127    }
128    // ECMAScript Number.prototype.toString via ryu-js. This matches JavaScript
129    // exactly, including the exponential thresholds and format ("1e+21",
130    // "1e-7"), so the canonical form is byte-identical to the TypeScript SDK and
131    // to a conformant Python implementation for any finite number.
132    let mut buf = ryu_js::Buffer::new();
133    buf.format(f).to_string()
134}
135
136/// The deepest nesting [`parse_deep`] reads: a value the reference can
137/// canonicalize (up to 500 levels) fits, inside a request, with room.
138pub const MAX_DEEP_NESTING: usize = 512;
139
140/// Read JSON text that may nest deeper than the reader's default of 128
141/// levels, up to [`MAX_DEEP_NESTING`] (checked by a scan before parsing, so
142/// the parser's stack stays bounded). For entries whose values the reference
143/// canonicalizes whatever their depth: proofs, signing inputs, chains of
144/// trust credentials.
145///
146/// The `no_std` build has no such allowance: it refuses text nested past
147/// [`crate::nesting::NO_STD_MAX_NESTING`] with the same scan, before parsing,
148/// and reads the rest with the reader's default limit.
149pub fn parse_deep(text: &str) -> crate::error::Result<serde_json::Value> {
150    #[cfg(not(feature = "std"))]
151    {
152        crate::nesting::parse(text)
153    }
154    #[cfg(feature = "std")]
155    parse_deep_std(text)
156}
157
158#[cfg(feature = "std")]
159fn parse_deep_std(text: &str) -> crate::error::Result<serde_json::Value> {
160    use crate::error::CoreError;
161    if crate::did_webvh::json_too_deep(text.as_bytes(), MAX_DEEP_NESTING) {
162        return Err(CoreError::Json("the request is nested too deeply".into()));
163    }
164    let mut de = serde_json::Deserializer::from_str(text);
165    de.disable_recursion_limit();
166    let value: serde_json::Value = serde::Deserialize::deserialize(&mut de)
167        .map_err(|e| CoreError::Json(format!("json: {e}")))?;
168    de.end()
169        .map_err(|e| CoreError::Json(format!("json: {e}")))?;
170    Ok(value)
171}
172
173/// How deep a request may nest and still be read on the caller's own stack.
174pub const SHALLOW_NESTING: usize = 128;
175/// The stack a deeper request is read on: the core's walkers (the reader,
176/// canonicalization, comparison, dropping) take about 300 KiB at
177/// [`MAX_DEEP_NESTING`] levels, more than a small thread (a 128 KiB musl
178/// default, a 256 KiB worker) has.
179pub const DEEP_STACK_BYTES: usize = 8 << 20;
180
181/// Whether the request `text` nests deeper than [`SHALLOW_NESTING`] levels,
182/// so it is read on a stack of its own ([`on_deep_stack`]).
183pub fn needs_deep_stack(text: &str) -> bool {
184    crate::did_webvh::json_too_deep(text.as_bytes(), SHALLOW_NESTING)
185}
186
187/// Run `f` (which reads and answers a request) where the request's depth
188/// has the stack it needs: on the caller's thread unless `deep` (see
189/// [`needs_deep_stack`]), else on a thread of its own with
190/// [`DEEP_STACK_BYTES`] of stack, joined before this returns. A panic in `f`
191/// carries on in the caller. In WebAssembly there are no threads: `f` runs
192/// in place (the module's own stack is 1 MiB). Part of the `std` build: the
193/// `no_std` build never reads a request that deep.
194#[cfg(feature = "std")]
195pub fn on_deep_stack<T: Send>(deep: bool, f: impl FnOnce() -> T + Send) -> T {
196    #[cfg(not(target_arch = "wasm32"))]
197    if deep {
198        let mut f = Some(f);
199        let joined = std::thread::scope(|s| {
200            let run = || (f.take().expect("runs once"))();
201            std::thread::Builder::new()
202                .stack_size(DEEP_STACK_BYTES)
203                .spawn_scoped(s, run)
204                .ok()
205                .map(|handle| handle.join())
206        });
207        return match joined {
208            Some(Ok(out)) => out,
209            Some(Err(panic)) => std::panic::resume_unwind(panic),
210            // No thread to be had: run in place.
211            None => (f.take().expect("not run"))(),
212        };
213    }
214    #[cfg(target_arch = "wasm32")]
215    let _ = deep;
216    f()
217}
218
219/// Wipe every string of a parsed request (its secrets travel as base64 or
220/// Multikey text) before the value is dropped. The walk keeps its own stack
221/// on the heap, so a deep value costs no call stack (the `no_std` build's
222/// callers may hand it any value).
223pub fn wipe_strings(value: &mut serde_json::Value) {
224    use zeroize::Zeroize;
225    let mut pending: alloc::vec::Vec<&mut serde_json::Value> = alloc::vec![value];
226    while let Some(v) = pending.pop() {
227        match v {
228            serde_json::Value::String(s) => s.zeroize(),
229            serde_json::Value::Array(items) => pending.extend(items.iter_mut()),
230            serde_json::Value::Object(map) => pending.extend(map.values_mut()),
231            _ => {}
232        }
233    }
234}
235
236/// An answer that may hold a secret (a decoded secret key, a recovered seed,
237/// recovery shares) as JSON text. The text is written into a buffer of
238/// exactly its size, so no growing buffer leaves a copy behind, and every
239/// string in the answer is wiped once it is written. The caller keeps the
240/// text in a `Zeroizing` wrapper while it holds it. Part of the `std` build,
241/// where the secrets it writes (recovery shares) are made.
242#[cfg(feature = "std")]
243pub fn secret_json_text(mut value: serde_json::Value) -> String {
244    let text = exact_json_text(&value);
245    wipe_strings(&mut value);
246    text
247}
248
249/// JSON text of a value that holds a secret, written into a buffer of exactly
250/// its size (so no growing buffer leaves a copy behind) and held in a
251/// `Zeroizing` wrapper. The value itself is left as it is.
252#[cfg(feature = "std")]
253pub(crate) fn secret_value_text(value: &serde_json::Value) -> zeroize::Zeroizing<String> {
254    zeroize::Zeroizing::new(exact_json_text(value))
255}
256
257/// `value.to_string()`, written in two passes: one to count the bytes, one to
258/// write them into a buffer of that size.
259#[cfg(feature = "std")]
260fn exact_json_text(value: &serde_json::Value) -> String {
261    struct Count(usize);
262    impl std::io::Write for Count {
263        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
264            self.0 += buf.len();
265            Ok(buf.len())
266        }
267        fn flush(&mut self) -> std::io::Result<()> {
268            Ok(())
269        }
270    }
271    let mut count = Count(0);
272    // Writing a Value to memory cannot fail.
273    let _ = serde_json::to_writer(&mut count, value);
274    let mut buf = Vec::with_capacity(count.0);
275    let _ = serde_json::to_writer(&mut buf, value);
276    String::from_utf8(buf).unwrap_or_default()
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    /// The walk keeps its own stack: a value nested 10,000 deep canonicalizes
284    /// on a 64 KiB thread stack, the same bytes as a plain string build.
285    #[test]
286    fn deep_nesting_needs_no_deep_call_stack() {
287        let depth = 10_000;
288        let out = std::thread::Builder::new()
289            .stack_size(64 * 1024)
290            .spawn(move || {
291                let mut v = json!(1);
292                for _ in 0..depth {
293                    let mut m = serde_json::Map::new();
294                    m.insert("a".into(), v);
295                    v = Value::Object(m);
296                }
297                let text = canonicalize_to_string(&v);
298                // Dropping the value recurses (serde_json), so it is left.
299                core::mem::forget(v);
300                text
301            })
302            .unwrap()
303            .join()
304            .unwrap();
305        let want = format!("{}1{}", "{\"a\":".repeat(depth), "}".repeat(depth));
306        assert_eq!(out, want);
307    }
308    use serde_json::json;
309
310    #[test]
311    #[cfg(feature = "std")]
312    fn a_deep_request_is_read_on_a_stack_of_its_own() {
313        // 500 levels inside a request, on a thread far smaller than the
314        // walkers need: parsed, canonicalized and dropped on the deep stack.
315        let text = format!("{{\"x\":{}1{}}}", "[".repeat(500), "]".repeat(500));
316        assert!(needs_deep_stack(&text));
317        assert!(!needs_deep_stack("[[1]]"));
318        let small = std::thread::Builder::new()
319            .stack_size(64 * 1024)
320            .spawn(move || {
321                on_deep_stack(needs_deep_stack(&text), || {
322                    let value = parse_deep(&text).unwrap();
323                    canonicalize_to_string(&value).len()
324                })
325            })
326            .unwrap();
327        assert_eq!(small.join().unwrap(), 1007);
328    }
329
330    #[test]
331    #[cfg(feature = "std")]
332    fn a_secret_answer_is_written_at_its_exact_size() {
333        let value = json!({"seed": "c2VjcmV0", "keys": [{"private_key": "a2V5"}], "n": 1});
334        let text = secret_json_text(value.clone());
335        assert_eq!(text, value.to_string());
336        assert_eq!(text.capacity(), text.len());
337    }
338
339    #[test]
340    #[cfg_attr(feature = "std", ignore = "checks the no_std build")]
341    fn no_std_parse_deep_refuses_past_the_cap() {
342        let nested = |n: usize| format!("{}1{}", "[".repeat(n), "]".repeat(n));
343        assert!(parse_deep(&nested(crate::nesting::NO_STD_MAX_NESTING)).is_ok());
344        for n in [crate::nesting::NO_STD_MAX_NESTING + 1, 129, 500] {
345            let e = parse_deep(&nested(n)).unwrap_err();
346            assert_eq!(e.to_string(), crate::nesting::too_deep().to_string());
347        }
348    }
349
350    #[test]
351    fn empty_containers() {
352        assert_eq!(canonicalize_to_string(&json!({})), "{}");
353        assert_eq!(canonicalize_to_string(&json!([])), "[]");
354    }
355
356    #[test]
357    fn sorts_object_keys() {
358        assert_eq!(
359            canonicalize_to_string(&json!({"b": 1, "a": 2, "c": 3})),
360            "{\"a\":2,\"b\":1,\"c\":3}"
361        );
362    }
363
364    #[test]
365    fn array_preserves_order() {
366        assert_eq!(canonicalize_to_string(&json!([3, 1, 2])), "[3,1,2]");
367    }
368
369    #[test]
370    fn negative_zero_normalized() {
371        assert_eq!(canonicalize_to_string(&json!({"n": -0})), "{\"n\":0}");
372    }
373}