Skip to main content

structured_cms/
timestamp.rs

1//! RFC3161 timestamp facts, independent of application timelines and trust.
2
3use structured_pkix::temporal::{Instant, LeapTable, Reading, Uncertainty};
4
5mod accuracy;
6pub use accuracy::{AccuracyReading, Component, ComponentReading, DeviationError, DeviationReason};
7mod imprint;
8pub use imprint::{HashAlgorithmReading, MessageImprint};
9mod imprint_check;
10pub use imprint_check::{ImprintAgreement, ImprintError};
11mod requested;
12pub use requested::{ImprintOperand, RequestAgreement, RequestImprintError, RequestedContentError};
13mod extension;
14pub use extension::{RecognitionError, TokenExtension, TokenExtensions};
15mod info;
16pub use info::{IntegerField, TokenInfo};
17mod tsa;
18pub use tsa::TsaReading;
19mod token;
20pub use token::{InfoError, Token};
21mod timeliness;
22pub use timeliness::{RequestWindow, Timeliness, timeliness};
23mod request;
24pub use request::Request;
25mod request_extensions;
26mod request_fields;
27pub use request_fields::{RequestFieldError, RequestFields};
28mod authority;
29mod carried;
30mod signature;
31pub use authority::{AuthorityError, AuthorityFacts, AuthoritySource, TsaIdentity, TsaUsage};
32pub use signature::{SignatureError, TokenSignature};
33mod check;
34pub use check::{
35    CheckContext, CheckError, CheckedTimestamp, Evidence, EvidenceCopyError, InfoCheckError,
36    MappedCheckError, Requested,
37};
38mod retained;
39pub use retained::{RetainedFacts, RetainedImprint};
40
41pub(crate) fn record<W: structured_asn1::memory::Work>(
42    faults: &mut structured_asn1::memory::OwnedVec<crate::Error, W>,
43    error: crate::Error,
44) -> crate::Result<()> {
45    if error.is_terminal() {
46        return Err(error);
47    }
48    let at = error.offset();
49    let field = error.field();
50    faults
51        .try_push(error)
52        .map_err(|reason| crate::Error::resource(reason, field, at))
53}
54
55/// Accuracy components as read, with zero for an omitted component.
56///
57/// The scalar model preserves readable malformed components for inspection;
58/// constructing it does not establish ASN.1 conformance or a successful proof.
59/// A missing entire Accuracy is represented separately by None. RFC3161
60/// §2.4.2 allows external policy to supply accuracy, but absence in a token
61/// alone never establishes a zero deviation.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct Accuracy {
64    seconds: u64,
65    millis: u64,
66    micros: u64,
67}
68
69impl Accuracy {
70    /// Original scalar components, without narrowing or syntax repair.
71    #[must_use]
72    pub const fn new(seconds: u64, millis: u64, micros: u64) -> Self {
73        Self {
74            seconds,
75            millis,
76            micros,
77        }
78    }
79    /// Whole seconds as read.
80    #[must_use]
81    pub const fn seconds(self) -> u64 {
82        self.seconds
83    }
84    /// Milliseconds as read, zero when omitted.
85    #[must_use]
86    pub const fn millis(self) -> u64 {
87        self.millis
88    }
89    /// Microseconds as read, zero when omitted.
90    #[must_use]
91    pub const fn micros(self) -> u64 {
92        self.micros
93    }
94    /// Exact total deviation, including retained malformed scalar components.
95    #[must_use]
96    pub fn nanos(self) -> u128 {
97        // All three parts are below 2^64; this sum is below 2^95.
98        u128::from(self.seconds) * 1_000_000_000
99            + u128::from(self.millis) * 1_000_000
100            + u128::from(self.micros) * 1_000
101    }
102}
103
104/// Why the timestamp facts cannot establish a temporal endpoint.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum BoundUncertainty {
107    /// No accuracy was stated by the token or supplied as authenticated policy.
108    AccuracyUnstated,
109    /// Existing UTC arithmetic cannot place the source or destination.
110    Utc(Uncertainty),
111}
112
113/// Lower endpoint of the authority's generation-time accuracy interval.
114/// This says nothing about when the imprinted document was signed.
115pub fn earliest(
116    reading: Reading,
117    accuracy: Option<Accuracy>,
118    utc: &LeapTable<'_>,
119) -> Result<Instant, BoundUncertainty> {
120    let accuracy = accuracy.ok_or(BoundUncertainty::AccuracyUnstated)?;
121    shift(reading.start(), accuracy, true, utc)
122}
123
124/// Upper endpoint, retaining subnanosecond rounding and supplied leap facts.
125/// This is a factual interval calculation, not signature or trust validation.
126pub fn latest(
127    reading: Reading,
128    accuracy: Option<Accuracy>,
129    utc: &LeapTable<'_>,
130) -> Result<Instant, BoundUncertainty> {
131    // RFC3161 §2.4.2 allows a policy to state omitted accuracy, but the
132    // absent token field alone supplies none. Prioritize this API limitation
133    // before attempting rounding with independently incomplete UTC facts.
134    // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2
135    let accuracy = accuracy.ok_or(BoundUncertainty::AccuracyUnstated)?;
136    let upper = reading.upper_bound(utc).map_err(BoundUncertainty::Utc)?;
137    shift(upper, accuracy, false, utc)
138}
139
140fn shift(
141    at: Instant,
142    accuracy: Accuracy,
143    earlier: bool,
144    utc: &LeapTable<'_>,
145) -> Result<Instant, BoundUncertainty> {
146    let nanos = i128::try_from(accuracy.nanos())
147        .map_err(|_| BoundUncertainty::Utc(Uncertainty::OutOfRange))?;
148    utc.shift(at, if earlier { -nanos } else { nanos })
149        .map_err(BoundUncertainty::Utc)
150}