gaze-proxy 0.15.1

Feature-gated multi-provider HTTP proxy for Gaze PII pseudonymization
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
use std::fmt;
use std::ops::Range;

use gaze::{
    CommittedSessionSnapshot, PrefixCacheWriteMode, RestoreError, RestoredTextWithProvenance,
};
use gaze_types::inspection::{
    JsonShapeSummaryV1, ProjectionAvailabilityV1, ProjectionOmissionReasonV1, SseTimelineMetaV1,
};

/// Transport-independent body representation selected by a reviewed adapter contract.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WireFormat {
    Empty,
    Json,
    Ndjson,
    Utf8Text,
    Sse,
}

/// Closed phase reported by a codec failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CodecPhase {
    RequestParse,
    RequestProtection,
    RequestProof,
    ResponseParse,
    ResponseRestore,
    ResponseProof,
    SseDecode,
    SseLifecycle,
    SseReplay,
}

/// Closed, sanitized codec failure code.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CodecErrorCode {
    InvalidUtf8,
    InvalidJson,
    InvalidWireFormat,
    DuplicateObjectKey,
    DepthLimitExceeded,
    NodeLimitExceeded,
    StringLimitExceeded,
    NumberLimitExceeded,
    BodyLimitExceeded,
    GrowthLimitExceeded,
    InternalCoverageFailure,
    UnsupportedRequestSurface,
    UnsupportedResponseSurface,
    ControlWouldMutate,
    OpaqueMediaUninspected,
    SignedMutationRequired,
    SignedSurfaceMalformed,
    ProtectionFailedClosed,
    RestoreFailedClosed,
    ProviderOriginNumeric,
    ProviderOriginPii,
    TransformedKeyCollision,
    InvalidSseField,
    InvalidSseFrame,
    InvalidSseEventPair,
    SseLineLimitExceeded,
    SseFrameLimitExceeded,
    SseEventLimitExceeded,
    SseIndexLimitExceeded,
    SseAccumulatorLimitExceeded,
    InvalidSseLifecycle,
    InvalidContentBlockIndex,
    InvalidContentBlockDelta,
    IncompleteSseStream,
    UnsafeFutureEvent,
    ProviderErrorEvent,
}

/// Closed carrier schemes that may safely identify an opaque request carrier.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum OpaqueCarrierScheme {
    Data,
    File,
    Http,
    Https,
}

impl OpaqueCarrierScheme {
    /// Returns the normalized scheme identifier without any carrier payload.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Data => "data:",
            Self::File => "file:",
            Self::Http => "http:",
            Self::Https => "https:",
        }
    }
}

/// Structural location of an opaque carrier, never its bytes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct OpaqueCarrierLocation {
    scheme: OpaqueCarrierScheme,
    byte_offset: usize,
    byte_length: usize,
    content_block_index: Option<usize>,
}

impl OpaqueCarrierLocation {
    pub(crate) const fn new(
        scheme: OpaqueCarrierScheme,
        byte_offset: usize,
        byte_length: usize,
        content_block_index: Option<usize>,
    ) -> Self {
        Self {
            scheme,
            byte_offset,
            byte_length,
            content_block_index,
        }
    }

    #[must_use]
    pub const fn scheme(self) -> OpaqueCarrierScheme {
        self.scheme
    }

    #[must_use]
    pub const fn byte_offset(self) -> usize {
        self.byte_offset
    }

    #[must_use]
    pub const fn byte_length(self) -> usize {
        self.byte_length
    }

    #[must_use]
    pub const fn content_block_index(self) -> Option<usize> {
        self.content_block_index
    }
}

/// Sanitized codec failure. It never retains parser, body, key, value, or provider error text.
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct CodecError {
    code: CodecErrorCode,
    phase: CodecPhase,
    opaque_carrier: Option<OpaqueCarrierLocation>,
}

impl CodecError {
    pub(crate) const fn new(code: CodecErrorCode, phase: CodecPhase) -> Self {
        Self {
            code,
            phase,
            opaque_carrier: None,
        }
    }

    pub(crate) const fn with_opaque_carrier(
        mut self,
        opaque_carrier: Option<OpaqueCarrierLocation>,
    ) -> Self {
        self.opaque_carrier = opaque_carrier;
        self
    }

    #[must_use]
    pub const fn code(self) -> CodecErrorCode {
        self.code
    }

    #[must_use]
    pub const fn phase(self) -> CodecPhase {
        self.phase
    }

    /// Returns only the carrier's structural location, never its bytes.
    #[must_use]
    pub const fn opaque_carrier(self) -> Option<OpaqueCarrierLocation> {
        self.opaque_carrier
    }
}

impl fmt::Debug for CodecError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = formatter.debug_struct("CodecError");
        debug.field("code", &self.code).field("phase", &self.phase);
        if let Some(opaque_carrier) = self.opaque_carrier {
            debug.field("opaque_carrier", &opaque_carrier);
        }
        debug.finish()
    }
}

impl fmt::Display for CodecError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "codec_{:?}_{:?}", self.phase, self.code)
    }
}

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

/// Reviewed finite codec limits. Builders may only lower these defaults in I3.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CodecLimits {
    max_body_bytes: usize,
    max_json_depth: usize,
    max_json_nodes: usize,
    max_string_bytes: usize,
    max_number_bytes: usize,
    max_growth_numerator: usize,
    max_growth_denominator: usize,
    max_sse_line_bytes: usize,
    max_sse_frame_bytes: usize,
    max_sse_events: usize,
    max_sse_indices: usize,
    max_sse_accumulator_bytes: usize,
}

impl Default for CodecLimits {
    fn default() -> Self {
        Self {
            max_body_bytes: 32 * 1024 * 1024,
            max_json_depth: 128,
            max_json_nodes: 100_000,
            max_string_bytes: 4 * 1024 * 1024,
            max_number_bytes: 128,
            max_growth_numerator: 2,
            max_growth_denominator: 1,
            max_sse_line_bytes: 256 * 1024,
            max_sse_frame_bytes: 1024 * 1024,
            max_sse_events: 10_000,
            max_sse_indices: 256,
            max_sse_accumulator_bytes: 8 * 1024 * 1024,
        }
    }
}

impl CodecLimits {
    #[must_use]
    pub const fn with_max_body_bytes(mut self, value: usize) -> Self {
        self.max_body_bytes = value;
        self
    }

    #[must_use]
    pub const fn with_max_json_depth(mut self, value: usize) -> Self {
        self.max_json_depth = value;
        self
    }

    #[must_use]
    pub const fn with_max_json_nodes(mut self, value: usize) -> Self {
        self.max_json_nodes = value;
        self
    }

    #[must_use]
    pub const fn with_max_string_bytes(mut self, value: usize) -> Self {
        self.max_string_bytes = value;
        self
    }

    #[must_use]
    pub const fn with_max_number_bytes(mut self, value: usize) -> Self {
        self.max_number_bytes = value;
        self
    }

    #[must_use]
    pub const fn with_max_sse_line_bytes(mut self, value: usize) -> Self {
        self.max_sse_line_bytes = value;
        self
    }

    #[must_use]
    pub const fn with_max_sse_frame_bytes(mut self, value: usize) -> Self {
        self.max_sse_frame_bytes = value;
        self
    }

    #[must_use]
    pub const fn with_max_sse_events(mut self, value: usize) -> Self {
        self.max_sse_events = value;
        self
    }

    #[must_use]
    pub const fn with_max_sse_indices(mut self, value: usize) -> Self {
        self.max_sse_indices = value;
        self
    }

    #[must_use]
    pub const fn with_max_sse_accumulator_bytes(mut self, value: usize) -> Self {
        self.max_sse_accumulator_bytes = value;
        self
    }

    #[must_use]
    pub const fn max_body_bytes(self) -> usize {
        self.max_body_bytes
    }

    #[must_use]
    pub const fn max_json_depth(self) -> usize {
        self.max_json_depth
    }

    #[must_use]
    pub const fn max_json_nodes(self) -> usize {
        self.max_json_nodes
    }

    #[must_use]
    pub const fn max_string_bytes(self) -> usize {
        self.max_string_bytes
    }

    #[must_use]
    pub const fn max_number_bytes(self) -> usize {
        self.max_number_bytes
    }

    #[must_use]
    pub const fn max_sse_line_bytes(self) -> usize {
        self.max_sse_line_bytes
    }

    #[must_use]
    pub const fn max_sse_frame_bytes(self) -> usize {
        self.max_sse_frame_bytes
    }

    #[must_use]
    pub const fn max_sse_events(self) -> usize {
        self.max_sse_events
    }

    #[must_use]
    pub const fn max_sse_indices(self) -> usize {
        self.max_sse_indices
    }

    #[must_use]
    pub const fn max_sse_accumulator_bytes(self) -> usize {
        self.max_sse_accumulator_bytes
    }

    pub(crate) fn output_within_growth_limit(self, input: usize, output: usize) -> bool {
        let proportional = input
            .checked_mul(self.max_growth_numerator)
            .map(|value| value / self.max_growth_denominator)
            .unwrap_or(usize::MAX);
        output <= self.max_body_bytes && output <= proportional.max(input)
    }
}

/// Staged request protection boundary supplied by I4.
pub trait RequestPseudonymizer {
    /// Protects one complete decoded logical value against the staged transaction.
    fn protect(&mut self, input: &str) -> Result<String, CodecErrorCode>;

    /// Protects one decoded value with an explicit prefix-cache mode.
    ///
    /// [`PrefixCacheWriteMode::Allow`] preserves the source-compatible delegation to
    /// [`Self::protect`]. [`PrefixCacheWriteMode::Suppress`] fails closed unless an
    /// implementation explicitly overrides this method with a stateless or isolated
    /// no-read/no-write guarantee.
    fn protect_with_prefix_cache_write_mode(
        &mut self,
        input: &str,
        mode: PrefixCacheWriteMode,
    ) -> Result<String, CodecErrorCode> {
        match mode {
            PrefixCacheWriteMode::Allow => self.protect(input),
            PrefixCacheWriteMode::Suppress => Err(CodecErrorCode::ProtectionFailedClosed),
        }
    }

    /// Proves that every Gaze-shaped token belongs to the staged transaction.
    fn validate_token_shapes(&mut self, input: &str) -> Result<(), CodecErrorCode>;
}

/// Residual response proof boundary supplied by I4.
pub trait ResponseResidualValidator {
    /// Validates one complete restored logical value. Every finding must fit wholly in an
    /// authorized manifest-backed output range.
    fn validate(
        &mut self,
        value: &str,
        authorized_output_ranges: &[Range<usize>],
    ) -> Result<(), CodecErrorCode>;
}

/// Private-field request transformation context.
pub struct RequestTransformContext<'a> {
    pseudonymizer: &'a mut dyn RequestPseudonymizer,
    format: WireFormat,
    limits: CodecLimits,
    inspection_projection_requested: bool,
    content_block_index: Option<usize>,
    opaque_carrier: Option<OpaqueCarrierLocation>,
}

impl<'a> RequestTransformContext<'a> {
    #[must_use]
    pub(crate) fn new(
        pseudonymizer: &'a mut dyn RequestPseudonymizer,
        format: WireFormat,
        limits: CodecLimits,
    ) -> Self {
        Self {
            pseudonymizer,
            format,
            limits,
            inspection_projection_requested: false,
            content_block_index: None,
            opaque_carrier: None,
        }
    }

    #[must_use]
    pub const fn format(&self) -> WireFormat {
        self.format
    }

    #[must_use]
    pub const fn limits(&self) -> CodecLimits {
        self.limits
    }

    pub(crate) fn request_inspection_projection(&mut self) {
        self.inspection_projection_requested = true;
    }

    pub(crate) const fn inspection_projection_requested(&self) -> bool {
        self.inspection_projection_requested
    }

    pub(crate) fn replace_content_block_index(
        &mut self,
        content_block_index: Option<usize>,
    ) -> Option<usize> {
        std::mem::replace(&mut self.content_block_index, content_block_index)
    }

    pub(crate) fn record_opaque_carrier(
        &mut self,
        scheme: OpaqueCarrierScheme,
        byte_offset: usize,
        byte_length: usize,
    ) {
        self.opaque_carrier.get_or_insert_with(|| {
            OpaqueCarrierLocation::new(scheme, byte_offset, byte_length, self.content_block_index)
        });
    }

    pub(crate) fn clear_opaque_carrier(&mut self) {
        self.opaque_carrier = None;
    }

    pub(crate) const fn opaque_carrier(&self) -> Option<OpaqueCarrierLocation> {
        self.opaque_carrier
    }

    pub(crate) fn protect(&mut self, input: &str) -> Result<String, CodecErrorCode> {
        self.pseudonymizer
            .protect_with_prefix_cache_write_mode(input, PrefixCacheWriteMode::Allow)
    }

    /// Runs an isolated mutation probe that may neither reuse nor publish prefix-cache state.
    pub(crate) fn probe_without_prefix_cache_write(
        &mut self,
        input: &str,
    ) -> Result<String, CodecErrorCode> {
        self.pseudonymizer
            .protect_with_prefix_cache_write_mode(input, PrefixCacheWriteMode::Suppress)
    }

    pub(crate) fn validate_token_shapes(&mut self, input: &str) -> Result<(), CodecErrorCode> {
        self.pseudonymizer.validate_token_shapes(input)
    }
}

/// Private-field response transformation context.
pub struct ResponseTransformContext<'a> {
    snapshot: &'a CommittedSessionSnapshot,
    residual: &'a mut dyn ResponseResidualValidator,
    format: WireFormat,
    limits: CodecLimits,
    inspection_projection_requested: bool,
}

impl<'a> ResponseTransformContext<'a> {
    #[must_use]
    pub(crate) fn new(
        snapshot: &'a CommittedSessionSnapshot,
        residual: &'a mut dyn ResponseResidualValidator,
        format: WireFormat,
        limits: CodecLimits,
    ) -> Self {
        Self {
            snapshot,
            residual,
            format,
            limits,
            inspection_projection_requested: false,
        }
    }

    #[must_use]
    pub const fn format(&self) -> WireFormat {
        self.format
    }

    #[must_use]
    pub const fn limits(&self) -> CodecLimits {
        self.limits
    }

    pub(crate) fn request_inspection_projection(&mut self) {
        self.inspection_projection_requested = true;
    }

    pub(crate) const fn inspection_projection_requested(&self) -> bool {
        self.inspection_projection_requested
    }

    pub(crate) fn restore(
        &mut self,
        input: &str,
    ) -> Result<RestoredTextWithProvenance, CodecErrorCode> {
        self.snapshot
            .restore_strict_text_with_provenance(input)
            .map_err(map_restore_error)
    }

    pub(crate) fn validate(
        &mut self,
        value: &str,
        authorized_output_ranges: &[Range<usize>],
    ) -> Result<(), CodecErrorCode> {
        self.residual.validate(value, authorized_output_ranges)
    }
}

fn map_restore_error(_error: RestoreError) -> CodecErrorCode {
    CodecErrorCode::RestoreFailedClosed
}

/// Output-coordinate proof retained beside the exact emitted buffer.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct OutputProvenance {
    authorized_output_ranges: Vec<Range<usize>>,
    signed_opaque_ranges: Vec<Range<usize>>,
    occurrence_count: usize,
    final_buffer_verified: bool,
}

impl OutputProvenance {
    #[must_use]
    pub fn authorized_output_ranges(&self) -> &[Range<usize>] {
        &self.authorized_output_ranges
    }

    #[must_use]
    pub fn signed_opaque_ranges(&self) -> &[Range<usize>] {
        &self.signed_opaque_ranges
    }

    #[must_use]
    pub const fn occurrence_count(&self) -> usize {
        self.occurrence_count
    }

    #[must_use]
    pub const fn final_buffer_verified(&self) -> bool {
        self.final_buffer_verified
    }

    pub(crate) fn record_authorized(&mut self, range: Range<usize>) {
        push_coalesced(&mut self.authorized_output_ranges, range);
    }

    pub(crate) fn record_signed(&mut self, range: Range<usize>) {
        push_coalesced(&mut self.signed_opaque_ranges, range);
    }

    pub(crate) fn set_occurrence_count(&mut self, count: usize) {
        self.occurrence_count = count;
    }

    pub(crate) fn mark_final_buffer_verified(&mut self) {
        self.final_buffer_verified = true;
    }
}

fn push_coalesced(ranges: &mut Vec<Range<usize>>, range: Range<usize>) {
    if range.start >= range.end {
        return;
    }
    if let Some(previous) = ranges.last_mut() {
        if range.start <= previous.end {
            previous.end = previous.end.max(range.end);
            return;
        }
    }
    ranges.push(range);
}

/// Crate-private structural projection created lazily from codec-owned proved structure.
pub(crate) struct InspectionStructuralProjectionV1 {
    pub(crate) json_shape: ProjectionAvailabilityV1<JsonShapeSummaryV1>,
    pub(crate) sse_timeline: ProjectionAvailabilityV1<SseTimelineMetaV1>,
}

impl InspectionStructuralProjectionV1 {
    pub(crate) const fn unsupported() -> Self {
        Self {
            json_shape: ProjectionAvailabilityV1::Omitted(
                ProjectionOmissionReasonV1::UnsupportedFormat,
            ),
            sse_timeline: ProjectionAvailabilityV1::Omitted(
                ProjectionOmissionReasonV1::UnsupportedFormat,
            ),
        }
    }

    pub(crate) const fn unavailable(format: WireFormat) -> Self {
        match format {
            WireFormat::Json => Self {
                json_shape: ProjectionAvailabilityV1::Omitted(
                    ProjectionOmissionReasonV1::ProjectionFailedClosed,
                ),
                sse_timeline: ProjectionAvailabilityV1::Omitted(
                    ProjectionOmissionReasonV1::UnsupportedFormat,
                ),
            },
            WireFormat::Sse => Self {
                json_shape: ProjectionAvailabilityV1::Omitted(
                    ProjectionOmissionReasonV1::UnsupportedFormat,
                ),
                sse_timeline: ProjectionAvailabilityV1::Omitted(
                    ProjectionOmissionReasonV1::ProjectionFailedClosed,
                ),
            },
            WireFormat::Ndjson | WireFormat::Utf8Text | WireFormat::Empty => Self {
                json_shape: ProjectionAvailabilityV1::Omitted(
                    ProjectionOmissionReasonV1::UnsupportedFormat,
                ),
                sse_timeline: ProjectionAvailabilityV1::Omitted(
                    ProjectionOmissionReasonV1::UnsupportedFormat,
                ),
            },
        }
    }
}

/// Opaque crate-private parsed facts moved from the codec's existing proof pass.
///
/// These facts are retained only for an immutable startup-selected stage. Turning them into an
/// inspection source/timeline remains inside the `gaze-inspection` build closure, after its real
/// lifecycle pre-projection fence. Proved bytes are never reparsed by the proxy.
pub(crate) enum InspectionParsedFactsV1 {
    AnthropicJson(crate::anthropic::JsonInspectionParsedFactsV1),
    AnthropicSse(crate::anthropic::SseInspectionParsedFactsV1),
}

impl InspectionParsedFactsV1 {
    pub(crate) fn project(self) -> InspectionStructuralProjectionV1 {
        match self {
            Self::AnthropicJson(facts) => facts.project(),
            Self::AnthropicSse(facts) => facts.project(),
        }
    }
}

macro_rules! proved_body {
    ($name:ident) => {
        pub struct $name {
            bytes: Vec<u8>,
            format: WireFormat,
            provenance: OutputProvenance,
            inspection_parsed_facts: Option<InspectionParsedFactsV1>,
            signed_or_encrypted_surface: bool,
        }

        impl $name {
            pub(crate) fn new(
                bytes: Vec<u8>,
                format: WireFormat,
                provenance: OutputProvenance,
            ) -> Self {
                let signed_or_encrypted_surface = !provenance.signed_opaque_ranges().is_empty();
                Self {
                    bytes,
                    format,
                    provenance,
                    inspection_parsed_facts: None,
                    signed_or_encrypted_surface,
                }
            }

            pub(crate) fn new_with_inspection_parsed_facts(
                bytes: Vec<u8>,
                format: WireFormat,
                provenance: OutputProvenance,
                inspection_parsed_facts: InspectionParsedFactsV1,
            ) -> Self {
                let signed_or_encrypted_surface = !provenance.signed_opaque_ranges().is_empty();
                Self {
                    bytes,
                    format,
                    provenance,
                    inspection_parsed_facts: (!signed_or_encrypted_surface)
                        .then_some(inspection_parsed_facts),
                    signed_or_encrypted_surface,
                }
            }

            #[must_use]
            pub fn bytes(&self) -> &[u8] {
                &self.bytes
            }

            #[must_use]
            pub const fn format(&self) -> WireFormat {
                self.format
            }

            #[must_use]
            pub const fn provenance(&self) -> &OutputProvenance {
                &self.provenance
            }

            pub(crate) const fn signed_or_encrypted_surface(&self) -> bool {
                self.signed_or_encrypted_surface
            }

            pub(crate) fn into_inspection_parts(
                self,
            ) -> (Vec<u8>, Option<InspectionParsedFactsV1>, bool) {
                (
                    self.bytes,
                    self.inspection_parsed_facts,
                    self.signed_or_encrypted_surface,
                )
            }

            pub(crate) fn take_inspection_parsed_facts(
                &mut self,
            ) -> Option<InspectionParsedFactsV1> {
                self.inspection_parsed_facts.take()
            }

            #[must_use]
            pub fn into_bytes(self) -> Vec<u8> {
                self.bytes
            }
        }

        impl fmt::Debug for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str(stringify!($name))
            }
        }
    };
}

proved_body!(ProvedRequestBody);
proved_body!(ProvedResponseBody);

/// Object-safe, synchronous, transport-free body codec.
pub trait BodyCodec: Send + Sync + 'static {
    fn protect_request(
        &self,
        input: &[u8],
        ctx: &mut RequestTransformContext<'_>,
    ) -> Result<ProvedRequestBody, CodecError>;

    fn restore_response(
        &self,
        input: &[u8],
        ctx: &mut ResponseTransformContext<'_>,
    ) -> Result<ProvedResponseBody, CodecError>;
}