lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

private_json.rs (4944B)


      1 //! Decode a private JSON string without a nonzeroizing decoded scratch buffer.
      2 use crate::command::CommandError;
      3 use alloc::string::String;
      4 use zeroize::Zeroizing;
      5 
      6 #[cfg(any(feature = "terms", test))]
      7 pub(crate) fn decode(raw: &str, maximum_chars: usize) -> Result<Zeroizing<String>, CommandError> {
      8     decode_limited(raw, maximum_chars, usize::MAX)
      9 }
     10 
     11 #[cfg(feature = "private_rumor")]
     12 pub(crate) fn decode_bytes(
     13     raw: &str,
     14     maximum_bytes: usize,
     15 ) -> Result<Zeroizing<String>, CommandError> {
     16     decode_limited(raw, usize::MAX, maximum_bytes)
     17 }
     18 
     19 fn decode_limited(
     20     raw: &str,
     21     maximum_chars: usize,
     22     maximum_bytes: usize,
     23 ) -> Result<Zeroizing<String>, CommandError> {
     24     let mut bytes = 0usize;
     25     let mut count = 0usize;
     26     visit(raw, |ch| {
     27         count += 1;
     28         if count > maximum_chars {
     29             return Err(CommandError::LimitExceeded);
     30         }
     31         bytes = bytes
     32             .checked_add(ch.len_utf8())
     33             .filter(|value| *value <= maximum_bytes)
     34             .ok_or(CommandError::LimitExceeded)?;
     35         Ok(())
     36     })?;
     37     let mut output = Zeroizing::new(String::with_capacity(bytes));
     38     visit(raw, |ch| {
     39         output.push(ch);
     40         Ok(())
     41     })?;
     42     Ok(output)
     43 }
     44 
     45 fn visit(
     46     raw: &str,
     47     mut emit: impl FnMut(char) -> Result<(), CommandError>,
     48 ) -> Result<(), CommandError> {
     49     let text = raw
     50         .strip_prefix('"')
     51         .and_then(|value| value.strip_suffix('"'))
     52         .ok_or(CommandError::InvalidInput)?;
     53     let mut chars = text.chars();
     54     while let Some(ch) = chars.next() {
     55         if ch == '\\' {
     56             let escaped = chars.next().ok_or(CommandError::InvalidInput)?;
     57             let value = match escaped {
     58                 '"' => '"',
     59                 '\\' => '\\',
     60                 '/' => '/',
     61                 'b' => '\u{08}',
     62                 'f' => '\u{0c}',
     63                 'n' => '\n',
     64                 'r' => '\r',
     65                 't' => '\t',
     66                 'u' => {
     67                     let first = hex(&mut chars)?;
     68                     let code = if (0xd800..=0xdbff).contains(&first) {
     69                         if chars.next() != Some('\\') || chars.next() != Some('u') {
     70                             return Err(CommandError::InvalidInput);
     71                         }
     72                         let second = hex(&mut chars)?;
     73                         if !(0xdc00..=0xdfff).contains(&second) {
     74                             return Err(CommandError::InvalidInput);
     75                         }
     76                         0x10000 + ((u32::from(first) - 0xd800) << 10) + (u32::from(second) - 0xdc00)
     77                     } else {
     78                         u32::from(first)
     79                     };
     80                     char::from_u32(code).ok_or(CommandError::InvalidInput)?
     81                 }
     82                 _ => return Err(CommandError::InvalidInput),
     83             };
     84             emit(value)?;
     85         } else {
     86             if ch == '"' || ch <= '\u{1f}' {
     87                 return Err(CommandError::InvalidInput);
     88             }
     89             emit(ch)?;
     90         }
     91     }
     92     Ok(())
     93 }
     94 
     95 fn hex(chars: &mut core::str::Chars<'_>) -> Result<u16, CommandError> {
     96     let mut value = 0;
     97     for _ in 0..4 {
     98         let digit = chars
     99             .next()
    100             .and_then(|ch| ch.to_digit(16))
    101             .ok_or(CommandError::InvalidInput)?;
    102         value = (value << 4) | u16::try_from(digit).map_err(|_| CommandError::InvalidInput)?;
    103     }
    104     Ok(value)
    105 }
    106 
    107 // Retain only bounded references into the caller's already byte/depth-bounded
    108 // frame. An excessive element is ignored without constructing its value.
    109 pub(crate) use crate::json_array::RawArray;
    110 
    111 #[cfg(test)]
    112 mod tests {
    113     use super::*;
    114 
    115     #[test]
    116     fn private_json_text_matches_independent_literal_and_surrogate_decoding() {
    117         for raw in [
    118             r#""""#,
    119             r#""plain 🥬 Å A\u030a""#,
    120             r#""\"\\\/\b\f\n\r\t\u0000\u001f\uD83E\uDD6C""#,
    121         ] {
    122             let expected: String = serde_json::from_str(raw).unwrap();
    123             assert_eq!(decode(raw, 2048).unwrap().as_str(), expected);
    124             assert_eq!(
    125                 decode(raw, expected.chars().count()).unwrap().as_str(),
    126                 expected
    127             );
    128             if !expected.is_empty() {
    129                 assert_eq!(
    130                     decode(raw, expected.chars().count() - 1),
    131                     Err(CommandError::LimitExceeded)
    132                 );
    133             }
    134         }
    135     }
    136 
    137     #[test]
    138     fn private_json_text_rejects_malformed_literals_and_surrogates() {
    139         for raw in [
    140             "null",
    141             "[]",
    142             "\"",
    143             "\"a\"b\"",
    144             "\"\n\"",
    145             r#""\x""#,
    146             r#""\u12""#,
    147             r#""\u000z""#,
    148             r#""\uDC00""#,
    149             r#""\uD800""#,
    150             r#""\uD800x""#,
    151             r#""\uD800\u0041""#,
    152         ] {
    153             assert_eq!(decode(raw, 2048), Err(CommandError::InvalidInput), "{raw}");
    154         }
    155     }
    156 }