1use std::collections::BTreeSet;
32use std::io::Read;
33
34use serde::{Deserialize, Serialize};
35
36use crate::markup_simplifier::remove_all_rsids;
37use crate::namespaces::{W, W15};
38use crate::opc::PartFs;
39use crate::xmllinq::{Dom, NodeId, XName};
40
41const CORE: &str = "docProps/core.xml";
42const APP: &str = "docProps/app.xml";
43const CUSTOM: &str = "docProps/custom.xml";
44const CUSTOM_REL: &str =
45 "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties";
46const CP: &str = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
47const DC: &str = "http://purl.org/dc/elements/1.1/";
48const DCTERMS: &str = "http://purl.org/dc/terms/";
49const EXTENDED: &str = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
50
51#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(deny_unknown_fields)]
55pub struct ScrubOptions {
56 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub author_alias: Option<String>,
59 #[serde(default)]
60 pub rsids: bool,
62 #[serde(default)]
63 pub docprops: bool,
65 #[serde(default)]
66 pub comments: bool,
68}
69
70impl Default for ScrubOptions {
71 fn default() -> Self {
72 Self {
73 author_alias: Some("Author".into()),
74 rsids: true,
75 docprops: true,
76 comments: true,
77 }
78 }
79}
80
81#[derive(Clone, Debug, PartialEq, Eq)]
83pub enum ScrubError {
84 Package(String),
86 Invalid(String),
89}
90
91impl std::fmt::Display for ScrubError {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 match self {
94 Self::Package(message) => write!(f, "opening DOCX: {message}"),
95 Self::Invalid(message) => write!(f, "cannot scrub: {message}"),
96 }
97 }
98}
99
100impl std::error::Error for ScrubError {}
101
102pub fn scrub(docx: &[u8], options: &ScrubOptions) -> Result<Vec<u8>, ScrubError> {
112 let mut pkg = PartFs::open(docx)
113 .map_err(|e| ScrubError::Package(crate::opc::refusal_message(docx, &e)))?;
114 if pkg
115 .main_document_part()
116 .is_none_or(|main| pkg.part_bytes(&main).is_none())
117 {
118 return Err(ScrubError::Invalid(
119 "the package has no main document part".into(),
120 ));
121 }
122 if let Some(alias) = &options.author_alias
123 && (alias.trim().is_empty() || alias.chars().any(char::is_control))
124 {
125 return Err(ScrubError::Invalid(
126 "author_alias must be a nonempty name without control characters".into(),
127 ));
128 }
129 let before = crate::validate::validate(docx).map_err(|e| ScrubError::Package(e.to_string()))?;
130 if options.comments {
131 remove_comments(&mut pkg);
132 }
133 if let Some(alias) = &options.author_alias {
134 alias_authors(&mut pkg, alias);
135 }
136 if options.rsids {
137 remove_rsids(&mut pkg);
138 }
139 if options.docprops {
140 scrub_properties(&mut pkg);
141 }
142 let out = pkg
143 .to_zip()
144 .map_err(|e| ScrubError::Package(e.to_string()))?;
145 let after = crate::validate::validate(&out).map_err(|e| ScrubError::Package(e.to_string()))?;
146 let new = introduced(&before, &after);
147 if !new.is_empty() {
148 return Err(ScrubError::Invalid(format!(
149 "scrubbing would introduce {}",
150 new.join(", ")
151 )));
152 }
153 Ok(out)
154}
155
156fn introduced(
160 before: &[crate::validate::Finding],
161 after: &[crate::validate::Finding],
162) -> Vec<String> {
163 let had = finding_counts(before);
164 finding_counts(after)
165 .into_iter()
166 .filter(|(key, n)| had.get(key).is_none_or(|h| n > h))
167 .map(|((code, part), _)| format!("{code} in {part}"))
168 .collect()
169}
170
171fn finding_counts(
172 findings: &[crate::validate::Finding],
173) -> std::collections::BTreeMap<(&str, &str), usize> {
174 let mut counts = std::collections::BTreeMap::new();
175 for f in findings {
176 *counts
177 .entry((f.code.as_str(), f.part.as_str()))
178 .or_default() += 1;
179 }
180 counts
181}
182
183struct Part {
185 name: String,
186 dom: Dom,
187 doc: NodeId,
188 root: NodeId,
189}
190
191impl Part {
192 fn load(pkg: &PartFs, name: &str) -> Option<Self> {
193 let xml = pkg.part_string(name)?;
194 let mut dom = Dom::new();
195 let doc = dom.parse_xdocument(&xml);
196 let root = dom.root(doc)?;
197 Some(Self {
198 name: name.to_string(),
199 dom,
200 doc,
201 root,
202 })
203 }
204
205 fn store(self, pkg: &mut PartFs) {
206 pkg.set_part(
207 &self.name,
208 self.dom.serialize_document(self.doc).into_bytes(),
209 );
210 }
211}
212
213fn word_parts(pkg: &PartFs) -> Vec<String> {
215 pkg.parts()
216 .into_iter()
217 .filter(|p| p.starts_with("word/") && p.ends_with(".xml"))
218 .collect()
219}
220
221fn remove_comments(pkg: &mut PartFs) {
224 let stories: Vec<String> = crate::revision_processor::revision_bearing_parts(pkg)
225 .into_iter()
226 .filter(|(_, is_styles)| !is_styles)
227 .map(|(part, _)| part)
228 .collect();
229 for story in &stories {
230 let Some(mut part) = Part::load(pkg, story) else {
231 continue;
232 };
233 let references = part
234 .dom
235 .descendants(part.root, Some(&W::comment_reference()));
236 if references.is_empty() {
237 continue;
238 }
239 for reference in references {
240 let run = part
241 .dom
242 .parent(reference)
243 .filter(|&r| part.dom.name_is(r, &W::r()));
244 part.dom.remove(reference);
245 if let Some(run) = run
247 && part
248 .dom
249 .elements(run, None)
250 .iter()
251 .all(|&k| part.dom.name_is(k, &W::r_pr()))
252 {
253 part.dom.remove(run);
254 }
255 }
256 part.store(pkg);
257 }
258 let comments = crate::revision_processor::comments_part(pkg);
259 crate::revision_processor::prune_orphan_comments(pkg, &stories, comments.as_deref());
260}
261
262fn initials(alias: &str) -> String {
264 alias
265 .split_whitespace()
266 .filter_map(|w| w.chars().next())
267 .flat_map(char::to_uppercase)
268 .collect()
269}
270
271fn alias_authors(pkg: &mut PartFs, alias: &str) {
274 let author = W::author();
275 let initials_name = W::name("initials");
276 let short = initials(alias);
277 for name in word_parts(pkg) {
278 if name == "word/people.xml" {
279 continue;
280 }
281 let Some(mut part) = Part::load(pkg, &name) else {
282 continue;
283 };
284 let mut changed = false;
285 for node in part.dom.descendants_and_self(part.root, None) {
286 if part
287 .dom
288 .attribute(node, &author)
289 .is_some_and(|a| a != alias)
290 {
291 part.dom.set_attribute_value(node, &author, Some(alias));
292 changed = true;
293 }
294 if part
295 .dom
296 .attribute(node, &initials_name)
297 .is_some_and(|i| i != short)
298 {
299 part.dom
300 .set_attribute_value(node, &initials_name, Some(&short));
301 changed = true;
302 }
303 }
304 if changed {
305 part.store(pkg);
306 }
307 }
308 let Some(mut people) = Part::load(pkg, "word/people.xml") else {
309 return;
310 };
311 let person = W15::name("person");
312 let w15_author = W15::name("author");
313 let mut kept = false;
314 for p in people.dom.descendants(people.root, Some(&person)) {
315 if kept {
316 people.dom.remove(p);
317 continue;
318 }
319 kept = true;
320 people.dom.set_attribute_value(p, &w15_author, Some(alias));
321 for presence in people.dom.elements(p, Some(&W15::name("presenceInfo"))) {
322 people.dom.remove(presence);
323 }
324 }
325 people.store(pkg);
326}
327
328fn remove_rsids(pkg: &mut PartFs) {
331 let rsids = W::name("rsids");
332 for name in word_parts(pkg) {
333 if !pkg.part_string(&name).is_some_and(|x| x.contains("rsid")) {
334 continue;
335 }
336 let Some(mut part) = Part::load(pkg, &name) else {
337 continue;
338 };
339 for list in part.dom.descendants(part.root, Some(&rsids)) {
340 part.dom.remove(list);
341 }
342 remove_all_rsids(&mut part.dom, part.root);
343 part.store(pkg);
344 }
345}
346
347fn remove_children(part: &mut Part, names: &[XName]) -> bool {
349 let mut changed = false;
350 for name in names {
351 for node in part.dom.elements(part.root, Some(name)) {
352 part.dom.remove(node);
353 changed = true;
354 }
355 }
356 changed
357}
358
359fn scrub_properties(pkg: &mut PartFs) {
362 if let Some(mut core) = Part::load(pkg, CORE) {
363 let names = [
364 XName::get("creator", DC),
365 XName::get("lastModifiedBy", CP),
366 XName::get("revision", CP),
367 XName::get("lastPrinted", CP),
368 XName::get("created", DCTERMS),
369 XName::get("modified", DCTERMS),
370 ];
371 if remove_children(&mut core, &names) {
372 core.store(pkg);
373 }
374 }
375 if let Some(mut app) = Part::load(pkg, APP) {
376 let names = [
377 XName::get("Manager", EXTENDED),
378 XName::get("Company", EXTENDED),
379 ];
380 if remove_children(&mut app, &names) {
381 app.store(pkg);
382 }
383 }
384 if pkg.part_bytes(CUSTOM).is_some() {
385 pkg.remove_part(CUSTOM);
386 pkg.remove_package_relationships_by_type(CUSTOM_REL);
387 pkg.remove_content_type_override(&format!("/{CUSTOM}"));
388 }
389}
390
391pub fn leaks(docx: &[u8], needle: &str) -> Vec<String> {
410 leaks_within(docx, needle, crate::admission::InputLimits::compare())
411}
412
413pub fn leak_scan(docx: &[u8], needle: &str) -> LeakScan {
422 leak_scan_within(docx, needle, crate::admission::InputLimits::compare())
423}
424
425#[derive(Debug, Clone, PartialEq, Eq)]
427pub enum LeakScan {
428 Complete(Vec<String>),
430 Incomplete {
432 part: String,
434 reason: &'static str,
436 },
437}
438
439impl LeakScan {
440 fn findings_fail_closed(self) -> Vec<String> {
441 match self {
442 Self::Complete(found) => found,
443 Self::Incomplete { part, reason } => vec![format!("{part} ({reason})")],
444 }
445 }
446}
447
448pub(crate) fn leaks_within(
451 docx: &[u8],
452 needle: &str,
453 limits: crate::admission::InputLimits,
454) -> Vec<String> {
455 leak_scan_within(docx, needle, limits).findings_fail_closed()
456}
457
458fn leak_scan_within(docx: &[u8], needle: &str, limits: crate::admission::InputLimits) -> LeakScan {
459 let mut found = BTreeSet::new();
460 if needle.is_empty() {
461 return LeakScan::Complete(Vec::new());
462 }
463 if let Err(error) = crate::admission::preindex_budget(docx, limits) {
464 return LeakScan::Complete(vec![format!("the package ({error})")]);
465 }
466 let mut zip = match crate::opc::open_archive(std::io::Cursor::new(docx)) {
467 Ok(zip) => zip,
468 Err(error) => {
469 return LeakScan::Complete(vec![format!("the package (cannot read: {error})")]);
470 }
471 };
472 let utf16: Vec<u8> = needle.encode_utf16().flat_map(u16::to_le_bytes).collect();
473 let mut total = 0u64;
474 for i in 0..zip.len() {
475 let mut entry = match zip.by_index(i) {
476 Ok(entry) => entry,
477 Err(error) => {
478 found.insert(format!("ZIP entry {i} (cannot read: {error})"));
479 break;
480 }
481 };
482 let name = match entry.name() {
483 Ok(name) => name,
484 Err(error) => {
485 found.insert(format!("ZIP entry {i} (cannot read name: {error})"));
486 break;
487 }
488 };
489 let name = crate::admission::shown(&name).into_owned();
492 if entry.size() > limits.max_part_bytes {
493 let error = crate::admission::part_declared_over(&name, entry.size(), &limits);
494 found.insert(format!("{name} ({error})"));
495 break;
496 }
497 let cap = limits
498 .max_part_bytes
499 .min(limits.max_uncompressed_bytes.saturating_sub(total));
500 let mut bytes = Vec::new();
501 let read = match (&mut entry)
502 .take(cap.saturating_add(1))
503 .read_to_end(&mut bytes)
504 {
505 Ok(read) => read as u64,
506 Err(error) => {
507 found.insert(format!("{name} (cannot read: {error})"));
508 break;
509 }
510 };
511 if let Err(error) = crate::admission::tally_inflated(&mut total, read, &name, cap, &limits)
512 {
513 found.insert(format!("{name} ({error})"));
514 break;
515 }
516 if let Some(reason) = uncertified_encoding(&bytes) {
517 return LeakScan::Incomplete { part: name, reason };
518 }
519 let xml = name.ends_with(".xml") || name.ends_with(".rels");
520 let hit = if xml {
521 xml_holds(&xml_text(&bytes), needle)
522 } else {
523 contains(&bytes, needle.as_bytes()) || contains(&bytes, &utf16)
524 };
525 if hit {
526 found.insert(name);
527 }
528 }
529 LeakScan::Complete(found.into_iter().collect())
530}
531
532fn xml_text(bytes: &[u8]) -> std::borrow::Cow<'_, str> {
535 let utf16 = bytes
536 .strip_prefix(&[0xFF, 0xFE])
537 .or_else(|| bytes.starts_with(b"<\0").then_some(bytes));
538 match utf16 {
539 Some(body) => std::borrow::Cow::Owned(
540 char::decode_utf16(body.chunks(2).map(|pair| {
541 u16::from_le_bytes([*pair.first().unwrap_or(&0), *pair.get(1).unwrap_or(&0)])
542 }))
543 .map(|unit| unit.unwrap_or(char::REPLACEMENT_CHARACTER))
544 .collect(),
545 ),
546 None => String::from_utf8_lossy(bytes),
547 }
548}
549
550fn uncertified_encoding(bytes: &[u8]) -> Option<&'static str> {
554 if bytes.starts_with(&[0x00, 0x00, 0xFE, 0xFF]) {
555 return Some(
556 "UTF-32BE is not a certified encoding; this scan reads UTF-8 and UTF-16LE only",
557 );
558 }
559 if bytes.starts_with(&[0xFF, 0xFE, 0x00, 0x00]) {
560 return Some(
561 "UTF-32LE is not a certified encoding; this scan reads UTF-8 and UTF-16LE only",
562 );
563 }
564 if bytes.starts_with(&[0xFE, 0xFF]) {
565 return Some(
566 "UTF-16BE is not a certified encoding; this scan reads UTF-8 and UTF-16LE only",
567 );
568 }
569 None
570}
571
572fn contains(hay: &[u8], needle: &[u8]) -> bool {
573 !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
574}
575
576const NUMERIC_ATTRIBUTES: &[&str] = &[
578 "id",
579 "paraId",
580 "textId",
581 "durableId",
582 "w",
583 "h",
584 "top",
585 "bottom",
586 "left",
587 "right",
588 "start",
589 "end",
590 "header",
591 "footer",
592 "gutter",
593 "before",
594 "after",
595 "line",
596 "firstLine",
597 "hanging",
598 "pos",
599 "x",
600 "y",
601 "cx",
602 "cy",
603 "sz",
604 "space",
605 "num",
606 "numId",
607 "ilvl",
608 "abstractNumId",
609 "colFirst",
610 "colLast",
611 "percent",
612];
613
614fn is_number(value: &str) -> bool {
615 let digits = value.strip_prefix('-').unwrap_or(value);
616 !digits.is_empty() && digits.chars().all(|c| c.is_ascii_hexdigit())
617}
618
619fn xml_holds(xml: &str, needle: &str) -> bool {
620 let mut dom = Dom::new();
621 let doc = dom.parse_xdocument(xml);
622 let Some(root) = dom.root(doc) else {
623 return xml.contains(needle);
625 };
626 for node in dom.descendant_nodes(doc) {
627 if dom.is_text(node) || dom.is_comment(node) {
628 if dom.text_value(node).is_some_and(|v| v.contains(needle)) {
629 return true;
630 }
631 } else if dom.is_pi(node) {
632 if dom.pi_data(node).is_some_and(|v| v.contains(needle)) {
633 return true;
634 }
635 } else if dom.is_element(node) {
636 for i in 0..dom.attr_count(node) {
637 let (name, value) = dom.attr_at(node, i);
638 if !value.contains(needle) || dom.is_namespace_declaration(name) {
639 continue;
640 }
641 if NUMERIC_ATTRIBUTES.contains(&name.local_name()) && is_number(value) {
642 continue;
643 }
644 return true;
645 }
646 }
647 }
648 let texts = [W::t(), W::del_text(), W::instr_text()];
650 for p in dom.descendants_and_self(root, Some(&W::p())) {
651 let joined: String = dom
652 .descendants(p, None)
653 .into_iter()
654 .filter(|&n| texts.iter().any(|t| dom.name_is(n, t)))
655 .map(|n| dom.value(n))
656 .collect();
657 if joined.contains(needle) {
658 return true;
659 }
660 }
661 false
662}
663
664#[cfg(test)]
665#[cfg_attr(all(coverage_nightly, test), coverage(off))]
666mod tests {
667 use super::*;
668
669 fn finding(code: &str, part: &str, path: &str) -> crate::validate::Finding {
670 crate::validate::Finding {
671 code: code.into(),
672 set: "word".into(),
673 severity: "error".into(),
674 part: part.into(),
675 location: path.into(),
676 r#ref: crate::ids::short_paragraph(path),
677 message: String::new(),
678 word_fatal: true,
679 repairable: false,
680 }
681 }
682
683 #[test]
684 fn introduced_counts_findings_by_code_and_part_not_path() {
685 let had = [finding("A", "word/document.xml", "w:body[0]/w:p[3]")];
686 let moved = [finding("A", "word/document.xml", "w:body[0]/w:p[1]")];
688 assert!(introduced(&had, &moved).is_empty());
689 let twice = [moved[0].clone(), finding("A", "word/document.xml", "x")];
691 assert_eq!(introduced(&had, &twice), ["A in word/document.xml"]);
692 let other = [
694 finding("A", "word/comments.xml", ""),
695 finding("B", "word/document.xml", ""),
696 ];
697 assert_eq!(
698 introduced(&had, &other),
699 ["A in word/comments.xml", "B in word/document.xml"]
700 );
701 assert!(introduced(&had, &[]).is_empty());
703 }
704
705 #[test]
706 fn initials_take_the_first_letter_of_each_word() {
707 assert_eq!(initials("Outside Counsel"), "OC");
708 assert_eq!(initials("reviewer"), "R");
709 }
710
711 #[test]
712 fn numbers_and_hex_ids_are_numbers() {
713 assert!(is_number("1440") && is_number("-720") && is_number("00AB12CD"));
714 assert!(!is_number("") && !is_number("12 345") && !is_number("Jane"));
715 }
716
717 #[test]
718 fn a_needle_in_a_numeric_attribute_is_no_leak_but_in_a_text_attribute_it_is() {
719 let w = W::URI;
720 let size = format!(r#"<w:document xmlns:w="{w}"><w:pgSz w:w="12240"/></w:document>"#);
721 assert!(!xml_holds(&size, "1224"));
722 let alt = format!(r#"<w:document xmlns:w="{w}"><w:x w:val="12240"/></w:document>"#);
723 assert!(xml_holds(&alt, "1224"));
724 }
725
726 #[test]
727 fn element_names_are_no_leak() {
728 let w = W::URI;
729 let xml = format!(r#"<w:document xmlns:w="{w}"><w:body/></w:document>"#);
730 assert!(!xml_holds(&xml, "body"));
731 assert!(xml_holds(&format!("{xml}<!-- body -->"), "body"));
732 }
733}
734
735#[cfg(test)]
736#[cfg_attr(all(coverage_nightly, test), coverage(off))]
737mod public_memory_leak_boundary_tests {
738 use super::*;
739
740 fn package(body: &str) -> PartFs {
741 let mut pkg = PartFs::open(include_bytes!(
742 "../../../tests/fixtures/redline/original.docx"
743 ))
744 .unwrap();
745 pkg.set_part("word/document.xml",format!("<w:document xmlns:w='{}'><w:body>{body}<w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>",W::URI).into_bytes());
746 pkg
747 }
748 fn snapshot(pkg: &PartFs) -> Vec<(String, Vec<u8>)> {
749 let mut parts = pkg.parts();
750 parts.sort();
751 parts
752 .into_iter()
753 .map(|name| {
754 let bytes = pkg.part_bytes(&name).unwrap().to_vec();
755 (name, bytes)
756 })
757 .collect()
758 }
759
760 #[test]
761 fn public_leaks_reports_exact_xml_and_binary_part_owners_without_mutating_sources() {
762 for secret in ["PrivateReviewer", "PendingReviewer"] {
763 let mut pkg = package("<w:p><w:r><w:t>Independent body payload</w:t></w:r></w:p>");
764 pkg.set_part(
765 "customXml/comment.xml",
766 format!("<metadata><!-- {secret} --></metadata>").into_bytes(),
767 );
768 pkg.set_part(
769 "customXml/pi.xml",
770 format!("<?privacy {secret}?><metadata/>").into_bytes(),
771 );
772 pkg.set_part(
773 "customXml/attribute.xml",
774 format!("<metadata id='{secret}'/>").into_bytes(),
775 );
776 pkg.set_part(
777 "customXml/namespace.xml",
778 format!("<metadata xmlns:private='urn:{secret}'/>").into_bytes(),
779 );
780 pkg.set_part("customXml/utf8.bin", secret.as_bytes().to_vec());
781 pkg.set_part(
782 "customXml/utf16.bin",
783 secret.encode_utf16().flat_map(u16::to_le_bytes).collect(),
784 );
785 pkg.set_part(
786 "customXml/clean.bin",
787 b"Independent binary payload".to_vec(),
788 );
789 for part in [
790 "/customXml/utf8.bin",
791 "/customXml/utf16.bin",
792 "/customXml/clean.bin",
793 ] {
794 pkg.add_content_type_override(part, "application/octet-stream");
795 }
796 let original = snapshot(&pkg);
797 let bytes = pkg.to_zip().unwrap();
798 let expected = vec![
799 "customXml/attribute.xml",
800 "customXml/comment.xml",
801 "customXml/pi.xml",
802 "customXml/utf16.bin",
803 "customXml/utf8.bin",
804 ];
805 assert_eq!(leaks(&bytes, secret), expected);
806 assert_eq!(leaks(&bytes, secret), expected);
807 assert!(leaks(&bytes, "").is_empty());
808 assert!(leaks(&bytes, "absent reviewer").is_empty());
809 assert_eq!(snapshot(&PartFs::open(&bytes).unwrap()), original);
810 }
811 }
812 #[test]
813 fn decoded_entities_and_split_word_runs_are_secrets_but_numeric_ids_are_not() {
814 let body = "<w:p><w:pPr><w:spacing w:before='1234' w:after='-1234'/></w:pPr><w:r><w:t>Jane </w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>Doe & </w:t></w:r><w:r><w:t>Associates</w:t></w:r></w:p>";
815 let mut pkg = package(body);
816 pkg.set_part(
817 "customXml/encoded.xml",
818 b"<metadata owner='Jane & Doe'>independent</metadata>".to_vec(),
819 );
820 let original = snapshot(&pkg);
821 let bytes = pkg.to_zip().unwrap();
822 assert_eq!(
823 leaks(&bytes, "Jane Doe & Associates"),
824 ["word/document.xml"]
825 );
826 assert_eq!(leaks(&bytes, "Jane & Doe"), ["customXml/encoded.xml"]);
827 assert!(leaks(&bytes, "1234").is_empty());
828 assert!(leaks(&bytes, "spacing").is_empty());
829 assert_eq!(snapshot(&PartFs::open(&bytes).unwrap()), original);
830 }
831 #[test]
832 fn invalid_aliases_are_rejected_before_any_source_property_is_rewritten() {
833 let pkg = package("<w:p><w:r><w:t>Owned source payload</w:t></w:r></w:p>");
834 let original = snapshot(&pkg);
835 let bytes = pkg.to_zip().unwrap();
836 for alias in ["", " ", "Reviewer\nname", "Reviewer\tname"] {
837 let options = ScrubOptions {
838 author_alias: Some(alias.into()),
839 rsids: false,
840 docprops: false,
841 comments: false,
842 };
843 assert!(
844 matches!(scrub(&bytes,&options),Err(ScrubError::Invalid(message)) if message=="author_alias must be a nonempty name without control characters")
845 );
846 assert_eq!(snapshot(&PartFs::open(&bytes).unwrap()), original);
847 }
848 }
849}
850
851#[cfg(test)]
852#[cfg_attr(all(coverage_nightly, test), coverage(off))]
853mod bounded_input_tests {
854 use super::*;
855 use crate::admission::{InputLimits, limit_test_support as fixture};
856
857 fn refuses(limits: InputLimits, detail: &str) {
858 let bytes = fixture::package();
859 let text = leaks_within(&bytes, "absent needle", limits).join(", ");
860 assert!(text.contains("INPUT_LIMIT"), "{text}");
861 assert!(text.contains(detail), "{text}");
862 }
863 #[test]
864 fn compressed_limit() {
865 refuses(fixture::compressed(), "input is");
866 }
867 #[test]
868 fn count_limit() {
869 refuses(fixture::count(), "3 ZIP entries; the limit is 2");
870 }
871 #[test]
872 fn part_limit() {
873 refuses(fixture::part(), "a.bin");
874 }
875 #[test]
876 fn aggregate_limit() {
877 refuses(fixture::total(), "the package limit is 160");
878 }
879 #[test]
880 fn unreadable_entry_is_a_finding() {
881 let mut bytes = fixture::package();
882 let cd = bytes.windows(4).position(|w| w == b"PK\x01\x02").unwrap();
884 bytes[cd + 16] ^= 1;
885 let findings = leaks_within(&bytes, "absent needle", fixture::limits());
886 assert!(
887 !findings.is_empty(),
888 "an unreadable part cannot certify a redaction"
889 );
890 }
891 #[test]
892 fn exact_budget_control() {
893 let bytes = fixture::package();
894 assert!(leaks_within(&bytes, "absent needle", fixture::limits()).is_empty());
895 assert_eq!(
896 leaks_within(&bytes, "aaaa", fixture::limits()),
897 ["word/media/a.bin"]
898 );
899 }
900}
901
902#[cfg(test)]
903#[cfg_attr(all(coverage_nightly, test), coverage(off))]
904mod leak_branch_tests {
905 use super::*;
906
907 #[test]
908 fn only_utf8_and_utf16le_are_certified() {
909 assert!(
910 uncertified_encoding(&[0x00, 0x00, 0xFE, 0xFF])
911 .unwrap()
912 .starts_with("UTF-32BE")
913 );
914 assert!(
915 uncertified_encoding(&[0xFF, 0xFE, 0x00, 0x00])
916 .unwrap()
917 .starts_with("UTF-32LE")
918 );
919 assert!(
920 uncertified_encoding(&[0xFE, 0xFF, 0x00, 0x3C])
921 .unwrap()
922 .starts_with("UTF-16BE")
923 );
924 assert_eq!(uncertified_encoding(&[0xFF, 0xFE, 0x3C, 0x00]), None);
925 assert_eq!(uncertified_encoding(b"<x/>"), None);
926 assert!(!contains(b"abc", b""));
927 assert!(contains(b"abc", b"bc"));
928 }
929
930 #[test]
931 fn a_needle_is_found_wherever_xml_can_hold_it() {
932 assert!(xml_holds("plain text Secret", "Secret"), "not XML");
933 assert!(xml_holds("<r><!-- Secret --></r>", "Secret"), "comment");
934 assert!(xml_holds("<r><?pi Secret?></r>", "Secret"), "instruction");
935 assert!(xml_holds("<r a=\"Secret\"/>", "Secret"), "attribute");
936 assert!(!xml_holds("<r id=\"1234\"/>", "23"));
938 assert!(xml_holds("<r name=\"1234\"/>", "23"));
939 assert!(
940 !xml_holds("<r xmlns:s=\"urn:Secret\"/>", "Secret"),
941 "declaration"
942 );
943 }
944}