1use 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
35pub const JSON_WALK_DEPTH_CAP: usize = 32;
38
39const PARSE_DEPTH_LIMIT: usize = 1000;
42
43#[derive(Debug, Clone, PartialEq)]
46enum Scalar {
47 Str(String),
48 Number(String),
50 Bool(bool),
51 Null,
52 Nan,
53 Infinity,
54 NegInfinity,
55}
56
57impl Scalar {
58 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#[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 Invalid,
127 Depth,
129}
130
131#[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 if !root.is_object && !root.is_array {
149 return None;
150 }
151 Some(root)
152}
153
154struct 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 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
177enum Flow {
179 Next(ParseState),
180 Done(JsonNode),
181}
182
183fn 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#[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 Value,
210 Key,
212 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 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 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 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 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 let mut frame = self.stack.last_mut();
338 #[cfg(not(coverage))] 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 fn step_attach(&mut self) -> Result<Flow, ParseError> {
358 #[cfg(not(coverage))] 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 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))] 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 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 fn parse_string(&mut self) -> Result<String, ParseError> {
456 self.bump(); 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 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))] 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))] _ => 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 let rest = &self.bytes[self.pos..];
530 #[cfg(not(coverage))] 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))] 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 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 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))] 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
609fn 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
625pub(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 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 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 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#[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
776fn 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 let deep = format!("{}1{}", "[".repeat(1001), "]".repeat(1001));
850 assert!(parse_ordered_json(&deep).is_none(), "depth bound fires");
851 let deep_objects = format!("{}1{}", "{\"a\":".repeat(1001), "1".repeat(1001));
853 assert!(parse_ordered_json(&deep_objects).is_none(), "object depth");
854 assert!(parse_ordered_json("{\"a\":1,2}").is_none());
857 assert!(parse_ordered_json("{\"a\":1,}").is_none());
859 assert!(parse_ordered_json("{\"k\":\"\\ud83d\\uZZZZ\"}").is_none());
861 assert!(parse_ordered_json("{\"\\q\":1}").is_none());
863 assert!(parse_ordered_json("{\"a\":1,}").is_none());
865 assert!(parse_ordered_json("{\"k\":\"a\u{1}b\"}").is_none());
867 assert!(parse_ordered_json("{\"k\":\"\\uZZZZ\"}").is_none());
869 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 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 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 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 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 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 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 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 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 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 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}", "[\"k\":1]", "\"abc", "\"abc\\", "{\"a\":01}", "{\"a\":-}", "{\"a\":tru}", "+1", "{\"a\":1,}", "{} extra", ] {
1094 assert!(parse_ordered_json(bad).is_none(), "accepted {bad:?}");
1095 }
1096 }
1097
1098 #[test]
1099 fn string_escapes_decode_including_surrogate_pairs() {
1100 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 let node = parse_ordered_json(r#"{"p":"\ud83d\ude00"}"#).expect("pair");
1107 assert_eq!(serialize_compact_json(&node), "{\"p\":\"\u{1F600}\"}");
1108
1109 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 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 assert!(values.iter().any(|value| value.content == "\u{FFFD}41"));
1160 }
1161
1162 #[test]
1163 fn a_truncated_unicode_escape_is_malformed() {
1164 assert!(parse_ordered_json("{\"k\":\"\\u1\"}").is_none());
1166 }
1167
1168 #[test]
1169 fn malformed_number_grammars_are_rejected() {
1170 assert!(parse_ordered_json("{\"k\":1.}").is_none());
1172 assert!(parse_ordered_json("{\"k\":1e+}").is_none());
1174 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 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}