Skip to main content

jubarte_opc/opc/
mod.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5// Untrusted bytes reach this module: an out-of-range index or an integer overflow
6// is an abort in the Python and WASM consumers, so both are refused here
7// (test fixtures are exempt).
8#![cfg_attr(
9    not(test),
10    deny(clippy::indexing_slicing, clippy::arithmetic_side_effects)
11)]
12
13//! OPC (Open Packaging Conventions) layer — M1.5.
14//!
15//! Uses `oxml_opc::OpcPackage` for byte-level parts, content types and target
16//! resolution, with local relationship storage and metadata readers to retain
17//! the adapter's refusal, repair and canonical serialization contracts.
18//!
19//! oxml-opc keys parts/rels with a LEADING SLASH (`/word/document.xml`). This
20//! adapter accepts the docxodus / opc-partfs style (no leading slash,
21//! `word/document.xml`) and normalizes internally, so the rest of the crate is
22//! oblivious to the difference.
23
24use std::borrow::Cow;
25use std::collections::{HashMap, HashSet};
26use std::io::{Cursor, Read, Write};
27use std::ops::{Deref, DerefMut};
28use std::sync::Arc;
29
30use oxml_opc::{ContentTypes, OpcPackage};
31pub use oxml_opc::{OpcError, Relationship};
32
33/// Relationships with this crate's per-record refusal contract: oxml-opc skips
34/// elements outside the relationships namespace, while this crate also reads
35/// legacy unnamespaced records and refuses a record missing a required
36/// attribute. Direct parsing uses the same reader as [`PartFs::open`].
37#[derive(Clone, Debug, Default)]
38pub struct Relationships(oxml_opc::Relationships);
39
40impl Relationships {
41    /// An empty collection whose generated IDs start at `rId1`.
42    pub fn new() -> Self {
43        Self(oxml_opc::Relationships::new())
44    }
45
46    /// Read a relationships part with the package reader's refusal contract.
47    ///
48    /// # Errors
49    ///
50    /// Returns [`OpcError`] for malformed XML or an invalid relationship record.
51    pub fn from_xml(xml: &[u8]) -> Result<Self, OpcError> {
52        read_relationships(xml)
53    }
54}
55
56impl Deref for Relationships {
57    type Target = oxml_opc::Relationships;
58
59    fn deref(&self) -> &Self::Target {
60        &self.0
61    }
62}
63
64impl DerefMut for Relationships {
65    fn deref_mut(&mut self) -> &mut Self::Target {
66        &mut self.0
67    }
68}
69
70/// Input the engine refuses before or while reading it, as an `Err` the
71/// caller can handle rather than a panic, which would abort a WASM instance
72/// or the Python interpreter. `InvalidData` is std's kind for input that is
73/// well-formed but unacceptable; the typed `err` travels as the
74/// [`std::io::Error`] source, so `Display` carries its message and
75/// `io::Error::get_ref` lets a caller downcast it (for example to
76/// [`crate::admission::AdmissionError`] and read its stable code).
77#[doc(hidden)]
78pub fn refused<E>(err: E) -> OpcError
79where
80    E: std::error::Error + Send + Sync + 'static,
81{
82    OpcError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, err))
83}
84
85/// The message a text surface prints for an [`OpcError`].
86/// `DuplicatePartName` carries only the second entry's spelling, so its
87/// line is the admission refusal for the same package — `DUPLICATE_PART:`
88/// with both spellings — and any other error keeps its own text (#600).
89#[must_use]
90pub fn refusal_message(docx: &[u8], err: &OpcError) -> String {
91    if let OpcError::DuplicatePartName(_) = err
92        && let Ok(archive) = open_archive_unchecked(Cursor::new(docx))
93    {
94        return duplicate_parts(&mut Cursor::new(docx), archive.central_directory_start())
95            .into_iter()
96            .next()
97            .map(|(_, defect)| defect.refusal().to_string())
98            .unwrap_or_else(|| err.to_string());
99    }
100    err.to_string()
101}
102use zip::write::SimpleFileOptions;
103use zip::{CompressionMethod, ZipWriter};
104
105mod archive;
106mod zip32;
107// The ZIP archive probes the doc layer and the CLI reach through the
108// facade's opc re-export (debug, scrub); doc(hidden) keeps them out of
109// the documented API (V2).
110#[doc(hidden)]
111pub use archive::{
112    ZipDefect, ZipDefectKind, duplicate_parts, open_archive, open_archive_unchecked,
113    open_archive_within, zip_defects,
114};
115pub use zip32::Zip32Limit;
116#[doc(hidden)]
117pub use zip32::zip32_plan;
118
119/// Exactly one leading slash: callers build `/{part}` from names that may
120/// already be absolute, and a `//word/…` part name is invalid OPC.
121/// Keeps one of each relationship `rels` repeats identically (same Id,
122/// type, target and mode), returning the repaired Ids; refuses two
123/// different relationships under one Id. Word reads neither as valid, and
124/// only the first is a repair that cannot guess wrong.
125fn drop_repeated_relationships(rels: &mut Relationships) -> Result<Vec<String>, OpcError> {
126    let mut seen: HashMap<&str, &Relationship> = HashMap::new();
127    let mut repaired: Vec<String> = Vec::new();
128    let mut keep = Vec::with_capacity(rels.items.len());
129    for item in &rels.items {
130        match seen.get(item.id.as_str()) {
131            None => {
132                seen.insert(&item.id, item);
133                keep.push(true);
134            }
135            Some(first) => {
136                if first.rel_type != item.rel_type
137                    || first.target != item.target
138                    || first.target_mode != item.target_mode
139                {
140                    return Err(OpcError::InvalidRelationship);
141                }
142                if !repaired.contains(&item.id) {
143                    repaired.push(item.id.clone());
144                }
145                keep.push(false);
146            }
147        }
148    }
149    let mut keep = keep.into_iter();
150    rels.items.retain(|_| keep.next().unwrap_or(true));
151    Ok(repaired)
152}
153
154fn norm(name: &str) -> String {
155    format!("/{}", name.trim_start_matches('/'))
156}
157
158/// The OPC identity of a part or relationship-owner name: resolved like a
159/// relationship target (leading slashes, `.`/`..` segments) and compared
160/// under ASCII case (ECMA-376 Part 2 §6.2.2.3 M1.12 — `word/Document.xml`
161/// IS `word/document.xml`, which is how Word opens probes p3–p5 of
162/// ZIP-15/#600). The `part_index`/`rels_index` maps keep one stored
163/// spelling per identity, so lookups stay O(1) without a scan.
164fn identity(name: &str) -> String {
165    // `resolve_rel_target` changes a name only to strip its leading '/'
166    // or to resolve `.`, `..` and empty segments: a name with none of
167    // those IS the resolved name, so the common lookup allocates once
168    // for the lowercasing instead of twice (#600 lookup cost).
169    let needs_resolve = name.starts_with('/')
170        || name
171            .split('/')
172            .any(|segment| segment.is_empty() || segment == "." || segment == "..");
173    if needs_resolve {
174        let mut resolved = resolve_rel_target("", name);
175        resolved.make_ascii_lowercase();
176        resolved
177    } else {
178        name.to_ascii_lowercase()
179    }
180}
181
182/// The relationship `Target` value that reaches `target_part` from
183/// `source_part`: relative to the source's folder when the target sits
184/// under it, absolute (`/media/image.bin`) otherwise. Stripping `word/`
185/// blindly pointed a root-level `media/image.bin` at the non-existent
186/// `word/media/image.bin` and Word refused the package.
187pub fn relative_rel_target(source_part: &str, target_part: &str) -> String {
188    let source = source_part.trim_start_matches('/');
189    let target = target_part.trim_start_matches('/');
190    let dir = source.rsplit_once('/').map_or("", |(d, _)| d);
191    match target.strip_prefix(dir).and_then(|t| t.strip_prefix('/')) {
192        Some(rel) if !dir.is_empty() => rel.to_string(),
193        _ => format!("/{target}"),
194    }
195}
196
197/// Refuse metadata that is not one authoritative document (#643).
198///
199/// `[Content_Types].xml` and `.rels` are interpreted only after this
200/// check. A second root is not folded in. A root whose default namespace
201/// is present and is not `namespace` is not rewritten into the OPC
202/// namespace. An absent default namespace stays the legacy local-name
203/// read, and a record-local `xmlns=""` is still dropped later so a missing
204/// attribute fails closed rather than disappearing.
205pub(crate) fn metadata_document(xml: &[u8], root: &str, namespace: &str) -> Result<(), String> {
206    use quick_xml::events::Event;
207    // Read the text admission reads (`admission::part_text`: UTF-16 by its
208    // BOM, otherwise lossy UTF-8). A raw-byte reader stops at the first
209    // encoding error and let a foreign namespace through (#2080 review).
210    let text = crate::admission::part_text(xml);
211    let mut reader = quick_xml::Reader::from_reader(text.as_bytes());
212    reader.config_mut().check_end_names = true;
213    let mut depth = 0usize;
214    let mut roots = 0usize;
215    loop {
216        match reader.read_event() {
217            Ok(Event::Start(ref tag)) => {
218                if depth == 0 {
219                    note_metadata_root(tag, &mut roots, root, namespace)?;
220                }
221                depth = depth.saturating_add(1);
222            }
223            Ok(Event::Empty(ref tag)) => {
224                if depth == 0 {
225                    note_metadata_root(tag, &mut roots, root, namespace)?;
226                }
227            }
228            Ok(Event::End(_)) => {
229                depth = depth
230                    .checked_sub(1)
231                    .ok_or_else(|| "unmatched XML end tag".to_string())?;
232            }
233            Ok(Event::DocType(_)) => {
234                return Err("DTD declarations are unsupported".to_string());
235            }
236            Ok(Event::Eof) => return Ok(()),
237            Ok(_) => {}
238            // A syntax error stays the 0.41 record reader's `OpcError::Xml`.
239            // This gate only refuses a document that reader would accept.
240            Err(_) => return Ok(()),
241        }
242    }
243}
244
245fn note_metadata_root(
246    tag: &quick_xml::events::BytesStart<'_>,
247    roots: &mut usize,
248    root: &str,
249    namespace: &str,
250) -> Result<(), String> {
251    *roots = roots.saturating_add(1);
252    if *roots > 1 {
253        return Err("multiple XML roots".to_string());
254    }
255    let local = tag.local_name();
256    if local.as_ref() != root {
257        return Err(format!("metadata root {local:?} is not {root}"));
258    }
259    // A prefixed root names its namespace through `xmlns:prefix`; with no
260    // default namespace its unprefixed records would otherwise take the
261    // legacy local-name read and be relabelled (#2080 review).
262    let prefixed = tag
263        .name()
264        .prefix()
265        .map(|prefix| format!("xmlns:{}", prefix.as_ref()));
266    let mut prefix_bound = prefixed.is_none();
267    for attr in tag.attributes().with_checks(false) {
268        let attr = attr.map_err(|err| err.to_string())?;
269        if prefixed.as_deref() == Some(attr.key.as_ref()) {
270            let value = attr
271                .normalized_value(quick_xml::XmlVersion::Implicit1_0)
272                .map_err(|err| err.to_string())?;
273            if value.as_ref() != namespace {
274                return Err(format!(
275                    "metadata root namespace {value:?} is not {namespace}"
276                ));
277            }
278            prefix_bound = true;
279        }
280        if attr.key.as_ref() == "xmlns" {
281            let value = attr
282                .normalized_value(quick_xml::XmlVersion::Implicit1_0)
283                .map_err(|err| err.to_string())?;
284            if value.as_ref() != namespace {
285                return Err(format!(
286                    "metadata root namespace {value:?} is not {namespace}"
287                ));
288            }
289        }
290    }
291    if !prefix_bound {
292        return Err("metadata root prefix is not bound on the root".to_string());
293    }
294    Ok(())
295}
296
297fn metadata_refused(why: String) -> OpcError {
298    refused(std::io::Error::new(std::io::ErrorKind::InvalidData, why))
299}
300
301/// Select the same unprefixed metadata records as the legacy adapter, folding
302/// explicit closes, then let upstream decode and validate each record. Parsing
303/// records separately preserves identical-duplicate repair and last-wins content
304/// types before the newer whole-document parsers reject those producer shapes.
305/// A record's own default-namespace declaration is dropped: it would unbind
306/// the synthetic root's OPC namespace (`<Relationship xmlns=""/>`) and upstream
307/// would silently skip the record instead of validating it, where the legacy
308/// parser matched records by local name whatever namespaces declared.
309fn metadata_records(
310    xml: &[u8],
311    root: &str,
312    namespace: &str,
313    tags: &[&str],
314) -> Result<Vec<Vec<u8>>, OpcError> {
315    // quick-xml 0.41 is the version `OpcError::Xml`/`XmlAttr` carry (oxml-opc
316    // 0.14.2), so the scanner's errors convert into those variants directly;
317    // 0.42's error types do not, and wrapping them made every syntax error an
318    // I/O refusal.
319    use quick_xml_041::events::{BytesEnd, BytesStart, Event};
320    let fold = |name: &str, tag: quick_xml_041::events::BytesStart<'_>| {
321        let mut record = BytesStart::new(name);
322        for attr in tag.attributes().with_checks(false) {
323            let attr = attr?;
324            if attr.key.as_ref() != &b"xmlns"[..] {
325                record.push_attribute(attr);
326            }
327        }
328        let mut writer = quick_xml_041::Writer::new(Vec::new());
329        let mut start = BytesStart::new(root);
330        start.push_attribute(("xmlns", namespace));
331        writer.write_event(Event::Start(start))?;
332        writer.write_event(Event::Empty(record))?;
333        writer.write_event(Event::End(BytesEnd::new(root)))?;
334        Ok::<_, OpcError>(writer.into_inner())
335    };
336    let mut reader = quick_xml_041::Reader::from_reader(xml);
337    let mut buf = Vec::new();
338    let mut records = Vec::new();
339    // An explicit close (`<Relationship …></Relationship>`) is folded between
340    // events: a `Start` immediately followed by its matching `End`, with no
341    // other event between, is one `Empty` record. The reader still checks end
342    // names, so a mismatched close stays an XML error, and a `>` inside an
343    // attribute value (`Target="a></Relationship>b"`, legal unescaped) is
344    // never rewritten — a textual `></tag>` replacement did both.
345    let mut pending: Option<(&str, BytesStart<'static>)> = None;
346    loop {
347        let event = reader.read_event_into(&mut buf).map_err(OpcError::from)?;
348        if let Some((name, tag)) = pending.take()
349            && matches!(&event, Event::End(end) if end.name() == tag.name())
350        {
351            records.push(fold(name, tag)?);
352            continue;
353        }
354        let matched = |tag: &BytesStart<'_>| {
355            tags.iter()
356                .copied()
357                .find(|name| tag.name().as_ref() == name.as_bytes())
358        };
359        match event {
360            Event::Start(ref tag) => {
361                if let Some(name) = matched(tag) {
362                    pending = Some((name, tag.to_owned()));
363                }
364            }
365            Event::Empty(ref tag) => {
366                if let Some(name) = matched(tag) {
367                    records.push(fold(name, tag.to_owned())?);
368                }
369            }
370            Event::Eof => return Ok(records),
371            _ => {}
372        }
373    }
374}
375
376fn read_relationships(xml: &[u8]) -> Result<Relationships, OpcError> {
377    metadata_document(
378        xml,
379        "Relationships",
380        "http://schemas.openxmlformats.org/package/2006/relationships",
381    )
382    .map_err(metadata_refused)?;
383    let mut rels = Relationships::new();
384    let mut items = Vec::new();
385    for record in metadata_records(
386        xml,
387        "Relationships",
388        "http://schemas.openxmlformats.org/package/2006/relationships",
389        &["Relationship"],
390    )? {
391        for item in oxml_opc::Relationships::from_xml(&record)?.items {
392            items.push(item);
393        }
394    }
395    // Seed the private counter once: add_with_id removes existing IDs, so
396    // calling it for every record would turn a linear read into a quadratic one.
397    // A fresh collection also has no retained source XML: to_xml stays canonical.
398    if let Some((_, item)) = items
399        .iter()
400        .filter_map(|item| {
401            item.id
402                .strip_prefix("rId")
403                .and_then(|id| id.parse::<u32>().ok())
404                .map(|id| (id, item))
405        })
406        .max_by_key(|(id, _)| *id)
407    {
408        rels.add_with_id(&item.id, &item.rel_type, &item.target);
409    }
410    rels.items = items;
411    Ok(rels)
412}
413
414/// Whether `name` ends with `suffix`, ASCII case-blind (OPC compares part
415/// names so).
416#[doc(hidden)]
417pub fn ends_with_ignore_case(name: &str, suffix: &str) -> bool {
418    name.len()
419        .checked_sub(suffix.len())
420        .and_then(|at| name.get(at..))
421        .is_some_and(|end| end.eq_ignore_ascii_case(suffix))
422}
423
424/// Whether a content type names XML: `…+xml`, `application/xml` or
425/// `text/xml`, ASCII case-blind.
426#[doc(hidden)]
427pub fn is_xml_content_type(content_type: &str) -> bool {
428    ends_with_ignore_case(content_type, "+xml")
429        || content_type.eq_ignore_ascii_case("application/xml")
430        || content_type.eq_ignore_ascii_case("text/xml")
431}
432
433/// Transitional's and Strict's `customXml` relationship types.
434const CUSTOM_XML_RELATIONSHIPS: [&str; 2] = [
435    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
436    "http://purl.oclc.org/ooxml/officeDocument/relationships/customXml",
437];
438
439/// The custom XML data parts `rels` reach, each `(source part, its
440/// relationships)`, the package's own under `""`: the parts only
441/// `customXml` relationships reach, by their exact type. Such a part holds
442/// the application's own XML. A part another relationship reaches too (the
443/// main document, a header) is that part, whatever else points at it.
444#[doc(hidden)]
445pub fn custom_xml_data<'a>(
446    rels: impl IntoIterator<Item = (&'a str, &'a Relationships)>,
447) -> Vec<String> {
448    // By ASCII-lowercase name: OPC compares part names so.
449    let mut only_custom: HashMap<String, bool> = HashMap::new();
450    for (source, rels) in rels {
451        for r in rels
452            .items
453            .iter()
454            .filter(|r| r.target_mode.as_deref() != Some("External"))
455        {
456            let target = crate::xmllinq::parse::unescape_xml_text(&r.target);
457            let part = resolve_rel_target(source, &target).to_ascii_lowercase();
458            *only_custom.entry(part).or_insert(true) &=
459                CUSTOM_XML_RELATIONSHIPS.contains(&r.rel_type.as_str());
460        }
461    }
462    only_custom
463        .into_iter()
464        .filter_map(|(part, custom)| custom.then_some(part))
465        .collect()
466}
467
468/// For a reader that has not opened the package: whether the raw
469/// `[Content_Types].xml` `content_types` types part `name` as XML
470/// ([`is_xml_content_type`]). Unreadable content types type nothing.
471pub(crate) fn typed_as_xml(content_types: Option<&[u8]>) -> impl Fn(&str) -> bool + use<> {
472    let types = content_types.and_then(|xml| read_content_types(xml).ok());
473    move |name| {
474        types
475            .as_ref()
476            .and_then(|types| types.content_type_for(&norm(name)))
477            .is_some_and(is_xml_content_type)
478    }
479}
480
481fn read_content_types(xml: &[u8]) -> Result<ContentTypes, OpcError> {
482    read_content_types_counted(xml).map(|(types, _)| types)
483}
484
485/// [`read_content_types`] and how many `Default`/`Override` records the
486/// XML held. Fewer model entries than records means the model collapsed a
487/// repeated one (last wins), so the loaded bytes no longer match it.
488fn read_content_types_counted(xml: &[u8]) -> Result<(ContentTypes, usize), OpcError> {
489    metadata_document(
490        xml,
491        "Types",
492        "http://schemas.openxmlformats.org/package/2006/content-types",
493    )
494    .map_err(metadata_refused)?;
495    let mut types = ContentTypes {
496        defaults: HashMap::new(),
497        overrides: HashMap::new(),
498    };
499    let records = metadata_records(
500        xml,
501        "Types",
502        "http://schemas.openxmlformats.org/package/2006/content-types",
503        &["Default", "Override"],
504    )?;
505    let count = records.len();
506    for record in records {
507        let parsed = ContentTypes::from_xml(&record)?;
508        types.defaults.extend(parsed.defaults);
509        types.overrides.extend(parsed.overrides);
510    }
511    Ok((types, count))
512}
513
514/// The loaded `[Content_Types].xml` to write back while the model is
515/// unchanged, or `None` when the model collapsed one of its records.
516fn content_types_kept(xml: Vec<u8>, types: &ContentTypes, records: usize) -> Option<Vec<u8>> {
517    (types.defaults.len().checked_add(types.overrides.len()) == Some(records)).then_some(xml)
518}
519
520/// Populate parts and local relationships without invoking upstream's whole-package
521/// normalization and duplicate-refusal policies ahead of the adapter's repairs.
522///
523/// Bounded like [`crate::admission::admit`] (#645): each entry inflates
524/// through a reader capped at the smaller of `limits.max_part_bytes` and the
525/// package budget left, with a checked cumulative total, because the sizes
526/// the central directory declares are not trusted and no caller can be
527/// relied on to have admitted the bytes first. An entry that declares or
528/// inflates past its cap is refused with the admission `INPUT_LIMIT`
529/// wording.
530fn read_package(bytes: &[u8], limits: crate::admission::InputLimits) -> Result<PartFs, OpcError> {
531    crate::admission::preindex_budget(bytes, limits).map_err(refused)?;
532    // Duplicate part identities are refused below as
533    // `DuplicatePartName`, the variant callers match on (#600); every
534    // other structural defect refuses in the shared open. The raw walk
535    // of the central directory must catch them: zip 9's index collapses
536    // a byte-equal duplicate before the decode loop can see both
537    // records, and its decoded names agree with the per-entry decode on
538    // every shape (bit 11 / CP437 / 0x7075).
539    let mut archive = open_archive_within(Cursor::new(bytes), false)?;
540    if let Some((second, _)) =
541        duplicate_parts(&mut Cursor::new(bytes), archive.central_directory_start())
542            .into_iter()
543            .next()
544    {
545        return Err(OpcError::DuplicatePartName(second));
546    }
547    let mut parts = HashMap::new();
548    let mut source_order = HashMap::new();
549    let mut total = 0u64;
550    let mut elements = 0u64;
551    for index in 0..archive.len() {
552        let mut entry = archive.by_index(index)?;
553        // zip 8's name decode (bit 11/CP437, 0x7075 override): the same one
554        // `admit` applies, so both readers see one name per entry (#524).
555        let name = crate::admission::zip_entry_name(
556            entry.name_raw(),
557            entry.flags().as_u16(),
558            crate::admission::unicode_path_fields(entry.extra_data_fields().cloned()),
559        )?;
560        let directory = entry.is_dir();
561        if !directory {
562            source_order.insert(name.clone(), index);
563        }
564        if entry.size() > limits.max_part_bytes {
565            return Err(refused(crate::admission::part_declared_over(
566                &name,
567                entry.size(),
568                &limits,
569            )));
570        }
571        let cap = limits
572            .max_part_bytes
573            .min(limits.max_uncompressed_bytes.saturating_sub(total));
574        let mut data = Vec::new();
575        // A directory entry's payload is drained too: the CRC stream is the
576        // only check on bytes nobody else reads, and the inflated count
577        // still charges the same budgets (#644). A corrupt directory
578        // payload is INVALID_PACKAGE, as it is in `admit`.
579        let read = if directory {
580            std::io::copy(
581                &mut (&mut entry).take(cap.saturating_add(1)),
582                &mut std::io::sink(),
583            )
584            .map_err(|e| {
585                refused(crate::admission::AdmissionError {
586                    kind: crate::admission::AdmissionErrorKind::InvalidPackage,
587                    message: format!("{}: {e}", crate::admission::shown(&name)),
588                })
589            })?
590        } else {
591            u64::try_from(
592                (&mut entry)
593                    .take(cap.saturating_add(1))
594                    .read_to_end(&mut data)?,
595            )
596            .unwrap_or(u64::MAX)
597        };
598        crate::admission::tally_inflated(&mut total, read, &name, cap, &limits).map_err(refused)?;
599        if directory {
600            continue;
601        }
602        // Every command opens the package here, `read`'s tolerant view
603        // included, so the element budget and the DOCTYPE refusal hold
604        // before any part is parsed (#2014, #2015).
605        crate::admission::tally_xml_elements(&mut elements, &name, &data, &limits)
606            .map_err(refused)?;
607        let lower = name.to_ascii_lowercase();
608        if lower == "[content_types].xml" || lower.ends_with(".rels") {
609            check_opc_attributes(&data)?;
610        }
611        parts.insert(name, data);
612    }
613    let mut package = PartFs {
614        pkg: OpcPackage::new(),
615        package_rels: Relationships::new(),
616        part_rels: HashMap::new(),
617        source_order,
618        repaired_duplicate_ids: Vec::new(),
619        part_index: HashMap::new(),
620        rels_index: HashMap::new(),
621        content_types_original: None,
622        content_types_canonical: Vec::new(),
623        package_rels_original: None,
624        package_rels_canonical: Vec::new(),
625        part_rels_original: HashMap::new(),
626        part_rels_canonical: HashMap::new(),
627    };
628    // The reserved names match under ASCII case (M1.12): a lone
629    // `[content_types].xml` or `_RELS/.RELS` is the part (Word opens it,
630    // #600 probes p4/p5); `to_zip` writes the canonical spelling back.
631    let content_types = parts
632        .keys()
633        .find(|name| name.eq_ignore_ascii_case("[Content_Types].xml"))
634        .cloned()
635        .and_then(|name| parts.remove(&name))
636        .ok_or_else(|| OpcError::PartNotFound("[Content_Types].xml".to_string()))?;
637    let (types, records) = read_content_types_counted(&content_types)?;
638    package.pkg.content_types = types;
639    package.content_types_canonical = package.pkg.content_types.to_xml().unwrap_or_default();
640    package.content_types_original =
641        content_types_kept(content_types, &package.pkg.content_types, records);
642    if let Some(name) = parts
643        .keys()
644        .find(|name| name.eq_ignore_ascii_case("_rels/.rels"))
645        .cloned()
646    {
647        let data = parts.remove(&name).unwrap_or_default();
648        package.package_rels = read_relationships(&data)?;
649        package.package_rels_canonical = package.package_rels.to_xml().unwrap_or_default();
650        package.package_rels_original = Some(data);
651    }
652    for (name, data) in parts {
653        if name.to_ascii_lowercase().ends_with(".rels") {
654            let owner = rels_path_to_part_name(&name).unwrap_or_else(|| {
655                name.get(..name.len().saturating_sub(5))
656                    .unwrap_or(name.as_str())
657                    .to_string()
658            });
659            let key = norm(&owner);
660            package.rels_index.insert(identity(&key), key.clone());
661            let rels = read_relationships(&data)?;
662            package
663                .part_rels_canonical
664                .insert(key.clone(), rels.to_xml().unwrap_or_default());
665            package.part_rels_original.insert(key.clone(), data);
666            package.part_rels.insert(key, rels);
667        } else {
668            let key = norm(&name);
669            package.part_index.insert(identity(&key), key.clone());
670            package.pkg.parts.insert(key, Arc::new(data));
671        }
672    }
673    Ok(package)
674}
675
676fn denorm(name: &str) -> String {
677    name.trim_start_matches('/').to_string()
678}
679
680/// `.rels` file path (e.g. `word/_rels/document.xml.rels`). Mirrors the
681/// private `oxml_opc::package::part_name_to_rels_path`.
682fn part_name_to_rels_path(part_name: &str) -> String {
683    let name = part_name.strip_prefix('/').unwrap_or(part_name);
684    if let Some((dir, file)) = name.rsplit_once('/') {
685        format!("{dir}/_rels/{file}.rels")
686    } else {
687        format!("_rels/{name}.rels")
688    }
689}
690
691/// The part a `.rels` path belongs to (`word/_rels/header1.xml.rels` →
692/// `word/header1.xml`; `_rels/.rels` → the package, as `""`), or None when
693/// `name` is not a relationships path. Inverse of `part_name_to_rels_path`.
694/// The `_rels` segment and the `.rels` suffix match under ASCII case —
695/// `_RELS/.RELS` is the package's own relationships (Word opens it, ZIP-15
696/// probe p5) — while the owner's spelling keeps the entry's case.
697pub(crate) fn rels_path_to_part_name(name: &str) -> Option<String> {
698    let name = name.strip_prefix('/').unwrap_or(name);
699    let lower = name.to_ascii_lowercase();
700    let file = lower.strip_suffix(".rels")?;
701    let (dir, base) = file.rsplit_once('/')?;
702    let tail = name.len().checked_sub(5)?;
703    let base = name.get(tail.checked_sub(base.len())?..tail)?;
704    let owner_dir = if dir == "_rels" {
705        ""
706    } else {
707        dir.strip_suffix("/_rels")?
708    };
709    Some(if owner_dir.is_empty() {
710        base.to_string()
711    } else {
712        format!("{}/{base}", name.get(..owner_dir.len())?)
713    })
714}
715
716/// One zip entry `PartFs::to_zip` writes after the two package-level ones.
717enum ZipEntry<'a> {
718    Rels(Vec<u8>),
719    Part(&'a [u8]),
720}
721
722impl ZipEntry<'_> {
723    /// The uncompressed byte length of the entry's content.
724    fn len(&self) -> u64 {
725        match self {
726            // Serialized at plan time; a rels part never nears the boundary.
727            ZipEntry::Rels(xml) => xml.len() as u64,
728            ZipEntry::Part(data) => data.len() as u64,
729        }
730    }
731}
732
733/// Original metadata bytes when `now` is still the serialization captured
734/// at load. A changed model writes `now`.
735fn unchanged_xml(now: Vec<u8>, original: Option<&[u8]>, canonical: &[u8]) -> Vec<u8> {
736    match original {
737        Some(bytes) if now.as_slice() == canonical => bytes.to_vec(),
738        _ => now,
739    }
740}
741
742// Retain the OPC metadata budget independently of the parser upgrade that
743// fixed RUSTSEC-2026-0194/0195. Direct Relationships::from_xml callers use
744// patched quick-xml through oxml-opc 0.14.2; package admission also bounds the
745// attribute count. 256 matches quick-xml's default namespace declaration limit.
746fn check_opc_attributes(xml: &[u8]) -> Result<(), OpcError> {
747    let mut reader = quick_xml::Reader::from_reader(xml);
748    loop {
749        match reader.read_event().map_err(refused)? {
750            quick_xml::events::Event::Start(tag) | quick_xml::events::Event::Empty(tag) => {
751                for (index, attr) in tag.attributes().with_checks(false).enumerate() {
752                    if index >= 256 {
753                        return Err(refused(std::io::Error::new(
754                            std::io::ErrorKind::InvalidData,
755                            "OPC metadata element exceeds 256 attributes",
756                        )));
757                    }
758                    attr.map_err(refused)?;
759                }
760            }
761            quick_xml::events::Event::Eof => return Ok(()),
762            _ => {}
763        }
764    }
765}
766
767/// Thin adapter over `oxml_opc::OpcPackage`. Port-equivalent of `PartFS`.
768pub struct PartFs {
769    // Only parts and content types live upstream; its relationship maps stay empty.
770    pkg: OpcPackage,
771    package_rels: Relationships,
772    part_rels: HashMap<String, Relationships>,
773    /// Each source zip entry's position, so `to_zip` writes the package back
774    /// in the source's order rather than the hash maps' run-to-run order.
775    source_order: HashMap<String, usize>,
776    /// `(part, Id)` of each relationship the source repeated identically and
777    /// [`PartFs::open`] kept once (`""` is the package's own relationships).
778    repaired_duplicate_ids: Vec<(String, String)>,
779    /// `pkg.parts` by OPC identity (ASCII-lowercased resolved name): one
780    /// stored key per identity, so an alias resolves in O(1) (ZIP-15/#600).
781    part_index: HashMap<String, String>,
782    /// `part_rels` owners by identity, same contract as `part_index`.
783    rels_index: HashMap<String, String>,
784    /// Bytes loaded for metadata the parsed model does not store. A later
785    /// serialization that still matches the load-time form writes these
786    /// back; a model that changed is serialized from the model.
787    content_types_original: Option<Vec<u8>>,
788    content_types_canonical: Vec<u8>,
789    package_rels_original: Option<Vec<u8>>,
790    package_rels_canonical: Vec<u8>,
791    part_rels_original: HashMap<String, Vec<u8>>,
792    part_rels_canonical: HashMap<String, Vec<u8>>,
793}
794
795/// Canonical target resolution shared by package APIs and text story labels.
796#[doc(hidden)]
797pub fn resolve_rel_target(source_part: &str, rel_target: &str) -> String {
798    // The upstream resolver already returns the normalized absolute
799    // name (`.`/`..`/empty segments collapsed under a leading '/');
800    // PartFs stores the no-leading-slash form.
801    OpcPackage::resolve_rel_target(&norm(source_part), rel_target)
802        .trim_start_matches('/')
803        .to_string()
804}
805
806impl PartFs {
807    /// Open a `.docx`/OPC package from raw bytes: read its parts,
808    /// relationships and `[Content_Types].xml`, normalize their part
809    /// names to the no-leading-slash form, fold any explicit `<…></…>`
810    /// closes of empty elements (`<Relationship …></Relationship>` and
811    /// its `[Content_Types]` siblings) into self-closing ones, decode
812    /// XML entities that the underlying parser left raw, and keep one
813    /// copy of any identical repeated relationship.
814    ///
815    /// The package is read under [`crate::admission::InputLimits::compare`]
816    /// (#645): an input past the compressed-size or entry-count budget is
817    /// refused before the archive is indexed, and a part past the per-part
818    /// or package budget while it inflates, with the admission `INPUT_LIMIT`
819    /// wording. Callers that admit under their own budget open through
820    /// `open_within` so their limits keep governing.
821    ///
822    /// # Errors
823    ///
824    /// [`OpcError`] for an unreadable zip, a package past the input budget
825    /// (an [`crate::admission::AdmissionError`] with code `INPUT_LIMIT` as
826    /// the [`std::io::Error`] source), an OPC metadata element exceeding
827    /// 256 attributes, two relationships under the same `Id` that differ in
828    /// any attribute, or two entries whose decoded part names are equal
829    /// byte-for-byte or under ASCII case
830    /// ([`OpcError::DuplicatePartName`], naming the second entry's
831    /// spelling; text surfaces print the admission `DUPLICATE_PART`
832    /// detail through [`refusal_message`]).
833    pub fn open(bytes: &[u8]) -> Result<Self, OpcError> {
834        Self::open_within(bytes, crate::admission::InputLimits::compare())
835    }
836
837    /// [`PartFs::open`] under an explicit budget: the entry points that
838    /// admit an input under their own limits (the comparer's settings)
839    /// open it under the same budget here, so a looser caller budget still
840    /// governs and a tighter one has already refused the package.
841    #[doc(hidden)]
842    pub fn open_within(
843        bytes: &[u8],
844        limits: crate::admission::InputLimits,
845    ) -> Result<Self, OpcError> {
846        let mut fs = read_package(bytes, limits)?;
847        let mut repaired_duplicate_ids: Vec<(String, String)> =
848            drop_repeated_relationships(&mut fs.package_rels)?
849                .into_iter()
850                .map(|id| (String::new(), id))
851                .collect();
852        let mut owners: Vec<(&String, &mut Relationships)> = fs.part_rels.iter_mut().collect();
853        owners.sort_by(|a, b| a.0.cmp(b.0));
854        for (owner, rels) in owners {
855            let part = owner.trim_start_matches('/').to_string();
856            repaired_duplicate_ids.extend(
857                drop_repeated_relationships(rels)?
858                    .into_iter()
859                    .map(|id| (part.clone(), id)),
860            );
861        }
862        fs.repaired_duplicate_ids = repaired_duplicate_ids;
863        Ok(fs)
864    }
865
866    /// `(part, Id)` of each relationship the source repeated identically,
867    /// kept once on open (`""`: the package's own relationships). Word
868    /// refuses such a package; `validate` reports these as `DUPLICATE_RID`.
869    #[must_use]
870    pub fn repaired_duplicate_ids(&self) -> &[(String, String)] {
871        &self.repaired_duplicate_ids
872    }
873
874    /// `PartFS.partBytes(name)` — raw bytes of a part. The lookup resolves
875    /// under OPC identity: `word/document.xml` finds a part stored as
876    /// `word/Document.xml` (#600).
877    pub fn part_bytes(&self, name: &str) -> Option<&[u8]> {
878        self.pkg
879            .parts
880            .get(self.part_index.get(&identity(name))?)
881            .map(|data| data.as_slice())
882    }
883
884    /// Read a part as a UTF-8 string.
885    pub fn part_string(&self, name: &str) -> Option<String> {
886        self.part_bytes(name)
887            .map(|b| String::from_utf8_lossy(b).into_owned())
888    }
889
890    /// `PartFS.setPart(name, data)` — replace or add a part.
891    ///
892    /// A `…/_rels/<part>.rels` name replaces that part's relationships: the
893    /// package keeps relationships parsed, and `to_zip` writes them next to the
894    /// raw parts, so a raw `.rels` copy would be a second zip entry of the same
895    /// name (the whole package fails) and invisible to `read_rels_for`.
896    /// Unparseable relationship XML is kept raw, as before.
897    /// `PartFS.setPart(name, data)` — replace or add a part. A name that
898    /// is a case alias of a stored part replaces it and keeps the stored
899    /// spelling (there is one part per identity, #600).
900    ///
901    /// A `…/_rels/<part>.rels` name (matched under ASCII case) replaces
902    /// that part's relationships: the package keeps relationships parsed,
903    /// and `to_zip` writes them next to the raw parts, so a raw `.rels`
904    /// copy would be a second zip entry of the same name (the whole
905    /// package fails) and invisible to `read_rels_for`. Unparseable
906    /// relationship XML is kept raw, as before; `to_zip` then refuses the
907    /// collision rather than write a duplicate name. A
908    /// `[Content_Types].xml` name likewise replaces the parsed content
909    /// types when it parses.
910    pub fn set_part(&mut self, name: &str, data: Vec<u8>) {
911        if let Some(owner) = rels_path_to_part_name(name)
912            && check_opc_attributes(&data).is_ok()
913            && let Ok(rels) = read_relationships(&data)
914        {
915            let canonical = rels.to_xml().unwrap_or_default();
916            if owner.is_empty() {
917                self.package_rels = rels;
918                self.package_rels_canonical = canonical;
919                self.package_rels_original = Some(data.clone());
920            } else {
921                let key = self
922                    .rels_index
923                    .get(&identity(&owner))
924                    .cloned()
925                    .unwrap_or_else(|| norm(&owner));
926                self.rels_index.insert(identity(&key), key.clone());
927                self.part_rels_canonical.insert(key.clone(), canonical);
928                self.part_rels_original.insert(key.clone(), data.clone());
929                self.part_rels.insert(key, rels);
930            }
931            // A raw part of the same .rels identity is superseded: `to_zip`
932            // writes the parsed copy, and two entries of one name fail.
933            if let Some(key) = self.part_index.remove(&identity(name)) {
934                self.pkg.parts.remove(&key);
935            }
936            return;
937        }
938        if name
939            .trim_start_matches('/')
940            .eq_ignore_ascii_case("[Content_Types].xml")
941            && check_opc_attributes(&data).is_ok()
942            && let Ok((types, records)) = read_content_types_counted(&data)
943        {
944            self.pkg.content_types = types;
945            self.content_types_canonical = self.pkg.content_types.to_xml().unwrap_or_default();
946            self.content_types_original =
947                content_types_kept(data.clone(), &self.pkg.content_types, records);
948            if let Some(key) = self.part_index.remove(&identity(name)) {
949                self.pkg.parts.remove(&key);
950            }
951            return;
952        }
953        let key = self
954            .part_index
955            .get(&identity(name))
956            .cloned()
957            .unwrap_or_else(|| norm(name));
958        self.part_index.insert(identity(&key), key.clone());
959        self.pkg.parts.insert(key, Arc::new(data));
960    }
961
962    /// Remove a part (no-op when absent), resolved under OPC identity:
963    /// an alias removes the stored part, a `.rels` name removes the
964    /// owner's relationships, and the `[Content_Types].xml` identity
965    /// clears the content types. Content-type overrides and rels pointing
966    /// at the part are left to the caller.
967    pub fn remove_part(&mut self, name: &str) {
968        if let Some(owner) = rels_path_to_part_name(name) {
969            if owner.is_empty() {
970                self.package_rels = Relationships::new();
971                self.package_rels_original = None;
972                self.package_rels_canonical.clear();
973            } else if let Some(key) = self.rels_index.remove(&identity(&owner)) {
974                self.part_rels.remove(&key);
975                self.part_rels_original.remove(&key);
976                self.part_rels_canonical.remove(&key);
977            }
978        }
979        if name
980            .trim_start_matches('/')
981            .eq_ignore_ascii_case("[Content_Types].xml")
982        {
983            self.pkg.content_types = ContentTypes {
984                defaults: HashMap::new(),
985                overrides: HashMap::new(),
986            };
987            self.content_types_original = None;
988            self.content_types_canonical.clear();
989        }
990        if let Some(key) = self.part_index.remove(&identity(name)) {
991            self.pkg.parts.remove(&key);
992        }
993    }
994
995    /// Enumerate all part names (docxodus style, no leading slash), sorted.
996    pub fn parts(&self) -> Vec<String> {
997        let mut v: Vec<String> = self.pkg.parts.keys().map(|k| denorm(k)).collect();
998        v.sort();
999        v
1000    }
1001
1002    /// Serialize the package back to zip bytes.
1003    ///
1004    /// Uses deflate compression level 1 (`deflate_quick`) instead of the
1005    /// `zip` crate default level 6. Level 1 skips `longest_match` (the
1006    /// largest WASM self-time frame, 26% of the deflate cluster per the W5
1007    /// profile) while producing content-identical decompressed bytes — Word
1008    /// opens any deflate level.
1009    ///
1010    /// Every entry is dated 1980-01-01 00:00, as Office dates its own, and
1011    /// names Unix as its "made by" system whatever the host (the zip crate
1012    /// would pick DOS on Windows), so the same input writes the same bytes
1013    /// on every platform.
1014    pub fn to_zip(&self) -> Result<Vec<u8>, OpcError> {
1015        let options = SimpleFileOptions::default()
1016            .compression_method(CompressionMethod::Deflated)
1017            .compression_level(Some(1))
1018            .last_modified_time(zip::DateTime::default())
1019            .system(zip::System::Unix);
1020
1021        let ct_xml = unchanged_xml(
1022            self.pkg.content_types.to_xml()?,
1023            self.content_types_original.as_deref(),
1024            &self.content_types_canonical,
1025        );
1026        let pkg_rels_xml = unchanged_xml(
1027            self.package_rels.to_xml()?,
1028            self.package_rels_original.as_deref(),
1029            &self.package_rels_canonical,
1030        );
1031
1032        // Source entries keep their places; added ones follow, by name.
1033        let mut entries: Vec<(Cow<'_, str>, ZipEntry<'_>)> = Vec::new();
1034        for (part, rels) in &self.part_rels {
1035            let xml = unchanged_xml(
1036                rels.to_xml()?,
1037                self.part_rels_original.get(part).map(Vec::as_slice),
1038                self.part_rels_canonical
1039                    .get(part)
1040                    .map(Vec::as_slice)
1041                    .unwrap_or(b""),
1042            );
1043            entries.push((
1044                Cow::Owned(part_name_to_rels_path(part)),
1045                ZipEntry::Rels(xml),
1046            ));
1047        }
1048        entries.extend(self.pkg.parts.iter().map(|(name, data)| {
1049            let zip_name = name.strip_prefix('/').unwrap_or(name);
1050            (Cow::Borrowed(zip_name), ZipEntry::Part(data.as_slice()))
1051        }));
1052        entries.sort_by(|(a, _), (b, _)| {
1053            let rank = |name: &str| self.source_order.get(name).copied().unwrap_or(usize::MAX);
1054            (rank(a), a).cmp(&(rank(b), b))
1055        });
1056        // jubarte writes ZIP32 only (ZIP-10/#604): a package that would
1057        // need ZIP64 is refused before `ZipWriter::new`, not mid-write.
1058        let plan: Vec<(&str, u64)> = [
1059            ("[Content_Types].xml", ct_xml.len() as u64),
1060            ("_rels/.rels", pkg_rels_xml.len() as u64),
1061        ]
1062        .into_iter()
1063        .chain(
1064            entries
1065                .iter()
1066                .map(|(name, entry)| (name.as_ref(), entry.len())),
1067        )
1068        .collect();
1069        // One entry per OPC identity (ZIP-15/#600): a raw part that shares
1070        // a name with a parsed rels part or a reserved name is
1071        // `DUPLICATE_PART`, not an archive Word refuses.
1072        let mut emitted = HashSet::new();
1073        if let Some(name) = plan
1074            .iter()
1075            .map(|(name, _)| name)
1076            .find(|name| !emitted.insert(name.to_ascii_lowercase()))
1077        {
1078            return Err(refused(crate::admission::AdmissionError::new(
1079                crate::admission::AdmissionErrorKind::DuplicatePart,
1080                format!("'{name}' would be written twice (part names ignore case)"),
1081            )));
1082        }
1083        zip32_plan(&plan).map_err(refused)?;
1084
1085        let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
1086        zip.start_file("[Content_Types].xml", options)?;
1087        zip.write_all(&ct_xml)?;
1088        zip.start_file("_rels/.rels", options)?;
1089        zip.write_all(&pkg_rels_xml)?;
1090        for (name, entry) in &entries {
1091            zip.start_file(name.as_ref(), options)?;
1092            match entry {
1093                ZipEntry::Rels(xml) => zip.write_all(xml)?,
1094                ZipEntry::Part(data) => zip.write_all(data)?,
1095            }
1096        }
1097
1098        Ok(zip.finish()?.into_inner())
1099    }
1100
1101    // ── gap helpers (the few bits opc-partfs adds on top of raw zip) ───────────
1102
1103    /// `resolveRelTarget(sourcePart, relTarget)` — the part a rel target names,
1104    /// relative to its source part, as a canonical part name: no leading slash
1105    /// (the form `parts()` returns) and `.`/`..` segments resolved. An echoed
1106    /// absolute target ("/word/footer1.xml") was later re-prefixed into a
1107    /// "//word/…" relationship, and "word/../customXml/item1.xml" named no part.
1108    pub fn resolve_rel_target(&self, source_part: &str, rel_target: &str) -> String {
1109        // PartFs receives raw relationship attributes; DOM consumers already
1110        // decoded XML entities and call the pure resolver directly.
1111        let target = crate::xmllinq::parse::unescape_xml_text(rel_target);
1112        resolve_rel_target(source_part, &target)
1113    }
1114
1115    /// `contentTypeFor(part)`.
1116    pub fn content_type_for(&self, name: &str) -> Option<String> {
1117        self.pkg
1118            .content_types
1119            .content_type_for(&norm(name))
1120            .map(|s| s.to_string())
1121    }
1122
1123    /// Add an Override entry to `[Content_Types].xml`.
1124    pub fn add_content_type_override(&mut self, part_name: &str, content_type: &str) {
1125        self.pkg
1126            .content_types
1127            .add_override(&norm(part_name), content_type);
1128    }
1129
1130    /// Add a Default extension mapping to `[Content_Types].xml`.
1131    pub fn add_content_type_default(&mut self, ext: &str, content_type: &str) {
1132        self.pkg.content_types.add_default(ext, content_type);
1133    }
1134
1135    /// Give every part that has no content type the one its source declares:
1136    /// the source's entry for the same part name, else the source's Default for
1137    /// the extension (case-insensitive, as OPC matches extensions). A part no
1138    /// source types is left alone rather than guessed.
1139    pub fn adopt_missing_content_types(&mut self, sources: &[&PartFs]) {
1140        for part in self.parts() {
1141            // `content_type_for` already matches a Default under another
1142            // case (`png` for `image3.PNG`), so a part typed by our own
1143            // Default stops here: a second Default for the same extension
1144            // would make the package unopenable.
1145            if self.content_type_for(&part).is_some() {
1146                continue;
1147            }
1148            let Some((_, ext)) = part.rsplit_once('.').filter(|(_, e)| !e.contains('/')) else {
1149                continue;
1150            };
1151            let by_ext = |fs: &PartFs| {
1152                fs.pkg
1153                    .content_types
1154                    .defaults
1155                    .iter()
1156                    .find(|(e, _)| e.eq_ignore_ascii_case(ext))
1157                    .map(|(_, ct)| ct.clone())
1158            };
1159            let key = norm(&part);
1160            for src in sources {
1161                if let Some(ct) = src.pkg.content_types.override_for(&key).map(str::to_string) {
1162                    self.add_content_type_override(&part, &ct);
1163                    break;
1164                }
1165                if let Some(ct) = by_ext(src) {
1166                    self.add_content_type_default(ext, &ct);
1167                    break;
1168                }
1169            }
1170        }
1171    }
1172
1173    /// Remove an Override entry from `[Content_Types].xml` (no-op when
1174    /// absent). The name resolves under OPC identity, so an alias removes
1175    /// the stored spelling (#600).
1176    pub fn remove_content_type_override(&mut self, part_name: &str) {
1177        self.pkg.content_types.remove_override(&norm(part_name));
1178    }
1179
1180    /// Remove every relationship of `source_part` with the given type.
1181    /// No-op when the source part has no relationships part yet — must not
1182    /// invent an empty `.rels` entry just to remove from it (PR #81 review).
1183    pub fn remove_relationships_by_type(&mut self, source_part: &str, rel_type: &str) {
1184        if let Some(key) = self.part_rels_key(source_part).cloned()
1185            && let Some(rels) = self.part_rels.get_mut(&key)
1186        {
1187            rels.items.retain(|r| r.rel_type != rel_type);
1188        }
1189    }
1190
1191    /// Remove every package-level relationship (`_rels/.rels`) of the given
1192    /// type. The parts they target are left to the caller.
1193    pub fn remove_package_relationships_by_type(&mut self, rel_type: &str) {
1194        self.package_rels.items.retain(|r| r.rel_type != rel_type);
1195    }
1196
1197    /// Remove the relationship `rel_id` of `source_part` and, unless another
1198    /// internal relationship still targets it, the part it names with that
1199    /// part's own relationships and content-type override, then the parts
1200    /// (a header's images) nothing else targets any more. No-op for an
1201    /// unknown or external relationship.
1202    pub fn remove_related_part(&mut self, source_part: &str, rel_id: &str) {
1203        let Some(key) = self.part_rels_key(source_part).cloned() else {
1204            return;
1205        };
1206        let Some(rels) = self.part_rels.get_mut(&key) else {
1207            return;
1208        };
1209        let Some(target) = rels
1210            .items
1211            .iter()
1212            .find(|r| r.id == rel_id && r.target_mode.as_deref() != Some("External"))
1213            .map(|r| r.target.clone())
1214        else {
1215            return;
1216        };
1217        rels.items.retain(|r| r.id != rel_id);
1218        let part = self.resolve_rel_target(source_part, &target);
1219        self.remove_untargeted_part(&part);
1220    }
1221
1222    /// Remove `part`, its relationships and content-type override when no
1223    /// internal relationship of another part targets it, then each part it
1224    /// targeted that is left untargeted. Its own relationships never keep
1225    /// it, and a removed part ends a loop.
1226    fn remove_untargeted_part(&mut self, part: &str) {
1227        let part_id = identity(part);
1228        let Some(key) = self.part_index.get(&part_id).cloned() else {
1229            return;
1230        };
1231        let still_targeted = self
1232            .part_rels
1233            .iter()
1234            .filter(|(source, _)| identity(source) != part_id)
1235            .map(|(source, rels)| (source.as_str(), rels))
1236            .chain(std::iter::once(("/", &self.package_rels)))
1237            .any(|(source, rels)| {
1238                rels.items.iter().any(|r| {
1239                    r.target_mode.as_deref() != Some("External")
1240                        && self
1241                            .resolve_rel_target(source, &r.target)
1242                            .eq_ignore_ascii_case(part)
1243                })
1244            });
1245        if still_targeted {
1246            return;
1247        }
1248        self.part_index.remove(&part_id);
1249        self.pkg.parts.remove(&key);
1250        let rels_key = self.rels_index.get(&part_id).cloned().unwrap_or(key);
1251        // Its loaded rels bytes go too, as in `remove_part`: rels built later
1252        // for the same owner are written from the model.
1253        self.part_rels_original.remove(&rels_key);
1254        self.part_rels_canonical.remove(&rels_key);
1255        let targets: Vec<String> = self
1256            .part_rels
1257            .remove(&rels_key)
1258            .map(|rels| {
1259                rels.items
1260                    .iter()
1261                    .filter(|r| r.target_mode.as_deref() != Some("External"))
1262                    .map(|r| self.resolve_rel_target(part, &r.target))
1263                    .collect()
1264            })
1265            .unwrap_or_default();
1266        self.rels_index.remove(&part_id);
1267        self.remove_content_type_override(&format!("/{part}"));
1268        for target in targets {
1269            self.remove_untargeted_part(&target);
1270        }
1271    }
1272
1273    /// `readRelsFor(part)` — the relationships of a part, if any.
1274    pub fn read_rels_for(&self, part_name: &str) -> Option<&Relationships> {
1275        self.part_rels.get(self.part_rels_key(part_name)?)
1276    }
1277
1278    // The stored owner key for `part_name` under OPC identity — upstream's
1279    // case-insensitive, normalized lookup over the rels index.
1280    fn part_rels_key(&self, part_name: &str) -> Option<&String> {
1281        self.rels_index.get(&identity(part_name))
1282    }
1283
1284    /// `addDocumentRelationship(...)` — add a relationship to a part, returning
1285    /// the new relationship id.
1286    pub fn add_document_relationship(
1287        &mut self,
1288        source_part: &str,
1289        rel_type: &str,
1290        target: &str,
1291    ) -> String {
1292        self.part_rels_mut(source_part).add(rel_type, target)
1293    }
1294
1295    /// The package's own relationships (`_rels/.rels`).
1296    pub fn package_relationships(&self) -> &Relationships {
1297        &self.package_rels
1298    }
1299
1300    /// All parsed relationships, including those whose source part is absent.
1301    /// The package's own relationships have the empty source name.
1302    #[doc(hidden)]
1303    pub fn relationship_parts(&self) -> Vec<(&str, &Relationships)> {
1304        let mut parts: Vec<_> = self
1305            .part_rels
1306            .iter()
1307            .map(|(source, rels)| (source.trim_start_matches('/'), rels))
1308            .collect();
1309        parts.sort_by_key(|(source, _)| *source);
1310        parts.insert(0, ("", self.package_relationships()));
1311        parts
1312    }
1313
1314    /// Add a package-level relationship, returning its id.
1315    pub fn add_package_relationship(&mut self, rel_type: &str, target: &str) -> String {
1316        self.package_rels.add(rel_type, target)
1317    }
1318
1319    /// A part's relationships, created empty when missing. Created through
1320    /// `Relationships::new`, which numbers from `rId1` as Word does; the
1321    /// dependency's `get_or_create_part_rels` defaults to `rId0`.
1322    fn part_rels_mut(&mut self, source_part: &str) -> &mut Relationships {
1323        use std::collections::hash_map::Entry;
1324        // An alias of a stored owner resolves to it rather than creating a
1325        // second rels entry of one identity (#600). Not `or_default()`:
1326        // the derived `Default` is the rId0 counter.
1327        let key = self
1328            .rels_index
1329            .get(&identity(source_part))
1330            .cloned()
1331            .unwrap_or_else(|| norm(source_part));
1332        match self.part_rels.entry(key.clone()) {
1333            Entry::Occupied(rels) => rels.into_mut(),
1334            Entry::Vacant(slot) => {
1335                self.rels_index.insert(identity(&key), key);
1336                slot.insert(Relationships::new())
1337            }
1338        }
1339    }
1340
1341    /// Add a relationship with `TargetMode="External"` (absolute-URI targets
1342    /// are ILLEGAL for the default Internal mode — strict packaging layers
1343    /// like Word's reject the package without this).
1344    pub fn add_document_relationship_external(
1345        &mut self,
1346        source_part: &str,
1347        rel_type: &str,
1348        target: &str,
1349    ) -> String {
1350        let rels = self.part_rels_mut(source_part);
1351        let id = rels.add(rel_type, target);
1352        if let Some(r) = rels.items.iter_mut().find(|r| r.id == id) {
1353            r.target_mode = Some("External".to_string());
1354        }
1355        id
1356    }
1357
1358    /// Mark an existing relationship of `source_part` as External (test aid).
1359    pub fn set_rel_target_mode_external(&mut self, source_part: &str, rel_id: &str) {
1360        let rels = self.part_rels_mut(source_part);
1361        if let Some(r) = rels.items.iter_mut().find(|r| r.id == rel_id) {
1362            r.target_mode = Some("External".to_string());
1363        }
1364    }
1365
1366    /// The main document part name (docxodus style).
1367    pub fn main_document_part(&self) -> Option<String> {
1368        self.package_rels
1369            .get_by_type(oxml_opc::relationship::rel_types::DOCUMENT)
1370            .map(|rel| denorm(&rel.target))
1371    }
1372}
1373
1374#[cfg(test)]
1375#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1376mod tests {
1377    use super::*;
1378    use crate::admission::zip_names;
1379    use zip::ZipArchive;
1380
1381    /// Every entry `to_zip` writes names Unix as its "made by" system, on
1382    /// every host. Left to the zip crate, that byte follows the host (DOS
1383    /// on Windows), so the same input wrote different bytes there and an
1384    /// edit plan bound by `source_sha256` to an earlier output refused as
1385    /// STALE_SOURCE on Windows only.
1386    #[test]
1387    fn to_zip_names_the_same_system_on_every_host() {
1388        let source = package_with_document_rels(
1389            "<Relationship Id=\"rId1\" Type=\"test\" Target=\"a.xml\"/>",
1390        );
1391        let written = PartFs::open(&source).unwrap().to_zip().unwrap();
1392        let mut archive = ZipArchive::new(Cursor::new(written)).unwrap();
1393        for i in 0..archive.len() {
1394            let entry = archive.by_index(i).unwrap();
1395            assert_eq!(
1396                entry.system(),
1397                zip::System::Unix,
1398                "{:?} names a host-dependent system",
1399                entry.name()
1400            );
1401        }
1402    }
1403
1404    #[test]
1405    fn opc_attribute_budget_bounds_upstream_duplicate_checks() {
1406        let attrs = |count| {
1407            (0..count)
1408                .map(|i| format!(" a{i}=\"x\""))
1409                .collect::<String>()
1410        };
1411        for close in ["/>", "></Relationship>"] {
1412            let at_limit = format!("<Relationship{}{close}", attrs(256));
1413            assert!(check_opc_attributes(at_limit.as_bytes()).is_ok());
1414            let over_limit = format!("<Relationship{}{close}", attrs(257));
1415            assert!(check_opc_attributes(over_limit.as_bytes()).is_err());
1416            let bytes = package_with_document_rels(&over_limit);
1417            assert!(PartFs::open(&bytes).is_err());
1418        }
1419        assert!(check_opc_attributes(b"<Relationship broken/>").is_err());
1420        assert!(check_opc_attributes(b"<Relationship").is_err());
1421        let bytes = package_with_document_rels(
1422            "<Relationship Id=\"rId1\" Type=\"test\" Target=\"a.xml\"/>",
1423        );
1424        assert!(PartFs::open(&bytes).is_ok());
1425        assert!(
1426            PartFs::open_within(
1427                &bytes,
1428                crate::admission::InputLimits {
1429                    max_part_bytes: 32,
1430                    ..crate::admission::InputLimits::compare()
1431                }
1432            )
1433            .is_err()
1434        );
1435        assert!(PartFs::open(b"not a zip").is_err());
1436
1437        // Content types are also parsed by upstream, before relationships.
1438        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
1439        writer
1440            .start_file("[Content_Types].xml", SimpleFileOptions::default())
1441            .unwrap();
1442        write!(writer, "<Types{}/>", attrs(257)).unwrap();
1443        let bytes = writer.finish().unwrap().into_inner();
1444        let err = PartFs::open(&bytes)
1445            .err()
1446            .expect("metadata attribute budget");
1447        assert!(err.to_string().contains("256 attributes"));
1448    }
1449
1450    const RELS_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
1451    const HYPERLINK: &str =
1452        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
1453
1454    #[test]
1455    fn public_and_package_relationship_readers_agree() {
1456        for namespace in [format!(r#" xmlns="{RELS_NS}""#), String::new()] {
1457            let document_type = oxml_opc::relationship::rel_types::DOCUMENT;
1458            let document_target = if namespace.is_empty() {
1459                "/word/document.xml"
1460            } else {
1461                "word/document.xml"
1462            };
1463            let xml = format!(
1464                r#"<Relationships{namespace}><Relationship Id="rId7" Type="{HYPERLINK}" Target="https://example.com/?a=1&amp;b=2" TargetMode="External"></Relationship><Relationship Id="rId2" Type="{document_type}" Target="{document_target}"/></Relationships>"#
1465            );
1466            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
1467            for (name, data) in [
1468                ("[Content_Types].xml", "<Types/>"),
1469                ("_rels/.rels", xml.as_str()),
1470                ("word/document.xml", "<document/>"),
1471                ("word/_rels/document.xml.rels", xml.as_str()),
1472            ] {
1473                writer
1474                    .start_file(name, SimpleFileOptions::default())
1475                    .unwrap();
1476                writer.write_all(data.as_bytes()).unwrap();
1477            }
1478            let bytes = writer.finish().unwrap().into_inner();
1479            let fs = PartFs::open(&bytes).unwrap();
1480            let mut direct = Relationships::from_xml(xml.as_bytes()).unwrap();
1481            assert_eq!(direct.items.len(), 2);
1482            assert_eq!(direct.items, fs.package_relationships().items);
1483            for owner in ["word/document.xml", "/WORD/folder/../document.xml"] {
1484                assert_eq!(direct.items, fs.read_rels_for(owner).unwrap().items);
1485            }
1486            assert_eq!(
1487                fs.main_document_part().as_deref(),
1488                Some("word/document.xml")
1489            );
1490            assert_eq!(
1491                direct.to_xml().unwrap(),
1492                fs.read_rels_for("word/document.xml")
1493                    .unwrap()
1494                    .to_xml()
1495                    .unwrap()
1496            );
1497            assert_eq!(direct.add("image", "media/b.png"), "rId8");
1498        }
1499    }
1500
1501    /// A write that does not change content types or relationships keeps
1502    /// attributes the parsed model does not store.
1503    #[test]
1504    fn an_unchanged_package_keeps_unmodeled_metadata_attributes() {
1505        let types = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types" Extra="kept"><Default Extension="xml" ContentType="application/xml"/></Types>"#;
1506        let package_rels = format!(
1507            r#"<Relationships xmlns="{RELS_NS}" Extra="kept"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#
1508        );
1509        let part_rels = format!(r#"<Relationships xmlns="{RELS_NS}" Extra="kept"/>"#);
1510        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
1511        for (name, data) in [
1512            ("[Content_Types].xml", types),
1513            ("_rels/.rels", package_rels.as_str()),
1514            ("word/document.xml", "<document/>"),
1515            ("word/_rels/document.xml.rels", part_rels.as_str()),
1516        ] {
1517            writer
1518                .start_file(name, SimpleFileOptions::default())
1519                .unwrap();
1520            writer.write_all(data.as_bytes()).unwrap();
1521        }
1522        let bytes = writer.finish().unwrap().into_inner();
1523        let written = PartFs::open(&bytes).unwrap().to_zip().unwrap();
1524        let mut archive = ZipArchive::new(Cursor::new(written)).unwrap();
1525        for name in [
1526            "[Content_Types].xml",
1527            "_rels/.rels",
1528            "word/_rels/document.xml.rels",
1529        ] {
1530            let mut text = String::new();
1531            archive
1532                .by_name(name)
1533                .unwrap()
1534                .read_to_string(&mut text)
1535                .unwrap();
1536            assert!(
1537                text.contains(r#"Extra="kept""#),
1538                "{name} dropped an attribute the model does not store: {text}"
1539            );
1540        }
1541    }
1542
1543    /// One zip entry of `zip` as text.
1544    fn zip_entry(zip: &[u8], name: &str) -> String {
1545        let mut text = String::new();
1546        ZipArchive::new(Cursor::new(zip))
1547            .unwrap()
1548            .by_name(name)
1549            .unwrap()
1550            .read_to_string(&mut text)
1551            .unwrap();
1552        text
1553    }
1554
1555    /// A part removed because nothing targets it any more takes its loaded
1556    /// relationship bytes with it: rels later built afresh for the same
1557    /// owner are written from the model, never from the old part's XML.
1558    #[test]
1559    fn a_removed_parts_loaded_rels_bytes_do_not_return_with_new_rels() {
1560        let mut buf = Vec::new();
1561        {
1562            let mut z = ZipWriter::new(Cursor::new(&mut buf));
1563            let opt = SimpleFileOptions::default();
1564            for (name, xml) in [
1565                ("[Content_Types].xml", r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/></Types>"#.to_string()),
1566                ("_rels/.rels", format!(r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#)),
1567                ("word/document.xml", "<w:document/>".to_string()),
1568                ("word/_rels/document.xml.rels", format!(r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/></Relationships>"#)),
1569                ("word/header1.xml", "<w:hdr/>".to_string()),
1570                ("word/_rels/header1.xml.rels", format!(r#"<Relationships xmlns="{RELS_NS}" Extra="old"><Relationship Id="rId1" Type="{HYPERLINK}" Target="https://a.example/" TargetMode="External"/></Relationships>"#)),
1571            ] {
1572                z.start_file(name, opt).unwrap();
1573                z.write_all(xml.as_bytes()).unwrap();
1574            }
1575            z.finish().unwrap();
1576        }
1577        let mut fs = PartFs::open(&buf).unwrap();
1578        fs.remove_related_part("word/document.xml", "rId9");
1579        assert!(fs.part_bytes("word/header1.xml").is_none());
1580        // The same header and the same link, built anew.
1581        fs.set_part("word/header1.xml", b"<w:hdr/>".to_vec());
1582        fs.add_document_relationship_external("word/header1.xml", HYPERLINK, "https://a.example/");
1583        let rels = zip_entry(&fs.to_zip().unwrap(), "word/_rels/header1.xml.rels");
1584        assert!(!rels.contains("Extra=\"old\""), "{rels}");
1585    }
1586
1587    /// The loaded `[Content_Types].xml` goes back only when the model holds
1588    /// every record it had. A repeated override collapses into one entry at
1589    /// load, so the package is written from the model, which states it once.
1590    #[test]
1591    fn content_types_the_model_collapsed_are_written_from_the_model() {
1592        let override_ = |content_type: &str| {
1593            format!(r#"<Override PartName="/word/document.xml" ContentType="{content_type}"/>"#)
1594        };
1595        let types = format!(
1596            r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/>{}{}</Types>"#,
1597            override_("application/xml"),
1598            override_(
1599                "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
1600            ),
1601        );
1602        let mut buf = Vec::new();
1603        {
1604            let mut z = ZipWriter::new(Cursor::new(&mut buf));
1605            let opt = SimpleFileOptions::default();
1606            for (name, xml) in [
1607                ("[Content_Types].xml", types),
1608                (
1609                    "_rels/.rels",
1610                    format!(
1611                        r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#
1612                    ),
1613                ),
1614                ("word/document.xml", "<w:document/>".to_string()),
1615            ] {
1616                z.start_file(name, opt).unwrap();
1617                z.write_all(xml.as_bytes()).unwrap();
1618            }
1619            z.finish().unwrap();
1620        }
1621        let written = zip_entry(
1622            &PartFs::open(&buf).unwrap().to_zip().unwrap(),
1623            "[Content_Types].xml",
1624        );
1625        assert_eq!(
1626            written.matches("PartName=\"/word/document.xml\"").count(),
1627            1,
1628            "{written}"
1629        );
1630    }
1631
1632    fn package_with_header_rels() -> PartFs {
1633        let mut buf = Vec::new();
1634        {
1635            let mut z = ZipWriter::new(Cursor::new(&mut buf));
1636            let opt = SimpleFileOptions::default();
1637            let parts: [(&str, String); 5] = [
1638                ("[Content_Types].xml", r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/></Types>"#.to_string()),
1639                ("_rels/.rels", format!(r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#)),
1640                ("word/document.xml", "<w:document/>".to_string()),
1641                ("word/header1.xml", "<w:hdr/>".to_string()),
1642                ("word/_rels/header1.xml.rels", format!(r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="{HYPERLINK}" Target="https://a.example/" TargetMode="External"/></Relationships>"#)),
1643            ];
1644            for (name, xml) in parts {
1645                z.start_file(name, opt).unwrap();
1646                z.write_all(xml.as_bytes()).unwrap();
1647            }
1648            z.finish().unwrap();
1649        }
1650        PartFs::open(&buf).unwrap()
1651    }
1652
1653    /// A package whose `word/_rels/document.xml.rels` holds `rels`.
1654    fn package_with_document_rels(rels: &str) -> Vec<u8> {
1655        let mut buf = Vec::new();
1656        {
1657            let mut z = ZipWriter::new(Cursor::new(&mut buf));
1658            let opt = SimpleFileOptions::default();
1659            let parts: [(&str, String); 4] = [
1660                ("[Content_Types].xml", r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/></Types>"#.to_string()),
1661                ("_rels/.rels", format!(r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#)),
1662                ("word/document.xml", "<w:document/>".to_string()),
1663                ("word/_rels/document.xml.rels", format!(r#"<Relationships xmlns="{RELS_NS}">{rels}</Relationships>"#)),
1664            ];
1665            for (name, xml) in parts {
1666                z.start_file(name, opt).unwrap();
1667                z.write_all(xml.as_bytes()).unwrap();
1668            }
1669            z.finish().unwrap();
1670        }
1671        buf
1672    }
1673
1674    /// Word refuses a package that repeats a relationship Id in one part
1675    /// (docxide case8's fontTable rels, opened in Word 16: unreadable).
1676    /// The same relationship twice is repaired by keeping one, and the
1677    /// repair is recorded for `validate`; two relationships under one Id
1678    /// are ambiguous and refused.
1679    #[test]
1680    fn a_repeated_relationship_id_is_repaired_when_identical_and_refused_otherwise() {
1681        let font = |id: &str, target: &str| {
1682            format!(
1683                r#"<Relationship Id="{id}" Type="{HYPERLINK}" Target="{target}" TargetMode="External"/>"#
1684            )
1685        };
1686        let same = package_with_document_rels(&format!(
1687            "{}{}{}",
1688            font("rId1", "https://a.example/"),
1689            font("rId2", "https://b.example/"),
1690            font("rId1", "https://a.example/")
1691        ));
1692        let fs = PartFs::open(&same).unwrap();
1693        let rels = fs.read_rels_for("word/document.xml").unwrap();
1694        let ids: Vec<&str> = rels.items.iter().map(|r| r.id.as_str()).collect();
1695        assert_eq!(ids, ["rId1", "rId2"]);
1696        assert_eq!(
1697            fs.repaired_duplicate_ids(),
1698            [("word/document.xml".to_string(), "rId1".to_string())]
1699        );
1700        let conflict = package_with_document_rels(&format!(
1701            "{}{}",
1702            font("rId1", "https://a.example/"),
1703            font("rId1", "https://other.example/")
1704        ));
1705        assert!(matches!(
1706            PartFs::open(&conflict),
1707            Err(OpcError::InvalidRelationship)
1708        ));
1709        let clean = package_with_document_rels(&font("rId1", "https://a.example/"));
1710        assert!(
1711            PartFs::open(&clean)
1712                .unwrap()
1713                .repaired_duplicate_ids()
1714                .is_empty()
1715        );
1716    }
1717
1718    #[test]
1719    fn the_package_is_written_in_the_source_order_then_new_parts_by_name() {
1720        // Parts and relationships live in hash maps, so the zip entries came
1721        // out in a different order on every run: same content, other bytes.
1722        let mut fs = package_with_header_rels();
1723        fs.set_part("word/b.xml", b"<b/>".to_vec());
1724        fs.set_part("word/a.xml", b"<a/>".to_vec());
1725        let zip = fs.to_zip().unwrap();
1726        let names: Vec<String> = ZipArchive::new(Cursor::new(&zip))
1727            .unwrap()
1728            .file_names()
1729            .map(|name| name.expect("decode ZIP fixture name"))
1730            .map(|name| name.into_owned())
1731            .collect();
1732        assert_eq!(
1733            names,
1734            [
1735                "[Content_Types].xml",
1736                "_rels/.rels",
1737                "word/document.xml",
1738                "word/header1.xml",
1739                "word/_rels/header1.xml.rels",
1740                "word/a.xml",
1741                "word/b.xml",
1742            ]
1743        );
1744        assert_eq!(fs.to_zip().unwrap(), zip);
1745    }
1746
1747    #[test]
1748    fn entries_carry_no_wall_clock_time() {
1749        // Another dependency turns on zip's `time` feature, and with it the
1750        // default options stamp each entry with the current time: two writes
1751        // a second apart gave other bytes. Office writes 1980-01-01 00:00.
1752        let zip = package_with_header_rels().to_zip().unwrap();
1753        let mut archive = ZipArchive::new(Cursor::new(&zip)).unwrap();
1754        for i in 0..archive.len() {
1755            let entry = archive.by_index(i).unwrap();
1756            assert_eq!(
1757                entry.last_modified(),
1758                Some(zip::DateTime::default()),
1759                "{}",
1760                entry.name().expect("decode ZIP fixture name")
1761            );
1762        }
1763    }
1764
1765    #[test]
1766    fn part_names_carry_exactly_one_leading_slash() {
1767        // `format!("/{part}")` on a part that already starts with '/' (an
1768        // absolute rel target) wrote a `//word/footer1.xml` content-type override;
1769        // OPC readers then refuse the whole package.
1770        let mut fs = package_with_header_rels();
1771        fs.add_content_type_override("//word/footer1.xml", "application/xml");
1772        fs.set_part("//word/footer1.xml", b"<w:ftr/>".to_vec());
1773        assert_eq!(
1774            fs.content_type_for("word/footer1.xml").as_deref(),
1775            Some("application/xml")
1776        );
1777        assert!(fs.parts().contains(&"word/footer1.xml".to_string()));
1778        let zip = fs.to_zip().unwrap();
1779        let ct = String::from_utf8(
1780            PartFs::open(&zip)
1781                .unwrap()
1782                .pkg
1783                .content_types
1784                .to_xml()
1785                .unwrap(),
1786        )
1787        .unwrap();
1788        assert!(!ct.contains("//word"), "{ct}");
1789    }
1790
1791    #[test]
1792    fn parts_without_a_content_type_adopt_the_sources_default() {
1793        // B's header pulls in `media/hdphoto1.wdp` (HD Photo); the copy kept the
1794        // bytes but not B's `wdp` Default, and a part with no content type makes
1795        // Word refuse the package.
1796        let mut src = package_with_header_rels();
1797        src.add_content_type_default("wdp", "image/vnd.ms-photo");
1798        src.add_content_type_default("PNG", "image/png");
1799        let mut out = package_with_header_rels();
1800        out.set_part("word/media/hdphoto1.wdp", vec![1, 2, 3]);
1801        out.set_part("word/media/pic.png", vec![4]);
1802        out.set_part("word/media/unknown.zzz", vec![5]);
1803        out.adopt_missing_content_types(&[&src]);
1804        assert_eq!(
1805            out.content_type_for("word/media/hdphoto1.wdp").as_deref(),
1806            Some("image/vnd.ms-photo")
1807        );
1808        // Extension matching is case-insensitive in OPC.
1809        assert_eq!(
1810            out.content_type_for("word/media/pic.png").as_deref(),
1811            Some("image/png")
1812        );
1813        // Nothing to adopt: left alone rather than guessed.
1814        assert_eq!(out.content_type_for("word/media/unknown.zzz"), None);
1815        // A part with no extension has no Default to ask for.
1816        out.set_part("word/media/LICENSE", vec![6]);
1817        out.adopt_missing_content_types(&[&src]);
1818        assert_eq!(out.content_type_for("word/media/LICENSE"), None);
1819        // A part the source names in an Override adopts that Override.
1820        let mut typed = package_with_header_rels();
1821        typed.add_content_type_override("word/media/logo.bin", "image/x-logo");
1822        let mut out = package_with_header_rels();
1823        out.set_part("word/media/logo.bin", vec![7]);
1824        out.adopt_missing_content_types(&[&typed]);
1825        assert_eq!(
1826            out.content_type_for("word/media/logo.bin").as_deref(),
1827            Some("image/x-logo")
1828        );
1829    }
1830
1831    #[test]
1832    fn an_upper_case_extension_is_already_typed_by_the_lower_case_default() {
1833        // `image3.PNG` under our own `png` Default is typed (OPC matches
1834        // extensions case-insensitively). Adding a second `PNG` Default made the
1835        // package unopenable (647bbcfb, 2026-09-26 English redlines).
1836        let mut out = package_with_header_rels();
1837        out.add_content_type_default("png", "image/png");
1838        out.set_part("word/media/image3.PNG", vec![4]);
1839        out.adopt_missing_content_types(&[]);
1840        let pngs = out
1841            .pkg
1842            .content_types
1843            .defaults
1844            .iter()
1845            .filter(|(e, _)| e.eq_ignore_ascii_case("png"))
1846            .count();
1847        assert_eq!(pngs, 1);
1848    }
1849
1850    #[test]
1851    fn migration_keeps_canonical_metadata_and_decodes_literal_entities_once() {
1852        let bytes = package_with_document_rels(
1853            r#"<Relationship Id="rId7" Type="image" Target="media/a&amp;amp;b.png"/>"#,
1854        );
1855        let loaded = zip_entry(&bytes, "word/_rels/document.xml.rels");
1856        let mut fs = PartFs::open(&bytes).unwrap();
1857        for _ in 0..3 {
1858            assert_eq!(
1859                fs.read_rels_for("word/document.xml").unwrap().items[0].target,
1860                "media/a&amp;b.png"
1861            );
1862            let bytes = fs.to_zip().unwrap();
1863            // Unchanged rels are the loaded bytes, round after round (#858).
1864            assert_eq!(zip_entry(&bytes, "word/_rels/document.xml.rels"), loaded);
1865            fs = PartFs::open(&bytes).unwrap();
1866        }
1867        assert_eq!(
1868            fs.add_document_relationship("word/document.xml", "image", "next.png"),
1869            "rId8"
1870        );
1871        // Changed rels are written from the model, canonical, with the
1872        // literal entity escaped once.
1873        assert_eq!(
1874            zip_entry(&fs.to_zip().unwrap(), "word/_rels/document.xml.rels"),
1875            concat!(
1876                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n",
1877                "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\n",
1878                "  <Relationship Id=\"rId7\" Type=\"image\" Target=\"media/a&amp;amp;b.png\"/>\n",
1879                "  <Relationship Id=\"rId8\" Type=\"image\" Target=\"next.png\"/>\n",
1880                "</Relationships>"
1881            )
1882        );
1883    }
1884
1885    #[test]
1886    fn rel_attributes_survive_round_trips_unescaped() {
1887        // rdocx-opc 0.1.0 keeps `Target="a&amp;b"` escaped when parsing and
1888        // escapes again when writing: every open/write added one `&amp;`, and
1889        // `image11.jpg&ehk=…` ended up pointing at `image11.jpg&amp;amp;amp;…`,
1890        // a part that does not exist (a2412654, 2026-09-26 English redlines).
1891        let mut fs = package_with_header_rels();
1892        fs.set_part(
1893            "word/_rels/document.xml.rels",
1894            format!(r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/p.jpg&amp;ehk=Q"/></Relationships>"#).into_bytes(),
1895        );
1896        let target = |fs: &PartFs| {
1897            fs.read_rels_for("word/document.xml").unwrap().items[0]
1898                .target
1899                .clone()
1900        };
1901        assert_eq!(target(&fs), "media/p.jpg&ehk=Q");
1902        let once = PartFs::open(&fs.to_zip().unwrap()).unwrap();
1903        let twice = PartFs::open(&once.to_zip().unwrap()).unwrap();
1904        assert_eq!(target(&twice), "media/p.jpg&ehk=Q");
1905    }
1906
1907    #[test]
1908    fn content_types_survive_round_trips_unescaped() {
1909        // Same rdocx-opc escaping gap as the relationships: a2412654's
1910        // `Default Extension="jpg&amp;ehk=…"` grew one `&amp;` per cycle and
1911        // stopped typing its picture.
1912        let mut fs = package_with_header_rels();
1913        fs.add_content_type_default("jpg&ehk=Q", "image/jpeg");
1914        fs.set_part("word/media/p.jpg&ehk=Q", vec![1]);
1915        let once = PartFs::open(&fs.to_zip().unwrap()).unwrap();
1916        let twice = PartFs::open(&once.to_zip().unwrap()).unwrap();
1917        assert_eq!(
1918            twice.content_type_for("word/media/p.jpg&ehk=Q").as_deref(),
1919            Some("image/jpeg")
1920        );
1921    }
1922
1923    #[test]
1924    fn rel_targets_resolve_to_canonical_part_names() {
1925        let fs = package_with_header_rels();
1926        // An absolute target once came back as "/word/footer1.xml" and was then
1927        // re-prefixed into a "//word/footer1.xml" relationship (package refused).
1928        assert_eq!(
1929            fs.resolve_rel_target("word/document.xml", "/word/footer1.xml"),
1930            "word/footer1.xml"
1931        );
1932        assert_eq!(
1933            fs.resolve_rel_target("word/document.xml", "media/a.png"),
1934            "word/media/a.png"
1935        );
1936        assert_eq!(
1937            fs.resolve_rel_target("word/document.xml", "../customXml/item1.xml"),
1938            "customXml/item1.xml"
1939        );
1940        assert_eq!(
1941            fs.resolve_rel_target("word/header1.xml", "./media/a.png"),
1942            "word/media/a.png"
1943        );
1944        assert_eq!(
1945            fs.resolve_rel_target("/word/document.xml", "styles.xml"),
1946            "word/styles.xml"
1947        );
1948    }
1949
1950    #[test]
1951    fn rel_targets_are_relative_to_the_source_folder() {
1952        assert_eq!(
1953            relative_rel_target("word/header1.xml", "word/media/P1.png"),
1954            "media/P1.png"
1955        );
1956        assert_eq!(
1957            relative_rel_target("/word/document.xml", "/word/comments.xml"),
1958            "comments.xml"
1959        );
1960        assert_eq!(
1961            relative_rel_target("word/header1.xml", "customXml/item1.xml"),
1962            "/customXml/item1.xml"
1963        );
1964        assert_eq!(
1965            relative_rel_target("word/document.xml", "media/image.bin"),
1966            "/media/image.bin"
1967        );
1968        // `word/document.xml` is not a folder prefix of `wordy/x.xml`.
1969        assert_eq!(
1970            relative_rel_target("word/document.xml", "wordy/x.xml"),
1971            "/wordy/x.xml"
1972        );
1973
1974        // Edge cases
1975        assert_eq!(
1976            relative_rel_target("a.xml", "b.xml"),
1977            "/b.xml",
1978            "Root level source and target"
1979        );
1980        assert_eq!(
1981            relative_rel_target("document.xml", "media/image.bin"),
1982            "/media/image.bin",
1983            "Root level source"
1984        );
1985        assert_eq!(
1986            relative_rel_target("word/theme/theme1.xml", "word/theme/themeManager.xml"),
1987            "themeManager.xml",
1988            "Deeply nested matching paths"
1989        );
1990        assert_eq!(
1991            relative_rel_target("//word/document.xml", "//word/comments.xml"),
1992            "comments.xml",
1993            "Multiple leading slashes"
1994        );
1995        assert_eq!(
1996            relative_rel_target("a/b.xml", "a/c/d.xml"),
1997            "c/d.xml",
1998            "Target as a subdirectory of the source directory"
1999        );
2000        assert_eq!(
2001            relative_rel_target("a/b/c.xml", "a/b/d.xml"),
2002            "d.xml",
2003            "Target and source in the same deeply nested directory"
2004        );
2005        assert_eq!(
2006            relative_rel_target("a/b.xml", "b/c.xml"),
2007            "/b/c.xml",
2008            "Target in completely different directory"
2009        );
2010    }
2011
2012    #[test]
2013    fn rels_paths_name_their_owning_part() {
2014        assert_eq!(
2015            rels_path_to_part_name("word/_rels/header1.xml.rels").as_deref(),
2016            Some("word/header1.xml")
2017        );
2018        assert_eq!(
2019            rels_path_to_part_name("/word/_rels/document.xml.rels").as_deref(),
2020            Some("word/document.xml")
2021        );
2022        assert_eq!(rels_path_to_part_name("_rels/.rels").as_deref(), Some(""));
2023        assert_eq!(rels_path_to_part_name("word/header1.xml"), None);
2024        assert_eq!(rels_path_to_part_name("word/media/odd.rels"), None);
2025    }
2026
2027    /// A part's first relationship is `rId1`, as Word numbers them: the
2028    /// dependency's `Default` relationships start from `rId0`.
2029    #[test]
2030    fn a_new_rels_part_starts_at_rid1() {
2031        let mut fs = package_with_header_rels();
2032        let id = fs.add_document_relationship(
2033            "word/numbering.xml",
2034            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
2035            "media/image1.gif",
2036        );
2037        assert_eq!(id, "rId1");
2038        let external = fs.add_document_relationship_external(
2039            "word/footer9.xml",
2040            HYPERLINK,
2041            "https://c.example/",
2042        );
2043        assert_eq!(external, "rId1");
2044    }
2045
2046    #[test]
2047    fn writing_a_rels_part_replaces_the_parts_relationships() {
2048        let mut fs = package_with_header_rels();
2049        fs.set_part(
2050            "word/_rels/header1.xml.rels",
2051            format!(r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId7" Type="{HYPERLINK}" Target="https://b.example/" TargetMode="External"/></Relationships>"#).into_bytes(),
2052        );
2053        let ids: Vec<String> = fs
2054            .read_rels_for("word/header1.xml")
2055            .unwrap()
2056            .items
2057            .iter()
2058            .map(|r| r.id.clone())
2059            .collect();
2060        assert_eq!(ids, ["rId7"]);
2061        // One .rels entry per part: a raw copy next to the parsed one is a
2062        // duplicate zip name and fails the whole package.
2063        let reopened = PartFs::open(&fs.to_zip().expect("no duplicate .rels")).unwrap();
2064        assert_eq!(
2065            reopened
2066                .read_rels_for("word/header1.xml")
2067                .unwrap()
2068                .items
2069                .len(),
2070            1
2071        );
2072    }
2073
2074    /// Dropping a header takes the media only it used with it; media another
2075    /// part still uses stays, and so does a part reached in a loop.
2076    #[test]
2077    fn removing_a_related_part_drops_the_parts_only_it_targeted() {
2078        const HEADER: &str =
2079            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header";
2080        const IMAGE: &str =
2081            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
2082        let rel = |id: &str, ty: &str, target: &str| {
2083            format!(r#"<Relationship Id="{id}" Type="{ty}" Target="{target}"/>"#)
2084        };
2085        let mut fs = PartFs::open(&package_with_document_rels(&format!(
2086            "{}{}",
2087            rel("rId1", HEADER, "header1.xml"),
2088            rel("rId2", HEADER, "header2.xml")
2089        )))
2090        .unwrap();
2091        for part in ["header1.xml", "header2.xml"] {
2092            fs.set_part(&format!("word/{part}"), b"<w:hdr/>".to_vec());
2093        }
2094        for media in ["logo.png", "shared.png"] {
2095            fs.set_part(&format!("word/media/{media}"), vec![0x89]);
2096        }
2097        fs.set_part(
2098            "word/_rels/header1.xml.rels",
2099            format!(
2100                r#"<Relationships xmlns="{RELS_NS}">{}{}{}</Relationships>"#,
2101                rel("rId1", IMAGE, "media/logo.png"),
2102                rel("rId2", IMAGE, "media/shared.png"),
2103                rel("rId3", HEADER, "header1.xml")
2104            )
2105            .into_bytes(),
2106        );
2107        fs.set_part(
2108            "word/_rels/header2.xml.rels",
2109            format!(
2110                r#"<Relationships xmlns="{RELS_NS}">{}</Relationships>"#,
2111                rel("rId1", IMAGE, "media/shared.png")
2112            )
2113            .into_bytes(),
2114        );
2115
2116        fs.remove_related_part("word/document.xml", "rId1");
2117
2118        let parts = fs.parts();
2119        let has = |name: &str| parts.iter().any(|p| p == name);
2120        assert!(!has("word/header1.xml"), "{parts:?}");
2121        assert!(
2122            !has("word/media/logo.png"),
2123            "only header1 used it: {parts:?}"
2124        );
2125        assert!(has("word/media/shared.png"), "header2 still uses it");
2126        assert!(has("word/header2.xml"));
2127        assert!(fs.read_rels_for("word/header1.xml").is_none());
2128        PartFs::open(&fs.to_zip().unwrap()).unwrap();
2129    }
2130
2131    #[test]
2132    fn migration_skips_zip_directories_and_keeps_a_missing_package_relationship_scope_empty() {
2133        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
2134        let options = SimpleFileOptions::default();
2135        writer.add_directory("word/", options).unwrap();
2136        writer.start_file("[Content_Types].xml", options).unwrap();
2137        writer.write_all(br#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/></Types>"#).unwrap();
2138        writer.start_file("word/document.xml", options).unwrap();
2139        writer.write_all(b"<document/>").unwrap();
2140        let bytes = writer.finish().unwrap().into_inner();
2141        let package = PartFs::open(&bytes).unwrap();
2142        assert_eq!(package.parts(), ["word/document.xml"]);
2143        assert!(package.package_relationships().items.is_empty());
2144        assert_eq!(package.main_document_part(), None);
2145        let reopened = PartFs::open(&package.to_zip().unwrap()).unwrap();
2146        assert_eq!(reopened.parts(), package.parts());
2147        assert!(reopened.package_relationships().items.is_empty());
2148        assert_eq!(
2149            reopened.part_bytes("word/document.xml"),
2150            Some(b"<document/>".as_slice())
2151        );
2152    }
2153
2154    #[test]
2155    fn migration_refuses_missing_required_metadata_attributes_in_package_loading() {
2156        let bytes = package_with_document_rels("<Relationship Id='rId1'/>");
2157        assert!(matches!(
2158            PartFs::open(&bytes),
2159            Err(OpcError::InvalidRelationship)
2160        ));
2161        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
2162        writer
2163            .start_file("[Content_Types].xml", SimpleFileOptions::default())
2164            .unwrap();
2165        writer.write_all(br#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml"/></Types>"#).unwrap();
2166        let bytes = writer.finish().unwrap().into_inner();
2167        assert!(matches!(
2168            PartFs::open(&bytes),
2169            Err(OpcError::InvalidContentTypes)
2170        ));
2171    }
2172
2173    #[test]
2174    fn a_record_local_default_namespace_cannot_bypass_metadata_validation() {
2175        // `<Default xmlns=""/>` unbinds the OPC namespace the reader wraps
2176        // records in, so upstream skipped the record and the package lost its
2177        // missing-attribute refusal; the same shape reaches `.rels` parts.
2178        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
2179        writer
2180            .start_file("[Content_Types].xml", SimpleFileOptions::default())
2181            .unwrap();
2182        writer
2183            .write_all(
2184                br#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default xmlns="" Extension="xml"/></Types>"#,
2185            )
2186            .unwrap();
2187        let bytes = writer.finish().unwrap().into_inner();
2188        assert!(matches!(
2189            PartFs::open(&bytes),
2190            Err(OpcError::InvalidContentTypes)
2191        ));
2192        let bytes = package_with_document_rels("<Relationship xmlns='' Id='rId1'/>");
2193        assert!(matches!(
2194            PartFs::open(&bytes),
2195            Err(OpcError::InvalidRelationship)
2196        ));
2197    }
2198
2199    /// ZIP-47 (#643): `[Content_Types].xml` and `.rels` are read only after
2200    /// they are one authoritative document. A second root, or a root whose
2201    /// default namespace is some other URI, must not be relabelled into the
2202    /// OPC namespace and then used. An absent default namespace stays the
2203    /// legacy local-name read.
2204    #[test]
2205    fn prefixed_or_non_utf8_metadata_is_not_relabelled() {
2206        // #2080 review: a prefixed root in a foreign namespace has
2207        // no default xmlns, and a UTF-16 or invalid UTF-8 document made the
2208        // gate's reader stop with an encoding error; both used to pass the
2209        // gate while the record reader still relabelled their children.
2210        const RELS_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
2211        const OFFICE: &str =
2212            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
2213        const MAIN: &str =
2214            "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
2215        let package = |types: &[u8]| {
2216            let rels = format!(
2217                r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="{OFFICE}" Target="word/document.xml"/></Relationships>"#
2218            );
2219            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
2220            let options = SimpleFileOptions::default();
2221            for (name, xml) in [
2222                ("[Content_Types].xml", types),
2223                ("_rels/.rels", rels.as_bytes()),
2224                ("word/document.xml", b"<w:document/>".as_slice()),
2225            ] {
2226                writer.start_file(name, options).unwrap();
2227                writer.write_all(xml).unwrap();
2228            }
2229            writer.finish().unwrap().into_inner()
2230        };
2231        let foreign = format!(
2232            r#"<Types xmlns="urn:not-opc"><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="{MAIN}"/></Types>"#
2233        );
2234        let prefixed = format!(
2235            r#"<ns:Types xmlns:ns="urn:not-opc"><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="{MAIN}"/></ns:Types>"#
2236        );
2237        let mut utf16 = vec![0xFF, 0xFE];
2238        utf16.extend(foreign.encode_utf16().flat_map(u16::to_le_bytes));
2239        let mut bad_utf8 = foreign.clone().into_bytes();
2240        bad_utf8.extend_from_slice(b"<!-- \xFF -->");
2241        bad_utf8.push(0xFF);
2242        for (label, types) in [
2243            ("prefixed foreign root", prefixed.into_bytes()),
2244            ("UTF-16 foreign default namespace", utf16),
2245            ("invalid UTF-8 foreign default namespace", bad_utf8),
2246        ] {
2247            let bytes = package(&types);
2248            if let Ok(pkg) =
2249                crate::admission::admit(&bytes, crate::admission::InputLimits::default())
2250            {
2251                panic!("{label}: admit interpreted it: {pkg:?}");
2252            }
2253            if let Ok(fs) = PartFs::open(&bytes) {
2254                assert_ne!(
2255                    fs.content_type_for("word/document.xml").as_deref(),
2256                    Some(MAIN),
2257                    "{label}: the package open relabelled the records"
2258                );
2259            }
2260        }
2261    }
2262
2263    #[test]
2264    fn strict_metadata_xml_is_not_relabelled() {
2265        const CT_NS: &str = "http://schemas.openxmlformats.org/package/2006/content-types";
2266        const RELS_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
2267        const OFFICE: &str =
2268            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
2269        const MAIN: &str =
2270            "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
2271        let package = |types: &str, rels: &str| {
2272            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
2273            let options = SimpleFileOptions::default();
2274            for (name, xml) in [
2275                ("[Content_Types].xml", types),
2276                ("_rels/.rels", rels),
2277                ("word/document.xml", "<w:document/>"),
2278            ] {
2279                writer.start_file(name, options).unwrap();
2280                writer.write_all(xml.as_bytes()).unwrap();
2281            }
2282            writer.finish().unwrap().into_inner()
2283        };
2284        let rels = format!(
2285            r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="{OFFICE}" Target="word/document.xml"/></Relationships>"#
2286        );
2287        let typed = format!(
2288            r#"<Types xmlns="{CT_NS}"><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="{MAIN}"/></Types>"#
2289        );
2290
2291        let wrong_types = package(
2292            &format!(
2293                r#"<Types xmlns="urn:not-opc"><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="{MAIN}"/></Types>"#
2294            ),
2295            &rels,
2296        );
2297        match PartFs::open(&wrong_types) {
2298            Ok(fs) => panic!(
2299                "wrong-namespace content types were interpreted as {:?}",
2300                fs.content_type_for("word/document.xml")
2301            ),
2302            Err(err) => assert!(err.to_string().contains("urn:not-opc"), "{err}"),
2303        }
2304        match crate::admission::admit(&wrong_types, crate::admission::InputLimits::default()) {
2305            Ok(pkg) => panic!("admit interpreted wrong-namespace content types: {pkg:?}"),
2306            Err(err) => assert!(err.to_string().contains("urn:not-opc"), "{err}"),
2307        }
2308
2309        let two_roots = package(
2310            &format!(
2311                r#"<Types xmlns="{CT_NS}"/><Types xmlns="{CT_NS}"><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="{MAIN}"/></Types>"#
2312            ),
2313            &rels,
2314        );
2315        match PartFs::open(&two_roots) {
2316            Ok(fs) => panic!(
2317                "two content-type roots were interpreted as {:?}",
2318                fs.content_type_for("word/document.xml")
2319            ),
2320            Err(err) => assert!(err.to_string().contains("multiple XML roots"), "{err}"),
2321        }
2322        match crate::admission::admit(&two_roots, crate::admission::InputLimits::default()) {
2323            Ok(pkg) => panic!("admit interpreted two content-type roots: {pkg:?}"),
2324            Err(err) => assert!(err.to_string().contains("multiple XML roots"), "{err}"),
2325        }
2326
2327        let wrong_rels = package(
2328            &typed,
2329            &format!(
2330                r#"<Relationships xmlns="urn:not-opc"><Relationship Id="rId1" Type="{OFFICE}" Target="word/document.xml"/></Relationships>"#
2331            ),
2332        );
2333        match PartFs::open(&wrong_rels) {
2334            Ok(fs) => panic!(
2335                "wrong-namespace relationships resolved {:?}",
2336                fs.main_document_part()
2337            ),
2338            Err(err) => assert!(err.to_string().contains("urn:not-opc"), "{err}"),
2339        }
2340        match crate::admission::admit(&wrong_rels, crate::admission::InputLimits::default()) {
2341            Ok(pkg) => panic!("admit resolved wrong-namespace relationships: {pkg:?}"),
2342            Err(err) => assert!(err.to_string().contains("urn:not-opc"), "{err}"),
2343        }
2344
2345        let ordinary = package(&typed, &rels);
2346        let fs = PartFs::open(&ordinary).expect("authoritative metadata opens");
2347        assert_eq!(
2348            fs.content_type_for("word/document.xml").as_deref(),
2349            Some(MAIN)
2350        );
2351        assert_eq!(
2352            fs.main_document_part().as_deref(),
2353            Some("word/document.xml")
2354        );
2355        assert!(
2356            crate::admission::admit(&ordinary, crate::admission::InputLimits::default()).is_ok()
2357        );
2358
2359        let unnamespaced = package(
2360            &typed,
2361            &format!(
2362                r#"<Relationships><Relationship Id="rId1" Type="{OFFICE}" Target="word/document.xml"/></Relationships>"#
2363            ),
2364        );
2365        let fs =
2366            PartFs::open(&unnamespaced).expect("an absent default namespace stays the legacy read");
2367        assert_eq!(
2368            fs.main_document_part().as_deref(),
2369            Some("word/document.xml")
2370        );
2371    }
2372
2373    /// A minimal package whose one media entry carries the raw name bytes and
2374    /// flag `media` names, with the document relationship pointing at the
2375    /// CP437 spelling of `\xc3\xa9` (`é`), as a legacy writer left it.
2376    fn legacy_media_package(media: zip_names::RawEntry<'_>) -> Vec<u8> {
2377        let rels = format!(
2378            "<Relationship Id=\"rId1\" Type=\"{HYPERLINK}\" Target=\"media/\u{251C}\u{2310}.png\"/>"
2379        );
2380        zip_names::docx_package(&rels, &[media])
2381    }
2382
2383    #[test]
2384    fn legacy_cp437_entry_names_keep_resolving_their_relationships() {
2385        // zip 8 decoded a flag-clear name as CP437 (zip-8.6.0/src/read.rs
2386        // 523-529: bit 11 set means UTF-8, clear means CP437); zip 9's
2387        // `name()` tries UTF-8 first whatever the flag says
2388        // (zip-9.0.4/src/types.rs:122-130), so `word/media/\xc3\xa9.png`
2389        // became `word/media/é.png` while the relationship still named
2390        // `media/é.png`, and the media lookup (the one convert uses) came
2391        // back empty (#524: no read/write regressions).
2392        let bytes = legacy_media_package(zip_names::RawEntry::raw(
2393            b"word/media/\xc3\xa9.png",
2394            b"PNGPAYLOAD",
2395        ));
2396        let fs = PartFs::open(&bytes).unwrap();
2397        let rel = &fs.read_rels_for("word/document.xml").unwrap().items[0];
2398        assert_eq!(rel.target, "media/\u{251C}\u{2310}.png");
2399        let part = fs.resolve_rel_target("word/document.xml", &rel.target);
2400        assert_eq!(part, "word/media/\u{251C}\u{2310}.png");
2401        assert_eq!(fs.part_bytes(&part), Some(b"PNGPAYLOAD".as_slice()));
2402        // The UTF-8 spelling of the same bytes is not a part of this package.
2403        assert_eq!(fs.part_bytes("word/media/\u{e9}.png"), None);
2404    }
2405
2406    #[test]
2407    fn decoded_part_name_aliases_are_refused_not_overwritten() {
2408        // Two entries whose decoded names collide are one OPC part: the second
2409        // `parts.insert` used to overwrite the first silently, `parts()` lost
2410        // a member and `to_zip()` dropped it. Upstream's reader refuses
2411        // `DuplicatePartName` on the second entry's name
2412        // (oxml-opc-0.14.2/src/package.rs 159-162); so does the constructor —
2413        // the raw central-directory pass reports the defect for `admit`,
2414        // `debug` and the archive readers while the constructor keeps the
2415        // typed variant Rust callers match on (#600).
2416        let base = |extra: &[zip_names::RawEntry<'_>]| zip_names::docx_package("", extra);
2417        // (a) two entries of the same name, byte for byte (the p1 shape):
2418        // one part, the refusal names the second entry's spelling.
2419        let exact = base(&[
2420            zip_names::RawEntry::raw(b"x.bin", b"FIRST"),
2421            zip_names::RawEntry::raw(b"x.bin", b"SECOND"),
2422        ]);
2423        assert!(
2424            matches!(PartFs::open(&exact), Err(OpcError::DuplicatePartName(ref n)) if n == "x.bin"),
2425            "{:?}",
2426            PartFs::open(&exact).err()
2427        );
2428        assert!(
2429            matches!(
2430                PartFs::open_within(&exact, crate::admission::InputLimits::compare()),
2431                Err(OpcError::DuplicatePartName(ref n)) if n == "x.bin"
2432            ),
2433            "open_within refuses the same"
2434        );
2435        // (b) two raw names, bit 11 set, that are not UTF-8. A lossy decode
2436        // used to alias both as `x\u{FFFD}.bin`; the flag's claim is refused
2437        // instead (#640).
2438        let aliased = base(&[
2439            zip_names::RawEntry::raw(b"x\x82.bin", b"FIRST").utf8(),
2440            zip_names::RawEntry::raw(b"x\x83.bin", b"SECOND").utf8(),
2441        ]);
2442        let Err(err) = PartFs::open(&aliased) else {
2443            panic!("invalid UTF-8 entry names were accepted");
2444        };
2445        assert!(err.to_string().contains("not valid UTF-8"), "{err}");
2446        // (c) two names that differ only in ASCII case: one part, OPC names
2447        // are case-insensitive.
2448        let cased = base(&[
2449            zip_names::RawEntry::raw(b"word/A.bin", b"FIRST"),
2450            zip_names::RawEntry::raw(b"word/a.bin", b"SECOND"),
2451        ]);
2452        assert!(
2453            matches!(PartFs::open(&cased), Err(OpcError::DuplicatePartName(ref n)) if n == "word/a.bin"),
2454            "{:?}",
2455            PartFs::open(&cased).err()
2456        );
2457        // (d) the zip 8 shape: both names flag-clear, CP437 decodes them
2458        // apart (`x\x82.bin` → `xé.bin`, `x\xc3\xa9.bin` → `x├⌐.bin`), and
2459        // both payloads survive instead of aliasing as zip 9's UTF-8-first
2460        // `name()` had them.
2461        let apart = base(&[
2462            zip_names::RawEntry::raw(b"x\x82.bin", b"FIRST"),
2463            zip_names::RawEntry::raw(b"x\xc3\xa9.bin", b"SECOND"),
2464        ]);
2465        let fs = PartFs::open(&apart).unwrap();
2466        assert_eq!(fs.part_bytes("x\u{e9}.bin"), Some(b"FIRST".as_slice()));
2467        assert_eq!(
2468            fs.part_bytes("x\u{251C}\u{2310}.bin"),
2469            Some(b"SECOND".as_slice())
2470        );
2471    }
2472    #[test]
2473    fn unicode_path_extra_fields_override_entry_names_as_zip8_did() {
2474        // zip 8 replaced the header name with the 0x7075 field's CRC-checked
2475        // UTF-8 content (zip-8.6.0/src/read.rs:705-709) and refused the
2476        // archive when the content was not UTF-8; zip 9 applies the valid
2477        // case itself and ignores the invalid one, so the readers refuse it.
2478        let bytes = legacy_media_package(
2479            zip_names::RawEntry::raw(b"word/media/plain.bin", b"BINPAYLOAD")
2480                .unicode_path("word/media/\u{2714}.bin".as_bytes()),
2481        );
2482        let fs = PartFs::open(&bytes).unwrap();
2483        assert!(fs.parts().contains(&"word/media/\u{2714}.bin".to_string()));
2484        assert_eq!(
2485            fs.part_bytes("word/media/\u{2714}.bin"),
2486            Some(b"BINPAYLOAD".as_slice())
2487        );
2488
2489        let bytes = legacy_media_package(
2490            zip_names::RawEntry::raw(b"word/media/plain.bin", b"BINPAYLOAD")
2491                .unicode_path(b"\xff\xfe"),
2492        );
2493        assert!(matches!(PartFs::open(&bytes), Err(OpcError::Zip(_))));
2494    }
2495
2496    /// A package with caller-chosen entry names — case-variant spellings
2497    /// of the reserved parts and the main part (#600 probes p3–p5).
2498    fn variant_package(entries: &[(&[u8], &[u8])]) -> Vec<u8> {
2499        zip_names::zip(
2500            &entries
2501                .iter()
2502                .map(|(name, data)| zip_names::RawEntry::raw(name, data))
2503                .collect::<Vec<_>>(),
2504        )
2505    }
2506
2507    const TYPES: &[u8] = br#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#;
2508    const PKG_RELS: &[u8] = br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
2509
2510    /// ZIP-15 (#600): OPC part names ignore ASCII case, so a single
2511    /// case-variant name is the part — Word opens these packages (probes
2512    /// p3, p4, p5) and every lookup must resolve the variant's content.
2513    #[test]
2514    fn a_case_variant_name_is_the_part_on_every_lookup() {
2515        let fs = PartFs::open(&variant_package(&[
2516            (b"[Content_Types].xml", TYPES),
2517            (b"_rels/.rels", PKG_RELS),
2518            (b"word/Document.xml", b"<w:document/>"),
2519        ]))
2520        .expect("the case-variant main part is the part the rels target names (p3)");
2521        assert_eq!(
2522            fs.main_document_part().as_deref(),
2523            Some("word/document.xml")
2524        );
2525        assert_eq!(
2526            fs.part_bytes("word/document.xml"),
2527            Some(b"<w:document/>".as_slice())
2528        );
2529        assert_eq!(
2530            fs.content_type_for("word/document.xml").as_deref(),
2531            Some(
2532                "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
2533            ),
2534            "the Override names /word/document.xml and must match by identity"
2535        );
2536
2537        let fs = PartFs::open(&variant_package(&[
2538            (b"[content_types].xml", TYPES),
2539            (b"_rels/.rels", PKG_RELS),
2540            (b"word/document.xml", b"<w:document/>"),
2541        ]))
2542        .expect("the lower-case [Content_Types].xml is the content types (p4)");
2543        assert_eq!(
2544            fs.content_type_for("word/document.xml").as_deref(),
2545            Some(
2546                "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
2547            )
2548        );
2549
2550        let fs = PartFs::open(&variant_package(&[
2551            (b"[Content_Types].xml", TYPES),
2552            (b"_RELS/.RELS", PKG_RELS),
2553            (b"word/document.xml", b"<w:document/>"),
2554        ]))
2555        .expect("the upper-case _RELS/.RELS is the package relationships (p5)");
2556        assert_eq!(fs.package_relationships().items.len(), 1);
2557        assert_eq!(
2558            fs.main_document_part().as_deref(),
2559            Some("word/document.xml")
2560        );
2561    }
2562
2563    /// `to_zip` of a package opened from case-variant spellings writes
2564    /// exactly one entry per identity: the reserved parts come out with
2565    /// their canonical names, an ordinary part keeps the spelling it was
2566    /// read with (#600).
2567    #[test]
2568    fn to_zip_writes_one_entry_per_identity() {
2569        let fs = PartFs::open(&variant_package(&[
2570            (b"[content_types].xml", TYPES),
2571            (b"_RELS/.RELS", PKG_RELS),
2572            (b"word/Document.xml", b"<w:document/>"),
2573        ]))
2574        .expect("case variants are the parts");
2575        let bytes = fs.to_zip().expect("one entry per identity serializes");
2576        let mut names: Vec<String> = ZipArchive::new(Cursor::new(&bytes))
2577            .unwrap()
2578            .file_names()
2579            .map(|name| name.expect("decode ZIP fixture name").into_owned())
2580            .collect();
2581        names.sort();
2582        assert_eq!(
2583            names,
2584            ["[Content_Types].xml", "_rels/.rels", "word/Document.xml"]
2585        );
2586        // … which the same open reads back under one identity.
2587        assert_eq!(
2588            PartFs::open(&bytes)
2589                .unwrap()
2590                .part_bytes("word/document.xml"),
2591            Some(b"<w:document/>".as_slice())
2592        );
2593    }
2594
2595    /// Mutation keeps one part per identity: `set_part` with a case alias
2596    /// replaces the stored part and keeps its spelling; `remove_part`
2597    /// with an alias removes it; a `.rels` alias routes to the owner's
2598    /// parsed relationships (#600).
2599    #[test]
2600    fn mutations_resolve_under_the_one_identity() {
2601        let mut fs = package_with_header_rels();
2602        fs.set_part("WORD/DOCUMENT.XML", b"replaced".to_vec());
2603        assert_eq!(fs.parts(), ["word/document.xml", "word/header1.xml"]);
2604        assert_eq!(
2605            fs.part_bytes("word/document.xml"),
2606            Some(b"replaced".as_slice()),
2607            "the alias replaced the stored part and kept its spelling"
2608        );
2609        // `_RELS/.RELS` is the package's own relationships.
2610        fs.set_part(
2611            "_RELS/.RELS",
2612            format!(r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId9" Type="{HYPERLINK}" Target="https://c.example/" TargetMode="External"/></Relationships>"#).into_bytes(),
2613        );
2614        assert_eq!(fs.package_relationships().items.len(), 1);
2615        assert_eq!(fs.package_relationships().items[0].id, "rId9");
2616        // A rels alias replaces the owner's parsed relationships.
2617        fs.set_part(
2618            "word/_RELS/HEADER1.xml.RELS",
2619            format!(r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId3" Type="{HYPERLINK}" Target="https://d.example/" TargetMode="External"/></Relationships>"#).into_bytes(),
2620        );
2621        let rels = fs
2622            .read_rels_for("WORD/header1.XML")
2623            .expect("owner resolves by identity");
2624        assert_eq!(rels.items.len(), 1);
2625        assert_eq!(rels.items[0].id, "rId3");
2626        // A `.rels` name for the package itself (any case) removes the
2627        // package's own relationships.
2628        fs.remove_part("_RELS/.rels");
2629        assert!(fs.package_relationships().items.is_empty());
2630        fs.remove_part("WORD/HEADER1.XML");
2631        assert_eq!(fs.parts(), ["word/document.xml"]);
2632        fs.remove_part("word/document.XML");
2633        assert!(fs.parts().is_empty());
2634    }
2635
2636    /// `set_part` with a `.rels` name whose XML does not parse keeps the
2637    /// raw part, and a later parseable `.rels` supersedes it — `to_zip`
2638    /// writes the parsed copy and no second entry of the one identity
2639    /// (#600).
2640    #[test]
2641    fn a_raw_rels_part_is_superseded_by_parsed_relationships() {
2642        let mut fs = package_with_header_rels();
2643        fs.set_part("word/_rels/extra.xml.rels", b"<broken".to_vec());
2644        assert_eq!(
2645            fs.part_bytes("word/_rels/extra.xml.rels"),
2646            Some(b"<broken".as_slice()),
2647            "unparseable relationship XML is kept raw"
2648        );
2649        fs.set_part(
2650            "word/_rels/extra.xml.rels",
2651            format!(r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId5" Type="{HYPERLINK}" Target="https://e.example/" TargetMode="External"/></Relationships>"#).into_bytes(),
2652        );
2653        assert_eq!(
2654            fs.part_bytes("word/_rels/extra.xml.rels"),
2655            None,
2656            "the parsed copy supersedes the raw part"
2657        );
2658        assert_eq!(
2659            fs.read_rels_for("word/extra.xml").unwrap().items[0].id,
2660            "rId5"
2661        );
2662        fs.to_zip()
2663            .expect("one entry of the rels identity serializes");
2664    }
2665
2666    /// The identity a part or owner name resolves to: the part a
2667    /// relationship target names (leading slashes and `.`/`..` segments
2668    /// resolved), compared under ASCII case (#600).
2669    #[test]
2670    fn identity_resolves_like_a_relationship_target() {
2671        assert_eq!(identity("word/document.xml"), "word/document.xml");
2672        assert_eq!(identity("/word/Document.xml"), "word/document.xml");
2673        assert_eq!(identity("WORD/document.xml"), "word/document.xml");
2674        assert_eq!(identity("word/./document.xml"), "word/document.xml");
2675        assert_eq!(identity("word/../word/document.xml"), "word/document.xml");
2676        assert_eq!(identity(""), "");
2677    }
2678
2679    /// `to_zip` must not write two entries of one identity: a raw part
2680    /// whose name aliases a rels path (or the reserved names) is
2681    /// `DUPLICATE_PART`, not a broken archive (#600).
2682    #[test]
2683    fn to_zip_refuses_an_identity_collision() {
2684        let mut fs = package_with_header_rels();
2685        fs.pkg.parts.insert(
2686            "word/_rels/header1.xml.rels".to_string(),
2687            Arc::new(b"raw".to_vec()),
2688        );
2689        let err = fs
2690            .to_zip()
2691            .expect_err("the raw copy collides with the parsed one");
2692        let text = err.to_string();
2693        assert!(text.contains("DUPLICATE_PART"), "{text}");
2694        let mut fs = package_with_header_rels();
2695        fs.pkg
2696            .parts
2697            .insert("[CONTENT_TYPES].XML".to_string(), Arc::new(b"raw".to_vec()));
2698        let err = fs
2699            .to_zip()
2700            .expect_err("the raw copy collides with the reserved part");
2701        assert!(err.to_string().contains("DUPLICATE_PART"), "{err}");
2702    }
2703
2704    /// A `.rels` entry that is not a `…/_rels/….rels` path still parses:
2705    /// its owner is the part the name's stem names, and `to_zip` writes it
2706    /// back beside that root part (#600 identity coverage).
2707    #[test]
2708    fn a_root_rels_part_belongs_to_its_stem() {
2709        let rels = format!(
2710            r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="{HYPERLINK}" Target="https://f.example/" TargetMode="External"/></Relationships>"#
2711        );
2712        let bytes = variant_package(&[
2713            (b"[Content_Types].xml", TYPES),
2714            (b"_rels/.rels", PKG_RELS),
2715            (b"word/document.xml", b"<w:document/>"),
2716            (b"x.rels", rels.as_bytes()),
2717        ]);
2718        let fs = PartFs::open(&bytes).expect("a root .rels part opens");
2719        // It is relationships storage, not a part of its own.
2720        assert!(!fs.parts().iter().any(|p| p == "x.rels"));
2721        assert_eq!(fs.read_rels_for("x").unwrap().items[0].id, "rId1");
2722    }
2723
2724    /// A package without `[Content_Types].xml` names the reserved part it
2725    /// is missing, under any spelling the entry could have carried.
2726    #[test]
2727    fn a_package_without_content_types_is_part_not_found() {
2728        let bytes = variant_package(&[
2729            (b"_rels/.rels", PKG_RELS),
2730            (b"word/document.xml", b"<w:document/>"),
2731        ]);
2732        assert!(matches!(
2733            PartFs::open(&bytes),
2734            Err(OpcError::PartNotFound(name)) if name == "[Content_Types].xml"
2735        ));
2736    }
2737
2738    /// Mutations resolve under the one OPC identity everywhere: a `.rels`
2739    /// name drops its owner's parsed relationships, the
2740    /// `[Content_Types].xml` identity clears the content types, a raw
2741    /// part of a reserved identity is superseded by a parsed one, the
2742    /// relationship helpers no-op on absent owners and unknown ids, and
2743    /// a root part's relationships serialize as `_rels/<part>.rels`.
2744    #[test]
2745    fn helper_mutations_resolve_under_the_same_index() {
2746        let mut fs = package_with_header_rels();
2747        fs.remove_part("word/_rels/header1.xml.rels");
2748        assert!(fs.read_rels_for("word/header1.xml").is_none());
2749        fs.remove_part("[CONTENT_TYPES].XML");
2750        assert_eq!(fs.content_type_for("word/document.xml"), None);
2751        // Absent owners and unknown or external ids are no-ops.
2752        assert!(fs.read_rels_for("word/styles.xml").is_none());
2753        fs.remove_relationships_by_type("word/styles.xml", HYPERLINK);
2754        fs.remove_related_part("word/styles.xml", "rId1");
2755        fs.remove_related_part("word/document.xml", "rId404");
2756        fs.set_rel_target_mode_external("word/document.xml", "rId9");
2757        // Removing by type drops matching items of a part's rels or the
2758        // package's own.
2759        assert_eq!(
2760            fs.add_package_relationship(HYPERLINK, "https://g.example/"),
2761            "rId2"
2762        );
2763        fs.add_document_relationship_external("word/document.xml", HYPERLINK, "https://h.example/");
2764        fs.set_rel_target_mode_external("word/document.xml", "rId1");
2765        fs.set_rel_target_mode_external("word/document.xml", "rId77");
2766        fs.remove_package_relationships_by_type(HYPERLINK);
2767        assert!(
2768            fs.package_relationships()
2769                .items
2770                .iter()
2771                .all(|r| r.rel_type != HYPERLINK)
2772        );
2773        fs.remove_relationships_by_type("word/document.xml", HYPERLINK);
2774        assert!(
2775            fs.read_rels_for("word/document.xml")
2776                .unwrap()
2777                .items
2778                .iter()
2779                .all(|r| r.rel_type != HYPERLINK)
2780        );
2781        // An absent id inside present rels is a no-op; an internal
2782        // relationship's removal drops the part it alone targeted.
2783        fs.remove_related_part("word/document.xml", "rId404");
2784        fs.set_part("word/media/bye.png", vec![9]);
2785        let drop_id = fs.add_document_relationship("word/document.xml", "image", "media/bye.png");
2786        fs.remove_related_part("word/document.xml", &drop_id);
2787        assert_eq!(fs.part_bytes("word/media/bye.png"), None);
2788        // A `.rels` path whose owner has no rels is a no-op, as is a
2789        // parseable [Content_Types].xml over none raw part.
2790        fs.remove_part("word/_rels/styles.xml.rels");
2791        fs.set_part("[Content_Types].xml", TYPES.to_vec());
2792        // A raw [Content_Types].xml part is superseded by a parseable one.
2793        fs.set_part("[Content_Types].xml", b"<broken".to_vec());
2794        assert!(fs.part_bytes("[content_types].xml").is_some());
2795        fs.set_part("[content_types].xml", TYPES.to_vec());
2796        assert_eq!(
2797            fs.part_bytes("[Content_Types].xml"),
2798            None,
2799            "the parsed content types supersede the raw part"
2800        );
2801        // Root-part relationships serialize as `_rels/<part>.rels`.
2802        fs.set_part("x.xml", b"<x/>".to_vec());
2803        fs.add_document_relationship("x.xml", HYPERLINK, "https://i.example/");
2804        let mut names: Vec<String> = ZipArchive::new(Cursor::new(&fs.to_zip().unwrap()))
2805            .unwrap()
2806            .file_names()
2807            .map(|name| name.expect("decode ZIP fixture name").into_owned())
2808            .collect();
2809        names.sort();
2810        assert!(names.contains(&"_rels/x.xml.rels".to_string()), "{names:?}");
2811    }
2812
2813    /// A relationship Id repeated three or more times still repairs to
2814    /// one entry and reports the Id once, in the package's own rels as in
2815    /// a part's (#600 coverage of the package-level repair and the
2816    /// recorded-ids dedup).
2817    #[test]
2818    fn a_relationship_repeated_more_than_twice_is_repaired_once() {
2819        let rels = format!(
2820            r#"<Relationships xmlns="{RELS_NS}"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/><Relationship Id="rId2" Type="{HYPERLINK}" Target="https://j.example/" TargetMode="External"/><Relationship Id="rId2" Type="{HYPERLINK}" Target="https://j.example/" TargetMode="External"/><Relationship Id="rId2" Type="{HYPERLINK}" Target="https://j.example/" TargetMode="External"/></Relationships>"#
2821        );
2822        let bytes = variant_package(&[
2823            (b"[Content_Types].xml", TYPES),
2824            (b"_rels/.rels", rels.as_bytes()),
2825            (b"word/document.xml", b"<w:document/>"),
2826        ]);
2827        let fs = PartFs::open(&bytes).expect("identical repeats repair");
2828        assert_eq!(fs.package_relationships().items.len(), 2);
2829        assert_eq!(
2830            fs.repaired_duplicate_ids(),
2831            [
2832                (String::new(), "rId1".to_string()),
2833                (String::new(), "rId2".to_string())
2834            ]
2835        );
2836    }
2837}
2838
2839#[cfg(test)]
2840#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2841mod bounded_input_tests {
2842    use super::*;
2843    use crate::admission::{InputLimits, limit_test_support as fixture};
2844
2845    fn refuses(limits: InputLimits, detail: &str) {
2846        let bytes = fixture::package();
2847        let text = PartFs::open_within(&bytes, limits)
2848            .err()
2849            .expect("over-budget package must be refused")
2850            .to_string();
2851        assert!(text.contains("INPUT_LIMIT"), "{text}");
2852        assert!(text.contains(detail), "{text}");
2853    }
2854    #[test]
2855    fn compressed_limit() {
2856        refuses(fixture::compressed(), "input is");
2857    }
2858    #[test]
2859    fn count_limit() {
2860        refuses(fixture::count(), "3 ZIP entries; the limit is 2");
2861    }
2862    #[test]
2863    fn part_limit() {
2864        refuses(fixture::part(), "a.bin");
2865    }
2866    #[test]
2867    fn aggregate_limit() {
2868        refuses(fixture::total(), "the package limit is 160");
2869    }
2870    #[test]
2871    fn exact_budget_control() {
2872        let bytes = fixture::package();
2873        assert!(PartFs::open_within(&bytes, fixture::limits()).is_ok());
2874    }
2875}
2876
2877#[cfg(test)]
2878#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2879mod zip32_tests {
2880    use super::*;
2881    use zip::ZipArchive;
2882
2883    /// `(name, local version-needed, central version-needed, local extra
2884    /// length, central extra length)` for every entry, read from the raw
2885    /// headers — the local field at +4 (APPNOTE 4.3.7), the central one at
2886    /// +6 (APPNOTE 4.3.12).
2887    fn header_versions(bytes: &[u8]) -> Vec<(String, u16, u16, u16, u16)> {
2888        let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap();
2889        (0..archive.len())
2890            .map(|i| {
2891                let entry = archive.by_index(i).unwrap();
2892                let local_at = usize::try_from(entry.header_start()).unwrap();
2893                let central_at = usize::try_from(entry.central_header_start()).unwrap();
2894                let u16_at = |at: usize| u16::from_le_bytes([bytes[at], bytes[at + 1]]);
2895                (
2896                    entry.name().unwrap().into_owned(),
2897                    u16_at(local_at + 4),
2898                    u16_at(central_at + 6),
2899                    u16_at(local_at + 28),
2900                    u16_at(central_at + 30),
2901                )
2902            })
2903            .collect()
2904    }
2905
2906    /// ZIP-10 (#604): `to_zip` writes Deflated entries, and a Deflated
2907    /// entry's version-needed is 20 (zip's `get_version_needed`), in both
2908    /// headers — never a hardcoded value, never the 45 a ZIP64 record
2909    /// carries. No extra fields means no 0x0001 ZIP64 field, and no ZIP64
2910    /// end record or locator follows.
2911    #[test]
2912    fn to_zip_entries_carry_version_20_and_no_zip64() {
2913        let mut fs = PartFs::open(&crate::admission::zip_names::docx_package("", &[])).unwrap();
2914        fs.set_part("word/media/logo.png", vec![7u8; 300]);
2915        let bytes = fs.to_zip().unwrap();
2916        let versions = header_versions(&bytes);
2917        assert!(versions.len() >= 4, "{versions:?}");
2918        for (name, local, central, local_extra, central_extra) in &versions {
2919            assert_eq!(
2920                (*local, *central),
2921                (20, 20),
2922                "{name}: a Deflated entry needs version 20 in both headers"
2923            );
2924            assert_eq!(
2925                (*local_extra, *central_extra),
2926                (0, 0),
2927                "{name}: no extra fields means no 0x0001 ZIP64 field"
2928            );
2929        }
2930        assert!(
2931            !bytes
2932                .windows(4)
2933                .any(|w| w == b"PK\x06\x06" || w == b"PK\x06\x07"),
2934            "no ZIP64 end record or locator"
2935        );
2936    }
2937
2938    /// The version-needed values differ by what the entry is, which is why
2939    /// no assertion may hardcode 20 (ZIP-10/#604): a Stored file needs 10
2940    /// (zip's `MIN_VERSION`), a Stored directory needs 20
2941    /// (`get_version_needed` raises a directory to 20), and a forced
2942    /// `large_file(true)` entry needs 45 and carries the 0x0001 ZIP64
2943    /// field — the record shape `zip32_plan` refuses to emit.
2944    #[test]
2945    fn version_needed_distinguishes_stored_deflate_and_zip64() {
2946        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
2947        let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
2948        writer.start_file("stored.bin", stored).unwrap();
2949        writer.write_all(b"raw").unwrap();
2950        writer.add_directory("dir/", stored).unwrap();
2951        writer
2952            .start_file(
2953                "wide.bin",
2954                SimpleFileOptions::default()
2955                    .compression_method(CompressionMethod::Stored)
2956                    .large_file(true),
2957            )
2958            .unwrap();
2959        writer.write_all(b"wide").unwrap();
2960        let bytes = writer.finish().unwrap().into_inner();
2961        let versions = header_versions(&bytes);
2962        let find = |name: &str| {
2963            versions
2964                .iter()
2965                .find(|(n, ..)| n == name)
2966                .unwrap_or_else(|| panic!("{name} in {versions:?}"))
2967        };
2968        let (_, local, central, ..) = find("stored.bin");
2969        assert_eq!((*local, *central), (10, 10), "a Stored file needs 10");
2970        let (_, local, central, ..) = find("dir/");
2971        assert_eq!(
2972            (*local, *central),
2973            (20, 20),
2974            "a Stored directory needs 20, not 10"
2975        );
2976        let (_, local, central, local_extra, central_extra) = find("wide.bin");
2977        assert_eq!((*local, *central), (45, 45), "a ZIP64 entry needs 45");
2978        assert!(
2979            *local_extra > 0 && *central_extra > 0,
2980            "a forced ZIP64 entry carries the 0x0001 field"
2981        );
2982    }
2983}
2984
2985#[cfg(test)]
2986#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2987mod package_branch_tests {
2988    use super::*;
2989    use std::io::{Read, Write};
2990
2991    const PKG_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
2992    const R_IMAGE: &str =
2993        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
2994    const R_LINK: &str =
2995        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
2996
2997    fn fixture() -> Vec<u8> {
2998        include_bytes!("../../../../tests/fixtures/redline/original.docx").to_vec()
2999    }
3000
3001    /// `docx` with entry `name` holding `data` instead.
3002    fn with_entry(docx: &[u8], name: &str, data: &str) -> Vec<u8> {
3003        let mut archive = zip::ZipArchive::new(Cursor::new(docx)).unwrap();
3004        let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
3005        let options = zip::write::SimpleFileOptions::default();
3006        for i in 0..archive.len() {
3007            let mut entry = archive.by_index(i).unwrap();
3008            let entry_name = entry.name().unwrap().to_string();
3009            let mut bytes = Vec::new();
3010            entry.read_to_end(&mut bytes).unwrap();
3011            writer.start_file(entry_name.as_str(), options).unwrap();
3012            if entry_name == name {
3013                writer.write_all(data.as_bytes()).unwrap();
3014            } else {
3015                writer.write_all(&bytes).unwrap();
3016            }
3017        }
3018        writer.finish().unwrap().into_inner()
3019    }
3020
3021    fn rels(items: &[(&str, &str, &str)]) -> String {
3022        let mut xml = format!("<Relationships xmlns=\"{PKG_NS}\">");
3023        for (id, ty, target) in items {
3024            xml.push_str(&format!(
3025                "<Relationship Id=\"{id}\" Type=\"{ty}\" Target=\"{target}\"/>"
3026            ));
3027        }
3028        xml + "</Relationships>"
3029    }
3030
3031    #[test]
3032    fn rel_targets_are_relative_only_inside_the_source_folder() {
3033        assert_eq!(
3034            relative_rel_target("/word/document.xml", "/word/media/a.png"),
3035            "media/a.png"
3036        );
3037        assert_eq!(
3038            relative_rel_target("word/document.xml", "media/a.png"),
3039            "/media/a.png"
3040        );
3041        assert_eq!(
3042            relative_rel_target("document.xml", "media/a.png"),
3043            "/media/a.png"
3044        );
3045    }
3046
3047    #[test]
3048    fn metadata_roots_must_be_one_element_in_their_namespace() {
3049        let ok = format!("<Relationships xmlns=\"{PKG_NS}\"/>");
3050        assert_eq!(
3051            metadata_document(ok.as_bytes(), "Relationships", PKG_NS),
3052            Ok(())
3053        );
3054        // A syntax error is left to the record reader that follows.
3055        assert_eq!(
3056            metadata_document(b"<Relationships", "Relationships", PKG_NS),
3057            Ok(())
3058        );
3059        let prefixed = format!("<r:Relationships xmlns:r=\"{PKG_NS}\"/>");
3060        assert_eq!(
3061            metadata_document(prefixed.as_bytes(), "Relationships", PKG_NS),
3062            Ok(())
3063        );
3064        for (xml, why) in [
3065            ("<Types/>", "is not Relationships"),
3066            ("<Relationships/><Relationships/>", "multiple XML roots"),
3067            ("<r:Relationships/>", "prefix is not bound"),
3068            ("<r:Relationships xmlns:r=\"urn:other\"/>", "namespace"),
3069            ("<!DOCTYPE r><Relationships/>", "DTD"),
3070        ] {
3071            let err = metadata_document(xml.as_bytes(), "Relationships", PKG_NS).unwrap_err();
3072            assert!(err.contains(why), "{xml}: {err}");
3073        }
3074    }
3075
3076    #[test]
3077    fn repeated_relationship_ids_are_kept_once_or_refused() {
3078        let docx = fixture();
3079        let name = "word/_rels/document.xml.rels";
3080        let original = PartFs::open(&docx).unwrap();
3081        let existing = original
3082            .read_rels_for("word/document.xml")
3083            .unwrap()
3084            .to_xml()
3085            .map(|x| String::from_utf8(x).unwrap())
3086            .unwrap();
3087        let mut twice = existing.clone();
3088        let one =
3089            format!("<Relationship Id=\"rId900\" Type=\"{R_IMAGE}\" Target=\"media/x.png\"/>");
3090        twice = twice.replace("</Relationships>", &format!("{one}{one}</Relationships>"));
3091        let repaired = PartFs::open(&with_entry(&docx, name, &twice)).unwrap();
3092        assert_eq!(repaired.repaired_duplicate_ids().len(), 1);
3093        for other in [
3094            format!("<Relationship Id=\"rId900\" Type=\"{R_LINK}\" Target=\"media/x.png\"/>"),
3095            format!("<Relationship Id=\"rId900\" Type=\"{R_IMAGE}\" Target=\"media/y.png\"/>"),
3096            format!(
3097                "<Relationship Id=\"rId900\" Type=\"{R_IMAGE}\" Target=\"media/x.png\" TargetMode=\"External\"/>"
3098            ),
3099        ] {
3100            let clash =
3101                existing.replace("</Relationships>", &format!("{one}{other}</Relationships>"));
3102            assert!(
3103                PartFs::open(&with_entry(&docx, name, &clash)).is_err(),
3104                "{other}"
3105            );
3106        }
3107    }
3108
3109    #[test]
3110    fn metadata_set_as_parts_replaces_the_parsed_copy_only_when_it_reads() {
3111        let mut pkg = PartFs::open(&fixture()).unwrap();
3112        let name = "word/_rels/document.xml.rels";
3113        pkg.set_part(name, rels(&[("rId1", R_IMAGE, "media/a.png")]).into_bytes());
3114        let read = pkg
3115            .read_rels_for("word/document.xml")
3116            .unwrap()
3117            .to_xml()
3118            .map(|x| String::from_utf8(x).unwrap())
3119            .unwrap();
3120        assert!(read.contains("media/a.png"), "{read}");
3121        pkg.set_part(name, b"<not rels".to_vec());
3122        let still = pkg
3123            .read_rels_for("word/document.xml")
3124            .unwrap()
3125            .to_xml()
3126            .map(|x| String::from_utf8(x).unwrap())
3127            .unwrap();
3128        assert!(still.contains("media/a.png"), "{still}");
3129        let before = pkg.content_type_for("/word/document.xml");
3130        pkg.set_part("[Content_Types].xml", b"<broken".to_vec());
3131        assert_eq!(pkg.content_type_for("/word/document.xml"), before);
3132        // Removing from a part with no relationships invents none.
3133        pkg.remove_relationships_by_type("word/styles.xml", R_IMAGE);
3134        assert!(pkg.read_rels_for("word/styles.xml").is_none());
3135        pkg.remove_related_part("word/styles.xml", "rId1");
3136        assert!(pkg.read_rels_for("word/styles.xml").is_none());
3137        let id = pkg.add_document_relationship_external(
3138            "word/document.xml",
3139            R_LINK,
3140            "https://example.com/",
3141        );
3142        let xml = pkg
3143            .read_rels_for("word/document.xml")
3144            .unwrap()
3145            .to_xml()
3146            .map(|x| String::from_utf8(x).unwrap())
3147            .unwrap();
3148        assert!(
3149            xml.contains(&format!("Id=\"{id}\"")) && xml.contains("TargetMode=\"External\""),
3150            "{xml}"
3151        );
3152    }
3153
3154    #[test]
3155    fn refusals_name_the_duplicate_only_for_a_readable_zip() {
3156        let err = OpcError::DuplicatePartName("word/document.xml".into());
3157        assert_eq!(refusal_message(b"not a zip", &err), err.to_string());
3158    }
3159}