jubarte-doc 0.20.0

The document operations of the jubarte engine above compare: changes, comments, validation, audit, scrub, append, fields and the debug views
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! Remove who touched a document before it goes out, and find where a text
//! still occurs in one.
//!
//! [`scrub`] works on four kinds of identifying data, each one optional:
//!
//! - **Author alias.** Every `w:author` in the `word/` parts (tracked
//!   changes, formatting changes, comments) becomes the alias, comment
//!   initials become the alias's initials, and `people.xml` keeps a single
//!   person, the alias, without presence information (e-mail, provider).
//! - **rsids.** Every `w:rsid*` attribute and the settings' `w:rsids` list:
//!   the edit-session ids that tie copies of a document to one another.
//! - **Document properties.** Core properties lose the creator, the last
//!   editor, the revision number and the created, modified and printed
//!   dates; extended properties lose the manager and company; the custom
//!   properties part goes with its relationship and content type. The
//!   title, subject and application stay.
//! - **Comments.** Every comment reference and range goes, then the comment
//!   parts and `people.xml` with them.
//!
//! Text, tracked changes and formatting stay. Revision dates stay.
//!
//! [`leaks`](crate::scrub::leaks) is the check behind the `redact` plan operation: the parts of a
//! package where a text still occurs. [`leak_scan`](crate::scrub::leak_scan) is that check with a
//! completeness receipt, so an encoding this scanner does not certify is
//! not reported as "the text is absent".

use std::collections::BTreeSet;
use std::io::Read;

use serde::{Deserialize, Serialize};

use crate::markup_simplifier::remove_all_rsids;
use crate::namespaces::{W, W15};
use crate::opc::PartFs;
use crate::xmllinq::{Dom, NodeId, XName};

const CORE: &str = "docProps/core.xml";
const APP: &str = "docProps/app.xml";
const CUSTOM: &str = "docProps/custom.xml";
const CUSTOM_REL: &str =
    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties";
const CP: &str = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
const DC: &str = "http://purl.org/dc/elements/1.1/";
const DCTERMS: &str = "http://purl.org/dc/terms/";
const EXTENDED: &str = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";

/// What [`scrub`] removes. A field left out of the JSON form is off; the
/// [`Default`] turns everything on with the alias `Author`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScrubOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    /// Name every author takes: revisions, comments and `people.xml`.
    pub author_alias: Option<String>,
    #[serde(default)]
    /// Remove `w:rsid*` attributes and the settings' `w:rsids`.
    pub rsids: bool,
    #[serde(default)]
    /// Remove the people and dates from the document properties.
    pub docprops: bool,
    #[serde(default)]
    /// Remove every comment.
    pub comments: bool,
}

impl Default for ScrubOptions {
    fn default() -> Self {
        Self {
            author_alias: Some("Author".into()),
            rsids: true,
            docprops: true,
            comments: true,
        }
    }
}

/// Why [`scrub`] refused its input.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ScrubError {
    /// The bytes are not an OPC package, or it cannot be written back.
    Package(String),
    /// The package has no main document, the options are invalid, or
    /// scrubbing would introduce new validation findings.
    Invalid(String),
}

impl std::fmt::Display for ScrubError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Package(message) => write!(f, "opening DOCX: {message}"),
            Self::Invalid(message) => write!(f, "cannot scrub: {message}"),
        }
    }
}

impl std::error::Error for ScrubError {}

/// Remove the identifying data `options` names from a `.docx`. Backs
/// `jubarte scrub`; returns the scrubbed bytes, writing nothing.
///
/// # Errors
///
/// [`ScrubError::Package`] when the bytes are not an OPC package or cannot
/// be written back; [`ScrubError::Invalid`] when the package has no main
/// document, the options are invalid, or scrubbing would introduce new
/// validation findings.
pub fn scrub(docx: &[u8], options: &ScrubOptions) -> Result<Vec<u8>, ScrubError> {
    let mut pkg = PartFs::open(docx)
        .map_err(|e| ScrubError::Package(crate::opc::refusal_message(docx, &e)))?;
    if pkg
        .main_document_part()
        .is_none_or(|main| pkg.part_bytes(&main).is_none())
    {
        return Err(ScrubError::Invalid(
            "the package has no main document part".into(),
        ));
    }
    if let Some(alias) = &options.author_alias
        && (alias.trim().is_empty() || alias.chars().any(char::is_control))
    {
        return Err(ScrubError::Invalid(
            "author_alias must be a nonempty name without control characters".into(),
        ));
    }
    let before = crate::validate::validate(docx).map_err(|e| ScrubError::Package(e.to_string()))?;
    if options.comments {
        remove_comments(&mut pkg);
    }
    if let Some(alias) = &options.author_alias {
        alias_authors(&mut pkg, alias);
    }
    if options.rsids {
        remove_rsids(&mut pkg);
    }
    if options.docprops {
        scrub_properties(&mut pkg);
    }
    let out = pkg
        .to_zip()
        .map_err(|e| ScrubError::Package(e.to_string()))?;
    let after = crate::validate::validate(&out).map_err(|e| ScrubError::Package(e.to_string()))?;
    let new = introduced(&before, &after);
    if !new.is_empty() {
        return Err(ScrubError::Invalid(format!(
            "scrubbing would introduce {}",
            new.join(", ")
        )));
    }
    Ok(out)
}

/// The findings `after` has more of than `before`, as `CODE in part`,
/// counted by code and part: removing elements shifts the paths of
/// findings that were already there.
fn introduced(
    before: &[crate::validate::Finding],
    after: &[crate::validate::Finding],
) -> Vec<String> {
    let had = finding_counts(before);
    finding_counts(after)
        .into_iter()
        .filter(|(key, n)| had.get(key).is_none_or(|h| n > h))
        .map(|((code, part), _)| format!("{code} in {part}"))
        .collect()
}

fn finding_counts(
    findings: &[crate::validate::Finding],
) -> std::collections::BTreeMap<(&str, &str), usize> {
    let mut counts = std::collections::BTreeMap::new();
    for f in findings {
        *counts
            .entry((f.code.as_str(), f.part.as_str()))
            .or_default() += 1;
    }
    counts
}

/// One parsed XML part, written back only when changed.
struct Part {
    name: String,
    dom: Dom,
    doc: NodeId,
    root: NodeId,
}

impl Part {
    fn load(pkg: &PartFs, name: &str) -> Option<Self> {
        let xml = pkg.part_string(name)?;
        let mut dom = Dom::new();
        let doc = dom.parse_xdocument(&xml);
        let root = dom.root(doc)?;
        Some(Self {
            name: name.to_string(),
            dom,
            doc,
            root,
        })
    }

    fn store(self, pkg: &mut PartFs) {
        pkg.set_part(
            &self.name,
            self.dom.serialize_document(self.doc).into_bytes(),
        );
    }
}

/// The XML parts under `word/`.
fn word_parts(pkg: &PartFs) -> Vec<String> {
    pkg.parts()
        .into_iter()
        .filter(|p| p.starts_with("word/") && p.ends_with(".xml"))
        .collect()
}

/// Drop every comment reference and range, then the comment parts and
/// `people.xml` that no comment needs any more.
fn remove_comments(pkg: &mut PartFs) {
    let stories: Vec<String> = crate::revision_processor::revision_bearing_parts(pkg)
        .into_iter()
        .filter(|(_, is_styles)| !is_styles)
        .map(|(part, _)| part)
        .collect();
    for story in &stories {
        let Some(mut part) = Part::load(pkg, story) else {
            continue;
        };
        let references = part
            .dom
            .descendants(part.root, Some(&W::comment_reference()));
        if references.is_empty() {
            continue;
        }
        for reference in references {
            let run = part
                .dom
                .parent(reference)
                .filter(|&r| part.dom.name_is(r, &W::r()));
            part.dom.remove(reference);
            // The reference's own run holds nothing else but properties.
            if let Some(run) = run
                && part
                    .dom
                    .elements(run, None)
                    .iter()
                    .all(|&k| part.dom.name_is(k, &W::r_pr()))
            {
                part.dom.remove(run);
            }
        }
        part.store(pkg);
    }
    let comments = crate::revision_processor::comments_part(pkg);
    crate::revision_processor::prune_orphan_comments(pkg, &stories, comments.as_deref());
}

/// The alias's initials: the first letter of each word, upper case.
fn initials(alias: &str) -> String {
    alias
        .split_whitespace()
        .filter_map(|w| w.chars().next())
        .flat_map(char::to_uppercase)
        .collect()
}

/// Every author in the `word/` parts becomes `alias`; `people.xml` keeps
/// one person, the alias, without presence information.
fn alias_authors(pkg: &mut PartFs, alias: &str) {
    let author = W::author();
    let initials_name = W::name("initials");
    let short = initials(alias);
    for name in word_parts(pkg) {
        if name == "word/people.xml" {
            continue;
        }
        let Some(mut part) = Part::load(pkg, &name) else {
            continue;
        };
        let mut changed = false;
        for node in part.dom.descendants_and_self(part.root, None) {
            if part
                .dom
                .attribute(node, &author)
                .is_some_and(|a| a != alias)
            {
                part.dom.set_attribute_value(node, &author, Some(alias));
                changed = true;
            }
            if part
                .dom
                .attribute(node, &initials_name)
                .is_some_and(|i| i != short)
            {
                part.dom
                    .set_attribute_value(node, &initials_name, Some(&short));
                changed = true;
            }
        }
        if changed {
            part.store(pkg);
        }
    }
    let Some(mut people) = Part::load(pkg, "word/people.xml") else {
        return;
    };
    let person = W15::name("person");
    let w15_author = W15::name("author");
    let mut kept = false;
    for p in people.dom.descendants(people.root, Some(&person)) {
        if kept {
            people.dom.remove(p);
            continue;
        }
        kept = true;
        people.dom.set_attribute_value(p, &w15_author, Some(alias));
        for presence in people.dom.elements(p, Some(&W15::name("presenceInfo"))) {
            people.dom.remove(presence);
        }
    }
    people.store(pkg);
}

/// Strip `w:rsid*` attributes and `w:rsid` elements everywhere under
/// `word/`, and the settings' `w:rsids` list.
fn remove_rsids(pkg: &mut PartFs) {
    let rsids = W::name("rsids");
    for name in word_parts(pkg) {
        if !pkg.part_string(&name).is_some_and(|x| x.contains("rsid")) {
            continue;
        }
        let Some(mut part) = Part::load(pkg, &name) else {
            continue;
        };
        for list in part.dom.descendants(part.root, Some(&rsids)) {
            part.dom.remove(list);
        }
        remove_all_rsids(&mut part.dom, part.root);
        part.store(pkg);
    }
}

/// Remove the elements named `names` that are children of `part`'s root.
fn remove_children(part: &mut Part, names: &[XName]) -> bool {
    let mut changed = false;
    for name in names {
        for node in part.dom.elements(part.root, Some(name)) {
            part.dom.remove(node);
            changed = true;
        }
    }
    changed
}

/// Drop the people and dates of the core and extended properties, and the
/// custom properties part.
fn scrub_properties(pkg: &mut PartFs) {
    if let Some(mut core) = Part::load(pkg, CORE) {
        let names = [
            XName::get("creator", DC),
            XName::get("lastModifiedBy", CP),
            XName::get("revision", CP),
            XName::get("lastPrinted", CP),
            XName::get("created", DCTERMS),
            XName::get("modified", DCTERMS),
        ];
        if remove_children(&mut core, &names) {
            core.store(pkg);
        }
    }
    if let Some(mut app) = Part::load(pkg, APP) {
        let names = [
            XName::get("Manager", EXTENDED),
            XName::get("Company", EXTENDED),
        ];
        if remove_children(&mut app, &names) {
            app.store(pkg);
        }
    }
    if pkg.part_bytes(CUSTOM).is_some() {
        pkg.remove_part(CUSTOM);
        pkg.remove_package_relationships_by_type(CUSTOM_REL);
        pkg.remove_content_type_override(&format!("/{CUSTOM}"));
    }
}

/// The parts of `docx` where `needle` still occurs, sorted: in a text node,
/// an attribute value that can hold text, an XML comment, the joined run
/// text of a paragraph (a text split across runs), or the raw bytes of a
/// part that is not XML (UTF-8 or UTF-16LE). An empty needle occurs nowhere.
/// An unreadable archive or entry is a finding: an incomplete scan cannot
/// certify a redaction. An encoding this scanner does not certify is also
/// a finding here; [`leak_scan`] reports that case as
/// [`LeakScan::Incomplete`] instead of a part where the text occurs.
///
/// The scan is bounded like the package constructor (#645): a package past
/// the admission budget, or an entry that inflates past its per-part or
/// package cap, is reported as a finding rather than skipped — `edit`'s
/// redaction check turns every finding into a refusal, so a package that
/// cannot be scanned fails closed.
///
/// The check fails closed: a short needle can also match an unrelated
/// attribute value. Attributes that only ever hold numbers (sizes, ids,
/// positions) are skipped when their value is a plain number.
pub fn leaks(docx: &[u8], needle: &str) -> Vec<String> {
    leaks_within(docx, needle, crate::admission::InputLimits::compare())
}

/// [`leaks`] plus a completeness receipt.
///
/// [`LeakScan::Complete`] means every part was read in a representation
/// this scanner certifies (XML as UTF-8 or UTF-16LE text, anything else as
/// raw UTF-8 or UTF-16LE). An empty finding list then means the needle does not
/// occur. [`LeakScan::Incomplete`] means a part uses an encoding this
/// scanner does not certify, which is not the same as the needle being
/// absent. The reason names the encoding, never the needle.
pub fn leak_scan(docx: &[u8], needle: &str) -> LeakScan {
    leak_scan_within(docx, needle, crate::admission::InputLimits::compare())
}

/// What [`leak_scan`] was able to certify.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LeakScan {
    /// Parts where `needle` occurs under a certified representation.
    Complete(Vec<String>),
    /// `part` is not in a representation this scanner can certify.
    Incomplete {
        /// Archive name of the part, with control characters escaped.
        part: String,
        /// Encoding the scan does not certify. This text does not contain the needle.
        reason: &'static str,
    },
}

impl LeakScan {
    fn findings_fail_closed(self) -> Vec<String> {
        match self {
            Self::Complete(found) => found,
            Self::Incomplete { part, reason } => vec![format!("{part} ({reason})")],
        }
    }
}

/// [`leaks`] under an explicit budget, so the fail-closed paths are provable
/// with budgets small enough for a test.
pub(crate) fn leaks_within(
    docx: &[u8],
    needle: &str,
    limits: crate::admission::InputLimits,
) -> Vec<String> {
    leak_scan_within(docx, needle, limits).findings_fail_closed()
}

fn leak_scan_within(docx: &[u8], needle: &str, limits: crate::admission::InputLimits) -> LeakScan {
    let mut found = BTreeSet::new();
    if needle.is_empty() {
        return LeakScan::Complete(Vec::new());
    }
    if let Err(error) = crate::admission::preindex_budget(docx, limits) {
        return LeakScan::Complete(vec![format!("the package ({error})")]);
    }
    let mut zip = match crate::opc::open_archive(std::io::Cursor::new(docx)) {
        Ok(zip) => zip,
        Err(error) => {
            return LeakScan::Complete(vec![format!("the package (cannot read: {error})")]);
        }
    };
    let utf16: Vec<u8> = needle.encode_utf16().flat_map(u16::to_le_bytes).collect();
    let mut total = 0u64;
    for i in 0..zip.len() {
        let mut entry = match zip.by_index(i) {
            Ok(entry) => entry,
            Err(error) => {
                found.insert(format!("ZIP entry {i} (cannot read: {error})"));
                break;
            }
        };
        let name = match entry.name() {
            Ok(name) => name,
            Err(error) => {
                found.insert(format!("ZIP entry {i} (cannot read name: {error})"));
                break;
            }
        };
        // Findings echo the name: escape control characters so a
        // crafted name cannot write terminal sequences.
        let name = crate::admission::shown(&name).into_owned();
        if entry.size() > limits.max_part_bytes {
            let error = crate::admission::part_declared_over(&name, entry.size(), &limits);
            found.insert(format!("{name} ({error})"));
            break;
        }
        let cap = limits
            .max_part_bytes
            .min(limits.max_uncompressed_bytes.saturating_sub(total));
        let mut bytes = Vec::new();
        let read = match (&mut entry)
            .take(cap.saturating_add(1))
            .read_to_end(&mut bytes)
        {
            Ok(read) => read as u64,
            Err(error) => {
                found.insert(format!("{name} (cannot read: {error})"));
                break;
            }
        };
        if let Err(error) = crate::admission::tally_inflated(&mut total, read, &name, cap, &limits)
        {
            found.insert(format!("{name} ({error})"));
            break;
        }
        if let Some(reason) = uncertified_encoding(&bytes) {
            return LeakScan::Incomplete { part: name, reason };
        }
        let xml = name.ends_with(".xml") || name.ends_with(".rels");
        let hit = if xml {
            xml_holds(&xml_text(&bytes), needle)
        } else {
            contains(&bytes, needle.as_bytes()) || contains(&bytes, &utf16)
        };
        if hit {
            found.insert(name);
        }
    }
    LeakScan::Complete(found.into_iter().collect())
}

/// An XML part as text: UTF-16LE when it opens with that BOM or with a
/// UTF-16LE `<` (SharePoint writes customXml items so), UTF-8 otherwise.
fn xml_text(bytes: &[u8]) -> std::borrow::Cow<'_, str> {
    let utf16 = bytes
        .strip_prefix(&[0xFF, 0xFE])
        .or_else(|| bytes.starts_with(b"<\0").then_some(bytes));
    match utf16 {
        Some(body) => std::borrow::Cow::Owned(
            char::decode_utf16(body.chunks(2).map(|pair| {
                u16::from_le_bytes([*pair.first().unwrap_or(&0), *pair.get(1).unwrap_or(&0)])
            }))
            .map(|unit| unit.unwrap_or(char::REPLACEMENT_CHARACTER))
            .collect(),
        ),
        None => String::from_utf8_lossy(bytes),
    }
}

/// BOM of an encoding this scanner does not read. UTF-8 and UTF-16LE,
/// with or without a BOM, stay certified: the XML path reads UTF-8 text
/// and every other part is searched as raw UTF-8 and UTF-16LE bytes.
fn uncertified_encoding(bytes: &[u8]) -> Option<&'static str> {
    if bytes.starts_with(&[0x00, 0x00, 0xFE, 0xFF]) {
        return Some(
            "UTF-32BE is not a certified encoding; this scan reads UTF-8 and UTF-16LE only",
        );
    }
    if bytes.starts_with(&[0xFF, 0xFE, 0x00, 0x00]) {
        return Some(
            "UTF-32LE is not a certified encoding; this scan reads UTF-8 and UTF-16LE only",
        );
    }
    if bytes.starts_with(&[0xFE, 0xFF]) {
        return Some(
            "UTF-16BE is not a certified encoding; this scan reads UTF-8 and UTF-16LE only",
        );
    }
    None
}

fn contains(hay: &[u8], needle: &[u8]) -> bool {
    !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}

/// Attributes that only ever hold a number or a hex id.
const NUMERIC_ATTRIBUTES: &[&str] = &[
    "id",
    "paraId",
    "textId",
    "durableId",
    "w",
    "h",
    "top",
    "bottom",
    "left",
    "right",
    "start",
    "end",
    "header",
    "footer",
    "gutter",
    "before",
    "after",
    "line",
    "firstLine",
    "hanging",
    "pos",
    "x",
    "y",
    "cx",
    "cy",
    "sz",
    "space",
    "num",
    "numId",
    "ilvl",
    "abstractNumId",
    "colFirst",
    "colLast",
    "percent",
];

fn is_number(value: &str) -> bool {
    let digits = value.strip_prefix('-').unwrap_or(value);
    !digits.is_empty() && digits.chars().all(|c| c.is_ascii_hexdigit())
}

fn xml_holds(xml: &str, needle: &str) -> bool {
    let mut dom = Dom::new();
    let doc = dom.parse_xdocument(xml);
    let Some(root) = dom.root(doc) else {
        // Not XML after all: read it as bytes.
        return xml.contains(needle);
    };
    for node in dom.descendant_nodes(doc) {
        if dom.is_text(node) || dom.is_comment(node) {
            if dom.text_value(node).is_some_and(|v| v.contains(needle)) {
                return true;
            }
        } else if dom.is_pi(node) {
            if dom.pi_data(node).is_some_and(|v| v.contains(needle)) {
                return true;
            }
        } else if dom.is_element(node) {
            for i in 0..dom.attr_count(node) {
                let (name, value) = dom.attr_at(node, i);
                if !value.contains(needle) || dom.is_namespace_declaration(name) {
                    continue;
                }
                if NUMERIC_ATTRIBUTES.contains(&name.local_name()) && is_number(value) {
                    continue;
                }
                return true;
            }
        }
    }
    // A text split across runs shows only in the paragraph's joined text.
    let texts = [W::t(), W::del_text(), W::instr_text()];
    for p in dom.descendants_and_self(root, Some(&W::p())) {
        let joined: String = dom
            .descendants(p, None)
            .into_iter()
            .filter(|&n| texts.iter().any(|t| dom.name_is(n, t)))
            .map(|n| dom.value(n))
            .collect();
        if joined.contains(needle) {
            return true;
        }
    }
    false
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
    use super::*;

    fn finding(code: &str, part: &str, path: &str) -> crate::validate::Finding {
        crate::validate::Finding {
            code: code.into(),
            set: "word".into(),
            severity: "error".into(),
            part: part.into(),
            location: path.into(),
            r#ref: crate::ids::short_paragraph(path),
            message: String::new(),
            word_fatal: true,
            repairable: false,
        }
    }

    #[test]
    fn introduced_counts_findings_by_code_and_part_not_path() {
        let had = [finding("A", "word/document.xml", "w:body[0]/w:p[3]")];
        // The same finding at a shifted path is not new.
        let moved = [finding("A", "word/document.xml", "w:body[0]/w:p[1]")];
        assert!(introduced(&had, &moved).is_empty());
        // A second one of the code in the part is.
        let twice = [moved[0].clone(), finding("A", "word/document.xml", "x")];
        assert_eq!(introduced(&had, &twice), ["A in word/document.xml"]);
        // So is the code in another part, or another code.
        let other = [
            finding("A", "word/comments.xml", ""),
            finding("B", "word/document.xml", ""),
        ];
        assert_eq!(
            introduced(&had, &other),
            ["A in word/comments.xml", "B in word/document.xml"]
        );
        // Fewer findings is fine.
        assert!(introduced(&had, &[]).is_empty());
    }

    #[test]
    fn initials_take_the_first_letter_of_each_word() {
        assert_eq!(initials("Outside Counsel"), "OC");
        assert_eq!(initials("reviewer"), "R");
    }

    #[test]
    fn numbers_and_hex_ids_are_numbers() {
        assert!(is_number("1440") && is_number("-720") && is_number("00AB12CD"));
        assert!(!is_number("") && !is_number("12 345") && !is_number("Jane"));
    }

    #[test]
    fn a_needle_in_a_numeric_attribute_is_no_leak_but_in_a_text_attribute_it_is() {
        let w = W::URI;
        let size = format!(r#"<w:document xmlns:w="{w}"><w:pgSz w:w="12240"/></w:document>"#);
        assert!(!xml_holds(&size, "1224"));
        let alt = format!(r#"<w:document xmlns:w="{w}"><w:x w:val="12240"/></w:document>"#);
        assert!(xml_holds(&alt, "1224"));
    }

    #[test]
    fn element_names_are_no_leak() {
        let w = W::URI;
        let xml = format!(r#"<w:document xmlns:w="{w}"><w:body/></w:document>"#);
        assert!(!xml_holds(&xml, "body"));
        assert!(xml_holds(&format!("{xml}<!-- body -->"), "body"));
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod public_memory_leak_boundary_tests {
    use super::*;

    fn package(body: &str) -> PartFs {
        let mut pkg = PartFs::open(include_bytes!(
            "../../../tests/fixtures/redline/original.docx"
        ))
        .unwrap();
        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());
        pkg
    }
    fn snapshot(pkg: &PartFs) -> Vec<(String, Vec<u8>)> {
        let mut parts = pkg.parts();
        parts.sort();
        parts
            .into_iter()
            .map(|name| {
                let bytes = pkg.part_bytes(&name).unwrap().to_vec();
                (name, bytes)
            })
            .collect()
    }

    #[test]
    fn public_leaks_reports_exact_xml_and_binary_part_owners_without_mutating_sources() {
        for secret in ["PrivateReviewer", "PendingReviewer"] {
            let mut pkg = package("<w:p><w:r><w:t>Independent body payload</w:t></w:r></w:p>");
            pkg.set_part(
                "customXml/comment.xml",
                format!("<metadata><!-- {secret} --></metadata>").into_bytes(),
            );
            pkg.set_part(
                "customXml/pi.xml",
                format!("<?privacy {secret}?><metadata/>").into_bytes(),
            );
            pkg.set_part(
                "customXml/attribute.xml",
                format!("<metadata id='{secret}'/>").into_bytes(),
            );
            pkg.set_part(
                "customXml/namespace.xml",
                format!("<metadata xmlns:private='urn:{secret}'/>").into_bytes(),
            );
            pkg.set_part("customXml/utf8.bin", secret.as_bytes().to_vec());
            pkg.set_part(
                "customXml/utf16.bin",
                secret.encode_utf16().flat_map(u16::to_le_bytes).collect(),
            );
            pkg.set_part(
                "customXml/clean.bin",
                b"Independent binary payload".to_vec(),
            );
            for part in [
                "/customXml/utf8.bin",
                "/customXml/utf16.bin",
                "/customXml/clean.bin",
            ] {
                pkg.add_content_type_override(part, "application/octet-stream");
            }
            let original = snapshot(&pkg);
            let bytes = pkg.to_zip().unwrap();
            let expected = vec![
                "customXml/attribute.xml",
                "customXml/comment.xml",
                "customXml/pi.xml",
                "customXml/utf16.bin",
                "customXml/utf8.bin",
            ];
            assert_eq!(leaks(&bytes, secret), expected);
            assert_eq!(leaks(&bytes, secret), expected);
            assert!(leaks(&bytes, "").is_empty());
            assert!(leaks(&bytes, "absent reviewer").is_empty());
            assert_eq!(snapshot(&PartFs::open(&bytes).unwrap()), original);
        }
    }
    #[test]
    fn decoded_entities_and_split_word_runs_are_secrets_but_numeric_ids_are_not() {
        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>";
        let mut pkg = package(body);
        pkg.set_part(
            "customXml/encoded.xml",
            b"<metadata owner='Jane &amp; Doe'>independent</metadata>".to_vec(),
        );
        let original = snapshot(&pkg);
        let bytes = pkg.to_zip().unwrap();
        assert_eq!(
            leaks(&bytes, "Jane Doe & Associates"),
            ["word/document.xml"]
        );
        assert_eq!(leaks(&bytes, "Jane & Doe"), ["customXml/encoded.xml"]);
        assert!(leaks(&bytes, "1234").is_empty());
        assert!(leaks(&bytes, "spacing").is_empty());
        assert_eq!(snapshot(&PartFs::open(&bytes).unwrap()), original);
    }
    #[test]
    fn invalid_aliases_are_rejected_before_any_source_property_is_rewritten() {
        let pkg = package("<w:p><w:r><w:t>Owned source payload</w:t></w:r></w:p>");
        let original = snapshot(&pkg);
        let bytes = pkg.to_zip().unwrap();
        for alias in ["", "  ", "Reviewer\nname", "Reviewer\tname"] {
            let options = ScrubOptions {
                author_alias: Some(alias.into()),
                rsids: false,
                docprops: false,
                comments: false,
            };
            assert!(
                matches!(scrub(&bytes,&options),Err(ScrubError::Invalid(message)) if message=="author_alias must be a nonempty name without control characters")
            );
            assert_eq!(snapshot(&PartFs::open(&bytes).unwrap()), original);
        }
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod bounded_input_tests {
    use super::*;
    use crate::admission::{InputLimits, limit_test_support as fixture};

    fn refuses(limits: InputLimits, detail: &str) {
        let bytes = fixture::package();
        let text = leaks_within(&bytes, "absent needle", limits).join(", ");
        assert!(text.contains("INPUT_LIMIT"), "{text}");
        assert!(text.contains(detail), "{text}");
    }
    #[test]
    fn compressed_limit() {
        refuses(fixture::compressed(), "input is");
    }
    #[test]
    fn count_limit() {
        refuses(fixture::count(), "3 ZIP entries; the limit is 2");
    }
    #[test]
    fn part_limit() {
        refuses(fixture::part(), "a.bin");
    }
    #[test]
    fn aggregate_limit() {
        refuses(fixture::total(), "the package limit is 160");
    }
    #[test]
    fn unreadable_entry_is_a_finding() {
        let mut bytes = fixture::package();
        // Corrupt a central-directory CRC, leaving its payload and size intact.
        let cd = bytes.windows(4).position(|w| w == b"PK\x01\x02").unwrap();
        bytes[cd + 16] ^= 1;
        let findings = leaks_within(&bytes, "absent needle", fixture::limits());
        assert!(
            !findings.is_empty(),
            "an unreadable part cannot certify a redaction"
        );
    }
    #[test]
    fn exact_budget_control() {
        let bytes = fixture::package();
        assert!(leaks_within(&bytes, "absent needle", fixture::limits()).is_empty());
        assert_eq!(
            leaks_within(&bytes, "aaaa", fixture::limits()),
            ["word/media/a.bin"]
        );
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod leak_branch_tests {
    use super::*;

    #[test]
    fn only_utf8_and_utf16le_are_certified() {
        assert!(
            uncertified_encoding(&[0x00, 0x00, 0xFE, 0xFF])
                .unwrap()
                .starts_with("UTF-32BE")
        );
        assert!(
            uncertified_encoding(&[0xFF, 0xFE, 0x00, 0x00])
                .unwrap()
                .starts_with("UTF-32LE")
        );
        assert!(
            uncertified_encoding(&[0xFE, 0xFF, 0x00, 0x3C])
                .unwrap()
                .starts_with("UTF-16BE")
        );
        assert_eq!(uncertified_encoding(&[0xFF, 0xFE, 0x3C, 0x00]), None);
        assert_eq!(uncertified_encoding(b"<x/>"), None);
        assert!(!contains(b"abc", b""));
        assert!(contains(b"abc", b"bc"));
    }

    #[test]
    fn a_needle_is_found_wherever_xml_can_hold_it() {
        assert!(xml_holds("plain text Secret", "Secret"), "not XML");
        assert!(xml_holds("<r><!-- Secret --></r>", "Secret"), "comment");
        assert!(xml_holds("<r><?pi Secret?></r>", "Secret"), "instruction");
        assert!(xml_holds("<r a=\"Secret\"/>", "Secret"), "attribute");
        // A numeric attribute that happens to contain the needle is no leak.
        assert!(!xml_holds("<r id=\"1234\"/>", "23"));
        assert!(xml_holds("<r name=\"1234\"/>", "23"));
        assert!(
            !xml_holds("<r xmlns:s=\"urn:Secret\"/>", "Secret"),
            "declaration"
        );
    }
}