1use std::collections::BTreeMap;
2
3use crate::error::{ErrorCode, WriteSafetyError};
4use crate::sha256::sha256_hex;
5
6pub(crate) const MAX_SAFE_INTEGER: i64 = (1 << 53) - 1;
7const MAX_DEPTH: usize = 128;
8
9#[derive(Debug, Clone, PartialEq)]
13pub enum JsonValue {
14 Null,
15 Bool(bool),
16 Int(i64),
17 Float(f64),
18 String(String),
19 Array(Vec<JsonValue>),
20 Object(BTreeMap<String, JsonValue>),
21}
22
23impl JsonValue {
24 pub fn as_object(&self) -> Option<&BTreeMap<String, JsonValue>> {
25 match self {
26 JsonValue::Object(map) => Some(map),
27 _ => None,
28 }
29 }
30
31 pub fn as_array(&self) -> Option<&[JsonValue]> {
32 match self {
33 JsonValue::Array(items) => Some(items),
34 _ => None,
35 }
36 }
37
38 pub fn as_str(&self) -> Option<&str> {
39 match self {
40 JsonValue::String(s) => Some(s.as_str()),
41 _ => None,
42 }
43 }
44
45 pub fn as_bool(&self) -> Option<bool> {
46 match self {
47 JsonValue::Bool(b) => Some(*b),
48 _ => None,
49 }
50 }
51
52 pub fn as_i64(&self) -> Option<i64> {
53 match self {
54 JsonValue::Int(n) => Some(*n),
55 _ => None,
56 }
57 }
58}
59
60fn write_escaped_string(s: &str, out: &mut String) {
61 out.push('"');
62 for ch in s.chars() {
63 match ch {
64 '"' => out.push_str("\\\""),
65 '\\' => out.push_str("\\\\"),
66 '\u{08}' => out.push_str("\\b"),
67 '\u{0C}' => out.push_str("\\f"),
68 '\n' => out.push_str("\\n"),
69 '\r' => out.push_str("\\r"),
70 '\t' => out.push_str("\\t"),
71 c if (c as u32) < 0x20 => {
72 use std::fmt::Write as _;
73 let _ = write!(out, "\\u{:04x}", c as u32);
74 }
75 c => out.push(c),
76 }
77 }
78 out.push('"');
79}
80
81fn exact_midpoint(value: f64, odd_decimal: u64, power: i32) -> bool {
82 let bits = value.to_bits();
83 let biased_exponent = ((bits >> 52) & 0x7ff) as i32;
84 let fraction = bits & ((1 << 52) - 1);
85 let (significand, exponent) = if biased_exponent == 0 {
86 (fraction, -1074)
87 } else {
88 (fraction | (1 << 52), biased_exponent - 1075)
89 };
90 let trailing = significand.trailing_zeros();
91 if exponent + trailing as i32 != power - 1 {
94 return false;
95 }
96 let odd_binary = significand >> trailing;
97 let Some(five) = 5_u64.checked_pow(power.unsigned_abs()) else {
98 return false;
99 };
100 if power >= 0 {
101 odd_decimal.checked_mul(five) == Some(odd_binary)
102 } else {
103 odd_binary.checked_mul(five) == Some(odd_decimal)
104 }
105}
106
107fn write_float(value: f64, out: &mut String) {
108 use std::fmt::Write as _;
109 if value == 0.0 {
110 out.push('0');
111 return;
112 }
113 if value.is_sign_negative() {
114 out.push('-');
115 }
116 let value = value.abs();
117 let scientific = format!("{value:e}");
118 let (mantissa, exponent) = scientific.split_once('e').expect("scientific notation");
119 let exponent = exponent.parse::<i32>().expect("decimal exponent");
120 let mut digits = mantissa.replace('.', "");
121 let coefficient = digits.parse::<u64>().expect("shortest binary64 significand");
122 let power = exponent + 1 - digits.len() as i32;
123 if coefficient % 2 != 0 {
126 if exact_midpoint(value, 2 * coefficient - 1, power) {
127 digits = (coefficient - 1).to_string();
128 } else if exact_midpoint(value, 2 * coefficient + 1, power) {
129 digits = (coefficient + 1).to_string();
130 }
131 }
132 let point = power + digits.len() as i32;
133 let digits = digits.trim_end_matches('0');
134 if (1..=21).contains(&point) {
135 let point = point as usize;
136 if point >= digits.len() {
137 out.push_str(digits);
138 out.push_str(&"0".repeat(point - digits.len()));
139 } else {
140 out.push_str(&digits[..point]);
141 out.push('.');
142 out.push_str(&digits[point..]);
143 }
144 } else if (-5..=0).contains(&point) {
145 out.push_str("0.");
146 out.push_str(&"0".repeat((-point) as usize));
147 out.push_str(digits);
148 } else {
149 out.push_str(&digits[..1]);
150 if digits.len() > 1 {
151 out.push('.');
152 out.push_str(&digits[1..]);
153 }
154 write!(out, "e{:+}", point - 1).expect("write to String");
155 }
156}
157
158fn write_canonical(value: &JsonValue, out: &mut String, depth: usize) -> Result<(), WriteSafetyError> {
159 if depth >= MAX_DEPTH && matches!(value, JsonValue::Array(_) | JsonValue::Object(_)) {
160 return Err(WriteSafetyError::new(ErrorCode::Validation, "JSON nested too deeply."));
161 }
162 match value {
163 JsonValue::Null => out.push_str("null"),
164 JsonValue::Bool(true) => out.push_str("true"),
165 JsonValue::Bool(false) => out.push_str("false"),
166 JsonValue::Int(n) => {
167 if !(-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(n) {
168 return Err(WriteSafetyError::new(ErrorCode::Validation, "JSON integer is outside the safe range."));
169 }
170 out.push_str(&n.to_string());
171 }
172 JsonValue::Float(f) => {
173 if !f.is_finite() {
174 return Err(WriteSafetyError::new(
175 ErrorCode::Validation,
176 "Write input must contain only finite JSON numbers.",
177 ));
178 }
179 write_float(*f, out);
180 }
181 JsonValue::String(s) => write_escaped_string(s, out),
182 JsonValue::Array(items) => {
183 out.push('[');
184 for (idx, item) in items.iter().enumerate() {
185 if idx > 0 {
186 out.push(',');
187 }
188 write_canonical(item, out, depth + 1)?;
189 }
190 out.push(']');
191 }
192 JsonValue::Object(map) => {
193 out.push('{');
194 for (idx, (k, v)) in map.iter().enumerate() {
195 if idx > 0 {
196 out.push(',');
197 }
198 write_escaped_string(k, out);
199 out.push(':');
200 write_canonical(v, out, depth + 1)?;
201 }
202 out.push('}');
203 }
204 }
205 Ok(())
206}
207
208pub fn canonical_json(value: &JsonValue) -> Result<String, WriteSafetyError> {
210 let mut out = String::new();
211 write_canonical(value, &mut out, 0)?;
212 Ok(out)
213}
214
215pub fn canonical_binding_json(
217 operation: &str,
218 scope: &str,
219 input: &JsonValue,
220) -> Result<String, WriteSafetyError> {
221 canonical_binding_json_with_context(operation, scope, input, None)
222}
223
224pub fn canonical_binding_json_with_context(
227 operation: &str,
228 scope: &str,
229 input: &JsonValue,
230 binding_context: Option<&JsonValue>,
231) -> Result<String, WriteSafetyError> {
232 let mut out = String::from("{");
233 if let Some(context) = binding_context {
234 out.push_str("\"bindingContext\":");
235 write_canonical(context, &mut out, 0)?;
236 out.push(',');
237 }
238 out.push_str("\"input\":");
239 write_canonical(input, &mut out, 0)?;
240 out.push_str(",\"operation\":");
241 write_escaped_string(operation, &mut out);
242 out.push_str(",\"scope\":");
243 write_escaped_string(scope, &mut out);
244 out.push_str(",\"version\":1}");
245 Ok(out)
246}
247
248pub fn canonical_hash(
250 operation: &str,
251 scope: &str,
252 input: &JsonValue,
253) -> Result<String, WriteSafetyError> {
254 canonical_hash_with_context(operation, scope, input, None)
255}
256
257pub fn canonical_hash_with_context(
259 operation: &str,
260 scope: &str,
261 input: &JsonValue,
262 binding_context: Option<&JsonValue>,
263) -> Result<String, WriteSafetyError> {
264 let payload = canonical_binding_json_with_context(operation, scope, input, binding_context)?;
265 Ok(sha256_hex(payload.as_bytes()))
266}
267
268struct Parser<'a> {
269 text: &'a str,
270 pos: usize,
271}
272
273impl<'a> Parser<'a> {
274 fn skip_ws(&mut self) {
275 while self.pos < self.text.len() {
276 match self.text.as_bytes()[self.pos] {
277 b' ' | b'\t' | b'\r' | b'\n' => self.pos += 1,
278 _ => break,
279 }
280 }
281 }
282
283 fn peek(&self) -> Option<u8> {
284 self.text.as_bytes().get(self.pos).copied()
285 }
286
287 fn parse_value(&mut self, depth: usize) -> Result<JsonValue, WriteSafetyError> {
288 self.skip_ws();
289 match self.peek() {
290 Some(b'[' | b'{') if depth >= MAX_DEPTH => {
291 Err(WriteSafetyError::new(ErrorCode::Validation, "JSON nested too deeply."))
292 }
293 Some(b'n') => self.parse_literal(b"null", JsonValue::Null),
294 Some(b't') => self.parse_literal(b"true", JsonValue::Bool(true)),
295 Some(b'f') => self.parse_literal(b"false", JsonValue::Bool(false)),
296 Some(b'"') => self.parse_string().map(JsonValue::String),
297 Some(b'[') => self.parse_array(depth),
298 Some(b'{') => self.parse_object(depth),
299 Some(b'-') | Some(b'0'..=b'9') => self.parse_number(),
300 _ => Err(WriteSafetyError::new(ErrorCode::Validation, "Invalid JSON value.")),
301 }
302 }
303
304 fn parse_literal(&mut self, expected: &[u8], value: JsonValue) -> Result<JsonValue, WriteSafetyError> {
305 if self.text.as_bytes()[self.pos..].starts_with(expected) {
306 self.pos += expected.len();
307 Ok(value)
308 } else {
309 Err(WriteSafetyError::new(ErrorCode::Validation, "Invalid JSON literal."))
310 }
311 }
312
313 fn parse_hex4(&mut self) -> Result<u16, WriteSafetyError> {
314 let hex = self.text.get(self.pos..self.pos + 4)
315 .filter(|hex| hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
316 .ok_or_else(|| WriteSafetyError::new(ErrorCode::Validation, "Invalid unicode escape."))?;
317 let val = u16::from_str_radix(hex, 16).expect("four hex digits");
318 self.pos += 4;
319 Ok(val)
320 }
321
322 fn parse_string(&mut self) -> Result<String, WriteSafetyError> {
323 self.pos += 1; let mut out = String::new();
325 while let Some(b) = self.peek() {
326 if b == b'"' {
327 self.pos += 1;
328 return Ok(out);
329 }
330 if b == b'\\' {
331 self.pos += 1;
332 let esc = self
333 .peek()
334 .ok_or_else(|| WriteSafetyError::new(ErrorCode::Validation, "Unterminated escape."))?;
335 self.pos += 1;
336 match esc {
337 b'"' => out.push('"'),
338 b'\\' => out.push('\\'),
339 b'/' => out.push('/'),
340 b'b' => out.push('\u{08}'),
341 b'f' => out.push('\u{0C}'),
342 b'n' => out.push('\n'),
343 b'r' => out.push('\r'),
344 b't' => out.push('\t'),
345 b'u' => {
346 let code = self.parse_hex4()?;
347 if (0xD800..=0xDBFF).contains(&code) {
348 if !self.text.as_bytes()[self.pos..].starts_with(b"\\u") {
349 return Err(WriteSafetyError::new(
350 ErrorCode::Validation,
351 "Unpaired high surrogate.",
352 ));
353 }
354 self.pos += 2;
355 let low = self.parse_hex4()?;
356 if !(0xDC00..=0xDFFF).contains(&low) {
357 return Err(WriteSafetyError::new(
358 ErrorCode::Validation,
359 "Invalid low surrogate.",
360 ));
361 }
362 let cp = 0x10000 + (((code as u32 - 0xD800) << 10) | (low as u32 - 0xDC00));
363 let ch = char::from_u32(cp).ok_or_else(|| {
364 WriteSafetyError::new(ErrorCode::Validation, "Invalid unicode scalar.")
365 })?;
366 out.push(ch);
367 } else {
368 let ch = char::from_u32(code as u32).ok_or_else(|| {
369 WriteSafetyError::new(ErrorCode::Validation, "Invalid unicode scalar.")
370 })?;
371 out.push(ch);
372 }
373 }
374 _ => return Err(WriteSafetyError::new(ErrorCode::Validation, "Unknown JSON escape.")),
375 }
376 } else {
377 if b < 0x20 {
378 return Err(WriteSafetyError::new(ErrorCode::Validation, "Unescaped control character."));
379 }
380 let ch = self.text[self.pos..]
381 .chars()
382 .next()
383 .ok_or_else(|| WriteSafetyError::new(ErrorCode::Validation, "Unterminated string."))?;
384 out.push(ch);
385 self.pos += ch.len_utf8();
386 }
387 }
388 Err(WriteSafetyError::new(ErrorCode::Validation, "Unterminated JSON string."))
389 }
390
391 fn parse_number(&mut self) -> Result<JsonValue, WriteSafetyError> {
392 let invalid = || WriteSafetyError::new(ErrorCode::Validation, "Invalid JSON number.");
393 let start = self.pos;
394 if self.peek() == Some(b'-') {
395 self.pos += 1;
396 }
397 match self.peek() {
398 Some(b'0') => {
399 self.pos += 1;
400 if self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
401 return Err(invalid());
402 }
403 }
404 Some(b'1'..=b'9') => self.consume_digits(),
405 _ => return Err(invalid()),
406 }
407 let mut is_float = false;
408 if self.peek() == Some(b'.') {
409 is_float = true;
410 self.pos += 1;
411 if !self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
412 return Err(invalid());
413 }
414 self.consume_digits();
415 }
416 if matches!(self.peek(), Some(b'e' | b'E')) {
417 is_float = true;
418 self.pos += 1;
419 if matches!(self.peek(), Some(b'+' | b'-')) {
420 self.pos += 1;
421 }
422 if !self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
423 return Err(invalid());
424 }
425 self.consume_digits();
426 }
427 let slice = &self.text[start..self.pos];
428 if !is_float {
429 if let Some(integer) = slice.parse::<i64>().ok()
430 .filter(|n| (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(n))
431 {
432 return Ok(JsonValue::Int(integer));
433 }
434 }
435 let f = slice
436 .parse::<f64>()
437 .map_err(|_| WriteSafetyError::new(ErrorCode::Validation, "Invalid JSON number."))?;
438 if !f.is_finite() {
439 return Err(WriteSafetyError::new(ErrorCode::Validation, "Non-finite JSON number."));
440 }
441 Ok(JsonValue::Float(f))
442 }
443
444 fn consume_digits(&mut self) {
445 while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
446 self.pos += 1;
447 }
448 }
449
450 fn parse_array(&mut self, depth: usize) -> Result<JsonValue, WriteSafetyError> {
451 self.pos += 1; let mut items = Vec::new();
453 self.skip_ws();
454 if self.peek() == Some(b']') {
455 self.pos += 1;
456 return Ok(JsonValue::Array(items));
457 }
458 loop {
459 items.push(self.parse_value(depth + 1)?);
460 self.skip_ws();
461 match self.peek() {
462 Some(b',') => self.pos += 1,
463 Some(b']') => {
464 self.pos += 1;
465 return Ok(JsonValue::Array(items));
466 }
467 _ => return Err(WriteSafetyError::new(ErrorCode::Validation, "Expected ',' or ']'.")),
468 }
469 }
470 }
471
472 fn parse_object(&mut self, depth: usize) -> Result<JsonValue, WriteSafetyError> {
473 self.pos += 1; let mut map = BTreeMap::new();
475 self.skip_ws();
476 if self.peek() == Some(b'}') {
477 self.pos += 1;
478 return Ok(JsonValue::Object(map));
479 }
480 loop {
481 self.skip_ws();
482 if self.peek() != Some(b'"') {
483 return Err(WriteSafetyError::new(ErrorCode::Validation, "Expected object key string."));
484 }
485 let key = self.parse_string()?;
486 self.skip_ws();
487 if self.peek() != Some(b':') {
488 return Err(WriteSafetyError::new(ErrorCode::Validation, "Expected ':' after key."));
489 }
490 self.pos += 1;
491 let value = self.parse_value(depth + 1)?;
492 map.insert(key, value);
493 self.skip_ws();
494 match self.peek() {
495 Some(b',') => self.pos += 1,
496 Some(b'}') => {
497 self.pos += 1;
498 return Ok(JsonValue::Object(map));
499 }
500 _ => return Err(WriteSafetyError::new(ErrorCode::Validation, "Expected ',' or '}'.")),
501 }
502 }
503 }
504}
505
506pub fn parse_json(text: &str) -> Result<JsonValue, WriteSafetyError> {
508 let mut parser = Parser {
509 text,
510 pos: 0,
511 };
512 let value = parser.parse_value(0)?;
513 parser.skip_ws();
514 if parser.pos != parser.text.len() {
515 return Err(WriteSafetyError::new(ErrorCode::Validation, "Trailing characters after JSON."));
516 }
517 Ok(value)
518}