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: Reading,
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        Ok(RetainedFacts {
142            imprint: RetainedImprint {
143                algorithm: hash_algorithm,
144                parameters,
145                hashed,
146            },
147            policy,
148            serial,
149            nonce,
150            gen_time: self.gen_time(),
151            accuracy,
152            ordering: self.ordering(),
153            source_span: self.span(),
154        })
155    }
156}
157
158fn retain<W: Work>(bytes: &[u8], work: &W, field: &'static str, at: u64) -> Result<OwnedVec<u8>> {
159    let mut owned = work.vector();
160    owned
161        .try_extend_from_slice(bytes)
162        .map_err(|reason| Error::resource(reason, field, at))?;
163    Ok(owned.into_owned())
164}
165
166impl RetainedFacts {
167    /// Copies declared facts into independently charged current storage.
168    /// Moving the owner needs no copy; a genuine deep copy admits new work and
169    /// capacity before execution. Partial refusal leaves this source unchanged.
170    pub fn try_copy_in<W: Work>(&self, work: &W) -> Result<Self> {
171        work.charge_work(8)
172            .map_err(|reason| Error::resource(reason, "tstInfo", self.source_span.start))?;
173        let algorithm =
174            OwnedOid::from_oid_in(self.imprint.algorithm(), work).map_err(|reason| {
175                Error::resource(
176                    reason,
177                    "tstInfo.messageImprint.hashAlgorithm",
178                    self.source_span.start,
179                )
180            })?;
181        let parameters = self
182            .imprint
183            .parameters()
184            .map(|bytes| {
185                retain(
186                    bytes,
187                    work,
188                    "tstInfo.messageImprint.hashAlgorithm.parameters",
189                    self.source_span.start,
190                )
191            })
192            .transpose()?;
193        let hashed = retain(
194            self.imprint.hashed(),
195            work,
196            "tstInfo.messageImprint.hashedMessage",
197            self.source_span.start,
198        )?;
199        let policy = OwnedOid::from_oid_in(self.policy(), work)
200            .map_err(|reason| Error::resource(reason, "tstInfo.policy", self.source_span.start))?;
201        let serial = retain(
202            self.serial(),
203            work,
204            "tstInfo.serialNumber",
205            self.source_span.start,
206        )?;
207        let nonce = self
208            .nonce()
209            .map(|bytes| retain(bytes, work, "tstInfo.nonce", self.source_span.start))
210            .transpose()?;
211        Ok(Self {
212            imprint: RetainedImprint {
213                algorithm,
214                parameters,
215                hashed,
216            },
217            policy,
218            serial,
219            nonce,
220            gen_time: self.gen_time,
221            accuracy: self.accuracy,
222            ordering: self.ordering,
223            source_span: self.source_span,
224        })
225    }
226    /// Declared complete imprint, requiring selected-provider resolution to use.
227    #[must_use]
228    pub fn imprint(&self) -> &RetainedImprint {
229        &self.imprint
230    }
231    /// Original policy arcs; no product policy acceptance is implied.
232    #[must_use]
233    pub fn policy(&self) -> Oid<'_> {
234        self.policy.as_oid()
235    }
236    /// Original serial INTEGER contents, never a narrowing numeric conversion.
237    #[must_use]
238    pub fn serial(&self) -> &[u8] {
239        &self.serial
240    }
241    /// Original nonce INTEGER contents when one was written.
242    #[must_use]
243    pub fn nonce(&self) -> Option<&[u8]> {
244        self.nonce.as_deref()
245    }
246    /// Original common UTC reading, not a fabricated exact instant.
247    #[must_use]
248    pub fn gen_time(&self) -> Reading {
249        self.gen_time
250    }
251    /// Complete Accuracy absence remains distinct from a present zero value.
252    #[must_use]
253    pub fn accuracy(&self) -> Option<Accuracy> {
254        self.accuracy
255    }
256    /// Original ordering assertion, which does not establish chronology itself.
257    #[must_use]
258    pub fn ordering(&self) -> bool {
259        self.ordering
260    }
261    /// Range in the original callback reader's coordinates. When logical, keep
262    /// its supplied `SourceMap` separately; this is not a physical document span.
263    #[must_use]
264    pub fn source_span(&self) -> Span {
265        self.source_span
266    }
267}