reallyme-codec-jcs 0.3.1

JSON Canonicalization Scheme support for ReallyMe Codec.
Documentation
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
// SPDX-FileCopyrightText: 2026 ReallyMe LLC
//
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::cmp::Ordering;

use serde_json::Value;
use zeroize::Zeroizing;

use crate::error::JcsError;
use crate::parse_json::{parse_json_text, SensitiveJsonValue, SensitiveNumber};

const MAX_INTEROPERABLE_INTEGER: u64 = 9_007_199_254_740_991;
const MIN_INTEROPERABLE_INTEGER: i64 = -9_007_199_254_740_991;
const MAX_INTEROPERABLE_INTEGER_F64: f64 = 9_007_199_254_740_991.0;
const MIN_INTEROPERABLE_INTEGER_F64: f64 = -9_007_199_254_740_991.0;

/// Canonicalize a trusted, already-materialized JSON value according to RFC
/// 8785 (JSON Canonicalization Scheme).
///
/// Integer and integer-valued binary64 numbers are rejected outside the
/// interoperable `[-(2^53)+1, (2^53)-1]` range. This function cannot determine
/// whether a source document contained duplicate object member names because
/// [`Value`] has already discarded that provenance. It is therefore intended
/// only for values constructed programmatically or produced by a parser that
/// already enforced the same duplicate-member policy. Call
/// [`canonicalize_json_text`] at every untrusted text boundary.
pub fn canonicalize_trusted_json_value(value: &Value) -> Result<String, JcsError> {
    let output_length = canonicalized_len(value, 0)?;
    let mut output = Zeroizing::new(String::with_capacity(output_length));
    write_canonical(value, 0, &mut output)?;
    if output.len() != output_length {
        return Err(JcsError::SerializationError);
    }
    Ok(core::mem::take(&mut *output))
}

/// Parse and canonicalize one untrusted JSON text according to RFC 8785.
///
/// Unlike deserializing directly into [`Value`], this entry point detects and
/// rejects duplicate object member names instead of silently retaining one
/// value. It also rejects trailing data. Integer tokens retained exactly as
/// `i64`, `u64`, or integer-valued binary64 are rejected outside the
/// interoperable range, while non-integer binary64 numbers follow RFC 8785's
/// required ECMAScript rounding behavior.
pub fn canonicalize_json_text(input: &str) -> Result<String, JcsError> {
    let value = parse_json_text(input)?;
    canonicalize_sensitive_json_value(&value)
}

/// `depth` counts the array/object containers currently open, bounded by
/// [`MAX_NESTING_DEPTH`](crate::MAX_NESTING_DEPTH) as defense in depth
/// against a `Value` that was built without a parser depth limit.
fn write_canonical(value: &Value, depth: usize, output: &mut String) -> Result<(), JcsError> {
    match value {
        Value::Null => output.push_str("null"),
        Value::Bool(false) => output.push_str("false"),
        Value::Bool(true) => output.push_str("true"),
        Value::Number(value) => write_canonical_number(value, output)?,
        Value::String(value) => write_escaped_string(value, output),
        Value::Array(values) => write_canonical_array(values, depth, output)?,
        Value::Object(values) => {
            let child_depth = descend(depth)?;
            let mut keys: Vec<&String> = values.keys().collect();
            // RFC 8785 §3.2.3: sort by UTF-16 code unit, NOT by Unicode
            // scalar value. The two orders agree across the BMP but diverge
            // for supplementary-plane names, whose UTF-16 surrogate code
            // units (0xD800–0xDFFF) sort below BMP code points such as
            // 0xE000–0xFFFF. A plain `str` sort (UTF-8 / code-point order)
            // would place them differently and yield non-canonical output.
            keys.sort_by(|left, right| utf16_cmp(left, right));

            output.push('{');
            for (index, key) in keys.iter().enumerate() {
                if index > 0 {
                    output.push(',');
                }
                write_escaped_string(key, output);
                output.push(':');
                write_canonical(&values[*key], child_depth, output)?;
            }
            output.push('}');
        }
    }
    Ok(())
}

/// Enters one nesting level, rejecting input deeper than
/// [`MAX_NESTING_DEPTH`](crate::MAX_NESTING_DEPTH).
fn descend(depth: usize) -> Result<usize, JcsError> {
    let next = depth.checked_add(1).ok_or(JcsError::DepthExceeded)?;
    if next > crate::MAX_NESTING_DEPTH {
        return Err(JcsError::DepthExceeded);
    }
    Ok(next)
}

/// Compares two strings by their UTF-16 code units, as RFC 8785 requires
/// for object member ordering.
fn utf16_cmp(left: &str, right: &str) -> Ordering {
    left.encode_utf16().cmp(right.encode_utf16())
}

fn write_canonical_number(value: &serde_json::Number, output: &mut String) -> Result<(), JcsError> {
    if let Some(unsigned) = value.as_u64() {
        if unsigned > MAX_INTEROPERABLE_INTEGER {
            return Err(JcsError::IntegerOutsideInteroperableRange);
        }
        let mut buffer = itoa::Buffer::new();
        output.push_str(buffer.format(unsigned));
        return Ok(());
    }
    if let Some(signed) = value.as_i64() {
        if signed < MIN_INTEROPERABLE_INTEGER {
            return Err(JcsError::IntegerOutsideInteroperableRange);
        }
        let mut buffer = itoa::Buffer::new();
        output.push_str(buffer.format(signed));
        return Ok(());
    }

    let float = value.as_f64().ok_or(JcsError::SerializationError)?;
    if !float.is_finite() {
        return Err(JcsError::NonFiniteNumber);
    }
    validate_interoperable_float_integer(float)?;

    // RFC 8785 §3.2.2.3 mandates the ECMAScript `Number.prototype.toString`
    // algorithm (exponent thresholds, exponent signs, shortest round-trip
    // digits). `serde_json`/`ryu` do not fully match those ES6 formatting
    // rules, so we use `ryu-js` after applying ReallyMe's stricter
    // interoperable-integer policy.
    let mut buffer = ryu_js::Buffer::new();
    output.push_str(buffer.format_finite(float));
    Ok(())
}

fn write_sensitive_number(value: &SensitiveNumber, output: &mut String) -> Result<(), JcsError> {
    match value {
        SensitiveNumber::Unsigned(unsigned) => {
            if *unsigned > MAX_INTEROPERABLE_INTEGER {
                return Err(JcsError::IntegerOutsideInteroperableRange);
            }
            let mut buffer = itoa::Buffer::new();
            output.push_str(buffer.format(*unsigned));
        }
        SensitiveNumber::Signed(signed) => {
            if *signed < MIN_INTEROPERABLE_INTEGER {
                return Err(JcsError::IntegerOutsideInteroperableRange);
            }
            let mut buffer = itoa::Buffer::new();
            output.push_str(buffer.format(*signed));
        }
        SensitiveNumber::Float(float) => {
            if !float.is_finite() {
                return Err(JcsError::NonFiniteNumber);
            }
            validate_interoperable_float_integer(*float)?;
            let mut buffer = ryu_js::Buffer::new();
            output.push_str(buffer.format_finite(*float));
        }
    }
    Ok(())
}

fn write_canonical_array(
    values: &[Value],
    depth: usize,
    output: &mut String,
) -> Result<(), JcsError> {
    let child_depth = descend(depth)?;
    output.push('[');
    for (index, item) in values.iter().enumerate() {
        if index > 0 {
            output.push(',');
        }
        write_canonical(item, child_depth, output)?;
    }
    output.push(']');
    Ok(())
}

fn canonicalized_len(value: &Value, depth: usize) -> Result<usize, JcsError> {
    match value {
        Value::Null => Ok("null".len()),
        Value::Bool(false) => Ok("false".len()),
        Value::Bool(true) => Ok("true".len()),
        Value::Number(value) => canonical_number_len(value),
        Value::String(value) => escaped_string_len(value),
        Value::Array(values) => canonical_array_len(values, depth),
        Value::Object(values) => canonical_object_len(values, depth),
    }
}

fn canonicalize_sensitive_json_value(value: &SensitiveJsonValue) -> Result<String, JcsError> {
    let output_length = canonicalized_sensitive_len(value, 0)?;
    let mut output = Zeroizing::new(String::with_capacity(output_length));
    write_sensitive_canonical(value, 0, &mut output)?;
    if output.len() != output_length {
        return Err(JcsError::SerializationError);
    }
    Ok(core::mem::take(&mut *output))
}

fn write_sensitive_canonical(
    value: &SensitiveJsonValue,
    depth: usize,
    output: &mut String,
) -> Result<(), JcsError> {
    match value {
        SensitiveJsonValue::Null => output.push_str("null"),
        SensitiveJsonValue::Bool(false) => output.push_str("false"),
        SensitiveJsonValue::Bool(true) => output.push_str("true"),
        SensitiveJsonValue::Number(value) => write_sensitive_number(value, output)?,
        SensitiveJsonValue::String(value) => write_escaped_string(value, output),
        SensitiveJsonValue::Array(values) => {
            let child_depth = descend(depth)?;
            output.push('[');
            for (index, item) in values.iter().enumerate() {
                if index > 0 {
                    output.push(',');
                }
                write_sensitive_canonical(item, child_depth, output)?;
            }
            output.push(']');
        }
        SensitiveJsonValue::Object(values) => {
            let child_depth = descend(depth)?;
            let mut keys: Vec<&String> = values.keys().collect();
            keys.sort_by(|left, right| utf16_cmp(left, right));

            output.push('{');
            for (index, key) in keys.iter().enumerate() {
                if index > 0 {
                    output.push(',');
                }
                write_escaped_string(key, output);
                output.push(':');
                let value = values.get(*key).ok_or(JcsError::SerializationError)?;
                write_sensitive_canonical(value, child_depth, output)?;
            }
            output.push('}');
        }
    }
    Ok(())
}

fn canonicalized_sensitive_len(
    value: &SensitiveJsonValue,
    depth: usize,
) -> Result<usize, JcsError> {
    match value {
        SensitiveJsonValue::Null => Ok("null".len()),
        SensitiveJsonValue::Bool(false) => Ok("false".len()),
        SensitiveJsonValue::Bool(true) => Ok("true".len()),
        SensitiveJsonValue::Number(value) => canonical_sensitive_number_len(value),
        SensitiveJsonValue::String(value) => escaped_string_len(value),
        SensitiveJsonValue::Array(values) => canonical_sensitive_array_len(values, depth),
        SensitiveJsonValue::Object(values) => canonical_sensitive_object_len(values, depth),
    }
}

fn canonical_sensitive_array_len(
    values: &[Box<SensitiveJsonValue>],
    depth: usize,
) -> Result<usize, JcsError> {
    let child_depth = descend(depth)?;
    let mut length = "["
        .len()
        .checked_add("]".len())
        .ok_or(JcsError::SerializationError)?;
    for (index, item) in values.iter().enumerate() {
        if index > 0 {
            length = length
                .checked_add(",".len())
                .ok_or(JcsError::SerializationError)?;
        }
        length = length
            .checked_add(canonicalized_sensitive_len(item, child_depth)?)
            .ok_or(JcsError::SerializationError)?;
    }
    Ok(length)
}

fn canonical_sensitive_object_len(
    values: &std::collections::BTreeMap<String, Box<SensitiveJsonValue>>,
    depth: usize,
) -> Result<usize, JcsError> {
    let child_depth = descend(depth)?;
    let mut keys: Vec<&String> = values.keys().collect();
    keys.sort_by(|left, right| utf16_cmp(left, right));

    let mut length = "{"
        .len()
        .checked_add("}".len())
        .ok_or(JcsError::SerializationError)?;
    for (index, key) in keys.iter().enumerate() {
        if index > 0 {
            length = length
                .checked_add(",".len())
                .ok_or(JcsError::SerializationError)?;
        }
        let value = values.get(*key).ok_or(JcsError::SerializationError)?;
        let value_length = canonicalized_sensitive_len(value, child_depth)?;
        length = length
            .checked_add(escaped_string_len(key)?)
            .and_then(|value| value.checked_add(":".len()))
            .and_then(|value| value.checked_add(value_length))
            .ok_or(JcsError::SerializationError)?;
    }
    Ok(length)
}

fn canonical_array_len(values: &[Value], depth: usize) -> Result<usize, JcsError> {
    let child_depth = descend(depth)?;
    let mut length = "["
        .len()
        .checked_add("]".len())
        .ok_or(JcsError::SerializationError)?;
    for (index, item) in values.iter().enumerate() {
        if index > 0 {
            length = length
                .checked_add(",".len())
                .ok_or(JcsError::SerializationError)?;
        }
        length = length
            .checked_add(canonicalized_len(item, child_depth)?)
            .ok_or(JcsError::SerializationError)?;
    }
    Ok(length)
}

fn canonical_object_len(
    values: &serde_json::Map<String, Value>,
    depth: usize,
) -> Result<usize, JcsError> {
    let child_depth = descend(depth)?;
    let mut keys: Vec<&String> = values.keys().collect();
    keys.sort_by(|left, right| utf16_cmp(left, right));

    let mut length = "{"
        .len()
        .checked_add("}".len())
        .ok_or(JcsError::SerializationError)?;
    for (index, key) in keys.iter().enumerate() {
        if index > 0 {
            length = length
                .checked_add(",".len())
                .ok_or(JcsError::SerializationError)?;
        }
        let value_length = canonicalized_len(&values[*key], child_depth)?;
        length = length
            .checked_add(escaped_string_len(key)?)
            .and_then(|value| value.checked_add(":".len()))
            .and_then(|value| value.checked_add(value_length))
            .ok_or(JcsError::SerializationError)?;
    }
    Ok(length)
}

fn canonical_number_len(value: &serde_json::Number) -> Result<usize, JcsError> {
    if let Some(unsigned) = value.as_u64() {
        if unsigned > MAX_INTEROPERABLE_INTEGER {
            return Err(JcsError::IntegerOutsideInteroperableRange);
        }
        let mut buffer = itoa::Buffer::new();
        return Ok(buffer.format(unsigned).len());
    }
    if let Some(signed) = value.as_i64() {
        if signed < MIN_INTEROPERABLE_INTEGER {
            return Err(JcsError::IntegerOutsideInteroperableRange);
        }
        let mut buffer = itoa::Buffer::new();
        return Ok(buffer.format(signed).len());
    }

    let float = value.as_f64().ok_or(JcsError::SerializationError)?;
    if !float.is_finite() {
        return Err(JcsError::NonFiniteNumber);
    }
    validate_interoperable_float_integer(float)?;

    let mut buffer = ryu_js::Buffer::new();
    Ok(buffer.format_finite(float).len())
}

fn canonical_sensitive_number_len(value: &SensitiveNumber) -> Result<usize, JcsError> {
    match value {
        SensitiveNumber::Unsigned(unsigned) => {
            if *unsigned > MAX_INTEROPERABLE_INTEGER {
                return Err(JcsError::IntegerOutsideInteroperableRange);
            }
            let mut buffer = itoa::Buffer::new();
            Ok(buffer.format(*unsigned).len())
        }
        SensitiveNumber::Signed(signed) => {
            if *signed < MIN_INTEROPERABLE_INTEGER {
                return Err(JcsError::IntegerOutsideInteroperableRange);
            }
            let mut buffer = itoa::Buffer::new();
            Ok(buffer.format(*signed).len())
        }
        SensitiveNumber::Float(float) => {
            if !float.is_finite() {
                return Err(JcsError::NonFiniteNumber);
            }
            validate_interoperable_float_integer(*float)?;
            let mut buffer = ryu_js::Buffer::new();
            Ok(buffer.format_finite(*float).len())
        }
    }
}

fn validate_interoperable_float_integer(value: f64) -> Result<(), JcsError> {
    if value.fract() == 0.0
        && !(MIN_INTEROPERABLE_INTEGER_F64..=MAX_INTEROPERABLE_INTEGER_F64).contains(&value)
    {
        return Err(JcsError::IntegerOutsideInteroperableRange);
    }
    Ok(())
}

fn escaped_string_len(value: &str) -> Result<usize, JcsError> {
    let mut length = "\""
        .len()
        .checked_add("\"".len())
        .ok_or(JcsError::SerializationError)?;
    for character in value.chars() {
        let scalar = u32::from(character);
        if (0xfdd0..=0xfdef).contains(&scalar) || scalar & 0xfffe == 0xfffe {
            return Err(JcsError::Noncharacter);
        }
        length = length
            .checked_add(escaped_character_len(character))
            .ok_or(JcsError::SerializationError)?;
    }
    Ok(length)
}

fn escaped_character_len(character: char) -> usize {
    match character {
        '"' | '\\' | '\u{08}' | '\t' | '\n' | '\u{0c}' | '\r' => 2,
        '\u{00}'..='\u{1f}' => 6,
        _ => character.len_utf8(),
    }
}

fn write_escaped_string(value: &str, output: &mut String) {
    const HEX: &[u8; 16] = b"0123456789abcdef";

    output.push('"');
    for character in value.chars() {
        match character {
            '"' => output.push_str("\\\""),
            '\\' => output.push_str("\\\\"),
            '\u{08}' => output.push_str("\\b"),
            '\t' => output.push_str("\\t"),
            '\n' => output.push_str("\\n"),
            '\u{0c}' => output.push_str("\\f"),
            '\r' => output.push_str("\\r"),
            '\u{00}'..='\u{1f}' => {
                let byte = character as u8;
                output.push_str("\\u00");
                output.push(char::from(HEX[usize::from(byte >> 4)]));
                output.push(char::from(HEX[usize::from(byte & 0x0f)]));
            }
            _ => output.push(character),
        }
    }
    output.push('"');
}