1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
use crate::security::primitives::PrimitiveError;
use thiserror::Error;
/// Crate-wide [`std::result::Result`] specialization.
pub type Result<T> = std::result::Result<T, Error>;
/// Errors produced by the public APIs of `flpdf`.
///
/// I/O failures bubble up via [`Error::Io`]. Structural problems (malformed tokens,
/// unexpected types, depth limits, oversized fields) use [`Error::Parse`] or
/// [`Error::Unsupported`]. [`Error::Missing`] is reserved for required dictionary
/// entries that the spec mandates, e.g. `/Root` on the trailer.
/// [`Error::Encrypted`] covers all encryption-related failures; its subkind is
/// carried by [`EncryptedError`].
#[derive(Debug, Error)]
pub enum Error {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("parse error at byte {offset}: {message}")]
Parse { offset: usize, message: String },
#[error("unsupported PDF feature: {0}")]
Unsupported(String),
#[error("missing required PDF entry: {0}")]
Missing(&'static str),
#[error("encrypted PDF: {0}")]
Encrypted(#[from] EncryptedError),
}
impl Error {
/// Convenience constructor for [`Error::Parse`].
pub fn parse(offset: usize, message: impl Into<String>) -> Self {
Self::Parse {
offset,
message: message.into(),
}
}
}
/// Sub-kind of [`Error::Encrypted`], describing why an encrypted PDF could not
/// be processed.
///
/// Each variant carries enough context for the CLI to emit an actionable
/// diagnostic message. Downstream callers may pattern-match on these variants
/// to decide whether to retry with a different password, refuse processing, etc.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum EncryptedError {
/// The supplied password (or the empty default) was rejected by the security handler.
#[error("incorrect password")]
BadPassword,
/// The `/Encrypt` dictionary specifies a filter or algorithm revision that
/// `flpdf` does not support.
#[error("unsupported encryption handler: filter={filter}, V={v}, R={r}, CFM={cfm:?}")]
UnsupportedHandler {
/// Value of the `/Filter` key (e.g. `"Standard"`).
filter: String,
/// Encryption algorithm version (`/V`).
v: i64,
/// Revision of the standard security handler (`/R`).
r: i64,
/// Crypt filter method (`/CFM`), if present.
cfm: Option<String>,
},
/// The `/Encrypt` dictionary is structurally invalid or missing required
/// entries.
#[error("malformed /Encrypt dictionary: {reason}")]
Malformed {
/// Human-readable description of what is missing or invalid.
reason: String,
},
/// The document is encrypted with RC4, which is a weak cipher. The caller
/// must pass `--allow-weak-crypto` to permit processing.
#[error("encryption uses weak crypto (RC4); pass --allow-weak-crypto to permit")]
WeakCryptoNotAllowed,
}
/// Bridge from the low-level [`PrimitiveError`] to [`Error::Encrypted`].
///
/// This allows `?`-propagation from `security::primitives` functions directly
/// into the public error type without exposing `PrimitiveError` in the public
/// API.
impl From<PrimitiveError> for Error {
fn from(e: PrimitiveError) -> Self {
Error::Encrypted(EncryptedError::Malformed {
reason: format!("primitive: {e}"),
})
}
}
impl EncryptedError {
/// A short machine-readable code suitable for use in diagnostic messages,
/// e.g. `"encrypted.bad-password"`.
pub fn code(&self) -> &'static str {
match self {
Self::BadPassword => "encrypted.bad-password",
Self::UnsupportedHandler { .. } => "encrypted.unsupported-handler",
Self::Malformed { .. } => "encrypted.malformed",
Self::WeakCryptoNotAllowed => "encrypted.weak-crypto-not-allowed",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::security::primitives::PrimitiveError;
#[test]
fn encrypted_error_display_bad_password() {
let e = EncryptedError::BadPassword;
assert_eq!(e.to_string(), "incorrect password");
}
#[test]
fn encrypted_error_display_unsupported_handler() {
let e = EncryptedError::UnsupportedHandler {
filter: "Standard".into(),
v: 4,
r: 6,
cfm: Some("AESV3".into()),
};
assert_eq!(
e.to_string(),
r#"unsupported encryption handler: filter=Standard, V=4, R=6, CFM=Some("AESV3")"#
);
}
#[test]
fn encrypted_error_display_unsupported_handler_no_cfm() {
let e = EncryptedError::UnsupportedHandler {
filter: "Standard".into(),
v: 1,
r: 2,
cfm: None,
};
assert_eq!(
e.to_string(),
"unsupported encryption handler: filter=Standard, V=1, R=2, CFM=None"
);
}
#[test]
fn encrypted_error_display_malformed() {
let e = EncryptedError::Malformed {
reason: "missing /O entry".into(),
};
assert_eq!(
e.to_string(),
"malformed /Encrypt dictionary: missing /O entry"
);
}
#[test]
fn encrypted_error_display_weak_crypto() {
let e = EncryptedError::WeakCryptoNotAllowed;
assert_eq!(
e.to_string(),
"encryption uses weak crypto (RC4); pass --allow-weak-crypto to permit"
);
}
#[test]
fn error_encrypted_wraps_subkind() {
let e: Error = EncryptedError::BadPassword.into();
assert_eq!(e.to_string(), "encrypted PDF: incorrect password");
}
#[test]
fn encrypted_error_codes() {
assert_eq!(EncryptedError::BadPassword.code(), "encrypted.bad-password");
assert_eq!(
EncryptedError::UnsupportedHandler {
filter: String::new(),
v: 0,
r: 0,
cfm: None
}
.code(),
"encrypted.unsupported-handler"
);
assert_eq!(
EncryptedError::Malformed {
reason: String::new()
}
.code(),
"encrypted.malformed"
);
assert_eq!(
EncryptedError::WeakCryptoNotAllowed.code(),
"encrypted.weak-crypto-not-allowed"
);
}
#[test]
fn primitive_error_invalid_length_maps_to_encrypted_malformed() {
let e: Error = PrimitiveError::InvalidLength.into();
match e {
Error::Encrypted(EncryptedError::Malformed { ref reason }) => {
assert!(
reason.contains("primitive"),
"expected 'primitive' in reason, got: {reason}"
);
assert!(
reason.contains("invalid key/IV length"),
"expected original message in reason, got: {reason}"
);
}
other => panic!("expected Error::Encrypted(Malformed), got: {other:?}"),
}
}
#[test]
fn primitive_error_padding_maps_to_encrypted_malformed() {
let e: Error = PrimitiveError::PaddingError.into();
assert!(
e.to_string()
.contains("malformed /Encrypt dictionary: primitive: invalid PKCS#7 padding"),
"unexpected display: {e}"
);
}
}