structured-xades 0.9.2

XAdES mechanisms over caller-owned XML and explicit resource accounting
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
//! Source-bound independent credentials and their actual authority paths.

use crate::role;
use crate::xml::{Access, AccessError, Snapshot, Xml};
use structured_asn1::memory::{MemoryError, OwnedVec, Work};
use structured_ltv::pki::{self as ltv, Authorities, CredentialGroup, CredentialReceipts};

/// One original credential protected by the selected `SignedProperties` binding.
/// Construction is private; a self-claimed role cannot become a credential.
#[derive(Debug, Clone, Copy)]
pub struct Credential<N, D, G> {
    snapshot: Snapshot<D, G>,
    signature: N,
    entry: role::Entry<N>,
}

impl<N: Copy, D: Copy, G: Copy> Credential<N, D, G> {
    /// Exact original source/generation, never a reconstructed assertion.
    #[must_use]
    pub fn snapshot(self) -> Snapshot<D, G> {
        self.snapshot
    }
    /// Signature protecting this original credential's role property.
    #[must_use]
    pub fn signature(self) -> N {
        self.signature
    }
    /// Original payload, group and selected credential syntax.
    #[must_use]
    pub fn entry(self) -> role::Entry<N> {
        self.entry
    }
}

/// Completed format authentication, separate from application authorization.
pub enum Authentication<'path, 'document, E> {
    /// This original credential format has no selected authentication handler.
    Unsupported,
    /// The selected handler completed and rejected the original credential.
    Rejected,
    /// Original signature/issuer authentication succeeded using exactly these
    /// checked authority paths and their effective keys. This is not approval
    /// of asserted roles, historical trust or revocation/freshness.
    Authenticated {
        /// Actual format-specific authentication receipt, not a trusted flag.
        evidence: E,
        /// Actual format authority/anchor requirements used by this receipt.
        authorities: Authorities<'path, 'document>,
    },
}

/// Format-specific authentication at the original protected credential source.
///
/// EN319132-1 ยง5.2.6 leaves concrete `SignedAssertion` and
/// `OtherAttributeCertificate` content types outside `XAdES`. Their owner reuses
/// its actual format/signature mechanisms; this core does not invent SAML,
/// attribute-certificate syntax or another crypto dispatcher.
/// <https://www.etsi.org/deliver/etsi_en/319100_319199/31913201/01.03.01_60/en_31913201v010301p.pdf>
///
/// Implementations authenticate THIS exact original credential, including its
/// binding to the signer where required by its format, with the returned paths'
/// actual effective keys. They must not substitute a receipt for another
/// credential or omit a path used by authentication. Source decoding, signature
/// work, retained evidence and all intermediate capacity are pre-admitted under
/// current Access/Work and the format owner's enforced limits. Errors preserve
/// resource/processing causes and truthful inner-source provenance. No implicit
/// acquisition, reparsing XML or application authorization is performed here.
pub trait Provider<'path, 'document, X: Xml> {
    /// Actual retained format evidence; may own admitted data or original IDs.
    type Evidence;
    /// Original format/provider/resource failure, not semantic rejection.
    type Error;

    /// Authenticate this original source once under the current operation.
    fn authenticate<W: Work>(
        &self,
        access: &Access<'_, X, W>,
        credential: Credential<X::Id, X::Document, X::Generation>,
    ) -> Result<Authentication<'path, 'document, Self::Evidence>, Self::Error>;
}

/// Actual authentication result retained with its immutable original source.
pub struct Checked<'path, 'document, E, N, D, G> {
    source: Credential<N, D, G>,
    evidence: E,
    authorities: Authorities<'path, 'document>,
}

impl<'path, 'document, E, N: Copy, D: Copy, G: Copy> Checked<'path, 'document, E, N, D, G> {
    /// Same original protected credential processed by the format owner.
    #[must_use]
    pub fn source(&self) -> Credential<N, D, G> {
        self.source
    }
    /// Original retained authentication evidence, without cloning it.
    #[must_use]
    pub fn evidence(&self) -> &E {
        &self.evidence
    }
    /// Actual authority inputs, including an explicit direct anchor or
    /// certificate-free format. Subsequent path traversal must be paid.
    #[must_use]
    pub fn authorities(&self) -> Authorities<'path, 'document> {
        self.authorities
    }
}

/// Complete credential-actor set for this original signed role catalogue.
/// This is neither a baseline grade nor proof of status/material availability.
pub struct Credentials<'path, 'document, E, N, D, G> {
    snapshot: Snapshot<D, G>,
    signature: N,
    entries: OwnedVec<Checked<'path, 'document, E, N, D, G>>,
}

impl<'path, 'document, E, N: Copy, D: Copy, G: Copy> Credentials<'path, 'document, E, N, D, G> {
    /// Original protected role source/generation.
    #[must_use]
    pub fn snapshot(&self) -> Snapshot<D, G> {
        self.snapshot
    }
    /// Original selected signature, independent of a credential issuer.
    #[must_use]
    pub fn signature(&self) -> N {
        self.signature
    }
    /// Every independently authenticated credential in original order.
    #[must_use]
    pub fn entries(&self) -> &[Checked<'path, 'document, E, N, D, G>] {
        &self.entries
    }
}

// One signature's authenticated credentials are a common credential group.
impl<'path, 'document, E, N: Copy, D: Copy, G: Copy> CredentialGroup<'path, 'document>
    for Credentials<'path, 'document, E, N, D, G>
{
    type Id = N;

    fn signature(&self) -> N {
        self.signature
    }

    fn len(&self) -> usize {
        self.entries.len()
    }

    fn credential(&self, ordinal: usize) -> ltv::Credential<'path, 'document, N> {
        let checked = &self.entries[ordinal];
        ltv::Credential {
            signature: checked.source.signature,
            node: checked.source.entry.node,
            authorities: checked.authorities,
        }
    }
}

/// Refusal does not return a successfully checked credential prefix.
#[derive(Debug)]
pub enum Error<E, PE, N> {
    /// Caller supplied a complete counter set from another selected signature.
    Foreign {
        /// Original root signature expected by this operation.
        signature: N,
    },
    /// Original source/generation or operation refused.
    Access(AccessError<E, N>),
    /// The selected original format is unsupported, not absent or authenticated.
    Unsupported {
        /// Original credential payload.
        node: N,
    },
    /// Completed original credential authentication was negative.
    Rejected {
        /// Original credential payload.
        node: N,
    },
    /// A handler selected certificate paths but returned an empty set. Direct
    /// anchors and certificate-free formats require their explicit arms; this
    /// is incomplete provider evidence, not bad XML.
    MissingAuthorities {
        /// Original credential payload.
        node: N,
    },
    /// Original provider failure with its credential source retained.
    Provider {
        /// Original credential payload.
        node: N,
        /// Unchanged provider/resource cause.
        cause: PE,
    },
    /// Retained catalogue storage/copy work was not admitted.
    Resource {
        /// Original credential payload or catalogue for empty input.
        node: N,
        /// Actual memory/work refusal.
        cause: MemoryError,
    },
}

/// Complete original credential authentication and retained-source result.
pub type CheckResult<'path, 'document, X, P> = Result<
    Credentials<
        'path,
        'document,
        <P as Provider<'path, 'document, X>>::Evidence,
        <X as Xml>::Id,
        <X as Xml>::Document,
        <X as Xml>::Generation,
    >,
    Error<<X as Xml>::Error, <P as Provider<'path, 'document, X>>::Error, <X as Xml>::Id>,
>;

/// Authenticate EVERY original non-claimed credential before returning the
/// complete authority-input set required by EN319132-1 ยง6.3(aa). The original
/// catalogue determines this set, never a caller-selected list of successes.
/// Claimed roles are traversed and paid but need no independent issuer check.
/// A late unsupported/rejected credential or terminal refusal drops all earlier
/// retained evidence. External provider side effects cannot be rolled back.
pub fn check<'path, 'document, X: Xml, P: Provider<'path, 'document, X>, W: Work>(
    roles: &role::Catalogue<X>,
    provider: &P,
    access: &Access<'_, X, W>,
) -> CheckResult<'path, 'document, X, P> {
    if roles.snapshot() != access.snapshot() {
        return Err(Error::Access(AccessError::Changed { node: roles.node() }));
    }
    let mut entries = access
        .query(roles.node(), |_, _, work| Ok(work.vector()))
        .map_err(Error::Access)?;
    for entry in roles.entries() {
        access
            .query(entry.node, |_, _, work| Ok(work.charge_work(1)))
            .map_err(Error::Access)?
            .map_err(|cause| Error::Resource {
                node: entry.node,
                cause,
            })?;
        if entry.kind == role::Kind::Claimed {
            continue;
        }
        let source = Credential {
            snapshot: roles.snapshot(),
            signature: roles.signature(),
            entry: *entry,
        };
        let outcome = access
            .query(entry.node, |_, _, _| {
                Ok(provider.authenticate(access, source))
            })
            .map_err(Error::Access)?
            .map_err(|cause| Error::Provider {
                node: entry.node,
                cause,
            })?;
        let (evidence, authorities) = match outcome {
            Authentication::Unsupported => return Err(Error::Unsupported { node: entry.node }),
            Authentication::Rejected => return Err(Error::Rejected { node: entry.node }),
            Authentication::Authenticated {
                evidence,
                authorities,
            } => (evidence, authorities),
        };
        if let Authorities::Paths(paths) = authorities
            && paths.is_empty()
        {
            return Err(Error::MissingAuthorities { node: entry.node });
        }
        entries
            .try_push(Checked {
                source,
                evidence,
                authorities,
            })
            .map_err(|cause| Error::Resource {
                node: entry.node,
                cause,
            })?;
    }
    access
        .query(roles.node(), |_, _, _| Ok(()))
        .map_err(Error::Access)?;
    Ok(Credentials {
        snapshot: roles.snapshot(),
        signature: roles.signature(),
        entries: entries.into_owned(),
    })
}

/// Actual credentials of one incorporated counter, retaining its source edge.
pub struct CounterCredentials<'path, 'document, E, N, D, G> {
    source: crate::counter::Checked<N, D, G>,
    credentials: Credentials<'path, 'document, E, N, D, G>,
}

impl<'path, 'document, E, N, D, G> CounterCredentials<'path, 'document, E, N, D, G> {
    /// Original checked child/parent signature coverage receipt.
    #[must_use]
    pub fn source(&self) -> &crate::counter::Checked<N, D, G> {
        &self.source
    }
    /// Every credential of this counter, without a copied catalogue/evidence.
    #[must_use]
    pub fn credentials(&self) -> &Credentials<'path, 'document, E, N, D, G> {
        &self.credentials
    }
}

/// Complete current-role credentials of the root and all incorporated counters.
/// No caller-provided success list determines which groups are visited. Other
/// actor path/status/material and format-specific obligations remain separate.
pub struct ParticipantCredentials<'path, 'document, E, N, D, G> {
    snapshot: Snapshot<D, G>,
    signature: N,
    root: Option<Credentials<'path, 'document, E, N, D, G>>,
    counters: OwnedVec<CounterCredentials<'path, 'document, E, N, D, G>>,
}

impl<'path, 'document, E, N: Copy, D: Copy, G: Copy>
    ParticipantCredentials<'path, 'document, E, N, D, G>
{
    /// Original root source and generation for the whole participant set.
    #[must_use]
    pub fn snapshot(&self) -> Snapshot<D, G> {
        self.snapshot
    }
    /// Original root signature, independent of every credential issuer.
    #[must_use]
    pub fn signature(&self) -> N {
        self.signature
    }
    /// All original root credentials, if a role property was present.
    #[must_use]
    pub fn root(&self) -> Option<&Credentials<'path, 'document, E, N, D, G>> {
        self.root.as_ref()
    }
    /// Every incorporated counter with a protected current role property.
    /// Other counters remain in the separate complete counter-signer census.
    #[must_use]
    pub fn counters(&self) -> &[CounterCredentials<'path, 'document, E, N, D, G>] {
        &self.counters
    }
}

// The root and counter credential groups are the common credential census.
impl<'path, 'document, E, N: Copy, D: Copy, G: Copy> CredentialReceipts<'path, 'document>
    for ParticipantCredentials<'path, 'document, E, N, D, G>
{
    type Id = N;
    type Document = D;
    type Generation = G;
    type Group = Credentials<'path, 'document, E, N, D, G>;

    fn snapshot(&self) -> Snapshot<D, G> {
        self.snapshot
    }

    fn signature(&self) -> N {
        self.signature
    }

    fn root(&self) -> Option<&Self::Group> {
        self.root.as_ref()
    }

    fn counters(&self) -> usize {
        self.counters.len()
    }

    fn counter(&self, ordinal: usize) -> (N, &Self::Group) {
        let counter = &self.counters[ordinal];
        (counter.source.original().child(), &counter.credentials)
    }
}

/// Source-bound complete credential participants in this XML identity domain.
pub type ParticipantResult<'path, 'document, X, P> = Result<
    ParticipantCredentials<
        'path,
        'document,
        <P as Provider<'path, 'document, X>>::Evidence,
        <X as Xml>::Id,
        <X as Xml>::Document,
        <X as Xml>::Generation,
    >,
    Error<<X as Xml>::Error, <P as Provider<'path, 'document, X>>::Error, <X as Xml>::Id>,
>;

/// Check every credential group of the original root and COMPLETE counter set.
/// Reuses `check` rather than another credential decoder/authenticator. Missing
/// paths, unsupported formats and all late refusals release partial groups.
/// No root/counter signature or certificate-path mathematics is repeated.
pub fn check_participants<'path, 'document, X: Xml, P: Provider<'path, 'document, X>, W: Work>(
    prepared: &crate::prepare::Prepared<X>,
    counters: &crate::pki::CounterPaths<'_, '_, X::Id, X::Document, X::Generation>,
    provider: &P,
    access: &Access<'_, X, W>,
) -> ParticipantResult<'path, 'document, X, P> {
    use structured_asn1::memory::HashWork;
    let layout = prepared.bound().containers();
    let signature = layout.signature();
    if layout.snapshot() != access.snapshot() || counters.snapshot() != access.snapshot() {
        return Err(Error::Access(AccessError::Changed { node: signature }));
    }
    let mut groups = access
        .query(signature, |_, _, work| Ok(work.vector()))
        .map_err(Error::Access)?;
    let cost = signature
        .hash_work()
        .and_then(|cost| {
            cost.checked_add(counters.signature().hash_work()?)
                .ok_or(MemoryError::WorkExceeded)
        })
        .map_err(|cause| Error::Resource {
            node: signature,
            cause,
        })?;
    access
        .execution()
        .charge_work(cost)
        .map_err(|cause| Error::Resource {
            node: signature,
            cause,
        })?;
    if signature != counters.signature() {
        return Err(Error::Foreign { signature });
    }
    let root = match prepared.roles() {
        Some(roles) => Some(check(roles, provider, access)?),
        None => None,
    };
    for actor in counters.actors() {
        access
            .query(signature, |_, _, work| Ok(work.charge_work(1)))
            .map_err(Error::Access)?
            .map_err(|cause| Error::Resource {
                node: signature,
                cause,
            })?;
        let Some(roles) = actor.roles() else {
            continue;
        };
        let credentials = check(roles, provider, access)?;
        groups
            .try_push(CounterCredentials {
                source: *actor.signer().counter(),
                credentials,
            })
            .map_err(|cause| Error::Resource {
                node: roles.node(),
                cause,
            })?;
    }
    access
        .query(signature, |_, _, _| Ok(()))
        .map_err(Error::Access)?;
    Ok(ParticipantCredentials {
        snapshot: layout.snapshot(),
        signature,
        root,
        counters: groups.into_owned(),
    })
}