structured-xades 0.21.1

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
//! Recomputed Manifest digests before an archive is requested.

use super::check::{self, Input, Mode};
use crate::{
    binding::{Bound, Status},
    certificate::{self, Agreement, DigestProvider},
    container::DS,
    digest,
    produce::{Emit, Error, Transaction},
    reference::ObjectLocation,
    timestamp::{TimestampXml, XADES_141},
    xml::{Access, Snapshot},
};
use structured_asn1::{
    digest::Resolution,
    memory::{OwnedVec, Work},
};

/// One original authenticated Manifest instruction offered to the caller's
/// algorithm-longevity decision. The format does not invent a weak-hash policy.
#[derive(Debug, Clone, Copy)]
pub struct Candidate<N> {
    /// Original Reference instruction, not its detached target.
    pub reference: N,
    /// Actual resolver-observed origin, not inferred from URI spelling.
    pub location: ObjectLocation,
    /// Completed original reference outcome.
    pub status: Status,
}

/// Failure before a complete renewal can be returned or written.
#[derive(Debug)]
pub enum CreationError<E, PE, N, D, G> {
    /// Original append-position traversal/source/resource refusal.
    Input(crate::timestamp::InputError<E, N>),
    /// Original source, method, provider, traversal or streaming failure.
    Processing(super::CheckError<E, PE, N, D, G>),
    /// Selected old/new algorithm is unsupported, malformed or prohibited.
    Algorithm {
        /// Actual offending method.
        method: N,
        /// Completed algorithm classification.
        answer: Agreement,
    },
    /// Classification of the supplied new parameter-free method, not a source node.
    NewAlgorithm(Agreement),
    /// Original construction resolver cause, including deployment/resource refusal.
    NewProvider(PE),
    /// Selected instruction is not an actual successfully checked detached reference.
    Ineligible {
        /// Original instruction.
        reference: N,
    },
    /// New and old semantic digest identities are equal.
    Unchanged {
        /// Original instruction whose digest was not strengthened.
        reference: N,
    },
}

struct Pair<N, O> {
    reference: N,
    instruction: O,
    object: O,
}

/// Complete recomputed pairs from the selected original Manifest instructions.
/// Output ownership is that of the existing selected digest provider. No whole
/// detached input is buffered, and no URI-based algorithm dispatcher is added.
pub struct Renewal<'method, N, D, G, O> {
    snapshot: Snapshot<D, G>,
    signature: N,
    parent: Option<N>,
    canonicalization: N,
    digest: &'method str,
    pairs: OwnedVec<Pair<N, O>>,
}

impl<N: Copy, D: Copy + Eq, G: Copy + Eq, O: AsRef<[u8]>> Renewal<'_, N, D, G, O> {
    /// Number of actual selected original instructions, not a success subset.
    #[must_use]
    pub fn len(&self) -> usize {
        self.pairs.len()
    }
    /// No selected expiring digest means no property should be written.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.pairs.is_empty()
    }

    /// Append the original computed pairs in selection order. The transaction
    /// copies the original canonicalization method with its parameters and
    /// emits the exact new parameter-free digest URI resolved during creation.
    /// EN319132-1 ยง5.5.3 requires ordinary `ReferenceOutput` for `NewSDODigestValue`
    /// and canonicalized Reference XML for `OriginalRefDigest`, in that order.
    /// <https://www.etsi.org/deliver/etsi_en/319100_319199/31913201/01.03.01_60/en_31913201v010301p.pdf>
    pub fn write<B: Transaction<Id = N, Document = D, Generation = G>, W: Work>(
        &self,
        writer: &mut B,
        work: &W,
    ) -> Result<(), Error<B::Error>>
    where
        N: structured_asn1::memory::HashWork,
    {
        work.charge_work(1).map_err(Error::Resource)?;
        if writer.base() != self.snapshot
            || !structured_ltv::source::equal_id(writer.signature(), self.signature, work)
                .map_err(Error::Resource)?
            || !crate::produce::same_parent(writer.unsigned_parent(), self.parent, work)
                .map_err(Error::Resource)?
        {
            return Err(Error::Foreign);
        }
        if self.pairs.is_empty() {
            return Ok(());
        }
        let mut emit = Emit { writer, work };
        emit.begin(XADES_141, "RenewedDigestsV2")?;
        work.charge_work(1).map_err(Error::Resource)?;
        emit.writer
            .method(self.canonicalization, work)
            .map_err(Error::Writer)?;
        emit.begin(DS, "DigestMethod")?;
        emit.attribute("Algorithm", self.digest)?;
        emit.end()?;
        for pair in &self.pairs {
            emit.begin(XADES_141, "RecomputedDigestValue")?;
            emit.binary(XADES_141, "NewSDODigestValue", pair.object.as_ref())?;
            emit.binary(XADES_141, "OriginalRefDigest", pair.instruction.as_ref())?;
            emit.end()?;
        }
        emit.end()?;
        work.charge_work(1).map_err(Error::Resource)?;
        if emit.writer.base() != self.snapshot
            || !structured_ltv::source::equal_id(emit.writer.signature(), self.signature, work)
                .map_err(Error::Resource)?
            || !crate::produce::same_parent(emit.writer.unsigned_parent(), self.parent, work)
                .map_err(Error::Resource)?
        {
            return Err(Error::Foreign);
        }
        Ok(())
    }
    /// Actual original instruction ordinal-to-identity mapping, without copying.
    pub fn references(&self) -> impl ExactSizeIterator<Item = N> + '_ {
        self.pairs.iter().map(|p| p.reference)
    }
}

/// Creation result in the XML owner's source and error domain.
pub type CreationResult<T, X, PE> = Result<
    T,
    CreationError<
        <X as crate::xml::Xml>::Error,
        PE,
        <X as crate::xml::Xml>::Id,
        <X as crate::xml::Xml>::Document,
        <X as crate::xml::Xml>::Generation,
    >,
>;
/// Complete new renewal with the selected provider's actual output storage.
pub type Created<'method, 'p, X, P> = Renewal<
    'method,
    <X as crate::xml::Xml>::Id,
    <X as crate::xml::Xml>::Document,
    <X as crate::xml::Xml>::Generation,
    <P as structured_asn1::digest::Digest<'p>>::Output,
>;

/// New parameter-free XML digest methods through the SAME selected provider.
/// This capability does not add a dispatcher or change existing-node resolution.
pub trait MethodProvider<'p, X: crate::xml::Xml>: DigestProvider<'p, X> {
    /// Resolve exactly this URI under the current operation's compiled policy.
    /// It is emitted unchanged as the new `DigestMethod` Algorithm attribute.
    /// Admit lexical scans, policy evaluation and any retained identity storage
    /// through `work` before execution. Reject noncanonical lexical input as
    /// `Malformed`; do not normalize into a different emitted value. Methods
    /// requiring parameters are `Unsupported` or `Malformed`, never silently
    /// assigned absent/default parameters. Original terminal errors stay errors.
    fn resolve_new<W: Work>(
        &self,
        algorithm: &str,
        work: &W,
    ) -> Result<Resolution<Self::Identity>, Self::Error>;
}

/// Resolve every selected method before starting any digest/source callback.
/// Selection examines the complete authenticated Manifest census under Work;
/// unknown origin/unchecked/invalid selected instructions refuse, never skip.
/// Both hashes reuse validation's source and digest kernels. Strength beyond
/// semantic inequality is the caller's explicit algorithm-longevity policy.
pub fn create<'method, 'p, X, P, W>(
    xml: &X,
    bound: &Bound<X::Id, X::Document, X::Generation>,
    canonicalization: X::Id,
    new_method: &'method str,
    provider: &'p P,
    work: &W,
    selected: impl FnMut(Candidate<X::Id>, &W) -> Result<bool, P::Error>,
) -> CreationResult<Created<'method, 'p, X, P>, X, P::Error>
where
    X: TimestampXml,
    P: MethodProvider<'p, X>,
    W: Work,
{
    let layout = bound.containers();
    let access = Access::new(xml, layout.snapshot(), work);
    let processing = CreationError::Processing;
    let resource = |cause| {
        processing(super::CheckError::Resource {
            node: layout.signature(),
            cause,
        })
    };
    let parent = match layout.unsigned() {
        Some(unsigned) => crate::timestamp::optional(
            &access,
            unsigned,
            crate::container::XADES,
            "UnsignedSignatureProperties",
        )
        .map_err(CreationError::Input)?,
        None => None,
    };
    access
        .query(layout.signature(), |_, _, _| Ok(()))
        .map_err(|e| processing(super::CheckError::Access(e)))?;
    if !access
        .has_name(
            canonicalization,
            crate::xml::Name {
                namespace: crate::container::DS,
                local: "CanonicalizationMethod",
            },
        )
        .map_err(|e| processing(super::CheckError::Access(e)))?
    {
        return Err(CreationError::Ineligible {
            reference: canonicalization,
        });
    }
    let identity = resolve_new(&access, layout.signature(), new_method, provider)?;
    let choices = choose(&access, layout.signature(), &identity, provider, selected)?;
    let mut pairs = work.vector();
    pairs.try_reserve_exact(choices.len()).map_err(resource)?;
    for reference in choices {
        let mut source = Input {
            xml,
            snapshot: layout.snapshot(),
            mode: Mode::Canonical {
                node: reference,
                method: canonicalization,
            },
        };
        let instruction = computed(&identity, &mut source, provider, work, reference)?;
        source.mode = Mode::Reference {
            signature: layout.signature(),
            node: reference,
        };
        let object = computed(&identity, &mut source, provider, work, reference)?;
        pairs
            .try_push(Pair {
                reference,
                instruction,
                object,
            })
            .map_err(resource)?;
    }
    access
        .query(layout.signature(), |_, _, _| Ok(()))
        .map_err(|e| processing(super::CheckError::Access(e)))?;
    Ok(Renewal {
        snapshot: layout.snapshot(),
        signature: layout.signature(),
        parent,
        canonicalization,
        digest: new_method,
        pairs: pairs.into_owned(),
    })
}

fn resolve_new<'p, X: TimestampXml, P: MethodProvider<'p, X>, W: Work>(
    access: &Access<'_, X, W>,
    signature: X::Id,
    algorithm: &str,
    provider: &P,
) -> CreationResult<certificate::FormatDigest<P::Identity>, X, P::Error> {
    if let Some(answer) =
        certificate::preflight_algorithm(algorithm, access.execution()).map_err(|cause| {
            CreationError::Processing(super::CheckError::Resource {
                node: signature,
                cause,
            })
        })?
    {
        return Err(CreationError::NewAlgorithm(answer));
    }
    let resolved = access
        .query(signature, |_, _, work| {
            Ok(provider.resolve_new(algorithm, work))
        })
        .map_err(|e| CreationError::Processing(super::CheckError::Access(e)))?
        .map_err(CreationError::NewProvider)?;
    let resolved = match resolved {
        Resolution::Supported(identity) => identity,
        Resolution::Unsupported => return Err(CreationError::NewAlgorithm(Agreement::Unsupported)),
        Resolution::Malformed => {
            return Err(CreationError::NewAlgorithm(Agreement::MalformedMethod));
        }
    };
    match certificate::baseline_digest::<X, P>(resolved, provider) {
        certificate::Expected::Ready(identity) => Ok(identity),
        certificate::Expected::Answer(answer) => Err(CreationError::NewAlgorithm(answer)),
    }
}

fn choose<'p, X: TimestampXml, P: DigestProvider<'p, X>, W: Work>(
    access: &Access<'_, X, W>,
    signature: X::Id,
    identity: &certificate::FormatDigest<P::Identity>,
    provider: &P,
    mut selected: impl FnMut(Candidate<X::Id>, &W) -> Result<bool, P::Error>,
) -> CreationResult<OwnedVec<X::Id>, X, P::Error> {
    let work = access.execution();
    let processing = CreationError::Processing;
    let resource = |cause| {
        processing(super::CheckError::Resource {
            node: signature,
            cause,
        })
    };
    let instructions = check::inventory(access, signature, signature).map_err(processing)?;
    let mut choices = work.vector();
    for instruction in instructions {
        work.charge_work(1).map_err(resource)?;
        let choose = selected(
            Candidate {
                reference: instruction.node,
                location: instruction.location,
                status: instruction.status,
            },
            work,
        )
        .map_err(|cause| {
            processing(super::CheckError::Provider {
                node: instruction.node,
                cause,
            })
        })?;
        if !choose {
            continue;
        }
        if instruction.location != ObjectLocation::Detached || instruction.status != Status::Valid {
            return Err(CreationError::Ineligible {
                reference: instruction.node,
            });
        }
        let method = check::original_method(access, instruction.node)
            .map_err(|e| processing(super::CheckError::Property(e)))?;
        let old = match check::resolve(access, method, provider).map_err(processing)? {
            certificate::Expected::Ready(identity) => identity,
            certificate::Expected::Answer(answer) => {
                return Err(CreationError::Algorithm { method, answer });
            }
        };
        work.charge_work(1).map_err(resource)?;
        if provider
            .compare(old.identity(), identity.identity(), work)
            .map_err(|cause| {
                processing(super::CheckError::Provider {
                    node: method,
                    cause,
                })
            })?
            == core::cmp::Ordering::Equal
        {
            return Err(CreationError::Unchanged {
                reference: instruction.node,
            });
        }
        choices.try_push(instruction.node).map_err(resource)?;
    }
    Ok(choices.into_owned())
}

fn computed<'p, X: TimestampXml, P: DigestProvider<'p, X>, W: Work>(
    identity: &certificate::FormatDigest<P::Identity>,
    source: &mut Input<'_, X>,
    provider: &'p P,
    work: &W,
    node: X::Id,
) -> CreationResult<P::Output, X, P::Error> {
    match digest::compute_resolved::<P, _, _>(identity, source, provider, work)
        .map_err(|cause| CreationError::Processing(super::CheckError::Digest { node, cause }))?
    {
        Resolution::Supported(output) => Ok(output),
        Resolution::Unsupported => Err(CreationError::Algorithm {
            method: node,
            answer: Agreement::Unsupported,
        }),
        Resolution::Malformed => Err(CreationError::Algorithm {
            method: node,
            answer: Agreement::MalformedMethod,
        }),
    }
}