odf-crypto 0.1.1

LibreOffice-faithful encryption for ODF packages (.odt, .ods, .odp): detect it, decrypt it, write it
Documentation
//! Reproduces `zip::result::ZipError`'s `Display` wording without ever
//! calling `ZipError::to_string`.
//!
//! `ZipError` is `#[non_exhaustive]` (`zip-9.1.3/src/result.rs:14`) — semver
//! protects the shape of the variants already enumerated, not that the
//! enumeration stays complete. Calling `.to_string()` on it directly would
//! flow whatever a future variant's `Display` writes straight into a public
//! `Zip(String)` payload on a plain `cargo update`, with nothing at compile
//! time to catch it. This is not hypothetical: `zip` 6.0.0 widened
//! `InvalidArchive(&'static str)` to `InvalidArchive(Cow<'static, str>)` and
//! began interpolating an archive entry name into it
//! (`"Duplicate filename: {}"`, `zip-6.0.0/src/write.rs:1061`, still present
//! at `zip-8.6.0/src/write.rs:1382`, as `{:?}` at
//! `zip-9.0.4/src/write.rs:786`, and at `zip-9.1.3/src/write.rs:883, 1182`).
//!
//! [`message`] matches every variant `zip` 9.1.3 declares and reproduces its
//! `Display` string byte for byte — pinned by a test in this module that
//! asserts `message(&e) == e.to_string()` for each one. That test is the
//! guard: it is the one that fires the day a `zip` minor release changes its
//! wording. The wildcard arm, present only because `#[non_exhaustive]`
//! requires one, contributes no text of its own.
//!
//! **The one deliberate departure is an owned `InvalidArchive`.** Through
//! 0.1.0-rc.10 this crate was on `zip` 2.4.2, where both string payloads were
//! `&'static str`, and the arms bound them with an explicit
//! `let s: &'static str = s;` so that the widening `zip` 6.0.0 made would be
//! a compile error here rather than a silent quote of package-controlled
//! text. Checked rather than reasoned about at the time — the binding
//! compiled against `&'static str` and failed against `Cow<'static, str>`
//! with `lifetime may not live long enough` — and it fired exactly so on the
//! move to 8.6.0 (and on 2.6.1, which made the same change; 9.0.4 and 9.1.3
//! are the same again). The answer is
//! to split on the `Cow` rather than drop the guard: `Cow::Borrowed` holds a
//! `&'static str`, which in `zip` is a literal, so it is quoted (the binding
//! still forces `'static`); `Cow::Owned` was formatted at run time — e.g.
//! `"Extra field {} header truncated"` (`zip-9.1.3/src/extra_fields/extra_field.rs:106`) — and
//! gets the variant's fixed prefix only. That is the one place `message`
//! and `Display` intentionally differ, and a test pins it.

use std::borrow::Cow;
use zip::result::ZipError;

/// Formats `err` the way `zip` 9.1.3's `Display` impl does, except that an
/// owned `InvalidArchive` message is not quoted.
///
/// Every call site in this crate that turns a `ZipError` into one of the
/// three `Zip(String)` payloads (`DetectError`, `DecryptError`,
/// `EncryptError`) goes through this function instead of `ZipError`'s own
/// `Display`. See the module doc for why.
pub(crate) fn message(err: &ZipError) -> String {
    match err {
        ZipError::Io(io_err) => format!("i/o error: {io_err}"),
        ZipError::InvalidArchive(Cow::Borrowed(s)) => {
            let s: &'static str = s;
            format!("invalid Zip archive: {s}")
        }
        ZipError::InvalidArchive(Cow::Owned(_)) => "invalid Zip archive".to_string(),
        ZipError::UnsupportedArchive(s) => {
            let s: &'static str = s;
            format!("unsupported Zip archive: {s}")
        }
        ZipError::FileNotFound => "specified file not found in archive".to_string(),
        ZipError::InvalidPassword => "provided password is incorrect".to_string(),
        ZipError::CompressionMethodNotSupported(id) => {
            format!("compression method not supported: {id}")
        }
        // Added in 9.1.0 for `ExtractOptions::size_limit`, which this crate
        // never sets, so neither is reachable here. Both quote only numbers.
        ZipError::DecompressedSizeLimitExceeded { size, limit } => {
            format!("decompressed size {size} exceeds limit {limit}")
        }
        ZipError::DecompressedSizeUnknown => {
            "decompressed size is unknown, so a size limit cannot be checked".to_string()
        }
        _ => "zip error (unrecognized variant)".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::message;
    use std::borrow::Cow;
    use std::io;
    use zip::result::ZipError;

    /// Methods whose `Result` carries a [`ZipError`] in `zip` 9.1.3, plus
    /// `classify::open_archive`, which every read path opens through.
    const ZIP_RETURNING: [&str; 6] = [
        "ZipArchive::new",
        "open_archive(",
        ".by_index(",
        ".by_name(",
        ".start_file(",
        ".finish()",
    ];

    /// `include_str!` resolves against this file at compile time, so these do
    /// not depend on the directory the tests are run from, and they are plain
    /// text -- the gated modules are readable here even in a detection-only
    /// build, so this guard runs in every feature configuration.
    ///
    /// The streaming modules were missing until rc.15, although every archive
    /// `decrypt`, `encrypt` and `reencrypt_to` reads has been opened in them
    /// since the streaming arc moved those opens there.
    const SOURCES: [(&str, &str); 8] = [
        ("classify.rs", include_str!("classify.rs")),
        ("decrypt.rs", include_str!("decrypt.rs")),
        ("decrypt_entries.rs", include_str!("decrypt_entries.rs")),
        ("decrypt_stream.rs", include_str!("decrypt_stream.rs")),
        ("encrypt.rs", include_str!("encrypt.rs")),
        ("encrypt_stream.rs", include_str!("encrypt_stream.rs")),
        ("reencrypt.rs", include_str!("reencrypt.rs")),
        ("zip_stream.rs", include_str!("zip_stream.rs")),
    ];

    /// The invariant the module exists for: no `ZipError` reaches a
    /// `Zip(String)` payload through its own `Display`.
    ///
    /// Fidelity is pinned by
    /// [`message_matches_display_for_every_known_variant`], but fidelity is not
    /// routing: before this test, reverting any of the call sites to
    /// `e.to_string()` left the whole suite green, clippy clean in all three
    /// configurations, and the headline claim silently false. A misrouted site
    /// cannot be caught by the compiler either, because `ZipError` and
    /// `io::Error` both implement `Display`.
    ///
    /// Scanning source text is blunt, and deliberately so: the property is
    /// syntactic. Broken on purpose to prove it fires -- restoring one
    /// `decrypt.rs` site to `DecryptError::Zip(e.to_string())` failed this test
    /// and nothing else in the suite.
    #[test]
    fn every_ziperror_site_routes_through_message() {
        for (name, src) in SOURCES {
            let lines: Vec<&str> = src.lines().collect();
            for (i, line) in lines.iter().enumerate() {
                if !ZIP_RETURNING.iter().any(|m| line.contains(m)) {
                    continue;
                }
                // Check ONLY this call's own `map_err`, which is on its line or
                // the next one or two. A fixed multi-line window is wrong here
                // and was caught failing on a clean tree: in `rebuild_zip` a
                // routed `start_file` is followed immediately by a `write_all`
                // that correctly keeps `to_string()`, so a window wide enough
                // to reach the next statement reads the neighbour's io::Error
                // conversion as this one's. The alternating trap catches the
                // guard as readily as the edit.
                let Some(conv) = lines[i..(i + 3).min(lines.len())]
                    .iter()
                    .find(|l| l.contains(".map_err("))
                else {
                    continue; // the error is discarded, not stringified
                };
                assert!(
                    !(conv.contains("::Zip(") && conv.contains(".to_string()")),
                    "{name}:{} converts a ZipError with its own Display; route it \
                     through zip_err::message instead:\n  {}",
                    i + 1,
                    line.trim()
                );
            }
        }
    }

    /// The wildcard arm is the whole point of the module and the one arm no
    /// test can reach: `#[non_exhaustive]` means an unknown variant cannot be
    /// constructed here to exercise it. So the guard is on the source instead
    /// -- it must not interpolate the error it was given.
    #[test]
    fn wildcard_arm_contributes_no_text_of_its_own() {
        let src = include_str!("zip_err.rs");
        let arm = src
            .lines()
            .find(|l| l.trim_start().starts_with("_ =>"))
            .expect("message() must keep a wildcard arm; #[non_exhaustive] requires one");
        // Testing for the substring "err" was the obvious check and was wrong:
        // the arm's own literal says "zip error", so it matched itself and the
        // guard passed only by accident. The property is that the arm does not
        // *interpolate* — `_` binds nothing, so quoting an unknown variant
        // takes a named binding and a format, and both need `format!`/`{`.
        assert!(
            !arm.contains("format!") && !arm.contains('{'),
            "the wildcard arm must not quote an unknown variant's Display: {}",
            arm.trim()
        );
    }

    /// Pins `message` to `ZipError`'s own `Display` for every variant `zip`
    /// 9.1.3 declares, with `InvalidArchive` in its borrowed form. Broken on
    /// purpose once to prove it fires (CLAUDE.md: "test the guard by breaking
    /// the thing it guards") — deleting the `FileNotFound` arm's string made
    /// this fail, as expected, and it was restored.
    #[test]
    fn message_matches_display_for_every_known_variant() {
        let cases = [
            ZipError::Io(io::Error::other("disk exploded")),
            ZipError::InvalidArchive(Cow::Borrowed("bad local file header")),
            ZipError::UnsupportedArchive("zip64 not supported"),
            ZipError::FileNotFound,
            ZipError::InvalidPassword,
            ZipError::CompressionMethodNotSupported(99),
            ZipError::DecompressedSizeLimitExceeded { size: 7, limit: 3 },
            ZipError::DecompressedSizeUnknown,
        ];
        for case in cases {
            assert_eq!(message(&case), case.to_string());
        }
    }

    /// An owned `InvalidArchive` was formatted at run time and may carry
    /// package-controlled text, so `message` keeps the prefix and drops the
    /// payload -- the one place it departs from `Display` on purpose.
    #[test]
    fn an_owned_invalid_archive_message_is_not_quoted() {
        let e = ZipError::InvalidArchive(Cow::Owned("Duplicate filename: EVIL".into()));
        assert_eq!(message(&e), "invalid Zip archive");
        assert_ne!(message(&e), e.to_string());
    }
}