structured-cades 0.18.2

Source-bound CAdES baseline composition over CMS and long-term validation facts
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
//! One original timestamp envelope reading shared by preparation and material.

use super::{Finding, Rule, Severity, Timestamp, finding};
use crate::{
    Error,
    source::{Document, Node},
};
use core::convert::Infallible;
use structured_asn1::{
    Reader,
    memory::{OwnedMap, OwnedVec, Work},
};
use structured_cms::{
    content_source::{ContentError, Coordinates, SourceMap},
    timestamp::{InfoError, Token},
};

mod index;
mod signing;

/// An original timestamp syntax refusal with independently retained source maps.
#[derive(Debug)]
pub enum ReadError {
    /// Original outer-source or processing refusal.
    Processing(Error),
    /// Original carried-information refusal. The retained map describes the
    /// cause's coordinate system; the physical carrier is an honest enclosure.
    Information(ContentError<InfoError<Infallible>>),
    /// Inspection callback refusal with its independent carried source map.
    /// The coordinate discriminator separates reader-derived locations from
    /// failures retaining findings at an already physical carrier location.
    Inspection {
        /// Unchanged callback cause, including resource refusal.
        source: Error,
        /// Original physical fragments, never a retained temporary join.
        context: SourceMap,
        /// Coordinate system of the callback cause's own offset.
        coordinates: Coordinates,
    },
}
impl From<Error> for ReadError {
    fn from(cause: Error) -> Self {
        Self::Processing(cause)
    }
}
impl From<structured_cms::Error> for ReadError {
    fn from(cause: structured_cms::Error) -> Self {
        Self::Processing(Error::Cms(cause))
    }
}
impl ReadError {
    /// Resource/source misuse aborts preparation rather than becoming a finding.
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        match self {
            Self::Processing(cause) => cause.is_terminal(),
            Self::Information(cause) => information_cause(cause).is_terminal(),
            Self::Inspection { source, .. } => source.is_terminal(),
        }
    }
    /// Original physical failure position or carried-source enclosure start.
    #[must_use]
    pub fn offset(&self) -> u64 {
        match self {
            Self::Processing(cause) => cause.offset(),
            Self::Information(ContentError::Processing(cause)) => cause.offset(),
            Self::Inspection { context, .. }
            | Self::Information(
                ContentError::Decoding { context, .. } | ContentError::Callback { context, .. },
            ) => context.carrier().start,
        }
    }
}
fn information_cause(cause: &ContentError<InfoError<Infallible>>) -> &structured_cms::Error {
    match cause {
        ContentError::Processing(cause)
        | ContentError::Decoding { source: cause, .. }
        | ContentError::Callback {
            source: InfoError::Processing(cause),
            ..
        } => cause,
        ContentError::Callback {
            source: InfoError::Callback(never),
            ..
        } => match *never {},
    }
}
pub(crate) struct Model<'d> {
    pub(crate) token: Token<'d>,
    pub(crate) properties: Option<crate::properties::Properties<'d>>,
}
pub(crate) struct Cache<'m, 'd> {
    pub(crate) models: OwnedVec<Model<'d>>,
    pub(crate) ordinals: OwnedVec<Option<TokenIndex>>,
    pub(crate) proofs: super::proofs::Proofs<'d>,
    pub(crate) faults: OwnedVec<(Node, ReadError)>,
    pub(crate) related: Option<OwnedVec<Finding<'m, 'd>>>,
}
#[derive(Clone, Copy)]
pub(crate) enum TokenIndex {
    Direct(usize),
    Proof(super::proofs::Reference),
}
pub(crate) struct ModelView<'a, 'd> {
    pub(crate) ordinal: usize,
    pub(crate) token: &'a Token<'d>,
    pub(crate) properties: Option<&'a crate::properties::Properties<'d>>,
}
impl<'d> Cache<'_, 'd> {
    pub(crate) fn token(&self, ordinal: usize) -> Option<ModelView<'_, 'd>> {
        let (token, properties) = match self.ordinals.get(ordinal)?.as_ref()? {
            TokenIndex::Direct(index) => {
                let model = &self.models[*index];
                (&model.token, model.properties.as_ref())
            }
            TokenIndex::Proof(reference) => self.proofs.token(*reference)?,
        };
        Some(ModelView {
            ordinal,
            token,
            properties,
        })
    }
}

pub(super) struct Findings<'a, 'm, 'd, W: Work> {
    pub(super) rows: &'a mut OwnedVec<Finding<'m, 'd>, W>,
    pub(super) work: &'a W,
}
struct Reading<'d> {
    model: Option<Model<'d>>,
    fault: Option<ReadError>,
}

#[expect(
    clippy::result_large_err,
    reason = "retain the original source map without allocating during resource refusal"
)]
fn read_one<'m, 'd, W: Work>(
    document: &Document<'m, 'd>,
    entry: &Timestamp<'d>,
    parent: &Reader<'d>,
    findings: &mut OwnedVec<Finding<'m, 'd>, W>,
) -> Result<Reading<'d>, ReadError> {
    let at = entry.property.span().start;
    let cause = if let Some(source) = entry.value {
        let mut reader = source.reader_in(parent)?;
        match Token::read_from(&mut reader) {
            Ok(token) => {
                let properties =
                    if crate::properties::Properties::has_legacy_values(token.signer(), &reader)? {
                        // The shared property reader retains AnnexA cardinality
                        // faults too, before skipping an unreadable value.
                        // Timestamp signers must not rely on root-only rules.
                        let properties =
                            crate::properties::Properties::read(token.signer(), &reader)?;
                        super::property_findings(document, &properties, &reader, findings)?;
                        Some(properties)
                    } else {
                        None
                    };
                let fault = inspect_cached(document, entry, &token, &reader, findings)?;
                return Ok(Reading {
                    model: Some(Model { token, properties }),
                    fault,
                });
            }
            Err(cause) => {
                if cause.is_terminal() {
                    return Err(cause.into());
                }
                finding(
                    document,
                    entry.property.span(),
                    Severity::Required,
                    Rule::Schema {
                        code: cause.code(),
                        field: cause.field(),
                    },
                    findings,
                )?;
                ReadError::from(cause)
            }
        }
    } else {
        let cause = Error::Syntax {
            code: structured_cms::ErrorCode::MissingField,
            field: "cades.timestamp",
            at,
        };
        finding(
            document,
            entry.property.span(),
            Severity::Required,
            Rule::Schema {
                code: structured_cms::ErrorCode::MissingField,
                field: "cades.timestamp",
            },
            findings,
        )?;
        ReadError::from(cause)
    };
    Ok(Reading {
        model: None,
        fault: Some(cause),
    })
}

#[expect(
    clippy::result_large_err,
    reason = "retain the original information refusal and source map without allocating while refusing resources"
)]
pub(super) fn read<'m, 'd, W: Work>(
    document: &Document<'m, 'd>,
    timestamps: &[Timestamp<'d>],
    root: Node,
    counters: &OwnedMap<Node, usize, impl Work>,
    parent: &Reader<'d>,
    proofs: super::proofs::Proofs<'d>,
    findings: Findings<'_, 'm, 'd, W>,
) -> Result<Cache<'m, 'd>, ReadError> {
    let Findings {
        rows: findings,
        work: findings_work,
    } = findings;
    let work = parent.execution();
    let mut models = work.vector();
    let mut ordinals = work.vector();
    let mut faults = work.vector();
    let mut related = None;
    ordinals
        .try_reserve_exact(timestamps.len())
        .map_err(|cause| {
            Error::resource(cause, "cades.timestamp", document.message().span().start)
        })?;
    for entry in timestamps {
        let at = entry.property.span().start;
        let resource = |cause| Error::resource(cause, "cades.timestamp", at);
        work.charge_work(1).map_err(resource)?;
        let selected_owner = entry.owner == root
            || counters
                .get(&entry.owner, &work)
                .map_err(resource)?
                .is_some();
        // Other roots' preservation findings stay visible without becoming
        // this selected root's B-B syntax. Their actual tokens STILL enter
        // the complete historical TSA census and must independently validate.
        let entry_findings = if selected_owner {
            &mut *findings
        } else {
            related.get_or_insert_with(|| findings_work.vector())
        };
        if let Some(source) = entry.value {
            let reference = proofs
                .index
                .get(&Node::of(source.element().span()), &work)
                .map_err(resource)?;
            if let Some(reference) = reference {
                let selected = if let Some((token, properties)) = proofs.token(*reference) {
                    let reader = source.reader_in(parent)?;
                    if let Some(properties) = properties {
                        super::property_findings(document, properties, &reader, entry_findings)?;
                    }
                    if let Some(fault) =
                        inspect_cached(document, entry, token, &reader, entry_findings)?
                    {
                        faults.try_push((entry.property, fault)).map_err(resource)?;
                    }
                    Some(TokenIndex::Proof(*reference))
                } else {
                    faults
                        .try_push((
                            entry.property,
                            ReadError::Processing(Error::Syntax {
                                code: structured_cms::ErrorCode::UnexpectedContentType,
                                field: "cades.evidence.timestamp",
                                at: source.element().span().start,
                            }),
                        ))
                        .map_err(resource)?;
                    None
                };
                ordinals.try_push(selected).map_err(resource)?;
                continue;
            }
        }
        let reading = read_one(document, entry, parent, entry_findings)?;
        if let Some(fault) = reading.fault {
            faults.try_push((entry.property, fault)).map_err(resource)?;
        }
        let selected = if let Some(model) = reading.model {
            let index = models.len();
            models.try_push(model).map_err(resource)?;
            Some(TokenIndex::Direct(index))
        } else {
            None
        };
        ordinals.try_push(selected).map_err(resource)?;
    }
    Ok(Cache {
        models: models.into_owned(),
        ordinals: ordinals.into_owned(),
        proofs,
        faults: faults.into_owned(),
        related: related
            .filter(|rows| !rows.is_empty())
            .map(OwnedVec::into_owned),
    })
}

#[expect(
    clippy::result_large_err,
    reason = "Inspection retains original source mapping inline so an exhausted operation does not allocate an error box."
)]
fn inspect_cached<'m, 'd>(
    document: &Document<'m, 'd>,
    entry: &Timestamp<'d>,
    token: &Token<'d>,
    reader: &Reader<'d>,
    findings: &mut OwnedVec<Finding<'m, 'd>, impl Work>,
) -> Result<Option<ReadError>, ReadError> {
    if let Err(cause) = inspect(document, entry, token, reader, findings) {
        if cause.is_terminal() {
            return Err(cause);
        }
        let ReadError::Information(source) = cause else {
            return Err(cause);
        };
        finding(
            document,
            entry.property.span(),
            Severity::Required,
            Rule::Schema {
                code: information_cause(&source).code(),
                field: information_cause(&source).field(),
            },
            findings,
        )?;
        return Ok(Some(ReadError::Information(source)));
    }
    Ok(None)
}

#[expect(
    clippy::result_large_err,
    reason = "retain the original information refusal and source map without allocating while refusing resources"
)]
fn inspect<'m, 'd>(
    document: &Document<'m, 'd>,
    entry: &Timestamp<'d>,
    token: &Token<'d>,
    reader: &Reader<'d>,
    findings: &mut OwnedVec<Finding<'m, 'd>, impl Work>,
) -> Result<(), ReadError> {
    let index_algorithm = {
        let signing_fields = signing::read(document, entry, token, reader, findings)?;
        index::read(document, entry, token, &signing_fields, reader, findings)?
    };
    // ESS/index catalogues are temporary inspection scratch. Release their
    // capacity before opening potentially fragmented carried information.
    // The envelope model is retained once. A subsequent cryptographic check
    // opens information under CURRENT work: temporary joined TSTInfo cannot
    // be pinned in this cache. Its faults use a physical attribute enclosure,
    // never a logical offset disguised as an original document position.
    let inspection = token.with_info(reader, |info, inside, _| {
        if let structured_cms::timestamp::HashAlgorithmReading::Identifier(algorithm) =
            info.imprint().algorithm()
        {
            let imprint = signing::digest(
                document,
                entry.property.span(),
                algorithm,
                Some(info.imprint().hashed().len()),
                "tstInfo.messageImprint.hashedMessage",
                inside,
                findings,
            )?;
            if let Some((structured_asn1::digest::Resolution::Supported(index), span)) =
                &index_algorithm
                && let structured_asn1::digest::Resolution::Supported(imprint) = imprint
            {
                reader.charge(1).map_err(|cause| {
                    signing::InspectionError::Physical(Error::encoding(
                        cause,
                        "cades.archive.index",
                    ))
                })?;
                if *index != imprint {
                    finding(
                        document,
                        *span,
                        Severity::Required,
                        Rule::ArchiveAlgorithm,
                        findings,
                    )
                    .map_err(signing::InspectionError::Physical)?;
                }
            }
        }
        for cause in token
            .faults()
            .iter()
            .chain(token.message().faults())
            .chain(token.signer().faults())
            .chain(info.faults())
        {
            reader.charge(1).map_err(|cause| {
                signing::InspectionError::Physical(Error::encoding(cause, "cades.timestamp"))
            })?;
            finding(
                document,
                entry.property.span(),
                Severity::Required,
                Rule::Schema {
                    code: cause.code(),
                    field: cause.field(),
                },
                findings,
            )
            .map_err(signing::InspectionError::Physical)?;
        }
        Ok::<_, signing::InspectionError>(())
    });
    let source = match inspection {
        Ok(()) => return Ok(()),
        Err(ContentError::Callback {
            source: InfoError::Callback(cause),
            context,
        }) => {
            let coordinates = match &cause {
                signing::InspectionError::Reader(_) => context.coordinates(),
                signing::InspectionError::Physical(_) => Coordinates::Original,
            };
            return Err(ReadError::Inspection {
                source: cause.into_source(),
                context,
                coordinates,
            });
        }
        Err(ContentError::Processing(cause)) => ContentError::Processing(cause),
        Err(ContentError::Decoding { source, context }) => {
            ContentError::Decoding { source, context }
        }
        Err(ContentError::Callback {
            source: InfoError::Processing(source),
            context,
        }) => ContentError::Callback {
            source: InfoError::Processing(source),
            context,
        },
    };
    Err(ReadError::Information(source))
}