structured-cades 0.15.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Complete source-derived independently authenticated credential census.

use crate::{
    Error,
    basic::SignerBinding,
    counters::Paths,
    prepare::Preparation,
    properties::{OpenRole, OpenValue, Properties},
    source::{DocumentId, Node, Original},
};
use structured_asn1::{
    Reader, ScopedReader,
    memory::{OwnedVec, Work},
};
use structured_ltv::source::Snapshot;
use structured_ltv::{
    credential::Authentication,
    pki::{self, Authorities, CounterReceipts, CredentialGroup, CredentialReceipts},
};
use structured_pkix::Certificate;

/// Actual protected credential delivered to its selected format owner. The
/// private source/owner comes from the complete original property reading.
pub struct Context<'scope, 'model, 'document> {
    source: Original<'model, 'document>,
    signature: Node,
    value: OpenValue<'document>,
    signer: &'scope Certificate<'document>,
    operation: &'scope ScopedReader<'document, 'scope>,
}
impl<'m, 'd> Context<'_, 'm, 'd> {
    /// Original protected credential source and immutable document identity.
    #[must_use]
    pub fn source(&self) -> Original<'m, 'd> {
        self.source
    }
    /// Actual root/counter signature protecting this value.
    #[must_use]
    pub fn signature(&self) -> Node {
        self.signature
    }
    /// Actual independently bound signing certificate, not an arbitrary hint.
    #[must_use]
    pub fn signer(&self) -> &Certificate<'d> {
        self.signer
    }
    /// Original open type, explicit OPTIONAL absence, and source context.
    #[must_use]
    pub fn value(&self) -> OpenValue<'d> {
        self.value
    }
    /// Current operation; use the value's saved reader context for ASN.1
    /// inspection, preserving original source/depth and both work ceilings.
    #[must_use]
    pub fn operation(&self) -> &ScopedReader<'d, '_> {
        self.operation
    }
}

/// Actual credential-format authentication, without a parallel crypto engine.
///
/// EN319122-1 ยง5.2.6.1 leaves non-X.509 certificate/assertion formats to their
/// own specifications. Authenticate THIS original value and its binding to the
/// actual signer, returning the concrete format evidence and every actual
/// authority path/direct anchor or explicit certificate-free mechanism used.
/// Admit parsing, arithmetic, copies, output and retained evidence through the
/// current execution before work; preserve original resource/processing causes.
/// No network/file acquisition or asserted-role authorization occurs here.
/// <https://www.etsi.org/deliver/etsi_en/319100_319199/31912201/01.03.01_60/en_31912201v010301p.pdf>
pub trait Provider<'path, 'document> {
    /// Actual retained format evidence, without Clone/Send/Sync bounds.
    type Evidence;
    /// Original provider/source/resource refusal, distinct from rejection.
    type Error;
    /// Authenticate one original independently signed credential exactly once.
    fn authenticate(
        &self,
        context: Context<'_, '_, 'document>,
    ) -> Result<Authentication<'path, 'document, Self::Evidence>, Self::Error>;
}

/// Completed credential answer retained even when no complete census exists.
pub enum Outcome<'path, 'document, E> {
    /// Concrete original authentication outcome (including negative answers).
    Authentication(Authentication<'path, 'document, E>),
    /// The open schema carries no payload; this cannot become authenticated.
    Absent,
    /// Empty Paths is incomplete handler evidence, not certificate-free.
    MissingAuthorities(E),
}
/// One original credential and its completed original-format answer.
pub struct Checked<'model, 'document, 'path, E> {
    source: Original<'model, 'document>,
    outcome: Outcome<'path, 'document, E>,
}
impl<'m, 'd, 'p, E> Checked<'m, 'd, 'p, E> {
    /// Exact original credential enclosure and protecting document.
    #[must_use]
    pub fn source(&self) -> Original<'m, 'd> {
        self.source
    }
    /// Actual format evidence or explicit negative outcome, without copying.
    #[must_use]
    pub fn outcome(&self) -> &Outcome<'p, 'd, E> {
        &self.outcome
    }
}

/// Complete original group, exposed as an LTV group only through [`Complete`].
pub struct Group<'model, 'document, 'path, E> {
    signature: Node,
    entries: OwnedVec<Checked<'model, 'document, 'path, E>>,
}
impl<'m, 'd, 'p, E> Group<'m, 'd, 'p, E> {
    /// Actual retained authentication results in their original source order.
    #[must_use]
    pub fn entries(&self) -> &[Checked<'m, 'd, 'p, E>] {
        &self.entries
    }
}
impl<'d, 'p, E> CredentialGroup<'p, 'd> for Group<'_, 'd, 'p, E> {
    type Id = Node;
    fn signature(&self) -> Node {
        self.signature
    }
    fn len(&self) -> usize {
        self.entries.len()
    }
    fn credential(&self, ordinal: usize) -> pki::Credential<'p, 'd, Node> {
        let entry = &self.entries[ordinal];
        let Outcome::Authentication(Authentication::Authenticated { authorities, .. }) =
            &entry.outcome
        else {
            unreachable!("only complete groups are exposed as credential receipts");
        };
        pki::Credential {
            signature: self.signature,
            node: entry.source.node,
            authorities: *authorities,
        }
    }
}

/// Complete original root/counter results. A negative later credential does
/// not disappear behind the successful prefix, and no complete receipt exists.
pub struct Report<'model, 'document, 'path, E> {
    signature: Original<'model, 'document>,
    root: Group<'model, 'document, 'path, E>,
    counters: OwnedVec<Group<'model, 'document, 'path, E>>,
    complete: bool,
}
/// One original borrowed counter group, without copying retained evidence.
pub type CounterGroup<'view, 'm, 'd, 'p, E> = (Node, &'view [Checked<'m, 'd, 'p, E>]);
impl<'m, 'd, 'p, E> Report<'m, 'd, 'p, E> {
    /// Every original root credential, including absent/rejected/unsupported.
    #[must_use]
    pub fn root(&self) -> &[Checked<'m, 'd, 'p, E>] {
        &self.root.entries
    }
    /// Number of counter groups with original credentials.
    #[must_use]
    pub fn counters(&self) -> usize {
        self.counters.len()
    }
    /// One original counter group after current metadata admission. Absence is
    /// distinct from refusal; the caller cannot traverse attacker-sized groups
    /// through an infallible iterator that bypasses current Work.
    pub fn counter<W: Work>(
        &self,
        ordinal: usize,
        work: &W,
    ) -> Result<Option<CounterGroup<'_, 'm, 'd, 'p, E>>, structured_asn1::memory::MemoryError> {
        work.charge_work(1)?;
        Ok(self
            .counters
            .get(ordinal)
            .map(|group| (group.signature, &*group.entries)))
    }
    /// Complete actual authority-input census, only after ALL original values
    /// authenticated with nonempty/explicit authority facts.
    #[must_use]
    pub fn complete(&self) -> Option<Complete<'_, 'm, 'd, 'p, E>> {
        if self.complete {
            Some(Complete { report: self })
        } else {
            None
        }
    }
}

/// Borrowed full credential proof. Its construction cannot select a successful
/// subset or replace the original protecting signature.
pub struct Complete<'receipt, 'model, 'document, 'path, E> {
    pub(crate) report: &'receipt Report<'model, 'document, 'path, E>,
}
impl<'r, 'm, 'd, 'p, E> Complete<'r, 'm, 'd, 'p, E> {
    /// Borrows the actual retained root group, without tying its lifetime to
    /// a temporary complete-census descriptor or copying authentication.
    #[must_use]
    pub fn root_group(&self) -> Option<&'r Group<'m, 'd, 'p, E>> {
        if self.report.root.entries.is_empty() {
            None
        } else {
            Some(&self.report.root)
        }
    }
    /// Original counter group after current metadata admission. Absence is
    /// distinct from refusal; the group remains owned by the source report.
    pub fn counter_group(
        &self,
        ordinal: usize,
        work: &impl Work,
    ) -> Result<Option<&'r Group<'m, 'd, 'p, E>>, structured_asn1::memory::MemoryError> {
        work.charge_work(1)?;
        Ok(self.report.counters.get(ordinal))
    }
}
impl<'m, 'd, 'p, E> CredentialReceipts<'p, 'd> for Complete<'_, 'm, 'd, 'p, E> {
    type Id = Node;
    type Document = DocumentId<'m, 'd>;
    type Generation = ();
    type Group = Group<'m, 'd, 'p, E>;
    fn snapshot(&self) -> Snapshot<DocumentId<'m, 'd>, ()> {
        self.report.signature.snapshot
    }
    fn signature(&self) -> Node {
        self.report.signature.node
    }
    fn root(&self) -> Option<&Self::Group> {
        if self.report.root.entries.is_empty() {
            None
        } else {
            Some(&self.report.root)
        }
    }
    fn counters(&self) -> usize {
        self.report.counters.len()
    }
    fn counter(&self, ordinal: usize) -> (Node, &Self::Group) {
        let group = &self.report.counters[ordinal];
        (group.signature, group)
    }
}

/// Processing refuses without returning a successful partial authentication.
#[derive(Debug)]
pub enum CheckError<E> {
    /// Source, original association or capacity/work refused before use.
    Processing(Error),
    /// Actual root/counter has no bound signing certificate for this operation.
    Unbound {
        /// Original protecting signer.
        signature: Node,
    },
    /// Original format/schema/placement findings prevent a complete protected
    /// credential census. The preparation retains every original cause; no
    /// format handler has been called and no successful empty set is issued.
    Nonconforming {
        /// Original selected root.
        signature: Node,
    },
    /// Original opaque format refusal and its physical enclosing credential.
    Provider {
        /// Original protected credential.
        node: Node,
        /// Unchanged provider/resource error.
        cause: E,
    },
}

/// Authenticate every actual root/counter non-claimed credential using the
/// existing format-owner contract. All original selections are checked before
/// authentication begins; a caller cannot supply only successful groups.
pub fn check<'m, 'd, 'p, E, P: Provider<'p, 'd, Evidence = E>>(
    prepared: &Preparation<'m, 'd>,
    signer: &SignerBinding<'_, 'm, 'd, 'p>,
    counters: &Paths<'_, 'm, 'd, 'p>,
    provider: &P,
    operation: &Reader<'d>,
) -> Result<Report<'m, 'd, 'p, E>, CheckError<P::Error>> {
    prepared
        .document()
        .message()
        .require_session(operation, "cades.credentials")
        .map_err(|cause| CheckError::Processing(crate::Error::Cms(cause)))?;
    operation.charge(1).map_err(|cause| {
        CheckError::Processing(crate::Error::encoding(cause, "cades.credentials"))
    })?;
    if !prepared.basic_format_requirements_met() {
        return Err(CheckError::Nonconforming {
            signature: prepared.document().locate(prepared.signer().span()).node,
        });
    }
    check_properties(prepared, signer, counters, provider, operation)
}

/// Authenticates the complete protected root/counter property set without
/// imposing `CAdES`-specific root services on a containing format. `PAdES` uses
/// the same signed properties but forbids `CAdES`'s required signing-time.
/// Actual CMS placement/cardinality, ESS, source/key binding and every counter
/// are still checked before any handler. This does not assert `CAdES` B-B.
/// EN319142-1 ยง6.3/Table1 and EN319122-1 ยง5.2.6 define the separate profiles.
pub fn check_properties<'m, 'd, 'p, E, P: Provider<'p, 'd, Evidence = E>>(
    prepared: &Preparation<'m, 'd>,
    signer: &SignerBinding<'_, 'm, 'd, 'p>,
    counters: &Paths<'_, 'm, 'd, 'p>,
    provider: &P,
    operation: &ScopedReader<'d, '_>,
) -> Result<Report<'m, 'd, 'p, E>, CheckError<P::Error>> {
    let processing = CheckError::Processing;
    prepared
        .document()
        .message()
        .require_session(operation, "cades.credentials")
        .map_err(|cause| processing(Error::Cms(cause)))?;
    let selected = prepared.document().locate(prepared.signer().span());
    operation
        .charge(1)
        .map_err(|cause| processing(Error::encoding(cause, "cades.credentials")))?;
    if !core::ptr::eq(prepared, signer.prepared())
        || selected.snapshot != counters.snapshot()
        || selected.node != counters.signature()
        || counters.len() != prepared.counters().len()
    {
        return Err(processing(Error::Foreign {
            at: selected.node.span().start,
        }));
    }
    if !signer.is_bound() {
        return Err(CheckError::Unbound {
            signature: selected.node,
        });
    }
    preflight_properties(prepared, counters, operation)?;
    let mut complete = true;
    let root = group(
        prepared,
        selected.node,
        prepared.properties(),
        signer.certificate(),
        provider,
        operation,
        &mut complete,
    )?;
    let work = operation.execution();
    let mut groups = work.vector();
    for (ordinal, counter) in prepared.counters().iter().enumerate() {
        operation
            .charge(1)
            .map_err(|cause| processing(Error::encoding(cause, "cades.credentials")))?;
        let Some(properties) = counter.properties() else {
            return Err(CheckError::Unbound {
                signature: counter.node(),
            });
        };
        let path = counters.counter(ordinal).path;
        let target = path.members().last().ok_or(CheckError::Unbound {
            signature: counter.node(),
        })?;
        let group = group(
            prepared,
            counter.node(),
            properties,
            target.certificate(),
            provider,
            operation,
            &mut complete,
        )?;
        if !group.entries.is_empty() {
            groups.try_push(group).map_err(|cause| {
                processing(Error::resource(
                    cause,
                    "cades.credentials",
                    counter.node().span().start,
                ))
            })?;
        }
    }
    Ok(Report {
        signature: selected,
        root,
        counters: groups.into_owned(),
        complete,
    })
}

fn preflight_properties<E>(
    prepared: &Preparation<'_, '_>,
    counters: &Paths<'_, '_, '_, '_>,
    operation: &ScopedReader<'_, '_>,
) -> Result<(), CheckError<E>> {
    // A partial or misplaced open-value prefix cannot become a complete
    // protected census. Finish every source check before the first handler.
    if !prepared.signer().faults().is_empty()
        || !prepared.profile().faults().is_empty()
        || !prepared.profile().signing().faults().is_empty()
        || !prepared.properties().faults().is_empty()
    {
        return Err(CheckError::Nonconforming {
            signature: prepared.document().locate(prepared.signer().span()).node,
        });
    }
    for (ordinal, expected) in prepared.counters().iter().enumerate() {
        operation
            .charge(1)
            .map_err(|cause| CheckError::Processing(Error::encoding(cause, "cades.credentials")))?;
        if counters.counter(ordinal).signature != expected.node() {
            return Err(CheckError::Processing(Error::Foreign {
                at: expected.node().span().start,
            }));
        }
        if expected.malformed().is_some()
            || expected
                .properties()
                .is_none_or(|value| !value.faults().is_empty())
        {
            return Err(CheckError::Nonconforming {
                signature: expected.node(),
            });
        }
    }
    Ok(())
}

fn group<'m, 'd, 'p, E, P: Provider<'p, 'd, Evidence = E>>(
    prepared: &Preparation<'m, 'd>,
    signature: Node,
    properties: &Properties<'d>,
    signer: &Certificate<'d>,
    provider: &P,
    operation: &ScopedReader<'d, '_>,
    complete: &mut bool,
) -> Result<Group<'m, 'd, 'p, E>, CheckError<P::Error>> {
    let work = operation.execution();
    let mut entries = work.vector();
    for value in properties.open_values() {
        work.charge_work(1).map_err(|cause| {
            CheckError::Processing(Error::resource(
                cause,
                "cades.credentials",
                signature.span().start,
            ))
        })?;
        if !matches!(
            value.role,
            OpenRole::AttributeCertificate
                | OpenRole::OtherAttributeCertificate
                | OpenRole::SignedAssertion
        ) {
            continue;
        }
        let source = prepared.document().locate(value.enclosure.span());
        let outcome = if value.value.is_none() {
            *complete = false;
            Outcome::Absent
        } else {
            match provider
                .authenticate(Context {
                    source,
                    signature,
                    value: *value,
                    signer,
                    operation,
                })
                .map_err(|cause| CheckError::Provider {
                    node: source.node,
                    cause,
                })? {
                Authentication::Authenticated {
                    evidence,
                    authorities: Authorities::Paths([]),
                } => {
                    *complete = false;
                    Outcome::MissingAuthorities(evidence)
                }
                Authentication::Unsupported => {
                    *complete = false;
                    Outcome::Authentication(Authentication::Unsupported)
                }
                Authentication::Rejected => {
                    *complete = false;
                    Outcome::Authentication(Authentication::Rejected)
                }
                authenticated @ Authentication::Authenticated { .. } => {
                    Outcome::Authentication(authenticated)
                }
            }
        };
        entries
            .try_push(Checked { source, outcome })
            .map_err(|cause| {
                CheckError::Processing(Error::resource(
                    cause,
                    "cades.credentials",
                    source.node.span().start,
                ))
            })?;
    }
    Ok(Group {
        signature,
        entries: entries.into_owned(),
    })
}