Skip to main content

guard_core_engine/
json_walk.rs

1//! Ordered JSON body walk, ported from the Go engine's `jsonwalk.go`, which
2//! ports `guard_core/_utils/body_json_scan.py` and `embedded_json_scan.py`.
3//!
4//! The reference engine parses with `json.loads` (dict insertion order) and
5//! walks the tree depth-first in insertion order: for each object entry the
6//! key is checked against the mongo-operator-key registry (a direct `nosql`
7//! hit reported without a pattern scan) and scanned as a name; then the entry
8//! value descends. Objects and arrays deeper than the JSON depth cap are
9//! serialized back to compact JSON and scanned as one text value. Scalar
10//! leaves scan `str(value)`.
11//!
12//! Values parsed out of a form or multipart field string walk with the field
13//! context plus the [`crate::detect::EMBEDDED_JSON_LEAF_CONTEXT_SUFFIX`]
14//! (`embedded_json_scan.py`), and such a leaf string that itself parses as a
15//! JSON object or array walks again with another suffix, exactly like
16//! `_check_embedded_json` short-circuiting the raw value scan. The top-level
17//! JSON body walk keeps the plain `request_body` context and never re-parses
18//! leaf strings (the reference skips the embedded check when the context is
19//! exactly `request_body`).
20//!
21//! Deviations: number leaves scan the literal JSON text instead of Python's
22//! float `repr` (Python's arbitrary-precision ints render identically); a
23//! lone surrogate escape becomes U+FFFD at the decode boundary (the engine
24//! string model) instead of Python's lone surrogate rune; parse recursion is
25//! bounded like Python's `json.loads` recursion limit, so deeper bodies fall
26//! back to the blob scan exactly as a `RecursionError` does in the reference.
27
28use std::sync::LazyLock;
29
30use regex::Regex;
31
32use crate::body_scan::{BodyScanValue, REQUEST_BODY_CONTEXT};
33use crate::detect::EMBEDDED_JSON_LEAF_CONTEXT_SUFFIX;
34
35/// JSON walk depth cap (`_json_depth_cap_value` default): containers at or
36/// beyond this walk depth serialize back to compact JSON and scan as text.
37pub const JSON_WALK_DEPTH_CAP: usize = 32;
38
39/// Parse recursion bound standing in for Python's `json.loads`
40/// `RecursionError`, which falls back to the blob scan.
41const PARSE_DEPTH_LIMIT: usize = 1000;
42
43/// One scalar leaf, storing the JSON literal where scanning needs it
44/// (see [`Scalar::scan_text`]).
45#[derive(Debug, Clone, PartialEq)]
46enum Scalar {
47    Str(String),
48    /// The raw JSON number literal.
49    Number(String),
50    Bool(bool),
51    Null,
52    Nan,
53    Infinity,
54    NegInfinity,
55}
56
57impl Scalar {
58    /// Python `str(value)` rendering, the text the reference scans.
59    fn scan_text(&self) -> String {
60        match self {
61            Self::Str(s) | Self::Number(s) => s.clone(),
62            Self::Bool(true) => "True".to_owned(),
63            Self::Bool(false) => "False".to_owned(),
64            Self::Null => "None".to_owned(),
65            Self::Nan => "nan".to_owned(),
66            Self::Infinity => "inf".to_owned(),
67            Self::NegInfinity => "-inf".to_owned(),
68        }
69    }
70}
71
72/// One node of the ordered parse tree. Duplicate object keys keep the first
73/// insertion position and the last value (Python dict semantics).
74#[derive(Debug, Clone, PartialEq)]
75pub struct JsonNode {
76    is_object: bool,
77    is_array: bool,
78    keys: Vec<String>,
79    values: Vec<Self>,
80    items: Vec<Self>,
81    scalar: Option<Scalar>,
82}
83
84impl JsonNode {
85    const fn container(is_object: bool) -> Self {
86        Self {
87            is_object,
88            is_array: !is_object,
89            keys: Vec::new(),
90            values: Vec::new(),
91            items: Vec::new(),
92            scalar: None,
93        }
94    }
95
96    const fn leaf(scalar: Scalar) -> Self {
97        Self {
98            is_object: false,
99            is_array: false,
100            keys: Vec::new(),
101            values: Vec::new(),
102            items: Vec::new(),
103            scalar: Some(scalar),
104        }
105    }
106
107    fn object(keys: Vec<String>, values: Vec<Self>) -> Self {
108        Self {
109            keys,
110            values,
111            ..Self::container(true)
112        }
113    }
114
115    fn array(items: Vec<Self>) -> Self {
116        Self {
117            items,
118            ..Self::container(false)
119        }
120    }
121}
122
123#[derive(Debug)]
124enum ParseError {
125    /// Malformed JSON (`json.JSONDecodeError`).
126    Invalid,
127    /// Beyond the recursion bound (`RecursionError` in the reference).
128    Depth,
129}
130
131/// `parseOrderedJSON`: parse `s` and return the root when it is a JSON
132/// object or array.
133///
134/// Trailing data or any parse failure returns `None`, like the reference
135/// falling through to the blob or raw-value scan (`_scan_json_content` and
136/// `_check_embedded_json` only walk dict/list).
137#[must_use]
138pub fn parse_ordered_json(s: &str) -> Option<JsonNode> {
139    let mut parser = Parser {
140        bytes: s.as_bytes(),
141        pos: 0,
142        stack: Vec::new(),
143        depth: 0,
144        pending: None,
145    };
146    let root = parser.parse_root().ok()?;
147    // _scan_json_content and _check_embedded_json only walk dict/list.
148    if !root.is_object && !root.is_array {
149        return None;
150    }
151    Some(root)
152}
153
154/// The flattened parser: `bytes`/`pos` carry the cursor, the frame stack the
155/// open containers, `depth` the container nesting, and `pending` the last
156/// completed node waiting to attach to its parent.
157struct Parser<'a> {
158    bytes: &'a [u8],
159    pos: usize,
160    stack: Vec<ParseFrame>,
161    depth: usize,
162    pending: Option<JsonNode>,
163}
164
165impl ParseFrame {
166    /// The object frame's pending-key slot; `None` for array frames (a Key
167    /// step only ever follows an object frame, so callers treat `None` as
168    /// an unreachable invariant violation).
169    const fn object_key_slot(&mut self) -> Option<&mut Option<String>> {
170        match self {
171            Self::Object { current_key, .. } => Some(current_key),
172            Self::Array(_) => None,
173        }
174    }
175}
176
177/// The next machine step: continue with a state, or finish with the root.
178enum Flow {
179    Next(ParseState),
180    Done(JsonNode),
181}
182
183/// Duplicate keys keep the first insertion position and the last value
184/// (Python dict semantics).
185fn upsert_object(keys: &mut Vec<String>, values: &mut Vec<JsonNode>, key: String, node: JsonNode) {
186    if let Some(at) = keys.iter().position(|existing| *existing == key) {
187        values[at] = node;
188    } else {
189        keys.push(key);
190        values.push(node);
191    }
192}
193
194/// Explicit parse-frame stack entry: the recursive descent of the reference
195/// `json.loads`, flattened so the depth bound is a semantic cap rather than a
196/// stack-overflow guard.
197#[derive(Debug)]
198enum ParseFrame {
199    Array(Vec<JsonNode>),
200    Object {
201        keys: Vec<String>,
202        values: Vec<JsonNode>,
203        current_key: Option<String>,
204    },
205}
206
207enum ParseState {
208    /// Parse one value (leaf, or open a container).
209    Value,
210    /// Parse an object key (or the closing brace in the caller).
211    Key,
212    /// A completed node is waiting to attach to its parent.
213    Attach,
214}
215
216fn frame_into_node(frame: ParseFrame) -> JsonNode {
217    match frame {
218        ParseFrame::Array(items) => JsonNode::array(items),
219        ParseFrame::Object { keys, values, .. } => JsonNode::object(keys, values),
220    }
221}
222
223impl Parser<'_> {
224    const fn peek(&self) -> Option<u8> {
225        if self.pos < self.bytes.len() {
226            Some(self.bytes[self.pos])
227        } else {
228            None
229        }
230    }
231
232    const fn bump(&mut self) {
233        self.pos += 1;
234    }
235
236    const fn skip_ws(&mut self) {
237        while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
238            self.pos += 1;
239        }
240    }
241
242    fn literal(&mut self, word: &str) -> bool {
243        if self.bytes[self.pos..].starts_with(word.as_bytes()) {
244            self.pos += word.len();
245            return true;
246        }
247        false
248    }
249
250    fn parse_root(&mut self) -> Result<JsonNode, ParseError> {
251        let mut flow = Flow::Next(ParseState::Value);
252        loop {
253            flow = match flow {
254                Flow::Next(ParseState::Value) => Flow::Next(self.step_value()?),
255                Flow::Next(ParseState::Key) => Flow::Next(self.step_key()?),
256                Flow::Next(ParseState::Attach) => self.step_attach()?,
257                Flow::Done(node) => return Ok(node),
258            };
259        }
260    }
261
262    /// One Value step: open a container or parse a leaf.
263    fn step_value(&mut self) -> Result<ParseState, ParseError> {
264        self.skip_ws();
265        match self.peek() {
266            Some(b'[') => {
267                self.bump();
268                self.open_frame()?;
269                self.skip_ws();
270                if self.peek() == Some(b']') {
271                    self.bump();
272                    self.close_frame();
273                    Ok(ParseState::Attach)
274                } else {
275                    Ok(ParseState::Value)
276                }
277            }
278            Some(b'{') => {
279                self.bump();
280                self.open_frame()?;
281                self.skip_ws();
282                if self.peek() == Some(b'}') {
283                    self.bump();
284                    self.close_frame();
285                    Ok(ParseState::Attach)
286                } else {
287                    Ok(ParseState::Key)
288                }
289            }
290            _ => {
291                self.pending = Some(self.parse_leaf()?);
292                Ok(ParseState::Attach)
293            }
294        }
295    }
296
297    /// Open the container whose opening bracket was just consumed.
298    fn open_frame(&mut self) -> Result<(), ParseError> {
299        self.depth += 1;
300        if self.depth > PARSE_DEPTH_LIMIT {
301            return Err(ParseError::Depth);
302        }
303        if self.bytes[self.pos - 1] == b'[' {
304            self.stack.push(ParseFrame::Array(Vec::new()));
305        } else {
306            self.stack.push(ParseFrame::Object {
307                keys: Vec::new(),
308                values: Vec::new(),
309                current_key: None,
310            });
311        }
312        Ok(())
313    }
314
315    /// Close the top frame after consuming its closing bracket: pop it, turn
316    /// it into a node, and queue it for attachment.
317    fn close_frame(&mut self) {
318        self.depth -= 1;
319        let frame = self.stack.pop().expect("frame stack not empty");
320        self.pending = Some(frame_into_node(frame));
321    }
322
323    /// One Key step: parse `"key":` and store it on the open object frame.
324    fn step_key(&mut self) -> Result<ParseState, ParseError> {
325        self.skip_ws();
326        if self.peek() != Some(b'"') {
327            return Err(ParseError::Invalid);
328        }
329        let key = self.parse_string()?;
330        self.skip_ws();
331        if self.peek() != Some(b':') {
332            return Err(ParseError::Invalid);
333        }
334        self.bump();
335        // a Key step only follows an opened object frame, so the frame under
336        // the key is always the object being filled
337        let mut frame = self.stack.last_mut();
338        #[cfg(not(coverage))] // unreachable: the machine only enters a Key
339        // step right after an object frame opened, so the slot is always
340        // present
341        if let Some(slot) = frame.as_mut().and_then(|frame| frame.object_key_slot()) {
342            *slot = Some(key);
343        }
344        #[cfg(coverage)]
345        {
346            let slot = frame
347                .as_mut()
348                .and_then(|frame| frame.object_key_slot())
349                .expect("a Key step always follows an object frame");
350            *slot = Some(key);
351        }
352        Ok(ParseState::Value)
353    }
354
355    /// One Attach step: attach the completed node to its parent, close the
356    /// parent on its closing bracket, or finish the root value.
357    fn step_attach(&mut self) -> Result<Flow, ParseError> {
358        #[cfg(not(coverage))] // unreachable: every Attach entry queues a node
359        let Some(node) = self.pending.take() else {
360            return Err(ParseError::Invalid);
361        };
362        #[cfg(coverage)]
363        let node = self
364            .pending
365            .take()
366            .expect("every Attach entry queues a node");
367        self.skip_ws();
368        let delimiter = self.peek();
369        let Some(frame) = self.stack.pop() else {
370            if self.pos != self.bytes.len() {
371                // json.loads rejects trailing content after the value.
372                return Err(ParseError::Invalid);
373            }
374            return Ok(Flow::Done(node));
375        };
376        match frame {
377            ParseFrame::Array(mut items) => match delimiter {
378                Some(b',') => {
379                    self.bump();
380                    items.push(node);
381                    self.stack.push(ParseFrame::Array(items));
382                    Ok(Flow::Next(ParseState::Value))
383                }
384                Some(b']') => {
385                    self.bump();
386                    items.push(node);
387                    self.depth -= 1;
388                    self.pending = Some(JsonNode::array(items));
389                    Ok(Flow::Next(ParseState::Attach))
390                }
391                _ => Err(ParseError::Invalid),
392            },
393            ParseFrame::Object {
394                mut keys,
395                mut values,
396                mut current_key,
397            } => {
398                #[cfg(not(coverage))] // unreachable: the machine re-arms the
399                // frame's key slot on every comma and closer, and a Key step
400                // rejects non-string input before any Attach can run
401                let key = current_key.take().ok_or(ParseError::Invalid)?;
402                #[cfg(coverage)]
403                let key = current_key
404                    .take()
405                    .expect("the key slot is re-armed before every Attach");
406                match delimiter {
407                    Some(b',') => {
408                        self.bump();
409                        upsert_object(&mut keys, &mut values, key, node);
410                        self.stack.push(ParseFrame::Object {
411                            keys,
412                            values,
413                            current_key,
414                        });
415                        Ok(Flow::Next(ParseState::Key))
416                    }
417                    Some(b'}') => {
418                        self.bump();
419                        upsert_object(&mut keys, &mut values, key, node);
420                        self.depth -= 1;
421                        self.pending = Some(JsonNode::object(keys, values));
422                        Ok(Flow::Next(ParseState::Attach))
423                    }
424                    _ => Err(ParseError::Invalid),
425                }
426            }
427        }
428    }
429
430    /// A non-container value: string, number, boolean, null, or the Python
431    /// `json.loads` NaN/Infinity extensions.
432    fn parse_leaf(&mut self) -> Result<JsonNode, ParseError> {
433        match self.peek() {
434            Some(b'"') => Ok(JsonNode::leaf(Scalar::Str(self.parse_string()?))),
435            Some(b't') if self.literal("true") => Ok(JsonNode::leaf(Scalar::Bool(true))),
436            Some(b'f') if self.literal("false") => Ok(JsonNode::leaf(Scalar::Bool(false))),
437            Some(b'n') if self.literal("null") => Ok(JsonNode::leaf(Scalar::Null)),
438            Some(b'N') if self.literal("NaN") => Ok(JsonNode::leaf(Scalar::Nan)),
439            Some(b'I') if self.literal("Infinity") => Ok(JsonNode::leaf(Scalar::Infinity)),
440            Some(b'-') => {
441                if self.literal("-Infinity") {
442                    return Ok(JsonNode::leaf(Scalar::NegInfinity));
443                }
444                Ok(JsonNode::leaf(Scalar::Number(self.parse_number_literal()?)))
445            }
446            Some(c) if c.is_ascii_digit() => {
447                Ok(JsonNode::leaf(Scalar::Number(self.parse_number_literal()?)))
448            }
449            _ => Err(ParseError::Invalid),
450        }
451    }
452
453    /// A JSON string with escape and surrogate-pair processing; unescaped
454    /// control characters are rejected (Python's strict mode).
455    fn parse_string(&mut self) -> Result<String, ParseError> {
456        self.bump(); // opening '"'
457        let mut out = String::new();
458        loop {
459            match self.peek() {
460                None => return Err(ParseError::Invalid),
461                Some(b'"') => {
462                    self.bump();
463                    return Ok(out);
464                }
465                Some(b'\\') => {
466                    self.bump();
467                    let escaped = self.peek().ok_or(ParseError::Invalid)?;
468                    self.bump();
469                    match escaped {
470                        b'"' => out.push('"'),
471                        b'\\' => out.push('\\'),
472                        b'/' => out.push('/'),
473                        b'b' => out.push('\u{8}'),
474                        b'f' => out.push('\u{c}'),
475                        b'n' => out.push('\n'),
476                        b'r' => out.push('\r'),
477                        b't' => out.push('\t'),
478                        b'u' => {
479                            let first = self.parse_hex4()?;
480                            let ch = match first {
481                                (0xD800..=0xDBFF) => {
482                                    // High surrogate: a following low
483                                    // surrogate combines, anything else is a
484                                    // lone surrogate (U+FFFD at the engine's
485                                    // decode boundary).
486                                    if self.peek() == Some(b'\\')
487                                        && self.bytes.get(self.pos + 1) == Some(&b'u')
488                                    {
489                                        self.pos += 2;
490                                        let second = self.parse_hex4()?;
491                                        if (0xDC00..=0xDFFF).contains(&second) {
492                                            let combined = 0x1_0000
493                                                + ((u32::from(first) - 0xD800) << 10)
494                                                + (u32::from(second) - 0xDC00);
495                                            #[cfg(not(coverage))] // unreachable:
496                                            // the surrogate-pair arithmetic
497                                            // always lands in the astral range
498                                            let ch = char::from_u32(combined)
499                                                .ok_or(ParseError::Invalid)?;
500                                            #[cfg(coverage)]
501                                            let ch = char::from_u32(combined).expect(
502                                                "the pair arithmetic yields a valid scalar",
503                                            );
504                                            ch
505                                        } else {
506                                            self.pos -= 2;
507                                            '\u{FFFD}'
508                                        }
509                                    } else {
510                                        '\u{FFFD}'
511                                    }
512                                }
513                                (0xDC00..=0xDFFF) => '\u{FFFD}',
514                                #[cfg(not(coverage))] // unreachable: every
515                                // non-surrogate u16 is a valid scalar
516                                _ => char::from_u32(u32::from(first)).ok_or(ParseError::Invalid)?,
517                                #[cfg(coverage)]
518                                _ => char::from_u32(u32::from(first))
519                                    .expect("a non-surrogate u16 is a valid scalar"),
520                            };
521                            out.push(ch);
522                        }
523                        _ => return Err(ParseError::Invalid),
524                    }
525                }
526                Some(c) if c < 0x20 => return Err(ParseError::Invalid),
527                Some(_) => {
528                    // Copy one full UTF-8 scalar; the input is a valid &str.
529                    let rest = &self.bytes[self.pos..];
530                    #[cfg(not(coverage))] // unreachable: the input is a &str,
531                    // so every slice of it is valid UTF-8...
532                    let s = std::str::from_utf8(rest).map_err(|_| ParseError::Invalid)?;
533                    #[cfg(coverage)]
534                    let s = std::str::from_utf8(rest).expect("a &str slice is valid UTF-8");
535                    #[cfg(not(coverage))] // unreachable: ...and non-empty (a
536                    // byte was peeked above), so a scalar always follows
537                    let ch = s.chars().next().ok_or(ParseError::Invalid)?;
538                    #[cfg(coverage)]
539                    let ch = s.chars().next().expect("the remainder is non-empty");
540                    out.push(ch);
541                    self.pos += ch.len_utf8();
542                }
543            }
544        }
545    }
546
547    fn parse_hex4(&mut self) -> Result<u16, ParseError> {
548        if self.pos + 4 > self.bytes.len() {
549            return Err(ParseError::Invalid);
550        }
551        let slice = &self.bytes[self.pos..self.pos + 4];
552        // A scalar can straddle the 4-byte window and break UTF-8 validity
553        // (a `\u` escape followed by a multi-byte character), so the
554        // conversion failure stays a real arm, not a defensive one.
555        let text = std::str::from_utf8(slice).map_err(|_| ParseError::Invalid)?;
556        let value = u16::from_str_radix(text, 16).map_err(|_| ParseError::Invalid)?;
557        self.pos += 4;
558        Ok(value)
559    }
560
561    /// Strict JSON number grammar; leading zeros rejected like Python's
562    /// strict parser. The literal span is kept verbatim for scanning.
563    fn parse_number_literal(&mut self) -> Result<String, ParseError> {
564        let start = self.pos;
565        if self.peek() == Some(b'-') {
566            self.bump();
567        }
568        match self.peek() {
569            Some(b'0') => self.bump(),
570            Some(c) if c.is_ascii_digit() => {
571                while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
572                    self.bump();
573                }
574            }
575            _ => return Err(ParseError::Invalid),
576        }
577        if self.peek() == Some(b'.') {
578            self.bump();
579            if !matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
580                return Err(ParseError::Invalid);
581            }
582            while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
583                self.bump();
584            }
585        }
586        if matches!(self.peek(), Some(b'e' | b'E')) {
587            self.bump();
588            if matches!(self.peek(), Some(b'+' | b'-')) {
589                self.bump();
590            }
591            if !matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
592                return Err(ParseError::Invalid);
593            }
594            while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {
595                self.bump();
596            }
597        }
598        #[cfg(not(coverage))] // unreachable: the number span is a slice of
599        // a &str, so it is valid UTF-8
600        let text =
601            std::str::from_utf8(&self.bytes[start..self.pos]).map_err(|_| ParseError::Invalid)?;
602        #[cfg(coverage)]
603        let text = std::str::from_utf8(&self.bytes[start..self.pos])
604            .expect("the number span is valid UTF-8");
605        Ok(text.to_owned())
606    }
607}
608
609/// `_MONGO_OPERATOR_KEY_RE` from `guard_core/_utils/body_json_scan.py`.
610fn mongo_operator_key_re() -> &'static Regex {
611    static RE: LazyLock<Regex> = LazyLock::new(|| {
612        Regex::new(r"^\$(?:ne|gt|gte|lt|lte|eq|in|nin|nor|and|or|not|all|size|exists|type|mod|options|where|regex|expr|function|elemMatch)$")
613            .expect("mongo operator key regex")
614    });
615    &RE
616}
617
618struct Frame<'a> {
619    is_entry: bool,
620    key: String,
621    node: &'a JsonNode,
622    depth: usize,
623}
624
625/// `appendJSONWalkEntries` emits the scan values of one JSON walk in the
626/// reference order. Entry keys carry the `request_body` context; leaves carry
627/// the walk context (`request_body` for a top-level body walk, or a field
628/// context with the `:embedded_json` suffix per embedded walk level).
629///
630/// `excluded` carries the excluded detection body fields (entries
631/// lowercased at resolution time): an entry key in the set skips its whole
632/// subtree, exactly the reference's excluded-field routing in the JSON walk
633/// (the mongo-operator direct hit sits behind the same check).
634pub(crate) fn append_json_walk_entries(
635    mut values: Vec<BodyScanValue>,
636    root: &JsonNode,
637    context: &str,
638    excluded: crate::body_scan::ExcludedBodyFields<'_>,
639) -> Vec<BodyScanValue> {
640    let allow_leaf_reparse = context != REQUEST_BODY_CONTEXT;
641    // Frames are consumed in order; the reference uses a LIFO stack and pushes
642    // children reversed, so children process in insertion order.
643    let mut stack = vec![Frame {
644        is_entry: false,
645        key: String::new(),
646        node: root,
647        depth: 1,
648    }];
649    while let Some(frame) = stack.pop() {
650        if frame.is_entry {
651            if excluded.contains(&frame.key) {
652                continue;
653            }
654            if mongo_operator_key_re().is_match(&frame.key) {
655                // body_json_scan._mongo_operator_key_hit: the reference
656                // reports this hit straight from the walk, unfiltered.
657                values.push(BodyScanValue::forced(
658                    frame.key,
659                    crate::body_scan::MONGO_OPERATOR_CATEGORY,
660                ));
661                continue;
662            }
663            values.push(BodyScanValue::plain(
664                frame.key.as_str(),
665                REQUEST_BODY_CONTEXT,
666            ));
667            stack.push(Frame {
668                is_entry: false,
669                key: frame.key.clone(),
670                node: frame.node,
671                depth: frame.depth + 1,
672            });
673            continue;
674        }
675        let node = frame.node;
676        if node.is_object {
677            if frame.depth >= JSON_WALK_DEPTH_CAP {
678                values.push(BodyScanValue::plain(serialize_compact_json(node), context));
679                continue;
680            }
681            for index in (0..node.keys.len()).rev() {
682                stack.push(Frame {
683                    is_entry: true,
684                    key: node.keys[index].clone(),
685                    node: &node.values[index],
686                    depth: frame.depth,
687                });
688            }
689        } else if node.is_array {
690            if frame.depth >= JSON_WALK_DEPTH_CAP {
691                values.push(BodyScanValue::plain(serialize_compact_json(node), context));
692                continue;
693            }
694            for item in node.items.iter().rev() {
695                // List items inherit the container's label.
696                stack.push(Frame {
697                    is_entry: false,
698                    key: frame.key.clone(),
699                    node: item,
700                    depth: frame.depth + 1,
701                });
702            }
703        } else {
704            let scalar = node.scalar.as_ref().expect("leaf node carries a scalar");
705            let text = scalar.scan_text();
706            if allow_leaf_reparse && let Some(inner) = parse_ordered_json(&text) {
707                values = append_json_walk_entries(
708                    values,
709                    &inner,
710                    &format!("{context}{EMBEDDED_JSON_LEAF_CONTEXT_SUFFIX}"),
711                    excluded,
712                );
713                continue;
714            }
715            values.push(BodyScanValue::plain(text, context));
716        }
717    }
718    values
719}
720
721/// Render a subtree the way
722/// `json.dumps(value, separators=(",", ":"), ensure_ascii=False)` does for
723/// the depth-capped subtree scan.
724///
725/// `NaN`/`Infinity`/`-Infinity` are emitted bare, like `json.dumps` with the
726/// default `allow_nan=True`.
727#[must_use]
728pub fn serialize_compact_json(node: &JsonNode) -> String {
729    let mut out = String::new();
730    write_compact_json(&mut out, node);
731    out
732}
733
734fn write_compact_json(out: &mut String, node: &JsonNode) {
735    if node.is_object {
736        out.push('{');
737        for (index, key) in node.keys.iter().enumerate() {
738            if index > 0 {
739                out.push(',');
740            }
741            out.push('"');
742            write_json_string_body(out, key);
743            out.push_str("\":");
744            write_compact_json(out, &node.values[index]);
745        }
746        out.push('}');
747        return;
748    }
749    if node.is_array {
750        out.push('[');
751        for (index, item) in node.items.iter().enumerate() {
752            if index > 0 {
753                out.push(',');
754            }
755            write_compact_json(out, item);
756        }
757        out.push(']');
758        return;
759    }
760    match node.scalar.as_ref().expect("leaf node carries a scalar") {
761        Scalar::Str(s) => {
762            out.push('"');
763            write_json_string_body(out, s);
764            out.push('"');
765        }
766        Scalar::Number(literal) => out.push_str(literal),
767        Scalar::Bool(true) => out.push_str("true"),
768        Scalar::Bool(false) => out.push_str("false"),
769        Scalar::Null => out.push_str("null"),
770        Scalar::Nan => out.push_str("NaN"),
771        Scalar::Infinity => out.push_str("Infinity"),
772        Scalar::NegInfinity => out.push_str("-Infinity"),
773    }
774}
775
776/// Escape `s` the way `json.dumps(ensure_ascii=False)` does: quote,
777/// backslash, and the C0 controls; everything else stays literal UTF-8.
778fn write_json_string_body(out: &mut String, s: &str) {
779    for r in s.chars() {
780        match r {
781            '"' => out.push_str("\\\""),
782            '\\' => out.push_str("\\\\"),
783            '\n' => out.push_str("\\n"),
784            '\r' => out.push_str("\\r"),
785            '\t' => out.push_str("\\t"),
786            '\u{8}' => out.push_str("\\b"),
787            '\u{c}' => out.push_str("\\f"),
788            _ => {
789                if r < ' ' {
790                    const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef";
791                    let cp = r as u32;
792                    out.push_str("\\u00");
793                    out.push(HEX_DIGITS[((cp >> 4) & 0xf) as usize] as char);
794                    out.push(HEX_DIGITS[(cp & 0xf) as usize] as char);
795                } else {
796                    out.push(r);
797                }
798            }
799        }
800    }
801}
802
803#[cfg(test)]
804mod tests {
805    use super::*;
806
807    fn walk(context: &str, body: &str) -> Vec<(String, String, Option<&'static str>)> {
808        parse_ordered_json(body)
809            .map(|root| {
810                append_json_walk_entries(
811                    Vec::new(),
812                    &root,
813                    context,
814                    crate::body_scan::ExcludedBodyFields::default(),
815                )
816                .into_iter()
817                .map(|v| (v.context, v.content, v.forced_category))
818                .collect()
819            })
820            .unwrap_or_default()
821    }
822
823    #[test]
824    fn root_must_be_object_or_array() {
825        assert!(parse_ordered_json("123").is_none());
826        assert!(parse_ordered_json("\"str\"").is_none());
827        assert!(parse_ordered_json("true").is_none());
828        assert!(parse_ordered_json("null").is_none());
829        assert!(parse_ordered_json("").is_none());
830        assert!(parse_ordered_json("{\"a\":1}").is_some());
831        assert!(parse_ordered_json("[1,2]").is_some());
832    }
833
834    #[test]
835    fn object_key_slot_answers_none_for_array_frames() {
836        let mut array = ParseFrame::Array(Vec::new());
837        assert!(array.object_key_slot().is_none());
838        let mut object = ParseFrame::Object {
839            keys: Vec::new(),
840            values: Vec::new(),
841            current_key: None,
842        };
843        assert!(object.object_key_slot().is_some());
844    }
845
846    #[test]
847    fn parse_error_arms_reject_the_reference_failures() {
848        // The recursion bound standing in for RecursionError.
849        let deep = format!("{}1{}", "[".repeat(1001), "]".repeat(1001));
850        assert!(parse_ordered_json(&deep).is_none(), "depth bound fires");
851        // the object arm of the frame bound: nested objects, not arrays
852        let deep_objects = format!("{}1{}", "{\"a\":".repeat(1001), "1".repeat(1001));
853        assert!(parse_ordered_json(&deep_objects).is_none(), "object depth");
854        // a comma followed by a value re-opens the object frame keyless,
855        // and the stray value cannot attach
856        assert!(parse_ordered_json("{\"a\":1,2}").is_none());
857        // a trailing comma before the closer is rejected like json.loads
858        assert!(parse_ordered_json("{\"a\":1,}").is_none());
859        // a malformed second \\u escape after a high surrogate
860        assert!(parse_ordered_json("{\"k\":\"\\ud83d\\uZZZZ\"}").is_none());
861        // An invalid escape inside an object key fails the key step.
862        assert!(parse_ordered_json("{\"\\q\":1}").is_none());
863        // A trailing comma leaves the object frame without a pending key.
864        assert!(parse_ordered_json("{\"a\":1,}").is_none());
865        // Control characters inside strings are rejected.
866        assert!(parse_ordered_json("{\"k\":\"a\u{1}b\"}").is_none());
867        // A non-hex \\u escape is rejected.
868        assert!(parse_ordered_json("{\"k\":\"\\uZZZZ\"}").is_none());
869        // A multi-byte scalar straddling the \\u window breaks the read.
870        assert!(parse_ordered_json("{\"k\":\"\\u\u{e9}\u{20ac}\"}").is_none());
871    }
872
873    #[test]
874    fn surrogate_pair_arms_follow_the_reference() {
875        // A valid high/low pair combines into an astral scalar...
876        let entries = walk("body", "{\"k\":\"\\ud83d\\ude00\"}");
877        let joined: String = entries.iter().map(|e| e.1.as_str()).collect();
878        assert!(
879            joined.contains('\u{1F600}'),
880            "the surrogate pair combines: {entries:?}"
881        );
882        // ...a lone high surrogate degrades to U+FFFD, and the parser
883        // rewinds before the unconsumed \\u.
884        let entries = walk("body", "{\"k\":\"\\ud83dx\"}");
885        let joined: String = entries.iter().map(|e| e.1.as_str()).collect();
886        assert!(
887            joined.contains('\u{FFFD}'),
888            "the lone high surrogate degrades: {entries:?}"
889        );
890        // A lone low surrogate degrades to U+FFFD too.
891        let entries = walk("body", "{\"k\":\"\\udc00\"}");
892        let joined: String = entries.iter().map(|e| e.1.as_str()).collect();
893        assert!(
894            joined.contains('\u{FFFD}'),
895            "the lone low surrogate degrades: {entries:?}"
896        );
897    }
898
899    #[test]
900    fn trailing_data_rejected_like_json_loads() {
901        assert!(parse_ordered_json("{\"a\":1} trailing").is_none());
902        assert!(parse_ordered_json("[1] [2]").is_none());
903    }
904
905    #[test]
906    fn duplicate_keys_keep_first_position_and_last_value() {
907        let values = walk(REQUEST_BODY_CONTEXT, "{\"a\":1,\"b\":2,\"a\":3}");
908        let contents: Vec<&str> = values.iter().map(|(_, c, _)| c.as_str()).collect();
909        // Insertion order a, b with the last value winning per key.
910        assert_eq!(contents, vec!["a", "3", "b", "2"]);
911    }
912
913    #[test]
914    fn number_and_boolean_leaves_scan_python_str_renderings() {
915        let values = walk(REQUEST_BODY_CONTEXT, "[1, -2.5, 1e2, true, false, null]");
916        let contents: Vec<&str> = values.iter().map(|(_, c, _)| c.as_str()).collect();
917        // Number leaves scan the literal (documented deviation from Python's
918        // float repr for 1e2, which Python renders as "100.0").
919        assert_eq!(contents, vec!["1", "-2.5", "1e2", "True", "False", "None"]);
920    }
921
922    #[test]
923    fn nan_and_infinity_accepted_like_json_loads() {
924        let values = walk(REQUEST_BODY_CONTEXT, "[NaN, Infinity, -Infinity]");
925        let contents: Vec<&str> = values.iter().map(|(_, c, _)| c.as_str()).collect();
926        assert_eq!(contents, vec!["nan", "inf", "-inf"]);
927    }
928
929    #[test]
930    fn mongo_operator_keys_force_nosql_hits() {
931        for key in ["$where", "$ne", "$regex", "$elemMatch"] {
932            let body = format!("{{\"{key}\": 1}}");
933            let values = walk(REQUEST_BODY_CONTEXT, &body);
934            assert_eq!(values.len(), 1, "{key}");
935            assert_eq!(values[0].0, REQUEST_BODY_CONTEXT);
936            assert_eq!(values[0].1, key);
937            assert_eq!(values[0].2, Some(crate::body_scan::MONGO_OPERATOR_CATEGORY));
938        }
939    }
940
941    #[test]
942    fn dollar_word_that_is_not_an_operator_scans_plain() {
943        let values = walk(REQUEST_BODY_CONTEXT, "{\"$money\": 1}");
944        assert_eq!(values.len(), 2);
945        assert_eq!(values[0].2, None);
946        assert_eq!(values[0].1, "$money");
947    }
948
949    #[test]
950    fn embedded_walk_appends_the_suffix_per_level() {
951        // A form field walk whose leaf is a JSON string carrying JSON: the
952        // leaf re-parses once per level, so each level adds one suffix.
953        let single = r#"{"outer":"{\"a\":\"1 OR 1=1\"}"}"#;
954        let values = walk("request_body:form_field", single);
955        assert_eq!(
956            values,
957            vec![
958                (REQUEST_BODY_CONTEXT.to_owned(), "outer".to_owned(), None),
959                (REQUEST_BODY_CONTEXT.to_owned(), "a".to_owned(), None),
960                (
961                    "request_body:form_field:embedded_json".to_owned(),
962                    "1 OR 1=1".to_owned(),
963                    None
964                ),
965            ]
966        );
967
968        // A string leaf only re-walks when it parses to an object or array,
969        // so the second suffix needs another JSON object carried in the
970        // first one's leaf string.
971        let double = r#"{"outer":"{\"a\":\"{\\\"b\\\":\\\"1 OR 1=1\\\"}\"}"}"#;
972        let values = walk("request_body:form_field", double);
973        assert_eq!(
974            values,
975            vec![
976                (REQUEST_BODY_CONTEXT.to_owned(), "outer".to_owned(), None),
977                (REQUEST_BODY_CONTEXT.to_owned(), "a".to_owned(), None),
978                (REQUEST_BODY_CONTEXT.to_owned(), "b".to_owned(), None),
979                (
980                    "request_body:form_field:embedded_json:embedded_json".to_owned(),
981                    "1 OR 1=1".to_owned(),
982                    None
983                ),
984            ]
985        );
986    }
987
988    #[test]
989    fn top_level_walk_never_reparses_leaf_strings() {
990        let body = "{\"a\":\"{\\\"b\\\":\\\"c\\\"}\"}";
991        let values = walk(REQUEST_BODY_CONTEXT, body);
992        assert_eq!(
993            values,
994            vec![
995                (REQUEST_BODY_CONTEXT.to_owned(), "a".to_owned(), None),
996                (
997                    REQUEST_BODY_CONTEXT.to_owned(),
998                    "{\"b\":\"c\"}".to_owned(),
999                    None
1000                ),
1001            ]
1002        );
1003    }
1004
1005    #[test]
1006    fn depth_cap_serializes_the_subtree_as_compact_json() {
1007        let mut deep = String::new();
1008        for _ in 0..40 {
1009            deep.insert(0, '[');
1010            deep.push(']');
1011        }
1012        let values = walk(REQUEST_BODY_CONTEXT, &format!("{{\"a\":{deep}}}"));
1013        assert_eq!(values[0].1, "a");
1014        let last = values.last().expect("capped subtree value");
1015        // The 32nd-level container serializes back to compact JSON: 40
1016        // nested arrays minus the 30 walked levels leave 10 in the text.
1017        assert_eq!(last.1.matches('[').count(), 10);
1018        assert_eq!(last.1.matches(']').count(), 10);
1019    }
1020
1021    #[test]
1022    fn compact_serialization_escapes_like_json_dumps() {
1023        let values = walk(REQUEST_BODY_CONTEXT, "{\"a\":\"quote\\\" back\\\\ nl\\n\"}");
1024        let last = values.last().expect("leaf");
1025        assert_eq!(last.1, "quote\" back\\ nl\n");
1026        // Serialize the same string from a capped container.
1027        let node = parse_ordered_json("{\"a\":\"x\\u0001y\"}").expect("parses");
1028        let text = serialize_compact_json(&node);
1029        assert_eq!(text, "{\"a\":\"x\\u0001y\"}");
1030    }
1031
1032    #[test]
1033    fn parse_depth_limit_beyond_python_recursion_fails_to_blob() {
1034        let mut deep = String::new();
1035        for _ in 0..1500 {
1036            deep.insert(0, '[');
1037            deep.push(']');
1038        }
1039        assert!(parse_ordered_json(&deep).is_none());
1040        // Just above the walk cap but far below the parse limit still walks,
1041        // with the capped subtrees serialized.
1042        let mut mid = String::new();
1043        for _ in 0..40 {
1044            mid.insert(0, '[');
1045            mid.push(']');
1046        }
1047        assert!(parse_ordered_json(&mid).is_some());
1048    }
1049
1050    #[test]
1051    fn strict_grammar_rejects_loose_json() {
1052        for body in [
1053            "{\"a\":01}",
1054            "[1,]",
1055            "{\"a\":}",
1056            "{\"a\" 1}",
1057            "[unclosed",
1058            "\"\\x41\"",
1059            "[1 2]",
1060        ] {
1061            assert!(parse_ordered_json(body).is_none(), "{body:?} must fail");
1062        }
1063    }
1064
1065    #[test]
1066    fn unicode_escapes_decode() {
1067        let values = walk(
1068            REQUEST_BODY_CONTEXT,
1069            "[\"\\u00e9\\ud83d\\ude00\", \"\\ud800\"]",
1070        );
1071        assert_eq!(values[0].1, "\u{e9}\u{1F600}");
1072        assert_eq!(values[1].1, "\u{FFFD}", "lone surrogate -> replacement");
1073    }
1074}
1075
1076#[cfg(test)]
1077mod coverage_tests {
1078    use super::*;
1079
1080    #[test]
1081    fn strict_parser_rejects_malformed_documents() {
1082        for bad in [
1083            "{'1':2}",     // the key is not a string
1084            "[\"k\":1]",   // a key step on an array frame
1085            "\"abc",       // unterminated string
1086            "\"abc\\",     // a trailing backslash
1087            "{\"a\":01}",  // a leading zero number
1088            "{\"a\":-}",   // a bare minus
1089            "{\"a\":tru}", // a truncated literal
1090            "+1",          // a bad value start
1091            "{\"a\":1,}",  // a trailing comma
1092            "{} extra",    // trailing content after the value
1093        ] {
1094            assert!(parse_ordered_json(bad).is_none(), "accepted {bad:?}");
1095        }
1096    }
1097
1098    #[test]
1099    fn string_escapes_decode_including_surrogate_pairs() {
1100        // scalar roots are not walked (the corpus only carries objects and
1101        // arrays), so the escape probes ride inside an object
1102        let node = parse_ordered_json(r#"{"e":"\/\b\f\r\tA"}"#).expect("escapes");
1103        assert_eq!(serialize_compact_json(&node), r#"{"e":"/\b\f\r\tA"}"#);
1104
1105        // a valid surrogate pair assembles the astral char
1106        let node = parse_ordered_json(r#"{"p":"\ud83d\ude00"}"#).expect("pair");
1107        assert_eq!(serialize_compact_json(&node), "{\"p\":\"\u{1F600}\"}");
1108
1109        // lone surrogates decode to the replacement character
1110        let node = parse_ordered_json(r#"{"h":"\ud83d"}"#).expect("lone high");
1111        assert_eq!(serialize_compact_json(&node), "{\"h\":\"\u{FFFD}\"}");
1112        let node = parse_ordered_json(r#"{"l":"\udc00"}"#).expect("lone low");
1113        assert_eq!(serialize_compact_json(&node), "{\"l\":\"\u{FFFD}\"}");
1114    }
1115
1116    #[test]
1117    fn serializer_renders_every_scalar_and_separator() {
1118        let cases = [
1119            (
1120                r#"{"n":1,"t":true,"f":false,"z":null}"#,
1121                "{\"n\":1,\"t\":true,\"f\":false,\"z\":null}",
1122            ),
1123            ("[1,2]", "[1,2]"),
1124            (
1125                r#"{"x":NaN,"y":Infinity,"z":-Infinity}"#,
1126                "{\"x\":NaN,\"y\":Infinity,\"z\":-Infinity}",
1127            ),
1128            (
1129                r#"{"s":"quote\" back\\ nl\ncr\rtab\bbc\ffc"}"#,
1130                "{\"s\":\"quote\\\" back\\\\ nl\\ncr\\rtab\\bbc\\ffc\"}",
1131            ),
1132            (r#"{"o":{"k":[{},[]]}}"#, "{\"o\":{\"k\":[{},[]]}}"),
1133        ];
1134        for (src, want) in cases {
1135            let node = parse_ordered_json(src).expect(src);
1136            assert_eq!(serialize_compact_json(&node), want, "serializing {src}");
1137        }
1138    }
1139}
1140
1141#[cfg(test)]
1142mod gap_tests {
1143    use super::*;
1144    use crate::body_scan::ExcludedBodyFields;
1145
1146    #[test]
1147    fn a_high_surrogate_followed_by_a_non_low_escape_becomes_fffd() {
1148        // the second escape is re-scanned after the rewind, so only the lone
1149        // high surrogate degrades to U+FFFD
1150        let node = parse_ordered_json(r#"{"k":"\ud800\u0041"}"#).expect("parses");
1151        let values = append_json_walk_entries(
1152            Vec::new(),
1153            &node,
1154            REQUEST_BODY_CONTEXT,
1155            ExcludedBodyFields::default(),
1156        );
1157        // the rewind lands two chars into the failed second escape, so the
1158        // trailing digits rescan as literal text
1159        assert!(values.iter().any(|value| value.content == "\u{FFFD}41"));
1160    }
1161
1162    #[test]
1163    fn a_truncated_unicode_escape_is_malformed() {
1164        // fewer than four hex digits before the end of input
1165        assert!(parse_ordered_json("{\"k\":\"\\u1\"}").is_none());
1166    }
1167
1168    #[test]
1169    fn malformed_number_grammars_are_rejected() {
1170        // a fraction dot without digits
1171        assert!(parse_ordered_json("{\"k\":1.}").is_none());
1172        // an exponent sign without digits
1173        assert!(parse_ordered_json("{\"k\":1e+}").is_none());
1174        // a signed exponent walks
1175        let node = parse_ordered_json("{\"k\":1e+5}").expect("parses");
1176        let values = append_json_walk_entries(
1177            Vec::new(),
1178            &node,
1179            REQUEST_BODY_CONTEXT,
1180            ExcludedBodyFields::default(),
1181        );
1182        assert!(values.iter().any(|value| value.content == "1e+5"));
1183    }
1184
1185    #[test]
1186    fn an_excluded_entry_key_skips_its_subtree() {
1187        let excluded = std::iter::once("password".to_owned()).collect();
1188        let node = parse_ordered_json(r#"{"password":"secret","keep":"v"}"#).expect("parses");
1189        let values = append_json_walk_entries(
1190            Vec::new(),
1191            &node,
1192            REQUEST_BODY_CONTEXT,
1193            ExcludedBodyFields::new(&excluded),
1194        );
1195        let keys: Vec<&str> = values.iter().map(|value| value.content.as_str()).collect();
1196        assert!(!keys.contains(&"password"));
1197        assert!(!keys.contains(&"secret"));
1198        assert!(keys.contains(&"keep"));
1199    }
1200
1201    #[test]
1202    fn containers_at_the_depth_cap_serialize_back_to_json() {
1203        // 31 nested arrays put the inner object at walk depth 32
1204        let body = format!("{}{{\"k\":1}}{}", "[".repeat(31), "]".repeat(31));
1205        let node = parse_ordered_json(&body).expect("parses");
1206        let values = append_json_walk_entries(
1207            Vec::new(),
1208            &node,
1209            REQUEST_BODY_CONTEXT,
1210            ExcludedBodyFields::default(),
1211        );
1212        assert!(values.iter().any(|value| value.content == "{\"k\":1}"));
1213    }
1214}