Merge remote-tracking branch 'base-src/main' into pr-7646

# Conflicts:
#	Cargo.lock
This commit is contained in:
Dylan M. Taylor committed 2026-11-18 09:50:17 -05:00
commit 70c7cebde8
13 files changed
+389 -435

No files matched your search

Generated
+20 -1
View File
@@ -1384,7 +1384,7 @@ dependencies = [
[[package]]
name = "craft-pkcs7"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8479a1f3bbabb0e0b25194c508ab2eb14aa5490f#8479a1f3bbabb0e0b25194c508ab2eb14aa5490f"
source = "git+https://github.com/storytold/craft-libs?rev=a62ce81f2447b1791a8d8c0aa6317fb6388f189b#a62ce81f2447b1791a8d8c0aa6317fb6388f189b"
dependencies = [
"aes",
"aws-lc-rs",
@@ -1566,6 +1566,14 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "craft-xfa"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1a0d5d607859a2e529851482de09b8e53aaeec3e#1a0d5d607859a2e529851482de09b8e53aaeec3e"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1a0d5d607859a2e529851482de09b8e53aaeec3e)",
]
[[package]]
name = "craft-xfdf"
version = "0.1.0"
@@ -1575,6 +1583,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1a0d5d607859a2e529851482de09b8e53aaeec3e#1a0d5d607859a2e529851482de09b8e53aaeec3e"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
@@ -5190,6 +5208,7 @@ version = "0.21.1"
dependencies = [
"base64 0.23.1",
"craft-image-codecs",
"craft-xfa",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
"pdfcraft-cos",
"pdfcraft-fonts",
+25 -12
View File
@@ -294,15 +294,20 @@ fn reference_loops_terminate_and_a_delete_takes_the_cycle_with_it() {
// ── wrong types where the reader wants a number or a name ─────────────────────────────────────
/// Values of the wrong type in flag, opacity and colour entries: the reader falls back to its
/// defaults instead of panicking. NOTE on opacity: reading does **not** clamp, so `/CA 7.5` comes
/// back as 7.5 and would hand a nonsense value to a 0–1 slider; writing clamps (`add_annotation`
/// refuses non-finite and clamps the range). The asymmetry is recorded here, not endorsed.
/// defaults instead of panicking. Opacity is clamped on read to the supported 0-1 range;
/// the original malformed dictionary remains unchanged.
#[test]
fn wrong_typed_flag_opacity_and_colour_entries_fall_back_without_panicking() {
let doc = one_annot(b"<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /CA 7.5 /F /NotAnInt /C [1 2] >>");
read_everything(&doc);
let p = props(&doc, 0, 0).expect("still a comment");
assert_eq!(p.opacity, 7.5, "the out-of-range opacity is passed through as written");
assert_eq!(p.opacity, 1.0, "the out-of-range opacity is clamped on read");
// Exercise both clamp edges and an unchanged interior value, not just a constant fallback.
for (raw, expected) in [("-0.5", 0.0), ("0.4", 0.4), ("1.5", 1.0)] {
let bytes = format!("<< /Type /Annot /Subtype /Text /Rect [10 20 30 40] /CA {raw} >>");
let probe = one_annot(bytes.as_bytes());
assert_eq!(props(&probe, 0, 0).expect("still a comment").opacity, expected, "opacity {raw}");
}
assert!(!p.locked, "a name where /F belongs reads as no flags at all");
assert_eq!(p.color, None, "/C with two components is not a colour");
let listed = summaries(&doc);
@@ -382,7 +387,8 @@ fn a_link_area_that_is_too_small_or_broken_is_refused_before_it_is_written() {
];
for (label, rect, want_in_message) in cases {
let mut doc = blank(2);
let e = links::add(&mut doc, 0, rect, &links::LinkAction::Page(1), &links::LinkStyle::default()).err();
let e =
links::add(&mut doc, 0, rect, &links::LinkAction::Page { page: 1, zoom: links::LinkZoom::FitPage }, &links::LinkStyle::default()).err();
let msg = match &e {
Some(AnnotError::Invalid(m)) => m.clone(),
other => panic!("{label}: expected Invalid, got {other:?}"),
@@ -440,10 +446,10 @@ fn non_finite_builder_input_is_refused_and_leaves_the_document_untouched() {
}
for (label, style) in [
("nan opacity", Style { color: [0.0, 0.0, 0.0], opacity: f64::NAN, width: 1.0, fill: None }),
("infinite opacity", Style { color: [0.0, 0.0, 0.0], opacity: f64::INFINITY, width: 1.0, fill: None }),
("nan colour", Style { color: [f64::NAN, 0.0, 0.0], opacity: 1.0, width: 1.0, fill: None }),
("nan width", Style { color: [0.0, 0.0, 0.0], opacity: 1.0, width: f64::NAN, fill: None }),
("nan opacity", Style { color: [0.0, 0.0, 0.0], opacity: f64::NAN, width: 1.0, fill: None, ..Style::default() }),
("infinite opacity", Style { color: [0.0, 0.0, 0.0], opacity: f64::INFINITY, width: 1.0, fill: None, ..Style::default() }),
("nan colour", Style { color: [f64::NAN, 0.0, 0.0], opacity: 1.0, width: 1.0, fill: None, ..Style::default() }),
("nan width", Style { color: [0.0, 0.0, 0.0], opacity: 1.0, width: f64::NAN, fill: None, ..Style::default() }),
] {
let mut doc = blank(1);
let e = add_annotation(
@@ -593,7 +599,14 @@ fn unvalidated_stamp_size_and_signature_contours_are_rewritten_silently_in_the_f
&mut doc,
&NewAnnotation {
page: 0,
shape: Shape::CustomStamp { rect: [10.0, 20.0, 60.0, 50.0], name: "Sig".into(), picture, image: true, size: (1e300, f64::NAN) },
shape: Shape::CustomStamp {
rect: [10.0, 20.0, 60.0, 50.0],
name: "Sig".into(),
picture,
image: true,
size: (1e300, f64::NAN),
line: None,
},
style: Style::default(),
contents: String::new(),
author: "A".into(),
@@ -656,7 +669,7 @@ fn a_nan_fill_is_accepted_on_create_and_refused_on_edit() {
&NewAnnotation {
page: 0,
shape: Shape::Rectangle { rect: [10.0, 20.0, 60.0, 40.0] },
style: Style { color: [0.9, 0.1, 0.1], opacity: 1.0, width: 2.0, fill: Some(nan) },
style: Style { color: [0.9, 0.1, 0.1], opacity: 1.0, width: 2.0, fill: Some(nan), ..Style::default() },
contents: String::new(),
author: "A".into(),
},
@@ -842,7 +855,7 @@ fn the_same_huge_fill_is_accepted_on_create_and_refused_on_edit() {
&NewAnnotation {
page: 0,
shape: Shape::Rectangle { rect: [10.0, 20.0, 60.0, 40.0] },
style: Style { color: [0.9, 0.1, 0.1], opacity: 1.0, width: 2.0, fill: Some(probe) },
style: Style { color: [0.9, 0.1, 0.1], opacity: 1.0, width: 2.0, fill: Some(probe), ..Style::default() },
contents: String::new(),
author: "A".into(),
},
+4 -4
View File
@@ -165,7 +165,7 @@ proptest! {
#[test]
fn opacity_and_flags_follow_their_rules(opacity in any::<f64>()) {
let mut doc = blank(1);
let added = add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: [10.0, 10.0, 60.0, 40.0] }, Style { color: [0.5, 0.25, 0.75], opacity, width: 1.0, fill: None }, String::new(), "Ada".into()), &meta("c".into()));
let added = add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: [10.0, 10.0, 60.0, 40.0] }, Style { color: [0.5, 0.25, 0.75], opacity, width: 1.0, fill: None, ..Style::default() }, String::new(), "Ada".into()), &meta("c".into()));
if !opacity.is_finite() {
prop_assert!(added.is_err(), "a non-finite opacity ({:?}) must be refused, not written", opacity);
return Ok(());
@@ -243,7 +243,7 @@ proptest! {
2 => -0.5,
_ => 0.0,
};
add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: *r }, Style { color: [0.9, 0.1, 0.1], opacity, width: 2.0, fill: None }, format!("c{i}"), "Ada".into()), &meta(format!("k{i}")))
add_annotation(&mut doc, &comment(0, Shape::Rectangle { rect: *r }, Style { color: [0.9, 0.1, 0.1], opacity, width: 2.0, fill: None, ..Style::default() }, format!("c{i}"), "Ada".into()), &meta(format!("k{i}")))
.expect("adds");
want_rects.push(norm(*r));
}
@@ -333,7 +333,7 @@ proptest! {
#[test]
fn width_and_fill_are_written_as_they_were_given(width in -4.0f64..12.0, fill in prop::option::of(prop::array::uniform3(0.0f64..1.0))) {
let mut doc = blank(1);
add_annotation(&mut doc, &comment(0, Shape::Oval { rect: [5.0, 5.0, 65.0, 35.0] }, Style { color: [1.0, 0.0, 0.0], opacity: 1.0, width, fill }, String::new(), "Ada".into()), &meta("f".into()))
add_annotation(&mut doc, &comment(0, Shape::Oval { rect: [5.0, 5.0, 65.0, 35.0] }, Style { color: [1.0, 0.0, 0.0], opacity: 1.0, width, fill, ..Style::default() }, String::new(), "Ada".into()), &meta("f".into()))
.expect("adds");
for path in [Save::Incremental, Save::FullTable] {
let (file, reopened) = save_and_reopen(&doc, path);
@@ -360,7 +360,7 @@ proptest! {
fn a_line_keeps_its_endpoints_and_its_rectangle_spans_them(from in prop::array::uniform2(coord()), dx in 1.0f64..300.0, dy in -300.0f64..300.0, width in 0.5f64..8.0) {
let to = [(from[0] + dx).min(450.0), from[1] + dy];
let mut doc = blank(1);
add_annotation(&mut doc, &comment(0, Shape::Line { from, to, start: LineEnding::None, end: LineEnding::OpenArrow }, Style { color: [0.0, 0.0, 0.0], opacity: 1.0, width, fill: None }, String::new(), "Ada".into()), &meta("l".into()))
add_annotation(&mut doc, &comment(0, Shape::Line { from, to, start: LineEnding::None, end: LineEnding::OpenArrow }, Style { color: [0.0, 0.0, 0.0], opacity: 1.0, width, fill: None, ..Style::default() }, String::new(), "Ada".into()), &meta("l".into()))
.expect("adds");
let span = bounds_of(&[from, to]);
for path in [Save::Incremental, Save::FullTable, Save::FullStreams] {
+17 -9
View File
@@ -33,8 +33,8 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions};
use support::bytes;
use support::fixture::{
ALL_SAVES, FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, FLAG_READONLY, Save, annot_entries, blank, blank_with_indirect_annots, dict_of, name_of,
num, nums, page_object_numbers, pdf, save_and_reopen, str_of,
ALL_SAVES, FLAG_HIDDEN, FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, FLAG_READONLY, Save, annot_entries, blank, blank_with_indirect_annots, dict_of,
name_of, num, nums, page_object_numbers, pdf, save_and_reopen, str_of,
};
/// A deterministic `/M` date and `/NM` id, so nothing here depends on the clock.
@@ -48,7 +48,7 @@ fn ann(page: usize, shape: Shape, contents: &str) -> NewAnnotation {
}
fn styled(page: usize, shape: Shape, contents: &str, color: [f64; 3], opacity: f64, width: f64, fill: Option<[f64; 3]>) -> NewAnnotation {
NewAnnotation { page, shape, style: Style { color, opacity, width, fill }, contents: contents.into(), author: "Ada".into() }
NewAnnotation { page, shape, style: Style { color, opacity, width, fill, ..Style::default() }, contents: contents.into(), author: "Ada".into() }
}
/// The dictionary of the `k`-th `/Annots` entry of a page.
@@ -658,8 +658,9 @@ fn reply_threads_and_the_delete_cascade_survive_every_save_path() {
assert_eq!(str_of(&reopened, &st, b"State").as_deref(), Some("Accepted"), "{path:?}");
assert_eq!(str_of(&reopened, &st, b"StateModel").as_deref(), Some("Review"), "{path:?}");
assert_eq!(str_of(&reopened, &st, b"Subj").as_deref(), Some("Status"), "{path:?}");
// Replies are printed but keep the icon flags of a comment; no Hidden bit here.
assert_eq!(st.int(b"F"), Some(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE), "{path:?}");
// Review-state records are hidden; ordinary text replies retain their visible comment flags.
assert_eq!(st.int(b"F"), Some(FLAG_HIDDEN | FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE), "{path:?}");
assert_eq!(annot_at(&reopened, 0, 2, path).int(b"F"), Some(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE), "{path:?}: ordinary reply");
let listed = summaries(&reopened);
assert_eq!(listed.iter().filter(|s| s.in_reply_to.as_deref() == Some("p1")).count(), 2, "{path:?}: both replies name the parent's /NM");
assert_eq!(listed.iter().filter(|s| s.state.as_deref() == Some("Accepted")).count(), 1, "{path:?}");
@@ -714,7 +715,7 @@ fn links_keep_page_targets_uri_and_dash_structure_across_renumbering() {
&mut doc,
0,
[120.0, 700.0, 240.0, 720.0],
&links::LinkAction::Page(2),
&links::LinkAction::Page { page: 2, zoom: links::LinkZoom::FitPage },
&links::LinkStyle { visible: true, width: 2.0, dashed: true, ..Default::default() },
)
.expect("links to page 3");
@@ -735,7 +736,7 @@ fn links_keep_page_targets_uri_and_dash_structure_across_renumbering() {
.into_iter()
.map(|l| {
let a = match l.action {
links::LinkAction::Page(p) => format!("page {p}"),
links::LinkAction::Page { page: p, zoom: _ } => format!("page {p}"),
links::LinkAction::Uri(u) => u,
links::LinkAction::Other(o) => format!("other:{o}"),
};
@@ -770,7 +771,14 @@ fn links_keep_page_targets_uri_and_dash_structure_across_renumbering() {
fn removing_all_links_keeps_comments() {
let mut doc = blank(2);
add_annotation(&mut doc, &ann(0, Shape::Note { at: [50.0, 700.0], icon: NoteIcon::Help }, "note"), &meta("n")).expect("adds");
links::add(&mut doc, 0, [200.0, 700.0, 300.0, 715.0], &links::LinkAction::Page(0), &links::LinkStyle::default()).expect("links");
links::add(
&mut doc,
0,
[200.0, 700.0, 300.0, 715.0],
&links::LinkAction::Page { page: 0, zoom: links::LinkZoom::FitPage },
&links::LinkStyle::default(),
)
.expect("links");
let removed = links::remove_all(&mut doc, None).expect("removes all links");
assert_eq!(removed, 1);
@@ -980,7 +988,7 @@ fn a_full_rewrite_into_object_streams_describes_the_same_comments_as_a_plain_tab
assert_eq!(summaries(&plain).len(), summaries(&packed).len());
// The plain-table output is bigger here: object streams compress, which is the point of them.
let opts = SaveOptions { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: true, drop_unlinked: false };
let opts = SaveOptions { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: true, drop_unlinked: false, id_entropy: None };
let packed_bytes = pdfcraft_cos::write_full(&doc, &opts).expect("writes");
assert!(
packed_bytes.len() < pdfcraft_cos::write_full(&doc, &SaveOptions { object_streams: false, ..opts }).expect("writes").len(),
+7 -1
View File
@@ -118,7 +118,13 @@ pub fn save_and_reopen(doc: &Document, path: Save) -> (Vec<u8>, Document) {
/// Save with the path's options. `/Info /ModDate` is left unset so a full save adds nothing that
/// would make byte comparisons depend on the clock.
pub fn save(doc: &Document, path: Save) -> Vec<u8> {
let opts = SaveOptions { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: path == Save::FullStreams, drop_unlinked: false };
let opts = SaveOptions {
mod_date: None,
id_seed: 0x5052_494E_5443_5241,
object_streams: path == Save::FullStreams,
drop_unlinked: false,
id_entropy: None,
};
match path {
Save::Incremental => write_incremental(doc, &opts),
Save::FullTable | Save::FullStreams => write_full(doc, &opts),
+1 -1
View File
@@ -12,7 +12,7 @@ workspace = true
[dependencies]
# Existing shared ASN.1 codec; PDF signature policy remains local.
craft-pkcs7 = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8479a1f3bbabb0e0b25194c508ab2eb14aa5490f" }
craft-pkcs7 = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a62ce81f2447b1791a8d8c0aa6317fb6388f189b" }
pdfcraft-cos = { workspace = true }
pdfcraft-annot = { workspace = true }
pdfcraft-content = { workspace = true }
+56
View File
@@ -65,6 +65,21 @@ pub struct CertificateList {
impl CertificateList {
pub fn parse(bytes: &[u8]) -> Result<CertificateList, SignError> {
let parsed = craft_pkcs7::revocation::CertificateList::parse(bytes).map_err(crate::der::app_error)?.into_parts();
Ok(Self {
tbs: parsed.tbs,
sig_alg: parsed.sig_alg,
signature: parsed.signature,
issuer_raw: parsed.issuer_raw,
this_update: parsed.this_update,
next_update: parsed.next_update,
revoked: parsed.revoked,
})
}
// Retained parity oracle: original CRL parser by Justin John (4d0078aeff).
#[cfg(test)]
fn parse_legacy(bytes: &[u8]) -> Result<CertificateList, SignError> {
if bytes.is_empty() || bytes.len() > MAX_EVIDENCE {
return Err(bad("CRL is empty or exceeds the 2 MiB limit"));
}
@@ -307,3 +322,44 @@ impl OcspResponse {
}
}
}
#[cfg(test)]
mod shared_crl_tests {
use super::*;
use crate::der;
#[test]
fn shared_crl_parser_matches_retained_app_reader() {
let date = Time { year: 2026, month: 6, day: 15, hour: 12, minute: 0, second: 0 };
let algorithm = DigestAlg::Sha256.algorithm();
let tbs = der::seq(&[
&der::int(1),
&algorithm,
&der::seq(&[]),
&date.encode(),
&date.encode(),
&der::seq(&[&der::seq(&[&der::uint(&[0x80]), &date.encode()])]),
]);
let valid = der::seq(&[&tbs, &algorithm, &der::bit_string(&[1, 2, 3])]);
let compare = |bytes: &[u8]| match (CertificateList::parse(bytes), CertificateList::parse_legacy(bytes)) {
(Ok(a), Ok(b)) => {
assert_eq!(
(a.tbs, a.sig_alg, a.signature, a.issuer_raw, a.this_update, a.next_update, a.revoked),
(b.tbs, b.sig_alg, b.signature, b.issuer_raw, b.this_update, b.next_update, b.revoked)
);
}
(Err(a), Err(b)) => assert_eq!(format!("{a:?}"), format!("{b:?}")),
_ => panic!("shared and retained CRL parsers disagree"),
};
for end in 0..=valid.len() {
compare(&valid[..end]);
}
for i in 0..valid.len() {
let mut mutated = valid.clone();
mutated[i] ^= 0x80;
compare(&mutated);
}
compare(&vec![0; MAX_EVIDENCE]);
compare(&vec![0; MAX_EVIDENCE + 1]);
}
}
+85 -21
View File
@@ -14,6 +14,7 @@ use crate::{SignError, Time};
const TST_INFO: &str = "1.2.840.113549.1.9.16.1.4";
const MAX_RESPONSE: usize = 4 * 1024 * 1024;
const MAX_TOKEN: usize = 2 * 1024 * 1024;
#[cfg(test)]
const MAX_REQUEST: usize = 1024 * 1024;
/// RFC 3161 request data. `nonce` is optional but recommended for online requests.
@@ -106,27 +107,24 @@ fn bad(message: impl Into<String>) -> SignError {
/// Decode a `TimeStampReq` as [`TimestampQuery::encode`] wrote it.
pub fn parse_request(bytes: &[u8]) -> Result<TimestampQuery, SignError> {
if bytes.is_empty() || bytes.len() > MAX_REQUEST {
return Err(bad("request is empty or exceeds the 1 MiB limit"));
}
let fields = Tlv::parse_all(bytes)?.expect(tag::SEQUENCE, "TimeStampReq")?.children()?;
let mut it = fields.into_iter();
let _version = it.next().ok_or_else(|| bad("missing version"))?.u64()?;
let imprint = it.next().ok_or_else(|| bad("missing message imprint"))?.children()?;
let alg_oid =
imprint.first().ok_or_else(|| bad("missing imprint algorithm"))?.children()?.first().ok_or_else(|| bad("missing algorithm OID"))?.oid()?;
let digest = DigestAlg::from_oid(&alg_oid).ok_or_else(|| bad("unsupported imprint digest algorithm"))?;
let hash = imprint.get(1).ok_or_else(|| bad("missing imprint digest"))?.expect(tag::OCTET_STRING, "imprint digest")?.value.to_vec();
let mut q = TimestampQuery::new(digest, hash)?;
for f in it {
match f.tag {
tag::OID => q.policy = Some(f.oid()?),
tag::INTEGER => q.nonce = Some(f.u64()?),
tag::BOOLEAN => q.certificate_request = f.value.first() == Some(&0xFF),
_ => {}
}
}
Ok(q)
let query = craft_pkcs7::timestamp::parse_request(bytes).map_err(der::app_error)?;
// Exhaustive mapping preserves the app's digest identity without reparsing or copying.
use craft_pkcs7::DigestAlg as Shared;
let digest = match query.digest {
Shared::Sha1 => DigestAlg::Sha1,
Shared::Sha224 => DigestAlg::Sha224,
Shared::Sha256 => DigestAlg::Sha256,
Shared::Sha384 => DigestAlg::Sha384,
Shared::Sha512 => DigestAlg::Sha512,
Shared::Sha512_224 => DigestAlg::Sha512_224,
Shared::Sha512_256 => DigestAlg::Sha512_256,
Shared::Sha3_224 => DigestAlg::Sha3_224,
Shared::Sha3_256 => DigestAlg::Sha3_256,
Shared::Sha3_384 => DigestAlg::Sha3_384,
Shared::Sha3_512 => DigestAlg::Sha3_512,
Shared::Ripemd160 => DigestAlg::Ripemd160,
};
Ok(TimestampQuery { digest, imprint: query.imprint, policy: query.policy, nonce: query.nonce, certificate_request: query.certificate_request })
}
/// Parse and validate a token (a bare CMS `ContentInfo`): TSTInfo content, bounded size, the
@@ -251,3 +249,69 @@ mod tests {
assert!(parse_request(&vec![0; MAX_REQUEST + 1]).is_err());
}
}
#[cfg(test)]
mod request_parity {
use super::*;
// Original request reader: Justin John; algorithm support: Thorsten Hirsch.
// Retained as an independent higher-level parser oracle (MIT OR Apache-2.0).
fn legacy_request(bytes: &[u8]) -> Result<TimestampQuery, SignError> {
if bytes.is_empty() || bytes.len() > MAX_REQUEST {
return Err(bad("request is empty or exceeds the 1 MiB limit"));
}
let fields = Tlv::parse_all(bytes)?.expect(tag::SEQUENCE, "TimeStampReq")?.children()?;
let mut it = fields.into_iter();
let _version = it.next().ok_or_else(|| bad("missing version"))?.u64()?;
let imprint = it.next().ok_or_else(|| bad("missing message imprint"))?.children()?;
let alg_oid = imprint
.first()
.ok_or_else(|| bad("missing imprint algorithm"))?
.children()?
.first()
.ok_or_else(|| bad("missing algorithm OID"))?
.oid()?;
let digest = DigestAlg::from_oid(&alg_oid).ok_or_else(|| bad("unsupported imprint digest algorithm"))?;
let hash = imprint.get(1).ok_or_else(|| bad("missing imprint digest"))?.expect(tag::OCTET_STRING, "imprint digest")?.value.to_vec();
let mut q = TimestampQuery::new(digest, hash)?;
for f in it {
match f.tag {
tag::OID => q.policy = Some(f.oid()?),
tag::INTEGER => q.nonce = Some(f.u64()?),
tag::BOOLEAN => q.certificate_request = f.value.first() == Some(&0xFF),
_ => {}
}
}
Ok(q)
}
fn compare(bytes: &[u8]) {
match (legacy_request(bytes), parse_request(bytes)) {
(Ok(a), Ok(b)) => assert_eq!(a, b),
(Err(a), Err(b)) => assert_eq!(format!("{a:?}"), format!("{b:?}")),
other => panic!("request parity mismatch: {other:?}"),
}
}
#[test]
fn shared_request_preserves_algorithms_fields_errors_and_limits() {
for digest in DigestAlg::ALL {
let mut query = TimestampQuery::new(digest, digest.digest(&[b"fixture"])).unwrap();
query.policy = Some("1.2.3.4".into());
query.nonce = Some(u64::MAX);
for cert in [false, true] {
query.certificate_request = cert;
let bytes = query.encode().unwrap();
compare(&bytes);
for len in 0..bytes.len() {
compare(&bytes[..len]);
}
for pos in 0..bytes.len() {
let mut changed = bytes.clone();
changed[pos] ^= 255;
compare(&changed);
}
}
}
compare(&vec![0; MAX_REQUEST]);
compare(&vec![0; MAX_REQUEST + 1]);
}
}
+79
View File
@@ -151,6 +151,7 @@ pub struct Certificate {
/// qcStatements (1.3.6.1.5.5.7.1.3) is included: RFC 3739 lets qualified (eIDAS and other national)
/// certificates mark it critical, and it declares the certificate's status rather than limiting
/// what the key may sign.
#[cfg(test)]
const PROCESSED_EXTENSIONS: [&str; 11] = [
"2.5.29.19",
"2.5.29.15",
@@ -178,6 +179,7 @@ const DOCUMENT_SIGNING_EKUS: [&str; 6] =
/// extension that does not parse leaves its field at the default instead of failing the
/// certificate (real-world issuers use encodings with edge cases, e.g. a single-URI CRL
/// distribution point whose `fullName [0]` is IMPLICIT over a bare GeneralName).
#[cfg(test)]
#[derive(Default)]
struct Extensions {
is_ca: bool,
@@ -191,6 +193,7 @@ struct Extensions {
crl_urls: Vec<String>,
}
#[cfg(test)]
impl Extensions {
fn read(&mut self, oid: &str, value: &Tlv<'_>) {
match oid {
@@ -288,6 +291,51 @@ impl Extensions {
impl Certificate {
pub fn parse(raw: &[u8]) -> Result<Certificate, SignError> {
craft_pkcs7::x509::Certificate::parse(raw).map(Self::from_shared).map_err(crate::der::app_error)
}
pub(crate) fn from_shared(cert: craft_pkcs7::x509::Certificate) -> Self {
let parsed = cert.into_parts();
use craft_pkcs7::keys::PublicKey as Shared;
let public_key = match parsed.public_key {
Shared::Rsa { n, e } => PublicKey::Rsa { n, e },
Shared::P256(v) => PublicKey::P256(v),
Shared::P384(v) => PublicKey::P384(v),
Shared::P521(v) => PublicKey::P521(v),
Shared::BrainpoolP256(v) => PublicKey::BrainpoolP256(v),
Shared::BrainpoolP384(v) => PublicKey::BrainpoolP384(v),
Shared::BrainpoolP512(v) => PublicKey::BrainpoolP512(v),
Shared::Ed25519(v) => PublicKey::Ed25519(v),
Shared::Unsupported { what, spki } => PublicKey::Unsupported { what, spki },
};
Self {
raw: parsed.raw,
tbs: parsed.tbs,
sig_alg: parsed.sig_alg,
signature: parsed.signature,
serial: parsed.serial,
issuer: Name { attrs: parsed.issuer.attrs, raw: parsed.issuer.raw },
subject: Name { attrs: parsed.subject.attrs, raw: parsed.subject.raw },
not_before: parsed.not_before,
not_after: parsed.not_after,
public_key,
is_ca: parsed.is_ca,
has_basic_constraints: parsed.has_basic_constraints,
path_len: parsed.path_len,
key_usage: parsed.key_usage,
subject_key_id: parsed.subject_key_id,
authority_key_id: parsed.authority_key_id,
extended_key_usage: parsed.extended_key_usage,
ocsp_urls: parsed.ocsp_urls,
crl_urls: parsed.crl_urls,
version: parsed.version,
unknown_critical: parsed.unknown_critical,
}
}
// Original certificate reader retained as an independent parity oracle; see source history.
#[cfg(test)]
fn parse_legacy(raw: &[u8]) -> Result<Certificate, SignError> {
let cert = Tlv::parse_all(raw)?.expect(tag::SEQUENCE, "Certificate")?;
let parts = cert.children()?;
let [tbs, sig_alg, sig] = parts.as_slice() else { return Err(SignError::Malformed("Certificate".into())) };
@@ -695,3 +743,34 @@ mod xfa_ext_tests {
}
}
}
#[cfg(test)]
mod shared_certificate_tests {
use super::*;
#[test]
fn shared_certificate_matches_retained_parser_and_error_policy() {
let compare = |bytes: &[u8]| match (Certificate::parse(bytes), Certificate::parse_legacy(bytes)) {
(Ok(a), Ok(b)) => assert_eq!(a, b),
(Err(a), Err(b)) => assert_eq!(format!("{a:?}"), format!("{b:?}")),
_ => panic!("shared and retained certificate parsers disagree"),
};
for fixture in [
include_bytes!("../tests/data/ec-p256.p12").as_slice(),
include_bytes!("../tests/data/ec-p384.p12").as_slice(),
include_bytes!("../tests/data/rsa-aes.p12").as_slice(),
] {
let id = crate::pkcs12::open(fixture, "test").unwrap();
let raw = &id.certificate.raw;
compare(raw);
for end in 0..raw.len() {
compare(&raw[..end]);
}
for i in 0..raw.len() {
let mut changed = raw.clone();
changed[i] ^= 0x80;
compare(&changed);
}
}
}
}
+1
View File
@@ -11,6 +11,7 @@ repository.workspace = true
workspace = true
[dependencies]
craft-xfa = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1a0d5d607859a2e529851482de09b8e53aaeec3e" }
pdfcraft-cos = { workspace = true }
pdfcraft-fonts = { workspace = true }
craft-xml = { workspace = true }
+20 -1
View File
@@ -74,6 +74,7 @@ pub(crate) fn expand(template: Node) -> (Option<String>, Vec<String>) {
soms: HashMap::new(),
search: MAX_SEARCH,
work: MAX_WORK,
child_counts: HashMap::new(),
active: HashMap::new(),
missing: false,
external: false,
@@ -124,6 +125,8 @@ struct Writer<'a> {
search: usize,
/// Children, attributes and namespaces left to look at while merging layers.
work: usize,
/// Bounded memoization only; each use still pays the full child count.
child_counts: HashMap<NodeId, usize>,
/// The elements being written around the current one: inheriting from one is a loop.
active: HashMap<NodeId, u32>,
missing: bool,
@@ -132,6 +135,22 @@ struct Writer<'a> {
layers_cut: bool,
}
/// Counting a reused prototype must not itself repeatedly walk its descendants.
/// Cache only complete direct-child counts, and cap the optimization's memory.
/// Truncated counts are not exact and must never be cached. Budget charging is unchanged.
fn child_count(node: Node<'_>, work: usize, cache: &mut HashMap<NodeId, usize>) -> usize {
const MAX_CACHED_COUNTS: usize = 4_096;
let stop = work.saturating_add(1);
if let Some(count) = cache.get(&node.id()) {
return (*count).min(stop);
}
let count = node.children().take(stop).count();
if count < stop && cache.len() < MAX_CACHED_COUNTS {
cache.insert(node.id(), count);
}
count
}
fn escape(s: &str, attribute: bool, out: &mut String) {
for c in s.chars() {
match c {
@@ -439,7 +458,7 @@ impl<'a> Writer<'a> {
// further than the budget left), attributes and namespaces, and the scope around it.
let mut cost = scope.len().saturating_add(layers.len());
for l in &layers {
let children = l.children().take(self.work.saturating_add(1)).count();
let children = child_count(*l, self.work, &mut self.child_counts);
cost = cost.saturating_add(children).saturating_add(l.attributes().len()).saturating_add(l.namespaces().len());
}
if self.failed.is_some() || !self.charge(cost) {
+60
View File
@@ -399,3 +399,63 @@ fn a_som_expression_past_its_length_limit_is_not_followed() {
assert_eq!(field(&t, "long").common.h, None);
assert!(close(field(&t, "short").common.h, 2.0 * MM));
}
#[test]
fn cached_child_counts_preserve_truncation_and_charge_when_budget_shrinks() {
let doc = crate::xml::Document::parse("<root><a/><b/><c/></root>").unwrap();
let node = doc.root_element();
let mut cache = std::collections::HashMap::new();
assert_eq!(super::child_count(node, 1, &mut cache), 2);
assert!(cache.is_empty(), "truncated counts are not reusable");
assert_eq!(super::child_count(node, 10, &mut cache), 3);
assert_eq!(cache.get(&node.id()), Some(&3));
for remaining in 0..=5 {
assert_eq!(super::child_count(node, remaining, &mut cache), node.children().take(remaining + 1).count());
}
assert_eq!(super::child_count(node, 10, &mut cache), 3, "a cached use is still charged");
}
#[test]
fn child_count_memoization_has_a_fixed_entry_limit() {
let doc = crate::xml::Document::parse(&format!("<root>{}</root>", "<a/>".repeat(5_000))).unwrap();
let mut cache = std::collections::HashMap::new();
for node in doc.root_element().children() {
assert_eq!(super::child_count(node, 1, &mut cache), 0);
}
assert_eq!(cache.len(), 4_096);
}
#[test]
fn cached_layers_still_subtract_work_and_stop_at_the_budget() {
let doc = crate::xml::Document::parse("<root><a/><b/><c/></root>").unwrap();
let node = doc.root_element();
let mut writer = super::Writer {
template: node,
out: String::new(),
limit: super::MAX_OUTPUT,
failed: None,
ids: None,
refs: std::collections::HashMap::new(),
soms: std::collections::HashMap::new(),
search: super::MAX_SEARCH,
work: 100,
child_counts: std::collections::HashMap::new(),
active: std::collections::HashMap::new(),
missing: false,
external: false,
looped: false,
layers_cut: false,
};
writer.element(&[node], &super::Scope::new(), 0);
assert!(writer.failed.is_none());
let first_cost = 100 - writer.work;
assert!(first_cost > 0);
assert!(!writer.child_counts.is_empty());
let before = writer.work;
writer.element(&[node], &super::Scope::new(), 0);
assert!(writer.failed.is_none());
assert_eq!(before - writer.work, first_cost, "cached layers pay the same work charge");
writer.work = 0;
writer.element(&[node], &super::Scope::new(), 0);
assert!(writer.failed.as_ref().is_some_and(|why| why.contains("children, attributes and namespaces")));
}
+14 -385
View File
@@ -1,389 +1,18 @@
//! Lightweight namespace-aware XML DOM with source byte ranges, backed by `craft_xml`.
//! Namespace-aware XFA DOM delegated to the shared implementation.
pub(crate) use craft_xfa::xml::*;
use std::ops::Range;
#[cfg(test)]
mod tests {
use super::*;
const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct NodeId(pub(crate) usize);
#[derive(Clone, Debug)]
pub(crate) struct ParsingOptions {
pub(crate) allow_dtd: bool,
pub(crate) nodes_limit: u32,
}
impl Default for ParsingOptions {
fn default() -> Self {
Self { allow_dtd: false, nodes_limit: u32::MAX }
}
}
#[derive(Clone, Debug)]
struct AttrData {
ns: Option<String>,
name: String,
value: String,
}
#[derive(Clone, Debug)]
enum NodeKind {
Element {
ns: Option<String>,
name: String,
attrs: Vec<AttrData>,
/// In-scope `(prefix, uri)` bindings at this element (`""` for default namespace).
namespaces: Vec<(String, String)>,
range: Range<usize>,
},
Text(String),
}
#[derive(Clone, Debug)]
struct NodeData {
kind: NodeKind,
children: Vec<usize>,
}
pub(crate) struct Document {
nodes: Vec<NodeData>,
root: usize,
}
#[derive(Clone, Copy)]
pub(crate) struct Node<'a> {
doc: &'a Document,
id: usize,
}
impl PartialEq for Node<'_> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && std::ptr::eq(self.doc, other.doc)
}
}
impl Eq for Node<'_> {}
#[derive(Clone, Copy)]
pub(crate) struct ExpandedName<'a> {
ns: Option<&'a str>,
name: &'a str,
}
impl<'a> ExpandedName<'a> {
pub(crate) fn name(&self) -> &'a str {
self.name
}
pub(crate) fn namespace(&self) -> Option<&'a str> {
self.ns
}
}
pub(crate) trait AttributeKey {
fn matches(&self, ns: Option<&str>, name: &str) -> bool;
}
impl AttributeKey for &str {
fn matches(&self, ns: Option<&str>, name: &str) -> bool {
ns.is_none() && name == *self
}
}
impl AttributeKey for (&str, &str) {
fn matches(&self, ns: Option<&str>, name: &str) -> bool {
ns == Some(self.0) && name == self.1
}
}
#[derive(Clone, Copy)]
pub(crate) struct Attribute<'a> {
attr: &'a AttrData,
}
impl<'a> Attribute<'a> {
pub(crate) fn name(&self) -> &'a str {
&self.attr.name
}
pub(crate) fn namespace(&self) -> Option<&'a str> {
self.attr.ns.as_deref()
}
pub(crate) fn value(&self) -> &'a str {
&self.attr.value
}
}
#[derive(Clone, Copy)]
pub(crate) struct Namespace<'a> {
prefix: &'a str,
uri: &'a str,
}
impl<'a> Namespace<'a> {
pub(crate) fn name(&self) -> Option<&'a str> {
(!self.prefix.is_empty()).then_some(self.prefix)
}
pub(crate) fn uri(&self) -> &'a str {
self.uri
}
}
fn split_qname(qname: &str) -> (&str, &str) {
match qname.split_once(':') {
Some((p, l)) => (p, l),
None => ("", qname),
}
}
fn resolve_ns(scope: &[(String, String)], prefix: &str, is_attr: bool) -> Result<Option<String>, String> {
if prefix == "xml" {
return Ok(Some(XML_NS.to_string()));
}
if prefix == "xmlns" {
return Ok(Some(XMLNS_NS.to_string()));
}
if prefix.is_empty() {
if is_attr {
return Ok(None);
}
return Ok(scope.iter().rev().find(|(p, _)| p.is_empty()).and_then(|(_, u)| (!u.is_empty()).then(|| u.clone())));
}
match scope.iter().rev().find(|(p, _)| p == prefix) {
Some((_, u)) if !u.is_empty() => Ok(Some(u.clone())),
_ => Err(format!("undeclared namespace prefix: {prefix}")),
}
}
impl Document {
#[cfg(test)]
pub(crate) fn parse(text: &str) -> Result<Self, String> {
Self::parse_with_options(text, ParsingOptions::default())
}
pub(crate) fn parse_with_options(text: &str, options: ParsingOptions) -> Result<Self, String> {
let mut opts = craft_xml::Options {
strict: true,
doctype: if options.allow_dtd { craft_xml::Doctype::Ignore } else { craft_xml::Doctype::Reject },
..Default::default()
};
opts.limits.max_nodes = options.nodes_limit as usize;
opts.limits.max_depth = crate::MAX_XML_DEPTH;
let mut events = opts.events(text.as_bytes());
let mut nodes: Vec<NodeData> = Vec::new();
let mut open: Vec<(usize, usize)> = Vec::new(); // (node_id, scope_len_before)
let mut scope: Vec<(String, String)> = Vec::new();
let mut root: Option<usize> = None;
while let Some(ev) = events.next().map_err(|e| e.to_string())? {
let span = events.span();
match ev {
craft_xml::Event::Start { name, attrs } => {
if nodes.len() >= options.nodes_limit as usize {
return Err("nodes limit reached".to_string());
}
let scope_mark = scope.len();
for (k, v) in &attrs {
if k == "xmlns" {
scope.push((String::new(), v.clone()));
} else if let Some(prefix) = k.strip_prefix("xmlns:") {
scope.push((prefix.to_string(), v.clone()));
}
}
let (el_prefix, el_local) = split_qname(&name);
let el_ns = resolve_ns(&scope, el_prefix, false)?;
let mut el_attrs = Vec::new();
for (k, v) in attrs {
if k == "xmlns" || k.starts_with("xmlns:") {
continue;
}
let (ap, al) = split_qname(&k);
let ans = resolve_ns(&scope, ap, true)?;
el_attrs.push(AttrData { ns: ans, name: al.to_string(), value: v });
}
// Deduplicate in-scope namespace bindings, keeping the innermost binding per prefix.
let mut namespaces: Vec<(String, String)> = Vec::new();
for (p, u) in scope.iter().rev() {
if !namespaces.iter().any(|(ep, _)| ep == p) {
namespaces.push((p.clone(), u.clone()));
}
}
namespaces.retain(|(_, u)| !u.is_empty());
let id = nodes.len();
nodes.push(NodeData {
kind: NodeKind::Element { ns: el_ns, name: el_local.to_string(), attrs: el_attrs, namespaces, range: span.start..span.end },
children: Vec::new(),
});
if let Some(&(parent, _)) = open.last() {
nodes[parent].children.push(id);
} else if root.is_none() {
root = Some(id);
}
open.push((id, scope_mark));
}
craft_xml::Event::End { .. } => {
if let Some((id, scope_mark)) = open.pop() {
if let NodeKind::Element { range, .. } = &mut nodes[id].kind {
range.end = span.end;
}
scope.truncate(scope_mark);
}
}
craft_xml::Event::Text(t) | craft_xml::Event::CData(t) => {
if let Some(&(parent, _)) = open.last() {
if let Some(&last_child) = nodes[parent].children.last()
&& let NodeKind::Text(existing) = &mut nodes[last_child].kind
{
existing.push_str(&t);
continue;
}
if nodes.len() >= options.nodes_limit as usize {
return Err("nodes limit reached".to_string());
}
let id = nodes.len();
nodes.push(NodeData { kind: NodeKind::Text(t), children: Vec::new() });
nodes[parent].children.push(id);
}
}
craft_xml::Event::Pi { .. } | craft_xml::Event::Comment(_) => {}
}
}
let Some(root) = root else {
return Err("empty XML document".to_string());
};
Ok(Self { nodes, root })
}
pub(crate) fn root_element(&self) -> Node<'_> {
Node { doc: self, id: self.root }
}
pub(crate) fn get_node(&self, id: NodeId) -> Option<Node<'_>> {
(id.0 < self.nodes.len()).then_some(Node { doc: self, id: id.0 })
}
pub(crate) fn descendants(&self) -> Descendants<'_> {
Descendants { doc: self, stack: vec![self.root] }
}
}
pub(crate) struct Descendants<'a> {
doc: &'a Document,
stack: Vec<usize>,
}
impl<'a> Iterator for Descendants<'a> {
type Item = Node<'a>;
fn next(&mut self) -> Option<Self::Item> {
let id = self.stack.pop()?;
let children = &self.doc.nodes[id].children;
for &c in children.iter().rev() {
self.stack.push(c);
}
Some(Node { doc: self.doc, id })
}
}
impl<'a> Node<'a> {
pub(crate) fn id(&self) -> NodeId {
NodeId(self.id)
}
pub(crate) fn document(&self) -> &'a Document {
self.doc
}
pub(crate) fn is_element(&self) -> bool {
matches!(self.doc.nodes[self.id].kind, NodeKind::Element { .. })
}
pub(crate) fn is_text(&self) -> bool {
matches!(self.doc.nodes[self.id].kind, NodeKind::Text(_))
}
pub(crate) fn tag_name(&self) -> ExpandedName<'a> {
match &self.doc.nodes[self.id].kind {
NodeKind::Element { ns, name, .. } => ExpandedName { ns: ns.as_deref(), name },
NodeKind::Text(_) => ExpandedName { ns: None, name: "" },
}
}
pub(crate) fn attribute<K: AttributeKey>(&self, key: K) -> Option<&'a str> {
match &self.doc.nodes[self.id].kind {
NodeKind::Element { attrs, .. } => attrs.iter().find(|a| key.matches(a.ns.as_deref(), &a.name)).map(|a| a.value.as_str()),
NodeKind::Text(_) => None,
}
}
pub(crate) fn attributes(&self) -> impl ExactSizeIterator<Item = Attribute<'a>> + use<'a> {
let attrs = match &self.doc.nodes[self.id].kind {
NodeKind::Element { attrs, .. } => attrs.as_slice(),
NodeKind::Text(_) => &[],
};
attrs.iter().map(|attr| Attribute { attr })
}
pub(crate) fn namespaces(&self) -> impl ExactSizeIterator<Item = Namespace<'a>> + use<'a> {
let ns = match &self.doc.nodes[self.id].kind {
NodeKind::Element { namespaces, .. } => namespaces.as_slice(),
NodeKind::Text(_) => &[],
};
ns.iter().map(|(p, u)| Namespace { prefix: p, uri: u })
}
pub(crate) fn lookup_prefix(&self, uri: &str) -> Option<&'a str> {
if uri == XML_NS {
return Some("xml");
}
match &self.doc.nodes[self.id].kind {
NodeKind::Element { namespaces, .. } => namespaces.iter().find(|(_, u)| u == uri).map(|(p, _)| p.as_str()),
NodeKind::Text(_) => None,
}
}
pub(crate) fn lookup_namespace_uri(&self, prefix: Option<&str>) -> Option<&'a str> {
if prefix == Some("xml") {
return Some(XML_NS);
}
if prefix == Some("xmlns") {
return Some(XMLNS_NS);
}
let target = prefix.unwrap_or("");
match &self.doc.nodes[self.id].kind {
NodeKind::Element { namespaces, .. } => namespaces.iter().find(|(p, _)| p == target).map(|(_, u)| u.as_str()),
NodeKind::Text(_) => None,
}
}
pub(crate) fn children(&self) -> impl Iterator<Item = Node<'a>> + use<'a> {
let doc = self.doc;
doc.nodes[self.id].children.iter().map(move |&id| Node { doc, id })
}
pub(crate) fn descendants(&self) -> Descendants<'a> {
Descendants { doc: self.doc, stack: vec![self.id] }
}
pub(crate) fn text(&self) -> Option<&'a str> {
match &self.doc.nodes[self.id].kind {
NodeKind::Text(t) => Some(t.as_str()),
NodeKind::Element { .. } => self.doc.nodes[self.id].children.first().and_then(|&cid| match &self.doc.nodes[cid].kind {
NodeKind::Text(t) => Some(t.as_str()),
_ => None,
}),
}
}
pub(crate) fn range(&self) -> Range<usize> {
match &self.doc.nodes[self.id].kind {
NodeKind::Element { range, .. } => range.clone(),
NodeKind::Text(_) => 0..0,
}
#[test]
fn shared_dom_keeps_depth_policy_and_rejects_duplicate_attributes() {
assert_eq!(crate::MAX_XML_DEPTH, craft_xfa::MAX_XML_DEPTH);
assert!(Document::parse("<r a='1' a='2'/>").is_err());
assert!(Document::parse("<r xmlns:a='u' xmlns:b='u' a:x='1' b:x='2'/>").is_err());
let doc = Document::parse("<r xmlns='u'><field>value</field></r>").unwrap();
let field = doc.root_element().children().next().unwrap();
assert_eq!(field.tag_name().namespace(), Some("u"));
assert_eq!(field.text(), Some("value"));
}
}