1use std::fmt::{self, Debug, Display, Formatter};
6use std::hash::{DefaultHasher, Hash, Hasher};
7
8use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
9use serde_json::error::Category;
10
11use crate::errors::json_error_category;
12
13pub trait JsonRedaction {
52 const FIELD_NAMES: bool = false;
55
56 const DATA_KEYED_MAPS: FieldPaths = FieldPaths::NONE;
61
62 const SIZES: bool = false;
66
67 const REVEALED_FIELDS: FieldPaths = FieldPaths::NONE;
70}
71
72pub struct ShapeOnly;
76
77impl JsonRedaction for ShapeOnly {}
78
79#[derive(Debug, Clone, Copy)]
84pub struct FieldPaths(&'static [&'static str]);
85
86impl FieldPaths {
87 pub const NONE: Self = Self(&[]);
89
90 pub const fn from_static(paths: &'static [&'static str]) -> Self {
99 let mut index = 0;
100 while index < paths.len() {
101 if !Self::is_field_path(paths[index].as_bytes()) {
102 panic!(
103 "a field path is field names joined by `.`, with `[]` after a field for the items of its array"
104 );
105 }
106 index += 1;
107 }
108 Self(paths)
109 }
110
111 const fn is_field_path(path: &[u8]) -> bool {
114 let mut index = 0;
115 let mut first = true;
116 loop {
117 let start = index;
118 while index < path.len() && !matches!(path[index], b'.' | b'[' | b']') {
119 index += 1;
120 }
121 let named = index > start;
122 let mut items = false;
123 while index + 1 < path.len() && path[index] == b'[' && path[index + 1] == b']' {
124 index += 2;
125 items = true;
126 }
127 if !named && !(first && items) {
128 return false;
129 }
130 if index == path.len() {
131 return true;
132 }
133 if path[index] != b'.' {
134 return false;
135 }
136 index += 1;
137 first = false;
138 }
139 }
140}
141
142pub struct RedactedJson<'a> {
185 json: &'a [u8],
186 policy: Policy,
187}
188
189impl<'a> RedactedJson<'a> {
190 pub fn new<P: JsonRedaction>(json: &'a [u8]) -> Self {
192 Self {
193 json,
194 policy: Policy {
195 field_names: P::FIELD_NAMES,
196 data_keyed_maps: P::DATA_KEYED_MAPS,
197 sizes: P::SIZES,
198 revealed_fields: P::REVEALED_FIELDS,
199 },
200 }
201 }
202
203 pub(crate) fn describe(&self, error: &serde_json::Error) -> String {
205 self.policy.describe(error)
206 }
207}
208
209impl Display for RedactedJson<'_> {
210 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
211 f.write_str(&Outliner::new(self.policy).outline(self.json))
212 }
213}
214
215impl Debug for RedactedJson<'_> {
217 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
218 Display::fmt(self, f)
219 }
220}
221
222#[derive(Clone, Copy)]
224struct Policy {
225 field_names: bool,
226 data_keyed_maps: FieldPaths,
227 sizes: bool,
228 revealed_fields: FieldPaths,
229}
230
231impl Policy {
232 fn describe(&self, error: &serde_json::Error) -> String {
235 let position = format!(" at line {} column {}", error.line(), error.column());
236 let message = error.to_string();
237 let mut description = Self::fixed_message(error.classify(), &message, &position);
238 if self.sizes && error.line() > 0 {
239 description.push_str(&position);
240 }
241 description
242 }
243
244 fn fixed_message(category: Category, message: &str, position: &str) -> String {
249 match category {
250 Category::Syntax | Category::Eof => message
251 .strip_suffix(position)
252 .map_or_else(|| json_error_category(category), ToString::to_string),
253 category => json_error_category(category),
254 }
255 }
256}
257
258const MAX_OUTLINE_LEN: usize = 4096;
260const OUTLINE_END_RESERVE: usize = 256;
262const MAX_ITEMS_SHOWN: usize = 8;
264const MAX_REVEALED_LEN: usize = 64;
266
267struct FieldTree(Vec<FieldNode>);
269
270#[derive(Default)]
271struct FieldNode {
272 children: Vec<(Step<'static>, usize)>,
273 revealed: bool,
274 toward_revealed: bool,
275 data_keyed_map: bool,
276}
277
278#[derive(Clone, Copy, PartialEq)]
279enum Step<'a> {
280 Field(&'a str),
281 Items,
282}
283
284#[derive(Clone, Copy)]
286enum Position {
287 Revealed,
289 Node(usize),
290 Outside,
292}
293
294impl FieldTree {
295 fn new(policy: Policy) -> Self {
296 let mut tree = Self(vec![FieldNode::default()]);
297 for (paths, revealed) in [
298 (policy.revealed_fields, true),
299 (policy.data_keyed_maps, false),
300 ] {
301 for path in paths.0 {
302 let mut node = 0;
303 for step in path.split('.').flat_map(|segment| {
304 let (name, items) =
305 segment.split_at(segment.find('[').unwrap_or(segment.len()));
306 (!name.is_empty())
307 .then_some(Step::Field(name))
308 .into_iter()
309 .chain(std::iter::repeat_n(Step::Items, items.len() / 2))
310 }) {
311 node = tree.0[node].child(step).unwrap_or_else(|| {
312 let child = tree.0.len();
313 tree.0[node].children.push((step, child));
314 tree.0.push(FieldNode::default());
315 child
316 });
317 tree.0[node].toward_revealed |= revealed;
318 }
319 tree.0[node].revealed |= revealed;
320 tree.0[node].data_keyed_map |= !revealed;
321 }
322 }
323 tree
324 }
325
326 fn step(&self, parent: Position, step: Step<'_>) -> Position {
328 let Position::Node(node) = parent else {
329 return parent;
330 };
331 match self.0[node].child(step) {
332 Some(child) if self.0[child].revealed => Position::Revealed,
333 Some(child) => Position::Node(child),
334 None => Position::Outside,
335 }
336 }
337
338 fn entry(&self, object: Position, key: &str) -> Position {
341 let step = match object {
342 Position::Node(node) if self.0[node].data_keyed_map => Step::Items,
343 _ => Step::Field(key),
344 };
345 self.step(object, step)
346 }
347
348 fn shows_key(&self, object: Position, value: Position, field_names: bool) -> bool {
351 match (object, value) {
352 (Position::Revealed, _) => true,
353 (Position::Node(node), _) if self.0[node].data_keyed_map => false,
354 (_, Position::Revealed) => true,
355 (_, Position::Node(node)) if self.0[node].toward_revealed => true,
356 _ => field_names,
357 }
358 }
359}
360
361impl FieldNode {
362 fn child(&self, step: Step<'_>) -> Option<usize> {
363 self.children
364 .iter()
365 .find(|(child, _)| *child == step)
366 .map(|&(_, node)| node)
367 }
368}
369
370#[derive(Clone, Copy, PartialEq, Eq, Hash)]
374struct Shape(u64);
375
376impl Shape {
377 fn of(printed: impl Hash) -> Self {
378 let mut hasher = DefaultHasher::new();
379 printed.hash(&mut hasher);
380 Self(hasher.finish())
381 }
382}
383
384struct Outliner {
386 policy: Policy,
387 tree: FieldTree,
388 text: OutlineText,
389}
390
391impl Outliner {
392 fn new(policy: Policy) -> Self {
393 Self {
394 policy,
395 tree: FieldTree::new(policy),
396 text: OutlineText::new(),
397 }
398 }
399
400 fn outline(mut self, json: &[u8]) -> String {
401 if self.policy.sizes {
402 self.text.push(&format!(
403 "{} {}",
404 json.len(),
405 plural(json.len(), "byte", "bytes")
406 ));
407 }
408 let mark = self.text.mark();
409 let first = json.trim_ascii_start().first().copied();
410 let read = matches!(
411 first,
412 Some(b'{' | b'[' | b'"' | b'-' | b'0'..=b'9' | b't' | b'f' | b'n')
413 )
414 .then(|| {
415 self.text.separate(": ");
416 let mut deserializer = serde_json::Deserializer::from_slice(json);
417 let at = Position::Node(0);
418 ValueSeed {
419 outliner: &mut self,
420 at,
421 }
422 .deserialize(&mut deserializer)
423 .and_then(|_| deserializer.end())
424 .err()
425 });
426 let error = match read {
427 Some(error) if error.is_none() || matches!(first, Some(b'{' | b'[' | b'"')) => error,
428 _ => {
431 self.text.restore(mark);
432 self.text.separate(", ");
433 self.text.push("not JSON: ");
434 self.text.push(input_class(json));
435 None
436 }
437 };
438 self.text.end_body();
439 if let Some(error) = error {
440 self.text.push_space();
441 self.text
442 .push(&format!("<error: {}>", self.policy.describe(&error)));
443 }
444 self.text.text
445 }
446
447 fn hidden(&mut self, kind: &str, chars: Option<usize>) -> Shape {
449 match chars.filter(|_| self.policy.sizes) {
450 Some(chars) => self.text.push(&format!(
451 "<{kind}, {chars} {}>",
452 plural(chars, "char", "chars")
453 )),
454 None => self.text.push(&format!("<{kind}>")),
455 }
456 Shape::of(("hidden", kind))
457 }
458
459 fn plain(&mut self, at: Position, kind: &str, text: &str, chars: Option<usize>) -> Shape {
461 if !matches!(at, Position::Revealed) {
462 return self.hidden(kind, chars);
463 }
464 self.text.push(text);
465 Shape::of(("revealed", text))
466 }
467
468 fn quoted(&mut self, value: &str) -> Shape {
470 let mut escaped = String::new();
471 let mut cut = false;
472 for character in value.chars() {
473 let fits = escaped.len();
474 match character {
475 '"' | '\\' => {
476 escaped.push('\\');
477 escaped.push(character);
478 }
479 '\n' => escaped.push_str("\\n"),
480 '\r' => escaped.push_str("\\r"),
481 '\t' => escaped.push_str("\\t"),
482 ' '..='~' if !matches!(character, '<' | '>') => escaped.push(character),
484 other => {
485 for unit in other.encode_utf16(&mut [0; 2]) {
486 escaped.push_str(&format!("\\u{unit:04x}"));
487 }
488 }
489 }
490 if escaped.len() > MAX_REVEALED_LEN {
491 escaped.truncate(fits);
492 cut = true;
493 break;
494 }
495 }
496 self.text.push(&format!("\"{escaped}\""));
497 if cut {
498 self.hidden("cut", Some(value.chars().count()));
499 }
500 Shape::of(("revealed", escaped))
501 }
502}
503
504struct ValueSeed<'o> {
506 outliner: &'o mut Outliner,
507 at: Position,
508}
509
510impl<'de> DeserializeSeed<'de> for ValueSeed<'_> {
511 type Value = Shape;
512
513 fn deserialize<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<Shape, D::Error> {
514 deserializer.deserialize_any(self)
515 }
516}
517
518impl<'de> Visitor<'de> for ValueSeed<'_> {
519 type Value = Shape;
520
521 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
522 formatter.write_str("a JSON value")
523 }
524
525 fn visit_bool<E>(self, value: bool) -> Result<Shape, E> {
526 let text = if value { "true" } else { "false" };
527 Ok(self.outliner.plain(self.at, "bool", text, None))
528 }
529
530 fn visit_i64<E>(self, value: i64) -> Result<Shape, E> {
531 let text = value.to_string();
532 Ok(self
533 .outliner
534 .plain(self.at, "number", &text, Some(text.len())))
535 }
536
537 fn visit_u64<E>(self, value: u64) -> Result<Shape, E> {
538 let text = value.to_string();
539 Ok(self
540 .outliner
541 .plain(self.at, "number", &text, Some(text.len())))
542 }
543
544 fn visit_f64<E>(self, value: f64) -> Result<Shape, E> {
545 let text = serde_json::Number::from_f64(value)
546 .map_or_else(|| value.to_string(), |number| number.to_string());
547 Ok(self
548 .outliner
549 .plain(self.at, "number", &text, Some(text.len())))
550 }
551
552 fn visit_str<E>(self, value: &str) -> Result<Shape, E> {
553 Ok(match self.at {
554 Position::Revealed => self.outliner.quoted(value),
555 _ => self.outliner.hidden("string", Some(value.chars().count())),
556 })
557 }
558
559 fn visit_unit<E>(self) -> Result<Shape, E> {
560 self.outliner.text.push("null");
561 Ok(Shape::of("null"))
562 }
563
564 fn visit_seq<A: SeqAccess<'de>>(self, mut items: A) -> Result<Shape, A::Error> {
565 let Self { outliner, at } = self;
566 outliner.text.push("[");
567 let item_at = outliner.tree.step(at, Step::Items);
568 let mut run = ItemRun::default();
569 "[".hash(&mut run.shape);
570 loop {
571 run.begin(&mut outliner.text);
572 let item = ValueSeed {
573 outliner: &mut *outliner,
574 at: item_at,
575 };
576 let Some(shape) = items.next_element_seed(item)? else {
577 outliner.text.restore(run.mark);
578 break;
579 };
580 run.end(shape, &mut outliner.text);
581 }
582 run.push_counts(&mut outliner.text);
583 outliner.text.push("]");
584 Ok(Shape(run.shape.finish()))
585 }
586
587 fn visit_map<A: MapAccess<'de>>(self, mut entries: A) -> Result<Shape, A::Error> {
588 let Self { outliner, at } = self;
589 outliner.text.push("{");
590 let mut shape = DefaultHasher::new();
591 "{".hash(&mut shape);
592 let mut first = true;
593 loop {
594 let mark = outliner.text.mark();
595 if !first {
596 outliner.text.push(", ");
597 }
598 let Some(key) = entries.next_key::<String>()? else {
599 outliner.text.restore(mark);
600 break;
601 };
602 first = false;
603 let value_at = outliner.tree.entry(at, &key);
604 if outliner
605 .tree
606 .shows_key(at, value_at, outliner.policy.field_names)
607 {
608 outliner.quoted(&key)
609 } else {
610 outliner.hidden("key", Some(key.chars().count()))
611 }
612 .hash(&mut shape);
613 outliner.text.push(": ");
614 let value = ValueSeed {
615 outliner: &mut *outliner,
616 at: value_at,
617 };
618 entries.next_value_seed(value)?.hash(&mut shape);
619 }
620 outliner.text.push("}");
621 Ok(Shape(shape.finish()))
622 }
623}
624
625#[derive(Default)]
629struct ItemRun {
630 read: usize,
631 shown: usize,
632 same: usize,
634 more: usize,
636 previous: Option<Shape>,
637 mark: Mark,
639 shape: DefaultHasher,
640}
641
642impl ItemRun {
643 fn begin(&mut self, text: &mut OutlineText) {
644 self.mark = text.mark();
645 self.push_counts(text);
646 if self.read > 0 {
647 text.push(", ");
648 }
649 }
650
651 fn end(&mut self, shape: Shape, text: &mut OutlineText) {
652 let same = self.previous == Some(shape);
653 if (same && self.more == 0) || self.shown >= MAX_ITEMS_SHOWN {
654 text.restore(self.mark);
655 if same && self.more == 0 {
656 self.same += 1;
657 } else {
658 self.more += 1;
659 }
660 } else {
661 self.same = 0;
662 self.shown += 1;
663 }
664 if !same {
665 shape.hash(&mut self.shape);
666 }
667 self.previous = Some(shape);
668 self.read += 1;
669 }
670
671 fn push_counts(&self, text: &mut OutlineText) {
673 if self.same > 0 {
674 text.push(&format!(", <{} more of the same shape>", self.same));
675 }
676 if self.more > 0 {
677 text.push(&format!(
678 ", <{} more {}>",
679 self.more,
680 plural(self.more, "item", "items")
681 ));
682 }
683 }
684}
685
686struct OutlineText {
690 text: String,
691 budget: usize,
692 cut: bool,
693}
694
695#[derive(Clone, Copy, Default)]
697struct Mark {
698 len: usize,
699 cut: bool,
700}
701
702impl OutlineText {
703 fn new() -> Self {
704 Self {
705 text: String::new(),
706 budget: MAX_OUTLINE_LEN - OUTLINE_END_RESERVE,
707 cut: false,
708 }
709 }
710
711 fn push(&mut self, part: &str) {
712 if self.cut {
713 return;
714 }
715 let room = self.budget.saturating_sub(self.text.len());
716 self.text
718 .push_str(part.get(..room.min(part.len())).unwrap_or_default());
719 self.cut = part.len() > room;
720 }
721
722 fn separate(&mut self, separator: &str) {
724 if !self.text.is_empty() {
725 self.push(separator);
726 }
727 }
728
729 fn push_space(&mut self) {
731 if !self.text.ends_with(' ') {
732 self.separate(" ");
733 }
734 }
735
736 fn mark(&self) -> Mark {
737 Mark {
738 len: self.text.len(),
739 cut: self.cut,
740 }
741 }
742
743 fn restore(&mut self, mark: Mark) {
744 self.text.truncate(mark.len);
745 self.cut = mark.cut;
746 }
747
748 fn end_body(&mut self) {
751 self.budget = MAX_OUTLINE_LEN;
752 if std::mem::take(&mut self.cut) {
753 self.push_space();
754 self.push("<outline cut>");
755 }
756 }
757}
758
759fn input_class(bytes: &[u8]) -> &'static str {
761 let content = bytes.trim_ascii();
762 if bytes.is_empty() {
763 "empty"
764 } else if content.is_empty() {
765 "whitespace only"
766 } else if content.iter().all(u8::is_ascii_hexdigit) {
767 "hex digits"
768 } else if content.iter().all(|byte| {
769 byte.is_ascii_alphanumeric()
771 || matches!(byte, b'+' | b'/' | b'-' | b'_' | b'=' | b'\r' | b'\n')
772 }) {
773 "base64-like text"
774 } else if std::str::from_utf8(bytes).is_ok_and(|text| {
775 text.chars()
776 .all(|character| !character.is_control() || character.is_ascii_whitespace())
777 }) {
778 "text"
779 } else {
780 "binary data"
781 }
782}
783
784fn plural(count: usize, one: &'static str, many: &'static str) -> &'static str {
785 if count == 1 { one } else { many }
786}
787
788#[cfg(test)]
789mod tests {
790 use proptest::prelude::*;
791 use serde_json::{Map, Value};
792
793 use super::*;
794
795 const INVOICE: &str = r#"{"number":"INV-1042","customer":"Northwind Traders","currency":"EUR","lines":[{"description":"Standing desk","quantity":2},{"description":"Cable tray","quantity":4}],"paid":true,"total_cents":117600}"#;
797
798 struct InvoiceLog;
799
800 impl JsonRedaction for InvoiceLog {
801 const REVEALED_FIELDS: FieldPaths =
802 FieldPaths::from_static(&["number", "currency", "lines[].quantity"]);
803 }
804
805 struct InvoiceSizes;
806
807 impl JsonRedaction for InvoiceSizes {
808 const SIZES: bool = true;
809 }
810
811 const SECRET_LETTERS: &str = "ABCDGHIKLMPQRVWXYZ";
814
815 fn outline<P: JsonRedaction>(json: &[u8]) -> String {
816 RedactedJson::new::<P>(json).to_string()
817 }
818
819 fn cut_invoice() -> &'static [u8] {
821 &INVOICE.as_bytes()[..INVOICE.rfind("quantity").expect("a second line") + 3]
822 }
823
824 #[test]
825 fn the_default_policy_shows_the_shape_only() {
826 assert_eq!(
827 outline::<ShapeOnly>(INVOICE.as_bytes()),
828 "{<key>: <string>, <key>: <string>, <key>: <string>, <key>: [{<key>: <string>, <key>: <number>}, <1 more of the same shape>], <key>: <bool>, <key>: <number>}"
829 );
830 assert_eq!(
831 outline::<ShapeOnly>(cut_invoice()),
832 "{<key>: <string>, <key>: <string>, <key>: <string>, <key>: [{<key>: <string>, <key>: <number>}, {<key>: <string>, <error: EOF while parsing a string>"
833 );
834 }
835
836 #[test]
837 fn a_revealed_path_shows_its_values_and_the_names_on_the_way() {
838 assert_eq!(
839 outline::<InvoiceLog>(INVOICE.as_bytes()),
840 r#"{"number": "INV-1042", <key>: <string>, "currency": "EUR", "lines": [{<key>: <string>, "quantity": 2}, {<key>: <string>, "quantity": 4}], <key>: <bool>, <key>: <number>}"#
841 );
842 }
843
844 #[test]
845 fn field_names_show_except_the_keys_of_data_keyed_maps() {
846 struct AccountLog;
847
848 impl JsonRedaction for AccountLog {
849 const FIELD_NAMES: bool = true;
850 const DATA_KEYED_MAPS: FieldPaths = FieldPaths::from_static(&["balances"]);
851 }
852
853 let account = br#"{"owner":"ann@example.com","balances":{"ann@example.com":10,"bob@example.com":-2}}"#;
854
855 assert_eq!(
856 outline::<AccountLog>(account),
857 r#"{"owner": <string>, "balances": {<key>: <number>, <key>: <number>}}"#
858 );
859 }
860
861 #[test]
862 fn the_values_of_a_data_keyed_map_are_named_by_items() {
863 struct NestedLog;
864
865 impl JsonRedaction for NestedLog {
866 const FIELD_NAMES: bool = true;
867 const DATA_KEYED_MAPS: FieldPaths =
868 FieldPaths::from_static(&["balances", "balances[]"]);
869 }
870
871 struct TotalLog;
872
873 impl JsonRedaction for TotalLog {
874 const FIELD_NAMES: bool = true;
875 const DATA_KEYED_MAPS: FieldPaths = FieldPaths::from_static(&["balances"]);
876 const REVEALED_FIELDS: FieldPaths = FieldPaths::from_static(&["balances[].total"]);
877 }
878
879 assert_eq!(
880 outline::<NestedLog>(br#"{"balances":{"ann@x.com":{"bob@y.com":1}}}"#),
881 r#"{"balances": {<key>: {<key>: <number>}}}"#
882 );
883 assert_eq!(
884 outline::<TotalLog>(br#"{"balances":{"ann@x.com":{"total":5,"note":"n"}}}"#),
885 r#"{"balances": {<key>: {"total": 5, "note": <string>}}}"#
886 );
887 }
888
889 #[test]
890 fn a_syntax_message_without_the_position_suffix_gives_the_category() {
891 let position = " at line 1 column 7";
892
893 assert_eq!(
894 Policy::fixed_message(
895 Category::Eof,
896 "EOF while parsing a list at line 1 column 7",
897 position
898 ),
899 "EOF while parsing a list"
900 );
901 assert_eq!(
902 Policy::fixed_message(Category::Syntax, "invalid number: 4111-1111-1111", position),
903 "Syntax error"
904 );
905 }
906
907 #[test]
908 fn sizes_show_lengths_the_byte_count_and_the_error_position() {
909 let cut = cut_invoice();
910
911 assert_eq!(
912 outline::<InvoiceSizes>(cut),
913 format!(
914 "{} bytes: {{<key, 6 chars>: <string, 8 chars>, <key, 8 chars>: <string, 17 chars>, <key, 8 chars>: <string, 3 chars>, <key, 5 chars>: [{{<key, 11 chars>: <string, 13 chars>, <key, 8 chars>: <number, 1 char>}}, {{<key, 11 chars>: <string, 10 chars>, <error: EOF while parsing a string at line 1 column {}>",
915 cut.len(),
916 cut.len()
917 )
918 );
919 }
920
921 #[test]
922 fn a_revealed_value_is_escaped_into_one_capped_line() {
923 struct NoteLog;
924
925 impl JsonRedaction for NoteLog {
926 const REVEALED_FIELDS: FieldPaths = FieldPaths::from_static(&["note", "long"]);
927 }
928
929 let json = format!(
930 "{{\"note\":\"one\\ntwo \\\"quoted\\\" <b> caf\u{e9} \u{2028} \u{1f600}\",\"long\":\"{}\"}}",
931 "x".repeat(1000)
932 );
933
934 assert_eq!(
935 outline::<NoteLog>(json.as_bytes()),
936 format!(
937 r#"{{"note": "one\ntwo \"quoted\" \u003cb\u003e caf\u00e9 \u2028 \ud83d\ude00", "long": "{}"<cut>}}"#,
938 "x".repeat(MAX_REVEALED_LEN)
939 )
940 );
941 }
942
943 #[test]
944 fn items_of_the_same_shape_are_counted() {
945 struct LinesLog;
946
947 impl JsonRedaction for LinesLog {
948 const REVEALED_FIELDS: FieldPaths = FieldPaths::from_static(&["[].quantity"]);
949 }
950
951 let line = r#"{"description":"Standing desk","quantity":2}"#;
952 let lines = format!("[{}]", vec![line; 100_000].join(","));
953
954 assert_eq!(
955 outline::<LinesLog>(lines.as_bytes()),
956 r#"[{<key>: <string>, "quantity": 2}, <99999 more of the same shape>]"#
957 );
958 }
959
960 #[test]
961 fn an_array_shows_a_few_items_of_different_shapes() {
962 struct ItemsLog;
963
964 impl JsonRedaction for ItemsLog {
965 const REVEALED_FIELDS: FieldPaths = FieldPaths::from_static(&["[]"]);
966 }
967
968 let quantities =
969 serde_json::to_string(&(0..1000).collect::<Vec<u32>>()).expect("numbers serialise");
970
971 assert_eq!(
972 outline::<ItemsLog>(quantities.as_bytes()),
973 "[0, 1, 2, 3, 4, 5, 6, 7, <992 more items>]"
974 );
975 }
976
977 #[test]
978 fn bytes_that_are_not_json_print_as_their_class() {
979 const CARD: &str = "4111 1111 1111 1111";
980 let base64 = secret_vault_value::SecretValue::from(CARD)
981 .as_sensitive_base64_str()
982 .to_string();
983
984 for (input, class) in [
985 (base64.as_bytes(), "base64-like text"),
986 (b"cafe4111".as_slice(), "hex digits"),
987 (CARD.as_bytes(), "text"),
988 (b"\x1f\x8b\x08\x00card".as_slice(), "binary data"),
989 (b" \n".as_slice(), "whitespace only"),
990 (b"".as_slice(), "empty"),
991 ] {
992 assert_eq!(outline::<ShapeOnly>(input), format!("not JSON: {class}"));
993 }
994 }
995
996 #[test]
997 fn a_long_outline_is_cut_and_still_ends_with_the_error() {
998 let entries: Vec<String> = (0..10_000)
999 .map(|index| format!("\"field{index}\":{index}"))
1000 .collect();
1001 let json = format!("{{{}", entries.join(","));
1002
1003 let outline = outline::<ShapeOnly>(json.as_bytes());
1004
1005 assert!(outline.len() <= MAX_OUTLINE_LEN, "{}", outline.len());
1006 assert!(
1007 outline.ends_with(" <outline cut> <error: EOF while parsing an object>"),
1008 "{outline}"
1009 );
1010 }
1011
1012 #[test]
1013 fn nesting_past_serde_jsons_limit_ends_the_outline() {
1014 let open = "[".repeat(1_000_000);
1015
1016 let outline = outline::<ShapeOnly>(open.as_bytes());
1017
1018 assert_eq!(
1019 outline,
1020 format!("{} <error: recursion limit exceeded>", "[".repeat(127))
1021 );
1022 }
1023
1024 #[test]
1025 fn a_field_path_is_field_names_and_items() {
1026 for valid in ["number", "lines[].quantity", "[]", "[].id", "matrix[][]"] {
1027 assert!(FieldPaths::is_field_path(valid.as_bytes()), "{valid}");
1028 }
1029 for invalid in ["", "a..b", "a[", "a]", "a[]b"] {
1031 assert!(!FieldPaths::is_field_path(invalid.as_bytes()), "{invalid}");
1032 }
1033 }
1034
1035 fn document_and_paths() -> impl Strategy<Value = (Value, Vec<String>)> {
1037 let secret = proptest::string::string_regex(&format!("[{SECRET_LETTERS}]{{16}}"))
1038 .expect("a regular expression");
1039 let key = proptest::string::string_regex(&format!("[{SECRET_LETTERS}]{{12}}"))
1040 .expect("a regular expression")
1041 .boxed();
1042 let leaf = prop_oneof![
1043 secret.prop_map(Value::String),
1044 (1_000_000_000_000_u64..10_000_000_000_000).prop_map(Value::from),
1045 any::<bool>().prop_map(Value::Bool),
1046 Just(Value::Null),
1047 ];
1048 let document = leaf.prop_recursive(4, 32, 4, move |inner| {
1049 prop_oneof![
1050 proptest::collection::vec(inner.clone(), 0..4).prop_map(Value::Array),
1051 proptest::collection::vec((key.clone(), inner), 0..4)
1052 .prop_map(|entries| Value::Object(entries.into_iter().collect::<Map<_, _>>())),
1053 ]
1054 });
1055 document.prop_flat_map(|document| {
1056 let mut paths = Vec::new();
1057 collect_paths(&document, "", &mut paths);
1058 paths.sort();
1059 paths.dedup();
1060 let count = paths.len();
1061 (
1062 Just(document),
1063 proptest::sample::subsequence(paths, 0..=count.min(4)),
1064 )
1065 })
1066 }
1067
1068 fn collect_paths(value: &Value, prefix: &str, paths: &mut Vec<String>) {
1070 let children: Vec<(String, &Value)> = match value {
1071 Value::Object(entries) => entries
1072 .iter()
1073 .map(|(key, child)| match prefix {
1074 "" => (key.clone(), child),
1075 prefix => (format!("{prefix}.{key}"), child),
1076 })
1077 .collect(),
1078 Value::Array(items) => items
1079 .iter()
1080 .map(|child| (format!("{prefix}[]"), child))
1081 .collect(),
1082 _ => Vec::new(),
1083 };
1084 for (path, child) in children {
1085 collect_paths(child, &path, paths);
1086 paths.push(path);
1087 }
1088 }
1089
1090 fn secrets(value: &Value, paths: &[&str], shown: &mut Vec<String>, hidden: &mut Vec<String>) {
1094 let revealed = paths.contains(&"");
1095 let below = |step: &str| -> Vec<&str> {
1096 if revealed {
1097 return vec![""];
1098 }
1099 paths
1100 .iter()
1101 .filter_map(|path| {
1102 let rest = path.strip_prefix(step)?;
1103 match rest.strip_prefix('.') {
1104 Some(rest) => Some(rest),
1105 None => (rest.is_empty() || rest.starts_with('[')).then_some(rest),
1106 }
1107 })
1108 .collect()
1109 };
1110 let secret = match value {
1111 Value::String(secret) => secret.clone(),
1112 Value::Number(secret) => secret.to_string(),
1113 Value::Object(entries) => {
1114 for (key, child) in entries {
1115 let below = below(key);
1116 if below.is_empty() {
1117 hidden.push(key.clone());
1118 } else {
1119 shown.push(key.clone());
1120 }
1121 secrets(child, &below, shown, hidden);
1122 }
1123 return;
1124 }
1125 Value::Array(items) => {
1126 let below = below("[]");
1127 for child in items {
1128 secrets(child, &below, shown, hidden);
1129 }
1130 return;
1131 }
1132 Value::Bool(_) | Value::Null => return,
1133 };
1134 if revealed {
1135 shown.push(secret);
1136 } else {
1137 hidden.push(secret);
1138 }
1139 }
1140
1141 fn digits_are_counts_only(outline: &str) -> bool {
1144 let is_digit = |character: char| character.is_ascii_digit();
1145 let outline = outline.replace("base64-like", "");
1146 outline.match_indices(is_digit).all(|(at, _)| {
1147 outline[..at].trim_end_matches(is_digit).ends_with('<')
1148 && outline[at..]
1149 .trim_start_matches(is_digit)
1150 .starts_with(" more")
1151 })
1152 }
1153
1154 proptest! {
1155 #[test]
1156 fn an_outline_shows_nothing_its_policy_does_not_opt_into(
1157 (document, paths) in document_and_paths(),
1158 cut in any::<prop::sample::Index>(),
1159 ) {
1160 let json = serde_json::to_string(&document)?;
1161 let cut_json = &json.as_bytes()[..cut.index(json.len() + 1)];
1162 let leaked: &'static [&'static str] =
1163 Vec::leak(paths.iter().map(|path| &*String::leak(path.clone())).collect());
1164 let sizes_and_paths = |json: &[u8]| RedactedJson {
1165 json,
1166 policy: Policy {
1167 field_names: false,
1168 data_keyed_maps: FieldPaths::NONE,
1169 sizes: true,
1170 revealed_fields: FieldPaths::from_static(leaked),
1171 },
1172 }
1173 .to_string();
1174 let mut shown = Vec::new();
1175 let mut hidden = Vec::new();
1176 secrets(&document, &paths.iter().map(String::as_str).collect::<Vec<_>>(), &mut shown, &mut hidden);
1177
1178 for shape_only in [outline::<ShapeOnly>(json.as_bytes()), outline::<ShapeOnly>(cut_json)] {
1179 prop_assert!(digits_are_counts_only(&shape_only), "{}", shape_only);
1180 prop_assert!(!shape_only.contains(|character| SECRET_LETTERS.contains(character)), "{}", shape_only);
1181 }
1182 let whole = sizes_and_paths(json.as_bytes());
1183 let cut = sizes_and_paths(cut_json);
1184 for secret in &shown {
1185 prop_assert!(whole.contains(secret.as_str()), "{} not in {}", secret, whole);
1186 }
1187 for secret in &hidden {
1188 for window in secret.as_bytes().windows(10) {
1189 let window = std::str::from_utf8(window)?;
1190 prop_assert!(!whole.contains(window), "{} of {} in {}", window, secret, whole);
1191 prop_assert!(!cut.contains(window), "{} of {} in {}", window, secret, cut);
1192 }
1193 }
1194 }
1195
1196 #[test]
1197 fn any_bytes_outline_as_one_bounded_line_of_printable_ascii(
1198 input in prop_oneof![
1199 proptest::collection::vec(any::<u8>(), 0..512),
1200 "[{}\\[\\],:\"0-9a-z \\\\.eE+\\-\u{e9}\n]{0,256}".prop_map(String::into_bytes),
1201 ],
1202 ) {
1203 for outline in [outline::<ShapeOnly>(&input), outline::<InvoiceLog>(&input), outline::<InvoiceSizes>(&input)] {
1204 prop_assert!(outline.len() <= MAX_OUTLINE_LEN, "{}", outline.len());
1205 prop_assert!(outline.bytes().all(|byte| matches!(byte, 0x20..=0x7E)), "{}", outline);
1206 }
1207 }
1208 }
1209}