1use lopdf::{Dictionary, Document, Object, ObjectId};
29
30#[derive(Debug, thiserror::Error, uniffi::Error)]
32pub enum PdfError {
33 #[error("pdf parse: {0}")]
34 Parse(String),
35 #[error("pdf is encrypted; refusing to rewrite it")]
36 Encrypted,
37 #[error("pdf write: {0}")]
38 Write(String),
39}
40
41const METADATA_KEYS: [&[u8]; 2] = [b"Metadata", b"PieceInfo"];
43
44#[uniffi::export]
49pub fn pdf_strip_metadata(data: Vec<u8>) -> Result<Vec<u8>, PdfError> {
50 let mut doc = Document::load_mem(&data).map_err(|e| PdfError::Parse(e.to_string()))?;
51
52 if doc.trailer.get(b"Encrypt").is_ok() {
55 return Err(PdfError::Encrypted);
56 }
57
58 if let Ok(Object::Reference(id)) = doc.trailer.get(b"Info").cloned() {
62 blank_object(&mut doc, id);
63 }
64 doc.trailer.remove(b"Info");
65
66 let catalog_id = doc
70 .catalog()
71 .ok()
72 .and_then(|_| doc.trailer.get(b"Root").ok().cloned())
73 .and_then(|root| match root {
74 Object::Reference(id) => Some(id),
75 _ => None,
76 });
77 if let Some(id) = catalog_id {
78 strip_keys_from(&mut doc, id);
79 }
80
81 let page_ids: Vec<ObjectId> = doc.page_iter().collect();
83 for id in page_ids {
84 strip_keys_from(&mut doc, id);
85 }
86
87 doc.trailer.remove(b"ID");
90
91 doc.prune_objects();
95 doc.renumber_objects();
96
97 let mut out = Vec::new();
98 doc.save_to(&mut out)
99 .map_err(|e| PdfError::Write(e.to_string()))?;
100 Ok(out)
101}
102
103fn blank_object(doc: &mut Document, id: ObjectId) {
106 if let Some(obj) = doc.objects.get_mut(&id) {
107 *obj = Object::Dictionary(Dictionary::new());
108 }
109}
110
111fn strip_keys_from(doc: &mut Document, id: ObjectId) {
114 let mut referenced = Vec::new();
115 if let Some(Object::Dictionary(dict)) = doc.objects.get_mut(&id) {
116 for key in METADATA_KEYS {
117 if let Ok(Object::Reference(rid)) = dict.get(key) {
118 referenced.push(*rid);
119 }
120 dict.remove(key);
121 }
122 }
123 for rid in referenced {
124 blank_object(doc, rid);
125 }
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131 use lopdf::{dictionary, Stream};
132
133 fn document_with_metadata() -> (Vec<u8>, &'static str) {
137 let mut doc = Document::with_version("1.5");
138
139 let content_bytes = b"BT /F1 12 Tf 72 720 Td (Hello from the document body) Tj ET";
140 let content_id = doc.add_object(Stream::new(dictionary! {}, content_bytes.to_vec()));
141
142 let catalog_xmp = doc.add_object(Stream::new(
143 dictionary! { "Type" => "Metadata", "Subtype" => "XML" },
144 b"<x:xmpmeta><dc:creator>Jane Author</dc:creator></x:xmpmeta>".to_vec(),
145 ));
146 let page_xmp = doc.add_object(Stream::new(
147 dictionary! { "Type" => "Metadata", "Subtype" => "XML" },
148 b"<x:xmpmeta><pdf:Producer>Secret Editor 9</pdf:Producer></x:xmpmeta>".to_vec(),
149 ));
150
151 let pages_id = doc.new_object_id();
152 let page_id = doc.add_object(dictionary! {
153 "Type" => "Page",
154 "Parent" => pages_id,
155 "Contents" => content_id,
156 "Metadata" => page_xmp,
157 "PieceInfo" => dictionary! { "SomeEditor" => dictionary! { "Private" => "/Users/jane/secret/path.pdf" } },
158 });
159 doc.objects.insert(
160 pages_id,
161 Object::Dictionary(dictionary! {
162 "Type" => "Pages", "Count" => 1, "Kids" => vec![page_id.into()],
163 }),
164 );
165
166 let catalog_id = doc.add_object(dictionary! {
167 "Type" => "Catalog", "Pages" => pages_id, "Metadata" => catalog_xmp,
168 });
169 let info_id = doc.add_object(dictionary! {
170 "Author" => Object::string_literal("Jane Author"),
171 "Producer" => Object::string_literal("Secret Editor 9"),
172 "Creator" => Object::string_literal("/Users/jane/secret/path.pdf"),
173 });
174
175 doc.trailer.set("Root", catalog_id);
176 doc.trailer.set("Info", info_id);
177 doc.trailer.set(
178 "ID",
179 Object::Array(vec![
180 Object::string_literal("stable-doc-identity"),
181 Object::string_literal("stable-doc-identity"),
182 ]),
183 );
184
185 let mut bytes = Vec::new();
186 doc.save_to(&mut bytes).expect("build fixture");
187 (bytes, "Hello from the document body")
188 }
189
190 fn as_text(bytes: &[u8]) -> String {
191 String::from_utf8_lossy(bytes).to_string()
192 }
193
194 #[test]
195 fn strips_every_identifying_field() {
196 let (input, body) = document_with_metadata();
197 let before = as_text(&input);
200 assert!(before.contains("Jane Author"), "fixture lacks an author");
201 assert!(before.contains("Secret Editor 9"), "fixture lacks a producer");
202 assert!(before.contains("/Users/jane/secret"), "fixture lacks a path");
203 assert!(before.contains("stable-doc-identity"), "fixture lacks a doc id");
204
205 let cleaned = pdf_strip_metadata(input).expect("strip");
206 let after = as_text(&cleaned);
207
208 assert!(!after.contains("Jane Author"), "author survived");
209 assert!(!after.contains("Secret Editor 9"), "producer survived");
210 assert!(!after.contains("/Users/jane/secret"), "local path survived");
211 assert!(!after.contains("stable-doc-identity"), "document id survived");
212 assert!(!after.contains("xmpmeta"), "XMP packet survived");
213
214 assert!(after.contains(body), "page content was damaged");
216 }
217
218 #[test]
219 fn cleaned_document_still_parses_and_keeps_its_pages() {
220 let (input, _) = document_with_metadata();
221 let cleaned = pdf_strip_metadata(input).expect("strip");
222
223 let doc = Document::load_mem(&cleaned).expect("cleaned pdf must still parse");
224 assert_eq!(doc.page_iter().count(), 1, "page count changed");
225 assert!(doc.trailer.get(b"Info").is_err(), "Info is still referenced");
226 assert!(doc.trailer.get(b"ID").is_err(), "ID is still present");
227 }
228
229 #[test]
230 fn stripping_twice_is_stable() {
231 let (input, body) = document_with_metadata();
234 let once = pdf_strip_metadata(input).expect("first");
235 let twice = pdf_strip_metadata(once.clone()).expect("second");
236 assert!(as_text(&twice).contains(body), "content lost on second pass");
237 assert!(Document::load_mem(&twice).is_ok(), "second pass corrupted it");
238 }
239
240 #[test]
241 fn garbage_input_fails_closed() {
242 assert!(pdf_strip_metadata(b"not a pdf at all".to_vec()).is_err());
245 assert!(pdf_strip_metadata(Vec::new()).is_err());
246 }
247
248 #[test]
249 fn encrypted_documents_are_refused_not_mangled() {
250 let (input, _) = document_with_metadata();
251 let mut doc = Document::load_mem(&input).unwrap();
252 let enc = doc.add_object(dictionary! { "Filter" => "Standard", "V" => 1 });
253 doc.trailer.set("Encrypt", enc);
254 let mut bytes = Vec::new();
255 doc.save_to(&mut bytes).unwrap();
256
257 match pdf_strip_metadata(bytes) {
258 Err(PdfError::Encrypted) => {}
259 other => panic!("expected a refusal, got {other:?}"),
260 }
261 }
262}