xml-sec 0.1.23

Pure Rust XML Security: XMLDSig, XMLEnc, C14N. Drop-in replacement for libxmlsec1.
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
//!
//! ```
//! # #[cfg(not(feature = "embedded"))]
//! # {
//! use sxd_document_no_unsafe::Package;
//! let package = Package::new();
//! let doc = package.as_document();
//!
//! let hello = doc.create_element("hello");
//! hello.set_attribute_value("planet", "Earth");
//! let comment = doc.create_comment("What about other planets?");
//! let text = doc.create_text("Greetings, Earthlings!");
//!
//! hello.append_child(comment);
//! hello.append_child(text);
//! doc.root().append_child(hello);
//! # }
//! ```
//!
//! ### Memory and ownership
//!
//! The `Package` struct is responsible for owning every node in the
//! document. Strings are interned, allowing repeated text to consume
//! less memory. This is very useful for documents containing lots of
//! the same attributes and tag names.
//!
//! The flip side of this decision is that allocated nodes and strings
//! are not deallocated until the entire `Package` is dropped. This is
//! a reasonable decision for two common cases: building up an XML
//! document and reading an XML document. You may wish to perform
//! large modifications to your data *before* creating a document.
//!
//! ### Namespaces, QNames, and Prefixes
//!
//! The names of elements and attributes may use namespaces. XML
//! namespacing uses URIs to uniquely distinguish items with the same
//! local name. A qualified name (`QName`) combines this optional URI
//! with the local name.
//!
//! When an XML document is represented as text, namespaces are given
//! a shorthand reference known as a prefix. Prefix names are
//! non-authoritative, and only the URI can be used to namespace a
//! name.
//!
//! Elements and attributes may specify a *preferred prefix*, which is
//! an indication of what the user would like to be used as a
//! prefix. There are times where the preferred prefix would cause a
//! conflict, and so an autogenerated prefix will be used instead.
//!
//! ### Design decisions
//!
//! Try to leverage the type system as much as possible.

#![deny(rust_2018_idioms)]

#[cfg(not(any(feature = "no-unsafe", feature = "raw-pointer-backend")))]
compile_error!("select either `no-unsafe` or `raw-pointer-backend`");

// Cargo's all-feature verification enables both selectors. Safe precedence keeps that profile
// free of raw pointers; selecting the legacy backend requires disabling default features.

#[cfg(not(feature = "embedded"))]
#[macro_use]
extern crate peresil;

use std::{
    fmt,
    sync::atomic::{AtomicUsize, Ordering},
};

static NEXT_PACKAGE_IDENTITY: AtomicUsize = AtomicUsize::new(1);

fn next_package_identity() -> usize {
    allocate_package_identity(&NEXT_PACKAGE_IDENTITY)
}

fn allocate_package_identity(counter: &AtomicUsize) -> usize {
    let mut current = counter.load(Ordering::Relaxed);
    loop {
        let next = current
            .checked_add(1)
            .expect("document identity space exhausted");
        match counter.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) {
            Ok(_) => return current,
            Err(observed) => current = observed,
        }
    }
}

#[cfg(test)]
mod identity_tests {
    use super::*;

    #[test]
    fn exhausted_identity_space_does_not_wrap() {
        let counter = AtomicUsize::new(usize::MAX);
        let result = std::panic::catch_unwind(|| allocate_package_identity(&counter));
        assert!(result.is_err());
        assert_eq!(counter.load(Ordering::Relaxed), usize::MAX);
    }

    #[test]
    fn concurrent_allocations_remain_unique() {
        let counter = AtomicUsize::new(1);
        let identities = std::thread::scope(|scope| {
            let workers: Vec<_> = (0..8)
                .map(|_| {
                    scope.spawn(|| {
                        (0..128)
                            .map(|_| allocate_package_identity(&counter))
                            .collect::<Vec<_>>()
                    })
                })
                .collect();
            workers
                .into_iter()
                .flat_map(|worker| worker.join().unwrap())
                .collect::<Vec<_>>()
        });
        let unique: std::collections::HashSet<_> = identities.iter().copied().collect();
        assert_eq!(unique.len(), 8 * 128);
        assert_eq!(counter.load(Ordering::Relaxed), 1 + 8 * 128);
    }
}

/// Node and edge counts used to reserve storage before projecting into this DOM.
#[derive(Debug, Clone, Copy, Default)]
pub struct StorageRequirements {
    pub roots: usize,
    pub elements: usize,
    pub attributes: usize,
    pub texts: usize,
    pub comments: usize,
    pub processing_instructions: usize,
    pub child_edges: usize,
    pub namespace_bindings: usize,
    pub interned_strings: usize,
    pub string_bytes: usize,
}

/// Conservative heap-storage estimate for one projected document.
#[must_use]
pub fn estimated_storage_bytes(requirements: StorageRequirements) -> usize {
    raw::estimated_storage_bytes(requirements)
}

mod lazy_hash_map;
#[cfg(feature = "no-unsafe")]
mod namespace_storage;
pub(crate) mod str;
mod str_ext;

#[cfg(not(feature = "no-unsafe"))]
pub mod dom;
#[cfg(not(feature = "no-unsafe"))]
mod raw;
#[cfg(not(feature = "no-unsafe"))]
pub(crate) mod string_pool;
#[cfg(not(feature = "no-unsafe"))]
#[doc(hidden)]
pub mod thindom;
#[cfg(not(feature = "no-unsafe"))]
pub mod writer;

#[cfg(feature = "no-unsafe")]
#[path = "raw_no_unsafe.rs"]
mod raw;
#[cfg(feature = "no-unsafe")]
mod storage;
#[cfg(feature = "no-unsafe")]
#[path = "string_pool_no_unsafe.rs"]
pub(crate) mod string_pool;
#[cfg(feature = "no-unsafe")]
pub use string_pool::{AccountedStringPool, InternedString};
#[cfg(feature = "no-unsafe")]
#[path = "dom_no_unsafe.rs"]
pub mod dom;
#[cfg(feature = "no-unsafe")]
#[path = "thindom_no_unsafe.rs"]
#[doc(hidden)]
pub mod thindom;
#[cfg(feature = "no-unsafe")]
#[path = "writer_no_unsafe.rs"]
pub mod writer;

pub mod parser;

#[cfg(not(feature = "no-unsafe"))]
#[cfg(feature = "__internal_expose_string_pool")]
pub mod __internal {
    pub use super::string_pool::StringPool;
}

#[cfg(feature = "no-unsafe")]
#[cfg(feature = "__internal_expose_string_pool")]
pub mod __internal {
    pub use super::string_pool::StringPool;
}

pub use crate::str::XmlChar;
#[cfg(feature = "embedded")]
pub use crate::{as_opt_str, as_qname, as_str, to_ns_str};

#[cfg(not(feature = "no-unsafe"))]
#[macro_export]
macro_rules! as_str {
    ($e:expr) => {
        $e
    };
}

#[cfg(not(feature = "no-unsafe"))]
#[macro_export]
macro_rules! as_opt_str {
    ($e:expr) => {
        $e
    };
}

#[cfg(not(feature = "no-unsafe"))]
#[macro_export]
macro_rules! as_qname {
    ($e:expr) => {
        $e
    };
}

#[cfg(feature = "no-unsafe")]
#[macro_export]
macro_rules! as_str {
    ($e:expr) => {
        &*$e
    };
}

#[cfg(feature = "no-unsafe")]
#[macro_export]
macro_rules! as_opt_str {
    ($e:expr) => {
        $e.as_deref()
    };
}

#[cfg(feature = "no-unsafe")]
#[macro_export]
macro_rules! as_qname {
    ($e:expr) => {
        $e.get()
    };
}

#[cfg(not(feature = "no-unsafe"))]
#[macro_export]
macro_rules! to_ns_str {
    ($e:expr) => {
        $e
    };
}

#[cfg(feature = "no-unsafe")]
#[macro_export]
macro_rules! to_ns_str {
    ($e:expr) => {
        ($e).to_owned().into()
    };
}

/// String type used for namespace prefix/URI storage.
/// `&'d str` in default mode, `String` in no-unsafe mode.
#[cfg(not(feature = "no-unsafe"))]
pub type NsStr<'d> = &'d str;
/// String type used for namespace prefix/URI storage.
/// `&'d str` in default mode, `String` in no-unsafe mode.
#[cfg(all(feature = "no-unsafe", not(feature = "embedded")))]
///
/// The lifetime is intentionally retained so cfg-independent generic code has one public type
/// signature; owned storage does not borrow from `'d` in this mode.
pub type NsStr<'d> = String;

#[cfg(feature = "embedded")]
pub type NsStr<'d> = NamespaceText;

/// Namespace payloads preserve the execution owner when identity handles clone.
#[cfg(feature = "embedded")]
#[derive(Debug, Clone)]
pub enum NamespaceText {
    Native(String),
    Current(structured_asn1::memory::SharedString),
    Static(&'static str),
}

#[cfg(feature = "embedded")]
impl NamespaceText {
    pub(crate) fn can_share(&self) -> bool {
        matches!(self, Self::Current(_) | Self::Static(_))
    }
}
#[cfg(feature = "embedded")]
impl From<String> for NamespaceText {
    fn from(value: String) -> Self {
        Self::Native(value)
    }
}
#[cfg(feature = "embedded")]
impl From<&str> for NamespaceText {
    fn from(value: &str) -> Self {
        Self::Native(value.to_owned())
    }
}
#[cfg(feature = "embedded")]
impl std::ops::Deref for NamespaceText {
    type Target = str;
    fn deref(&self) -> &str {
        match self {
            Self::Native(s) => s,
            Self::Current(s) => s,
            Self::Static(s) => s,
        }
    }
}
#[cfg(feature = "embedded")]
impl AsRef<str> for NamespaceText {
    fn as_ref(&self) -> &str {
        self
    }
}
#[cfg(feature = "embedded")]
impl PartialEq for NamespaceText {
    fn eq(&self, other: &Self) -> bool {
        **self == **other
    }
}
#[cfg(feature = "embedded")]
impl Eq for NamespaceText {}
#[cfg(feature = "embedded")]
impl std::borrow::Borrow<str> for NamespaceText {
    fn borrow(&self) -> &str {
        self
    }
}
#[cfg(feature = "embedded")]
impl structured_asn1::memory::HashWork for NamespaceText {
    fn hash_work(&self) -> Result<u64, structured_asn1::memory::MemoryError> {
        structured_asn1::memory::HashWork::hash_work(&**self)
    }
}
#[cfg(feature = "embedded")]
impl std::hash::Hash for NamespaceText {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        std::hash::Hash::hash(&**self, state);
    }
}

pub(crate) static XML_NS_PREFIX: &str = "xml";
pub(crate) static XML_NS_URI: &str = "http://www.w3.org/XML/1998/namespace";

/// A prefixed name. This represents what is found in the string form
/// of an XML document, and does not apply any namespace mapping.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PrefixedName<'a> {
    prefix: Option<&'a str>,
    local_part: &'a str,
}

impl<'a> PrefixedName<'a> {
    /// Create a `PrefixedName` without a prefix
    pub fn new(local_part: &str) -> PrefixedName<'_> {
        PrefixedName::with_prefix(None, local_part)
    }

    /// Create a `PrefixedName` without an optional prefix
    pub fn with_prefix(prefix: Option<&'a str>, local_part: &'a str) -> PrefixedName<'a> {
        PrefixedName { prefix, local_part }
    }

    /// Borrows the original source, independently of this copied name view.
    pub fn prefix(&self) -> Option<&'a str> {
        self.prefix
    }
    /// Borrows the original source, independently of this copied name view.
    pub fn local_part(&self) -> &'a str {
        self.local_part
    }
}

/// A namespace-qualified name. This represents the name of an element
/// or attribute *after* the prefix has been mapped to a specific
/// namespace.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct QName<'s> {
    namespace_uri: Option<&'s str>,
    local_part: &'s str,
}

impl<'s> QName<'s> {
    /// Create a `QName` without a namespace
    pub fn new(local_part: &'s str) -> QName<'s> {
        QName::with_namespace_uri(None, local_part)
    }

    /// Create a `QName` with an optional namespace
    pub fn with_namespace_uri(namespace_uri: Option<&'s str>, local_part: &'s str) -> QName<'s> {
        QName {
            namespace_uri,
            local_part,
        }
    }

    pub fn namespace_uri(&self) -> Option<&'s str> {
        self.namespace_uri
    }
    pub fn local_part(&self) -> &'s str {
        self.local_part
    }
}

impl<'s> From<(&'s str, &'s str)> for QName<'s> {
    fn from(v: (&'s str, &'s str)) -> QName<'s> {
        QName {
            namespace_uri: Some(v.0),
            local_part: v.1,
        }
    }
}

impl<'s> From<&'s str> for QName<'s> {
    fn from(v: &'s str) -> QName<'s> {
        QName {
            namespace_uri: None,
            local_part: v,
        }
    }
}

/// The main entrypoint to an XML document
///
/// This is an opaque structure that stores the internal details of
/// the XML document. Modify the document via `as_document`.
pub struct Package {
    identity: usize,
    storage: raw::Storage,
    connections: raw::Connections,
}

impl Default for Package {
    fn default() -> Package {
        let s = raw::Storage::new();
        let root = s.create_root();
        Package {
            identity: next_package_identity(),
            storage: s,
            connections: raw::Connections::new(root),
        }
    }
}

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

    #[cfg(feature = "embedded")]
    pub(crate) fn try_current(
        work: &impl structured_asn1::memory::Work,
    ) -> Result<Self, structured_asn1::memory::MemoryError> {
        let (storage, root) = raw::current::storage(work)?;
        Ok(Self {
            identity: next_package_identity(),
            storage,
            connections: raw::Connections::new(root),
        })
    }

    pub fn as_document(&self) -> dom::Document<'_> {
        dom::Document::new(self.identity, &self.storage, &self.connections)
    }

    #[doc(hidden)]
    pub fn as_thin_document(&self) -> (thindom::Storage<'_>, thindom::Connections<'_>) {
        // The returned handles borrow this Package, so its address is a stable runtime brand
        // for rejecting nodes created by a different arena before index or pointer access.
        let identity = std::ptr::from_ref(self).addr();
        let s = thindom::Storage::new(&self.storage, identity);
        #[cfg(not(feature = "no-unsafe"))]
        let c = thindom::Connections::new(&self.connections, identity);
        #[cfg(feature = "no-unsafe")]
        let c = thindom::Connections::new(&self.connections, &self.storage, identity);
        (s, c)
    }
}

impl PartialEq for Package {
    fn eq(&self, other: &Package) -> bool {
        std::ptr::eq(self, other)
    }
}

impl fmt::Debug for Package {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Package")
    }
}