xdoc-rs 0.1.1

Declarative XML engine for Rust
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
use sha2::{Digest, Sha256};

use crate::core::{Attribute, Document, ErrorKind, NodeId, NodeKind, QName, XmlError, XmlResult};

use super::xmldsig::{
    element_children, find_signature, required_child, required_child_text, XMLDSIG_NAMESPACE_URI,
};
use super::{
    canonicalize_node, decode_standard_base64, digest_bytes, encode_standard_base64,
    CanonicalizationConfig, DigestAlgorithm, XADES_NAMESPACE_URI,
};

/// Request sent to a timestamp authority abstraction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimestampRequest {
    pub digest_algorithm: DigestAlgorithm,
    pub message_imprint: Vec<u8>,
}

/// Opaque timestamp token bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimestampToken {
    pub encoded: Vec<u8>,
}

impl TimestampToken {
    pub fn new(encoded: impl Into<Vec<u8>>) -> Self {
        Self {
            encoded: encoded.into(),
        }
    }
}

/// Supplies timestamp tokens for XAdES unsigned properties.
///
/// Implementations may call a real TSA, HSM, KMS, or local service, but the
/// engine does not include any network client by default.
pub trait TimestampAuthorityClient {
    fn timestamp(&self, request: &TimestampRequest) -> XmlResult<TimestampToken>;

    fn verify(&self, request: &TimestampRequest, token: &TimestampToken) -> XmlResult<bool> {
        Ok(self.timestamp(request)?.encoded == token.encoded)
    }
}

/// Deterministic timestamp authority for tests and fixtures.
///
/// This is not an RFC 3161 implementation. It creates stable opaque bytes so
/// the XAdES-T structure and message-imprint flow can be tested without
/// enabling network access.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeterministicTimestampAuthority {
    secret: Vec<u8>,
}

impl DeterministicTimestampAuthority {
    pub fn new(secret: impl Into<Vec<u8>>) -> Self {
        Self {
            secret: secret.into(),
        }
    }
}

impl TimestampAuthorityClient for DeterministicTimestampAuthority {
    fn timestamp(&self, request: &TimestampRequest) -> XmlResult<TimestampToken> {
        let mut hasher = Sha256::new();
        hasher.update(b"xdoc-deterministic-timestamp");
        hasher.update([0]);
        hasher.update(request.digest_algorithm.uri().as_bytes());
        hasher.update([0]);
        hasher.update(&self.secret);
        hasher.update([0]);
        hasher.update(&request.message_imprint);
        Ok(TimestampToken::new(hasher.finalize().to_vec()))
    }
}

/// Configuration for adding and validating XAdES signature timestamps.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct XadesTimestampConfig {
    digest_algorithm: DigestAlgorithm,
    canonicalization: CanonicalizationConfig,
}

impl XadesTimestampConfig {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_digest_algorithm(mut self, digest_algorithm: DigestAlgorithm) -> Self {
        self.digest_algorithm = digest_algorithm;
        self
    }

    pub fn with_canonicalization(mut self, canonicalization: CanonicalizationConfig) -> Self {
        self.canonicalization = canonicalization;
        self
    }

    pub fn digest_algorithm(&self) -> DigestAlgorithm {
        self.digest_algorithm
    }

    pub fn canonicalization(&self) -> &CanonicalizationConfig {
        &self.canonicalization
    }
}

impl Default for XadesTimestampConfig {
    fn default() -> Self {
        Self {
            digest_algorithm: DigestAlgorithm::Sha256,
            canonicalization: CanonicalizationConfig::default(),
        }
    }
}

/// Result of validating a XAdES SignatureTimeStamp.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimestampValidationReport {
    pub timestamp_present: bool,
    pub structure_valid: bool,
    pub token_valid: bool,
    pub message_imprint: Vec<u8>,
}

/// Adds `xades:SignatureTimeStamp` as an unsigned property to an existing XAdES signature.
pub fn add_signature_timestamp<C>(
    document: &Document,
    client: &C,
    config: &XadesTimestampConfig,
) -> XmlResult<Document>
where
    C: TimestampAuthorityClient + ?Sized,
{
    config.digest_algorithm.ensure_allowed_for_generation()?;

    let mut timestamped = document.clone();
    let signature = find_signature(&timestamped)?;
    let signature_value = required_child(&timestamped, signature, "SignatureValue")?;
    let message_imprint = signature_value_message_imprint(&timestamped, signature_value, config)?;
    let request = TimestampRequest {
        digest_algorithm: config.digest_algorithm,
        message_imprint,
    };
    let token = client.timestamp(&request)?;
    let qualifying_properties = find_qualifying_properties(&timestamped, signature)?;
    let unsigned_signature_properties =
        ensure_unsigned_signature_properties(&mut timestamped, qualifying_properties)?;

    if optional_xades_child(
        &timestamped,
        unsigned_signature_properties,
        "SignatureTimeStamp",
    )?
    .is_some()
    {
        return Err(XmlError::new(
            ErrorKind::Signature,
            "XAdES SignatureTimeStamp already exists",
        ));
    }

    let signature_timestamp = timestamped.add_element(
        unsigned_signature_properties,
        QName::qualified("xades", "SignatureTimeStamp", XADES_NAMESPACE_URI)?,
    )?;
    let canonicalization = timestamped.add_element(
        signature_timestamp,
        QName::qualified("ds", "CanonicalizationMethod", XMLDSIG_NAMESPACE_URI)?,
    )?;
    timestamped.add_attribute(
        canonicalization,
        Attribute::new(
            QName::new("Algorithm")?,
            config.canonicalization.algorithm().uri(),
        ),
    )?;
    let encoded = timestamped.add_element(
        signature_timestamp,
        QName::qualified("xades", "EncapsulatedTimeStamp", XADES_NAMESPACE_URI)?,
    )?;
    timestamped.add_text(encoded, encode_standard_base64(&token.encoded))?;

    Ok(timestamped)
}

/// Validates the presence, structure, and opaque token of a XAdES SignatureTimeStamp.
pub fn verify_signature_timestamp<C>(
    document: &Document,
    client: &C,
    config: &XadesTimestampConfig,
) -> XmlResult<TimestampValidationReport>
where
    C: TimestampAuthorityClient + ?Sized,
{
    config.digest_algorithm.ensure_allowed_for_generation()?;

    let signature = find_signature(document)?;
    let signature_value = required_child(document, signature, "SignatureValue")?;
    let message_imprint = signature_value_message_imprint(document, signature_value, config)?;
    let Some(signature_timestamp) = find_signature_timestamp(document, signature)? else {
        return Ok(TimestampValidationReport {
            timestamp_present: false,
            structure_valid: false,
            token_valid: false,
            message_imprint,
        });
    };

    let canonicalization_method =
        required_child(document, signature_timestamp, "CanonicalizationMethod")?;
    let canonicalization_algorithm =
        optional_attribute(document, canonicalization_method, "Algorithm")?.ok_or_else(|| {
            XmlError::new(
                ErrorKind::Signature,
                "XAdES SignatureTimeStamp CanonicalizationMethod requires Algorithm",
            )
        })?;
    let structure_valid = canonicalization_algorithm == config.canonicalization.algorithm().uri();
    let token_text = required_child_text(document, signature_timestamp, "EncapsulatedTimeStamp")?;
    let token = TimestampToken::new(decode_standard_base64(&token_text)?);
    let request = TimestampRequest {
        digest_algorithm: config.digest_algorithm,
        message_imprint: message_imprint.clone(),
    };
    let token_valid = structure_valid && client.verify(&request, &token)?;

    Ok(TimestampValidationReport {
        timestamp_present: true,
        structure_valid,
        token_valid,
        message_imprint,
    })
}

fn signature_value_message_imprint(
    document: &Document,
    signature_value: NodeId,
    config: &XadesTimestampConfig,
) -> XmlResult<Vec<u8>> {
    let canonicalized = canonicalize_node(document, signature_value, &config.canonicalization)?;
    digest_bytes(config.digest_algorithm, canonicalized)
}

fn find_signature_timestamp(document: &Document, signature: NodeId) -> XmlResult<Option<NodeId>> {
    let qualifying_properties = find_qualifying_properties(document, signature)?;
    let Some(unsigned_properties) =
        optional_xades_child(document, qualifying_properties, "UnsignedProperties")?
    else {
        return Ok(None);
    };
    let Some(unsigned_signature_properties) =
        optional_xades_child(document, unsigned_properties, "UnsignedSignatureProperties")?
    else {
        return Ok(None);
    };
    optional_xades_child(
        document,
        unsigned_signature_properties,
        "SignatureTimeStamp",
    )
}

fn ensure_unsigned_signature_properties(
    document: &mut Document,
    qualifying_properties: NodeId,
) -> XmlResult<NodeId> {
    let unsigned_properties =
        match optional_xades_child(document, qualifying_properties, "UnsignedProperties")? {
            Some(node) => node,
            None => document.add_element(
                qualifying_properties,
                QName::qualified("xades", "UnsignedProperties", XADES_NAMESPACE_URI)?,
            )?,
        };

    match optional_xades_child(document, unsigned_properties, "UnsignedSignatureProperties")? {
        Some(node) => Ok(node),
        None => document.add_element(
            unsigned_properties,
            QName::qualified("xades", "UnsignedSignatureProperties", XADES_NAMESPACE_URI)?,
        ),
    }
}

fn find_qualifying_properties(document: &Document, signature: NodeId) -> XmlResult<NodeId> {
    let object = required_child(document, signature, "Object")?;
    element_children(document, object)?
        .into_iter()
        .find(|child| is_xades_element(document, *child, "QualifyingProperties"))
        .ok_or_else(|| {
            XmlError::new(
                ErrorKind::Signature,
                "missing required XAdES QualifyingProperties",
            )
        })
}

fn optional_xades_child(
    document: &Document,
    parent: NodeId,
    local: &str,
) -> XmlResult<Option<NodeId>> {
    Ok(element_children(document, parent)?
        .into_iter()
        .find(|child| is_xades_element(document, *child, local)))
}

fn optional_attribute(document: &Document, node: NodeId, local: &str) -> XmlResult<Option<String>> {
    let NodeKind::Element(element) = document.node(node)?.kind() else {
        return Ok(None);
    };
    Ok(element
        .attributes()
        .iter()
        .find(|attribute| attribute.name().local() == local)
        .map(|attribute| attribute.value().to_owned()))
}

fn is_xades_element(document: &Document, node: NodeId, local: &str) -> bool {
    matches!(
        document.node(node).map(|node| node.kind()),
        Ok(NodeKind::Element(element))
            if element.name().namespace_uri().map(|uri| uri.as_str()) == Some(XADES_NAMESPACE_URI)
                && element.name().local() == local
    )
}

#[cfg(test)]
mod tests {
    use crate::parser::parse_str;
    use crate::signature::{
        sign_xades_bes_enveloped, verify_xades_bes_enveloped, DeterministicSigningProvider,
        XadesConfig,
    };
    use crate::writer::to_string_compact;

    use super::*;

    fn signing_provider() -> DeterministicSigningProvider {
        DeterministicSigningProvider::new(b"test-cert".to_vec(), b"test-secret".to_vec())
    }

    fn timestamp_client() -> DeterministicTimestampAuthority {
        DeterministicTimestampAuthority::new(b"timestamp-secret".to_vec())
    }

    fn unsigned_document() -> XmlResult<Document> {
        parse_str(r#"<Root Id="doc-1"><Item>value</Item></Root>"#)
    }

    fn signed_document() -> XmlResult<Document> {
        sign_xades_bes_enveloped(
            &unsigned_document()?,
            &signing_provider(),
            &XadesConfig::new().with_signing_time("2026-06-11T12:00:00Z"),
        )
    }

    #[test]
    fn xades_timestamp_adds_unsigned_signature_timestamp() -> XmlResult<()> {
        let timestamped = add_signature_timestamp(
            &signed_document()?,
            &timestamp_client(),
            &XadesTimestampConfig::new(),
        )?;
        let xml = to_string_compact(&timestamped)?;
        let report = verify_signature_timestamp(
            &timestamped,
            &timestamp_client(),
            &XadesTimestampConfig::new(),
        )?;

        assert!(report.timestamp_present);
        assert!(report.structure_valid);
        assert!(report.token_valid);
        assert!(xml.contains("<xades:UnsignedProperties>"));
        assert!(xml.contains("<xades:UnsignedSignatureProperties>"));
        assert!(xml.contains("<xades:SignatureTimeStamp>"));
        assert!(xml.contains("<xades:EncapsulatedTimeStamp>"));
        assert!(
            verify_xades_bes_enveloped(&timestamped, &signing_provider(), &XadesConfig::new())?
                .valid
        );
        Ok(())
    }

    #[test]
    fn xades_timestamp_report_marks_missing_timestamp() -> XmlResult<()> {
        let report = verify_signature_timestamp(
            &signed_document()?,
            &timestamp_client(),
            &XadesTimestampConfig::new(),
        )?;

        assert!(!report.timestamp_present);
        assert!(!report.structure_valid);
        assert!(!report.token_valid);
        assert!(!report.message_imprint.is_empty());
        Ok(())
    }

    #[test]
    fn xades_timestamp_rejects_duplicate_timestamp() -> XmlResult<()> {
        let timestamped = add_signature_timestamp(
            &signed_document()?,
            &timestamp_client(),
            &XadesTimestampConfig::new(),
        )?;
        let error = add_signature_timestamp(
            &timestamped,
            &timestamp_client(),
            &XadesTimestampConfig::new(),
        )
        .expect_err("duplicate timestamp must fail");

        assert_eq!(error.kind(), &ErrorKind::Signature);
        assert!(error.message().contains("already exists"));
        Ok(())
    }

    #[test]
    fn xades_timestamp_detects_tampered_signature_value() -> XmlResult<()> {
        let timestamped = add_signature_timestamp(
            &signed_document()?,
            &timestamp_client(),
            &XadesTimestampConfig::new(),
        )?;
        let xml = to_string_compact(&timestamped)?
            .replace("<ds:SignatureValue>", "<ds:SignatureValue>tampered");
        let tampered = parse_str(&xml)?;
        let report = verify_signature_timestamp(
            &tampered,
            &timestamp_client(),
            &XadesTimestampConfig::new(),
        )?;

        assert!(report.timestamp_present);
        assert!(report.structure_valid);
        assert!(!report.token_valid);
        Ok(())
    }
}