1use crate::basic::{BindError, PathRestriction};
6use crate::prepare::{Preparation, Timestamp};
7use crate::source::{DocumentId, Node};
8use crate::{Cades, Error, ISSUER};
9use structured_asn1::{
10 Reader,
11 memory::{Execution, OwnedVec, Work},
12 value::OwnedOid,
13};
14use structured_cms::{
15 octets::Piece,
16 provider::{SignatureAnswer, SignatureProvider},
17 stream::{Receiver, Refused, Source},
18 timestamp::{
19 self as tsp, CheckContext, ProfileCheckError, ProfileFailure, ProfileSource, Token,
20 },
21 verify::ContentAgreement,
22};
23use structured_ltv::{
24 pki::CheckedPath,
25 timestamp::{CheckedActor, Purpose, Verified},
26};
27use structured_pkix::temporal::LeapTable;
28
29pub struct CheckTime<'a, 'document> {
34 pub utc: &'a LeapTable<'document>,
36 pub reference: Option<structured_pkix::temporal::Instant>,
38}
39
40mod archive;
41pub mod historical;
42pub mod references;
43pub(crate) mod requirements;
44pub use archive::{
45 ArchiveCheckError, ArchiveChecked, ArchiveError, ArchiveStreamError, ArchiveView, NoDetached,
46 ScopeError as ArchiveScopeError,
47};
48
49#[derive(Debug)]
52pub enum VisitError<E> {
53 Processing(Error),
55 Unreadable {
57 property: Node,
59 },
60 Callback(E),
62}
63
64pub fn with_token<'m, 'd, R, E>(
67 prepared: &Preparation<'m, 'd>,
68 ordinal: usize,
69 operation: &Reader<'d>,
70 visitor: impl for<'scope> FnOnce(Context<'scope, 'm, 'd>) -> Result<R, E>,
71) -> Result<R, VisitError<E>> {
72 prepared
73 .document()
74 .message()
75 .require_session(operation, "cades.timestamp")
76 .map_err(|cause| VisitError::Processing(Error::Cms(cause)))?;
77 operation
78 .charge(1)
79 .map_err(|cause| VisitError::Processing(Error::encoding(cause, "cades.timestamp")))?;
80 let entry = prepared.timestamps().get(ordinal).ok_or_else(|| {
81 VisitError::Processing(Error::Foreign {
82 at: prepared.signer().span().start,
83 })
84 })?;
85 let source = entry.source().ok_or(VisitError::Unreadable {
86 property: entry.property(),
87 })?;
88 let reader = source
89 .reader_in(operation)
90 .map_err(VisitError::Processing)?;
91 let Some(model) = prepared.parsed.token(ordinal) else {
92 return Err(VisitError::Unreadable {
93 property: entry.property(),
94 });
95 };
96 let token = model.token;
97 visitor(Context {
98 prepared,
99 ordinal,
100 entry,
101 token,
102 reader: &reader,
103 })
104 .map_err(VisitError::Callback)
105}
106
107pub struct Context<'scope, 'model, 'document> {
110 prepared: &'scope Preparation<'model, 'document>,
111 ordinal: usize,
112 entry: &'scope Timestamp<'document>,
113 token: &'scope Token<'document>,
114 reader: &'scope Reader<'document>,
115}
116
117pub(crate) fn with_existing<'m, 'd, R, E>(
118 prepared: &Preparation<'m, 'd>,
119 ordinal: usize,
120 token: &Token<'d>,
121 operation: &Reader<'d>,
122 visitor: impl for<'scope> FnOnce(Context<'scope, 'm, 'd>) -> Result<R, E>,
123) -> Result<R, VisitError<E>> {
124 prepared
125 .document()
126 .message()
127 .require_session(operation, "cades.timestamp")
128 .map_err(|cause| VisitError::Processing(Error::Cms(cause)))?;
129 operation
130 .charge(1)
131 .map_err(|cause| VisitError::Processing(Error::encoding(cause, "cades.timestamp")))?;
132 let entry = prepared.timestamps().get(ordinal).ok_or_else(|| {
133 VisitError::Processing(Error::Foreign {
134 at: prepared.signer().span().start,
135 })
136 })?;
137 let source = entry.source().ok_or(VisitError::Unreadable {
138 property: entry.property(),
139 })?;
140 let reader = source
141 .reader_in(operation)
142 .map_err(VisitError::Processing)?;
143 visitor(Context {
144 prepared,
145 ordinal,
146 entry,
147 token,
148 reader: &reader,
149 })
150 .map_err(VisitError::Callback)
151}
152
153#[derive(Debug)]
155pub enum Signature {
156 Checked {
158 content: ContentAgreement,
160 signature: Option<SignatureAnswer>,
162 },
163 Unsupported(structured_cms::prepare::Part),
165 Malformed(structured_cms::Error),
167}
168
169pub struct Checked<'model, 'document, 'path> {
173 pub signature: Signature,
175 pub identifier: structured_cms::directory::CertificateAgreement,
177 pub bindings: structured_cms::ess::Bindings,
179 pub authority: tsp::AuthorityFacts,
181 pub imprint: tsp::ImprintAgreement,
183 pub accuracy: Option<tsp::DeviationError>,
185 pub timeliness: tsp::Timeliness,
187 pub unknown_critical: OwnedVec<OwnedOid>,
189 pub restrictions: PathRestriction,
191 actor: Option<CheckedActor<'path, 'document, Node, DocumentId<'model, 'document>, (), Cades>>,
192}
193
194impl<'m, 'd, 'p> Checked<'m, 'd, 'p> {
195 #[must_use]
197 pub fn actor(&self) -> Option<&CheckedActor<'p, 'd, Node, DocumentId<'m, 'd>, (), Cades>> {
198 self.actor.as_ref()
199 }
200 #[must_use]
202 pub fn into_actor(self) -> Option<CheckedActor<'p, 'd, Node, DocumentId<'m, 'd>, (), Cades>> {
203 self.actor
204 }
205}
206
207#[derive(Debug)]
209pub enum InputError<E> {
210 Detached(E),
212 Carried(structured_cms::octets::SourceError),
214 Resource(structured_asn1::memory::MemoryError),
216 Receiver(Refused),
218}
219
220#[derive(Debug)]
222pub enum CheckError<SE, PE, RE, FE = core::convert::Infallible> {
223 ForbiddenDigest {
225 at: u64,
227 },
228 Selection(Error),
231 Material {
234 property: Node,
236 },
237 Check(ProfileCheckError<SE, PE, RE, ProfileError<PE, FE>>),
239}
240
241#[derive(Debug)]
243pub enum ProfileError<PE, E> {
244 Cades(structured_cms::Error),
246 Restriction(BindError<PE>),
248 Md5 {
250 at: u64,
252 },
253 Input(E),
255}
256
257struct Pieces<'s, 'd>(&'s [Piece<'d>]);
258impl Source for Pieces<'_, '_> {
259 type Error = InputError<core::convert::Infallible>;
260 fn stream<W: Work>(
261 &mut self,
262 receiver: &mut impl Receiver,
263 work: &W,
264 ) -> Result<(), Self::Error> {
265 for piece in self.0 {
266 work.charge_work(1).map_err(InputError::Resource)?;
267 receiver
268 .write(piece.as_bytes())
269 .map_err(InputError::Receiver)?;
270 }
271 Ok(())
272 }
273}
274
275pub(crate) enum ContentInput<'s, 'd, S> {
276 Carried(&'s structured_cms::Octets<'d>),
277 Counter(&'s [Piece<'d>]),
278 Detached(&'s mut S),
279}
280impl<S: Source> Source for ContentInput<'_, '_, S> {
281 type Error = InputError<S::Error>;
282 fn stream<W: Work>(
283 &mut self,
284 receiver: &mut impl Receiver,
285 work: &W,
286 ) -> Result<(), Self::Error> {
287 match self {
288 Self::Carried(source) => source.stream(receiver, work).map_err(InputError::Carried),
289 Self::Detached(source) => source.stream(receiver, work).map_err(InputError::Detached),
290 Self::Counter(pieces) => {
291 for piece in *pieces {
292 work.charge_work(1).map_err(InputError::Resource)?;
293 receiver
294 .write(piece.as_bytes())
295 .map_err(InputError::Receiver)?;
296 }
297 Ok(())
298 }
299 }
300 }
301}
302
303impl<'m, 'd> Context<'_, 'm, 'd> {
304 #[must_use]
307 pub fn properties(&self) -> Option<&crate::properties::Properties<'d>> {
308 self.prepared.parsed.token(self.ordinal)?.properties
309 }
310 #[must_use]
312 pub fn token(&self) -> &Token<'d> {
313 self.token
314 }
315 #[must_use]
317 pub fn reader(&self) -> &Reader<'d> {
318 self.reader
319 }
320
321 #[expect(
326 clippy::result_large_err,
327 reason = "carried-content failures retain original envelope/information maps without allocating while reporting resource refusal"
328 )]
329 pub fn check_content<'a, 'p, P, PE, RE>(
330 &'a self,
331 provider: &'a P,
332 path: &'p CheckedPath<'d>,
333 certificate_parent: &Reader<'d>,
334 time: &CheckTime<'_, 'd>,
335 recognizes: impl FnMut(&tsp::TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
336 ) -> Result<Checked<'m, 'd, 'p>, CheckError<InputError<core::convert::Infallible>, PE, RE>>
337 where
338 P: for<'scope> SignatureProvider<'scope, Error = PE>,
339 {
340 if self.entry.purpose() != Purpose::Content {
341 return Err(CheckError::Selection(Error::Foreign {
342 at: self.entry.property().span().start,
343 }));
344 }
345 let original = if let Some(pieces) = self
346 .prepared
347 .counter_content_input(self.ordinal, self.reader)
348 .map_err(CheckError::Selection)?
349 {
350 ContentInput::<NoDetached>::Counter(pieces)
351 } else {
352 let source = self
353 .prepared
354 .document()
355 .message()
356 .content()
357 .content()
358 .ok_or_else(|| {
359 CheckError::Selection(Error::Foreign {
360 at: self.entry.property().span().start,
361 })
362 })?;
363 ContentInput::Carried(source)
364 };
365 self.check(
366 provider,
367 path,
368 certificate_parent,
369 time,
370 &mut { original },
371 recognizes,
372 )
373 }
374
375 #[expect(
378 clippy::result_large_err,
379 reason = "detached acquisition cause and both original source maps must survive the failed pass without a new allocation"
380 )]
381 pub fn check_detached_content<'a, 'p, P, S: Source, PE, RE>(
382 &'a self,
383 provider: &'a P,
384 path: &'p CheckedPath<'d>,
385 certificate_parent: &Reader<'d>,
386 time: &CheckTime<'_, 'd>,
387 detached: &mut S,
388 recognizes: impl FnMut(&tsp::TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
389 ) -> Result<Checked<'m, 'd, 'p>, CheckError<InputError<S::Error>, PE, RE>>
390 where
391 P: for<'scope> SignatureProvider<'scope, Error = PE>,
392 {
393 if self.entry.purpose() != Purpose::Content
394 || self.entry.owner() != Node::of(self.prepared.signer().span())
395 || !self.prepared.document().message().content().is_detached()
396 {
397 return Err(CheckError::Selection(Error::Foreign {
398 at: self.entry.property().span().start,
399 }));
400 }
401 self.check(
402 provider,
403 path,
404 certificate_parent,
405 time,
406 &mut ContentInput::Detached(detached),
407 recognizes,
408 )
409 }
410
411 #[expect(
417 clippy::result_large_err,
418 reason = "original signature-input and nested token refusals carry their source maps even on memory exhaustion"
419 )]
420 pub fn check_signature<'a, 'p, P, PE, RE>(
421 &'a self,
422 provider: &'a P,
423 path: &'p CheckedPath<'d>,
424 certificate_parent: &Reader<'d>,
425 time: &CheckTime<'_, 'd>,
426 recognizes: impl FnMut(&tsp::TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
427 ) -> Result<Checked<'m, 'd, 'p>, CheckError<InputError<core::convert::Infallible>, PE, RE>>
428 where
429 P: for<'scope> SignatureProvider<'scope, Error = PE>,
430 {
431 if self.entry.purpose() != Purpose::Signature {
432 return Err(CheckError::Selection(Error::Foreign {
433 at: self.entry.property().span().start,
434 }));
435 }
436 let pieces = self
437 .prepared
438 .signature_input(self.ordinal, self.reader)
439 .map_err(CheckError::Selection)?
440 .ok_or_else(|| {
441 CheckError::Selection(Error::Foreign {
442 at: self.entry.property().span().start,
443 })
444 })?;
445 self.check(
446 provider,
447 path,
448 certificate_parent,
449 time,
450 &mut Pieces(pieces),
451 recognizes,
452 )
453 }
454
455 #[expect(
456 clippy::result_large_err,
457 reason = "dispatch preserves the complete mapped refusal from the one common profile check"
458 )]
459 fn check<'a, 'p, P, S: Source, PE, RE>(
460 &'a self,
461 provider: &'a P,
462 path: &'p CheckedPath<'d>,
463 certificate_parent: &Reader<'d>,
464 time: &CheckTime<'_, 'd>,
465 covered: &mut S,
466 recognizes: impl FnMut(&tsp::TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
467 ) -> Result<Checked<'m, 'd, 'p>, CheckError<S::Error, PE, RE>>
468 where
469 P: for<'scope> SignatureProvider<'scope, Error = PE>,
470 {
471 self.check_profile(
472 provider,
473 path,
474 certificate_parent,
475 time,
476 covered,
477 (recognizes, |_| {
478 Ok::<(), ProfileFailure<core::convert::Infallible>>(())
479 }),
480 )
481 }
482
483 #[expect(
484 clippy::result_large_err,
485 reason = "the shared profile refusal owns envelope and information provenance; boxing during refusal would require additional admitted storage"
486 )]
487 fn check_profile<'a, 'p, P, S: Source, PE, RE, FE>(
488 &'a self,
489 provider: &'a P,
490 path: &'p CheckedPath<'d>,
491 certificate_parent: &Reader<'d>,
492 time: &CheckTime<'_, 'd>,
493 covered: &mut S,
494 callbacks: (
495 impl FnMut(&tsp::TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
496 impl for<'view, 'scope> FnOnce(
497 tsp::ProfileInput<'view, 'd, 'a, 'scope>,
498 ) -> Result<(), ProfileFailure<FE>>,
499 ),
500 ) -> Result<Checked<'m, 'd, 'p>, CheckError<S::Error, PE, RE, FE>>
501 where
502 P: for<'scope> SignatureProvider<'scope, Error = PE>,
503 {
504 self.check_computed_profile(
505 provider,
506 path,
507 certificate_parent,
508 time,
509 &mut tsp::RawInput::new(covered),
510 callbacks,
511 )
512 }
513
514 #[expect(
515 clippy::result_large_err,
516 reason = "mapped original causes remain unboxed on an exhausted account"
517 )]
518 fn check_computed_profile<'a, 'p, P, S, PE, RE, FE>(
519 &'a self,
520 provider: &'a P,
521 path: &'p CheckedPath<'d>,
522 certificate_parent: &Reader<'d>,
523 time: &CheckTime<'_, 'd>,
524 covered: &mut S,
525 callbacks: (
526 impl FnMut(&tsp::TokenExtension<'_>, &Execution<'_>) -> Result<bool, RE>,
527 impl for<'view, 'scope> FnOnce(
528 tsp::ProfileInput<'view, 'd, 'a, 'scope>,
529 ) -> Result<(), ProfileFailure<FE>>,
530 ),
531 ) -> Result<Checked<'m, 'd, 'p>, CheckError<S::Error, PE, RE, FE>>
532 where
533 P: for<'scope> SignatureProvider<'scope, Error = PE>,
534 S: tsp::ComputedInput<P, PE>,
535 {
536 let (recognizes, profile) = callbacks;
537 if self
538 .properties()
539 .is_some_and(|properties| !properties.faults().is_empty())
540 {
541 return Err(CheckError::Material {
542 property: self.entry.property(),
543 });
544 }
545 let digest = self.token.signer().digest_algorithm();
546 self.reader
547 .charge(1 + digest.algorithm().as_bytes().len().min(8) as u64)
548 .map_err(|cause| {
549 CheckError::Selection(Error::encoding(cause, "cades.timestamp.digestAlgorithm"))
550 })?;
551 if digest.algorithm()
555 == structured_asn1::Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 2, 5])
556 {
557 return Err(CheckError::ForbiddenDigest {
558 at: digest.offset(),
559 });
560 }
561 let Some(target) = path.members().last() else {
562 return Err(CheckError::Selection(Error::Foreign {
563 at: self.entry.property().span().start,
564 }));
565 };
566 let certificate = target.certificate();
567 let key = target.key();
568 let selection = CheckContext {
569 certificate,
570 certificate_parent,
571 key,
572 requested: None,
573 utc: time.utc,
574 reference: time.reference,
575 window: None,
576 };
577 let restriction = core::cell::Cell::new(PathRestriction::Unproven);
578 let checked = self
579 .token
580 .check_input_with_profile(
581 provider,
582 self.reader,
583 &selection,
584 covered,
585 recognizes,
586 |input| {
587 if self.entry.purpose() == Purpose::Archive
588 && self.entry.preservation_kind().is_none()
589 {
590 Self::archive_profile(&input)?;
591 }
592 restriction.set(Self::profile_rules(&input, path, provider)?);
593 profile(input).map_err(|cause| ProfileFailure {
594 source: cause.source,
595 cause: ProfileError::Input(cause.cause),
596 })
597 },
598 )
599 .map_err(CheckError::Check)?;
600 Ok(self.checked(checked, restriction.get(), certificate, key))
601 }
602 pub(crate) fn checked<'p>(
603 &self,
604 mut checked: tsp::CheckedTimestamp<'_>,
605 restriction: PathRestriction,
606 certificate: &'p structured_pkix::Certificate<'d>,
607 key: structured_pkix::path::WorkingKey<'d>,
608 ) -> Checked<'m, 'd, 'p> {
609 let actor = match checked.take_evidence() {
610 Some(evidence)
611 if matches!(
612 restriction,
613 PathRestriction::Unstated | PathRestriction::Matches
614 ) =>
615 {
616 let verified = Verified::new(
617 ISSUER,
618 self.prepared.document().locate(
619 self.entry
620 .value()
621 .expect("with_token requires original value")
622 .span(),
623 ),
624 self.entry.owner(),
625 self.entry.property(),
626 self.entry.purpose(),
627 evidence,
628 );
629 Some(CheckedActor::new(ISSUER, verified, certificate, key))
630 }
631 _ => None,
632 };
633 let signature = match checked.signature {
634 tsp::TokenSignature::Checked(value) => {
635 let (_, _, content, signature) = value.into_parts();
636 Signature::Checked { content, signature }
637 }
638 tsp::TokenSignature::Unsupported(part) => Signature::Unsupported(part),
639 tsp::TokenSignature::Malformed(cause) => Signature::Malformed(cause),
640 };
641 Checked {
642 signature,
643 identifier: checked.identifier,
644 bindings: checked.bindings,
645 authority: checked.authority,
646 imprint: checked.imprint,
647 accuracy: checked.accuracy_error,
648 timeliness: checked.timeliness,
649 unknown_critical: checked.unknown_critical,
650 restrictions: restriction,
651 actor,
652 }
653 }
654 fn archive_profile<PE, FE>(
655 input: &tsp::ProfileInput<'_, 'd, '_, '_>,
656 ) -> Result<(), ProfileFailure<ProfileError<PE, FE>>> {
657 let faults = structured_cms::cades::findings_from_reading(
662 input.token.signer(),
663 structured_cms::cades::Role::ArchiveTimestamp,
664 input.ess,
665 input.parent,
666 )
667 .map_err(|cause| ProfileFailure {
668 source: ProfileSource::Envelope,
669 cause: ProfileError::Cades(cause),
670 })?;
671 if let Some(cause) = faults.into_iter().next() {
672 return Err(ProfileFailure {
673 source: ProfileSource::Envelope,
674 cause: ProfileError::Cades(cause),
675 });
676 }
677 Ok(())
678 }
679 pub(crate) fn profile_rules<'a, P, PE, FE>(
680 input: &tsp::ProfileInput<'_, 'd, 'a, '_>,
681 path: &CheckedPath<'d>,
682 provider: &'a P,
683 ) -> Result<PathRestriction, ProfileFailure<ProfileError<PE, FE>>>
684 where
685 P: for<'scope> SignatureProvider<'scope, Error = PE>,
686 {
687 let md5 = structured_asn1::Oid::from_bytes(&[42, 134, 72, 134, 247, 13, 2, 5]);
690 for attribute in [input.ess.v1(), input.ess.v2()].into_iter().flatten() {
691 for certificate in attribute.identifiers() {
692 input.parent.charge(1).map_err(|cause| ProfileFailure {
693 source: ProfileSource::Envelope,
694 cause: ProfileError::Restriction(BindError::Processing(Error::encoding(
695 cause,
696 "cades.timestamp.ess",
697 ))),
698 })?;
699 if let structured_cms::provider::DigestAlgorithm::Written(algorithm) =
700 certificate.digest_algorithm()
701 {
702 input
703 .parent
704 .charge(1 + algorithm.algorithm().as_bytes().len().min(8) as u64)
705 .map_err(|cause| ProfileFailure {
706 source: ProfileSource::Envelope,
707 cause: ProfileError::Restriction(BindError::Processing(
708 Error::encoding(cause, "cades.timestamp.ess"),
709 )),
710 })?;
711 if algorithm.algorithm() == md5 {
712 return Err(ProfileFailure {
713 source: ProfileSource::Envelope,
714 cause: ProfileError::Md5 {
715 at: algorithm.offset(),
716 },
717 });
718 }
719 }
720 }
721 }
722 input.reader.charge(12).map_err(|cause| ProfileFailure {
723 source: ProfileSource::Information,
724 cause: ProfileError::Restriction(BindError::Processing(Error::encoding(
725 cause,
726 "cades.timestamp",
727 ))),
728 })?;
729 if let tsp::HashAlgorithmReading::Identifier(identifier) = input.info.imprint().algorithm()
730 && identifier.algorithm() == md5
731 {
732 return Err(ProfileFailure {
733 source: ProfileSource::Information,
734 cause: ProfileError::Md5 {
735 at: identifier.offset(),
736 },
737 });
738 }
739 let result = crate::basic::restrictions(input.ess, Some(path), provider, input.parent)
740 .map_err(|cause| ProfileFailure {
741 source: ProfileSource::Envelope,
742 cause: ProfileError::Restriction(cause),
743 })?;
744 Ok(result)
745 }
746}