Skip to main content

msoffice_crypto/
error.rs

1//! Failures from decryption and encryption.
2//!
3//! [`Error`] is re-exported at the crate root under `crypto-ops`. In a
4//! detection-only build no public function returns a [`Result`], so the type is not
5//! public there — see the enum's own docs.
6
7/// Every reason this crate refuses a file.
8///
9/// `#[non_exhaustive]`: variants are still arriving — RC4 CryptoAPI decryption (GH #4),
10/// the encrypt path (GH #6) and the encrypt guard have each added their own — and this
11/// crate's own testing rule makes consumers match on variants by name, so a wildcard arm
12/// has to be theirs to write.
13///
14/// Adding a variant therefore never fails a consumer's build. That is the hazard, not the
15/// safety: their wildcard arm silently absorbs the new case, so a variant that splits a
16/// fact they were handling changes what their code does with nothing red anywhere. The
17/// crate is published on a release-candidate line where that is permitted (see CLAUDE.md
18/// § *Project Status*), and the obligation it leaves is to name the split in the changelog
19/// as a fact.
20///
21/// Thirteen of the nineteen variants exist only under `crypto-ops`, two only under
22/// `legacy-binary`, and so does the public re-export of the type itself. In a
23/// detection-only build no public function returns a `Result` — [`crate::classify()`]
24/// answers every input and [`crate::is_cfb_office()`] is a `bool` — so the type would be a
25/// public name nothing
26/// produces. The four ungated variants are the ones the container reader constructs on
27/// the way to `classify`, which swallows them.
28///
29/// Messages never carry key material. Where a message quotes the file —
30/// [`Error::UnsupportedAlgorithm`]'s `name`, the lengths and declared values
31/// interpolated into [`Error::BadParameters`] — it is bounded and truncated at
32/// the construction site, and the variant says so. Match with a `_` arm: the enum does
33/// not implement `PartialEq`.
34///
35/// [`Error::EncryptParams`] quotes nothing either, and for a reason none of the others
36/// can claim: it is raised before any file is opened at all. Its three numbers are the
37/// caller's own arguments and this crate's own bounds, and its two enum payloads are
38/// fieldless.
39///
40/// The encrypt guard's three variants quote nothing at all.
41/// [`Error::AlreadyEncrypted`] carries [`crate::Family`] and [`crate::Document`], which
42/// are fieldless `Copy` enums from the detection half; the other two carry no payload.
43/// None of the three has a byte of the file in it, and none interpolates its payload into
44/// its message.
45///
46/// # Who the messages are written for
47///
48/// **A programmer choosing a policy, not the person holding the file.** Several name a
49/// [`crate::IntegrityPolicy`] variant, which is a Rust path and useful only to whoever
50/// writes the call. A consumer that renders a failure to an end user should **match on
51/// the variant and write its own copy**, not forward `Display`.
52///
53/// That is a real hazard rather than a style note, and it was found by a consumer reading
54/// its own test output. The three integrity failures are *not* symmetric in what their
55/// opt-out costs:
56///
57/// - [`Error::IntegrityCheckFailed`] offers none, because there is none.
58/// - [`Error::IntegrityUnavailable`]'s is a property of the **format** — a 2007 file has
59///   no tag to check, and opening it anyway concedes only what that format never offered.
60/// - [`Error::IntegrityElementMissing`]'s is "decrypt evidence of tampering anyway", on a
61///   file whose missing element is, per that variant's docs, never innocent.
62///
63/// Forwarded uniformly, the third reaches the person holding the file as instructions for
64/// opening the document an attacker prepared for them. The message says what the opt-out
65/// concedes, so that forwarding it is at worst unhelpful rather than misleading — but the
66/// fix is to map the variant, and this paragraph exists so that nobody has to discover
67/// that by reading test output a second time.
68///
69/// # What `source()` returns, and why it is mostly `None`
70///
71/// `None` for every variant except [`Error::Io`] — deliberately, and not for want of
72/// `thiserror`. The variants that wrap a foreign failure reduce it to a string instead of
73/// holding it behind `#[source]`. Holding it would reopen, in two places rather than one,
74/// the conduit that reduction exists to close: `source()` would hand a caller the
75/// dependency's `Display`, and this enum's derived `Debug` would print it. A walkable
76/// error chain is worth less here than a message this crate can characterise completely —
77/// this type's whole input is a document an attacker wrote.
78///
79/// The three foreign failures are not treated alike, and the difference is the point:
80///
81/// | Variant | Foreign `Display` | Why |
82/// | --- | --- | --- |
83/// | [`Error::XmlParse`] | **never** — classified by an exhaustive match | quick-xml quotes text drawn from the document |
84/// | [`Error::RandomSource`] | forwarded, truncated to 200 characters | names an environment failure; on a failure nothing was generated |
85/// | [`Error::Io`] | forwarded | `cfb` 0.15.0 audited: lengths and fixed strings only |
86///
87/// [`Error::Io`] is the one `#[from]`, and it does forward `std::io::Error`'s `Display`.
88/// That is audited rather than assumed: on these paths the only producers are `cfb`,
89/// whose `invalid_data!` messages interpolate lengths and fixed strings and never a
90/// stream name or a file byte (`direntry.rs:122-140` in 0.15.0; the messages 0.15 added
91/// interpolate only sector numbers and counts, and its two `OutOfMemory` errors are fixed
92/// strings, `stream.rs:184-207`), and `std::io::Cursor`, which fails only on allocation. **Re-check it on a `cfb` bump** — that is the standing
93/// cost of a `#[from]` on a foreign error type, and the reason there is only one.
94// `unreachable_pub` fires on this type in the **detection** build and only there: the
95// re-export at `lib.rs` is `#[cfg(feature = "crypto-ops")]`, so without that feature this
96// is a `pub` item in a private module that nothing re-exports. That is the design the doc
97// above describes, not an oversight — the type is the crate's public error under
98// `crypto-ops` and `legacy-binary`, and `pub(crate)` would delete it from the public API.
99//
100// `allow` rather than `expect`: the lint fires in one of the three configurations, so an
101// `expect` would itself go unfulfilled in the other two.
102#[allow(unreachable_pub)]
103#[derive(Debug, thiserror::Error)]
104#[non_exhaustive]
105pub enum Error {
106    /// The bytes are not a CFB container: they lack the eight-byte magic, or `cfb`
107    /// refused to open them.
108    #[error("not a CFB (Compound Binary File) container")]
109    #[cfg(feature = "crypto-ops")]
110    NotACfbFile,
111
112    /// A binary document handed to [`crate::decrypt_binary_office()`] carries no password-to-open
113    /// at all: the FIB's `fEncrypted` bit is clear, the workbook has no `FILEPASS`
114    /// record, the presentation's `UserEditAtom` is the unencrypted shape.
115    ///
116    /// Its own variant, per CLAUDE.md § *Cryptographic Rules*: "there is nothing to
117    /// decrypt" is a fact a caller acts on by using the bytes it already has, which is
118    /// the opposite of what it does for every other variant here. [`crate::classify()`]
119    /// reports the same file as [`crate::Family::Unencrypted`] wherever its own probe
120    /// reached the marker; a workbook whose record walk ran out before proving anything is
121    /// [`crate::Family::Unknown`] there — `Unencrypted` is a proof, not a default — while
122    /// this path still answers `NotEncrypted`.
123    #[error("the document is not encrypted; there is nothing to decrypt")]
124    #[cfg(feature = "legacy-binary")]
125    NotEncrypted,
126
127    /// A required CFB stream is missing, unreadable, shorter than its header — or
128    /// carries a fixed structural field this crate cannot proceed past.
129    ///
130    /// The payload names the stream or the structure (`"EncryptionInfo"`, `"Workbook"`,
131    /// `"EncryptionVerifier missing or truncated"`, …). It is always a fixed
132    /// `&'static str`, never attacker-chosen file content.
133    #[error("required CFB stream missing or unreadable: {0}")]
134    MissingStream(&'static str),
135
136    /// The `EncryptionInfo` version pair names a format this crate does not implement.
137    ///
138    /// The message says only that, because that is all the pair tells us. It used to
139    /// assert "Office XP/2003 RC4 encryption is not supported — re-save the file with
140    /// Office 2007 or later" for *every* pair that reached it, including `vMinor = 3`
141    /// (extensible encryption) and, until `standard::aes_key_bits` landed (as
142    /// `require_aes_128`, which is what it was called then), every
143    /// Office 2007 file whose `AlgID` was the conforming `0x660E`. A cipher this crate
144    /// has not implemented is [`Error::UnsupportedAlgorithm`]; this variant is
145    /// for the version pair alone.
146    #[error(
147        "unsupported Office encryption version {0}.{1} \
148        (this crate implements ECMA-376 standard encryption, vMinor 2, \
149        and agile encryption, 4.4)"
150    )]
151    #[cfg(feature = "crypto-ops")]
152    UnsupportedEncryptionVersion(u16, u16),
153
154    /// The agile `EncryptionInfo` XML could not be parsed, or a required attribute was
155    /// absent.
156    ///
157    /// Distinct from [`Self::BadParameters`]: that one is a value that parsed and is
158    /// out of range; this one is XML that did not yield a value at all.
159    ///
160    /// **The string is always one this crate wrote.** No dependency's `Display` reaches
161    /// it: `agile::xml_error` and `agile::base64_error` classify quick-xml and base64
162    /// failures into fixed descriptions, and both match exhaustively, so a variant added
163    /// upstream is a compile error here rather than a silent forward.
164    ///
165    /// That is a correction and not a description of how it always was. Until
166    /// 2026-09-11 the quick-xml `Display` was forwarded verbatim by four call sites, three
167    /// of which run on attribute *values* — `saltValue`, `encryptedKeyValue` and the two
168    /// verifier blobs. quick-xml quotes the text between `&` and the next `;` of whatever
169    /// it is unescaping, so a crafted `encryptedKeyValue` put its own text here, bounded
170    /// only by `limits::ENCRYPTION_INFO_READ_CAP` — 1 MiB. Not key material, since the
171    /// attacker supplies the text, but unbounded attacker-chosen content in an error
172    /// string is the thing [`Error::UnsupportedAlgorithm`] truncates to 32 characters and
173    /// documents doing. Found by the downstream consumer, reading this file.
174    ///
175    /// The guard is
176    /// `malformed_input::a_hostile_entity_in_an_attribute_value_never_reaches_the_error_message`,
177    /// with a well-formed-value control beside it; reverting `xml_error` to
178    /// `e.to_string()` fails it with a 4609-byte message quoting 4608 bytes of the file.
179    #[error("EncryptionInfo XML parse error: {0}")]
180    #[cfg(feature = "crypto-ops")]
181    XmlParse(String),
182
183    /// The password verifier did not match.
184    ///
185    /// Distinct from [`Self::UnsupportedAlgorithm`] on purpose: that one is a file this
186    /// crate cannot act on, and reporting it as a wrong password sends the user looking
187    /// for a typo in a password that was right.
188    #[error("wrong password")]
189    #[cfg(feature = "crypto-ops")]
190    WrongPassword,
191
192    /// An AES operation rejected its input.
193    ///
194    /// Typically a ciphertext length that is not a block multiple — a truncated stream,
195    /// not a wrong password. The encrypt path reaches it only if an internal length
196    /// invariant fails.
197    #[error("cipher operation failed")]
198    #[cfg(feature = "crypto-ops")]
199    CipherError,
200
201    /// A value the file declares is out of range, or disagrees with another it declares.
202    ///
203    /// `field` names it in the specification's spelling and `problem` says what is wrong,
204    /// with the value the file declares and what was allowed. **No byte of the file is in
205    /// it**: every payload is a fieldless enum or an integer, so a caller may match on it
206    /// and quote its numbers. Until 0.1.0-rc.9 this was a `String`.
207    ///
208    /// Contrast [`Error::UnsupportedAlgorithm`], which is the file being
209    /// internally consistent about something this crate has not implemented, and
210    /// [`Error::InvariantViolated`], which is a fault of this crate's.
211    #[error("{field} {problem}")]
212    #[cfg(feature = "crypto-ops")]
213    BadParameters {
214        /// Which field.
215        field: crate::FileField,
216        /// What is wrong with it.
217        problem: crate::FileProblem,
218    },
219
220    /// An invariant of this crate's failed: something upstream should have refused the
221    /// input first. Reaching it is a bug here, not a property of the file, so it is not
222    /// [`Error::BadParameters`] (which it was until 0.1.0-rc.9).
223    #[error("internal invariant violated: {0}")]
224    #[cfg(feature = "crypto-ops")]
225    InvariantViolated(crate::Invariant),
226
227    /// A stream is larger than this crate reads whole: more than `limit` bytes. The
228    /// read stops one byte past the limit, so its whole size is not known.
229    ///
230    /// A measured size, not a value the file declares, so not a bad parameter (the
231    /// reasoning that moved the 1 GiB refusals to `PackageTooLarge` in 0.1.0-rc.7).
232    /// `stream` is this crate's own name for it, never the file's. Until 0.1.0-rc.9 this
233    /// was a `BadParameters` message.
234    #[error("the {stream} stream is larger than {limit} bytes, the most this crate reads")]
235    StreamTooLarge {
236        /// Which stream, as this crate names it.
237        stream: &'static str,
238        /// The most read.
239        limit: u64,
240    },
241
242    /// A legacy binary document carries encrypted content of a kind this crate does not
243    /// decrypt, so [`crate::decrypt_binary_office()`] refuses the file rather than return
244    /// one with that content still encrypted.
245    ///
246    /// The alternative is the defect this variant was added to end: until 0.1.0-rc.6 a
247    /// `.ppt`'s pictures and any CryptoAPI file's encrypted properties came back as
248    /// ciphertext inside an output that looked plain, and a caller that kept only the
249    /// output lost them for good. What is decrypted now is what Office writes; what the
250    /// format permits and no Office build was measured writing — a storage inside the
251    /// encrypted summary stream, a stream there other than the two property sets, a
252    /// blip of a type [MS-ODRAW] does not define, a file-block entry — lands here. A
253    /// `Pictures` record of a type that is neither (a value the file declares) is
254    /// [`Error::BadParameters`] instead; this doc said otherwise until 0.1.0-rc.9 while
255    /// the code returned `BadParameters`.
256    ///
257    /// The payload is a fixed `&'static str` naming the kind, never file content.
258    #[error("the document holds encrypted content this crate does not decrypt: {0}")]
259    #[cfg(feature = "legacy-binary")]
260    UnsupportedEncryptedContent(&'static str),
261
262    /// The file names an algorithm this crate does not implement.
263    ///
264    /// **Distinct from [`Error::WrongPassword`] on purpose.** The password
265    /// may be perfectly correct and simply unusable: before this variant existed, an
266    /// agile file declaring `hashAlgorithm="SHA256"` derived a SHA-512 spin hash, failed
267    /// the verifier comparison, and was reported as a wrong password — telling the user
268    /// the one thing that was not true. `office-crypto` already returned a dedicated
269    /// `Unimplemented` here (`src/lib.rs:29`), so silently misdiagnosing was strictly
270    /// worse than the alternative this crate exists to improve on.
271    ///
272    /// `what` names the attribute — a fixed set of `&'static str`, never formatted, so
273    /// this cannot become a second free-text channel. `name` is closed too
274    /// ([`crate::AlgorithmName`]): a name the specification defines, or an unknown name
275    /// by its length alone. Until 0.1.0-rc.9 it was the file's own spelling, truncated
276    /// to 32 characters.
277    ///
278    /// # This refusal is authorised by the format, which is a third thing
279    ///
280    /// Not a spec violation and not merely an implementation limit. [MS-OFFCRYPTO]
281    /// §2.3.4.10, immediately after the `HashAlgorithm` table that lists MD5, MD4, MD2,
282    /// RIPEMD-128, RIPEMD-160 and WHIRLPOOL alongside the SHA family: **"Values that are
283    /// not defined MAY be used, and a compliant implementation is not required to support
284    /// all defined values."**
285    ///
286    /// So a document naming WHIRLPOOL is conforming, this crate refusing it is
287    /// conforming, and both are true at once. A consumer rendering this has three
288    /// sentences available and should not collapse them:
289    ///
290    /// | | what the format says |
291    /// | --- | --- |
292    /// | a spec violation | the file is wrong |
293    /// | an implementation limit | the format permits it; *we could* and chose not to, so an override is coherent |
294    /// | **this** | the format permits the value **and permits us not to support it** |
295    ///
296    /// The third is not a weaker form of the second. An override is not a coherent thing
297    /// to offer, because there is nothing to override — the format contemplated the
298    /// refusal.
299    ///
300    /// Worth contrasting with the `spinCount` ceiling, which looked like the same shape
301    /// and was not: the spec states a maximum there and carries no clause permitting a
302    /// narrower one, so this crate's tighter bound was a defect and was removed. Here the
303    /// clause exists. Whether to add the older hashes is a support decision; it is not a
304    /// conformance one, and the difference is this sentence.
305    #[error("{what} names an algorithm this crate does not implement: {name}")]
306    #[cfg(feature = "crypto-ops")]
307    UnsupportedAlgorithm {
308        /// Which attribute named it, e.g. `p:encryptedKey/@hashAlgorithm`.
309        what: &'static str,
310        /// What was named: a known algorithm, an unknown name's length, an `AlgID`, or a
311        /// fixed description of what was refused. Never text the file chose.
312        name: crate::AlgorithmName,
313    },
314
315    /// The `dataIntegrity` HMAC did not match the `EncryptedPackage` stream.
316    ///
317    /// The password is verified before this check runs, so a failure here means the
318    /// package was corrupted or modified — by someone who did *not* hold the password,
319    /// since producing a matching tag requires the session key.
320    #[error(
321        "package integrity check failed: the encrypted package does not match its \
322        dataIntegrity HMAC (the file is corrupt or was modified after encryption)"
323    )]
324    #[cfg(feature = "crypto-ops")]
325    IntegrityCheckFailed,
326
327    /// A file declaring **agile** encryption carries no `<dataIntegrity>` element, under
328    /// a policy that requires one — which since GH #12 includes the default policy.
329    ///
330    /// Distinct from [`Self::IntegrityUnavailable`] on purpose, per CLAUDE.md
331    /// § *Cryptographic Rules*: that one is a caller asking a format for a guarantee the
332    /// format does not define, a property of the **request**. This one is a file that
333    /// should carry a tag and does not, a property of the **file** — and deleting the
334    /// element is the cheapest tamper there is, needing no password. A caller acts on
335    /// the two differently, so they are different variants.
336    ///
337    /// The message names the opt-out, because at least one consumer flattens this error
338    /// to its `Display` string and a dead end is a worse answer than a signposted one.
339    /// The `Display` text names [`crate::IntegrityPolicy`]'s opt-out in plain words
340    /// because a `#[error]` string cannot carry an intra-doc link.
341    ///
342    /// **This is the one opt-out in the enum that concedes something a caller should not
343    /// concede lightly**, and the message therefore carries its cost rather than only its
344    /// name. [`Self::IntegrityCheckFailed`] offers no way out because none exists, and
345    /// [`Self::IntegrityUnavailable`]'s is a limit of the format; this one is "accept a
346    /// file whose tamper-evidence was deleted", on a file where — see above — the deletion
347    /// is never innocent. A consumer that forwards `Display` to an end user forwards that
348    /// too. See the enum's own docs: render integrity failures by matching the variant.
349    #[error(
350        "this file declares agile encryption but carries no <dataIntegrity> element: \
351        every known agile writer emits one, so it was removed or the file is malformed. \
352        IntegrityPolicy::VerifyIfPresent decrypts it unverified, which accepts a file \
353        whose tamper-evidence is absent"
354    )]
355    #[cfg(feature = "crypto-ops")]
356    IntegrityElementMissing,
357
358    /// An integrity guarantee was demanded of a format that defines no integrity tag at
359    /// all — `IntegrityPolicy::Require` on ECMA-376 standard encryption (Office 2007).
360    ///
361    /// An *agile* file missing its element is [`Self::IntegrityElementMissing`] instead:
362    /// that is a defect in the file, this is a limit of the format. The two want different
363    /// words in front of a user — "this format cannot prove it was not modified" against
364    /// "this file's proof was removed" — which is the whole reason they are two variants.
365    ///
366    /// Like that sibling, the message names the way out, because a consumer flattens this
367    /// to its `Display`. Measured at one: the string reaches a user as *"integrity
368    /// verification was required, but ECMA-376 standard encryption (Office 2007) defines
369    /// no integrity element…"*, and a message that states the problem without the remedy
370    /// is a dead end where a signposted one costs nothing.
371    ///
372    /// Both this variant and [`crate::IntegrityPolicy`] exist only under `crypto-ops`,
373    /// so the link resolves in every configuration that renders it.
374    #[error("integrity verification was required, but {0}")]
375    #[cfg(feature = "crypto-ops")]
376    IntegrityUnavailable(&'static str),
377
378    /// The random source failed while generating key material.
379    ///
380    /// Its own variant rather than folding into [`Self::CipherError`], per CLAUDE.md
381    /// § *Cryptographic Rules*: a CSPRNG that will not produce bytes is an environment
382    /// failure a caller may be able to act on — a sandbox with no `getrandom`, an
383    /// exhausted file-descriptor table — and it is emphatically **not** the same fact as
384    /// "the cipher rejected this input". Encryption is the only path that reaches it;
385    /// decryption generates nothing.
386    ///
387    /// The string is the RNG's own `Display`, which describes *the source* — never its
388    /// output. No generated byte can reach here: on failure there is nothing generated.
389    /// Truncated to 200 characters at the construction site, `agile_encrypt::random_source`,
390    /// which explains why this one foreign `Display` is forwarded where
391    /// [`Self::XmlParse`]'s is not.
392    #[error("the random source failed while generating key material: {0}")]
393    #[cfg(feature = "crypto-ops")]
394    RandomSource(String),
395
396    /// A caller asked an encrypt entry point for encryption parameters this crate will
397    /// not write.
398    ///
399    /// **This is a caller error, raised before a single byte of any document has been
400    /// examined.** Nothing in it describes the input, so a consumer that renders it as
401    /// "your document is damaged" tells the holder of a perfectly good file that their
402    /// file is broken. Often there is no file yet: the parameters are validated at the
403    /// top of the call, ahead of the container sniff that produces
404    /// [`Self::AlreadyEncrypted`] and its siblings. The remedy is always to change the
405    /// argument, never to change the document — which is why this variant maps to the
406    /// CLI's usage exit code and not to any of its file codes.
407    ///
408    /// Distinct from [`Self::BadParameters`], and the distinction is *whose number it
409    /// is*. `BadParameters` is a value the **file** declares about itself, arriving out
410    /// of an attacker-supplied `EncryptionInfo` stream; this is a value the **caller**
411    /// passed in. They are raised at opposite ends of the crate and acted on by different
412    /// people — one by whoever chose the file, one by whoever wrote the call — so
413    /// collapsing them would hand a programmer's mistake to an end user as a verdict on
414    /// their document.
415    ///
416    /// **No file byte can reach this variant.** `got`, `min` and `max` are `u32`s the
417    /// caller supplied or that this crate's own `limits` module holds, and `param` and
418    /// `problem` are fieldless `Copy` enums. There is deliberately no `String` field, the
419    /// shape `BadParameters` took too in 0.1.0-rc.9: a free-text channel invites the
420    /// file-content-in-a-message defect [`Self::XmlParse`] documents having had.
421    ///
422    /// # Why the problem is a second enum rather than part of the first
423    ///
424    /// [`EncryptParamProblem`] is `src/limits.rs`'s own **spec / cipher / margin**
425    /// provenance taxonomy made matchable — see the table in that module's header. A
426    /// bound this crate enforces is one of three quite different kinds of fact, and until
427    /// they were labelled a consumer had to read each doc comment and infer, which one
428    /// did, got partly wrong, and had to ask about. Reporting a *margin* as though it
429    /// were a spec violation is a typed lie, and a typed lie is worse than a vague
430    /// message: a consumer renders a typed fact as authoritative and tells its user the
431    /// format forbids something the format permits.
432    /// [`EncryptParamProblem::ExceedsImplementationLimit`] exists so that never has to
433    /// happen.
434    #[error(
435        "encryption parameter rejected before any file was read: {param} {problem} \
436        (requested {got}; this crate accepts {min}..={max})"
437    )]
438    #[cfg(feature = "crypto-ops")]
439    EncryptParams {
440        /// Which `EncryptionInfo` attribute the rejected request was setting.
441        param: EncryptParam,
442        /// Whose rule the value broke — the format's, the cipher's, or this crate's own.
443        problem: EncryptParamProblem,
444        /// The value the caller asked for. Caller-supplied; never read from a file.
445        got: u32,
446        /// The low end of an accepted value for `param`.
447        ///
448        /// For a range-valued parameter — `spinCount`, `saltSize` — this is the bound's
449        /// real floor and `min..=max` is the whole accepted set. For a **set**-valued one
450        /// it cannot be: `keyBits` accepts `{128, 192, 256}`, and printing that as
451        /// `128..=256` would name 200 as acceptable when the next call refuses it. Those
452        /// refusals therefore carry `min == max`, the single nearest accepted size, so
453        /// that every number in the message is one the caller may actually use.
454        ///
455        /// The cost, stated rather than hidden: for `keyBits` the pair is no longer the
456        /// *whole* accepted set, only a correct member of it. Completeness is the right
457        /// thing to lose — a caller who follows `192..=192` succeeds, and a caller who
458        /// follows `128..=256` may not.
459        min: u32,
460        /// The high end of an accepted value for `param`. Equal to `min` where the
461        /// accepted values are a set rather than a range — see `min`.
462        max: u32,
463    },
464
465    /// The bytes handed to an encrypt entry point already carry a password-to-open.
466    ///
467    /// **This crate used to encrypt them anyway.** The result was a CFB container wrapped
468    /// in a second CFB container, indistinguishable from a single wrap without decrypting
469    /// it, and openable only by decrypting twice with two passwords the holder believed
470    /// was one. It was found by a consumer, which had to reimplement this crate's own CLI
471    /// guard to avoid it — the definition of a check that was in the wrong place.
472    ///
473    /// Distinct from [`Self::NotAPlainPackage`], and the distinction is the remedy: this
474    /// file can be decrypted and re-encrypted, and that one cannot be encrypted at all. A
475    /// renderer that collapses the two tells the holder of a `.doc` to decrypt it first,
476    /// which this crate will do and then refuse to undo.
477    ///
478    /// The partition is [`crate::Classification::is_encrypted`], so a CFB whose container
479    /// could not be read ([`crate::ContainerRead::Unreadable`]) reports
480    /// [`Self::NotAPlainPackage`] rather than this. Both are refusals, so nothing is
481    /// admitted because a family could not be determined.
482    ///
483    /// `family` and `document` are [`crate::classify()`]'s verdict on the same bytes:
484    /// `Copy` enums from the detection half, never text, so no part of the file reaches
485    /// this variant. They are payload rather than message because the wording a caller
486    /// wants depends on them — "decrypt it first" is a remedy for an encrypted package and
487    /// a dead end for an encrypted `.doc`, which has no writer in any build — and because
488    /// making a caller re-run `classify()` to learn a fact this refusal already
489    /// established is what the note above tells consumers they should not have to do.
490    /// Neither is interpolated into the message: neither has a `Display` impl,
491    /// deliberately, because naming them is a renderer's job.
492    #[error(
493        "the input is already encrypted: this crate encrypts a plain OOXML package, and \
494        these bytes are an Office-encrypted CFB container"
495    )]
496    #[cfg(feature = "crypto-ops")]
497    AlreadyEncrypted {
498        /// The encryption family [`crate::classify()`] found.
499        family: crate::Family,
500        /// The document kind it found, or [`crate::Document::Unknown`] where it could not
501        /// tell — eight bytes of CFB magic are `Unknown`, and the remedy differs by kind.
502        document: crate::Document,
503    },
504
505    /// The bytes are a CFB container that is not an encrypted package: a 97-2003 binary
506    /// document, or a container this crate could not read far enough to say.
507    ///
508    /// Distinct from [`Self::AlreadyEncrypted`] because there is no remedy. This crate has
509    /// no writer for the 97-2003 binary formats, so "decrypt it first" is advice that ends
510    /// in a second refusal in every build.
511    ///
512    /// **Deliberately carries no `Document`.** The commonest input here — a CFB whose
513    /// directory is unreachable — is [`crate::Document::Unknown`], and a message built
514    /// from it would name a document kind [`crate::classify()`] refused to name. The
515    /// variant has no field to build one from, so that cannot be written by accident.
516    #[error(
517        "the input is a CFB container, not a plain OOXML package: this crate writes \
518        encryption around a .docx/.xlsx/.pptx ZIP, and there is no writer for the \
519        97-2003 binary formats"
520    )]
521    #[cfg(feature = "crypto-ops")]
522    NotAPlainPackage,
523
524    /// The bytes are neither a ZIP package nor a CFB container.
525    ///
526    /// Its own variant rather than a case of [`Self::NotAPlainPackage`] because a caller
527    /// acts on it differently, and this crate's CLI already proves it: an unrecognised
528    /// container is "you handed me the wrong file" (exit 3) and a CFB is "I recognise this
529    /// and will not write into it" (exit 5). Two facts, two numbers, two variants.
530    ///
531    /// Not [`Self::NotACfbFile`], which is the decrypt side's refusal and means the
532    /// opposite thing: there a CFB is what was wanted, and here it is one of the two
533    /// shapes being refused.
534    #[error(
535        "the input is neither an OOXML package nor a CFB container: there is nothing \
536        here to encrypt"
537    )]
538    #[cfg(feature = "crypto-ops")]
539    UnknownContainer,
540
541    /// The input is larger than this path will take: `len` bytes against a `limit`.
542    ///
543    /// Not a statement that the file is malformed. Two different ceilings report it, and
544    /// `limit` says which, so a caller words the refusal from the field rather than from a
545    /// number it assumed:
546    ///
547    /// - **The whole-buffer functions** ([`crate::encrypt_ooxml`] and the rest that take
548    ///   `&[u8]` or return `Vec<u8>`) stop at 1 GiB, because they hold the whole package
549    ///   in memory. On encrypt `len` is the plaintext package; on decrypt it is the
550    ///   `\EncryptedPackage` stream. The streaming functions (`*_to`) have no such
551    ///   ceiling; that is what they are for.
552    /// - **The streaming encrypt functions** stop at 2 GiB less 16 bytes of plaintext,
553    ///   the most a version 3 compound file can carry: [MS-CFB] §2.6.1 caps every stream
554    ///   at 0x80000000 bytes, and the stream is an 8-byte prefix plus the plaintext padded
555    ///   to a 16-byte block. Version 3 is the container Office writes. `len` is the
556    ///   plaintext package, measured before anything is written.
557    ///
558    /// Until 0.1.0-rc.7 the 1 GiB refusals were [`Self::BadParameters`], whose meaning is
559    /// a value *the file* declares. An input's size is not one.
560    #[error("the input is {len} bytes; this path takes at most {limit}")]
561    #[cfg(feature = "crypto-ops")]
562    PackageTooLarge {
563        /// The size measured.
564        len: u64,
565        /// The most this path accepts.
566        limit: u64,
567    },
568
569    /// Reading or writing failed: the caller's reader or writer, or the in-memory CFB
570    /// container the whole-buffer functions build.
571    ///
572    /// A cancelling reader's error comes back here as itself. The inner
573    /// [`std::io::Error`] describes the operation — a flush, a stream write, a length the
574    /// input did not keep to — never key material or file content.
575    #[error("I/O error: {0}")]
576    Io(#[from] std::io::Error),
577}
578
579/// Which `EncryptionInfo` attribute a rejected encryption request named.
580///
581/// Half the payload of [`Error::EncryptParams`]; the other half is
582/// [`EncryptParamProblem`]. A fieldless `Copy` enum rather than the `&'static str` the
583/// neighbouring [`Error::UnsupportedAlgorithm`] uses, because this one is a caller's
584/// mistake and a caller acts on it in code: a string forces a string comparison, which
585/// is a match nobody can make exhaustive and nobody notices going stale.
586///
587/// `Display` gives the attribute's own spelling, as [MS-OFFCRYPTO] §2.3.4.10 spells it
588/// in `CT_KeyData` and `CT_PasswordKeyEncryptor`, so the `#[error]` string interpolates
589/// it directly and a consumer with no match arm still reads the real attribute name
590/// rather than a Rust identifier.
591///
592/// `#[non_exhaustive]`: `cipherAlgorithm`, `cipherChaining` and `blockSize` are absent
593/// because this crate writes exactly one value for each and so has no caller parameter
594/// to reject — `blockSize` is 16 because AES-CBC fixes it, not because anyone chose it.
595/// If one of them ever becomes a caller's choice, it arrives here as a variant.
596#[derive(Debug, Clone, Copy, PartialEq, Eq)]
597#[cfg(feature = "crypto-ops")]
598#[non_exhaustive]
599pub enum EncryptParam {
600    /// `spinCount`: the iteration count of the password derivation ([MS-OFFCRYPTO]
601    /// §2.3.4.11).
602    ///
603    /// `ST_SpinCount` is `0..=10000000` (§2.3.4.10) — `minInclusive="0"`, and the prose
604    /// states only "It MUST NOT be greater than 10,000,000". **The floor is zero, and
605    /// only one end is live.**
606    ///
607    /// The single refusal is [`EncryptParamProblem::OutsideSpecRange`], for a value above
608    /// 10 000 000. Below that nothing rejects: the field is a `u32`, which already
609    /// enforces `minInclusive="0"`, so the floor needs no check and cannot be tripped,
610    /// and `limits::SPIN_COUNT_MAX` is the spec's own figure rather than a reduced one,
611    /// so there is **no margin between the two and no second refusal to report**.
612    ///
613    /// In particular this crate does **not** refuse a weak spin count.
614    /// `spinCount="0"` is conforming, this writer emits it on request, and an earlier
615    /// version of this doc claimed an
616    /// [`EncryptParamProblem::ExceedsImplementationLimit`] refusal for values "too weak
617    /// to author" that no code path has ever produced. Declining to have an opinion about
618    /// a writer's stretching is the position `EncryptParams::validate` actually takes.
619    SpinCount,
620
621    /// `hashAlgorithm`: the hash driving the key derivation and the verifier.
622    ///
623    /// **A hash algorithm is not defined by a cipher**, so a refusal here is *not*
624    /// [`EncryptParamProblem::UnsupportedByCipher`], whatever an earlier version of this
625    /// doc said. AES fixes key sizes and a block length; it has no opinion about SHA-512,
626    /// and citing it as the authority that refused a hash names an authority with no say.
627    ///
628    /// The four hashes this crate writes — SHA-1, SHA-256, SHA-384, SHA-512 — are a
629    /// **crate choice the format explicitly licenses**. [MS-OFFCRYPTO] §2.3.4.10, in the
630    /// sentence immediately after the `HashAlgorithm` table (the table that also lists
631    /// MD5, MD4, MD2, RIPEMD-128, RIPEMD-160 and WHIRLPOOL), says:
632    ///
633    /// > Values that are not defined MAY be used, and a compliant implementation is not
634    /// > required to support all defined values.
635    ///
636    /// **That is a third shape, distinct from both of the others**, and the distinction
637    /// is what a consumer needs to write refusal copy. A spec violation says the caller
638    /// asked for a file no conforming reader need accept; an implementation margin says
639    /// the format and the cipher both allow it and this crate declines. This is neither:
640    /// the format permits the value **and** permits an implementation not to support it,
641    /// so the honest sentence is "that hash is conforming, and this writer does not emit
642    /// it" — no fault on either side.
643    ///
644    /// No refusal carries this variant today. `EncryptParams::validate`'s exhaustive
645    /// match over [`crate::HashAlgorithm`] rejects nothing; it is a tripwire that turns a
646    /// fifth variant added to that enum into an `E0004` at the one place that must decide
647    /// whether the writer may emit it. Should such a refusal ever be wanted, it arrives
648    /// with an [`EncryptParamProblem`] variant that states the shape above — not by
649    /// borrowing `UnsupportedByCipher`, and not by borrowing
650    /// [`EncryptParamProblem::OutsideSpecRange`], which would assert that the format
651    /// forbids what the clause quoted here expressly allows.
652    HashAlgorithm,
653
654    /// `keyBits`: the size of a key, in bits.
655    ///
656    /// **The format has two of these and they are independent quantities.** §2.3.4.13
657    /// step 1 sizes the package and intermediate key from `Encryptor.KeyData.keyBits`,
658    /// while §2.3.4.11 sizes the password-derived key-encrypting key from
659    /// `PasswordKeyEncryptor.keyBits`. §2.3.4.10 requires `p:encryptedKey` to match
660    /// `keyData` on `hashAlgorithm` and on `cipherAlgorithm` — and on nothing else, so
661    /// no rule makes these two equal. This variant names whichever of them the rejected
662    /// call was setting.
663    ///
664    /// **Two rules refuse a `keyBits`, and they are not the same authority.**
665    /// `ST_KeyBits` sets `minInclusive="8"`, requires a multiple of 8, and states **no
666    /// maximum**, being generic across cipher algorithms. AES then defines exactly three
667    /// sizes inside that. So:
668    ///
669    /// | value | refused by | `problem` |
670    /// | --- | --- | --- |
671    /// | 7, 12 | `ST_KeyBits` — below 8, or not a multiple of 8 | [`EncryptParamProblem::OutsideSpecRange`] |
672    /// | 64, 512 | AES — legal `ST_KeyBits`, no such key size | [`EncryptParamProblem::UnsupportedByCipher`] |
673    ///
674    /// The spec test runs first, because "AES has no 7-bit key" is true and beside the
675    /// point: 7 is not a legal `keyBits` for any cipher, and naming AES would credit a
676    /// refusal to an authority that never had jurisdiction.
677    ///
678    /// This doc said for one commit that every refusal here was
679    /// `UnsupportedByCipher` — written the same day the variant that exists to prevent
680    /// exactly that mislabelling was added, and caught by an adversarial audit rather
681    /// than by a test. The prose form of the defect is the harder one to see, because
682    /// nothing compiles it.
683    ///
684    /// **This variant is the agile format's XML attribute only.** ECMA-376 *standard*
685    /// encryption states its key size in a different field, in a different structure,
686    /// under a different clause; it is [`Self::KeySize`], and the two are not
687    /// interchangeable.
688    KeyBits,
689
690    /// `EncryptionHeader.KeySize`: the key size of an ECMA-376 **standard** (Office
691    /// 2007) file, in bits ([MS-OFFCRYPTO] §2.3.2).
692    ///
693    /// Separate from [`Self::KeyBits`] rather than folded into it, because the two name
694    /// different fields under different rules and a consumer acts on the difference:
695    ///
696    /// | | [`Self::KeyBits`] | this variant |
697    /// | --- | --- | --- |
698    /// | field | `keyBits`, an XML attribute of `<keyData>` / `<p:encryptedKey>` | `KeySize`, a `u32` in the binary `EncryptionHeader` |
699    /// | typed by | `ST_KeyBits` (§2.3.4.10) — `minInclusive="8"`, a multiple of 8, **no maximum** | §2.3.4.5's header table — `0x00000080`, `0x000000C0` or `0x00000100` |
700    /// | written by | [`crate::encrypt_ooxml_with_params`] | [`crate::encrypt_ooxml_standard_with_key_bits`] |
701    ///
702    /// `Display` prints `EncryptionHeader.KeySize`, so a consumer forwarding the sentence
703    /// names the field its user would find in the file rather than an attribute that is
704    /// not in it.
705    ///
706    /// **Its only `problem` is [`EncryptParamProblem::OutsideSpecRange`], and
707    /// [`EncryptParamProblem::UnsupportedByCipher`] is unreachable here** — the opposite
708    /// of [`Self::KeyBits`], where both fire. `ST_KeyBits` is generic across cipher
709    /// algorithms, so there the format and AES are two authorities with different reach.
710    /// §2.3.4.5 names AES for this stream and then enumerates AES's three key sizes
711    /// itself, so here the format's set and the cipher's set are one set and the format
712    /// states it first. Reporting 64 as a cipher limitation would assert that this header
713    /// may carry a 64-bit key — §2.3.4.5 says it may not — which is the typed lie
714    /// [`EncryptParamProblem`]'s split exists to prevent. `AesKeySize::new` in
715    /// `src/standard_encrypt.rs` carries the argument in full, including why §2.3.2's
716    /// RC4 and `0x00000000` rows are not a counter-example.
717    KeySize,
718
719    /// `saltSize`: the length in bytes of a salt.
720    ///
721    /// Per-element in the same way `keyBits` is: §2.3.4.10 binds each `saltSize` only to
722    /// its own element's `saltValue`, whose decoded form "MUST be" that many bytes, and
723    /// imposes no equality between `keyData`'s and `p:encryptedKey`'s.
724    ///
725    /// `ST_SaltSize` is `1..=65536`, and **this crate adopts that range whole**, so the
726    /// single refusal is [`EncryptParamProblem::OutsideSpecRange`]: zero at one end, and
727    /// anything above 65 536 at the other. A 65 536-byte salt is absurd and conforming,
728    /// and `EncryptParams::validate` writes it — an earlier version of this doc called
729    /// that an [`EncryptParamProblem::ExceedsImplementationLimit`] refusal, which no code
730    /// path produced, because `limits::AGILE_SALT_SIZE` is the schema's range and not a
731    /// reduced one.
732    SaltSize,
733
734    /// keyBits AND hashAlgorithm together — neither wrong alone.
735    ///
736    /// The case the single-attribute variants cannot express: both values are acceptable
737    /// on their own and the pair is not, so naming either one alone would send the caller
738    /// to change the parameter that was fine.
739    ///
740    /// The concrete pair is a digest shorter than the key asked for — SHA-1's 20 bytes
741    /// with `keyBits="256"`, which wants 32. [MS-OFFCRYPTO] §2.3.4.11 says such a key
742    /// "MUST be padded by appending bytes with a value of 0x36"; `agile::derive_block_key`
743    /// refuses to do it, because the pad manufactures twelve constant bytes of key that
744    /// no writer ever used. That refusal is this crate's decrypt-side property, and this
745    /// variant is the encrypt side declining to author the file that would trip it.
746    KeyBitsWithHash,
747}
748
749/// Whose rule a rejected encryption parameter broke.
750///
751/// The other half of [`Error::EncryptParams`]'s payload, and the reason that variant is
752/// shaped as two enums rather than one. It is `src/limits.rs`'s **spec / cipher /
753/// margin** provenance taxonomy — see the table in that module's header — turned into
754/// something a consumer can `match` on, plus a fourth case for two values that are each
755/// fine alone.
756///
757/// | variant | label in `limits.rs` | was the request non-conforming? |
758/// | --- | --- | --- |
759/// | [`Self::OutsideSpecRange`] | **spec** | yes |
760/// | [`Self::UnsupportedByCipher`] | **cipher** | no — AES does not define it |
761/// | [`Self::UnusableCombination`] | — | no, not value by value |
762/// | [`Self::ExceedsImplementationLimit`] | **margin** | no — this crate declines |
763///
764/// Every `Display` string names whose rule it was, so that a consumer which forwards the
765/// message instead of matching on it still says something true. That is the whole point
766/// of the fourth variant: a margin reported as a spec violation is a typed lie, and a
767/// typed lie is worse than a vague one, because a consumer renders a typed fact as
768/// authoritative.
769///
770/// The fourth is also the one nothing currently produces, because this crate currently
771/// imposes no margin on a caller's parameter. [`Self::ExceedsImplementationLimit`]'s own
772/// docs say why it is kept anyway.
773#[derive(Debug, Clone, Copy, PartialEq, Eq)]
774#[cfg(feature = "crypto-ops")]
775#[non_exhaustive]
776pub enum EncryptParamProblem {
777    /// Outside the range [MS-OFFCRYPTO] states for the attribute.
778    ///
779    /// The **spec** row of `limits.rs`'s table: the number the format itself states —
780    /// §2.3.4.10's simple types for the agile attributes, §2.3.4.5's header table for
781    /// [`EncryptParam::KeySize`] — so a request that trips it would produce a file no
782    /// conforming reader need accept. The only one of the four that says the *caller*
783    /// asked for something the format forbids.
784    OutsideSpecRange,
785
786    /// Inside the spec, outside AES as implemented here.
787    ///
788    /// The **cipher** row: fixed by the algorithm rather than by the format. `ST_KeyBits`
789    /// states no maximum precisely because it is generic across ciphers; AES defines
790    /// three sizes, and this crate writes AES. A request refused for this reason is not
791    /// non-conforming, and a message implying it was would be wrong.
792    UnsupportedByCipher,
793
794    /// Legal apart, unreadable together.
795    ///
796    /// No row in `limits.rs`'s table, because a range check cannot see it: each value is
797    /// inside its own bound and the combination is still not writable. Paired with
798    /// [`EncryptParam::KeyBitsWithHash`], whose docs give the case.
799    UnusableCombination,
800
801    /// Spec-legal, cipher-fine, and this crate declines anyway.
802    ///
803    /// The **margin** row: this crate's own defence, as the read caps and
804    /// `limits::crypto::PAYLOAD_CEILING` are. A file built to the requested value could
805    /// be perfectly valid and perfectly implementable, and this crate is choosing not to
806    /// write it. **It does not mean the format forbids the value**, and its `Display`
807    /// string says so in as many words — that distinction is why this variant exists
808    /// separately from [`Self::OutsideSpecRange`] instead of being folded into it.
809    ///
810    /// # Nothing produces it, and that is the design
811    ///
812    /// **No code path in this crate constructs this variant**, and the docs that once
813    /// said otherwise — a spin count "too weak to author", a 65 536-byte salt "this crate
814    /// declines to write" — described refusals `EncryptParams::validate` has never
815    /// emitted. They are corrected at [`EncryptParam::SpinCount`] and
816    /// [`EncryptParam::SaltSize`]. The only constructions left are the two exit-code
817    /// tables' synthetic payloads, in `src/error.rs`'s own `exit_code_canary` and in
818    /// `src/bin/msoffice-crypto_tests.rs`, which pin a number rather than report a
819    /// refusal.
820    ///
821    /// The reason is simply that **this crate presently imposes no margin on any
822    /// caller-settable parameter**. `limits::SPIN_COUNT_MAX` is the spec's own
823    /// 10 000 000, `limits::AGILE_SALT_SIZE` is `ST_SaltSize` whole, and both `keyBits`
824    /// refusals belong to the format or to AES. The margins that do exist — the read
825    /// caps, `PAYLOAD_CEILING` — bound what a *file* declares or how large a payload may
826    /// be, and are reported by [`Error::BadParameters`] and its neighbours, never by
827    /// [`Error::EncryptParams`].
828    ///
829    /// It is kept unproduced **deliberately**, as a design commitment rather than dead
830    /// code, and the commitment is this: the first margin imposed on a caller's parameter
831    /// arrives wearing this variant. Without it the cheap thing to do is to reach for
832    /// [`Self::OutsideSpecRange`], which would tell a consumer the format forbids a value
833    /// the format permits — a typed lie, and the precise failure the fourth variant was
834    /// added to prevent. An unproduced variant with a stated reason costs a consumer one
835    /// match arm that never fires; the alternative costs its users a false statement
836    /// about [MS-OFFCRYPTO], rendered as authoritative.
837    ExceedsImplementationLimit,
838}
839
840#[cfg(feature = "crypto-ops")]
841impl core::fmt::Display for EncryptParam {
842    /// The field's own spelling in [MS-OFFCRYPTO] — §2.3.4.10's attribute names for the
843    /// agile parameters, §2.3.2's field name for the standard header's `KeySize` — never
844    /// the Rust identifier.
845    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
846        // Exhaustive, with no `_` arm, so that a variant added above is a compile error
847        // here rather than a parameter that silently prints as something else.
848        f.write_str(match self {
849            Self::SpinCount => "spinCount",
850            Self::HashAlgorithm => "hashAlgorithm",
851            Self::KeyBits => "keyBits",
852            Self::SaltSize => "saltSize",
853            Self::KeyBitsWithHash => "keyBits together with hashAlgorithm",
854            // Qualified by its structure, because `keyBits` is printed above and a bare
855            // "KeySize" beside it would read as a spelling variant of the same field
856            // rather than as a different field in a different format.
857            Self::KeySize => "EncryptionHeader.KeySize",
858        })
859    }
860}
861
862#[cfg(feature = "crypto-ops")]
863impl core::fmt::Display for EncryptParamProblem {
864    /// A predicate whose subject is the [`EncryptParam`] printed before it, naming
865    /// **whose** rule was broken.
866    ///
867    /// A consumer with no match arm forwards this sentence, so each one has to be honest
868    /// standing alone: the spec case names [MS-OFFCRYPTO] as the authority, and the
869    /// margin case says this crate declines without implying the format agrees.
870    ///
871    /// **The spec case names no section number, deliberately.** Which clause states the
872    /// range depends on the parameter printed before it — §2.3.4.10's simple types for
873    /// the agile attributes, §2.3.4.5's header table for
874    /// [`EncryptParam::KeySize`] — so a fixed citation here would be right for one and
875    /// wrong for the other. It said "§2.3.4.10" until the standard writer learned its
876    /// second and third key sizes, at which point the sentence would have cited the
877    /// agile schema at a caller who never touched it. The section numbers live in the
878    /// [`EncryptParam`] variants' docs, where they can be per-parameter.
879    ///
880    /// Each is phrased "was given …" rather than "is …" so that it reads correctly after
881    /// a compound subject too — [`EncryptParam::KeyBitsWithHash`] names two attributes,
882    /// and "keyBits together with hashAlgorithm is legal on its own" is not a sentence.
883    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
884        f.write_str(match self {
885            Self::OutsideSpecRange => {
886                "was given a value outside the range [MS-OFFCRYPTO] states for it, so \
887                 the file would not conform"
888            }
889            Self::UnsupportedByCipher => {
890                "was given a value [MS-OFFCRYPTO] permits but AES, the only cipher this \
891                 crate writes, does not define"
892            }
893            Self::UnusableCombination => {
894                "was given values that are legal apart and unusable together; the file \
895                 they describe could not be read back"
896            }
897            Self::ExceedsImplementationLimit => {
898                "was given a value [MS-OFFCRYPTO] permits and AES can use, which this \
899                 crate declines as a limit of its own — the format does not forbid it"
900            }
901        })
902    }
903}
904
905/// The coverage half of the CLI's exit-code proof.
906///
907/// `src/bin/msoffice-crypto.rs` maps every [`Error`] to an exit code, and its `match`
908/// needs a `_` arm: the enum is `#[non_exhaustive]` and the binary is a separate crate.
909/// A `_` arm produces no diagnostic when a variant is added, so a twentieth variant
910/// would silently become exit 7 with nothing red anywhere.
911///
912/// This table duplicates that one **without** a `_` arm, inside the defining crate,
913/// where `#[non_exhaustive]` does not apply. Adding a variant to [`Error`] and not
914/// deciding its exit code is then `E0004` here, naming the variant. It is deliberately
915/// a duplicate: the alternative — a public `Error::exit_code()` — would make an API
916/// promise at publish for a binary's benefit.
917///
918/// The values are checked against the binary's own table by
919/// `exit_codes_map_every_error_class` in `src/bin/msoffice-crypto_tests.rs`. This test
920/// is the coverage evidence; that one is the value evidence. Both are required.
921#[cfg(test)]
922mod exit_code_canary {
923    use super::Error;
924
925    fn exit_code(e: &Error) -> u8 {
926        match e {
927            #[cfg(feature = "crypto-ops")]
928            Error::NotACfbFile => 3,
929            Error::MissingStream(_) => 6,
930            #[cfg(feature = "crypto-ops")]
931            Error::BadParameters { .. } => 6,
932            #[cfg(feature = "crypto-ops")]
933            Error::InvariantViolated(_) => 7,
934            Error::StreamTooLarge { .. } => 5,
935            Error::Io(_) => 2,
936            #[cfg(feature = "legacy-binary")]
937            Error::NotEncrypted => 5,
938            #[cfg(feature = "legacy-binary")]
939            Error::UnsupportedEncryptedContent(_) => 9,
940            #[cfg(feature = "crypto-ops")]
941            Error::UnsupportedEncryptionVersion(_, _) => 9,
942            #[cfg(feature = "crypto-ops")]
943            Error::XmlParse(_) => 6,
944            #[cfg(feature = "crypto-ops")]
945            Error::WrongPassword => 4,
946            #[cfg(feature = "crypto-ops")]
947            Error::CipherError => 6,
948            #[cfg(feature = "crypto-ops")]
949            Error::UnsupportedAlgorithm { .. } => 9,
950            #[cfg(feature = "crypto-ops")]
951            Error::IntegrityCheckFailed => 8,
952            #[cfg(feature = "crypto-ops")]
953            Error::IntegrityElementMissing => 8,
954            #[cfg(feature = "crypto-ops")]
955            Error::IntegrityUnavailable(_) => 8,
956            #[cfg(feature = "crypto-ops")]
957            Error::RandomSource(_) => 7,
958            #[cfg(feature = "crypto-ops")]
959            Error::EncryptParams { .. } => 1,
960            #[cfg(feature = "crypto-ops")]
961            Error::AlreadyEncrypted { .. } => 5,
962            #[cfg(feature = "crypto-ops")]
963            Error::NotAPlainPackage => 5,
964            #[cfg(feature = "crypto-ops")]
965            Error::UnknownContainer => 3,
966            #[cfg(feature = "crypto-ops")]
967            Error::PackageTooLarge { .. } => 5,
968        }
969    }
970
971    #[test]
972    fn every_error_variant_is_named_in_the_exit_code_table() {
973        #[cfg(feature = "crypto-ops")]
974        assert_eq!(exit_code(&Error::NotACfbFile), 3);
975        #[cfg(feature = "crypto-ops")]
976        assert_eq!(exit_code(&Error::PackageTooLarge { len: 2, limit: 1 }), 5);
977        assert_eq!(exit_code(&Error::Io(std::io::Error::other("x"))), 2);
978        #[cfg(feature = "crypto-ops")]
979        assert_eq!(exit_code(&Error::IntegrityElementMissing), 8);
980        #[cfg(feature = "legacy-binary")]
981        assert_eq!(exit_code(&Error::NotEncrypted), 5);
982        // The two encrypt-guard refusals that share a code, and the one that does not:
983        // 5 is "I recognise this and will not write into it", 3 is "wrong file".
984        #[cfg(feature = "crypto-ops")]
985        assert_eq!(exit_code(&Error::NotAPlainPackage), 5);
986        #[cfg(feature = "crypto-ops")]
987        assert_eq!(exit_code(&Error::UnknownContainer), 3);
988        // The one caller error in the table: EX_USAGE (1), which every other variant
989        // avoids because every other variant is a verdict on a file. By the time this
990        // one is raised there is often no file at all.
991        #[cfg(feature = "crypto-ops")]
992        assert_eq!(
993            exit_code(&Error::EncryptParams {
994                param: super::EncryptParam::SpinCount,
995                problem: super::EncryptParamProblem::ExceedsImplementationLimit,
996                got: 0,
997                min: 100_000,
998                max: 10_000_000,
999            }),
1000            1
1001        );
1002    }
1003}