Skip to main content

kms_aead/
redaction.rs

1//! What the `WARN` event of a [`JsonEncoded`](crate::JsonEncoded) value that does not decode shows
2//! of its JSON: a [`RedactedJson`] outline under the type's [`JsonRedaction`] policy, which an
3//! application can also log for JSON of its own.
4
5use 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
13/// What the outline of JSON that does not decode shows besides its shape: the policy `P` of a
14/// [`JsonEncoded<T, P>`](crate::JsonEncoded), a type of the application's own whose constants opt
15/// into each disclosure. [`ShapeOnly`], the default, opts into none.
16///
17/// A plaintext is encrypted because it is secret, so its outline stays [`ShapeOnly`] or reveals
18/// codes and identifiers only. A signed payload is often not secret, and its outline may show more.
19///
20/// Under every policy the outline ends with serde_json's message for a syntax error, such as
21/// `EOF while parsing a string`. It is fixed text that never quotes the input, and it can state a
22/// property of a value the outline hides: `number out of range`, `control character
23/// (\u0000-\u001F) found while parsing a string`, `invalid unicode code point` or `unexpected end
24/// of hex escape`. Any other error shows its category only, such as `Data error`.
25///
26/// ```rust
27/// use kms_aead::redaction::{FieldPaths, JsonRedaction};
28/// use kms_aead::JsonEncoded;
29/// use serde::{Deserialize, Serialize};
30///
31/// #[derive(Serialize, Deserialize)]
32/// struct Invoice {
33///     number: String,
34///     customer: String,
35/// }
36///
37/// struct InvoiceLog;
38///
39/// impl JsonRedaction for InvoiceLog {
40///     const SIZES: bool = true;
41///     const REVEALED_FIELDS: FieldPaths = FieldPaths::from_static(&["number"]);
42/// }
43///
44/// type InvoiceJson = JsonEncoded<Invoice, InvoiceLog>;
45///
46/// let invoice = InvoiceJson::from(Invoice {
47///     number: "INV-1042".to_string(),
48///     customer: "Northwind Traders".to_string(),
49/// });
50/// ```
51pub trait JsonRedaction {
52    /// Whether the outline shows field names, the keys of objects, except the keys of
53    /// [`DATA_KEYED_MAPS`](Self::DATA_KEYED_MAPS).
54    const FIELD_NAMES: bool = false;
55
56    /// The objects whose keys are data rather than field names, such as a map from a customer's
57    /// email to a balance: their keys stay hidden under [`FIELD_NAMES`](Self::FIELD_NAMES). A `[]`
58    /// after the path of such an object names its values, whatever their keys: `balances[].total`
59    /// can be revealed, and `balances[]` listed here when the values are maps keyed by data too.
60    const DATA_KEYED_MAPS: FieldPaths = FieldPaths::NONE;
61
62    /// Whether the outline shows sizes: the length of every value and key it hides, the length of
63    /// the JSON in bytes, and the line and column where serde_json stopped reading it. A length
64    /// gives away a hidden boolean, `true` against `false`, and narrows a short value down.
65    const SIZES: bool = false;
66
67    /// The fields whose values the outline shows, and with them the names of the fields on the
68    /// way to each.
69    const REVEALED_FIELDS: FieldPaths = FieldPaths::NONE;
70}
71
72/// The default [`JsonRedaction`]: the outline shows the shape of the JSON only, and serde_json's
73/// message for a syntax error, which can state a property of a hidden value, see
74/// [`JsonRedaction`].
75pub struct ShapeOnly;
76
77impl JsonRedaction for ShapeOnly {}
78
79/// Fields of a JSON document, as paths: field names joined by `.`, and `[]` after a field for
80/// every item of the array it holds, or every value of the data-keyed map it holds, such as
81/// `number`, `lines[].quantity`, or `[].id` for the items of an array at the top level. A path
82/// takes in the whole value at its end. A field whose name holds `.`, `[` or `]` cannot be named.
83#[derive(Debug, Clone, Copy)]
84pub struct FieldPaths(&'static [&'static str]);
85
86impl FieldPaths {
87    /// No field.
88    pub const NONE: Self = Self(&[]);
89
90    /// The fields at `paths`.
91    ///
92    /// # Panics
93    ///
94    /// When a path is empty, has an empty field name, a `[` not followed by `]`, a `]` alone, or a
95    /// field name right after `[]`. In a `const` item that is a compile error of every build. In a
96    /// [`JsonRedaction`] constant it is a compile error of the build that decodes with the policy,
97    /// which `cargo check` does not report.
98    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    /// Whether `path` is field names joined by `.`, each followed by any number of `[]`, the first
112    /// of which may be `[]` alone.
113    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
142/// An outline of JSON bytes that may be broken, for a log line: its shape, and what its
143/// [`JsonRedaction`] policy opts into. `Display` writes the outline, and so does `Debug`, never the
144/// bytes.
145///
146/// The outline is one line of printable ASCII, 4 KiB at most:
147///
148/// - a value prints as its type, `<string>`, `<number>` or `<bool>`, a key as `<key>`, and `null`
149///   as itself. With [`SIZES`](JsonRedaction::SIZES), a string, number or key prints its length
150///   too, such as `<string, 17 chars>`, and the outline starts with the length of the JSON;
151/// - a key prints itself under [`FIELD_NAMES`](JsonRedaction::FIELD_NAMES), and on the way to a
152///   revealed field;
153/// - a revealed value prints itself, a string escaped and cut after 64 bytes: `"`, `\`, `<`, `>`
154///   and every character outside printable ASCII as a JSON escape;
155/// - the items of an array with the shape of the item before them print as a count, such as
156///   `<2 more of the same shape>`, and an array prints 8 items of different shapes at most;
157/// - where serde_json stops reading the JSON, the outline ends with its error, such as
158///   `<error: EOF while parsing a string>`, with the line and column under `SIZES`. serde_json
159///   reads 128 levels of nesting at most;
160/// - bytes that do not start as JSON print as their class only, such as `base64-like text`.
161///
162/// The outline is built when it is formatted, in time linear in the input, and never panics.
163/// With serde_json's `arbitrary_precision` feature on, a number prints as an object of one
164/// string.
165///
166/// ```rust
167/// use kms_aead::redaction::{FieldPaths, JsonRedaction, RedactedJson};
168///
169/// struct OrderLog;
170///
171/// impl JsonRedaction for OrderLog {
172///     const REVEALED_FIELDS: FieldPaths = FieldPaths::from_static(&["id", "lines[].sku"]);
173/// }
174///
175/// let body = br#"{"id":"A-17","email":"ann@example.com","lines":[{"sku":"desk","price":"#;
176/// let outline = RedactedJson::new::<OrderLog>(body);
177///
178/// tracing::warn!(%outline, "An order that does not parse");
179/// assert_eq!(
180///     outline.to_string(),
181///     r#"{"id": "A-17", <key>: <string>, "lines": [{"sku": "desk", <key>: <error: EOF while parsing a value>"#
182/// );
183/// ```
184pub struct RedactedJson<'a> {
185    json: &'a [u8],
186    policy: Policy,
187}
188
189impl<'a> RedactedJson<'a> {
190    /// The outline of `json` under the policy `P`.
191    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    /// serde_json's `error` as far as the policy shows it, for the event beside the outline.
204    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
215/// The outline, as `Display` writes it.
216impl Debug for RedactedJson<'_> {
217    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
218        Display::fmt(self, f)
219    }
220}
221
222/// The constants of a [`JsonRedaction`].
223#[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    /// serde_json's `error` as far as the policy shows it: the message of a syntax error, which is
233    /// fixed text, or the category of any other, and the position under `SIZES`.
234    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    /// The `message` of an error of `category` without its `position`, when serde_json writes the
245    /// message from fixed text that never quotes the input, as it does for a syntax error. The
246    /// message of a data error may quote the input, so any other category, and a message that does
247    /// not end with `position`, give the category alone.
248    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
258/// The longest outline, in bytes.
259const MAX_OUTLINE_LEN: usize = 4096;
260/// The bytes of [`MAX_OUTLINE_LEN`] kept for the annotations at the end of an outline.
261const OUTLINE_END_RESERVE: usize = 256;
262/// The items of different shapes an array shows.
263const MAX_ITEMS_SHOWN: usize = 8;
264/// The longest revealed string, escaped, in bytes.
265const MAX_REVEALED_LEN: usize = 64;
266
267/// The fields the policy names, as a tree of their steps that an outline walks beside the JSON.
268struct 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/// Where a value is in the [`FieldTree`].
285#[derive(Clone, Copy)]
286enum Position {
287    /// At or below a revealed field.
288    Revealed,
289    Node(usize),
290    /// Below no field the policy names.
291    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    /// The position of the value one `step` below a value at `parent`.
327    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    /// The position of the value under `key` in an object at `object`. The values of a data-keyed
339    /// map are one `[]` step below it, whatever their keys.
340    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    /// Whether the key of a value at `value`, in an object at `object`, prints itself. The keys of a
349    /// data-keyed map do not, whatever its values reveal.
350    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/// What an outline prints of a value without its lengths and counts, hashed, so that the items of
371/// an array compare in constant memory. A collision counts an item as one more of the shape before
372/// it, which hides the item and reveals nothing.
373#[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
384/// The outline of one input as serde_json reads it.
385struct 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            // Bytes that do not start as JSON, or a number or a word at the top level that is not
429            // all of the input, which is more likely text, hex or base64 than broken JSON.
430            _ => {
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    /// Writes a value the outline hides, of `kind`, and its length in `chars` under `SIZES`.
448    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    /// Writes `text`, a boolean or a number as serde_json writes it, where `at` is revealed.
460    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    /// Writes `value` quoted and escaped, cut after [`MAX_REVEALED_LEN`] bytes.
469    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                // `<` and `>` are escaped so that a value cannot pass for an annotation.
483                ' '..='~' 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
504/// A value at a position, and the visitor that writes it.
505struct 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/// The items of an array as they are read. Every item is written, and taken back when it has the
626/// shape of the item before it or the array already shows [`MAX_ITEMS_SHOWN`], so that an item
627/// serde_json stops in stays in the outline.
628#[derive(Default)]
629struct ItemRun {
630    read: usize,
631    shown: usize,
632    /// The items after the last one shown that have its shape.
633    same: usize,
634    /// The items past the ones shown and their run.
635    more: usize,
636    previous: Option<Shape>,
637    /// The outline before the item being read.
638    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    /// Writes the counts of the items not shown.
672    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
686/// The outline as it is written: printable ASCII within a budget, which
687/// [`end_body`](Self::end_body) raises for the annotations at the end. A write that does not fit is
688/// cut, and the writes after it are dropped until the text is restored to a mark before the cut.
689struct OutlineText {
690    text: String,
691    budget: usize,
692    cut: bool,
693}
694
695/// A length of the outline to restore it to.
696#[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        // Every part is ASCII, so a cut falls between characters.
717        self.text
718            .push_str(part.get(..room.min(part.len())).unwrap_or_default());
719        self.cut = part.len() > room;
720    }
721
722    /// Writes `separator` unless the outline is empty.
723    fn separate(&mut self, separator: &str) {
724        if !self.text.is_empty() {
725            self.push(separator);
726        }
727    }
728
729    /// Writes the space before an annotation, unless the outline is empty or ends with one.
730    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    /// Ends the body of the outline: notes where it was cut, and opens the reserve for the
749    /// annotations of the end.
750    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
759/// The class of `bytes` that do not start as JSON, which names nothing of them.
760fn 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        // The alphabets of base64 and base64url, the padding, and the line breaks of MIME.
770        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    /// An invoice whose customer, line descriptions, flag and total no test reveals.
796    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    /// Uppercase letters that no word of an outline has, so that a secret made of them is found
812    /// in an outline only where the outline shows it.
813    const SECRET_LETTERS: &str = "ABCDGHIKLMPQRVWXYZ";
814
815    fn outline<P: JsonRedaction>(json: &[u8]) -> String {
816        RedactedJson::new::<P>(json).to_string()
817    }
818
819    /// The invoice cut inside the key of the second line's quantity.
820    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        // Empty; an empty field name; `[` without `]`; `]` alone; a name right after `[]`.
1030        for invalid in ["", "a..b", "a[", "a]", "a[]b"] {
1031            assert!(!FieldPaths::is_field_path(invalid.as_bytes()), "{invalid}");
1032        }
1033    }
1034
1035    /// A JSON document whose strings, numbers and keys are secrets, and a choice of its paths.
1036    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    /// Every path below `value`, which is at `prefix`.
1069    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    /// The secrets of `value` an outline revealing `paths` shows and hides: its strings, the
1091    /// decimal text of its numbers, and its keys. `paths` are what is left of the revealed paths
1092    /// below `value`, an empty one when a path ends at it.
1093    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    /// Whether every digit of `outline` is in a count of items, such as `<3 more items>`, or in
1142    /// the name of a class of bytes.
1143    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}