Skip to main content

jubarte_doc/
scrub.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Remove who touched a document before it goes out, and find where a text
6//! still occurs in one.
7//!
8//! [`scrub`] works on four kinds of identifying data, each one optional:
9//!
10//! - **Author alias.** Every `w:author` in the `word/` parts (tracked
11//!   changes, formatting changes, comments) becomes the alias, comment
12//!   initials become the alias's initials, and `people.xml` keeps a single
13//!   person, the alias, without presence information (e-mail, provider).
14//! - **rsids.** Every `w:rsid*` attribute and the settings' `w:rsids` list:
15//!   the edit-session ids that tie copies of a document to one another.
16//! - **Document properties.** Core properties lose the creator, the last
17//!   editor, the revision number and the created, modified and printed
18//!   dates; extended properties lose the manager and company; the custom
19//!   properties part goes with its relationship and content type. The
20//!   title, subject and application stay.
21//! - **Comments.** Every comment reference and range goes, then the comment
22//!   parts and `people.xml` with them.
23//!
24//! Text, tracked changes and formatting stay. Revision dates stay.
25//!
26//! [`leaks`](crate::scrub::leaks) is the check behind the `redact` plan operation: the parts of a
27//! package where a text still occurs. [`leak_scan`](crate::scrub::leak_scan) is that check with a
28//! completeness receipt, so an encoding this scanner does not certify is
29//! not reported as "the text is absent".
30
31use 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/// What [`scrub`] removes. A field left out of the JSON form is off; the
52/// [`Default`] turns everything on with the alias `Author`.
53#[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    /// Name every author takes: revisions, comments and `people.xml`.
58    pub author_alias: Option<String>,
59    #[serde(default)]
60    /// Remove `w:rsid*` attributes and the settings' `w:rsids`.
61    pub rsids: bool,
62    #[serde(default)]
63    /// Remove the people and dates from the document properties.
64    pub docprops: bool,
65    #[serde(default)]
66    /// Remove every comment.
67    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/// Why [`scrub`] refused its input.
82#[derive(Clone, Debug, PartialEq, Eq)]
83pub enum ScrubError {
84    /// The bytes are not an OPC package, or it cannot be written back.
85    Package(String),
86    /// The package has no main document, the options are invalid, or
87    /// scrubbing would introduce new validation findings.
88    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
102/// Remove the identifying data `options` names from a `.docx`. Backs
103/// `jubarte scrub`; returns the scrubbed bytes, writing nothing.
104///
105/// # Errors
106///
107/// [`ScrubError::Package`] when the bytes are not an OPC package or cannot
108/// be written back; [`ScrubError::Invalid`] when the package has no main
109/// document, the options are invalid, or scrubbing would introduce new
110/// validation findings.
111pub 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
156/// The findings `after` has more of than `before`, as `CODE in part`,
157/// counted by code and part: removing elements shifts the paths of
158/// findings that were already there.
159fn 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
183/// One parsed XML part, written back only when changed.
184struct 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
213/// The XML parts under `word/`.
214fn 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
221/// Drop every comment reference and range, then the comment parts and
222/// `people.xml` that no comment needs any more.
223fn 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            // The reference's own run holds nothing else but properties.
246            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
262/// The alias's initials: the first letter of each word, upper case.
263fn 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
271/// Every author in the `word/` parts becomes `alias`; `people.xml` keeps
272/// one person, the alias, without presence information.
273fn 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
328/// Strip `w:rsid*` attributes and `w:rsid` elements everywhere under
329/// `word/`, and the settings' `w:rsids` list.
330fn 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
347/// Remove the elements named `names` that are children of `part`'s root.
348fn 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
359/// Drop the people and dates of the core and extended properties, and the
360/// custom properties part.
361fn 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
391/// The parts of `docx` where `needle` still occurs, sorted: in a text node,
392/// an attribute value that can hold text, an XML comment, the joined run
393/// text of a paragraph (a text split across runs), or the raw bytes of a
394/// part that is not XML (UTF-8 or UTF-16LE). An empty needle occurs nowhere.
395/// An unreadable archive or entry is a finding: an incomplete scan cannot
396/// certify a redaction. An encoding this scanner does not certify is also
397/// a finding here; [`leak_scan`] reports that case as
398/// [`LeakScan::Incomplete`] instead of a part where the text occurs.
399///
400/// The scan is bounded like the package constructor (#645): a package past
401/// the admission budget, or an entry that inflates past its per-part or
402/// package cap, is reported as a finding rather than skipped — `edit`'s
403/// redaction check turns every finding into a refusal, so a package that
404/// cannot be scanned fails closed.
405///
406/// The check fails closed: a short needle can also match an unrelated
407/// attribute value. Attributes that only ever hold numbers (sizes, ids,
408/// positions) are skipped when their value is a plain number.
409pub fn leaks(docx: &[u8], needle: &str) -> Vec<String> {
410    leaks_within(docx, needle, crate::admission::InputLimits::compare())
411}
412
413/// [`leaks`] plus a completeness receipt.
414///
415/// [`LeakScan::Complete`] means every part was read in a representation
416/// this scanner certifies (XML as UTF-8 or UTF-16LE text, anything else as
417/// raw UTF-8 or UTF-16LE). An empty finding list then means the needle does not
418/// occur. [`LeakScan::Incomplete`] means a part uses an encoding this
419/// scanner does not certify, which is not the same as the needle being
420/// absent. The reason names the encoding, never the needle.
421pub fn leak_scan(docx: &[u8], needle: &str) -> LeakScan {
422    leak_scan_within(docx, needle, crate::admission::InputLimits::compare())
423}
424
425/// What [`leak_scan`] was able to certify.
426#[derive(Debug, Clone, PartialEq, Eq)]
427pub enum LeakScan {
428    /// Parts where `needle` occurs under a certified representation.
429    Complete(Vec<String>),
430    /// `part` is not in a representation this scanner can certify.
431    Incomplete {
432        /// Archive name of the part, with control characters escaped.
433        part: String,
434        /// Encoding the scan does not certify. This text does not contain the needle.
435        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
448/// [`leaks`] under an explicit budget, so the fail-closed paths are provable
449/// with budgets small enough for a test.
450pub(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        // Findings echo the name: escape control characters so a
490        // crafted name cannot write terminal sequences.
491        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
532/// An XML part as text: UTF-16LE when it opens with that BOM or with a
533/// UTF-16LE `<` (SharePoint writes customXml items so), UTF-8 otherwise.
534fn 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
550/// BOM of an encoding this scanner does not read. UTF-8 and UTF-16LE,
551/// with or without a BOM, stay certified: the XML path reads UTF-8 text
552/// and every other part is searched as raw UTF-8 and UTF-16LE bytes.
553fn 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
576/// Attributes that only ever hold a number or a hex id.
577const 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        // Not XML after all: read it as bytes.
624        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    // A text split across runs shows only in the paragraph's joined text.
649    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        // The same finding at a shifted path is not new.
687        let moved = [finding("A", "word/document.xml", "w:body[0]/w:p[1]")];
688        assert!(introduced(&had, &moved).is_empty());
689        // A second one of the code in the part is.
690        let twice = [moved[0].clone(), finding("A", "word/document.xml", "x")];
691        assert_eq!(introduced(&had, &twice), ["A in word/document.xml"]);
692        // So is the code in another part, or another code.
693        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        // Fewer findings is fine.
702        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 &amp; </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 &amp; 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        // Corrupt a central-directory CRC, leaving its payload and size intact.
883        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        // A numeric attribute that happens to contain the needle is no leak.
937        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}