odf_crypto/bad_parameter.rs
1//! What [`crate::DecryptError::BadParameters`] carries: which manifest setting
2//! a package declares wrongly, the value it declares, and what was allowed.
3//!
4//! **No byte of the file is in it** (the owner, 2026-10-19 UTC; plan
5//! `docs/plans/structured-bad-parameters-2026-10-19.md`). Every payload is a
6//! fieldless enum or an integer, and every `Display` renders only those. The
7//! string this replaced could carry text the file chose: a row's
8//! `manifest:full-path`, up to the 8 MiB manifest cap, reached a terminal through
9//! the CLI's `report()` unbounded. A consumer can now write its own sentence
10//! from `got`, `min` and `max` instead of quoting ours.
11//!
12//! The write side's [`crate::ParamsReason`] is mirrored, not reused. That type
13//! is a verdict on a caller's own tuple and the CLI pins it to exit 1 (usage);
14//! a [`BadParameter`] is a verdict on a file and maps to exit 6 (malformed). One
15//! type with two exit codes would read wrong in a `match`.
16
17use crate::{Argon2Axis, Cipher};
18
19/// Which manifest setting a [`BadParameter`] is about.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum ManifestField {
23 /// `manifest:iteration-count`, the PBKDF2 iteration count.
24 IterationCount,
25 /// `loext:argon2-iterations`, `-memory` or `-lanes`.
26 Argon2(Argon2Axis),
27 /// `manifest:key-size`, the derived key's length in bytes.
28 KeySize,
29 /// `manifest:size`, the member's declared plaintext length.
30 Size,
31 /// `manifest:initialisation-vector`, its decoded length in bytes.
32 IvLen,
33 /// `manifest:salt`, its decoded length in bytes.
34 SaltLen,
35 /// How many encrypted rows the manifest lists.
36 EncryptedEntries,
37}
38
39impl core::fmt::Display for ManifestField {
40 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
41 // Exhaustive, with no `_` arm, as `Argon2Axis` is: a new field fails
42 // to compile here until it is given a name.
43 match self {
44 Self::IterationCount => f.write_str("manifest:iteration-count"),
45 Self::Argon2(Argon2Axis::T) => f.write_str("loext:argon2-iterations"),
46 Self::Argon2(Argon2Axis::MKib) => f.write_str("loext:argon2-memory (KiB)"),
47 Self::Argon2(Argon2Axis::P) => f.write_str("loext:argon2-lanes"),
48 Self::KeySize => f.write_str("manifest:key-size"),
49 Self::Size => f.write_str("manifest:size"),
50 Self::IvLen => f.write_str("manifest:initialisation-vector length"),
51 Self::SaltLen => f.write_str("manifest:salt length"),
52 Self::EncryptedEntries => f.write_str("encrypted row count"),
53 }
54 }
55}
56
57/// The primitive whose own requirement a [`BadParameter::CipherRejects`]
58/// names: not a bound of this crate's, and not adjustable.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60#[non_exhaustive]
61pub enum Primitive {
62 /// The `argon2` crate (and libargon2, which LibreOffice uses): `m >= 8p`,
63 /// `p <= 0xFFFFFF`, a salt of at least 8 bytes.
64 Argon2,
65 /// AES-GCM: a 12-byte IV.
66 AesGcm,
67 /// AES-CBC: a 16-byte IV.
68 AesCbc,
69 /// Blowfish CFB: an 8-byte IV.
70 Blowfish,
71}
72
73impl core::fmt::Display for Primitive {
74 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
75 f.write_str(match self {
76 Self::Argon2 => "argon2",
77 Self::AesGcm => "AES-GCM",
78 Self::AesCbc => "AES-CBC",
79 Self::Blowfish => "Blowfish",
80 })
81 }
82}
83
84/// A member's bytes disagree with its manifest row.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86#[non_exhaustive]
87pub enum MemberFault {
88 /// An AES-GCM member is shorter than its IV and tag together (28 bytes).
89 ShorterThanIvAndTag,
90 /// An AES-GCM member's first 12 bytes are not the manifest's IV.
91 IvMismatch,
92 /// An AES-CBC member is empty or not a whole number of 16-byte blocks.
93 NotBlockMultiple,
94 /// A member holds more bytes than its zip header says.
95 LongerThanHeader,
96}
97
98impl core::fmt::Display for MemberFault {
99 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
100 f.write_str(match self {
101 Self::ShorterThanIvAndTag => "an AES-GCM member is shorter than its IV and tag",
102 Self::IvMismatch => "an AES-GCM member does not begin with its manifest IV",
103 Self::NotBlockMultiple => "an AES-CBC member is not a whole number of blocks",
104 Self::LongerThanHeader => "a member is longer than its zip header says",
105 })
106 }
107}
108
109/// Why a package's own encryption settings were refused, and **whose rule**
110/// they broke. Every field is an enum or an integer; nothing in it came from
111/// the file as text.
112///
113/// `#[non_exhaustive]`: more reasons may be added, so match with a `_` arm.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
115#[non_exhaustive]
116pub enum BadParameter {
117 /// Outside the range this crate acts on: a [`crate::DecryptLimits`]
118 /// ceiling or a `limits.rs` policy bound, or below a floor the format sets
119 /// (`positiveInteger`, `nonNegativeInteger`). A file the format and
120 /// LibreOffice allow can land here, so this is never evidence the file is
121 /// malformed.
122 #[error("{field} is {got}, outside {min}..={max}, the range this crate acts on")]
123 OutOfRange {
124 /// Which setting.
125 field: ManifestField,
126 /// The value the file declares.
127 got: i64,
128 /// Inclusive floor.
129 min: i64,
130 /// Inclusive ceiling.
131 max: i64,
132 },
133 /// A primitive cannot run it, so no limit of this crate's could help.
134 #[error("{field} is {got}, outside {min}..={max}, which {by} itself requires")]
135 CipherRejects {
136 /// Which setting.
137 field: ManifestField,
138 /// Whose requirement it is.
139 by: Primitive,
140 /// The value the file declares.
141 got: i64,
142 /// Inclusive floor.
143 min: i64,
144 /// Inclusive ceiling.
145 max: i64,
146 },
147 /// `manifest:key-size` cannot be used with the row's cipher. AES takes the
148 /// set {16, 24, 32}, which a range would misstate; Blowfish takes 4..=56.
149 #[error("manifest:key-size {got} cannot be used with {cipher:?}")]
150 KeySizeForCipher {
151 /// The key size the file declares.
152 got: i32,
153 /// The row's cipher.
154 cipher: Cipher,
155 },
156 /// A member's bytes disagree with its manifest row.
157 #[error("{0}")]
158 Member(MemberFault),
159 /// A manifest row names no zip member. The row is given by its index among
160 /// the encrypted rows ([`crate::Classification::encrypted_entries`]),
161 /// never by its `manifest:full-path`, which is text the file chose.
162 #[error("encrypted row {row} names no zip member")]
163 NoMember {
164 /// Index into the encrypted rows.
165 row: usize,
166 },
167}
168
169/// `n` as an `i64`, saturating: a count or length that does not fit is
170/// reported as `i64::MAX` rather than panicking.
171pub(crate) fn wide<T: TryInto<i64>>(n: T) -> i64 {
172 n.try_into().unwrap_or(i64::MAX)
173}