structured-cms 0.12.0

Borrowed CMS signatures, digital envelopes and timestamps with explicit providers and resource accounting
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
//! Complete common timestamp checks; path/status/policy acceptance stays external.

use super::profile::{
    self, MappedProfileCheckError, ProfileCheckError, ProfileFailure, ProfileInput,
};
use super::{
    AuthorityFacts, ComputedInput, ImprintAgreement, RawInput, RecognitionError, Request,
    RequestAgreement, RequestFields, RequestWindow, RetainedFacts, SignatureError, Timeliness,
    Token, TokenExtension, TokenSignature, TsaIdentity, TsaUsage,
};
use crate::{
    Error, ErrorCode,
    content_source::{ContentError, SourceMap},
    directory, ess,
    provider::{SignatureAnswer, SignatureProvider},
    stream::Source,
    verify,
};
use core::convert::Infallible;
use structured_asn1::{
    Reader,
    memory::{Execution, OwnedVec, Work},
    value::OwnedOid,
};
use structured_pkix::{
    Certificate,
    path::WorkingKey,
    temporal::{Instant, LeapTable},
};

/// Original parsed request and its producing reader, not reconstructed tuples.
pub struct Requested<'a, 'r> {
    /// Complete original request.
    pub request: &'r Request<'a>,
    /// Its own original producing session.
    pub parent: &'r Reader<'a>,
}

/// Explicit caller selection/time facts; this does not select a trusted path.
pub struct CheckContext<'a, 'r> {
    /// Caller-selected candidate, independently subject to trust/path checks.
    pub certificate: &'r Certificate<'a>,
    /// That certificate's own original producing reader.
    pub certificate_parent: &'r Reader<'a>,
    /// Effective key retaining independently established inherited parameters.
    pub key: WorkingKey<'a>,
    /// Complete live request, absent for archived evidence.
    pub requested: Option<Requested<'a, 'r>>,
    /// Explicit UTC correction facts, without implicit clock lookup.
    pub utc: &'r LeapTable<'a>,
    /// Caller-supplied comparison instant, when available.
    pub reference: Option<Instant>,
    /// Caller-established outstanding-imprint uniqueness/window fact.
    pub window: Option<RequestWindow>,
}

/// Scoped execution refusal retaining the actual source/operand and cause.
#[derive(Debug)]
pub enum InfoCheckError<SE, PE, RE> {
    /// Inspection retained schema faults; complete execution did not start.
    Nonconforming {
        /// Original information range, interpreted through the accompanying map.
        span: structured_asn1::Span,
    },
    /// Original CMS execution failed after information syntax preflight.
    Signature(SignatureError<PE>),
    /// Original ESS execution failed after information syntax preflight.
    Ess(ess::BindingError<PE>),
    /// Original token processing/resource refusal.
    Processing(Error),
    /// Source-map retention refusal already located at a physical carrier.
    /// Do not project this offset again as a logical token coordinate.
    Provenance(Error),
    /// Covered-content acquisition or selected digest execution failed.
    Imprint(super::ImprintError<SE, PE>),
    /// Complete request-imprint comparison failed.
    RequestImprint(super::RequestImprintError<PE>),
    /// Request nonce/policy comparison failed.
    RequestField(super::RequestFieldError),
    /// Token/certificate source role and original refusal.
    Authority(super::AuthorityError),
    /// Original extension handler refusal.
    Recognition(RecognitionError<RE>),
}

/// Execution refusal, never a semantic partial success.
#[derive(Debug)]
pub enum CheckError<SE, PE, RE> {
    /// Original envelope/ESS inspection faults prevent complete execution.
    Nonconforming {
        /// Original outer field enclosure, not a resource error.
        span: structured_asn1::Span,
    },
    /// Original outer processing/resource refusal.
    Processing(Error),
    /// Caller supplied a different original SPKI for the selected certificate.
    KeyMismatch {
        /// Honest enclosure of the selected certificate, not a document fault.
        certificate: structured_asn1::Span,
    },
    /// Certificate hint comparison failed, not a mismatch.
    Identifier(directory::Error),
    /// Request source role and original refusal are preserved.
    RequestField(super::RequestFieldError),
    /// Scoped original cause accompanied by independently retained source map.
    Information(ContentError<super::InfoError<InfoCheckError<SE, PE, RE>>>),
}

/// A check in a logical CMS envelope retains its own source context separately
/// from the inner `TSTInfo` map. CMS errors must not use `TSTInfo` coordinates.
#[derive(Debug)]
pub enum MappedCheckError<SE, PE, RE> {
    /// Caller source/session mismatch, refused before map admission or work.
    /// The original operand identifies its reader; no copied map is required.
    Preflight(CheckError<SE, PE, RE>),
    /// Envelope map admission failed at its already physical carrier.
    Provenance(Error),
    /// Original cause and independently retained envelope coordinate context.
    Execution {
        /// Maps the original CMS envelope's coordinates, not inner `TSTInfo`.
        envelope: SourceMap,
        /// Original check cause; source/operand variants select its context.
        source: CheckError<SE, PE, RE>,
    },
}

/// Independently retained cryptographic/time evidence, not a trust verdict.
/// The caller must establish TSA path/status, enforce signed ESS restrictions
/// and apply algorithm/policy permissions before granting product acceptance.
#[derive(Debug)]
pub struct Evidence {
    facts: RetainedFacts,
    source: SourceMap,
}

/// Independent-copy refusal retains the coordinate context of its cause.
#[derive(Debug)]
pub enum EvidenceCopyError {
    /// Map admission failed at its already physical carrier enclosure.
    Provenance(Error),
    /// Fact admission failed in logical/original fact coordinates.
    Facts {
        /// Original refusal, unchanged and distinct from verification failure.
        source: Error,
        /// Independent map surviving source evidence/parser drop.
        context: SourceMap,
    },
}
impl Evidence {
    /// Makes a genuine independently charged copy, without infallible Clone.
    /// Map admission precedes fact copying so an inner refusal can retain its
    /// provenance without allocating while already handling that refusal.
    #[expect(
        clippy::result_large_err,
        reason = "retain admitted source metadata with the original copy refusal; an error box would itself require unavailable capacity"
    )]
    pub fn try_copy_in<W: Work>(&self, work: &W) -> Result<Self, EvidenceCopyError> {
        let context = self
            .source
            .try_copy_in(work)
            .map_err(EvidenceCopyError::Provenance)?;
        match self.facts.try_copy_in(work) {
            Ok(facts) => Ok(Self {
                facts,
                source: context,
            }),
            Err(source) => Err(EvidenceCopyError::Facts { source, context }),
        }
    }
    /// Generation/imprint facts bound to this successfully checked token.
    #[must_use]
    pub fn facts(&self) -> &RetainedFacts {
        &self.facts
    }
    /// Independent original physical projection of logical facts.
    #[must_use]
    pub fn source(&self) -> &SourceMap {
        &self.source
    }
}

/// Common check facts including original ESS validation-set restrictions.
pub struct CheckedTimestamp<'a> {
    /// Actual CMS signature/content or explicit unusable preparation answer.
    pub signature: TokenSignature<'a>,
    /// Selected-certificate hint agreement, not pool uniqueness/trust.
    pub identifier: directory::CertificateAgreement,
    /// Original independent V1/V2 identifiers and signed path restrictions.
    pub ess: ess::SigningAttributes<'a>,
    /// Independent selected-certificate binding answers.
    pub bindings: ess::Bindings,
    /// Required TSA purpose and optional name agreement.
    pub authority: AuthorityFacts,
    /// Complete caller-covered-content agreement.
    pub imprint: ImprintAgreement,
    /// Complete live request-imprint equality, when supplied.
    pub requested_imprint: Option<RequestAgreement>,
    /// Independent requested nonce/policy agreement.
    pub requested_fields: Option<RequestFields>,
    /// Certificate carriage requirement, when requested.
    pub carried: Option<bool>,
    /// Explicit freshness answer, without an implicitly read clock.
    pub timeliness: Timeliness,
    /// Readable Accuracy scalar refusal, without clamping/narrowing.
    pub accuracy_error: Option<super::DeviationError>,
    /// Unknown critical identifiers with independently retained charges.
    pub unknown_critical: OwnedVec<OwnedOid>,
    evidence: Option<Evidence>,
}
impl CheckedTimestamp<'_> {
    /// Moves independently retained evidence out while keeping every original
    /// negative/check fact available to a scoped format adapter. No copy or
    /// second signature/content pass occurs, and mutable public facts still
    /// cannot manufacture evidence.
    pub fn take_evidence(&mut self) -> Option<Evidence> {
        self.evidence.take()
    }
    /// Moves retained evidence without deep copy or another storage charge.
    pub fn into_evidence(self) -> Option<Evidence> {
        self.evidence
    }
    /// Only the checker constructs evidence; editing public facts cannot do so.
    #[must_use]
    pub fn evidence(&self) -> Option<&Evidence> {
        self.evidence.as_ref()
    }
}

struct Information {
    authority: AuthorityFacts,
    imprint: ImprintAgreement,
    requested_imprint: Option<RequestAgreement>,
    requested_fields: Option<RequestFields>,
    timeliness: Timeliness,
    accuracy_error: Option<super::DeviationError>,
    unknown: OwnedVec<OwnedOid>,
    evidence: Option<Evidence>,
}

impl Information {
    fn holds(&self) -> bool {
        self.accuracy_error.is_none()
            && matches!(self.authority.usage, TsaUsage::TimeStampingOnly)
            && matches!(
                self.authority.identity,
                TsaIdentity::Absent | TsaIdentity::Matches
            )
            && self.imprint == ImprintAgreement::Matches
            && self
                .requested_imprint
                .is_none_or(|answer| answer == RequestAgreement::Matches)
            && self
                .requested_fields
                .is_none_or(|fields| fields.nonce != Some(false) && fields.policy != Some(false))
            && self.unknown.is_empty()
            && matches!(
                self.timeliness,
                Timeliness::NotRequested | Timeliness::LocalWindow | Timeliness::RequestNonce
            )
    }
}

struct Inspection<'a, 'r, P, S, R> {
    provider: &'a P,
    context: &'r CheckContext<'a, 'r>,
    covered: &'r mut S,
    recognizes: &'r mut R,
    common_holds: bool,
}

impl<P, S, R> Inspection<'_, '_, P, S, R> {
    fn inspect<'scope, PE, RE>(
        &mut self,
        info: &super::TokenInfo<'scope>,
        inside: &Reader<'scope>,
        source: &SourceMap,
    ) -> Result<Information, InfoCheckError<S::Error, PE, RE>>
    where
        P: for<'input> SignatureProvider<'input, Error = PE>,
        S: ComputedInput<P, PE>,
        R: FnMut(&TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
    {
        let authority = info
            .authority(
                self.context.certificate,
                inside,
                self.context.certificate_parent,
            )
            .map_err(InfoCheckError::Authority)?;
        let requested_fields = self
            .context
            .requested
            .as_ref()
            .map(|request| info.matches_request_fields(request.request, inside, request.parent))
            .transpose()
            .map_err(InfoCheckError::RequestField)?;
        let unknown = unrecognized(info, inside, self.recognizes)?;
        let (imprint, requested_imprint) = match &self.context.requested {
            Some(request) => {
                let (imprint, agreement) = info
                    .imprint()
                    .check_requested_input(
                        request.request.imprint(),
                        self.provider,
                        (inside, request.parent),
                        self.covered,
                    )
                    .map_err(|error| match error {
                        super::RequestedContentError::Request(source) => {
                            InfoCheckError::RequestImprint(source)
                        }
                        super::RequestedContentError::Content(source) => {
                            InfoCheckError::Imprint(source)
                        }
                    })?;
                (imprint, Some(agreement))
            }
            None => (
                info.imprint()
                    .check_input(self.provider, inside, self.covered)
                    .map_err(InfoCheckError::Imprint)?,
                None,
            ),
        };
        let (accuracy, accuracy_error) = match info
            .accuracy()
            .map(super::AccuracyReading::deviation)
            .transpose()
        {
            Ok(accuracy) => (accuracy, None),
            Err(error) => (None, Some(error)),
        };
        let timeliness = super::timeliness(
            info.gen_time(),
            accuracy,
            self.context.utc,
            self.context.reference,
            self.context.requested.is_some(),
            requested_fields.and_then(|fields| fields.nonce),
            self.context.window,
        );
        let mut information = Information {
            authority,
            imprint,
            requested_imprint,
            requested_fields,
            timeliness,
            accuracy_error,
            unknown,
            evidence: None,
        };
        if self.common_holds && !info.has_faults() && information.holds() {
            information.evidence = Some(Evidence {
                facts: info
                    .retain_facts(inside)
                    .map_err(InfoCheckError::Processing)?,
                source: source
                    .try_copy_in(&inside.execution())
                    .map_err(InfoCheckError::Provenance)?,
            });
        }
        Ok(information)
    }
}

fn unrecognized<SE, PE, RE>(
    info: &super::TokenInfo<'_>,
    inside: &Reader<'_>,
    recognizes: &mut impl FnMut(&TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
) -> Result<OwnedVec<OwnedOid>, InfoCheckError<SE, PE, RE>> {
    let scoped = inside.execution();
    let mut unknown = scoped.vector();
    if let Some(extensions) = info.extensions() {
        for kind in extensions
            .unrecognized_critical(inside, recognizes)
            .map_err(InfoCheckError::Recognition)?
        {
            let owned = OwnedOid::from_oid_in(kind, &scoped).map_err(|reason| {
                InfoCheckError::Processing(Error::resource(
                    reason,
                    "tstInfo.extensions",
                    extensions.span().start,
                ))
            })?;
            unknown.try_push(owned).map_err(|reason| {
                InfoCheckError::Processing(Error::resource(
                    reason,
                    "tstInfo.extensions",
                    extensions.span().start,
                ))
            })?;
        }
    }
    Ok(unknown.into_owned())
}

fn common_holds(
    signature: &TokenSignature<'_>,
    bindings: ess::Bindings,
    identifier: &directory::CertificateAgreement,
    carried: Option<bool>,
) -> bool {
    matches!(signature, TokenSignature::Checked(checked)
        if checked.signature() == Some(SignatureAnswer::Valid)
        && matches!(checked.content(), verify::ContentAgreement::Matches | verify::ContentAgreement::Direct))
        && (bindings.v1 == Some(ess::Binding::Matches)
            || bindings.v2 == Some(ess::Binding::Matches))
        && bindings
            .v1
            .is_none_or(|binding| binding == ess::Binding::Matches)
        && bindings
            .v2
            .is_none_or(|binding| binding == ess::Binding::Matches)
        && matches!(identifier, directory::CertificateAgreement::Matches)
        && carried != Some(false)
}

impl<'doc> Token<'doc> {
    /// Checks original CMS, ESS, TSA, content, request and time together.
    ///
    /// Caller path/status/policy and signed ESS restriction enforcement remain
    /// external. Semantic negatives remain facts, never evidence. Processing,
    /// provider and source refusals abort. Provider errors are source-independent
    /// so a temporary joined information buffer cannot escape in their type.
    /// Optional rejection of unlisted digest algorithms (RFC5652 §5.3) belongs
    /// to caller policy. Evidence does not assert that every sender SHOULD or
    /// application-profile requirement was satisfied.
    #[expect(
        clippy::result_large_err,
        reason = "preserve original cause and accounted source context without allocating on refusal"
    )]
    pub fn check<'a, P, S: Source, PE, RE>(
        &'a self,
        provider: &'a P,
        parent: &Reader<'a>,
        context: &CheckContext<'a, '_>,
        covered: &mut S,
        recognizes: impl FnMut(&TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
    ) -> Result<CheckedTimestamp<'a>, CheckError<S::Error, PE, RE>>
    where
        'doc: 'a,
        P: for<'scope> SignatureProvider<'scope, Error = PE>,
    {
        self.check_with_profile(provider, parent, context, covered, recognizes, |_| {
            Ok::<(), ProfileFailure<Infallible>>(())
        })
        .map_err(ProfileCheckError::into_common)
    }

    /// Checks the same common timestamp once, with a scoped profile inspection
    /// before any ESS binding, provider resolution, signature/content execution
    /// or extension-recognition callback. Original syntax faults still refuse
    /// first. The profile sees original fields, both producing readers and
    /// their coordinate contexts; it must fund its own work before execution.
    /// Refusal is terminal and cannot borrow a temporary information buffer.
    /// The common core does not roll back external side effects of the profile.
    #[expect(
        clippy::result_large_err,
        reason = "keep opaque common/profile refusal and its source context without allocating while returning an error"
    )]
    pub fn check_with_profile<'a, P, S: Source, PE, RE, FE>(
        &'a self,
        provider: &'a P,
        parent: &Reader<'a>,
        context: &CheckContext<'a, '_>,
        covered: &mut S,
        recognizes: impl FnMut(&TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
        profile: impl for<'view, 'scope> FnOnce(
            ProfileInput<'view, 'doc, 'a, 'scope>,
        ) -> Result<(), ProfileFailure<FE>>,
    ) -> Result<CheckedTimestamp<'a>, ProfileCheckError<S::Error, PE, RE, FE>>
    where
        'doc: 'a,
        P: for<'scope> SignatureProvider<'scope, Error = PE>,
    {
        self.check_input_with_profile(
            provider,
            parent,
            context,
            &mut RawInput::new(covered),
            recognizes,
            profile,
        )
    }

    /// Same complete timestamp, with a computed imprint rather than raw bytes.
    /// Common CMS/ESS/authority/time/profile checks execute once; only the
    /// recipe defines the normative hash input. A closed completed comparison
    /// is required before mathematical timestamp evidence can be retained.
    #[expect(
        clippy::result_large_err,
        reason = "retain opaque input/provider/profile failures and original source maps"
    )]
    pub fn check_input_with_profile<'a, P, I, PE, RE, FE>(
        &'a self,
        provider: &'a P,
        parent: &Reader<'a>,
        context: &CheckContext<'a, '_>,
        covered: &mut I,
        recognizes: impl FnMut(&TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
        profile: impl for<'view, 'scope> FnOnce(
            ProfileInput<'view, 'doc, 'a, 'scope>,
        ) -> Result<(), ProfileFailure<FE>>,
    ) -> Result<CheckedTimestamp<'a>, ProfileCheckError<I::Error, PE, RE, FE>>
    where
        'doc: 'a,
        P: for<'scope> SignatureProvider<'scope, Error = PE>,
        I: ComputedInput<P, PE>,
    {
        self.check_in(
            provider,
            (parent, None),
            context,
            covered,
            recognizes,
            profile,
        )
    }

    /// Checks a token decoded in another joined source using the same core.
    /// The map corresponds to its producing envelope reader. Child `TSTInfo`
    /// maps are composed to physical fragments; outer CMS errors separately
    /// retain the envelope map instead of borrowing a temporary joined buffer.
    #[expect(
        clippy::result_large_err,
        reason = "preserve both source frames and original opaque refusal without a fallible error box"
    )]
    pub fn check_mapped<'a, P, S: Source, PE, RE>(
        &'a self,
        provider: &'a P,
        source: (&Reader<'a>, &SourceMap),
        context: &CheckContext<'a, '_>,
        covered: &mut S,
        recognizes: impl FnMut(&TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
    ) -> Result<CheckedTimestamp<'a>, MappedCheckError<S::Error, PE, RE>>
    where
        'doc: 'a,
        P: for<'scope> SignatureProvider<'scope, Error = PE>,
    {
        self.check_mapped_with_profile(provider, source, context, covered, recognizes, |_| {
            Ok::<(), ProfileFailure<Infallible>>(())
        })
        .map_err(MappedProfileCheckError::into_common)
    }

    /// Same profile/core kernel for a logically joined CMS envelope. Both
    /// independent maps survive refusal; an outer profile location must use
    /// the envelope map rather than the inner information map. Reader/session
    /// misuse is refused before map admission or profile/provider dispatch.
    #[expect(
        clippy::result_large_err,
        reason = "preserve both independently retained source frames and the original opaque refusal without a fallible error allocation"
    )]
    pub fn check_mapped_with_profile<'a, P, S: Source, PE, RE, FE>(
        &'a self,
        provider: &'a P,
        source: (&Reader<'a>, &SourceMap),
        context: &CheckContext<'a, '_>,
        covered: &mut S,
        recognizes: impl FnMut(&TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
        profile: impl for<'view, 'scope> FnOnce(
            ProfileInput<'view, 'doc, 'a, 'scope>,
        ) -> Result<(), ProfileFailure<FE>>,
    ) -> Result<CheckedTimestamp<'a>, MappedProfileCheckError<S::Error, PE, RE, FE>>
    where
        'doc: 'a,
        P: for<'scope> SignatureProvider<'scope, Error = PE>,
    {
        self.check_mapped_input_with_profile(
            provider,
            source,
            context,
            &mut RawInput::new(covered),
            recognizes,
            profile,
        )
    }

    /// Computed input with the same independent envelope/information source
    /// maps as the raw path. Foreign sessions refuse before profile dispatch.
    #[expect(
        clippy::result_large_err,
        reason = "preserve both source frames and opaque refusal without allocating on failure"
    )]
    pub fn check_mapped_input_with_profile<'a, P, I, PE, RE, FE>(
        &'a self,
        provider: &'a P,
        source: (&Reader<'a>, &SourceMap),
        context: &CheckContext<'a, '_>,
        covered: &mut I,
        recognizes: impl FnMut(&TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
        profile: impl for<'view, 'scope> FnOnce(
            ProfileInput<'view, 'doc, 'a, 'scope>,
        ) -> Result<(), ProfileFailure<FE>>,
    ) -> Result<CheckedTimestamp<'a>, MappedProfileCheckError<I::Error, PE, RE, FE>>
    where
        'doc: 'a,
        P: for<'scope> SignatureProvider<'scope, Error = PE>,
        I: ComputedInput<P, PE>,
    {
        let (parent, source) = source;
        preflight_sessions(self, parent, context)
            .map_err(|error| MappedProfileCheckError::Preflight(error.into()))?;
        let envelope = source
            .try_copy_in(&parent.execution())
            .map_err(MappedProfileCheckError::Provenance)?;
        self.check_in(
            provider,
            (parent, Some(source)),
            context,
            covered,
            recognizes,
            profile,
        )
        .map_err(|source| MappedProfileCheckError::Execution { envelope, source })
    }

    #[expect(
        clippy::result_large_err,
        reason = "retain original cause and accounted source context on refusal"
    )]
    fn check_in<'a, P, S, PE, RE, FE>(
        &'a self,
        provider: &'a P,
        origin: (&Reader<'a>, Option<&SourceMap>),
        context: &CheckContext<'a, '_>,
        covered: &mut S,
        mut recognizes: impl FnMut(&TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
        profile: impl for<'view, 'scope> FnOnce(
            ProfileInput<'view, 'doc, 'a, 'scope>,
        ) -> Result<(), ProfileFailure<FE>>,
    ) -> Result<CheckedTimestamp<'a>, ProfileCheckError<S::Error, PE, RE, FE>>
    where
        'doc: 'a,
        P: for<'scope> SignatureProvider<'scope, Error = PE>,
        S: ComputedInput<P, PE>,
    {
        let (parent, source) = origin;
        preflight(self, parent, context).map_err(CheckError::from)?;
        let certificate = context.certificate;
        let identifier =
            directory::matches_certificate_in(self.signer().sid(), certificate, parent)
                .map_err(CheckError::Identifier)?;
        let ess =
            ess::SigningAttributes::read(self.signer(), parent).map_err(CheckError::Processing)?;
        let carried = context
            .requested
            .as_ref()
            .map(|requested| {
                self.matches_cert_req(
                    requested.request,
                    Some(certificate),
                    parent,
                    requested.parent,
                )
            })
            .transpose()
            .map_err(CheckError::RequestField)?;
        if !self.faults().is_empty()
            || !self.message().faults().is_empty()
            || !self.signer().faults().is_empty()
            || !ess.faults().is_empty()
            || ess.v1().is_some_and(|reading| !reading.faults().is_empty())
            || ess.v2().is_some_and(|reading| !reading.faults().is_empty())
        {
            return Err(CheckError::Nonconforming {
                span: self.message().span(),
            }
            .into());
        }
        let inspect = |info: &super::TokenInfo<'_>,
                       inside: &Reader<'_>,
                       information: &SourceMap|
         -> Result<_, profile::InformationFailure<S::Error, PE, RE, FE>> {
            if info.has_faults() {
                return Err(InfoCheckError::Nonconforming { span: info.span() }.into());
            }
            profile(ProfileInput {
                token: self,
                parent,
                envelope: source,
                ess: &ess,
                info,
                reader: inside,
                source: information,
            })
            .map_err(profile::InformationFailure::Profile)?;
            let bindings = ess
                .bind_certificate(provider, certificate, parent)
                .map_err(InfoCheckError::Ess)?;
            let signature = self
                .check_signature(provider, context.key, parent)
                .map_err(InfoCheckError::Signature)?;
            let common_holds = common_holds(&signature, bindings, &identifier, carried);
            let mut inspection = Inspection {
                provider,
                context,
                covered,
                recognizes: &mut recognizes,
                common_holds,
            };
            let checked = inspection.inspect(info, inside, information)?;
            Ok((signature, bindings, checked))
        };
        let (signature, bindings, information) = match source {
            Some(source) => self.with_info_mapped(parent, source, inspect),
            None => self.with_info(parent, inspect),
        }
        .map_err(profile::information_error)?;
        Ok(CheckedTimestamp {
            signature,
            identifier,
            ess,
            bindings,
            authority: information.authority,
            imprint: information.imprint,
            requested_imprint: information.requested_imprint,
            requested_fields: information.requested_fields,
            carried,
            timeliness: information.timeliness,
            accuracy_error: information.accuracy_error,
            unknown_critical: information.unknown,
            evidence: information.evidence,
        })
    }
}

enum PreflightError {
    Processing(Error),
    Requested(super::RequestFieldError),
    KeyMismatch(structured_asn1::Span),
}

impl<SE, PE, RE> From<PreflightError> for CheckError<SE, PE, RE> {
    fn from(error: PreflightError) -> Self {
        match error {
            PreflightError::Processing(error) => Self::Processing(error),
            PreflightError::Requested(error) => Self::RequestField(error),
            PreflightError::KeyMismatch(certificate) => Self::KeyMismatch { certificate },
        }
    }
}

fn preflight(
    token: &Token<'_>,
    parent: &Reader<'_>,
    context: &CheckContext<'_, '_>,
) -> Result<(), PreflightError> {
    preflight_sessions(token, parent, context)?;
    let certificate = context.certificate;
    let written = certificate.tbs().public_key().as_bytes();
    let key = context.key.key().as_bytes();
    let length = u64::try_from(written.len().max(key.len()))
        .ok()
        .and_then(|length| length.checked_add(1))
        .ok_or_else(|| {
            PreflightError::Processing(Error::schema(
                ErrorCode::LengthOverflow,
                "certificate.subjectPublicKeyInfo",
                certificate.span().start,
            ))
        })?;
    parent.execution().charge_work(length).map_err(|reason| {
        PreflightError::Processing(Error::resource(
            reason,
            "certificate.subjectPublicKeyInfo",
            certificate.span().start,
        ))
    })?;
    if written != key {
        return Err(PreflightError::KeyMismatch(certificate.span()));
    }
    Ok(())
}

fn preflight_sessions(
    token: &Token<'_>,
    parent: &Reader<'_>,
    context: &CheckContext<'_, '_>,
) -> Result<(), PreflightError> {
    token
        .signer()
        .require_session(parent, "signerInfo")
        .map_err(PreflightError::Processing)?;
    let certificate = context.certificate;
    if !certificate
        .tbs()
        .public_key()
        .algorithm()
        .same_session(context.certificate_parent)
    {
        return Err(PreflightError::Processing(Error::pkix(
            structured_pkix::Error::new(
                structured_pkix::ErrorCode::ForeignReader,
                "certificate",
                certificate.span().start,
            ),
        )));
    }
    if let Some(requested) = &context.requested
        && !requested.request.same_session(requested.parent)
    {
        return Err(PreflightError::Requested(super::RequestFieldError {
            operand: super::ImprintOperand::Requested,
            source: Error::pkix(structured_pkix::Error::new(
                structured_pkix::ErrorCode::ForeignReader,
                "timeStampReq",
                requested.request.span().start,
            )),
        }));
    }
    Ok(())
}