Skip to main content

structured_cms/timestamp/
retained.rs

1//! Independent generation/imprint facts, not a signature or trust proof.
2
3use super::{Accuracy, HashAlgorithmReading, TokenInfo};
4use crate::{Error, ErrorCode, Result};
5use structured_asn1::{
6    Oid, Reader, Span,
7    memory::{OwnedVec, Work},
8    value::OwnedOid,
9};
10use structured_pkix::temporal::Reading;
11
12/// Independently retained written hash algorithm and logical digest bytes.
13/// Parameter absence stays distinct from a written NULL; no re-encoding or
14/// generic normalization substitutes for the selected provider's semantics.
15#[derive(Debug)]
16pub struct RetainedImprint {
17    algorithm: OwnedOid,
18    parameters: Option<OwnedVec<u8>>,
19    hashed: OwnedVec<u8>,
20}
21impl RetainedImprint {
22    /// Original validated identifier arcs, now independent of the source parser.
23    #[must_use]
24    pub fn algorithm(&self) -> Oid<'_> {
25        self.algorithm.as_oid()
26    }
27    /// Whole original parameter TLV, without a fabricated absent/default value.
28    #[must_use]
29    pub fn parameters(&self) -> Option<&[u8]> {
30        self.parameters.as_deref()
31    }
32    /// Complete logical hashedMessage octets, with no fragment headers.
33    #[must_use]
34    pub fn hashed(&self) -> &[u8] {
35        &self.hashed
36    }
37}
38
39/// A conforming token's declared generation/imprint projection.
40///
41/// This deliberately carries no successful signature/trust verdict. Callers
42/// inspect and verify the token independently; only the complete timestamp
43/// checker may turn positive checks into evidence. Every retained allocation
44/// holds its charge after parser/token drop; no infallible deep Clone exists.
45#[derive(Debug)]
46pub struct RetainedFacts {
47    imprint: RetainedImprint,
48    policy: OwnedOid,
49    serial: OwnedVec<u8>,
50    nonce: Option<OwnedVec<u8>>,
51    gen_time: structured_pkix::temporal::ExactReading,
52    accuracy: Option<Accuracy>,
53    ordering: bool,
54    source_span: Span,
55}
56
57impl TokenInfo<'_> {
58    /// Retains this generation/imprint projection before the scoped source ends.
59    ///
60    /// A retained malformed token is not silently turned into conforming data.
61    /// This projection refuses inspection faults; the original model and all
62    /// diagnostics remain available on refusal. It copies only declared facts,
63    /// not a certificate, source payload, provider state or a trust assertion.
64    pub fn retain_facts(&self, parent: &Reader<'_>) -> Result<RetainedFacts> {
65        self.imprint().require_session(parent)?;
66        if self.has_faults() {
67            return Err(Error::schema(
68                ErrorCode::MalformedValue,
69                "tstInfo",
70                self.span().start,
71            ));
72        }
73        let HashAlgorithmReading::Identifier(algorithm) = self.imprint().algorithm() else {
74            return Err(Error::schema(
75                ErrorCode::MalformedValue,
76                "tstInfo.messageImprint",
77                self.imprint().span().start,
78            ));
79        };
80        let accuracy = self
81            .accuracy()
82            .map(super::AccuracyReading::deviation)
83            .transpose()
84            .map_err(|error| {
85                Error::schema(
86                    ErrorCode::MalformedValue,
87                    "tstInfo.accuracy",
88                    error.span.start,
89                )
90            })?;
91        let work = parent.execution();
92        work.charge_work(8)
93            .map_err(|reason| Error::resource(reason, "tstInfo", self.span().start))?;
94        let hash_algorithm =
95            OwnedOid::from_oid_in(algorithm.algorithm(), &work).map_err(|reason| {
96                Error::resource(
97                    reason,
98                    "tstInfo.messageImprint.hashAlgorithm",
99                    algorithm.offset(),
100                )
101            })?;
102        let parameters = algorithm
103            .parameters()
104            .map(|bytes| {
105                retain(
106                    bytes,
107                    &work,
108                    "tstInfo.messageImprint.hashAlgorithm.parameters",
109                    algorithm.offset(),
110                )
111            })
112            .transpose()?;
113        let hashed = self
114            .imprint()
115            .hashed()
116            .copy_in(
117                parent,
118                "tstInfo.messageImprint.hashedMessage",
119                self.imprint().hashed().span().start,
120            )?
121            .into_owned();
122        let policy = OwnedOid::from_oid_in(self.policy(), &work)
123            .map_err(|reason| Error::resource(reason, "tstInfo.policy", self.span().start))?;
124        let serial = retain(
125            self.serial().element().contents(),
126            &work,
127            "tstInfo.serialNumber",
128            self.serial().element().span().start,
129        )?;
130        let nonce = self
131            .nonce()
132            .map(|nonce| {
133                retain(
134                    nonce.element().contents(),
135                    &work,
136                    "tstInfo.nonce",
137                    nonce.element().span().start,
138                )
139            })
140            .transpose()?;
141        let gen_time = self
142            .precise_gen_time()
143            .try_copy_in(&work, "tstInfo.genTime", self.span().start)
144            .map_err(Error::pkix)?;
145        Ok(RetainedFacts {
146            imprint: RetainedImprint {
147                algorithm: hash_algorithm,
148                parameters,
149                hashed,
150            },
151            policy,
152            serial,
153            nonce,
154            gen_time,
155            accuracy,
156            ordering: self.ordering(),
157            source_span: self.span(),
158        })
159    }
160}
161
162fn retain<W: Work>(bytes: &[u8], work: &W, field: &'static str, at: u64) -> Result<OwnedVec<u8>> {
163    let mut owned = work.vector();
164    owned
165        .try_extend_from_slice(bytes)
166        .map_err(|reason| Error::resource(reason, field, at))?;
167    Ok(owned.into_owned())
168}
169
170impl RetainedFacts {
171    /// Copies declared facts into independently charged current storage.
172    /// Moving the owner needs no copy; a genuine deep copy admits new work and
173    /// capacity before execution. Partial refusal leaves this source unchanged.
174    pub fn try_copy_in<W: Work>(&self, work: &W) -> Result<Self> {
175        work.charge_work(8)
176            .map_err(|reason| Error::resource(reason, "tstInfo", self.source_span.start))?;
177        let algorithm =
178            OwnedOid::from_oid_in(self.imprint.algorithm(), work).map_err(|reason| {
179                Error::resource(
180                    reason,
181                    "tstInfo.messageImprint.hashAlgorithm",
182                    self.source_span.start,
183                )
184            })?;
185        let parameters = self
186            .imprint
187            .parameters()
188            .map(|bytes| {
189                retain(
190                    bytes,
191                    work,
192                    "tstInfo.messageImprint.hashAlgorithm.parameters",
193                    self.source_span.start,
194                )
195            })
196            .transpose()?;
197        let hashed = retain(
198            self.imprint.hashed(),
199            work,
200            "tstInfo.messageImprint.hashedMessage",
201            self.source_span.start,
202        )?;
203        let policy = OwnedOid::from_oid_in(self.policy(), work)
204            .map_err(|reason| Error::resource(reason, "tstInfo.policy", self.source_span.start))?;
205        let serial = retain(
206            self.serial(),
207            work,
208            "tstInfo.serialNumber",
209            self.source_span.start,
210        )?;
211        let nonce = self
212            .nonce()
213            .map(|bytes| retain(bytes, work, "tstInfo.nonce", self.source_span.start))
214            .transpose()?;
215        let gen_time = self
216            .gen_time
217            .try_copy_in(work, "tstInfo.genTime", self.source_span.start)
218            .map_err(Error::pkix)?;
219        Ok(Self {
220            imprint: RetainedImprint {
221                algorithm,
222                parameters,
223                hashed,
224            },
225            policy,
226            serial,
227            nonce,
228            gen_time,
229            accuracy: self.accuracy,
230            ordering: self.ordering,
231            source_span: self.source_span,
232        })
233    }
234    /// Declared complete imprint, requiring selected-provider resolution to use.
235    #[must_use]
236    pub fn imprint(&self) -> &RetainedImprint {
237        &self.imprint
238    }
239    /// Original policy arcs; no product policy acceptance is implied.
240    #[must_use]
241    pub fn policy(&self) -> Oid<'_> {
242        self.policy.as_oid()
243    }
244    /// Original serial INTEGER contents, never a narrowing numeric conversion.
245    #[must_use]
246    pub fn serial(&self) -> &[u8] {
247        &self.serial
248    }
249    /// Original nonce INTEGER contents when one was written.
250    #[must_use]
251    pub fn nonce(&self) -> Option<&[u8]> {
252        self.nonce.as_deref()
253    }
254    /// Original common UTC reading, not a fabricated exact instant.
255    #[must_use]
256    pub fn gen_time(&self) -> Reading {
257        self.gen_time.reading()
258    }
259    /// Exact generation-time order, retaining arbitrary subnanosecond digits.
260    /// This compares authenticated facts only when called on actual evidence;
261    /// a same-TSA ordering assertion or accuracy rule is a separate precondition.
262    /// Both UTC labels and complete comparison work are admitted before lookup.
263    pub fn compare_generation<W: Work>(
264        &self,
265        other: &Self,
266        utc: &super::LeapTable<'_>,
267        work: &W,
268    ) -> core::result::Result<core::cmp::Ordering, super::GenerationOrderError> {
269        self.gen_time.compare(&other.gen_time, utc, work)
270    }
271    /// Complete Accuracy absence remains distinct from a present zero value.
272    #[must_use]
273    pub fn accuracy(&self) -> Option<Accuracy> {
274        self.accuracy
275    }
276    /// Original ordering assertion, which does not establish chronology itself.
277    #[must_use]
278    pub fn ordering(&self) -> bool {
279        self.ordering
280    }
281    /// Range in the original callback reader's coordinates. When logical, keep
282    /// its supplied `SourceMap` separately; this is not a physical document span.
283    #[must_use]
284    pub fn source_span(&self) -> Span {
285        self.source_span
286    }
287}