structured-cades 0.21.1

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
//! Format-owner dependencies of every authenticated original credential.
//!
//! Reuses the original-artifact/coverage LTV core. Authentication receipts are
//! borrowed, never reconstructed from a public boolean or replayed signature.

use super::{Index, Open};
use crate::{
    Cades,
    counters::Paths,
    credential::{Checked, Complete},
    source::{DocumentId, Node, Original},
    timestamp::ArchiveView,
};
use structured_asn1::{
    Reader, ScopedReader,
    memory::{MemoryError, OwnedMap, OwnedVec, Work},
};
pub use structured_ltv::material::{Completeness, Finding, Missing, VisitError};
use structured_ltv::{
    baseline::CredentialMaterial,
    material::{ArchiveError, Archived, IndexError},
    pki::{CounterReceipts, CredentialReceipts},
    source::{Query, Snapshot},
    timestamp::{ObligationError, TimestampRequirements, TimestampScope},
};

/// One dependency established by the credential's actual format owner.
pub type Need<'value, 'source, 'model, 'document> =
    structured_ltv::material::Dependency<'value, 'source, Node, DocumentId<'model, 'document>, ()>;

/// Same format owner as authentication, using its actual retained evidence.
/// It discovers ALL credential-specific validation material, including the
/// credential's own status, using current Work before decoding/copy/allocation
/// or arithmetic. Certificate-free authentication does not waive this step.
/// EN319122-1 ยงยง5.2.6.1, 5.4 and 6.3 require credential validation data in
/// addition to the issuer's X.509 path/status.
/// <https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf>
pub trait Provider<E> {
    /// Original processing/resource cause, not a negative completeness result.
    type Error;
    /// Visit dependencies once without reauthenticating or acquiring sources.
    fn visit<'m, 'd, V>(
        &self,
        credential: &Checked<'m, 'd, '_, E>,
        open: &[Open<'d>],
        operation: &ScopedReader<'d, '_>,
        visitor: impl for<'value, 'source> FnMut(Need<'value, 'source, 'm, 'd>) -> Result<(), V>,
    ) -> Result<Completeness, VisitError<Self::Error, V>>;
}

/// Actual authenticated credential, including all negative material facts.
pub struct Entry<'model, 'document> {
    source: Original<'model, 'document>,
    completeness: Completeness,
    findings: OwnedVec<Finding>,
}
impl<'m, 'd> Entry<'m, 'd> {
    /// Original protected credential enclosure.
    #[must_use]
    pub fn source(&self) -> Original<'m, 'd> {
        self.source
    }
    /// Actual format interpretation rather than successful copy lookup.
    #[must_use]
    pub fn completeness(&self) -> Completeness {
        self.completeness
    }
    /// All missing dependencies, preserving original visitation order.
    #[must_use]
    pub fn findings(&self) -> &[Finding] {
        &self.findings
    }
}

/// Same complete credential receipt under one whole/archive source scope.
pub struct Report<'auth, 'receipt, 'model, 'document, 'path, E> {
    credentials: &'auth Complete<'receipt, 'model, 'document, 'path, E>,
    scope: TimestampScope<Node, DocumentId<'model, 'document>, ()>,
    entries: OwnedVec<Entry<'model, 'document>>,
    complete: bool,
}
impl<'m, 'd, E> Report<'_, '_, 'm, 'd, '_, E> {
    /// Every original credential required by this exact source scope.
    #[must_use]
    pub fn entries(&self) -> &[Entry<'m, 'd>] {
        &self.entries
    }
    /// Complete interpretation AND original incorporation/coverage.
    #[must_use]
    pub fn all_requirements_met(&self) -> bool {
        self.complete
    }
}
impl<'r, 'm, 'd, 'p, E> CredentialMaterial for Report<'_, 'r, 'm, 'd, 'p, E> {
    type Id = Node;
    type Document = DocumentId<'m, 'd>;
    type Generation = ();
    type Credentials = Complete<'r, 'm, 'd, 'p, E>;
    fn scope(&self) -> TimestampScope<Node, Self::Document, ()> {
        self.scope
    }
    fn snapshot(&self) -> Snapshot<Self::Document, ()> {
        self.credentials.snapshot()
    }
    fn credentials(&self) -> &Self::Credentials {
        self.credentials
    }
    fn all_requirements_met(&self) -> bool {
        self.complete
    }
}

/// A source/handler/resource failure never returns a successful partial report.
#[derive(Debug)]
pub enum Error<E> {
    /// Another document, signature, incomplete counter set or archive context.
    Foreign {
        /// Actual selecting enclosure.
        node: Node,
    },
    /// Original parser/current-operation refusal.
    Processing(crate::Error),
    /// Original full counter/scope membership refusal.
    Obligation(ObligationError<Node>),
    /// Exact original indexed lookup refused.
    Index(IndexError<Node>),
    /// Archive evidence or covered lookup refused.
    Archive(ArchiveError<Node>),
    /// Actual credential handler refused with its original cause.
    Provider {
        /// Original protected credential.
        node: Node,
        /// Unchanged opaque cause.
        cause: E,
    },
    /// Current work or retained report capacity refused before use.
    Resource {
        /// Original selecting enclosure.
        node: Node,
        /// Actual admission failure.
        cause: MemoryError,
    },
    /// Handler returned a visitor refusal without an actual refused callback.
    CallbackProtocol {
        /// Original credential enclosure.
        node: Node,
    },
}

/// Optional archive proof. Whole mode cannot impersonate a preceding archive;
/// construction retains the actual token's private mathematical receipt.
pub struct Scope<'a, 'm, 'd, 'p> {
    archive: Option<ArchiveView<'a, 'm, 'd, 'p>>,
}
impl<'a, 'm, 'd, 'p> Scope<'a, 'm, 'd, 'p> {
    /// Whole original incorporation without archive implications.
    #[must_use]
    pub fn whole() -> Self {
        Self { archive: None }
    }
    /// Actual modern or historical archive whose exact input must cover the
    /// dependencies. Both use the SAME retained format-material mechanism.
    #[must_use]
    pub fn before_archive(archive: impl Into<ArchiveView<'a, 'm, 'd, 'p>>) -> Self {
        Self {
            archive: Some(archive.into()),
        }
    }
    fn require<E, Q: Query<Id = Node, Document = DocumentId<'m, 'd>, Generation = ()>, W: Work>(
        &self,
        required: &TimestampRequirements<Node, DocumentId<'m, 'd>, (), Cades>,
        index: &Index<'_, 'm, 'd, W>,
        query: &Q,
    ) -> Result<(), Error<E>> {
        let location = required.scope().location();
        if location.snapshot != query.snapshot() {
            return Err(Error::Foreign {
                node: location.node,
            });
        }
        index
            .require_signature(required.signature(), query)
            .map_err(Error::Index)?;
        match (required.scope(), self.archive) {
            (TimestampScope::All(_), None) => Ok(()),
            (TimestampScope::BeforeArchive(_), Some(archive)) => {
                let actor = archive.timestamp().actor().ok_or(Error::Foreign {
                    node: location.node,
                })?;
                let evidence = actor.verified();
                query
                    .admit(location.node, 3)
                    .map_err(|cause| Error::Index(IndexError::Scope(cause)))?;
                if evidence.signature() != required.signature()
                    || archive.coverage().subject() != location.node
                    || evidence.token().snapshot != location.snapshot
                {
                    return Err(Error::Foreign {
                        node: location.node,
                    });
                }
                archive
                    .coverage()
                    .require_evidence(evidence, location.node, query)
                    .map_err(|cause| Error::Archive(ArchiveError::Coverage(cause)))
            }
            _ => Err(Error::Foreign {
                node: location.node,
            }),
        }
    }
    fn missing<E, Q: Query<Id = Node, Document = DocumentId<'m, 'd>, Generation = ()>, W: Work>(
        &self,
        need: Need<'_, '_, 'm, 'd>,
        index: &Index<'_, 'm, 'd, W>,
        open: &OwnedMap<Node, (), Q::Work>,
        query: &Q,
    ) -> Result<Option<Missing>, Error<E>> {
        match need {
            Need::Missing => Ok(Some(Missing::Absent)),
            Need::Known(artifact) => {
                if let Some(archive) = self.archive {
                    let actor = archive.timestamp().actor().ok_or(Error::Foreign {
                        node: index.signature(),
                    })?;
                    return index
                        .archived(artifact, archive.coverage(), actor.verified(), query)
                        .map(|answer| match answer {
                            Archived::Present(_) => None,
                            Archived::Missing => Some(Missing::Absent),
                            Archived::Uncovered => Some(Missing::Uncovered),
                        })
                        .map_err(Error::Archive);
                }
                let mut copies = index.artifact(artifact, query).map_err(Error::Index)?;
                copies
                    .next()
                    .transpose()
                    .map(|value| {
                        if value.is_some() {
                            None
                        } else {
                            Some(Missing::Absent)
                        }
                    })
                    .map_err(Error::Index)
            }
            Need::Open(location) => {
                if location.snapshot != query.snapshot() {
                    return Err(Error::Foreign {
                        node: location.node,
                    });
                }
                if open
                    .get(&location.node, query.execution())
                    .map_err(|cause| Error::Resource {
                        node: location.node,
                        cause,
                    })?
                    .is_none()
                {
                    return Ok(Some(Missing::Absent));
                }
                if let Some(archive) = self.archive {
                    let actor = archive.timestamp().actor().ok_or(Error::Foreign {
                        node: location.node,
                    })?;
                    return archive
                        .coverage()
                        .covers(actor.verified(), location.node, query)
                        .map(|covered| {
                            if covered {
                                None
                            } else {
                                Some(Missing::Uncovered)
                            }
                        })
                        .map_err(|cause| Error::Archive(ArchiveError::Coverage(cause)));
                }
                Ok(None)
            }
        }
    }
}

/// Check the complete original credential scope, using actual format receipts
/// and the shared exact-artifact index. A swallowed callback failure remains
/// terminal; later provider success cannot turn it into an empty complete set.
pub fn check<'a, 'r, 'm, 'd, 'p, E, P: Provider<E>, W: Work>(
    credentials: &'a Complete<'r, 'm, 'd, 'p, E>,
    counters: &Paths<'_, 'm, 'd, 'p>,
    required: &TimestampRequirements<Node, DocumentId<'m, 'd>, (), Cades>,
    index: &Index<'_, 'm, 'd, W>,
    scope: &Scope<'_, 'm, 'd, '_>,
    provider: &P,
    operation: &Reader<'d>,
) -> Result<Report<'a, 'r, 'm, 'd, 'p, E>, Error<P::Error>> {
    let document = credentials.snapshot().document.source();
    document
        .message()
        .require_session(operation, "cades.credential.material")
        .map_err(|cause| Error::Processing(crate::Error::Cms(cause)))?;
    let execution = operation.execution();
    let query = &structured_ltv::source::Scope::new(&document, credentials.snapshot(), &execution);
    scope.require(required, index, query)?;
    let node = credentials.signature();
    query
        .admit(node, 3)
        .map_err(|cause| Error::Index(IndexError::Scope(cause)))?;
    if credentials.snapshot() != query.snapshot()
        || counters.snapshot() != query.snapshot()
        || node != required.signature()
        || node != counters.signature()
    {
        return Err(Error::Foreign { node });
    }
    required
        .includes_counters(counters, query)
        .map_err(|cause| Error::Index(IndexError::Scope(cause)))?;
    let work = query.execution();
    let mut open = work.map();
    for entry in index.open() {
        work.charge_work(1).map_err(|cause| Error::Resource {
            node: entry.node,
            cause,
        })?;
        open.try_insert(entry.node, ())
            .map_err(|cause| Error::Resource {
                node: entry.node,
                cause,
            })?;
    }
    let mut selected = work.vector();
    for entry in credentials.report.root() {
        selected
            .try_push(entry)
            .map_err(|cause| Error::Resource { node, cause })?;
    }
    let mut group = 0;
    for ordinal in 0..counters.len() {
        work.charge_work(2)
            .map_err(|cause| Error::Resource { node, cause })?;
        let Some((signature, entries)) = credentials
            .report
            .counter(group, work)
            .map_err(|cause| Error::Resource { node, cause })?
        else {
            break;
        };
        if signature != counters.counter(ordinal).signature {
            continue;
        }
        if required
            .counter_in_scope(ordinal, query)
            .map_err(Error::Obligation)?
        {
            for entry in entries {
                selected
                    .try_push(entry)
                    .map_err(|cause| Error::Resource { node, cause })?;
            }
        }
        group += 1;
    }
    if group != credentials.report.counters() {
        return Err(Error::Foreign { node });
    }
    let mut entries = work.vector();
    entries
        .try_reserve_exact(selected.len())
        .map_err(|cause| Error::Resource { node, cause })?;
    let mut complete = true;
    for credential in selected {
        let entry = one(credential, index, scope, provider, operation, query, &open)?;
        if entry.completeness != Completeness::Complete || !entry.findings.is_empty() {
            complete = false;
        }
        entries
            .try_push(entry)
            .map_err(|cause| Error::Resource { node, cause })?;
    }
    query
        .admit(node, 1)
        .map_err(|cause| Error::Index(IndexError::Scope(cause)))?;
    Ok(Report {
        credentials,
        scope: required.scope(),
        entries: entries.into_owned(),
        complete,
    })
}

fn one<'m, 'd, E, P: Provider<E>, Q, W: Work>(
    credential: &Checked<'m, 'd, '_, E>,
    index: &Index<'_, 'm, 'd, W>,
    scope: &Scope<'_, 'm, 'd, '_>,
    provider: &P,
    operation: &Reader<'d>,
    query: &Q,
    open: &OwnedMap<Node, (), Q::Work>,
) -> Result<Entry<'m, 'd>, Error<P::Error>>
where
    Q: Query<Id = Node, Document = DocumentId<'m, 'd>, Generation = ()>,
{
    let work = query.execution();
    let node = credential.source().node;
    let mut visit = structured_ltv::material::DependencyVisit::new(node, work, |need| {
        scope.missing(need, index, open, query)
    })
    .map_err(|cause| Error::Resource { node, cause })?;
    let answer = provider.visit(credential, index.open(), operation, |need| {
        visit.observe(need)
    });
    let result = visit.finish(answer).map_err(|cause| match cause {
        structured_ltv::material::DependencyError::Processing { cause, .. } => cause,
        structured_ltv::material::DependencyError::Resource { node, cause } => {
            Error::Resource { node, cause }
        }
        structured_ltv::material::DependencyError::Provider { node, cause } => {
            Error::Provider { node, cause }
        }
        structured_ltv::material::DependencyError::CallbackProtocol { node } => {
            Error::CallbackProtocol { node }
        }
    })?;
    Ok(Entry {
        source: credential.source(),
        completeness: result.completeness,
        findings: result.findings,
    })
}