bugwarden 0.6.0

MCP server for Bugzilla with operator-controlled security guards
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! The diagnostic stream's bound, applied at the SINK: every field of
//! every tracing line is cut at [`PARAM_VALUE_MAX_CHARS`] characters and
//! rewritten wherever it carries a control character or a line break
//! (#260, #266, #275). That set is the WHOLE C0 range `\x00`–`\x1f`,
//! DEL, the C1 range `\u{80}`–`\u{9f}`, and U+2028 and U+2029 — every
//! control character, and every line break Unicode makes mandatory. It
//! is wider than the set tracing-subscriber escapes in `message`.
//!
//! bugwarden caps the client strings it logs at the CALL SITE
//! (`server::Capped`), which bounds its own lines and nothing else. rmcp
//! writes to the same stderr and into the same OTLP diagnostics stream,
//! and bounds nothing: `service.rs:1342` logs the whole `initialize`
//! parameters (`?peer_info`), `:1597` every client notification whole,
//! `:1585` a JSON-RPC request id raw on every error reply (`%id`), and
//! `service/server.rs:477` the declared protocol version raw. Raise the
//! level and `service.rs:1535` adds the whole of every request at debug
//! and `:1438` the whole of every loop event at trace. A cap that lives
//! at a call site reaches none of them, and a
//! level filter that hides them is undone by the next `RUST_LOG` an
//! operator sets — so the bound goes where every line passes instead:
//! the field formatter `main` gives the stderr layer, and the visitor
//! `otel` builds the exported body with.
//!
//! Escaping is the other half (#266). tracing-subscriber 0.3's
//! `DefaultVisitor` sanitizes `message` and `record_error` only, and a
//! `%`-formatted value is a tracing-core `DisplayValue` recorded through
//! `record_debug`, whose `Debug` hands straight to its `Display` — so it
//! reaches the terminal verbatim, and a `query` of ESC `[2J` cleared the
//! operator's screen while ESC `]0;` … BEL retitled it. [`CappedWriter`]
//! escapes those bytes for every field, and #275's as well: a LINE is
//! the unit stderr readers and log shippers trust, so a field carrying
//! LF ended one line and opened another that a reader could not tell
//! from one this server wrote.
//!
//! Every client string bugwarden names a field for is `?`-formatted
//! since #278, so `server::Capped` has already escaped it by the time it
//! arrives here and this adapter only ever escapes what `Debug` leaves
//! alone. That narrows nothing. bugwarden's `error`, `path`, `location`,
//! `thread` and startup `tool` fields are still `%` and still arrive
//! raw — `error` carries Bugzilla's own message text, which is where a
//! client string can come back at one remove — and so do rmcp's `%id`,
//! its `%client_requested` and every `message` on the stream.
//!
//! Those two families are also why the ESCAPE SPELLINGS on a line
//! identify the sigil rather than the writer: `\u{1b}` is what `Debug`
//! wrote, on a field of ours or on rmcp's `?peer_info` alike, and
//! `\x1b` is what this adapter wrote, on rmcp's `%id` or on one of
//! bugwarden's own `%` fields.
//!
//! Parity with `DefaultFields` is a requirement, not a courtesy: a value
//! under the cap carrying no control bytes must render byte for byte as
//! it does today, because the operator's own greps and this workspace's
//! `binary_tracing_caps` needles read those lines. The unit tests below
//! render the same events through both and compare.

use std::fmt;
use std::fmt::Write as _;

use tracing::field::{Field, Visit};
use tracing_subscriber::field::RecordFields;
use tracing_subscriber::fmt::format::Writer;
use tracing_subscriber::fmt::FormatFields;

/// The one bound every client-chosen string in this process answers to:
/// 1024 characters.
///
/// It is the audit record's cap — on an allowlisted parameter value, on a
/// recorded object key, on the tool name and on the JSON-RPC request id,
/// where `server.rs` reads it — and, since #260, the per-field cap of
/// every diagnostic line as well. One constant because a bound the record
/// enforces and the log undoes is not a bound, and because a second
/// number would have to be remembered next to this one.
pub const PARAM_VALUE_MAX_CHARS: usize = 1024;

/// A [`fmt::Write`] that bounds and sanitizes one field's value.
///
/// It passes characters through until [`PARAM_VALUE_MAX_CHARS`] of them
/// have been written and then swallows the rest, silently and with no
/// marker, at the constant the audit record's own cut uses. The budget
/// counts the characters handed TO the adapter, across however many
/// `write_str` calls a `fmt::Arguments` arrives in, so a value assembled
/// in pieces is cut at the total. It allocates nothing.
///
/// The budget covers the RENDERED value, decoration included: the adapter
/// sees a stream of characters and cannot know which of them the client
/// wrote, so it cuts wherever the count runs out — mid-value,
/// mid-escape, or between a value and the delimiter that was going to
/// close it. That last case is why `server::Capped` bounds its own
/// rendering eight characters under this one (#278) and closes its own
/// quote: a field this adapter cuts open is a field a quote-honouring
/// reader runs out of, into whatever follows on the line. Nothing a
/// `Capped` renders reaches this budget; what still does is rmcp's
/// fields, `message`, and bugwarden's own `%` ones — an OPERATOR's
/// config path among them, cut at 1024 like anyone else's, because a
/// bound with an exception for trusted values is a bound with a hole.
///
/// Characters are escaped on the way through. The set is every C0 byte
/// `\x00`–`\x1f`, DEL, every C1 byte `\u{80}`–`\u{9f}`, and U+2028
/// and U+2029: every control character, plus the only two mandatory
/// line breaks Unicode puts outside those ranges. UAX #14 makes LF, VT,
/// FF, CR, NEL, LS and PS mandatory breaks, and all but the last two
/// are C0 or C1 already — so the set ends where a rule ends it,
/// rather than where the last reported defect happened to reach.
///
/// LF, CR and TAB are written `\n`, `\r` and `\t`, the spellings
/// `str`'s own `Debug` uses. For THOSE THREE, and only those three, a
/// `?`-formatted field — escaped by `Debug` long before it reaches
/// this adapter — and a `%`-formatted one carrying the same text put
/// identical bytes on the line. The two part company over the rest of
/// C0 and DEL, where `Debug` writes `\0` and `\u{..}` against this
/// adapter's `\xNN`; that parity was never on offer and is not claimed.
/// Everything else in the set is written the way tracing-subscriber
/// 0.3's own `EscapeGuard` writes the part of it the two share: `\xNN`
/// for the five single characters it covers (ESC, BEL, BS, FF and DEL)
/// and `\u{..}` for the whole C1 range. Borrowing those two spellings
/// keeps one field's escapes one family rather than two.
///
/// Wider than `EscapeGuard`'s set, deliberately (#275). It passes LF,
/// CR, TAB, the C0 bytes outside its five, and U+2028/U+2029 through
/// raw even in `message` — defensible for text a program wrote, and
/// not for text a client chose: a LINE is the unit an operator greps
/// and a log shipper ships, so a `query` carrying LF ended the server's
/// line and opened one of its own, timestamp and level and target
/// included. Unit tests below pin both halves of the divergence, so a
/// later "make it match tracing-subscriber" cleanup has to argue with a
/// test rather than delete a comment.
///
/// The escaping is UNCONDITIONAL — it does not consult
/// `Writer::sanitizes_ansi_escapes`, whose `false` setting exists so that
/// TRUSTED sequences in logged values pass through unchanged, which is
/// exactly the channel a client must never inherit.
pub struct CappedWriter<'a, W: fmt::Write> {
    inner: &'a mut W,
    remaining: usize,
}

impl<'a, W: fmt::Write> CappedWriter<'a, W> {
    /// A budget of [`PARAM_VALUE_MAX_CHARS`] characters into `inner`.
    pub fn new(inner: &'a mut W) -> Self {
        Self {
            inner,
            remaining: PARAM_VALUE_MAX_CHARS,
        }
    }
}

impl<W: fmt::Write> fmt::Write for CappedWriter<'_, W> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        for ch in s.chars() {
            if self.remaining == 0 {
                return Ok(());
            }
            self.remaining -= 1;
            match ch {
                // The three that end a line or a column for a reader,
                // in `str`'s own `Debug` spellings — the three, and no
                // others, where a `?` field (already escaped by `Debug`
                // before it gets here) and a `%` field carrying the
                // same text read alike.
                '\n' => self.inner.write_str("\\n")?,
                '\r' => self.inner.write_str("\\r")?,
                '\t' => self.inner.write_str("\\t")?,
                // The rest of C0, and DEL: `EscapeGuard`'s `\xNN`,
                // widened from the five it spells that way to the range.
                '\x00'..='\x1f' | '\x7f' => write!(self.inner, "\\x{:02x}", ch as u32)?,
                // C1, the 8-bit forms of the same sequences, and the
                // two mandatory line breaks Unicode puts outside both
                // control ranges (#275).
                '\u{80}'..='\u{9f}' | '\u{2028}' | '\u{2029}' => {
                    write!(self.inner, "\\u{{{:x}}}", ch as u32)?
                }
                _ => self.inner.write_char(ch)?,
            }
        }
        Ok(())
    }
}

/// The stderr layer's field formatter: `DefaultFields`' rendering with
/// every value written through a [`CappedWriter`].
///
/// Installed by `main` with `fmt::layer().fmt_fields(..)`, so it formats
/// the fields of every event and of every span, whatever the target,
/// level or `RUST_LOG` — which is the whole point, since the lines this
/// exists for are rmcp's rather than ours.
#[derive(Debug, Clone, Copy, Default)]
pub struct CappedFields;

impl<'writer> FormatFields<'writer> for CappedFields {
    fn format_fields<R: RecordFields>(&self, writer: Writer<'writer>, fields: R) -> fmt::Result {
        let mut visitor = CappedVisitor {
            writer,
            is_empty: true,
            result: Ok(()),
        };
        fields.record(&mut visitor);
        visitor.result
    }
}

/// [`CappedFields`]' visitor, a transcription of tracing-subscriber
/// 0.3's `DefaultVisitor` whose one intended change is that the value
/// goes through a [`CappedWriter`] and the field NAME does not — a name
/// is static text of ours or of a dependency's, never the client's.
///
/// Transcribed rather than wrapped because `DefaultVisitor` writes
/// straight to its own `Writer` and exposes no seam. That transcription
/// carries one limit: `Writer`'s `italic()`/`dimmed()` are private to
/// tracing-subscriber, so names and separators are written unstyled.
/// bugwarden installs this layer with `with_ansi(false)`, where
/// `DefaultVisitor` writes them unstyled too, so the two agree byte for
/// byte in the only configuration this binary builds.
struct CappedVisitor<'a> {
    writer: Writer<'a>,
    is_empty: bool,
    result: fmt::Result,
}

impl CappedVisitor<'_> {
    /// The single space that separates two fields.
    fn maybe_pad(&mut self) {
        if self.is_empty {
            self.is_empty = false;
        } else {
            self.result = self.writer.write_char(' ');
        }
    }

    /// One field's value, bounded and sanitized.
    fn write_value(&mut self, value: &dyn fmt::Debug) -> fmt::Result {
        write!(CappedWriter::new(&mut self.writer), "{value:?}")
    }
}

impl Visit for CappedVisitor<'_> {
    fn record_str(&mut self, field: &Field, value: &str) {
        if self.result.is_err() {
            return;
        }
        // `message` prints bare and every other string prints quoted, so
        // the two reach `record_debug` as different kinds of value.
        if field.name() == "message" {
            self.record_debug(field, &format_args!("{value}"));
        } else {
            self.record_debug(field, &value);
        }
    }

    fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
        // The error's own text, then its chain under a `<name>.sources`
        // pseudo-field — `DefaultVisitor`'s shape, and the raw field name
        // in the label as it uses it, `r#` prefix and all.
        match value.source() {
            Some(source) => self.record_debug(
                field,
                &format_args!("{value} {}.sources={}", field.name(), ErrorSources(source)),
            ),
            None => self.record_debug(field, &format_args!("{value}")),
        }
    }

    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        if self.result.is_err() {
            return;
        }
        let name = field.name();
        // `tracing-log`'s bridge hangs a `log` record's real target,
        // module path, file and line on the event as `log.*` fields, and
        // `DefaultVisitor` drops them behind the same feature that
        // installs the bridge — so where they exist, the skip does too.
        // `otel::BodyVisitor` still reads `log.target`, because the
        // export has to know the target the metadata no longer carries.
        if name.starts_with("log.") {
            return;
        }
        self.maybe_pad();
        self.result = match name {
            "message" => self.write_value(value),
            // A raw identifier's field name keeps its `r#` in the
            // metadata and loses it on the line.
            name => {
                let key = name.strip_prefix("r#").unwrap_or(name);
                self.writer
                    .write_str(key)
                    .and_then(|()| self.writer.write_char('='))
                    .and_then(|()| self.write_value(value))
            }
        };
    }
}

/// An error's SOURCE chain as `DefaultVisitor` renders one: `[its
/// source, that source's own source, …]`, each entry a `Display` text
/// unquoted. The error itself is printed before the list, not in it.
struct ErrorSources<'a>(&'a (dyn std::error::Error + 'static));

impl fmt::Display for ErrorSources<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut list = f.debug_list();
        let mut current = Some(self.0);
        while let Some(error) = current {
            list.entry(&Unquoted(error));
            current = error.source();
        }
        list.finish()
    }
}

/// One entry of an [`ErrorSources`] list: `Debug` that prints `Display`,
/// so `debug_list` does not quote what is already prose.
struct Unquoted<'a>(&'a (dyn std::error::Error + 'static));

impl fmt::Debug for Unquoted<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self.0, f)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use tracing_subscriber::fmt::format::DefaultFields;
    use tracing_subscriber::layer::{Context, SubscriberExt as _};
    use tracing_subscriber::Layer;

    use super::*;

    /// ESC, the byte a terminal reads as the start of a control sequence.
    const ESC: char = '\x1b';

    /// Every character the sink rewrites, with the text it writes for
    /// it.
    ///
    /// Spelled out rather than computed from the same `match` the code
    /// uses: a table derived from the implementation agrees with any
    /// implementation, including a broken one.
    const ESCAPES: [(char, &str); 67] = [
        ('\u{00}', "\\x00"),
        ('\u{01}', "\\x01"),
        ('\u{02}', "\\x02"),
        ('\u{03}', "\\x03"),
        ('\u{04}', "\\x04"),
        ('\u{05}', "\\x05"),
        ('\u{06}', "\\x06"),
        ('\u{07}', "\\x07"),
        ('\u{08}', "\\x08"),
        ('\u{09}', "\\t"),
        ('\u{0a}', "\\n"),
        ('\u{0b}', "\\x0b"),
        ('\u{0c}', "\\x0c"),
        ('\u{0d}', "\\r"),
        ('\u{0e}', "\\x0e"),
        ('\u{0f}', "\\x0f"),
        ('\u{10}', "\\x10"),
        ('\u{11}', "\\x11"),
        ('\u{12}', "\\x12"),
        ('\u{13}', "\\x13"),
        ('\u{14}', "\\x14"),
        ('\u{15}', "\\x15"),
        ('\u{16}', "\\x16"),
        ('\u{17}', "\\x17"),
        ('\u{18}', "\\x18"),
        ('\u{19}', "\\x19"),
        ('\u{1a}', "\\x1a"),
        ('\u{1b}', "\\x1b"),
        ('\u{1c}', "\\x1c"),
        ('\u{1d}', "\\x1d"),
        ('\u{1e}', "\\x1e"),
        ('\u{1f}', "\\x1f"),
        ('\u{7f}', "\\x7f"),
        ('\u{80}', "\\u{80}"),
        ('\u{81}', "\\u{81}"),
        ('\u{82}', "\\u{82}"),
        ('\u{83}', "\\u{83}"),
        ('\u{84}', "\\u{84}"),
        ('\u{85}', "\\u{85}"),
        ('\u{86}', "\\u{86}"),
        ('\u{87}', "\\u{87}"),
        ('\u{88}', "\\u{88}"),
        ('\u{89}', "\\u{89}"),
        ('\u{8a}', "\\u{8a}"),
        ('\u{8b}', "\\u{8b}"),
        ('\u{8c}', "\\u{8c}"),
        ('\u{8d}', "\\u{8d}"),
        ('\u{8e}', "\\u{8e}"),
        ('\u{8f}', "\\u{8f}"),
        ('\u{90}', "\\u{90}"),
        ('\u{91}', "\\u{91}"),
        ('\u{92}', "\\u{92}"),
        ('\u{93}', "\\u{93}"),
        ('\u{94}', "\\u{94}"),
        ('\u{95}', "\\u{95}"),
        ('\u{96}', "\\u{96}"),
        ('\u{97}', "\\u{97}"),
        ('\u{98}', "\\u{98}"),
        ('\u{99}', "\\u{99}"),
        ('\u{9a}', "\\u{9a}"),
        ('\u{9b}', "\\u{9b}"),
        ('\u{9c}', "\\u{9c}"),
        ('\u{9d}', "\\u{9d}"),
        ('\u{9e}', "\\u{9e}"),
        ('\u{9f}', "\\u{9f}"),
        ('\u{2028}', "\\u{2028}"),
        ('\u{2029}', "\\u{2029}"),
    ];

    /// One event's fields rendered by both formatters.
    #[derive(Clone, Debug, Default)]
    struct Rendered {
        default: String,
        capped: String,
    }

    /// A layer that renders every event through `DefaultFields` and
    /// through [`CappedFields`], into one `Writer` configuration.
    ///
    /// The differential runs inside one `on_event` on purpose: both
    /// formatters see the SAME `ValueSet`, so a difference cannot come
    /// from the two runs having recorded different values, and no
    /// timestamp or level prefix has to be normalized away.
    ///
    /// `Writer::new` builds the configuration this binary installs — no
    /// ANSI, sanitization on — so the comparison is the one that matters
    /// rather than a convenient one.
    struct Differential(Arc<Mutex<Vec<Rendered>>>);

    impl<S: tracing::Subscriber> Layer<S> for Differential {
        fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
            let mut rendered = Rendered::default();
            DefaultFields::new()
                .format_fields(Writer::new(&mut rendered.default), event)
                .expect("a String never fails to be written");
            CappedFields
                .format_fields(Writer::new(&mut rendered.capped), event)
                .expect("a String never fails to be written");
            self.0.lock().expect("the render lock").push(rendered);
        }
    }

    /// Render everything `emit` logs through both formatters.
    ///
    /// `with_default` and not a global subscriber: these tests share a
    /// process with `testlog`, which installs one of its own.
    fn render(emit: impl FnOnce()) -> Vec<Rendered> {
        let out: Arc<Mutex<Vec<Rendered>>> = Arc::new(Mutex::new(Vec::new()));
        let subscriber = tracing_subscriber::registry().with(Differential(out.clone()));
        tracing::subscriber::with_default(subscriber, emit);
        let rendered = out.lock().expect("the render lock").clone();
        assert!(!rendered.is_empty(), "the differential saw no events");
        rendered
    }

    /// The one event `emit` logs, rendered through both formatters.
    fn render_one(emit: impl FnOnce()) -> Rendered {
        let mut rendered = render(emit);
        assert_eq!(rendered.len(), 1, "exactly one event: {rendered:?}");
        rendered.remove(0)
    }

    /// The adapter's budget is the whole point: over-cap text stops at
    /// exactly the cap, on a character boundary, and short text is
    /// untouched.
    #[test]
    fn the_budget_cuts_at_exactly_the_cap_on_a_char_boundary() {
        for chars in [0, 1, PARAM_VALUE_MAX_CHARS - 1, PARAM_VALUE_MAX_CHARS] {
            let mut out = String::new();
            // Multi-byte: an ASCII probe cannot tell a char budget from a
            // byte one.
            write!(CappedWriter::new(&mut out), "{}", "é".repeat(chars))
                .expect("a String never fails to be written");
            assert_eq!(out, "é".repeat(chars), "under the cap nothing moves");
        }
        let mut out = String::new();
        write!(
            CappedWriter::new(&mut out),
            "{}",
            "é".repeat(PARAM_VALUE_MAX_CHARS * 4)
        )
        .expect("a String never fails to be written");
        assert_eq!(
            out,
            "é".repeat(PARAM_VALUE_MAX_CHARS),
            "over the cap the cut is exact and lands between characters"
        );
    }

    /// A `fmt::Arguments` reaches the adapter in as many `write_str`
    /// calls as it has pieces, and the budget is the total across them.
    #[test]
    fn a_value_written_in_pieces_is_cut_at_the_char_total() {
        let piece = "é".repeat(PARAM_VALUE_MAX_CHARS / 2);
        let mut out = String::new();
        write!(CappedWriter::new(&mut out), "{piece}{piece}{piece}{piece}")
            .expect("a String never fails to be written");
        assert_eq!(out, "é".repeat(PARAM_VALUE_MAX_CHARS));

        // And the writes past the budget are swallowed rather than
        // failing, so the fields after this one still render.
        let mut writer = CappedWriter::new(&mut out);
        writer
            .write_str(&"z".repeat(PARAM_VALUE_MAX_CHARS * 2))
            .expect("an exhausted budget swallows, it does not error");
        writer
            .write_str("z")
            .expect("an exhausted budget swallows, it does not error");
        assert_eq!(
            out.chars().filter(|c| *c == 'z').count(),
            PARAM_VALUE_MAX_CHARS,
            "a second value gets its own budget and no more"
        );
    }

    /// Every character `EscapeGuard` rewrites, rendered here exactly as
    /// tracing-subscriber renders it in `message`: over that set the two
    /// are byte-equal, which is what makes the spellings borrowed above
    /// a reuse of its renderings rather than a guess at them.
    ///
    /// The probe stops at `EscapeGuard`'s set on purpose: where this
    /// sink goes further (#275) the two differ by decision, and
    /// [`the_characters_default_fields_leaves_raw_are_escaped_here`] is
    /// where that half is pinned.
    #[test]
    fn the_escaping_matches_what_default_fields_does_to_a_message() {
        let probe: String = ['\x1b', '\x07', '\x08', '\x0c', '\x7f']
            .into_iter()
            .chain(('\u{80}'..='\u{9f}').chain(['a', 'é', '"', '\\']))
            .collect();
        // `DefaultFields` escapes `message` and `record_error` and
        // nothing else, so `message` is where the two renderings can be
        // compared directly.
        let rendered = render_one(|| tracing::info!("{probe}"));
        assert_eq!(rendered.capped, rendered.default);
        assert!(
            rendered.capped.contains("\\x1b") && rendered.capped.contains("\\u{9b}"),
            "and it really escaped something: {:?}",
            rendered.capped
        );

        // The same bytes in a `%` field, which `DefaultFields` leaves
        // raw: ours is the escaped rendering of the message, prefixed by
        // the field's name.
        let escaped = rendered.capped.clone();
        let field = render_one(|| tracing::info!(probe = %probe));
        assert_eq!(field.capped, format!("probe={escaped}"));
        assert!(
            field.default.contains(ESC),
            "the raw ESC this exists to stop must still be in what \
             `DefaultFields` writes: {:?}",
            field.default
        );
    }

    /// Every character the sink escapes leaves it as the text
    /// [`ESCAPES`] names, on the adapter and through the visitor alike
    /// (#275).
    ///
    /// Both ranges walked whole rather than spot-checked: the characters
    /// an attacker reaches for are not the ones a reviewer thinks of,
    /// and a range arm is exactly the kind of code whose ends drift.
    #[test]
    fn every_escaped_character_leaves_the_sink_as_its_escape() {
        assert_eq!(
            ESCAPES.map(|(ch, _)| ch).to_vec(),
            ('\u{00}'..='\u{1f}')
                .chain(['\u{7f}'])
                .chain('\u{80}'..='\u{9f}')
                .chain(['\u{2028}', '\u{2029}'])
                .collect::<Vec<char>>(),
            "the table must walk C0, DEL, C1 and the two separators, \
             in order and whole"
        );
        for (ch, escaped) in ESCAPES {
            // Flanked, so an arm that swallowed the byte instead of
            // escaping it cannot pass by leaving an empty string behind.
            let value = format!("a{ch}b");
            let mut out = String::new();
            write!(CappedWriter::new(&mut out), "{value}")
                .expect("a String never fails to be written");
            assert_eq!(
                out,
                format!("a{escaped}b"),
                "U+{:04X} must leave the adapter escaped",
                ch as u32
            );
            assert_eq!(
                render_one(|| tracing::info!(probe = %value)).capped,
                format!("probe=a{escaped}b"),
                "and the same through the field visitor, U+{:04X}",
                ch as u32
            );
        }

        // The characters immediately past each range stay raw, so an
        // end that slipped by one is caught from the outside too: SPACE
        // sits just above C0, NBSP just above C1.
        for ch in [' ', '\u{a0}'] {
            let value = format!("a{ch}b");
            let mut out = String::new();
            write!(CappedWriter::new(&mut out), "{value}")
                .expect("a String never fails to be written");
            assert_eq!(
                out, value,
                "U+{:04X} is outside the set and must pass through raw",
                ch as u32
            );
        }
    }

    /// The divergence from `EscapeGuard`, pinned on both sides: over
    /// the characters tracing-subscriber does NOT cover — LF, CR, TAB,
    /// the C0 bytes outside its five, and U+2028/U+2029 — it writes the
    /// raw character into `message` where this sink writes an escape
    /// (#275).
    ///
    /// Asserting only our half would let a future "make it match
    /// tracing-subscriber again" change delete the decision quietly; a
    /// test that also states what tracing-subscriber does makes the
    /// difference the subject rather than a side effect. One
    /// representative of each uncovered group, since
    /// [`every_escaped_character_leaves_the_sink_as_its_escape`] already
    /// walks this side of the difference whole.
    #[test]
    fn the_characters_default_fields_leaves_raw_are_escaped_here() {
        for (ch, escaped) in [
            ('\n', "\\n"),
            ('\r', "\\r"),
            ('\t', "\\t"),
            ('\u{01}', "\\x01"),
            ('\u{2028}', "\\u{2028}"),
        ] {
            let probe = format!("a{ch}b");
            let rendered = render_one(|| tracing::info!("{probe}"));
            assert_eq!(
                rendered.default, probe,
                "tracing-subscriber leaves U+{:04X} raw even in \
                 `message`, which is the thing being diverged from",
                ch as u32
            );
            assert_eq!(
                rendered.capped,
                format!("a{escaped}b"),
                "and this sink escapes it instead, by decision: U+{:04X}",
                ch as u32
            );
        }
    }

    /// For LF, CR and TAB — and for those three only — a
    /// `?`-formatted field and a `%`-formatted one carrying the same
    /// text put the same bytes on the line, once the `?` one's own
    /// quotes come off. That agreement is the entire reason the three
    /// are spelled `\n`, `\r` and `\t` here rather than `\x0a`, `\x0d`
    /// and `\x09`.
    ///
    /// It does not generalise, and is not meant to: `str`'s `Debug`
    /// writes `\0` for NUL and `\u{1b}` for ESC where this sink writes
    /// `\x00` and `\x1b`, so the two shapes disagree on the other 30
    /// characters of C0 and DEL. The probe carries the three that agree,
    /// which is the claim being made.
    ///
    /// The two arrive by different routes: `str`'s `Debug` has already
    /// escaped the `?` field before the adapter sees it, and the adapter
    /// escapes the `%` one itself. Reading alike is what makes one field
    /// comparable with the one beside it.
    #[test]
    fn lf_cr_and_tab_read_alike_in_a_debug_field_and_a_display_one() {
        let probe = "a\nb\tc\rd";
        let rendered = render_one(|| tracing::info!(debug = ?probe, display = %probe)).capped;
        let (debug, display) = rendered
            .split_once(" display=")
            .unwrap_or_else(|| panic!("both fields must reach the line: {rendered:?}"));
        let debug = debug
            .strip_prefix("debug=\"")
            .and_then(|value| value.strip_suffix('"'))
            .unwrap_or_else(|| panic!("`str`'s `Debug` quotes its value: {debug:?}"));
        assert_eq!(
            debug, display,
            "the two shapes must render one value identically: {rendered:?}"
        );
        assert_eq!(
            display, "a\\nb\\tc\\rd",
            "and in the spellings `Debug` chose: {rendered:?}"
        );
    }

    /// Parity: a value under the cap with no control bytes renders byte
    /// for byte as it does today, for every shape a field arrives in.
    #[test]
    fn every_field_shape_renders_exactly_as_default_fields_renders_it() {
        #[derive(Debug)]
        struct Inner;

        impl std::fmt::Display for Inner {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("the inner cause")
            }
        }

        impl std::error::Error for Inner {}

        #[derive(Debug)]
        struct Outer(Inner);

        impl std::fmt::Display for Outer {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("the outer failure")
            }
        }

        impl std::error::Error for Outer {
            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
                Some(&self.0)
            }
        }

        let text = "a plain value";
        let owned = String::from("owned text");
        let lone: &(dyn std::error::Error + 'static) = &Inner;
        let chained: &(dyn std::error::Error + 'static) = &Outer(Inner);
        let rendered = render(|| {
            tracing::info!("a message alone");
            tracing::info!(display = %text, "message and fields");
            tracing::info!(debug = ?text, quoted = text, owned = owned.as_str());
            tracing::info!(count = 7u64, signed = -7i64, ratio = 0.5, flag = true);
            tracing::info!(r#type = "raw identifier", nested = ?vec![1, 2, 3]);
            // A field whose NAME really carries the `r#`: the raw
            // identifier above does not — the macro stringifies it to
            // `type` — and only a literal name reaches the visitor with
            // the prefix `DefaultVisitor` strips.
            tracing::info!("r#type" = "a literal raw name");
            tracing::error!(error = lone, "an error without a source");
            tracing::error!(error = chained, "an error with a source");
            // The bridge's own fields, which neither formatter renders.
            tracing::info!(
                log.target = "reqwest::connect",
                log.module_path = "reqwest",
                log.file = "connect.rs",
                log.line = 1,
                "a bridged record"
            );
        });
        for one in &rendered {
            assert_eq!(one.capped, one.default, "rendering must not drift");
        }
        // Named shapes the loop above would pass over silently if the
        // events stopped carrying them.
        let all = rendered
            .iter()
            .map(|one| one.capped.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        for needle in [
            "display=a plain value",
            "debug=\"a plain value\"",
            "quoted=\"a plain value\"",
            "count=7 signed=-7 ratio=0.5 flag=true",
            "type=\"raw identifier\"",
            "type=\"a literal raw name\"",
            "nested=[1, 2, 3]",
            "error=the outer failure error.sources=[the inner cause]",
        ] {
            assert!(all.contains(needle), "{needle:?} missing from:\n{all}");
        }
    }

    /// The bridge's `log.*` fields are dropped, and dropping them does
    /// not eat the separator of the fields that stay.
    #[test]
    fn the_log_bridge_fields_never_reach_the_line() {
        let rendered = render_one(|| {
            tracing::info!(
                log.target = "hyper_util::client::legacy::pool",
                kept = "yes",
                log.line = 12,
                also_kept = "yes",
                "bridged"
            );
        });
        assert_eq!(rendered.capped, "bridged kept=\"yes\" also_kept=\"yes\"");
        assert_eq!(rendered.capped, rendered.default);
    }

    /// `message` is a field like any other here. That is what bounds
    /// the #261 `serving error: {:?}` line, whose whole payload is the
    /// message; rmcp's `?notification` payload rides a field instead and
    /// is bounded by the same budget one field over.
    #[test]
    fn the_message_is_capped_too() {
        let long = "é".repeat(PARAM_VALUE_MAX_CHARS * 4);
        let rendered = render_one(|| tracing::info!("{long}"));
        assert_eq!(rendered.capped, "é".repeat(PARAM_VALUE_MAX_CHARS));
        assert!(
            rendered.default.chars().count() > PARAM_VALUE_MAX_CHARS,
            "and `DefaultFields` is what it is being capped against: {}",
            rendered.default.chars().count()
        );
    }

    /// The budget charges the characters handed IN, not the ones written
    /// OUT.
    ///
    /// The two orders agree on ordinary text and differ by a factor of
    /// up to eight on escapable input — `\u{2028}` is the widest
    /// escape the sink writes — and it is the in-order one that the
    /// rustdoc above and DESIGN.md's "at most eight bytes per budgeted
    /// character" rest on. Nothing on the stderr path tells them apart,
    /// because a real line's escapable characters are a handful among
    /// thousands.
    #[test]
    fn the_budget_charges_the_characters_handed_in_not_the_ones_written_out() {
        let mut out = String::new();
        write!(
            CappedWriter::new(&mut out),
            "{}",
            ESC.to_string().repeat(PARAM_VALUE_MAX_CHARS + 1)
        )
        .expect("a String never fails to be written");
        assert_eq!(
            out,
            "\\x1b".repeat(PARAM_VALUE_MAX_CHARS),
            "1024 escapes in, four characters out apiece"
        );

        // And for #275's own arm, whose escape is two characters out for
        // one in: a budget that charged the OUTPUT would cut this at 512.
        let mut out = String::new();
        write!(
            CappedWriter::new(&mut out),
            "{}",
            "\n".repeat(PARAM_VALUE_MAX_CHARS + 1)
        )
        .expect("a String never fails to be written");
        assert_eq!(
            out,
            "\\n".repeat(PARAM_VALUE_MAX_CHARS),
            "1024 newlines in, two characters out apiece"
        );

        // And for the widest escape the sink writes, eight characters
        // out for one in: an output-charged budget would stop at 128.
        let mut out = String::new();
        write!(
            CappedWriter::new(&mut out),
            "{}",
            "\u{2028}".repeat(PARAM_VALUE_MAX_CHARS + 1)
        )
        .expect("a String never fails to be written");
        assert_eq!(
            out,
            "\\u{2028}".repeat(PARAM_VALUE_MAX_CHARS),
            "1024 line separators in, eight characters out apiece"
        );

        // And through the visitor, on both the `%` path and `message`:
        // the leading ESC costs one character of the field's budget, so
        // 1023 of the client's own characters follow it.
        let long = format!("{ESC}{}", "é".repeat(PARAM_VALUE_MAX_CHARS * 4));
        let expected = format!("\\x1b{}", "é".repeat(PARAM_VALUE_MAX_CHARS - 1));
        assert_eq!(
            render_one(|| tracing::info!(probe = %long)).capped,
            format!("probe={expected}")
        );
        assert_eq!(render_one(|| tracing::info!("{long}")).capped, expected);
    }

    /// Each field gets its own budget, and the cut leaves the fields
    /// after it intact — a shared budget would silently drop them.
    #[test]
    fn every_field_is_capped_on_its_own_budget() {
        let long = "é".repeat(PARAM_VALUE_MAX_CHARS * 2);
        let rendered = render_one(|| tracing::info!(first = %long, second = %long, "m"));
        assert_eq!(
            rendered.capped,
            format!(
                "m first={cap} second={cap}",
                cap = "é".repeat(PARAM_VALUE_MAX_CHARS)
            )
        );
    }
}