blob: 627415e88ba0918cb67c60f7e2eff9d65682779d [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! High-level top-level JSON object validation and streaming key-value string
//! extraction (for `hwinfo`, `regulatory_region`, and similar config parsers).
use vx_core::slice::starts_with;
use crate::cursor::{encode_bmp_utf8, simple_escape_byte};
use crate::types::{JsonCursor, JsonDialect, JsonError};
#[curry::verified]
fn match_key_bytes(dec: &[u8], target: &[u8], idx: &mut usize, matched: &mut bool) {
if !*matched {
return;
}
let start = *idx;
let Some(rest) = target.get(start..) else {
*matched = false;
return;
};
if !starts_with(rest, dec) {
*matched = false;
return;
}
*idx = start + dec.len();
}
/// Decode one escape inside a JSON object key into `esc_buf[..*esc_len]`.
/// Returns `Ok(true)` if the escape is a UTF-16 surrogate (`0xD800..=0xDFFF`)
/// which marks a non-target key mismatch without aborting lookup.
#[curry::verified]
fn decode_key_escape(
cur: &mut JsonCursor<'_>,
esc_buf: &mut [u8; 4],
esc_len: &mut usize,
) -> Result<bool, JsonError> {
let esc = cur.peek().ok_or(JsonError::UnexpectedEof)?;
cur.pos += 1;
if esc == b'u' {
let code = cur.read_hex4()?;
if (0xD800..=0xDFFF).contains(&code) {
return Ok(true);
}
encode_bmp_utf8(code, esc_buf, esc_len)?;
return Ok(false);
}
let decoded = simple_escape_byte(esc).ok_or(JsonError::InvalidEscape)?;
esc_buf[0] = decoded;
*esc_len = 1;
Ok(false)
}
/// Decode one escape inside a JSON object key and stream-compare against
/// `target[*idx..]`.
#[curry::verified]
fn match_key_escape(
cur: &mut JsonCursor<'_>,
target: &[u8],
idx: &mut usize,
matched: &mut bool,
) -> Result<(), JsonError> {
let mut esc_buf = [0u8; 4];
let mut esc_len: usize = 0;
if decode_key_escape(cur, &mut esc_buf, &mut esc_len)? {
*matched = false;
return Ok(());
}
if let Some(dec) = esc_buf.get(..esc_len) {
match_key_bytes(dec, target, idx, matched);
} else {
*matched = false;
}
Ok(())
}
/// Parse a JSON key string of arbitrary length and compare it against
/// `target_key` without buffering the key.
#[curry::verified]
fn match_string_key(cur: &mut JsonCursor<'_>, target_key: &str) -> Result<bool, JsonError> {
cur.expect_byte(b'"')?;
let target = target_key.as_bytes();
let mut matched = true;
let mut idx: usize = 0;
while let Some(b) = cur.peek() {
cur.pos += 1;
if b == b'"' {
return Ok(matched && idx == target.len());
}
if b < 0x20 {
return Err(JsonError::InvalidString);
}
if b == b'\\' {
match_key_escape(cur, target, &mut idx, &mut matched)?;
} else if matched && target.get(idx) == Some(&b) {
idx += 1;
} else {
matched = false;
}
}
Err(JsonError::UnexpectedEof)
}
#[curry::verified]
fn validate_object_member(cur: &mut JsonCursor<'_>) -> Result<(), JsonError> {
cur.skip_string()?;
cur.expect_byte(b':')?;
cur.skip_value()
}
/// Validate that `input` is a syntactically well-formed top-level JSON object
/// `{ ... }` under `dialect` with bounded nesting depth (`MAX_JSON_DEPTH = 16`)
/// and no trailing tokens.
#[curry::verified]
pub fn is_valid_object(input: &[u8], dialect: JsonDialect) -> bool {
let mut cur = JsonCursor::new(input, dialect);
if cur.expect_byte(b'{').is_err() {
return false;
}
let mut first = true;
loop {
let mut has_more = false;
if cur.next_container_item(b'}', first, &mut has_more).is_err() {
return false;
}
if !has_more {
break;
}
first = false;
if validate_object_member(&mut cur).is_err() {
return false;
}
}
matches!(cur.peek_token(), Ok(None))
}
#[repr(u8)]
#[derive(Copy, Clone, Eq, PartialEq)]
enum ExtractStep {
Found = 0,
Continue = 1,
NotFound = 2,
}
#[curry::verified]
fn step_extract_member(
cur: &mut JsonCursor<'_>,
target_key: &str,
out: &mut [u8],
out_len: &mut usize,
) -> ExtractStep {
let Ok(matched) = match_string_key(cur, target_key) else {
return ExtractStep::NotFound;
};
if cur.expect_byte(b':').is_err() {
return ExtractStep::NotFound;
}
if matched {
if cur.read_string_into(out, out_len).is_ok() {
return ExtractStep::Found;
}
return ExtractStep::NotFound;
}
if cur.skip_value().is_err() {
return ExtractStep::NotFound;
}
ExtractStep::Continue
}
/// Extract a top-level string field named `target_key` from JSON object `input`
/// under `dialect`, writing its decoded UTF-8 value into `out` and returning
/// `Some(len)` on match.
///
/// Returns `None` if `input` is malformed up to the key, `target_key` is
/// absent, its value is not a JSON string, or the decoded value exceeds
/// `out.len()`.
#[curry::verified]
pub fn extract_top_level_string(
input: &[u8],
dialect: JsonDialect,
target_key: &str,
out: &mut [u8],
) -> Option<usize> {
let mut cur = JsonCursor::new(input, dialect);
if cur.expect_byte(b'{').is_err() {
return None;
}
let mut first = true;
let mut val_len: usize = 0;
loop {
let mut has_more = false;
if cur.next_container_item(b'}', first, &mut has_more).is_err() {
return None;
}
if !has_more {
return None;
}
first = false;
match step_extract_member(&mut cur, target_key, out, &mut val_len) {
ExtractStep::Found => return Some(val_len),
ExtractStep::Continue => {}
ExtractStep::NotFound => return None,
}
}
}