Skip to main content

umbera_core/
pdf.rs

1// AUDIT C-7 (documents) — strip identifying metadata from an outgoing PDF.
2//
3// Images are re-encoded and videos are remuxed before they leave the device, so the
4// EXIF GPS fix and the QuickTime location atom never ride along inside the encrypted
5// attachment. Documents were the hole left in that story: a PDF carries the author's
6// name, the producing application and often the full local file path in its Info
7// dictionary and its XMP packet, and none of it was touched. Sending one deanonymized
8// the sender to the recipient as effectively as a geotag would.
9//
10// This lives in the shared Rust core rather than in each platform's media pipeline
11// because neither Android nor iOS ships a PDF *writer* — Android has no such API at
12// all, and PDFKit cannot rewrite a document's metadata in place without re-rendering
13// it. One implementation here also means the two platforms cannot drift into stripping
14// different fields.
15//
16// SCOPE, honestly: this removes DOCUMENT-level metadata — the Info dictionary, the XMP
17// packet, page-level XMP, and the private per-application blobs (PieceInfo) that
18// editors leave behind. It does NOT rewrite content streams, so text that a human
19// typed into the document (a letterhead, a signature block) stays, exactly as the
20// pixels of a photo stay after EXIF is stripped. It also cannot help with an encrypted
21// PDF, which is refused rather than silently passed through.
22//
23// The input here is a file the USER picked to send, not a hostile document, so the
24// parser is not sitting on an attack surface. It is still wrapped in error handling
25// rather than unwraps: a PDF that lopdf cannot parse must fail the send (fail-closed,
26// same as the image and video paths) instead of falling back to the original.
27
28use lopdf::{Dictionary, Document, Object, ObjectId};
29
30/// Errors surfaced across the FFI when a PDF cannot be cleaned.
31#[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
41/// Keys removed from the document catalog and from each page.
42const METADATA_KEYS: [&[u8]; 2] = [b"Metadata", b"PieceInfo"];
43
44/// Strips document metadata from [data] and returns the rewritten PDF.
45///
46/// Fail-closed by contract: every failure is an error, never the original bytes, so a
47/// caller cannot accidentally send an uncleaned document because a rewrite went wrong.
48#[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    // An encrypted document cannot be rewritten without its password, and saving one
53    // half-decrypted would corrupt it. Refuse instead of guessing.
54    if doc.trailer.get(b"Encrypt").is_ok() {
55        return Err(PdfError::Encrypted);
56    }
57
58    // 1. The Info dictionary — Author, Creator, Producer, Title, Subject, Keywords and
59    //    the creation/modification timestamps. Detach it from the trailer AND blank the
60    //    object it pointed at, since the object itself survives in the file otherwise.
61    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    // 2. The catalog's XMP packet (an XML stream that repeats the Info fields and adds
67    //    document/instance ids that link separately-sent copies to one another) and the
68    //    PieceInfo blobs editors use to stash private application state.
69    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    // 3. Pages carry their own optional XMP and PieceInfo.
82    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    // 4. The trailer's /ID pair is a document identity that persists across saves and
88    //    links copies of the same file. Regenerating is not enough — it must simply go.
89    doc.trailer.remove(b"ID");
90
91    // Drop the objects nothing points at any more (the old Info dictionary, orphaned
92    // XMP streams) so they cannot be recovered from the file's free space, then
93    // renumber so no dangling generation survives.
94    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
103/// Replaces an object with an empty dictionary. Removing the entry alone would leave
104/// the metadata sitting in the file, reachable by anyone reading the raw bytes.
105fn 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
111/// Removes the metadata keys from the dictionary at [id], blanking whatever they
112/// referenced so the stream does not merely become unreferenced.
113fn 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    /// Builds a one-page PDF carrying every metadata surface this module strips: an
134    /// Info dictionary, a catalog XMP packet, a page-level XMP packet, PieceInfo, and
135    /// a trailer /ID — plus real page content that must survive untouched.
136    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        // The fixture must actually contain what we claim to remove, or this test
198        // would pass against a document that never had metadata in the first place.
199        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        // ...and the document is still the document.
215        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        // The send path may run over an already-clean file; that must be a no-op
232        // rather than a failure, and must not keep shrinking or corrupting it.
233        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        // Fail-closed is the whole contract: the caller must never be handed back
243        // something it could mistake for a cleaned document.
244        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}